From 401fbbedd61c6fac7c2a88cca7dcf00ba3afbac8 Mon Sep 17 00:00:00 2001 From: v3risec Date: Tue, 8 Sep 2026 23:55:50 +0800 Subject: [PATCH 1/5] Add Kani verification method for Challenge 7 --- library/Cargo.lock | 90 ++ library/core/src/intrinsics/mod.rs | 594 ++++++++++++ library/core/src/sync/atomic.rs | 1404 ++++++++++++++++++++++++++++ 3 files changed, 2088 insertions(+) diff --git a/library/Cargo.lock b/library/Cargo.lock index 8f60cea459c7d..213c7200e8a4a 100644 --- a/library/Cargo.lock +++ b/library/Cargo.lock @@ -28,6 +28,7 @@ version = "0.0.0" dependencies = [ "compiler_builtins", "core", + "safety", ] [[package]] @@ -67,6 +68,9 @@ dependencies = [ [[package]] name = "core" version = "0.0.0" +dependencies = [ + "safety", +] [[package]] name = "coretests" @@ -213,6 +217,39 @@ dependencies = [ "unwind", ] +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "syn 1.0.109", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + [[package]] name = "proc_macro" version = "0.0.0" @@ -229,6 +266,15 @@ dependencies = [ "cc", ] +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + [[package]] name = "r-efi" version = "5.3.0" @@ -313,6 +359,16 @@ dependencies = [ "std", ] +[[package]] +name = "safety" +version = "0.1.0" +dependencies = [ + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "shlex" version = "1.3.0" @@ -342,6 +398,7 @@ dependencies = [ "rand", "rand_xorshift", "rustc-demangle", + "safety", "std_detect", "unwind", "vex-sdk", @@ -359,6 +416,27 @@ dependencies = [ "rustc-std-workspace-core", ] +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "sysroot" version = "0.0.0" @@ -379,6 +457,12 @@ dependencies = [ "std", ] +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + [[package]] name = "unwind" version = "0.0.0" @@ -398,6 +482,12 @@ dependencies = [ "rustc-std-workspace-core", ] +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + [[package]] name = "vex-sdk" version = "0.27.1" diff --git a/library/core/src/intrinsics/mod.rs b/library/core/src/intrinsics/mod.rs index ddadeeb3c786a..04a0fc9797c8d 100644 --- a/library/core/src/intrinsics/mod.rs +++ b/library/core/src/intrinsics/mod.rs @@ -4150,4 +4150,598 @@ mod verify { fn supported_status(status: AllocationStatus) -> bool { status != AllocationStatus::Dangling && status != AllocationStatus::DeadObject } + + // Challenge 7, Part 3: atomic intrinsic contracts. + // + // Kani cannot currently attach contracts directly to bodyless + // `rustc_intrinsic` declarations (model-checking/kani#3345). These wrappers + // are the Kani-facing specifications for the const-generic intrinsics above. + // The harness instantiations follow the integer and pointer restrictions in + // the intrinsic documentation, while the contracts encode only the local + // memory obligations required by the intrinsic calls. + // + // `can_dereference` and `can_write` cover allocation bounds, initialization, + // and alignment for `T`. Kani function contracts do not currently expose a predicate for cross-thread + // access histories, so the atomic model remains responsible for detecting + // data races and mixed-size overlapping atomic accesses in concurrent proofs. + + #[allow(dead_code)] + #[kani::modifies(dst)] + #[requires(crate::ub_checks::can_write(dst))] + unsafe fn atomic_store_wrapper(dst: *mut T, val: T) { + unsafe { atomic_store::(dst, val) } + } + + #[allow(dead_code)] + #[requires(crate::ub_checks::can_dereference(src))] + unsafe fn atomic_load_wrapper(src: *const T) -> T { + unsafe { atomic_load::(src) } + } + + #[allow(dead_code)] + #[kani::modifies(dst)] + #[requires(crate::ub_checks::can_dereference(dst as *const T))] + #[requires(crate::ub_checks::can_write(dst))] + unsafe fn atomic_xchg_wrapper(dst: *mut T, val: T) -> T { + unsafe { atomic_xchg::(dst, val) } + } + + macro_rules! define_atomic_binary_rmw_wrapper { + ($wrapper:ident, $intrinsic:ident) => { + #[allow(dead_code)] + #[kani::modifies(dst)] + #[requires(crate::ub_checks::can_dereference(dst as *const T))] + #[requires(crate::ub_checks::can_write(dst))] + unsafe fn $wrapper( + dst: *mut T, + val: U, + ) -> T { + unsafe { $intrinsic::(dst, val) } + } + }; + } + + define_atomic_binary_rmw_wrapper!(atomic_xadd_wrapper, atomic_xadd); + define_atomic_binary_rmw_wrapper!(atomic_xsub_wrapper, atomic_xsub); + define_atomic_binary_rmw_wrapper!(atomic_and_wrapper, atomic_and); + define_atomic_binary_rmw_wrapper!(atomic_nand_wrapper, atomic_nand); + define_atomic_binary_rmw_wrapper!(atomic_or_wrapper, atomic_or); + define_atomic_binary_rmw_wrapper!(atomic_xor_wrapper, atomic_xor); + + macro_rules! define_atomic_extremum_wrapper { + ($wrapper:ident, $intrinsic:ident) => { + #[allow(dead_code)] + #[kani::modifies(dst)] + #[requires(crate::ub_checks::can_dereference(dst as *const T))] + #[requires(crate::ub_checks::can_write(dst))] + unsafe fn $wrapper(dst: *mut T, val: T) -> T { + unsafe { $intrinsic::(dst, val) } + } + }; + } + + define_atomic_extremum_wrapper!(atomic_max_wrapper, atomic_max); + define_atomic_extremum_wrapper!(atomic_min_wrapper, atomic_min); + define_atomic_extremum_wrapper!(atomic_umax_wrapper, atomic_umax); + define_atomic_extremum_wrapper!(atomic_umin_wrapper, atomic_umin); + + macro_rules! define_atomic_compare_exchange_wrapper { + ($wrapper:ident, $intrinsic:ident) => { + #[allow(dead_code)] + #[kani::modifies(dst)] + #[requires(crate::ub_checks::can_dereference(dst as *const T))] + #[requires(crate::ub_checks::can_write(dst))] + unsafe fn $wrapper< + T: Copy, + const ORD_SUCC: AtomicOrdering, + const ORD_FAIL: AtomicOrdering, + >( + dst: *mut T, + old: T, + new: T, + ) -> (T, bool) { + unsafe { $intrinsic::(dst, old, new) } + } + }; + } + + define_atomic_compare_exchange_wrapper!(atomic_cxchg_wrapper, atomic_cxchg); + define_atomic_compare_exchange_wrapper!(atomic_cxchgweak_wrapper, atomic_cxchgweak); + + // Every ordering-specific harness below expands to every legal integer + // width and to the pointer form. Storage is a local object, so the raw + // pointer passed to the intrinsic has concrete provenance without a + // separate wrapper type. Pointer *values* remain arbitrary addresses. + macro_rules! atomic_integer_load_store_types { + ($call:ident, $($args:tt)*) => { + #[cfg(target_has_atomic_load_store = "8")] { $call!(i8, $($args)*); $call!(u8, $($args)*); } + #[cfg(target_has_atomic_load_store = "16")] { $call!(i16, $($args)*); $call!(u16, $($args)*); } + #[cfg(target_has_atomic_load_store = "32")] { $call!(i32, $($args)*); $call!(u32, $($args)*); } + #[cfg(target_has_atomic_load_store = "64")] { $call!(i64, $($args)*); $call!(u64, $($args)*); } + #[cfg(target_has_atomic_load_store = "128")] { $call!(i128, $($args)*); $call!(u128, $($args)*); } + #[cfg(target_has_atomic_load_store = "ptr")] { $call!(isize, $($args)*); $call!(usize, $($args)*); } + }; + } + + macro_rules! atomic_integer_types { + ($call:ident, $($args:tt)*) => { + #[cfg(target_has_atomic = "8")] { $call!(i8, $($args)*); $call!(u8, $($args)*); } + #[cfg(target_has_atomic = "16")] { $call!(i16, $($args)*); $call!(u16, $($args)*); } + #[cfg(target_has_atomic = "32")] { $call!(i32, $($args)*); $call!(u32, $($args)*); } + #[cfg(target_has_atomic = "64")] { $call!(i64, $($args)*); $call!(u64, $($args)*); } + #[cfg(target_has_atomic = "128")] { $call!(i128, $($args)*); $call!(u128, $($args)*); } + #[cfg(target_has_atomic = "ptr")] { $call!(isize, $($args)*); $call!(usize, $($args)*); } + }; + } + + macro_rules! atomic_signed_types { + ($call:ident, $($args:tt)*) => { + #[cfg(target_has_atomic = "8")] { $call!(i8, $($args)*); } + #[cfg(target_has_atomic = "16")] { $call!(i16, $($args)*); } + #[cfg(target_has_atomic = "32")] { $call!(i32, $($args)*); } + #[cfg(target_has_atomic = "64")] { $call!(i64, $($args)*); } + #[cfg(target_has_atomic = "128")] { $call!(i128, $($args)*); } + #[cfg(target_has_atomic = "ptr")] { $call!(isize, $($args)*); } + }; + } + + macro_rules! atomic_unsigned_types { + ($call:ident, $($args:tt)*) => { + #[cfg(target_has_atomic = "8")] { $call!(u8, $($args)*); } + #[cfg(target_has_atomic = "16")] { $call!(u16, $($args)*); } + #[cfg(target_has_atomic = "32")] { $call!(u32, $($args)*); } + #[cfg(target_has_atomic = "64")] { $call!(u64, $($args)*); } + #[cfg(target_has_atomic = "128")] { $call!(u128, $($args)*); } + #[cfg(target_has_atomic = "ptr")] { $call!(usize, $($args)*); } + }; + } + + // Store: integer and pointer T, with the three orderings accepted by the + // intrinsic's stabilized atomic counterpart. + macro_rules! atomic_store_call { + ($ty:ty, $ord:path) => {{ + let mut dst: $ty = kani::any(); + let val: $ty = kani::any(); + unsafe { atomic_store_wrapper::<$ty, { $ord }>(&mut dst, val) }; + }}; + } + macro_rules! atomic_store_harness { + ($name:ident, $ord:path) => { + #[kani::proof_for_contract(atomic_store_wrapper)] + fn $name() { + atomic_integer_load_store_types!(atomic_store_call, $ord); + #[cfg(target_has_atomic_load_store = "ptr")] + { + let mut dst: *mut u8 = kani::any::() as *mut u8; + let val: *mut u8 = kani::any::() as *mut u8; + unsafe { atomic_store_wrapper::<*mut u8, { $ord }>(&mut dst, val) }; + } + kani::cover(true, "atomic intrinsic store: reached after call"); + } + }; + } + atomic_store_harness!(harness_intrinsic_atomic_store_relaxed, AtomicOrdering::Relaxed); + atomic_store_harness!(harness_intrinsic_atomic_store_release, AtomicOrdering::Release); + atomic_store_harness!(harness_intrinsic_atomic_store_seqcst, AtomicOrdering::SeqCst); + + // Load: the same complete T matrix as store. + macro_rules! atomic_load_call { + ($ty:ty, $ord:path) => {{ + let src: $ty = kani::any(); + let _ = unsafe { atomic_load_wrapper::<$ty, { $ord }>(&src) }; + }}; + } + macro_rules! atomic_load_harness { + ($name:ident, $ord:path) => { + #[kani::proof_for_contract(atomic_load_wrapper)] + fn $name() { + atomic_integer_load_store_types!(atomic_load_call, $ord); + #[cfg(target_has_atomic_load_store = "ptr")] + { + let src: *mut u8 = kani::any::() as *mut u8; + let _ = unsafe { atomic_load_wrapper::<*mut u8, { $ord }>(&src) }; + } + kani::cover(true, "atomic intrinsic load: reached after call"); + } + }; + } + atomic_load_harness!(harness_intrinsic_atomic_load_relaxed, AtomicOrdering::Relaxed); + atomic_load_harness!(harness_intrinsic_atomic_load_acquire, AtomicOrdering::Acquire); + atomic_load_harness!(harness_intrinsic_atomic_load_seqcst, AtomicOrdering::SeqCst); + + // Unary RMW operations (swap, xchg): integer and pointer T. + macro_rules! atomic_rmw_call { + ($ty:ty, $wrapper:ident, $ord:path) => {{ + let mut dst: $ty = kani::any(); + let val: $ty = kani::any(); + let _ = unsafe { $wrapper::<$ty, { $ord }>(&mut dst, val) }; + }}; + } + macro_rules! atomic_rmw_harness { + ($name:ident, $wrapper:ident, $ord:path) => { + #[kani::proof_for_contract($wrapper)] + fn $name() { + atomic_integer_types!(atomic_rmw_call, $wrapper, $ord); + #[cfg(target_has_atomic = "ptr")] + { + let mut dst: *mut u8 = kani::any::() as *mut u8; + let val: *mut u8 = kani::any::() as *mut u8; + let _ = unsafe { $wrapper::<*mut u8, { $ord }>(&mut dst, val) }; + } + kani::cover(true, "atomic intrinsic exchange: reached after call"); + } + }; + } + macro_rules! atomic_rmw_orders { + ($wrapper:ident, $relaxed:ident, $acquire:ident, $release:ident, $acqrel:ident, $seqcst:ident) => { + atomic_rmw_harness!($relaxed, $wrapper, AtomicOrdering::Relaxed); + atomic_rmw_harness!($acquire, $wrapper, AtomicOrdering::Acquire); + atomic_rmw_harness!($release, $wrapper, AtomicOrdering::Release); + atomic_rmw_harness!($acqrel, $wrapper, AtomicOrdering::AcqRel); + atomic_rmw_harness!($seqcst, $wrapper, AtomicOrdering::SeqCst); + }; + } + atomic_rmw_orders!( + atomic_xchg_wrapper, + harness_intrinsic_atomic_xchg_relaxed, + harness_intrinsic_atomic_xchg_acquire, + harness_intrinsic_atomic_xchg_release, + harness_intrinsic_atomic_xchg_acqrel, + harness_intrinsic_atomic_xchg_seqcst + ); + + // Binary RMW operations: U == T for integer T, and U == usize for pointer T. + macro_rules! atomic_binary_call { + ($ty:ty, $wrapper:ident, $ord:path) => {{ + let mut dst: $ty = kani::any(); + let val: $ty = kani::any(); + let _ = unsafe { $wrapper::<$ty, $ty, { $ord }>(&mut dst, val) }; + }}; + } + macro_rules! atomic_binary_harness { + ($name:ident, $wrapper:ident, $ord:path) => { + #[kani::proof_for_contract($wrapper)] + fn $name() { + atomic_integer_types!(atomic_binary_call, $wrapper, $ord); + #[cfg(target_has_atomic = "ptr")] + { + let mut dst: *mut u8 = kani::any::() as *mut u8; + let val: usize = kani::any(); + let _ = unsafe { $wrapper::<*mut u8, usize, { $ord }>(&mut dst, val) }; + } + kani::cover(true, "atomic intrinsic binary RMW: reached after call"); + } + }; + } + macro_rules! atomic_binary_orders { + ($wrapper:ident, $relaxed:ident, $acquire:ident, $release:ident, $acqrel:ident, $seqcst:ident) => { + atomic_binary_harness!($relaxed, $wrapper, AtomicOrdering::Relaxed); + atomic_binary_harness!($acquire, $wrapper, AtomicOrdering::Acquire); + atomic_binary_harness!($release, $wrapper, AtomicOrdering::Release); + atomic_binary_harness!($acqrel, $wrapper, AtomicOrdering::AcqRel); + atomic_binary_harness!($seqcst, $wrapper, AtomicOrdering::SeqCst); + }; + } + atomic_binary_orders!( + atomic_xadd_wrapper, + harness_intrinsic_atomic_xadd_relaxed, + harness_intrinsic_atomic_xadd_acquire, + harness_intrinsic_atomic_xadd_release, + harness_intrinsic_atomic_xadd_acqrel, + harness_intrinsic_atomic_xadd_seqcst + ); + atomic_binary_orders!( + atomic_xsub_wrapper, + harness_intrinsic_atomic_xsub_relaxed, + harness_intrinsic_atomic_xsub_acquire, + harness_intrinsic_atomic_xsub_release, + harness_intrinsic_atomic_xsub_acqrel, + harness_intrinsic_atomic_xsub_seqcst + ); + atomic_binary_orders!( + atomic_and_wrapper, + harness_intrinsic_atomic_and_relaxed, + harness_intrinsic_atomic_and_acquire, + harness_intrinsic_atomic_and_release, + harness_intrinsic_atomic_and_acqrel, + harness_intrinsic_atomic_and_seqcst + ); + atomic_binary_orders!( + atomic_nand_wrapper, + harness_intrinsic_atomic_nand_relaxed, + harness_intrinsic_atomic_nand_acquire, + harness_intrinsic_atomic_nand_release, + harness_intrinsic_atomic_nand_acqrel, + harness_intrinsic_atomic_nand_seqcst + ); + atomic_binary_orders!( + atomic_or_wrapper, + harness_intrinsic_atomic_or_relaxed, + harness_intrinsic_atomic_or_acquire, + harness_intrinsic_atomic_or_release, + harness_intrinsic_atomic_or_acqrel, + harness_intrinsic_atomic_or_seqcst + ); + atomic_binary_orders!( + atomic_xor_wrapper, + harness_intrinsic_atomic_xor_relaxed, + harness_intrinsic_atomic_xor_acquire, + harness_intrinsic_atomic_xor_release, + harness_intrinsic_atomic_xor_acqrel, + harness_intrinsic_atomic_xor_seqcst + ); + + // Signed and unsigned extrema have the restricted T matrices documented by + // atomic_max/min and atomic_umax/umin respectively. + macro_rules! atomic_extremum_call { + ($ty:ty, $wrapper:ident, $ord:path) => {{ + let mut dst: $ty = kani::any(); + let val: $ty = kani::any(); + let _ = unsafe { $wrapper::<$ty, { $ord }>(&mut dst, val) }; + }}; + } + macro_rules! atomic_extremum_harness { + ($name:ident, $wrapper:ident, $types:ident, $ord:path) => { + #[kani::proof_for_contract($wrapper)] + fn $name() { + $types!(atomic_extremum_call, $wrapper, $ord); + kani::cover(true, "atomic intrinsic extremum: reached after call"); + } + }; + } + macro_rules! atomic_extremum_orders { + ($wrapper:ident, $types:ident, $relaxed:ident, $acquire:ident, $release:ident, $acqrel:ident, $seqcst:ident) => { + atomic_extremum_harness!($relaxed, $wrapper, $types, AtomicOrdering::Relaxed); + atomic_extremum_harness!($acquire, $wrapper, $types, AtomicOrdering::Acquire); + atomic_extremum_harness!($release, $wrapper, $types, AtomicOrdering::Release); + atomic_extremum_harness!($acqrel, $wrapper, $types, AtomicOrdering::AcqRel); + atomic_extremum_harness!($seqcst, $wrapper, $types, AtomicOrdering::SeqCst); + }; + } + atomic_extremum_orders!( + atomic_max_wrapper, + atomic_signed_types, + harness_intrinsic_atomic_max_relaxed, + harness_intrinsic_atomic_max_acquire, + harness_intrinsic_atomic_max_release, + harness_intrinsic_atomic_max_acqrel, + harness_intrinsic_atomic_max_seqcst + ); + atomic_extremum_orders!( + atomic_min_wrapper, + atomic_signed_types, + harness_intrinsic_atomic_min_relaxed, + harness_intrinsic_atomic_min_acquire, + harness_intrinsic_atomic_min_release, + harness_intrinsic_atomic_min_acqrel, + harness_intrinsic_atomic_min_seqcst + ); + atomic_extremum_orders!( + atomic_umax_wrapper, + atomic_unsigned_types, + harness_intrinsic_atomic_umax_relaxed, + harness_intrinsic_atomic_umax_acquire, + harness_intrinsic_atomic_umax_release, + harness_intrinsic_atomic_umax_acqrel, + harness_intrinsic_atomic_umax_seqcst + ); + atomic_extremum_orders!( + atomic_umin_wrapper, + atomic_unsigned_types, + harness_intrinsic_atomic_umin_relaxed, + harness_intrinsic_atomic_umin_acquire, + harness_intrinsic_atomic_umin_release, + harness_intrinsic_atomic_umin_acqrel, + harness_intrinsic_atomic_umin_seqcst + ); + + // Compare exchange uses all integer/pointer T types for every legal + // success/failure ordering pair. Failure orderings are exactly the three + // values listed in the intrinsic documentation. + macro_rules! atomic_cxchg_call { + ($ty:ty, $wrapper:ident, $succ:path, $fail:path) => {{ + let mut dst: $ty = kani::any(); + let old: $ty = kani::any(); + let new: $ty = kani::any(); + let _ = unsafe { $wrapper::<$ty, { $succ }, { $fail }>(&mut dst, old, new) }; + }}; + } + macro_rules! atomic_cxchg_harness { + ($name:ident, $wrapper:ident, $succ:path, $fail:path) => { + #[kani::proof_for_contract($wrapper)] + fn $name() { + atomic_integer_types!(atomic_cxchg_call, $wrapper, $succ, $fail); + #[cfg(target_has_atomic = "ptr")] + { + let mut dst: *mut u8 = kani::any::() as *mut u8; + let old: *mut u8 = kani::any::() as *mut u8; + let new: *mut u8 = kani::any::() as *mut u8; + let _ = + unsafe { $wrapper::<*mut u8, { $succ }, { $fail }>(&mut dst, old, new) }; + } + kani::cover(true, "atomic intrinsic compare-exchange: reached after call"); + } + }; + } + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchg_relaxed_relaxed, + atomic_cxchg_wrapper, + AtomicOrdering::Relaxed, + AtomicOrdering::Relaxed + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchg_relaxed_acquire, + atomic_cxchg_wrapper, + AtomicOrdering::Relaxed, + AtomicOrdering::Acquire + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchg_relaxed_seqcst, + atomic_cxchg_wrapper, + AtomicOrdering::Relaxed, + AtomicOrdering::SeqCst + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchg_acquire_relaxed, + atomic_cxchg_wrapper, + AtomicOrdering::Acquire, + AtomicOrdering::Relaxed + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchg_acquire_acquire, + atomic_cxchg_wrapper, + AtomicOrdering::Acquire, + AtomicOrdering::Acquire + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchg_acquire_seqcst, + atomic_cxchg_wrapper, + AtomicOrdering::Acquire, + AtomicOrdering::SeqCst + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchg_release_relaxed, + atomic_cxchg_wrapper, + AtomicOrdering::Release, + AtomicOrdering::Relaxed + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchg_release_acquire, + atomic_cxchg_wrapper, + AtomicOrdering::Release, + AtomicOrdering::Acquire + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchg_release_seqcst, + atomic_cxchg_wrapper, + AtomicOrdering::Release, + AtomicOrdering::SeqCst + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchg_acqrel_relaxed, + atomic_cxchg_wrapper, + AtomicOrdering::AcqRel, + AtomicOrdering::Relaxed + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchg_acqrel_acquire, + atomic_cxchg_wrapper, + AtomicOrdering::AcqRel, + AtomicOrdering::Acquire + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchg_acqrel_seqcst, + atomic_cxchg_wrapper, + AtomicOrdering::AcqRel, + AtomicOrdering::SeqCst + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchg_seqcst_relaxed, + atomic_cxchg_wrapper, + AtomicOrdering::SeqCst, + AtomicOrdering::Relaxed + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchg_seqcst_acquire, + atomic_cxchg_wrapper, + AtomicOrdering::SeqCst, + AtomicOrdering::Acquire + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchg_seqcst_seqcst, + atomic_cxchg_wrapper, + AtomicOrdering::SeqCst, + AtomicOrdering::SeqCst + ); + + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchgweak_relaxed_relaxed, + atomic_cxchgweak_wrapper, + AtomicOrdering::Relaxed, + AtomicOrdering::Relaxed + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchgweak_relaxed_acquire, + atomic_cxchgweak_wrapper, + AtomicOrdering::Relaxed, + AtomicOrdering::Acquire + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchgweak_relaxed_seqcst, + atomic_cxchgweak_wrapper, + AtomicOrdering::Relaxed, + AtomicOrdering::SeqCst + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchgweak_acquire_relaxed, + atomic_cxchgweak_wrapper, + AtomicOrdering::Acquire, + AtomicOrdering::Relaxed + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchgweak_acquire_acquire, + atomic_cxchgweak_wrapper, + AtomicOrdering::Acquire, + AtomicOrdering::Acquire + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchgweak_acquire_seqcst, + atomic_cxchgweak_wrapper, + AtomicOrdering::Acquire, + AtomicOrdering::SeqCst + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchgweak_release_relaxed, + atomic_cxchgweak_wrapper, + AtomicOrdering::Release, + AtomicOrdering::Relaxed + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchgweak_release_acquire, + atomic_cxchgweak_wrapper, + AtomicOrdering::Release, + AtomicOrdering::Acquire + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchgweak_release_seqcst, + atomic_cxchgweak_wrapper, + AtomicOrdering::Release, + AtomicOrdering::SeqCst + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchgweak_acqrel_relaxed, + atomic_cxchgweak_wrapper, + AtomicOrdering::AcqRel, + AtomicOrdering::Relaxed + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchgweak_acqrel_acquire, + atomic_cxchgweak_wrapper, + AtomicOrdering::AcqRel, + AtomicOrdering::Acquire + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchgweak_acqrel_seqcst, + atomic_cxchgweak_wrapper, + AtomicOrdering::AcqRel, + AtomicOrdering::SeqCst + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchgweak_seqcst_relaxed, + atomic_cxchgweak_wrapper, + AtomicOrdering::SeqCst, + AtomicOrdering::Relaxed + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchgweak_seqcst_acquire, + atomic_cxchgweak_wrapper, + AtomicOrdering::SeqCst, + AtomicOrdering::Acquire + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchgweak_seqcst_seqcst, + atomic_cxchgweak_wrapper, + AtomicOrdering::SeqCst, + AtomicOrdering::SeqCst + ); } diff --git a/library/core/src/sync/atomic.rs b/library/core/src/sync/atomic.rs index 0c5552a0b81cc..4f54cfc3efcf2 100644 --- a/library/core/src/sync/atomic.rs +++ b/library/core/src/sync/atomic.rs @@ -242,10 +242,16 @@ // are just normal values that get loaded/stored, but not dereferenced. #![allow(clippy::not_unsafe_ptr_arg_deref)] +use safety::{ensures, requires}; + use self::Ordering::*; use crate::cell::UnsafeCell; use crate::hint::spin_loop; use crate::intrinsics::AtomicOrdering as AO; +#[cfg(kani)] +use crate::kani; +#[cfg(kani)] +use crate::ub_checks; use crate::{fmt, intrinsics}; trait Sealed {} @@ -571,6 +577,12 @@ impl AtomicBool { #[inline] #[stable(feature = "atomic_from_ptr", since = "1.75.0")] #[rustc_const_stable(feature = "const_atomic_from_ptr", since = "1.84.0")] + #[requires(ptr.cast::().is_aligned())] + #[requires(ub_checks::can_dereference(ptr))] + #[requires(ub_checks::can_write(ptr))] + #[ensures(|result: &&AtomicBool| { + core::ptr::eq(*result, ptr.cast::()) + })] pub const unsafe fn from_ptr<'a>(ptr: *mut bool) -> &'a AtomicBool { // SAFETY: guaranteed by the caller unsafe { &*ptr.cast() } @@ -721,6 +733,7 @@ impl AtomicBool { #[inline] #[stable(feature = "rust1", since = "1.0.0")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[requires(order == Relaxed || order == Acquire || order == SeqCst)] pub fn load(&self, order: Ordering) -> bool { // SAFETY: any data races are prevented by atomic intrinsics and the raw // pointer passed in is valid because we got it from a reference. @@ -750,6 +763,8 @@ impl AtomicBool { #[stable(feature = "rust1", since = "1.0.0")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[requires(order == Relaxed || order == Release || order == SeqCst)] + #[cfg_attr(kani, kani::modifies(self))] pub fn store(&self, val: bool, order: Ordering) { // SAFETY: any data races are prevented by atomic intrinsics and the raw // pointer passed in is valid because we got it from a reference. @@ -783,6 +798,7 @@ impl AtomicBool { #[cfg(target_has_atomic = "8")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] pub fn swap(&self, val: bool, order: Ordering) -> bool { if EMULATE_ATOMIC_BOOL { if val { self.fetch_or(true, order) } else { self.fetch_and(false, order) } @@ -851,6 +867,7 @@ impl AtomicBool { #[cfg(target_has_atomic = "8")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] pub fn compare_and_swap(&self, current: bool, new: bool, order: Ordering) -> bool { match self.compare_exchange(current, new, order, strongest_failure_ordering(order)) { Ok(x) => x, @@ -913,6 +930,8 @@ impl AtomicBool { #[cfg(target_has_atomic = "8")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[requires(failure == Relaxed || failure == Acquire || failure == SeqCst)] + #[cfg_attr(kani, kani::modifies(self))] pub fn compare_exchange( &self, current: bool, @@ -1009,6 +1028,8 @@ impl AtomicBool { #[cfg(target_has_atomic = "8")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[requires(failure == Relaxed || failure == Acquire || failure == SeqCst)] + #[cfg_attr(kani, kani::modifies(self))] pub fn compare_exchange_weak( &self, current: bool, @@ -1066,6 +1087,7 @@ impl AtomicBool { #[cfg(target_has_atomic = "8")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] pub fn fetch_and(&self, val: bool, order: Ordering) -> bool { // SAFETY: data races are prevented by atomic intrinsics. unsafe { atomic_and(self.v.get(), val as u8, order) != 0 } @@ -1109,6 +1131,7 @@ impl AtomicBool { #[cfg(target_has_atomic = "8")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] pub fn fetch_nand(&self, val: bool, order: Ordering) -> bool { // We can't use atomic_nand here because it can result in a bool with // an invalid value. This happens because the atomic operation is done @@ -1162,6 +1185,7 @@ impl AtomicBool { #[cfg(target_has_atomic = "8")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] pub fn fetch_or(&self, val: bool, order: Ordering) -> bool { // SAFETY: data races are prevented by atomic intrinsics. unsafe { atomic_or(self.v.get(), val as u8, order) != 0 } @@ -1204,6 +1228,7 @@ impl AtomicBool { #[cfg(target_has_atomic = "8")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] pub fn fetch_xor(&self, val: bool, order: Ordering) -> bool { // SAFETY: data races are prevented by atomic intrinsics. unsafe { atomic_xor(self.v.get(), val as u8, order) != 0 } @@ -1242,6 +1267,7 @@ impl AtomicBool { #[cfg(target_has_atomic = "8")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] pub fn fetch_not(&self, order: Ordering) -> bool { self.fetch_xor(true, order) } @@ -1335,6 +1361,8 @@ impl AtomicBool { #[cfg(target_has_atomic = "8")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[requires(fetch_order == Relaxed || fetch_order == Acquire || fetch_order == SeqCst)] + #[cfg_attr(kani, kani::modifies(self))] pub fn fetch_update( &self, set_order: Ordering, @@ -1407,6 +1435,8 @@ impl AtomicBool { #[cfg(target_has_atomic = "8")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[requires(fetch_order == Relaxed || fetch_order == Acquire || fetch_order == SeqCst)] + #[cfg_attr(kani, kani::modifies(self))] pub fn try_update( &self, set_order: Ordering, @@ -1466,6 +1496,8 @@ impl AtomicBool { #[cfg(target_has_atomic = "8")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[requires(fetch_order == Relaxed || fetch_order == Acquire || fetch_order == SeqCst)] + #[cfg_attr(kani, kani::modifies(self))] pub fn update( &self, set_order: Ordering, @@ -1543,6 +1575,12 @@ impl AtomicPtr { #[inline] #[stable(feature = "atomic_from_ptr", since = "1.75.0")] #[rustc_const_stable(feature = "const_atomic_from_ptr", since = "1.84.0")] + #[requires(ptr.cast::>().is_aligned())] + #[requires(ub_checks::can_dereference(ptr))] + #[requires(ub_checks::can_write(ptr))] + #[ensures(|result: &&AtomicPtr| { + core::ptr::eq(*result, ptr.cast::>()) + })] pub const unsafe fn from_ptr<'a>(ptr: *mut *mut T) -> &'a AtomicPtr { // SAFETY: guaranteed by the caller unsafe { &*ptr.cast() } @@ -1720,6 +1758,7 @@ impl AtomicPtr { #[inline] #[stable(feature = "rust1", since = "1.0.0")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[requires(order == Relaxed || order == Acquire || order == SeqCst)] pub fn load(&self, order: Ordering) -> *mut T { // SAFETY: data races are prevented by atomic intrinsics. unsafe { atomic_load(self.p.get(), order) } @@ -1750,6 +1789,8 @@ impl AtomicPtr { #[stable(feature = "rust1", since = "1.0.0")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[requires(order == Relaxed || order == Release || order == SeqCst)] + #[cfg_attr(kani, kani::modifies(self))] pub fn store(&self, ptr: *mut T, order: Ordering) { // SAFETY: data races are prevented by atomic intrinsics. unsafe { @@ -1784,6 +1825,7 @@ impl AtomicPtr { #[cfg(target_has_atomic = "ptr")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] pub fn swap(&self, ptr: *mut T, order: Ordering) -> *mut T { // SAFETY: data races are prevented by atomic intrinsics. unsafe { atomic_swap(self.p.get(), ptr, order) } @@ -1847,6 +1889,7 @@ impl AtomicPtr { #[cfg(target_has_atomic = "ptr")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] pub fn compare_and_swap(&self, current: *mut T, new: *mut T, order: Ordering) -> *mut T { match self.compare_exchange(current, new, order, strongest_failure_ordering(order)) { Ok(x) => x, @@ -1902,6 +1945,8 @@ impl AtomicPtr { #[cfg(target_has_atomic = "ptr")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[requires(failure == Relaxed || failure == Acquire || failure == SeqCst)] + #[cfg_attr(kani, kani::modifies(self))] pub fn compare_exchange( &self, current: *mut T, @@ -1966,6 +2011,8 @@ impl AtomicPtr { #[cfg(target_has_atomic = "ptr")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[requires(failure == Relaxed || failure == Acquire || failure == SeqCst)] + #[cfg_attr(kani, kani::modifies(self))] pub fn compare_exchange_weak( &self, current: *mut T, @@ -2040,6 +2087,8 @@ impl AtomicPtr { #[cfg(target_has_atomic = "ptr")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[requires(fetch_order == Relaxed || fetch_order == Acquire || fetch_order == SeqCst)] + #[cfg_attr(kani, kani::modifies(self))] pub fn fetch_update( &self, set_order: Ordering, @@ -2121,6 +2170,8 @@ impl AtomicPtr { #[cfg(target_has_atomic = "ptr")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[requires(fetch_order == Relaxed || fetch_order == Acquire || fetch_order == SeqCst)] + #[cfg_attr(kani, kani::modifies(self))] pub fn try_update( &self, set_order: Ordering, @@ -2185,6 +2236,8 @@ impl AtomicPtr { #[cfg(target_has_atomic = "8")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[requires(fetch_order == Relaxed || fetch_order == Acquire || fetch_order == SeqCst)] + #[cfg_attr(kani, kani::modifies(self))] pub fn update( &self, set_order: Ordering, @@ -2404,6 +2457,7 @@ impl AtomicPtr { #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] pub fn fetch_or(&self, val: usize, order: Ordering) -> *mut T { // SAFETY: data races are prevented by atomic intrinsics. unsafe { atomic_or(self.p.get(), val, order).cast() } @@ -2454,6 +2508,7 @@ impl AtomicPtr { #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] pub fn fetch_and(&self, val: usize, order: Ordering) -> *mut T { // SAFETY: data races are prevented by atomic intrinsics. unsafe { atomic_and(self.p.get(), val, order).cast() } @@ -2502,6 +2557,7 @@ impl AtomicPtr { #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] pub fn fetch_xor(&self, val: usize, order: Ordering) -> *mut T { // SAFETY: data races are prevented by atomic intrinsics. unsafe { atomic_xor(self.p.get(), val, order).cast() } @@ -2738,6 +2794,19 @@ macro_rules! atomic_int { #[inline] #[stable(feature = "atomic_from_ptr", since = "1.75.0")] #[rustc_const_stable(feature = "const_atomic_from_ptr", since = "1.84.0")] + #[requires(ptr.cast::<$atomic_type>().is_aligned())] + #[requires(!ptr.is_null())] + #[requires(ub_checks::can_dereference(ptr))] + #[requires(ub_checks::can_write(ptr))] + #[ensures(|result: &&$atomic_type| { + core::ptr::eq(*result, ptr.cast::<$atomic_type>()) + })] + #[ensures(|result: &&$atomic_type| { + ub_checks::can_dereference(*result as *const $atomic_type) + })] + #[ensures(|result: &&$atomic_type| { + ub_checks::can_write((*result).as_ptr()) + })] pub const unsafe fn from_ptr<'a>(ptr: *mut $int_type) -> &'a $atomic_type { // SAFETY: guaranteed by the caller unsafe { &*ptr.cast() } @@ -2915,6 +2984,7 @@ macro_rules! atomic_int { #[inline] #[$stable] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[requires(order == Relaxed || order == Acquire || order == SeqCst)] pub fn load(&self, order: Ordering) -> $int_type { // SAFETY: data races are prevented by atomic intrinsics. unsafe { atomic_load(self.v.get(), order) } @@ -2943,6 +3013,8 @@ macro_rules! atomic_int { #[$stable] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[requires(order == Relaxed || order == Release || order == SeqCst)] + #[cfg_attr(kani, kani::modifies(self))] pub fn store(&self, val: $int_type, order: Ordering) { // SAFETY: data races are prevented by atomic intrinsics. unsafe { atomic_store(self.v.get(), val, order); } @@ -2972,6 +3044,7 @@ macro_rules! atomic_int { #[$cfg_cas] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] pub fn swap(&self, val: $int_type, order: Ordering) -> $int_type { // SAFETY: data races are prevented by atomic intrinsics. unsafe { atomic_swap(self.v.get(), val, order) } @@ -3037,6 +3110,7 @@ macro_rules! atomic_int { #[$cfg_cas] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] pub fn compare_and_swap(&self, current: $int_type, new: $int_type, @@ -3106,6 +3180,8 @@ macro_rules! atomic_int { #[$cfg_cas] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[requires(failure == Relaxed || failure == Acquire || failure == SeqCst)] + #[cfg_attr(kani, kani::modifies(self))] pub fn compare_exchange(&self, current: $int_type, new: $int_type, @@ -3170,6 +3246,8 @@ macro_rules! atomic_int { #[$cfg_cas] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[requires(failure == Relaxed || failure == Acquire || failure == SeqCst)] + #[cfg_attr(kani, kani::modifies(self))] pub fn compare_exchange_weak(&self, current: $int_type, new: $int_type, @@ -3207,6 +3285,7 @@ macro_rules! atomic_int { #[$cfg_cas] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] pub fn fetch_add(&self, val: $int_type, order: Ordering) -> $int_type { // SAFETY: data races are prevented by atomic intrinsics. unsafe { atomic_add(self.v.get(), val, order) } @@ -3238,6 +3317,7 @@ macro_rules! atomic_int { #[$cfg_cas] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] pub fn fetch_sub(&self, val: $int_type, order: Ordering) -> $int_type { // SAFETY: data races are prevented by atomic intrinsics. unsafe { atomic_sub(self.v.get(), val, order) } @@ -3272,6 +3352,7 @@ macro_rules! atomic_int { #[$cfg_cas] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] pub fn fetch_and(&self, val: $int_type, order: Ordering) -> $int_type { // SAFETY: data races are prevented by atomic intrinsics. unsafe { atomic_and(self.v.get(), val, order) } @@ -3306,6 +3387,7 @@ macro_rules! atomic_int { #[$cfg_cas] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] pub fn fetch_nand(&self, val: $int_type, order: Ordering) -> $int_type { // SAFETY: data races are prevented by atomic intrinsics. unsafe { atomic_nand(self.v.get(), val, order) } @@ -3340,6 +3422,7 @@ macro_rules! atomic_int { #[$cfg_cas] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] pub fn fetch_or(&self, val: $int_type, order: Ordering) -> $int_type { // SAFETY: data races are prevented by atomic intrinsics. unsafe { atomic_or(self.v.get(), val, order) } @@ -3374,6 +3457,7 @@ macro_rules! atomic_int { #[$cfg_cas] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] pub fn fetch_xor(&self, val: $int_type, order: Ordering) -> $int_type { // SAFETY: data races are prevented by atomic intrinsics. unsafe { atomic_xor(self.v.get(), val, order) } @@ -3429,6 +3513,8 @@ macro_rules! atomic_int { #[$cfg_cas] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[requires(fetch_order == Relaxed || fetch_order == Acquire || fetch_order == SeqCst)] + #[cfg_attr(kani, kani::modifies(self))] pub fn fetch_update(&self, set_order: Ordering, fetch_order: Ordering, @@ -3497,6 +3583,8 @@ macro_rules! atomic_int { #[$cfg_cas] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[requires(fetch_order == Relaxed || fetch_order == Acquire || fetch_order == SeqCst)] + #[cfg_attr(kani, kani::modifies(self))] pub fn try_update( &self, set_order: Ordering, @@ -3559,6 +3647,8 @@ macro_rules! atomic_int { #[$cfg_cas] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[requires(fetch_order == Relaxed || fetch_order == Acquire || fetch_order == SeqCst)] + #[cfg_attr(kani, kani::modifies(self))] pub fn update( &self, set_order: Ordering, @@ -3614,6 +3704,7 @@ macro_rules! atomic_int { #[$cfg_cas] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] pub fn fetch_max(&self, val: $int_type, order: Ordering) -> $int_type { // SAFETY: data races are prevented by atomic intrinsics. unsafe { $max_fn(self.v.get(), val, order) } @@ -3661,6 +3752,7 @@ macro_rules! atomic_int { #[$cfg_cas] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] pub fn fetch_min(&self, val: $int_type, order: Ordering) -> $int_type { // SAFETY: data races are prevented by atomic intrinsics. unsafe { $min_fn(self.v.get(), val, order) } @@ -3985,6 +4077,11 @@ fn strongest_failure_ordering(order: Ordering) -> Ordering { #[inline] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +#[cfg_attr(kani, kani::modifies(dst))] +#[requires(ub_checks::can_write(dst))] +#[requires(order == Relaxed || order == Release || order == SeqCst)] +#[ensures(|_| ub_checks::can_dereference(dst as *const T))] +#[ensures(|_| ub_checks::can_write(dst))] unsafe fn atomic_store(dst: *mut T, val: T, order: Ordering) { // SAFETY: the caller must uphold the safety contract for `atomic_store`. unsafe { @@ -4000,6 +4097,9 @@ unsafe fn atomic_store(dst: *mut T, val: T, order: Ordering) { #[inline] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +#[requires(ub_checks::can_dereference(dst))] +#[requires(order == Relaxed || order == Acquire || order == SeqCst)] +#[ensures(|_| ub_checks::can_dereference(dst))] unsafe fn atomic_load(dst: *const T, order: Ordering) -> T { // SAFETY: the caller must uphold the safety contract for `atomic_load`. unsafe { @@ -4016,6 +4116,12 @@ unsafe fn atomic_load(dst: *const T, order: Ordering) -> T { #[inline] #[cfg(target_has_atomic)] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +#[cfg_attr(kani, kani::modifies(dst))] +#[requires(ub_checks::can_dereference(dst as *const T))] +#[requires(ub_checks::can_write(dst))] +#[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) +})] unsafe fn atomic_swap(dst: *mut T, val: T, order: Ordering) -> T { // SAFETY: the caller must uphold the safety contract for `atomic_swap`. unsafe { @@ -4033,6 +4139,12 @@ unsafe fn atomic_swap(dst: *mut T, val: T, order: Ordering) -> T { #[inline] #[cfg(target_has_atomic)] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +#[cfg_attr(kani, kani::modifies(dst))] +#[requires(ub_checks::can_dereference(dst as *const T))] +#[requires(ub_checks::can_write(dst))] +#[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) +})] unsafe fn atomic_add(dst: *mut T, val: U, order: Ordering) -> T { // SAFETY: the caller must uphold the safety contract for `atomic_add`. unsafe { @@ -4050,6 +4162,12 @@ unsafe fn atomic_add(dst: *mut T, val: U, order: Ordering) -> #[inline] #[cfg(target_has_atomic)] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +#[cfg_attr(kani, kani::modifies(dst))] +#[requires(ub_checks::can_dereference(dst as *const T))] +#[requires(ub_checks::can_write(dst))] +#[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) +})] unsafe fn atomic_sub(dst: *mut T, val: U, order: Ordering) -> T { // SAFETY: the caller must uphold the safety contract for `atomic_sub`. unsafe { @@ -4069,6 +4187,13 @@ unsafe fn atomic_sub(dst: *mut T, val: U, order: Ordering) -> #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[unstable(feature = "core_intrinsics", issue = "none")] #[doc(hidden)] +#[cfg_attr(kani, kani::modifies(dst))] +#[requires(ub_checks::can_dereference(dst as *const T))] +#[requires(ub_checks::can_write(dst))] +#[requires(failure != Release && failure != AcqRel)] +#[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) +})] pub unsafe fn atomic_compare_exchange( dst: *mut T, old: T, @@ -4134,6 +4259,13 @@ pub unsafe fn atomic_compare_exchange( #[inline] #[cfg(target_has_atomic)] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +#[cfg_attr(kani, kani::modifies(dst))] +#[requires(ub_checks::can_dereference(dst as *const T))] +#[requires(ub_checks::can_write(dst))] +#[requires(failure != Release && failure != AcqRel)] +#[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) +})] unsafe fn atomic_compare_exchange_weak( dst: *mut T, old: T, @@ -4199,6 +4331,12 @@ unsafe fn atomic_compare_exchange_weak( #[inline] #[cfg(target_has_atomic)] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +#[cfg_attr(kani, kani::modifies(dst))] +#[requires(ub_checks::can_dereference(dst as *const T))] +#[requires(ub_checks::can_write(dst))] +#[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) +})] unsafe fn atomic_and(dst: *mut T, val: U, order: Ordering) -> T { // SAFETY: the caller must uphold the safety contract for `atomic_and` unsafe { @@ -4215,6 +4353,12 @@ unsafe fn atomic_and(dst: *mut T, val: U, order: Ordering) -> #[inline] #[cfg(target_has_atomic)] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +#[cfg_attr(kani, kani::modifies(dst))] +#[requires(ub_checks::can_dereference(dst as *const T))] +#[requires(ub_checks::can_write(dst))] +#[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) +})] unsafe fn atomic_nand(dst: *mut T, val: U, order: Ordering) -> T { // SAFETY: the caller must uphold the safety contract for `atomic_nand` unsafe { @@ -4231,6 +4375,12 @@ unsafe fn atomic_nand(dst: *mut T, val: U, order: Ordering) -> #[inline] #[cfg(target_has_atomic)] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +#[cfg_attr(kani, kani::modifies(dst))] +#[requires(ub_checks::can_dereference(dst as *const T))] +#[requires(ub_checks::can_write(dst))] +#[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) +})] unsafe fn atomic_or(dst: *mut T, val: U, order: Ordering) -> T { // SAFETY: the caller must uphold the safety contract for `atomic_or` unsafe { @@ -4247,6 +4397,12 @@ unsafe fn atomic_or(dst: *mut T, val: U, order: Ordering) -> T #[inline] #[cfg(target_has_atomic)] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +#[cfg_attr(kani, kani::modifies(dst))] +#[requires(ub_checks::can_dereference(dst as *const T))] +#[requires(ub_checks::can_write(dst))] +#[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) +})] unsafe fn atomic_xor(dst: *mut T, val: U, order: Ordering) -> T { // SAFETY: the caller must uphold the safety contract for `atomic_xor` unsafe { @@ -4264,6 +4420,12 @@ unsafe fn atomic_xor(dst: *mut T, val: U, order: Ordering) -> #[inline] #[cfg(target_has_atomic)] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +#[cfg_attr(kani, kani::modifies(dst))] +#[requires(ub_checks::can_dereference(dst as *const T))] +#[requires(ub_checks::can_write(dst))] +#[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) +})] unsafe fn atomic_max(dst: *mut T, val: T, order: Ordering) -> T { // SAFETY: the caller must uphold the safety contract for `atomic_max` unsafe { @@ -4298,6 +4460,12 @@ unsafe fn atomic_min(dst: *mut T, val: T, order: Ordering) -> T { #[inline] #[cfg(target_has_atomic)] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +#[cfg_attr(kani, kani::modifies(dst))] +#[requires(ub_checks::can_dereference(dst as *const T))] +#[requires(ub_checks::can_write(dst))] +#[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) +})] unsafe fn atomic_umax(dst: *mut T, val: T, order: Ordering) -> T { // SAFETY: the caller must uphold the safety contract for `atomic_umax` unsafe { @@ -4315,6 +4483,12 @@ unsafe fn atomic_umax(dst: *mut T, val: T, order: Ordering) -> T { #[inline] #[cfg(target_has_atomic)] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +#[cfg_attr(kani, kani::modifies(dst))] +#[requires(ub_checks::can_dereference(dst as *const T))] +#[requires(ub_checks::can_write(dst))] +#[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) +})] unsafe fn atomic_umin(dst: *mut T, val: T, order: Ordering) -> T { // SAFETY: the caller must uphold the safety contract for `atomic_umin` unsafe { @@ -4609,3 +4783,1233 @@ impl fmt::Pointer for AtomicPtr { pub fn spin_loop_hint() { spin_loop() } + +#[cfg(kani)] +#[unstable(feature = "kani", issue = "none")] +mod verify { + use super::*; + + // Generate candidates across the allocation. Contract proofs assume the callee's + // preconditions, retaining only initialized, aligned, readable, and writable offsets. + fn ptr_at_offset(buf: &mut [u8; 100]) -> *mut T { + let offset = kani::any_where(|offset: &usize| *offset < 100); + buf.as_mut_ptr().wrapping_add(offset).cast::() + } + + fn any_ordering() -> Ordering { + match kani::any::() { + 0 => Relaxed, + 1 => Release, + 2 => Acquire, + 3 => AcqRel, + _ => SeqCst, + } + } + + // Part 1: from_ptr. + #[cfg(target_has_atomic_load_store = "8")] + #[kani::proof_for_contract(AtomicBool::from_ptr)] + pub fn harness_atomic_bool_from_ptr() { + let mut buf: [bool; 100] = kani::any(); + let offset = kani::any_where(|offset: &usize| *offset < 100); + let ptr = buf.as_mut_ptr().wrapping_add(offset); + + let _ = unsafe { AtomicBool::from_ptr(ptr) }; + kani::cover(true, "AtomicBool::from_ptr: reached after call"); + } + + // Harnesses for integer Atomic*::from_ptr functions. + macro_rules! from_ptr_harness { + ($name:ident, $atomic:ty, $value:ty) => { + #[kani::proof_for_contract(<$atomic>::from_ptr)] + pub fn $name() { + let mut buf: [u8; 100] = kani::any(); + let ptr = ptr_at_offset::<$value>(&mut buf); + + let _ = unsafe { <$atomic>::from_ptr(ptr) }; + kani::cover(true, "integer from_ptr: reached after call"); + } + }; + } + + #[cfg(target_has_atomic_load_store = "8")] + from_ptr_harness!(harness_atomic_i8_from_ptr, AtomicI8, i8); + #[cfg(target_has_atomic_load_store = "8")] + from_ptr_harness!(harness_atomic_u8_from_ptr, AtomicU8, u8); + #[cfg(target_has_atomic_load_store = "16")] + from_ptr_harness!(harness_atomic_i16_from_ptr, AtomicI16, i16); + #[cfg(target_has_atomic_load_store = "16")] + from_ptr_harness!(harness_atomic_u16_from_ptr, AtomicU16, u16); + #[cfg(target_has_atomic_load_store = "32")] + from_ptr_harness!(harness_atomic_i32_from_ptr, AtomicI32, i32); + #[cfg(target_has_atomic_load_store = "32")] + from_ptr_harness!(harness_atomic_u32_from_ptr, AtomicU32, u32); + #[cfg(target_has_atomic_load_store = "64")] + from_ptr_harness!(harness_atomic_i64_from_ptr, AtomicI64, i64); + #[cfg(target_has_atomic_load_store = "64")] + from_ptr_harness!(harness_atomic_u64_from_ptr, AtomicU64, u64); + #[cfg(target_has_atomic_load_store = "128")] + from_ptr_harness!(harness_atomic_i128_from_ptr, AtomicI128, i128); + #[cfg(target_has_atomic_load_store = "128")] + from_ptr_harness!(harness_atomic_u128_from_ptr, AtomicU128, u128); + + // Harnesses for AtomicPtr::from_ptr. + macro_rules! atomic_ptr_from_ptr_harness { + ($name:ident, $pointee:ty) => { + #[cfg(target_has_atomic_load_store = "ptr")] + #[kani::proof_for_contract(AtomicPtr::<$pointee>::from_ptr)] + pub fn $name() { + // The stored pointer is arbitrary; the outer pointer targets valid local storage. + let mut value = kani::any::() as *mut $pointee; + let ptr = &mut value as *mut *mut $pointee; + + let _ = unsafe { AtomicPtr::<$pointee>::from_ptr(ptr) }; + kani::cover(true, "AtomicPtr::from_ptr: reached after call"); + } + }; + } + + // Cover pointee sizes 0, 1, 2, 4, and the non-power-of-two size 3. + atomic_ptr_from_ptr_harness!(harness_atomic_ptr_from_ptr_unit, ()); + atomic_ptr_from_ptr_harness!(harness_atomic_ptr_from_ptr_u8, u8); + atomic_ptr_from_ptr_harness!(harness_atomic_ptr_from_ptr_u16, u16); + atomic_ptr_from_ptr_harness!(harness_atomic_ptr_from_ptr_u32, u32); + atomic_ptr_from_ptr_harness!(harness_atomic_ptr_from_ptr_u8_3, [u8; 3]); + + // Part 2: unsafe atomic helpers. + // Harnesses for atomic_store. + macro_rules! store_harness { + ($name:ident, $atomic:ty, $value:ty) => { + #[kani::proof_for_contract(atomic_store::<$value>)] + pub fn $name() { + let initial: $value = kani::any(); + let storage = <$atomic>::new(initial); + let val: $value = kani::any(); + + unsafe { atomic_store(storage.as_ptr(), val, any_ordering()) }; + kani::cover(true, "atomic_store: reached after call"); + } + }; + } + + #[cfg(target_has_atomic_load_store = "8")] + store_harness!(harness_atomic_store_i8, AtomicI8, i8); + #[cfg(target_has_atomic_load_store = "8")] + store_harness!(harness_atomic_store_u8, AtomicU8, u8); + #[cfg(target_has_atomic_load_store = "16")] + store_harness!(harness_atomic_store_i16, AtomicI16, i16); + #[cfg(target_has_atomic_load_store = "16")] + store_harness!(harness_atomic_store_u16, AtomicU16, u16); + #[cfg(target_has_atomic_load_store = "32")] + store_harness!(harness_atomic_store_i32, AtomicI32, i32); + #[cfg(target_has_atomic_load_store = "32")] + store_harness!(harness_atomic_store_u32, AtomicU32, u32); + #[cfg(target_has_atomic_load_store = "64")] + store_harness!(harness_atomic_store_i64, AtomicI64, i64); + #[cfg(target_has_atomic_load_store = "64")] + store_harness!(harness_atomic_store_u64, AtomicU64, u64); + #[cfg(target_has_atomic_load_store = "128")] + store_harness!(harness_atomic_store_i128, AtomicI128, i128); + #[cfg(target_has_atomic_load_store = "128")] + store_harness!(harness_atomic_store_u128, AtomicU128, u128); + #[cfg(target_has_atomic_load_store = "ptr")] + store_harness!(harness_atomic_store_isize, AtomicIsize, isize); + #[cfg(target_has_atomic_load_store = "ptr")] + store_harness!(harness_atomic_store_usize, AtomicUsize, usize); + + // Pointer harnesses for atomic_store. + #[cfg(target_has_atomic_load_store = "ptr")] + #[kani::proof_for_contract(atomic_store::<*mut u8>)] + pub fn harness_atomic_store_ptr() { + let initial = kani::any::() as *mut u8; + let storage = AtomicPtr::::new(initial); + let val = kani::any::() as *mut u8; + + unsafe { atomic_store(storage.as_ptr(), val, any_ordering()) }; + kani::cover(true, "atomic_store: reached after call"); + } + + // Harnesses for atomic_load. + macro_rules! load_harness { + ($name:ident, $atomic:ty, $value:ty) => { + #[kani::proof_for_contract(atomic_load::<$value>)] + pub fn $name() { + let initial: $value = kani::any(); + let storage = <$atomic>::new(initial); + + let _ = unsafe { atomic_load(storage.as_ptr().cast_const(), any_ordering()) }; + kani::cover(true, "atomic_load: reached after call"); + } + }; + } + + // Load helpers. + #[cfg(target_has_atomic_load_store = "8")] + load_harness!(harness_atomic_load_i8, AtomicI8, i8); + #[cfg(target_has_atomic_load_store = "8")] + load_harness!(harness_atomic_load_u8, AtomicU8, u8); + #[cfg(target_has_atomic_load_store = "16")] + load_harness!(harness_atomic_load_i16, AtomicI16, i16); + #[cfg(target_has_atomic_load_store = "16")] + load_harness!(harness_atomic_load_u16, AtomicU16, u16); + #[cfg(target_has_atomic_load_store = "32")] + load_harness!(harness_atomic_load_i32, AtomicI32, i32); + #[cfg(target_has_atomic_load_store = "32")] + load_harness!(harness_atomic_load_u32, AtomicU32, u32); + #[cfg(target_has_atomic_load_store = "64")] + load_harness!(harness_atomic_load_i64, AtomicI64, i64); + #[cfg(target_has_atomic_load_store = "64")] + load_harness!(harness_atomic_load_u64, AtomicU64, u64); + #[cfg(target_has_atomic_load_store = "128")] + load_harness!(harness_atomic_load_i128, AtomicI128, i128); + #[cfg(target_has_atomic_load_store = "128")] + load_harness!(harness_atomic_load_u128, AtomicU128, u128); + #[cfg(target_has_atomic_load_store = "ptr")] + load_harness!(harness_atomic_load_isize, AtomicIsize, isize); + #[cfg(target_has_atomic_load_store = "ptr")] + load_harness!(harness_atomic_load_usize, AtomicUsize, usize); + + // Pointer harness for atomic_load. + #[cfg(target_has_atomic_load_store = "ptr")] + #[kani::proof_for_contract(atomic_load::<*mut u8>)] + pub fn harness_atomic_load_ptr_u8() { + let initial = kani::any::() as *mut u8; + let storage = AtomicPtr::::new(initial); + + let _ = unsafe { atomic_load(storage.as_ptr().cast_const(), any_ordering()) }; + kani::cover(true, "atomic_load: reached after call"); + } + + // Harnesses for atomic_swap, atomic_max, atomic_umax, and atomic_umin. + macro_rules! rmw_harness { + ($name:ident, $operation:ident, $atomic:ty, $value:ty) => { + #[kani::proof_for_contract($operation::<$value>)] + pub fn $name() { + let initial: $value = kani::any(); + let storage = <$atomic>::new(initial); + let val: $value = kani::any(); + + let _ = unsafe { $operation(storage.as_ptr(), val, any_ordering()) }; + kani::cover(true, "atomic_swap/max/umax/umin: reached after call"); + } + }; + } + + // Exchange helpers. + #[cfg(target_has_atomic = "8")] + rmw_harness!(harness_atomic_swap_i8, atomic_swap, AtomicI8, i8); + #[cfg(target_has_atomic = "8")] + rmw_harness!(harness_atomic_swap_u8, atomic_swap, AtomicU8, u8); + #[cfg(target_has_atomic = "16")] + rmw_harness!(harness_atomic_swap_i16, atomic_swap, AtomicI16, i16); + #[cfg(target_has_atomic = "16")] + rmw_harness!(harness_atomic_swap_u16, atomic_swap, AtomicU16, u16); + #[cfg(target_has_atomic = "32")] + rmw_harness!(harness_atomic_swap_i32, atomic_swap, AtomicI32, i32); + #[cfg(target_has_atomic = "32")] + rmw_harness!(harness_atomic_swap_u32, atomic_swap, AtomicU32, u32); + #[cfg(target_has_atomic = "64")] + rmw_harness!(harness_atomic_swap_i64, atomic_swap, AtomicI64, i64); + #[cfg(target_has_atomic = "64")] + rmw_harness!(harness_atomic_swap_u64, atomic_swap, AtomicU64, u64); + #[cfg(target_has_atomic = "128")] + rmw_harness!(harness_atomic_swap_i128, atomic_swap, AtomicI128, i128); + #[cfg(target_has_atomic = "128")] + rmw_harness!(harness_atomic_swap_u128, atomic_swap, AtomicU128, u128); + #[cfg(target_has_atomic = "ptr")] + rmw_harness!(harness_atomic_swap_isize, atomic_swap, AtomicIsize, isize); + #[cfg(target_has_atomic = "ptr")] + rmw_harness!(harness_atomic_swap_usize, atomic_swap, AtomicUsize, usize); + + // Signed maximum helpers. + #[cfg(target_has_atomic = "8")] + rmw_harness!(harness_atomic_max_i8, atomic_max, AtomicI8, i8); + #[cfg(target_has_atomic = "16")] + rmw_harness!(harness_atomic_max_i16, atomic_max, AtomicI16, i16); + #[cfg(target_has_atomic = "32")] + rmw_harness!(harness_atomic_max_i32, atomic_max, AtomicI32, i32); + #[cfg(target_has_atomic = "64")] + rmw_harness!(harness_atomic_max_i64, atomic_max, AtomicI64, i64); + #[cfg(target_has_atomic = "128")] + rmw_harness!(harness_atomic_max_i128, atomic_max, AtomicI128, i128); + #[cfg(target_has_atomic = "ptr")] + rmw_harness!(harness_atomic_max_isize, atomic_max, AtomicIsize, isize); + + // Unsigned maximum helpers. + #[cfg(target_has_atomic = "8")] + rmw_harness!(harness_atomic_umax_u8, atomic_umax, AtomicU8, u8); + #[cfg(target_has_atomic = "16")] + rmw_harness!(harness_atomic_umax_u16, atomic_umax, AtomicU16, u16); + #[cfg(target_has_atomic = "32")] + rmw_harness!(harness_atomic_umax_u32, atomic_umax, AtomicU32, u32); + #[cfg(target_has_atomic = "64")] + rmw_harness!(harness_atomic_umax_u64, atomic_umax, AtomicU64, u64); + #[cfg(target_has_atomic = "128")] + rmw_harness!(harness_atomic_umax_u128, atomic_umax, AtomicU128, u128); + #[cfg(target_has_atomic = "ptr")] + rmw_harness!(harness_atomic_umax_usize, atomic_umax, AtomicUsize, usize); + + // Unsigned minimum helpers. + #[cfg(target_has_atomic = "8")] + rmw_harness!(harness_atomic_umin_u8, atomic_umin, AtomicU8, u8); + #[cfg(target_has_atomic = "16")] + rmw_harness!(harness_atomic_umin_u16, atomic_umin, AtomicU16, u16); + #[cfg(target_has_atomic = "32")] + rmw_harness!(harness_atomic_umin_u32, atomic_umin, AtomicU32, u32); + #[cfg(target_has_atomic = "64")] + rmw_harness!(harness_atomic_umin_u64, atomic_umin, AtomicU64, u64); + #[cfg(target_has_atomic = "128")] + rmw_harness!(harness_atomic_umin_u128, atomic_umin, AtomicU128, u128); + #[cfg(target_has_atomic = "ptr")] + rmw_harness!(harness_atomic_umin_usize, atomic_umin, AtomicUsize, usize); + + // Pointer harnesses for atomic_swap. + #[cfg(target_has_atomic = "ptr")] + #[kani::proof_for_contract(atomic_swap::<*mut u8>)] + pub fn harness_atomic_swap_ptr() { + let initial = kani::any::() as *mut u8; + let storage = AtomicPtr::::new(initial); + let val = kani::any::() as *mut u8; + + let _ = unsafe { atomic_swap(storage.as_ptr(), val, any_ordering()) }; + kani::cover(true, "atomic_swap: reached after call"); + } + + // Harnesses for atomic_add, atomic_sub, atomic_and, atomic_nand, atomic_or, and atomic_xor. + macro_rules! binary_rmw_harness { + ($name:ident, $operation:ident, $atomic:ty, $value:ty) => { + #[kani::proof_for_contract($operation::<$value, $value>)] + pub fn $name() { + let initial: $value = kani::any(); + let storage = <$atomic>::new(initial); + let val: $value = kani::any(); + + let _ = unsafe { $operation(storage.as_ptr(), val, any_ordering()) }; + kani::cover(true, "atomic_add/sub/and/nand/or/xor: reached after call"); + } + }; + } + + // Pointer versions use a usize operand; raw pointers do not implement kani::Arbitrary. + macro_rules! binary_rmw_ptr_harness { + ($name:ident, $operation:ident, $pointee:ty) => { + #[kani::proof_for_contract($operation::<*mut $pointee, usize>)] + pub fn $name() { + let initial = kani::any::() as *mut $pointee; + let storage = AtomicPtr::<$pointee>::new(initial); + let val: usize = kani::any(); + + let _ = unsafe { $operation(storage.as_ptr(), val, any_ordering()) }; + kani::cover(true, "atomic pointer binary RMW: reached after call"); + } + }; + } + + // Add helpers. + #[cfg(target_has_atomic = "8")] + binary_rmw_harness!(harness_atomic_add_i8, atomic_add, AtomicI8, i8); + #[cfg(target_has_atomic = "8")] + binary_rmw_harness!(harness_atomic_add_u8, atomic_add, AtomicU8, u8); + #[cfg(target_has_atomic = "16")] + binary_rmw_harness!(harness_atomic_add_i16, atomic_add, AtomicI16, i16); + #[cfg(target_has_atomic = "16")] + binary_rmw_harness!(harness_atomic_add_u16, atomic_add, AtomicU16, u16); + #[cfg(target_has_atomic = "32")] + binary_rmw_harness!(harness_atomic_add_i32, atomic_add, AtomicI32, i32); + #[cfg(target_has_atomic = "32")] + binary_rmw_harness!(harness_atomic_add_u32, atomic_add, AtomicU32, u32); + #[cfg(target_has_atomic = "64")] + binary_rmw_harness!(harness_atomic_add_i64, atomic_add, AtomicI64, i64); + #[cfg(target_has_atomic = "64")] + binary_rmw_harness!(harness_atomic_add_u64, atomic_add, AtomicU64, u64); + #[cfg(target_has_atomic = "128")] + binary_rmw_harness!(harness_atomic_add_i128, atomic_add, AtomicI128, i128); + #[cfg(target_has_atomic = "128")] + binary_rmw_harness!(harness_atomic_add_u128, atomic_add, AtomicU128, u128); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_harness!(harness_atomic_add_isize, atomic_add, AtomicIsize, isize); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_harness!(harness_atomic_add_usize, atomic_add, AtomicUsize, usize); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_ptr_harness!(harness_atomic_add_ptr, atomic_add, u8); + + // Subtract helpers. + #[cfg(target_has_atomic = "8")] + binary_rmw_harness!(harness_atomic_sub_i8, atomic_sub, AtomicI8, i8); + #[cfg(target_has_atomic = "8")] + binary_rmw_harness!(harness_atomic_sub_u8, atomic_sub, AtomicU8, u8); + #[cfg(target_has_atomic = "16")] + binary_rmw_harness!(harness_atomic_sub_i16, atomic_sub, AtomicI16, i16); + #[cfg(target_has_atomic = "16")] + binary_rmw_harness!(harness_atomic_sub_u16, atomic_sub, AtomicU16, u16); + #[cfg(target_has_atomic = "32")] + binary_rmw_harness!(harness_atomic_sub_i32, atomic_sub, AtomicI32, i32); + #[cfg(target_has_atomic = "32")] + binary_rmw_harness!(harness_atomic_sub_u32, atomic_sub, AtomicU32, u32); + #[cfg(target_has_atomic = "64")] + binary_rmw_harness!(harness_atomic_sub_i64, atomic_sub, AtomicI64, i64); + #[cfg(target_has_atomic = "64")] + binary_rmw_harness!(harness_atomic_sub_u64, atomic_sub, AtomicU64, u64); + #[cfg(target_has_atomic = "128")] + binary_rmw_harness!(harness_atomic_sub_i128, atomic_sub, AtomicI128, i128); + #[cfg(target_has_atomic = "128")] + binary_rmw_harness!(harness_atomic_sub_u128, atomic_sub, AtomicU128, u128); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_harness!(harness_atomic_sub_isize, atomic_sub, AtomicIsize, isize); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_harness!(harness_atomic_sub_usize, atomic_sub, AtomicUsize, usize); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_ptr_harness!(harness_atomic_sub_ptr, atomic_sub, u8); + + // Bitwise AND helpers. + #[cfg(target_has_atomic = "8")] + binary_rmw_harness!(harness_atomic_and_i8, atomic_and, AtomicI8, i8); + #[cfg(target_has_atomic = "8")] + binary_rmw_harness!(harness_atomic_and_u8, atomic_and, AtomicU8, u8); + #[cfg(target_has_atomic = "16")] + binary_rmw_harness!(harness_atomic_and_i16, atomic_and, AtomicI16, i16); + #[cfg(target_has_atomic = "16")] + binary_rmw_harness!(harness_atomic_and_u16, atomic_and, AtomicU16, u16); + #[cfg(target_has_atomic = "32")] + binary_rmw_harness!(harness_atomic_and_i32, atomic_and, AtomicI32, i32); + #[cfg(target_has_atomic = "32")] + binary_rmw_harness!(harness_atomic_and_u32, atomic_and, AtomicU32, u32); + #[cfg(target_has_atomic = "64")] + binary_rmw_harness!(harness_atomic_and_i64, atomic_and, AtomicI64, i64); + #[cfg(target_has_atomic = "64")] + binary_rmw_harness!(harness_atomic_and_u64, atomic_and, AtomicU64, u64); + #[cfg(target_has_atomic = "128")] + binary_rmw_harness!(harness_atomic_and_i128, atomic_and, AtomicI128, i128); + #[cfg(target_has_atomic = "128")] + binary_rmw_harness!(harness_atomic_and_u128, atomic_and, AtomicU128, u128); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_harness!(harness_atomic_and_isize, atomic_and, AtomicIsize, isize); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_harness!(harness_atomic_and_usize, atomic_and, AtomicUsize, usize); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_ptr_harness!(harness_atomic_and_ptr, atomic_and, u8); + + // Bitwise NAND helpers. + #[cfg(target_has_atomic = "8")] + binary_rmw_harness!(harness_atomic_nand_i8, atomic_nand, AtomicI8, i8); + #[cfg(target_has_atomic = "8")] + binary_rmw_harness!(harness_atomic_nand_u8, atomic_nand, AtomicU8, u8); + #[cfg(target_has_atomic = "16")] + binary_rmw_harness!(harness_atomic_nand_i16, atomic_nand, AtomicI16, i16); + #[cfg(target_has_atomic = "16")] + binary_rmw_harness!(harness_atomic_nand_u16, atomic_nand, AtomicU16, u16); + #[cfg(target_has_atomic = "32")] + binary_rmw_harness!(harness_atomic_nand_i32, atomic_nand, AtomicI32, i32); + #[cfg(target_has_atomic = "32")] + binary_rmw_harness!(harness_atomic_nand_u32, atomic_nand, AtomicU32, u32); + #[cfg(target_has_atomic = "64")] + binary_rmw_harness!(harness_atomic_nand_i64, atomic_nand, AtomicI64, i64); + #[cfg(target_has_atomic = "64")] + binary_rmw_harness!(harness_atomic_nand_u64, atomic_nand, AtomicU64, u64); + #[cfg(target_has_atomic = "128")] + binary_rmw_harness!(harness_atomic_nand_i128, atomic_nand, AtomicI128, i128); + #[cfg(target_has_atomic = "128")] + binary_rmw_harness!(harness_atomic_nand_u128, atomic_nand, AtomicU128, u128); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_harness!(harness_atomic_nand_isize, atomic_nand, AtomicIsize, isize); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_harness!(harness_atomic_nand_usize, atomic_nand, AtomicUsize, usize); + + // Bitwise OR helpers. + #[cfg(target_has_atomic = "8")] + binary_rmw_harness!(harness_atomic_or_i8, atomic_or, AtomicI8, i8); + #[cfg(target_has_atomic = "8")] + binary_rmw_harness!(harness_atomic_or_u8, atomic_or, AtomicU8, u8); + #[cfg(target_has_atomic = "16")] + binary_rmw_harness!(harness_atomic_or_i16, atomic_or, AtomicI16, i16); + #[cfg(target_has_atomic = "16")] + binary_rmw_harness!(harness_atomic_or_u16, atomic_or, AtomicU16, u16); + #[cfg(target_has_atomic = "32")] + binary_rmw_harness!(harness_atomic_or_i32, atomic_or, AtomicI32, i32); + #[cfg(target_has_atomic = "32")] + binary_rmw_harness!(harness_atomic_or_u32, atomic_or, AtomicU32, u32); + #[cfg(target_has_atomic = "64")] + binary_rmw_harness!(harness_atomic_or_i64, atomic_or, AtomicI64, i64); + #[cfg(target_has_atomic = "64")] + binary_rmw_harness!(harness_atomic_or_u64, atomic_or, AtomicU64, u64); + #[cfg(target_has_atomic = "128")] + binary_rmw_harness!(harness_atomic_or_i128, atomic_or, AtomicI128, i128); + #[cfg(target_has_atomic = "128")] + binary_rmw_harness!(harness_atomic_or_u128, atomic_or, AtomicU128, u128); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_harness!(harness_atomic_or_isize, atomic_or, AtomicIsize, isize); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_harness!(harness_atomic_or_usize, atomic_or, AtomicUsize, usize); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_ptr_harness!(harness_atomic_or_ptr, atomic_or, u8); + + // Bitwise XOR helpers. + #[cfg(target_has_atomic = "8")] + binary_rmw_harness!(harness_atomic_xor_i8, atomic_xor, AtomicI8, i8); + #[cfg(target_has_atomic = "8")] + binary_rmw_harness!(harness_atomic_xor_u8, atomic_xor, AtomicU8, u8); + #[cfg(target_has_atomic = "16")] + binary_rmw_harness!(harness_atomic_xor_i16, atomic_xor, AtomicI16, i16); + #[cfg(target_has_atomic = "16")] + binary_rmw_harness!(harness_atomic_xor_u16, atomic_xor, AtomicU16, u16); + #[cfg(target_has_atomic = "32")] + binary_rmw_harness!(harness_atomic_xor_i32, atomic_xor, AtomicI32, i32); + #[cfg(target_has_atomic = "32")] + binary_rmw_harness!(harness_atomic_xor_u32, atomic_xor, AtomicU32, u32); + #[cfg(target_has_atomic = "64")] + binary_rmw_harness!(harness_atomic_xor_i64, atomic_xor, AtomicI64, i64); + #[cfg(target_has_atomic = "64")] + binary_rmw_harness!(harness_atomic_xor_u64, atomic_xor, AtomicU64, u64); + #[cfg(target_has_atomic = "128")] + binary_rmw_harness!(harness_atomic_xor_i128, atomic_xor, AtomicI128, i128); + #[cfg(target_has_atomic = "128")] + binary_rmw_harness!(harness_atomic_xor_u128, atomic_xor, AtomicU128, u128); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_harness!(harness_atomic_xor_isize, atomic_xor, AtomicIsize, isize); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_harness!(harness_atomic_xor_usize, atomic_xor, AtomicUsize, usize); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_ptr_harness!(harness_atomic_xor_ptr, atomic_xor, u8); + + // Harnesses for atomic_compare_exchange and atomic_compare_exchange_weak. + macro_rules! compare_exchange_harness { + ($name:ident, $operation:ident, $atomic:ty, $value:ty) => { + #[kani::proof_for_contract($operation::<$value>)] + pub fn $name() { + let initial: $value = kani::any(); + let storage = <$atomic>::new(initial); + let old: $value = kani::any(); + let new: $value = kani::any(); + + let _ = unsafe { + $operation(storage.as_ptr(), old, new, any_ordering(), any_ordering()) + }; + kani::cover(true, "atomic_compare_exchange/weak: reached after call"); + } + }; + } + + // Strong compare-exchange helpers. + #[cfg(target_has_atomic = "8")] + compare_exchange_harness!( + harness_atomic_compare_exchange_i8, + atomic_compare_exchange, + AtomicI8, + i8 + ); + #[cfg(target_has_atomic = "8")] + compare_exchange_harness!( + harness_atomic_compare_exchange_u8, + atomic_compare_exchange, + AtomicU8, + u8 + ); + #[cfg(target_has_atomic = "16")] + compare_exchange_harness!( + harness_atomic_compare_exchange_i16, + atomic_compare_exchange, + AtomicI16, + i16 + ); + #[cfg(target_has_atomic = "16")] + compare_exchange_harness!( + harness_atomic_compare_exchange_u16, + atomic_compare_exchange, + AtomicU16, + u16 + ); + #[cfg(target_has_atomic = "32")] + compare_exchange_harness!( + harness_atomic_compare_exchange_i32, + atomic_compare_exchange, + AtomicI32, + i32 + ); + #[cfg(target_has_atomic = "32")] + compare_exchange_harness!( + harness_atomic_compare_exchange_u32, + atomic_compare_exchange, + AtomicU32, + u32 + ); + #[cfg(target_has_atomic = "64")] + compare_exchange_harness!( + harness_atomic_compare_exchange_i64, + atomic_compare_exchange, + AtomicI64, + i64 + ); + #[cfg(target_has_atomic = "64")] + compare_exchange_harness!( + harness_atomic_compare_exchange_u64, + atomic_compare_exchange, + AtomicU64, + u64 + ); + #[cfg(target_has_atomic = "128")] + compare_exchange_harness!( + harness_atomic_compare_exchange_i128, + atomic_compare_exchange, + AtomicI128, + i128 + ); + #[cfg(target_has_atomic = "128")] + compare_exchange_harness!( + harness_atomic_compare_exchange_u128, + atomic_compare_exchange, + AtomicU128, + u128 + ); + #[cfg(target_has_atomic = "ptr")] + compare_exchange_harness!( + harness_atomic_compare_exchange_isize, + atomic_compare_exchange, + AtomicIsize, + isize + ); + #[cfg(target_has_atomic = "ptr")] + compare_exchange_harness!( + harness_atomic_compare_exchange_usize, + atomic_compare_exchange, + AtomicUsize, + usize + ); + + // Weak compare-exchange helpers. + #[cfg(target_has_atomic = "8")] + compare_exchange_harness!( + harness_atomic_compare_exchange_weak_i8, + atomic_compare_exchange_weak, + AtomicI8, + i8 + ); + #[cfg(target_has_atomic = "8")] + compare_exchange_harness!( + harness_atomic_compare_exchange_weak_u8, + atomic_compare_exchange_weak, + AtomicU8, + u8 + ); + #[cfg(target_has_atomic = "16")] + compare_exchange_harness!( + harness_atomic_compare_exchange_weak_i16, + atomic_compare_exchange_weak, + AtomicI16, + i16 + ); + #[cfg(target_has_atomic = "16")] + compare_exchange_harness!( + harness_atomic_compare_exchange_weak_u16, + atomic_compare_exchange_weak, + AtomicU16, + u16 + ); + #[cfg(target_has_atomic = "32")] + compare_exchange_harness!( + harness_atomic_compare_exchange_weak_i32, + atomic_compare_exchange_weak, + AtomicI32, + i32 + ); + #[cfg(target_has_atomic = "32")] + compare_exchange_harness!( + harness_atomic_compare_exchange_weak_u32, + atomic_compare_exchange_weak, + AtomicU32, + u32 + ); + #[cfg(target_has_atomic = "64")] + compare_exchange_harness!( + harness_atomic_compare_exchange_weak_i64, + atomic_compare_exchange_weak, + AtomicI64, + i64 + ); + #[cfg(target_has_atomic = "64")] + compare_exchange_harness!( + harness_atomic_compare_exchange_weak_u64, + atomic_compare_exchange_weak, + AtomicU64, + u64 + ); + #[cfg(target_has_atomic = "128")] + compare_exchange_harness!( + harness_atomic_compare_exchange_weak_i128, + atomic_compare_exchange_weak, + AtomicI128, + i128 + ); + #[cfg(target_has_atomic = "128")] + compare_exchange_harness!( + harness_atomic_compare_exchange_weak_u128, + atomic_compare_exchange_weak, + AtomicU128, + u128 + ); + #[cfg(target_has_atomic = "ptr")] + compare_exchange_harness!( + harness_atomic_compare_exchange_weak_isize, + atomic_compare_exchange_weak, + AtomicIsize, + isize + ); + #[cfg(target_has_atomic = "ptr")] + compare_exchange_harness!( + harness_atomic_compare_exchange_weak_usize, + atomic_compare_exchange_weak, + AtomicUsize, + usize + ); + + // Pointer harnesses for atomic_compare_exchange and atomic_compare_exchange_weak. + macro_rules! compare_exchange_ptr_harness { + ($name:ident, $operation:ident, $pointee:ty) => { + #[kani::proof_for_contract($operation::<*mut $pointee>)] + pub fn $name() { + let initial = kani::any::() as *mut $pointee; + let storage = AtomicPtr::<$pointee>::new(initial); + let old = kani::any::() as *mut $pointee; + let new = kani::any::() as *mut $pointee; + + let _ = unsafe { + $operation(storage.as_ptr(), old, new, any_ordering(), any_ordering()) + }; + kani::cover(true, "atomic_compare_exchange/weak: reached after call"); + } + }; + } + + #[cfg(target_has_atomic = "ptr")] + compare_exchange_ptr_harness!(harness_atomic_compare_exchange_ptr, atomic_compare_exchange, u8); + #[cfg(target_has_atomic = "ptr")] + compare_exchange_ptr_harness!( + harness_atomic_compare_exchange_weak_ptr, + atomic_compare_exchange_weak, + u8 + ); + + // Part 2 (optional): safe atomic abstractions and ordering contracts. + fn any_load_order() -> Ordering { + match kani::any::() % 3 { + 0 => Relaxed, + 1 => Acquire, + _ => SeqCst, + } + } + + fn any_store_order() -> Ordering { + match kani::any::() % 3 { + 0 => Relaxed, + 1 => Release, + _ => SeqCst, + } + } + + fn any_failure_order() -> Ordering { + any_load_order() + } + + // Harnesses for load and store methods of atomic types, with safe abstractions. + macro_rules! safe_load_store_harness { + ($load_name:ident, $store_name:ident, $atomic:ty, $value:ty) => { + #[kani::proof_for_contract(<$atomic>::load)] + pub fn $load_name() { + let storage = <$atomic>::new(kani::any::<$value>()); + let _ = storage.load(any_load_order()); + kani::cover(true, "safe atomic load: reached after call"); + } + + #[kani::proof_for_contract(<$atomic>::store)] + pub fn $store_name() { + let storage = <$atomic>::new(kani::any::<$value>()); + storage.store(kani::any::<$value>(), any_store_order()); + kani::cover(true, "safe atomic store: reached after call"); + } + }; + } + + #[cfg(target_has_atomic_load_store = "8")] + safe_load_store_harness!(harness_safe_load_bool, harness_safe_store_bool, AtomicBool, bool); + #[cfg(target_has_atomic_load_store = "8")] + safe_load_store_harness!(harness_safe_load_i8, harness_safe_store_i8, AtomicI8, i8); + #[cfg(target_has_atomic_load_store = "8")] + safe_load_store_harness!(harness_safe_load_u8, harness_safe_store_u8, AtomicU8, u8); + #[cfg(target_has_atomic_load_store = "16")] + safe_load_store_harness!(harness_safe_load_i16, harness_safe_store_i16, AtomicI16, i16); + #[cfg(target_has_atomic_load_store = "16")] + safe_load_store_harness!(harness_safe_load_u16, harness_safe_store_u16, AtomicU16, u16); + #[cfg(target_has_atomic_load_store = "32")] + safe_load_store_harness!(harness_safe_load_i32, harness_safe_store_i32, AtomicI32, i32); + #[cfg(target_has_atomic_load_store = "32")] + safe_load_store_harness!(harness_safe_load_u32, harness_safe_store_u32, AtomicU32, u32); + #[cfg(target_has_atomic_load_store = "64")] + safe_load_store_harness!(harness_safe_load_i64, harness_safe_store_i64, AtomicI64, i64); + #[cfg(target_has_atomic_load_store = "64")] + safe_load_store_harness!(harness_safe_load_u64, harness_safe_store_u64, AtomicU64, u64); + #[cfg(target_has_atomic_load_store = "128")] + safe_load_store_harness!(harness_safe_load_i128, harness_safe_store_i128, AtomicI128, i128); + #[cfg(target_has_atomic_load_store = "128")] + safe_load_store_harness!(harness_safe_load_u128, harness_safe_store_u128, AtomicU128, u128); + #[cfg(target_has_atomic_load_store = "ptr")] + safe_load_store_harness!(harness_safe_load_isize, harness_safe_store_isize, AtomicIsize, isize); + #[cfg(target_has_atomic_load_store = "ptr")] + safe_load_store_harness!(harness_safe_load_usize, harness_safe_store_usize, AtomicUsize, usize); + + #[cfg(target_has_atomic_load_store = "ptr")] + #[kani::proof_for_contract(AtomicPtr::::load)] + pub fn harness_safe_load_ptr() { + let storage = AtomicPtr::::new(kani::any::() as *mut u8); + let _ = storage.load(any_load_order()); + kani::cover(true, "safe atomic pointer load: reached after call"); + } + + #[cfg(target_has_atomic_load_store = "ptr")] + #[kani::proof_for_contract(AtomicPtr::::store)] + pub fn harness_safe_store_ptr() { + let storage = AtomicPtr::::new(kani::any::() as *mut u8); + storage.store(kani::any::() as *mut u8, any_store_order()); + kani::cover(true, "safe atomic pointer store: reached after call"); + } + + macro_rules! safe_compare_exchange_harness { + ($name:ident, $atomic:ty, $value:ty, $method:ident) => { + #[kani::proof_for_contract(<$atomic>::$method)] + pub fn $name() { + let storage = <$atomic>::new(kani::any::<$value>()); + let _ = storage.$method( + kani::any::<$value>(), + kani::any::<$value>(), + any_ordering(), + any_failure_order(), + ); + kani::cover(true, "safe atomic compare-exchange: reached after call"); + } + }; + } + + #[cfg(target_has_atomic = "8")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_bool, + AtomicBool, + bool, + compare_exchange + ); + #[cfg(target_has_atomic = "8")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_weak_bool, + AtomicBool, + bool, + compare_exchange_weak + ); + #[cfg(target_has_atomic = "ptr")] + #[kani::proof_for_contract(AtomicPtr::::compare_exchange)] + pub fn harness_safe_compare_exchange_ptr() { + let storage = AtomicPtr::::new(kani::any::() as *mut u8); + let _ = storage.compare_exchange( + kani::any::() as *mut u8, + kani::any::() as *mut u8, + any_ordering(), + any_failure_order(), + ); + kani::cover(true, "safe atomic pointer compare-exchange: reached after call"); + } + #[cfg(target_has_atomic = "ptr")] + #[kani::proof_for_contract(AtomicPtr::::compare_exchange_weak)] + pub fn harness_safe_compare_exchange_weak_ptr() { + let storage = AtomicPtr::::new(kani::any::() as *mut u8); + let _ = storage.compare_exchange_weak( + kani::any::() as *mut u8, + kani::any::() as *mut u8, + any_ordering(), + any_failure_order(), + ); + kani::cover(true, "safe atomic pointer weak compare-exchange: reached after call"); + } + #[cfg(target_has_atomic = "8")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_u8, + AtomicU8, + u8, + compare_exchange + ); + #[cfg(target_has_atomic = "8")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_weak_u8, + AtomicU8, + u8, + compare_exchange_weak + ); + #[cfg(target_has_atomic = "8")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_i8, + AtomicI8, + i8, + compare_exchange + ); + #[cfg(target_has_atomic = "8")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_weak_i8, + AtomicI8, + i8, + compare_exchange_weak + ); + #[cfg(target_has_atomic = "16")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_i16, + AtomicI16, + i16, + compare_exchange + ); + #[cfg(target_has_atomic = "16")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_weak_i16, + AtomicI16, + i16, + compare_exchange_weak + ); + #[cfg(target_has_atomic = "16")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_u16, + AtomicU16, + u16, + compare_exchange + ); + #[cfg(target_has_atomic = "16")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_weak_u16, + AtomicU16, + u16, + compare_exchange_weak + ); + #[cfg(target_has_atomic = "32")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_i32, + AtomicI32, + i32, + compare_exchange + ); + #[cfg(target_has_atomic = "32")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_weak_i32, + AtomicI32, + i32, + compare_exchange_weak + ); + #[cfg(target_has_atomic = "32")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_u32, + AtomicU32, + u32, + compare_exchange + ); + #[cfg(target_has_atomic = "32")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_weak_u32, + AtomicU32, + u32, + compare_exchange_weak + ); + #[cfg(target_has_atomic = "64")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_i64, + AtomicI64, + i64, + compare_exchange + ); + #[cfg(target_has_atomic = "64")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_weak_i64, + AtomicI64, + i64, + compare_exchange_weak + ); + #[cfg(target_has_atomic = "64")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_u64, + AtomicU64, + u64, + compare_exchange + ); + #[cfg(target_has_atomic = "64")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_weak_u64, + AtomicU64, + u64, + compare_exchange_weak + ); + #[cfg(target_has_atomic = "128")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_i128, + AtomicI128, + i128, + compare_exchange + ); + #[cfg(target_has_atomic = "128")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_weak_i128, + AtomicI128, + i128, + compare_exchange_weak + ); + #[cfg(target_has_atomic = "128")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_u128, + AtomicU128, + u128, + compare_exchange + ); + #[cfg(target_has_atomic = "128")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_weak_u128, + AtomicU128, + u128, + compare_exchange_weak + ); + #[cfg(target_has_atomic = "ptr")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_isize, + AtomicIsize, + isize, + compare_exchange + ); + #[cfg(target_has_atomic = "ptr")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_weak_isize, + AtomicIsize, + isize, + compare_exchange_weak + ); + #[cfg(target_has_atomic = "ptr")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_usize, + AtomicUsize, + usize, + compare_exchange + ); + #[cfg(target_has_atomic = "ptr")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_weak_usize, + AtomicUsize, + usize, + compare_exchange_weak + ); + + macro_rules! safe_update_harness { + ($name:ident, $atomic:ty, $value:ty, $method:ident, $closure:expr) => { + #[kani::proof_for_contract(<$atomic>::$method)] + pub fn $name() { + let storage = <$atomic>::new(kani::any::<$value>()); + let _ = storage.$method(Relaxed, any_failure_order(), $closure); + kani::cover(true, "safe atomic update: reached after call"); + } + }; + } + + #[cfg(target_has_atomic = "8")] + safe_update_harness!(harness_safe_fetch_update_bool, AtomicBool, bool, fetch_update, |_| None); + #[cfg(target_has_atomic = "8")] + safe_update_harness!(harness_safe_try_update_bool, AtomicBool, bool, try_update, |_| None); + #[cfg(target_has_atomic = "8")] + safe_update_harness!(harness_safe_update_bool, AtomicBool, bool, update, |x| x); + #[cfg(target_has_atomic = "ptr")] + #[kani::proof_for_contract(AtomicPtr::::fetch_update)] + pub fn harness_safe_fetch_update_ptr() { + let storage = AtomicPtr::::new(kani::any::() as *mut u8); + let _ = storage.fetch_update(Relaxed, any_failure_order(), |_| None); + kani::cover(true, "safe atomic pointer fetch-update: reached after call"); + } + #[cfg(target_has_atomic = "ptr")] + #[kani::proof_for_contract(AtomicPtr::::try_update)] + pub fn harness_safe_try_update_ptr() { + let storage = AtomicPtr::::new(kani::any::() as *mut u8); + let _ = storage.try_update(Relaxed, any_failure_order(), |_| None); + kani::cover(true, "safe atomic pointer try-update: reached after call"); + } + #[cfg(all(target_has_atomic_load_store = "ptr", target_has_atomic = "8"))] + #[kani::proof_for_contract(AtomicPtr::::update)] + pub fn harness_safe_update_ptr() { + let storage = AtomicPtr::::new(kani::any::() as *mut u8); + let value = kani::any::() as *mut u8; + let _ = storage.update(Relaxed, any_failure_order(), |_| value); + kani::cover(true, "safe atomic pointer update: reached after call"); + } + #[cfg(target_has_atomic = "8")] + safe_update_harness!(harness_safe_fetch_update_i8, AtomicI8, i8, fetch_update, |_| None); + #[cfg(target_has_atomic = "8")] + safe_update_harness!(harness_safe_try_update_i8, AtomicI8, i8, try_update, |_| None); + #[cfg(target_has_atomic = "8")] + safe_update_harness!(harness_safe_update_i8, AtomicI8, i8, update, |x| x); + #[cfg(target_has_atomic = "8")] + safe_update_harness!(harness_safe_fetch_update_u8, AtomicU8, u8, fetch_update, |_| None); + #[cfg(target_has_atomic = "8")] + safe_update_harness!(harness_safe_try_update_u8, AtomicU8, u8, try_update, |_| None); + #[cfg(target_has_atomic = "8")] + safe_update_harness!(harness_safe_update_u8, AtomicU8, u8, update, |x| x); + #[cfg(target_has_atomic = "16")] + safe_update_harness!(harness_safe_fetch_update_i16, AtomicI16, i16, fetch_update, |_| None); + #[cfg(target_has_atomic = "16")] + safe_update_harness!(harness_safe_try_update_i16, AtomicI16, i16, try_update, |_| None); + #[cfg(target_has_atomic = "16")] + safe_update_harness!(harness_safe_update_i16, AtomicI16, i16, update, |x| x); + #[cfg(target_has_atomic = "16")] + safe_update_harness!(harness_safe_fetch_update_u16, AtomicU16, u16, fetch_update, |_| None); + #[cfg(target_has_atomic = "16")] + safe_update_harness!(harness_safe_try_update_u16, AtomicU16, u16, try_update, |_| None); + #[cfg(target_has_atomic = "16")] + safe_update_harness!(harness_safe_update_u16, AtomicU16, u16, update, |x| x); + #[cfg(target_has_atomic = "32")] + safe_update_harness!(harness_safe_fetch_update_i32, AtomicI32, i32, fetch_update, |_| None); + #[cfg(target_has_atomic = "32")] + safe_update_harness!(harness_safe_try_update_i32, AtomicI32, i32, try_update, |_| None); + #[cfg(target_has_atomic = "32")] + safe_update_harness!(harness_safe_update_i32, AtomicI32, i32, update, |x| x); + #[cfg(target_has_atomic = "32")] + safe_update_harness!(harness_safe_fetch_update_u32, AtomicU32, u32, fetch_update, |_| None); + #[cfg(target_has_atomic = "32")] + safe_update_harness!(harness_safe_try_update_u32, AtomicU32, u32, try_update, |_| None); + #[cfg(target_has_atomic = "32")] + safe_update_harness!(harness_safe_update_u32, AtomicU32, u32, update, |x| x); + #[cfg(target_has_atomic = "64")] + safe_update_harness!(harness_safe_fetch_update_i64, AtomicI64, i64, fetch_update, |_| None); + #[cfg(target_has_atomic = "64")] + safe_update_harness!(harness_safe_try_update_i64, AtomicI64, i64, try_update, |_| None); + #[cfg(target_has_atomic = "64")] + safe_update_harness!(harness_safe_update_i64, AtomicI64, i64, update, |x| x); + #[cfg(target_has_atomic = "64")] + safe_update_harness!(harness_safe_fetch_update_u64, AtomicU64, u64, fetch_update, |_| None); + #[cfg(target_has_atomic = "64")] + safe_update_harness!(harness_safe_try_update_u64, AtomicU64, u64, try_update, |_| None); + #[cfg(target_has_atomic = "64")] + safe_update_harness!(harness_safe_update_u64, AtomicU64, u64, update, |x| x); + #[cfg(target_has_atomic = "128")] + safe_update_harness!(harness_safe_fetch_update_i128, AtomicI128, i128, fetch_update, |_| None); + #[cfg(target_has_atomic = "128")] + safe_update_harness!(harness_safe_try_update_i128, AtomicI128, i128, try_update, |_| None); + #[cfg(target_has_atomic = "128")] + safe_update_harness!(harness_safe_update_i128, AtomicI128, i128, update, |x| x); + #[cfg(target_has_atomic = "128")] + safe_update_harness!(harness_safe_fetch_update_u128, AtomicU128, u128, fetch_update, |_| None); + #[cfg(target_has_atomic = "128")] + safe_update_harness!(harness_safe_try_update_u128, AtomicU128, u128, try_update, |_| None); + #[cfg(target_has_atomic = "128")] + safe_update_harness!(harness_safe_update_u128, AtomicU128, u128, update, |x| x); + #[cfg(target_has_atomic = "ptr")] + safe_update_harness!(harness_safe_fetch_update_isize, AtomicIsize, isize, fetch_update, |_| { + None + }); + #[cfg(target_has_atomic = "ptr")] + safe_update_harness!(harness_safe_try_update_isize, AtomicIsize, isize, try_update, |_| None); + #[cfg(target_has_atomic = "ptr")] + safe_update_harness!(harness_safe_update_isize, AtomicIsize, isize, update, |x| x); + #[cfg(target_has_atomic = "ptr")] + safe_update_harness!(harness_safe_fetch_update_usize, AtomicUsize, usize, fetch_update, |_| { + None + }); + #[cfg(target_has_atomic = "ptr")] + safe_update_harness!(harness_safe_try_update_usize, AtomicUsize, usize, try_update, |_| None); + #[cfg(target_has_atomic = "ptr")] + safe_update_harness!(harness_safe_update_usize, AtomicUsize, usize, update, |x| x); + #[cfg(target_has_atomic_load_store = "8")] + #[kani::proof] + #[kani::should_panic] + pub fn harness_safe_load_panics_on_release() { + let storage = AtomicBool::new(false); + let _ = storage.load(Release); + } + + #[cfg(target_has_atomic_load_store = "8")] + #[kani::proof] + #[kani::should_panic] + pub fn harness_safe_load_panics_on_acqrel() { + let storage = AtomicBool::new(false); + let _ = storage.load(AcqRel); + } + + #[cfg(target_has_atomic_load_store = "8")] + #[kani::proof] + #[kani::should_panic] + pub fn harness_safe_store_panics_on_acquire() { + let storage = AtomicBool::new(false); + storage.store(true, Acquire); + } + + #[cfg(target_has_atomic_load_store = "8")] + #[kani::proof] + #[kani::should_panic] + pub fn harness_safe_store_panics_on_acqrel() { + let storage = AtomicBool::new(false); + storage.store(true, AcqRel); + } + + macro_rules! safe_compare_exchange_panics_harness { + ($name:ident, $method:ident, $failure:expr) => { + #[cfg(target_has_atomic = "8")] + #[kani::proof] + #[kani::should_panic] + pub fn $name() { + let storage = AtomicBool::new(false); + let _ = storage.$method(false, true, Relaxed, $failure); + } + }; + } + + safe_compare_exchange_panics_harness!( + harness_safe_compare_exchange_panics_on_release, + compare_exchange, + Release + ); + safe_compare_exchange_panics_harness!( + harness_safe_compare_exchange_panics_on_acqrel, + compare_exchange, + AcqRel + ); + safe_compare_exchange_panics_harness!( + harness_safe_compare_exchange_weak_panics_on_release, + compare_exchange_weak, + Release + ); + safe_compare_exchange_panics_harness!( + harness_safe_compare_exchange_weak_panics_on_acqrel, + compare_exchange_weak, + AcqRel + ); + + macro_rules! safe_update_panics_harness { + ($name:ident, $method:ident, $failure:expr, $closure:expr) => { + #[cfg(target_has_atomic = "8")] + #[kani::proof] + #[kani::should_panic] + pub fn $name() { + let storage = AtomicBool::new(false); + let _ = storage.$method(Relaxed, $failure, $closure); + } + }; + } + + safe_update_panics_harness!( + harness_safe_fetch_update_panics_on_release, + fetch_update, + Release, + |_| None + ); + safe_update_panics_harness!( + harness_safe_fetch_update_panics_on_acqrel, + fetch_update, + AcqRel, + |_| None + ); + safe_update_panics_harness!( + harness_safe_try_update_panics_on_release, + try_update, + Release, + |_| None + ); + safe_update_panics_harness!( + harness_safe_try_update_panics_on_acqrel, + try_update, + AcqRel, + |_| None + ); + safe_update_panics_harness!(harness_safe_update_panics_on_release, update, Release, |x| x); + safe_update_panics_harness!(harness_safe_update_panics_on_acqrel, update, AcqRel, |x| x); +} From 394ab028e23602af9e84d17b57bf9447b3af388d Mon Sep 17 00:00:00 2001 From: v3risec Date: Wed, 23 Sep 2026 16:50:55 +0800 Subject: [PATCH 2/5] Bound atomic update loops in Kani harnesses --- library/core/src/sync/atomic.rs | 84 ++++++++++++++++++++------------- 1 file changed, 51 insertions(+), 33 deletions(-) diff --git a/library/core/src/sync/atomic.rs b/library/core/src/sync/atomic.rs index 82acb4fcf8abb..01dfbb7e00406 100644 --- a/library/core/src/sync/atomic.rs +++ b/library/core/src/sync/atomic.rs @@ -5829,8 +5829,6 @@ mod verify { safe_update_harness!(harness_safe_fetch_update_bool, AtomicBool, bool, fetch_update, |_| None); #[cfg(target_has_atomic = "8")] safe_update_harness!(harness_safe_try_update_bool, AtomicBool, bool, try_update, |_| None); - #[cfg(target_has_atomic = "8")] - safe_update_harness!(harness_safe_update_bool, AtomicBool, bool, update, |x| x); #[cfg(target_has_atomic = "ptr")] #[kani::proof_for_contract(AtomicPtr::::fetch_update)] pub fn harness_safe_fetch_update_ptr() { @@ -5845,74 +5843,46 @@ mod verify { let _ = storage.try_update(Relaxed, any_failure_order(), |_| None); kani::cover(true, "safe atomic pointer try-update: reached after call"); } - #[cfg(all(target_has_atomic_load_store = "ptr", target_has_atomic = "8"))] - #[kani::proof_for_contract(AtomicPtr::::update)] - pub fn harness_safe_update_ptr() { - let storage = AtomicPtr::::new(kani::any::() as *mut u8); - let value = kani::any::() as *mut u8; - let _ = storage.update(Relaxed, any_failure_order(), |_| value); - kani::cover(true, "safe atomic pointer update: reached after call"); - } #[cfg(target_has_atomic = "8")] safe_update_harness!(harness_safe_fetch_update_i8, AtomicI8, i8, fetch_update, |_| None); #[cfg(target_has_atomic = "8")] safe_update_harness!(harness_safe_try_update_i8, AtomicI8, i8, try_update, |_| None); #[cfg(target_has_atomic = "8")] - safe_update_harness!(harness_safe_update_i8, AtomicI8, i8, update, |x| x); - #[cfg(target_has_atomic = "8")] safe_update_harness!(harness_safe_fetch_update_u8, AtomicU8, u8, fetch_update, |_| None); #[cfg(target_has_atomic = "8")] safe_update_harness!(harness_safe_try_update_u8, AtomicU8, u8, try_update, |_| None); - #[cfg(target_has_atomic = "8")] - safe_update_harness!(harness_safe_update_u8, AtomicU8, u8, update, |x| x); #[cfg(target_has_atomic = "16")] safe_update_harness!(harness_safe_fetch_update_i16, AtomicI16, i16, fetch_update, |_| None); #[cfg(target_has_atomic = "16")] safe_update_harness!(harness_safe_try_update_i16, AtomicI16, i16, try_update, |_| None); #[cfg(target_has_atomic = "16")] - safe_update_harness!(harness_safe_update_i16, AtomicI16, i16, update, |x| x); - #[cfg(target_has_atomic = "16")] safe_update_harness!(harness_safe_fetch_update_u16, AtomicU16, u16, fetch_update, |_| None); #[cfg(target_has_atomic = "16")] safe_update_harness!(harness_safe_try_update_u16, AtomicU16, u16, try_update, |_| None); - #[cfg(target_has_atomic = "16")] - safe_update_harness!(harness_safe_update_u16, AtomicU16, u16, update, |x| x); #[cfg(target_has_atomic = "32")] safe_update_harness!(harness_safe_fetch_update_i32, AtomicI32, i32, fetch_update, |_| None); #[cfg(target_has_atomic = "32")] safe_update_harness!(harness_safe_try_update_i32, AtomicI32, i32, try_update, |_| None); #[cfg(target_has_atomic = "32")] - safe_update_harness!(harness_safe_update_i32, AtomicI32, i32, update, |x| x); - #[cfg(target_has_atomic = "32")] safe_update_harness!(harness_safe_fetch_update_u32, AtomicU32, u32, fetch_update, |_| None); #[cfg(target_has_atomic = "32")] safe_update_harness!(harness_safe_try_update_u32, AtomicU32, u32, try_update, |_| None); - #[cfg(target_has_atomic = "32")] - safe_update_harness!(harness_safe_update_u32, AtomicU32, u32, update, |x| x); #[cfg(target_has_atomic = "64")] safe_update_harness!(harness_safe_fetch_update_i64, AtomicI64, i64, fetch_update, |_| None); #[cfg(target_has_atomic = "64")] safe_update_harness!(harness_safe_try_update_i64, AtomicI64, i64, try_update, |_| None); #[cfg(target_has_atomic = "64")] - safe_update_harness!(harness_safe_update_i64, AtomicI64, i64, update, |x| x); - #[cfg(target_has_atomic = "64")] safe_update_harness!(harness_safe_fetch_update_u64, AtomicU64, u64, fetch_update, |_| None); #[cfg(target_has_atomic = "64")] safe_update_harness!(harness_safe_try_update_u64, AtomicU64, u64, try_update, |_| None); - #[cfg(target_has_atomic = "64")] - safe_update_harness!(harness_safe_update_u64, AtomicU64, u64, update, |x| x); #[cfg(target_has_atomic = "128")] safe_update_harness!(harness_safe_fetch_update_i128, AtomicI128, i128, fetch_update, |_| None); #[cfg(target_has_atomic = "128")] safe_update_harness!(harness_safe_try_update_i128, AtomicI128, i128, try_update, |_| None); #[cfg(target_has_atomic = "128")] - safe_update_harness!(harness_safe_update_i128, AtomicI128, i128, update, |x| x); - #[cfg(target_has_atomic = "128")] safe_update_harness!(harness_safe_fetch_update_u128, AtomicU128, u128, fetch_update, |_| None); #[cfg(target_has_atomic = "128")] safe_update_harness!(harness_safe_try_update_u128, AtomicU128, u128, try_update, |_| None); - #[cfg(target_has_atomic = "128")] - safe_update_harness!(harness_safe_update_u128, AtomicU128, u128, update, |x| x); #[cfg(target_has_atomic = "ptr")] safe_update_harness!(harness_safe_fetch_update_isize, AtomicIsize, isize, fetch_update, |_| { None @@ -5920,15 +5890,63 @@ mod verify { #[cfg(target_has_atomic = "ptr")] safe_update_harness!(harness_safe_try_update_isize, AtomicIsize, isize, try_update, |_| None); #[cfg(target_has_atomic = "ptr")] - safe_update_harness!(harness_safe_update_isize, AtomicIsize, isize, update, |x| x); - #[cfg(target_has_atomic = "ptr")] safe_update_harness!(harness_safe_fetch_update_usize, AtomicUsize, usize, fetch_update, |_| { None }); #[cfg(target_has_atomic = "ptr")] safe_update_harness!(harness_safe_try_update_usize, AtomicUsize, usize, try_update, |_| None); + + // Kani does not infer a finite bound for this CAS retry loop automatically. + // An unwind bound of 2 is sufficient for this single-threaded harness under + // Kani's current atomic intrinsic model. + macro_rules! safe_update_loop_harness { + ($name:ident, $atomic:ty, $value:ty) => { + #[kani::proof_for_contract(<$atomic>::update)] + #[kani::unwind(2)] + pub fn $name() { + let storage = <$atomic>::new(kani::any::<$value>()); + let _ = storage.update(Relaxed, any_failure_order(), |x| x); + kani::cover(true, "safe atomic update: reached after call"); + } + }; + } + #[cfg(target_has_atomic = "8")] + safe_update_loop_harness!(harness_safe_update_bool, AtomicBool, bool); + #[cfg(target_has_atomic = "8")] + safe_update_loop_harness!(harness_safe_update_i8, AtomicI8, i8); + #[cfg(target_has_atomic = "8")] + safe_update_loop_harness!(harness_safe_update_u8, AtomicU8, u8); + #[cfg(target_has_atomic = "16")] + safe_update_loop_harness!(harness_safe_update_i16, AtomicI16, i16); + #[cfg(target_has_atomic = "16")] + safe_update_loop_harness!(harness_safe_update_u16, AtomicU16, u16); + #[cfg(target_has_atomic = "32")] + safe_update_loop_harness!(harness_safe_update_i32, AtomicI32, i32); + #[cfg(target_has_atomic = "32")] + safe_update_loop_harness!(harness_safe_update_u32, AtomicU32, u32); + #[cfg(target_has_atomic = "64")] + safe_update_loop_harness!(harness_safe_update_i64, AtomicI64, i64); + #[cfg(target_has_atomic = "64")] + safe_update_loop_harness!(harness_safe_update_u64, AtomicU64, u64); + #[cfg(target_has_atomic = "128")] + safe_update_loop_harness!(harness_safe_update_i128, AtomicI128, i128); + #[cfg(target_has_atomic = "128")] + safe_update_loop_harness!(harness_safe_update_u128, AtomicU128, u128); + #[cfg(target_has_atomic = "ptr")] + safe_update_loop_harness!(harness_safe_update_isize, AtomicIsize, isize); #[cfg(target_has_atomic = "ptr")] - safe_update_harness!(harness_safe_update_usize, AtomicUsize, usize, update, |x| x); + safe_update_loop_harness!(harness_safe_update_usize, AtomicUsize, usize); + + #[cfg(all(target_has_atomic_load_store = "ptr", target_has_atomic = "8"))] + #[kani::proof_for_contract(AtomicPtr::::update)] + #[kani::unwind(2)] + pub fn harness_safe_update_ptr() { + let storage = AtomicPtr::::new(kani::any::() as *mut u8); + let value = kani::any::() as *mut u8; + let _ = storage.update(Relaxed, any_failure_order(), |_| value); + kani::cover(true, "safe atomic pointer update: reached after call"); + } + #[cfg(target_has_atomic_load_store = "8")] #[kani::proof] #[kani::should_panic] From 4bb26f7a876db5325dd0c1f9dfd4ba4e39c61d17 Mon Sep 17 00:00:00 2001 From: v3risec Date: Tue, 3 Nov 2026 20:29:06 +0800 Subject: [PATCH 3/5] Fix Challenge 7 proofs for updated atomic APIs --- library/core/src/intrinsics/mod.rs | 14 +- library/core/src/sync/atomic.rs | 249 ++++++++++++++++++----------- 2 files changed, 168 insertions(+), 95 deletions(-) diff --git a/library/core/src/intrinsics/mod.rs b/library/core/src/intrinsics/mod.rs index 442be4e43ad9e..0077f38b820fe 100644 --- a/library/core/src/intrinsics/mod.rs +++ b/library/core/src/intrinsics/mod.rs @@ -4692,22 +4692,24 @@ mod verify { // the intrinsic documentation, while the contracts encode only the local // memory obligations required by the intrinsic calls. // - // `can_dereference` and `can_write` cover allocation bounds, initialization, - // and alignment for `T`. Kani function contracts do not currently expose a predicate for cross-thread - // access histories, so the atomic model remains responsible for detecting - // data races and mixed-size overlapping atomic accesses in concurrent proofs. + // `can_dereference` and `can_write` express local memory requirements for `T`. + // Checking initialization through `can_dereference` requires `-Z uninit-checks`. + // These single-threaded proofs do not establish the absence of data races or + // unsynchronized mixed-size overlapping atomic accesses. The load and store + // wrappers cover non-volatile accesses only; volatile accesses have separate + // safety requirements. #[allow(dead_code)] #[kani::modifies(dst)] #[requires(crate::ub_checks::can_write(dst))] unsafe fn atomic_store_wrapper(dst: *mut T, val: T) { - unsafe { atomic_store::(dst, val) } + unsafe { atomic_store::(dst, val) } } #[allow(dead_code)] #[requires(crate::ub_checks::can_dereference(src))] unsafe fn atomic_load_wrapper(src: *const T) -> T { - unsafe { atomic_load::(src) } + unsafe { atomic_load::(src) } } #[allow(dead_code)] diff --git a/library/core/src/sync/atomic.rs b/library/core/src/sync/atomic.rs index d954f6442f807..cf90992f2e9e2 100644 --- a/library/core/src/sync/atomic.rs +++ b/library/core/src/sync/atomic.rs @@ -251,9 +251,9 @@ use crate::intrinsics::AtomicOrdering as AO; #[cfg(kani)] use crate::kani; use crate::mem::transmute; -use crate::{fmt, intrinsics}; #[cfg(kani)] use crate::ub_checks; +use crate::{fmt, intrinsics}; #[unstable( feature = "atomic_internals", @@ -1458,8 +1458,6 @@ impl AtomicBool { note = "renamed to `try_update` for consistency", suggestion = "try_update" )] - #[requires(fetch_order == Relaxed || fetch_order == Acquire || fetch_order == SeqCst)] - #[cfg_attr(kani, kani::modifies(self))] pub fn fetch_update( &self, set_order: Ordering, @@ -1524,8 +1522,6 @@ impl AtomicBool { #[cfg(target_has_atomic = "8")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] - #[requires(fetch_order == Relaxed || fetch_order == Acquire || fetch_order == SeqCst)] - #[cfg_attr(kani, kani::modifies(self))] pub fn try_update( &self, set_order: Ordering, @@ -1589,8 +1585,6 @@ impl AtomicBool { #[cfg(target_has_atomic = "8")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] - #[requires(fetch_order == Relaxed || fetch_order == Acquire || fetch_order == SeqCst)] - #[cfg_attr(kani, kani::modifies(self))] pub fn update( &self, set_order: Ordering, @@ -2297,8 +2291,6 @@ impl AtomicPtr { note = "renamed to `try_update` for consistency", suggestion = "try_update" )] - #[requires(fetch_order == Relaxed || fetch_order == Acquire || fetch_order == SeqCst)] - #[cfg_attr(kani, kani::modifies(self))] pub fn fetch_update( &self, set_order: Ordering, @@ -2372,8 +2364,6 @@ impl AtomicPtr { #[cfg(target_has_atomic = "ptr")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] - #[requires(fetch_order == Relaxed || fetch_order == Acquire || fetch_order == SeqCst)] - #[cfg_attr(kani, kani::modifies(self))] pub fn try_update( &self, set_order: Ordering, @@ -2442,8 +2432,6 @@ impl AtomicPtr { #[cfg(target_has_atomic = "ptr")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] - #[requires(fetch_order == Relaxed || fetch_order == Acquire || fetch_order == SeqCst)] - #[cfg_attr(kani, kani::modifies(self))] pub fn update( &self, set_order: Ordering, @@ -3817,8 +3805,6 @@ macro_rules! atomic_int { note = "renamed to `try_update` for consistency", suggestion = "try_update" )] - #[requires(fetch_order == Relaxed || fetch_order == Acquire || fetch_order == SeqCst)] - #[cfg_attr(kani, kani::modifies(self))] pub fn fetch_update(&self, set_order: Ordering, fetch_order: Ordering, @@ -3880,8 +3866,6 @@ macro_rules! atomic_int { #[cfg(any($cfg_cas, doc))] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] - #[requires(fetch_order == Relaxed || fetch_order == Acquire || fetch_order == SeqCst)] - #[cfg_attr(kani, kani::modifies(self))] pub fn try_update( &self, set_order: Ordering, @@ -3949,8 +3933,6 @@ macro_rules! atomic_int { #[cfg(any($cfg_cas, doc))] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_should_not_be_called_on_const_items] - #[requires(fetch_order == Relaxed || fetch_order == Acquire || fetch_order == SeqCst)] - #[cfg_attr(kani, kani::modifies(self))] pub fn update( &self, set_order: Ordering, @@ -5141,22 +5123,31 @@ mod verify { } } + // Use the concrete Atomic type in proof targets: Kani's contract resolver + // does not resolve methods through the AtomicBool/AtomicPtr/integer aliases. + // Calls below still exercise the corresponding public aliases. // Part 1: from_ptr. #[cfg(target_has_atomic_load_store = "8")] - #[kani::proof_for_contract(AtomicBool::from_ptr)] + #[kani::proof_for_contract(Atomic::::from_ptr)] pub fn harness_atomic_bool_from_ptr() { - let mut buf: [bool; 100] = kani::any(); - let offset = kani::any_where(|offset: &usize| *offset < 100); - let ptr = buf.as_mut_ptr().wrapping_add(offset); + // Arbitrary bool arrays use a MaybeUninit array internally, whose layout + // is unsupported by uninit-checks. Use independent symbolic bytes instead; + // from_ptr's preconditions retain only valid bool values at the chosen offset. + let mut buf: [u8; 100] = kani::any(); + let ptr = ptr_at_offset::(&mut buf); let _ = unsafe { AtomicBool::from_ptr(ptr) }; + let byte = unsafe { ptr.cast::().read() }; + assert!(byte <= 1); + kani::cover(byte == 0, "AtomicBool::from_ptr: false is reachable"); + kani::cover(byte == 1, "AtomicBool::from_ptr: true is reachable"); kani::cover(true, "AtomicBool::from_ptr: reached after call"); } // Harnesses for integer Atomic*::from_ptr functions. macro_rules! from_ptr_harness { ($name:ident, $atomic:ty, $value:ty) => { - #[kani::proof_for_contract(<$atomic>::from_ptr)] + #[kani::proof_for_contract(Atomic::<$value>::from_ptr)] pub fn $name() { let mut buf: [u8; 100] = kani::any(); let ptr = ptr_at_offset::<$value>(&mut buf); @@ -5189,10 +5180,13 @@ mod verify { from_ptr_harness!(harness_atomic_u128_from_ptr, AtomicU128, u128); // Harnesses for AtomicPtr::from_ptr. + // Kani matches this selector against the generic impl's definition path. + // `T` names its type parameter, not the concrete pointee used by the proof; + // each harness call below still instantiates the requested $pointee. macro_rules! atomic_ptr_from_ptr_harness { ($name:ident, $pointee:ty) => { #[cfg(target_has_atomic_load_store = "ptr")] - #[kani::proof_for_contract(AtomicPtr::<$pointee>::from_ptr)] + #[kani::proof_for_contract(Atomic::<*mut T>::from_ptr)] pub fn $name() { // The stored pointer is arbitrary; the outer pointer targets valid local storage. let mut value = kani::any::() as *mut $pointee; @@ -5212,16 +5206,17 @@ mod verify { atomic_ptr_from_ptr_harness!(harness_atomic_ptr_from_ptr_u8_3, [u8; 3]); // Part 2: unsafe atomic helpers. - // Harnesses for atomic_store. + // Harnesses for ordinary (non-volatile) atomic_store and atomic_load. + // Volatile accesses have separate safety requirements and are not covered here. macro_rules! store_harness { ($name:ident, $atomic:ty, $value:ty) => { - #[kani::proof_for_contract(atomic_store::<$value>)] + #[kani::proof_for_contract(atomic_store::<$value, false>)] pub fn $name() { let initial: $value = kani::any(); let storage = <$atomic>::new(initial); let val: $value = kani::any(); - unsafe { atomic_store(storage.as_ptr(), val, any_ordering()) }; + unsafe { atomic_store::<$value, false>(storage.as_ptr(), val, any_ordering()) }; kani::cover(true, "atomic_store: reached after call"); } }; @@ -5254,25 +5249,27 @@ mod verify { // Pointer harnesses for atomic_store. #[cfg(target_has_atomic_load_store = "ptr")] - #[kani::proof_for_contract(atomic_store::<*mut u8>)] + #[kani::proof_for_contract(atomic_store::<*mut u8, false>)] pub fn harness_atomic_store_ptr() { let initial = kani::any::() as *mut u8; let storage = AtomicPtr::::new(initial); let val = kani::any::() as *mut u8; - unsafe { atomic_store(storage.as_ptr(), val, any_ordering()) }; + unsafe { atomic_store::<*mut u8, false>(storage.as_ptr(), val, any_ordering()) }; kani::cover(true, "atomic_store: reached after call"); } // Harnesses for atomic_load. macro_rules! load_harness { ($name:ident, $atomic:ty, $value:ty) => { - #[kani::proof_for_contract(atomic_load::<$value>)] + #[kani::proof_for_contract(atomic_load::<$value, false>)] pub fn $name() { let initial: $value = kani::any(); let storage = <$atomic>::new(initial); - let _ = unsafe { atomic_load(storage.as_ptr().cast_const(), any_ordering()) }; + let _ = unsafe { + atomic_load::<$value, false>(storage.as_ptr().cast_const(), any_ordering()) + }; kani::cover(true, "atomic_load: reached after call"); } }; @@ -5306,12 +5303,13 @@ mod verify { // Pointer harness for atomic_load. #[cfg(target_has_atomic_load_store = "ptr")] - #[kani::proof_for_contract(atomic_load::<*mut u8>)] + #[kani::proof_for_contract(atomic_load::<*mut u8, false>)] pub fn harness_atomic_load_ptr_u8() { let initial = kani::any::() as *mut u8; let storage = AtomicPtr::::new(initial); - let _ = unsafe { atomic_load(storage.as_ptr().cast_const(), any_ordering()) }; + let _ = + unsafe { atomic_load::<*mut u8, false>(storage.as_ptr().cast_const(), any_ordering()) }; kani::cover(true, "atomic_load: reached after call"); } @@ -5847,14 +5845,14 @@ mod verify { // Harnesses for load and store methods of atomic types, with safe abstractions. macro_rules! safe_load_store_harness { ($load_name:ident, $store_name:ident, $atomic:ty, $value:ty) => { - #[kani::proof_for_contract(<$atomic>::load)] + #[kani::proof_for_contract(Atomic::<$value>::load)] pub fn $load_name() { let storage = <$atomic>::new(kani::any::<$value>()); let _ = storage.load(any_load_order()); kani::cover(true, "safe atomic load: reached after call"); } - #[kani::proof_for_contract(<$atomic>::store)] + #[kani::proof_for_contract(Atomic::<$value>::store)] pub fn $store_name() { let storage = <$atomic>::new(kani::any::<$value>()); storage.store(kani::any::<$value>(), any_store_order()); @@ -5891,7 +5889,7 @@ mod verify { safe_load_store_harness!(harness_safe_load_usize, harness_safe_store_usize, AtomicUsize, usize); #[cfg(target_has_atomic_load_store = "ptr")] - #[kani::proof_for_contract(AtomicPtr::::load)] + #[kani::proof_for_contract(Atomic::<*mut T>::load)] pub fn harness_safe_load_ptr() { let storage = AtomicPtr::::new(kani::any::() as *mut u8); let _ = storage.load(any_load_order()); @@ -5899,7 +5897,7 @@ mod verify { } #[cfg(target_has_atomic_load_store = "ptr")] - #[kani::proof_for_contract(AtomicPtr::::store)] + #[kani::proof_for_contract(Atomic::<*mut T>::store)] pub fn harness_safe_store_ptr() { let storage = AtomicPtr::::new(kani::any::() as *mut u8); storage.store(kani::any::() as *mut u8, any_store_order()); @@ -5908,7 +5906,7 @@ mod verify { macro_rules! safe_compare_exchange_harness { ($name:ident, $atomic:ty, $value:ty, $method:ident) => { - #[kani::proof_for_contract(<$atomic>::$method)] + #[kani::proof_for_contract(Atomic::<$value>::$method)] pub fn $name() { let storage = <$atomic>::new(kani::any::<$value>()); let _ = storage.$method( @@ -5937,7 +5935,7 @@ mod verify { compare_exchange_weak ); #[cfg(target_has_atomic = "ptr")] - #[kani::proof_for_contract(AtomicPtr::::compare_exchange)] + #[kani::proof_for_contract(Atomic::<*mut T>::compare_exchange)] pub fn harness_safe_compare_exchange_ptr() { let storage = AtomicPtr::::new(kani::any::() as *mut u8); let _ = storage.compare_exchange( @@ -5949,7 +5947,7 @@ mod verify { kani::cover(true, "safe atomic pointer compare-exchange: reached after call"); } #[cfg(target_has_atomic = "ptr")] - #[kani::proof_for_contract(AtomicPtr::::compare_exchange_weak)] + #[kani::proof_for_contract(Atomic::<*mut T>::compare_exchange_weak)] pub fn harness_safe_compare_exchange_weak_ptr() { let storage = AtomicPtr::::new(kani::any::() as *mut u8); let _ = storage.compare_exchange_weak( @@ -6129,98 +6127,160 @@ mod verify { compare_exchange_weak ); + // Callback-taking methods use ordinary proofs: a callback may legally write to + // captured state or other memory, so `modifies(self)` is not a valid general + // contract for these APIs. Keep the former ordering precondition explicit in + // each harness instead. The callbacks below mutate captured state to exercise + // this case; the proofs cover these callbacks, not every possible FnMut. + // As with the other harnesses, this is single-threaded verification. macro_rules! safe_update_harness { - ($name:ident, $atomic:ty, $value:ty, $method:ident, $closure:expr) => { - #[kani::proof_for_contract(<$atomic>::$method)] + ($name:ident, $atomic:ty, $value:ty, $method:ident) => { + #[kani::proof] + #[kani::unwind(2)] pub fn $name() { - let storage = <$atomic>::new(kani::any::<$value>()); - let _ = storage.$method(Relaxed, any_failure_order(), $closure); + let initial: $value = kani::any(); + let storage = <$atomic>::new(initial); + let new: $value = kani::any(); + let should_update: bool = kani::any(); + let set_order = any_ordering(); + let fetch_order = any_ordering(); + kani::assume(matches!(fetch_order, Relaxed | Acquire | SeqCst)); + let mut calls = 0u32; + let result = storage.$method(set_order, fetch_order, |_| { + calls += 1; + if should_update { Some(new) } else { None } + }); + assert!(calls > 0); + assert_eq!(result, if should_update { Ok(initial) } else { Err(initial) }); + assert_eq!(storage.load(Relaxed), if should_update { new } else { initial }); + kani::cover(result.is_ok(), "safe atomic update: Some branch completed"); + kani::cover(result.is_err(), "safe atomic update: None branch completed"); kani::cover(true, "safe atomic update: reached after call"); } }; } #[cfg(target_has_atomic = "8")] - safe_update_harness!(harness_safe_fetch_update_bool, AtomicBool, bool, fetch_update, |_| None); + safe_update_harness!(harness_safe_fetch_update_bool, AtomicBool, bool, fetch_update); #[cfg(target_has_atomic = "8")] - safe_update_harness!(harness_safe_try_update_bool, AtomicBool, bool, try_update, |_| None); + safe_update_harness!(harness_safe_try_update_bool, AtomicBool, bool, try_update); #[cfg(target_has_atomic = "ptr")] - #[kani::proof_for_contract(AtomicPtr::::fetch_update)] + #[kani::proof] + #[kani::unwind(2)] pub fn harness_safe_fetch_update_ptr() { - let storage = AtomicPtr::::new(kani::any::() as *mut u8); - let _ = storage.fetch_update(Relaxed, any_failure_order(), |_| None); + let initial = kani::any::() as *mut u8; + let storage = AtomicPtr::::new(initial); + let new = kani::any::() as *mut u8; + let should_update: bool = kani::any(); + let set_order = any_ordering(); + let fetch_order = any_ordering(); + kani::assume(matches!(fetch_order, Relaxed | Acquire | SeqCst)); + let mut calls = 0u32; + let result = storage.fetch_update(set_order, fetch_order, |_| { + calls += 1; + if should_update { Some(new) } else { None } + }); + assert!(calls > 0); + assert_eq!(result, if should_update { Ok(initial) } else { Err(initial) }); + assert_eq!(storage.load(Relaxed), if should_update { new } else { initial }); + kani::cover(result.is_ok(), "safe pointer fetch-update: Some branch completed"); + kani::cover(result.is_err(), "safe pointer fetch-update: None branch completed"); kani::cover(true, "safe atomic pointer fetch-update: reached after call"); } #[cfg(target_has_atomic = "ptr")] - #[kani::proof_for_contract(AtomicPtr::::try_update)] + #[kani::proof] + #[kani::unwind(2)] pub fn harness_safe_try_update_ptr() { - let storage = AtomicPtr::::new(kani::any::() as *mut u8); - let _ = storage.try_update(Relaxed, any_failure_order(), |_| None); + let initial = kani::any::() as *mut u8; + let storage = AtomicPtr::::new(initial); + let new = kani::any::() as *mut u8; + let should_update: bool = kani::any(); + let set_order = any_ordering(); + let fetch_order = any_ordering(); + kani::assume(matches!(fetch_order, Relaxed | Acquire | SeqCst)); + let mut calls = 0u32; + let result = storage.try_update(set_order, fetch_order, |_| { + calls += 1; + if should_update { Some(new) } else { None } + }); + assert!(calls > 0); + assert_eq!(result, if should_update { Ok(initial) } else { Err(initial) }); + assert_eq!(storage.load(Relaxed), if should_update { new } else { initial }); + kani::cover(result.is_ok(), "safe pointer try-update: Some branch completed"); + kani::cover(result.is_err(), "safe pointer try-update: None branch completed"); kani::cover(true, "safe atomic pointer try-update: reached after call"); } #[cfg(target_has_atomic = "8")] - safe_update_harness!(harness_safe_fetch_update_i8, AtomicI8, i8, fetch_update, |_| None); + safe_update_harness!(harness_safe_fetch_update_i8, AtomicI8, i8, fetch_update); #[cfg(target_has_atomic = "8")] - safe_update_harness!(harness_safe_try_update_i8, AtomicI8, i8, try_update, |_| None); + safe_update_harness!(harness_safe_try_update_i8, AtomicI8, i8, try_update); #[cfg(target_has_atomic = "8")] - safe_update_harness!(harness_safe_fetch_update_u8, AtomicU8, u8, fetch_update, |_| None); + safe_update_harness!(harness_safe_fetch_update_u8, AtomicU8, u8, fetch_update); #[cfg(target_has_atomic = "8")] - safe_update_harness!(harness_safe_try_update_u8, AtomicU8, u8, try_update, |_| None); + safe_update_harness!(harness_safe_try_update_u8, AtomicU8, u8, try_update); #[cfg(target_has_atomic = "16")] - safe_update_harness!(harness_safe_fetch_update_i16, AtomicI16, i16, fetch_update, |_| None); + safe_update_harness!(harness_safe_fetch_update_i16, AtomicI16, i16, fetch_update); #[cfg(target_has_atomic = "16")] - safe_update_harness!(harness_safe_try_update_i16, AtomicI16, i16, try_update, |_| None); + safe_update_harness!(harness_safe_try_update_i16, AtomicI16, i16, try_update); #[cfg(target_has_atomic = "16")] - safe_update_harness!(harness_safe_fetch_update_u16, AtomicU16, u16, fetch_update, |_| None); + safe_update_harness!(harness_safe_fetch_update_u16, AtomicU16, u16, fetch_update); #[cfg(target_has_atomic = "16")] - safe_update_harness!(harness_safe_try_update_u16, AtomicU16, u16, try_update, |_| None); + safe_update_harness!(harness_safe_try_update_u16, AtomicU16, u16, try_update); #[cfg(target_has_atomic = "32")] - safe_update_harness!(harness_safe_fetch_update_i32, AtomicI32, i32, fetch_update, |_| None); + safe_update_harness!(harness_safe_fetch_update_i32, AtomicI32, i32, fetch_update); #[cfg(target_has_atomic = "32")] - safe_update_harness!(harness_safe_try_update_i32, AtomicI32, i32, try_update, |_| None); + safe_update_harness!(harness_safe_try_update_i32, AtomicI32, i32, try_update); #[cfg(target_has_atomic = "32")] - safe_update_harness!(harness_safe_fetch_update_u32, AtomicU32, u32, fetch_update, |_| None); + safe_update_harness!(harness_safe_fetch_update_u32, AtomicU32, u32, fetch_update); #[cfg(target_has_atomic = "32")] - safe_update_harness!(harness_safe_try_update_u32, AtomicU32, u32, try_update, |_| None); + safe_update_harness!(harness_safe_try_update_u32, AtomicU32, u32, try_update); #[cfg(target_has_atomic = "64")] - safe_update_harness!(harness_safe_fetch_update_i64, AtomicI64, i64, fetch_update, |_| None); + safe_update_harness!(harness_safe_fetch_update_i64, AtomicI64, i64, fetch_update); #[cfg(target_has_atomic = "64")] - safe_update_harness!(harness_safe_try_update_i64, AtomicI64, i64, try_update, |_| None); + safe_update_harness!(harness_safe_try_update_i64, AtomicI64, i64, try_update); #[cfg(target_has_atomic = "64")] - safe_update_harness!(harness_safe_fetch_update_u64, AtomicU64, u64, fetch_update, |_| None); + safe_update_harness!(harness_safe_fetch_update_u64, AtomicU64, u64, fetch_update); #[cfg(target_has_atomic = "64")] - safe_update_harness!(harness_safe_try_update_u64, AtomicU64, u64, try_update, |_| None); + safe_update_harness!(harness_safe_try_update_u64, AtomicU64, u64, try_update); #[cfg(target_has_atomic = "128")] - safe_update_harness!(harness_safe_fetch_update_i128, AtomicI128, i128, fetch_update, |_| None); + safe_update_harness!(harness_safe_fetch_update_i128, AtomicI128, i128, fetch_update); #[cfg(target_has_atomic = "128")] - safe_update_harness!(harness_safe_try_update_i128, AtomicI128, i128, try_update, |_| None); + safe_update_harness!(harness_safe_try_update_i128, AtomicI128, i128, try_update); #[cfg(target_has_atomic = "128")] - safe_update_harness!(harness_safe_fetch_update_u128, AtomicU128, u128, fetch_update, |_| None); + safe_update_harness!(harness_safe_fetch_update_u128, AtomicU128, u128, fetch_update); #[cfg(target_has_atomic = "128")] - safe_update_harness!(harness_safe_try_update_u128, AtomicU128, u128, try_update, |_| None); + safe_update_harness!(harness_safe_try_update_u128, AtomicU128, u128, try_update); #[cfg(target_has_atomic = "ptr")] - safe_update_harness!(harness_safe_fetch_update_isize, AtomicIsize, isize, fetch_update, |_| { - None - }); + safe_update_harness!(harness_safe_fetch_update_isize, AtomicIsize, isize, fetch_update); #[cfg(target_has_atomic = "ptr")] - safe_update_harness!(harness_safe_try_update_isize, AtomicIsize, isize, try_update, |_| None); + safe_update_harness!(harness_safe_try_update_isize, AtomicIsize, isize, try_update); #[cfg(target_has_atomic = "ptr")] - safe_update_harness!(harness_safe_fetch_update_usize, AtomicUsize, usize, fetch_update, |_| { - None - }); + safe_update_harness!(harness_safe_fetch_update_usize, AtomicUsize, usize, fetch_update); #[cfg(target_has_atomic = "ptr")] - safe_update_harness!(harness_safe_try_update_usize, AtomicUsize, usize, try_update, |_| None); + safe_update_harness!(harness_safe_try_update_usize, AtomicUsize, usize, try_update); // Kani does not infer a finite bound for this CAS retry loop automatically. // An unwind bound of 2 is sufficient for this single-threaded harness under // Kani's current atomic intrinsic model. macro_rules! safe_update_loop_harness { ($name:ident, $atomic:ty, $value:ty) => { - #[kani::proof_for_contract(<$atomic>::update)] + #[kani::proof] #[kani::unwind(2)] pub fn $name() { - let storage = <$atomic>::new(kani::any::<$value>()); - let _ = storage.update(Relaxed, any_failure_order(), |x| x); + let initial: $value = kani::any(); + let storage = <$atomic>::new(initial); + let new: $value = kani::any(); + let set_order = any_ordering(); + let fetch_order = any_ordering(); + kani::assume(matches!(fetch_order, Relaxed | Acquire | SeqCst)); + let mut calls = 0u32; + let previous = storage.update(set_order, fetch_order, |_| { + calls += 1; + new + }); + assert!(calls > 0); + assert_eq!(previous, initial); + assert_eq!(storage.load(Relaxed), new); kani::cover(true, "safe atomic update: reached after call"); } }; @@ -6252,13 +6312,24 @@ mod verify { #[cfg(target_has_atomic = "ptr")] safe_update_loop_harness!(harness_safe_update_usize, AtomicUsize, usize); - #[cfg(all(target_has_atomic_load_store = "ptr", target_has_atomic = "8"))] - #[kani::proof_for_contract(AtomicPtr::::update)] + #[cfg(target_has_atomic = "ptr")] + #[kani::proof] #[kani::unwind(2)] pub fn harness_safe_update_ptr() { - let storage = AtomicPtr::::new(kani::any::() as *mut u8); - let value = kani::any::() as *mut u8; - let _ = storage.update(Relaxed, any_failure_order(), |_| value); + let initial = kani::any::() as *mut u8; + let storage = AtomicPtr::::new(initial); + let new = kani::any::() as *mut u8; + let set_order = any_ordering(); + let fetch_order = any_ordering(); + kani::assume(matches!(fetch_order, Relaxed | Acquire | SeqCst)); + let mut calls = 0u32; + let previous = storage.update(set_order, fetch_order, |_| { + calls += 1; + new + }); + assert!(calls > 0); + assert_eq!(previous, initial); + assert_eq!(storage.load(Relaxed), new); kani::cover(true, "safe atomic pointer update: reached after call"); } From 6e0614100b7369709c6e14dec0ad2bf257f6c2d7 Mon Sep 17 00:00:00 2001 From: v3risec Date: Fri, 4 Dec 2026 22:05:24 +0800 Subject: [PATCH 4/5] Add VeriFast concurrency proof and Kani updates for Challenge 7 atomics Complete Challenge 7 (Atomic types and intrinsics) verification: - Keep Kani contracts/harnesses in library/core with zero production body changes. - Add zero-Python VeriFast companion proof and negative suite under verifast-proofs/core/sync/atomic.rs{,-negative} wired into the existing check-verifast-proofs{,-negative}.sh entrypoints (no workflow or shared Kani script edits). - Cover all 12 Part 1 constructors, 14 Part 2 helpers + optional panics, 91 Part 3 intrinsic/ordering entries (810 x86-64 / 972 AArch64 integer permissions, 25 pointer RMW edges), writable and read-only fractional atomic borrows, 5 linked/executed POSIX two-worker clients, and 362 expected negative rejections. - Document upstream EMULATE_ATOMIC_BOOL data-race bug rust-lang/rust#166918 with standalone Miri reproducer. --- library/core/src/intrinsics/mod.rs | 22 +- library/core/src/sync/atomic.rs | 117 + verifast-proofs/README.md | 7 +- .../check-verifast-proofs-negative.sh | 2 + verifast-proofs/check-verifast-proofs.sh | 2 + .../core/sync/atomic.rs-negative/verify.sh | 1588 ++++ verifast-proofs/core/sync/atomic.rs/README.md | 173 + .../core/sync/atomic.rs/TRUSTED-BASE.md | 115 + .../core/sync/atomic.rs/build-linux-tools.sh | 122 + .../core/sync/atomic.rs/check-sources.sh | 11 + .../core/sync/atomic.rs/checks/bool-access.rs | 67 + .../core/sync/atomic.rs/checks/bool-rmw.rs | 89 + .../sync/atomic.rs/checks/bool-storage.gh | 45 + .../core/sync/atomic.rs/checks/bool-swap.awk | 28 + .../core/sync/atomic.rs/checks/bool.rs | 57 + .../atomic.rs/checks/bool_cas_byte_client.rs | 61 + .../core/sync/atomic.rs/checks/check_mir.rs | 5265 +++++++++++++ .../core/sync/atomic.rs/checks/common.sh | 508 ++ .../sync/atomic.rs/checks/integer-storage.gh | 152 + .../atomic.rs/checks/integer_cas_client.rs | 53 + .../atomic.rs/checks/integer_rmw_client.rs | 61 + .../atomic.rs/checks/integer_swap_client.rs | 41 + .../checks/kani-negative-ordering.sh | 285 + .../core/sync/atomic.rs/checks/layout.rs | 44 + .../core/sync/atomic.rs/checks/owned-u32.rs | 75 + .../sync/atomic.rs/checks/pointer-access.rs | 208 + .../core/sync/atomic.rs/checks/pointer-rmw.rs | 50 + .../sync/atomic.rs/checks/pointer-shape.rs | 8 + .../sync/atomic.rs/checks/pointer-view.rs | 114 + .../core/sync/atomic.rs/checks/ranges.rs | 136 + .../core/sync/atomic.rs/checks/readonly.rs | 390 + .../core/sync/atomic.rs/checks/storage.rs | 335 + .../sync/atomic.rs/checks/threads/boolean.rs | 193 + .../sync/atomic.rs/checks/threads/pointer.rs | 166 + .../sync/atomic.rs/checks/threads/readonly.rs | 409 + .../sync/atomic.rs/checks/threads/runtime.rs | 32 + .../core/sync/atomic.rs/checks/threads/u32.rs | 322 + .../sync/atomic.rs/checks/threads/width.rs | 219 + .../core/sync/atomic.rs/checks/u32.rs | 200 + .../checks/upstream_bug_166918_miri.rs | 42 + .../core/sync/atomic.rs/checks/width.rs | 194 + .../sync/atomic.rs/intrinsic-manifest.tsv | 92 + .../core/sync/atomic.rs/original/atomic.rs | 6556 +++++++++++++++++ .../original/atomic_load_volatile.md | 30 + .../original/atomic_store_volatile.md | 29 + .../sync/atomic.rs/original/intrinsics/mod.rs | 5712 ++++++++++++++ .../core/sync/atomic.rs/original/lib.rs | 430 ++ .../core/sync/atomic.rs/part1-manifest.tsv | 13 + .../sync/atomic.rs/permission-inventory.tsv | 92 + .../core/sync/atomic.rs/platform.Cargo.lock | 16 + .../core/sync/atomic.rs/specs/access.diff | 342 + .../core/sync/atomic.rs/specs/borrow.diff | 170 + .../core/sync/atomic.rs/specs/i128.diff | 15 + .../sync/atomic.rs/specs/integer-storage.diff | 94 + .../core/sync/atomic.rs/specs/panic.diff | 24 + .../sync/atomic.rs/specs/pointer-access.diff | 314 + .../sync/atomic.rs/specs/pointer-rmw.diff | 269 + .../sync/atomic.rs/specs/pointer-slot.diff | 135 + .../core/sync/atomic.rs/specs/readonly.diff | 508 ++ .../core/sync/atomic.rs/specs/rmw.diff | 759 ++ .../core/sync/atomic.rs/specs/u32.diff | 581 ++ .../core/sync/atomic.rs/specs/widths.diff | 47 + .../sync/atomic.rs/tool-tests/auto_traits.rs | 84 + .../core/sync/atomic.rs/tool-tests/drop.rs | 33 + .../tool-tests/external_array_client.rs | 13 + .../tool-tests/external_assoc_const.rs | 14 + .../atomic.rs/tool-tests/external_layout.rs | 55 + .../tool-tests/external_layout.rsspec | 6 + .../tool-tests/external_layout_client.rs | 69 + .../tool-tests/generic_projection.rs | 34 + .../atomic.rs/tool-tests/macro_expansion.rs | 22 + .../sync/atomic.rs/tool-tests/ordering.rs | 25 + .../atomic.rs/tool-tests/pointer_client.rs | 12 + .../sync/atomic.rs/tool-tests/pointer_lib.rs | 16 + .../tool-tests/projection_recursion.rs | 23 + .../sync/atomic.rs/tool-tests/projections.rs | 319 + .../atomic.rs/tool-tests/source_tokens.rs | 47 + .../atomic.rs/tool-tests/trait_dispatch.rs | 21 + .../tool-tests/wide_pointer_comparison.rs | 29 + verifast-proofs/core/sync/atomic.rs/update.sh | 241 + .../core/sync/atomic.rs/verifast-core.patch | 1925 +++++ verifast-proofs/core/sync/atomic.rs/verify.sh | 217 + 82 files changed, 31436 insertions(+), 5 deletions(-) create mode 100755 verifast-proofs/core/sync/atomic.rs-negative/verify.sh create mode 100644 verifast-proofs/core/sync/atomic.rs/README.md create mode 100644 verifast-proofs/core/sync/atomic.rs/TRUSTED-BASE.md create mode 100755 verifast-proofs/core/sync/atomic.rs/build-linux-tools.sh create mode 100755 verifast-proofs/core/sync/atomic.rs/check-sources.sh create mode 100644 verifast-proofs/core/sync/atomic.rs/checks/bool-access.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/checks/bool-rmw.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/checks/bool-storage.gh create mode 100644 verifast-proofs/core/sync/atomic.rs/checks/bool-swap.awk create mode 100644 verifast-proofs/core/sync/atomic.rs/checks/bool.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/checks/bool_cas_byte_client.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/checks/check_mir.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/checks/common.sh create mode 100644 verifast-proofs/core/sync/atomic.rs/checks/integer-storage.gh create mode 100644 verifast-proofs/core/sync/atomic.rs/checks/integer_cas_client.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/checks/integer_rmw_client.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/checks/integer_swap_client.rs create mode 100755 verifast-proofs/core/sync/atomic.rs/checks/kani-negative-ordering.sh create mode 100644 verifast-proofs/core/sync/atomic.rs/checks/layout.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/checks/owned-u32.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/checks/pointer-access.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/checks/pointer-rmw.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/checks/pointer-shape.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/checks/pointer-view.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/checks/ranges.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/checks/readonly.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/checks/storage.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/checks/threads/boolean.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/checks/threads/pointer.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/checks/threads/readonly.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/checks/threads/runtime.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/checks/threads/u32.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/checks/threads/width.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/checks/u32.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/checks/upstream_bug_166918_miri.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/checks/width.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/intrinsic-manifest.tsv create mode 100644 verifast-proofs/core/sync/atomic.rs/original/atomic.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/original/atomic_load_volatile.md create mode 100644 verifast-proofs/core/sync/atomic.rs/original/atomic_store_volatile.md create mode 100644 verifast-proofs/core/sync/atomic.rs/original/intrinsics/mod.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/original/lib.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/part1-manifest.tsv create mode 100644 verifast-proofs/core/sync/atomic.rs/permission-inventory.tsv create mode 100644 verifast-proofs/core/sync/atomic.rs/platform.Cargo.lock create mode 100644 verifast-proofs/core/sync/atomic.rs/specs/access.diff create mode 100644 verifast-proofs/core/sync/atomic.rs/specs/borrow.diff create mode 100644 verifast-proofs/core/sync/atomic.rs/specs/i128.diff create mode 100644 verifast-proofs/core/sync/atomic.rs/specs/integer-storage.diff create mode 100644 verifast-proofs/core/sync/atomic.rs/specs/panic.diff create mode 100644 verifast-proofs/core/sync/atomic.rs/specs/pointer-access.diff create mode 100644 verifast-proofs/core/sync/atomic.rs/specs/pointer-rmw.diff create mode 100644 verifast-proofs/core/sync/atomic.rs/specs/pointer-slot.diff create mode 100644 verifast-proofs/core/sync/atomic.rs/specs/readonly.diff create mode 100644 verifast-proofs/core/sync/atomic.rs/specs/rmw.diff create mode 100644 verifast-proofs/core/sync/atomic.rs/specs/u32.diff create mode 100644 verifast-proofs/core/sync/atomic.rs/specs/widths.diff create mode 100644 verifast-proofs/core/sync/atomic.rs/tool-tests/auto_traits.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/tool-tests/drop.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/tool-tests/external_array_client.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/tool-tests/external_assoc_const.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/tool-tests/external_layout.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/tool-tests/external_layout.rsspec create mode 100644 verifast-proofs/core/sync/atomic.rs/tool-tests/external_layout_client.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/tool-tests/generic_projection.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/tool-tests/macro_expansion.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/tool-tests/ordering.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/tool-tests/pointer_client.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/tool-tests/pointer_lib.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/tool-tests/projection_recursion.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/tool-tests/projections.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/tool-tests/source_tokens.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/tool-tests/trait_dispatch.rs create mode 100644 verifast-proofs/core/sync/atomic.rs/tool-tests/wide_pointer_comparison.rs create mode 100755 verifast-proofs/core/sync/atomic.rs/update.sh create mode 100644 verifast-proofs/core/sync/atomic.rs/verifast-core.patch create mode 100755 verifast-proofs/core/sync/atomic.rs/verify.sh diff --git a/library/core/src/intrinsics/mod.rs b/library/core/src/intrinsics/mod.rs index 17e3993ae4d38..f74fd9e2c1fec 100644 --- a/library/core/src/intrinsics/mod.rs +++ b/library/core/src/intrinsics/mod.rs @@ -5089,8 +5089,9 @@ mod verify { // `rustc_intrinsic` declarations (model-checking/kani#3345). These wrappers // are the Kani-facing specifications for the const-generic intrinsics above. // The harness instantiations follow the integer and pointer restrictions in - // the intrinsic documentation, while the contracts encode only the local - // memory obligations required by the intrinsic calls. + // the intrinsic documentation, while the contracts encode the local memory + // obligations and valid `AtomicOrdering` constraints required by the + // intrinsic calls. // // `can_dereference` and `can_write` express local memory requirements for `T`. // Checking initialization through `can_dereference` requires `-Z uninit-checks`. @@ -5101,12 +5102,24 @@ mod verify { #[allow(dead_code)] #[kani::modifies(dst)] + #[requires( + ORD == AtomicOrdering::Relaxed + || ORD == AtomicOrdering::Release + || ORD == AtomicOrdering::SeqCst + )] #[requires(crate::ub_checks::can_write(dst))] unsafe fn atomic_store_wrapper(dst: *mut T, val: T) { unsafe { atomic_store::(dst, val) } } #[allow(dead_code)] + #[requires( + ORD == AtomicOrdering::Relaxed + || ORD == AtomicOrdering::Acquire + || ORD == AtomicOrdering::SeqCst + )] + #[requires((ORD == AtomicOrdering::Relaxed && crate::sync::atomic::small_read_only_atomic_load::()) + || crate::ub_checks::can_write(src as *mut T))] #[requires(crate::ub_checks::can_dereference(src))] unsafe fn atomic_load_wrapper(src: *const T) -> T { unsafe { atomic_load::(src) } @@ -5163,6 +5176,11 @@ mod verify { ($wrapper:ident, $intrinsic:ident) => { #[allow(dead_code)] #[kani::modifies(dst)] + #[requires( + ORD_FAIL == AtomicOrdering::Relaxed + || ORD_FAIL == AtomicOrdering::Acquire + || ORD_FAIL == AtomicOrdering::SeqCst + )] #[requires(crate::ub_checks::can_dereference(dst as *const T))] #[requires(crate::ub_checks::can_write(dst))] unsafe fn $wrapper< diff --git a/library/core/src/sync/atomic.rs b/library/core/src/sync/atomic.rs index bd85b7236bae8..83042919c1aac 100644 --- a/library/core/src/sync/atomic.rs +++ b/library/core/src/sync/atomic.rs @@ -4391,6 +4391,8 @@ const unsafe fn atomic_store(dst: *mut T, val: T, #[inline] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] +// Kani models writable object bounds and alignment. Page protections belong to the OS. +#[requires((order == Relaxed && small_read_only_atomic_load::()) || ub_checks::can_write(dst as *mut T))] #[requires(ub_checks::can_dereference(dst))] #[requires(order == Relaxed || order == Acquire || order == SeqCst)] #[ensures(|_| ub_checks::can_dereference(dst))] @@ -5101,6 +5103,20 @@ pub fn spin_loop_hint() { spin_loop() } +// The module's read-only memory guarantee applies only to these small Relaxed loads. +#[cfg(kani)] +pub(crate) const fn small_read_only_atomic_load() -> bool { + (crate::mem::size_of::() <= 8 && cfg!(any( + target_arch = "x86_64", target_arch = "aarch64", target_arch = "loongarch64", + target_arch = "mips64", target_arch = "mips64r6", target_arch = "powerpc64", + target_arch = "riscv64", target_arch = "sparc64", target_arch = "s390x", + ))) || (crate::mem::size_of::() <= 4 && cfg!(any( + target_arch = "x86", target_arch = "arm", target_arch = "loongarch32", + target_arch = "mips", target_arch = "mips32r6", target_arch = "powerpc", + target_arch = "riscv32", target_arch = "sparc", target_arch = "hexagon", + ))) +} + #[cfg(kani)] #[unstable(feature = "kani", issue = "none")] mod verify { @@ -5178,6 +5194,10 @@ mod verify { from_ptr_harness!(harness_atomic_i128_from_ptr, AtomicI128, i128); #[cfg(target_has_atomic_load_store = "128")] from_ptr_harness!(harness_atomic_u128_from_ptr, AtomicU128, u128); + #[cfg(target_has_atomic_load_store = "ptr")] + from_ptr_harness!(harness_atomic_isize_from_ptr, AtomicIsize, isize); + #[cfg(target_has_atomic_load_store = "ptr")] + from_ptr_harness!(harness_atomic_usize_from_ptr, AtomicUsize, usize); // Harnesses for AtomicPtr::from_ptr. // Kani matches this selector against the generic impl's definition path. @@ -5842,6 +5862,103 @@ mod verify { any_load_order() } + // Check the frame of each public method carrying a modifies(self) contract. + macro_rules! rmw_contract { + ($target:ty, $method:ident, $initial:expr $(, $arg:expr)*) => { + #[allow(deprecated)] + #[kani::proof_for_contract(Atomic::<$target>::$method)] + pub fn $method() { + let cell = $initial; + let _ = cell.$method($($arg,)* any_ordering()); + kani::cover(true, "atomic operation returned"); + } + }; + } + + macro_rules! integer_rmw_contracts { + ($module:ident, $value:ty) => { + mod $module { + use super::*; + + fn cell() -> Atomic<$value> { + Atomic::<$value>::new(kani::any()) + } + + rmw_contract!($value, compare_and_swap, cell(), kani::any(), kani::any()); + rmw_contract!($value, swap, cell(), kani::any()); + rmw_contract!($value, fetch_add, cell(), kani::any()); + rmw_contract!($value, fetch_sub, cell(), kani::any()); + rmw_contract!($value, fetch_and, cell(), kani::any()); + rmw_contract!($value, fetch_nand, cell(), kani::any()); + rmw_contract!($value, fetch_or, cell(), kani::any()); + rmw_contract!($value, fetch_xor, cell(), kani::any()); + rmw_contract!($value, fetch_max, cell(), kani::any()); + rmw_contract!($value, fetch_min, cell(), kani::any()); + } + }; + } + + #[cfg(target_has_atomic = "8")] + integer_rmw_contracts!(rmw_i8, i8); + #[cfg(target_has_atomic = "8")] + integer_rmw_contracts!(rmw_u8, u8); + #[cfg(target_has_atomic = "16")] + integer_rmw_contracts!(rmw_i16, i16); + #[cfg(target_has_atomic = "16")] + integer_rmw_contracts!(rmw_u16, u16); + #[cfg(target_has_atomic = "32")] + integer_rmw_contracts!(rmw_i32, i32); + #[cfg(target_has_atomic = "32")] + integer_rmw_contracts!(rmw_u32, u32); + #[cfg(target_has_atomic = "64")] + integer_rmw_contracts!(rmw_i64, i64); + #[cfg(target_has_atomic = "64")] + integer_rmw_contracts!(rmw_u64, u64); + #[cfg(target_has_atomic = "128")] + integer_rmw_contracts!(rmw_i128, i128); + #[cfg(target_has_atomic = "128")] + integer_rmw_contracts!(rmw_u128, u128); + #[cfg(target_has_atomic = "ptr")] + integer_rmw_contracts!(rmw_isize, isize); + #[cfg(target_has_atomic = "ptr")] + integer_rmw_contracts!(rmw_usize, usize); + + #[cfg(target_has_atomic = "8")] + mod rmw_bool { + use super::*; + + fn cell() -> AtomicBool { + AtomicBool::new(kani::any()) + } + + rmw_contract!(bool, compare_and_swap, cell(), kani::any(), kani::any()); + rmw_contract!(bool, swap, cell(), kani::any()); + rmw_contract!(bool, fetch_and, cell(), kani::any()); + rmw_contract!(bool, fetch_or, cell(), kani::any()); + rmw_contract!(bool, fetch_xor, cell(), kani::any()); + rmw_contract!(bool, fetch_nand, cell(), kani::any()); + rmw_contract!(bool, fetch_not, cell()); + } + + #[cfg(target_has_atomic = "ptr")] + mod rmw_ptr { + use super::*; + + fn pointer() -> *mut u8 { + kani::any::() as *mut u8 + } + + fn cell() -> AtomicPtr { + AtomicPtr::new(pointer()) + } + + rmw_contract!(*mut T, compare_and_swap, cell(), pointer(), pointer()); + rmw_contract!(*mut T, swap, cell(), pointer()); + rmw_contract!(*mut T, fetch_and, cell(), kani::any()); + rmw_contract!(*mut T, fetch_or, cell(), kani::any()); + rmw_contract!(*mut T, fetch_xor, cell(), kani::any()); + } + // Harnesses for load and store methods of atomic types, with safe abstractions. macro_rules! safe_load_store_harness { ($load_name:ident, $store_name:ident, $atomic:ty, $value:ty) => { diff --git a/verifast-proofs/README.md b/verifast-proofs/README.md index 096d3e32e9061..5310a6377ac54 100644 --- a/verifast-proofs/README.md +++ b/verifast-proofs/README.md @@ -6,12 +6,13 @@ Specifically, it currently contains the following proofs: - Partial proof of [LinkedList](alloc/collections/linked_list.rs/) - Partial proof of [RawVec](alloc/raw_vec/mod.rs/) +- Challenge 7 [atomic storage, operations, and concurrent clients](core/sync/atomic.rs/) See each proof's accompanying README for a tour of the proof and applicable caveats. ## Maintaining the proofs - If the VeriFast CI action fails because of a failing diff, please run `cd verifast-proofs; ./patch-verifast-proofs.sh` to fix the problem. +For a LinkedList or RawVec snapshot mismatch, run `bash verifast-proofs/patch-verifast-proofs.sh` from the repository root. For atomic sources, run `bash verifast-proofs/core/sync/atomic.rs/update.sh` and review the annotation diffs against the new sources. ## `-skip_specless_fns` @@ -23,7 +24,7 @@ To verify a function in a file library/crate/src/mod/file 1. Copy that file to verifast-proofs/crate/mod/file.rs/original/file.rs as well as to verifast-proofs/crate/mod/file.rs/verified/file.rs. 2. Create a file verifast-proofs/crate/mod/file.rs/original/lib.rs to serve as crate root for verification, and include mod file;. (See the existing proofs for examples.) Copy it to verifast-proofs/crate/mod/file.rs/verified/lib.rs. 2. Add a VeriFast specification to the function(s) you want to verify, and any other VeriFast annotations to make the proof go through, in verifast-proofs/crate/mod/file.rs/verified/file.rs. While doing so, you will need to change the code slightly so as to be able to insert ghost commands in the correct places. -3. Add commands for checking your proof to `verifast-proofs/check-verifast-proofs.mysh`. This includes the following: +3. Add commands for checking your proof to `verifast-proofs/check-verifast-proofs.sh`. This includes the following: 1. A `verifast` invocation for checking the VeriFast proof. 2. A `refinement-checker` invocation for checking that the code changes you made in the verified version do not change the meaning of the program. Specifically, this tool checks that the original code *refines* the verified code, i.e. that each behavior of a function in the original version is also a behavior of the corresponding function in the verified version. As a result, if the verified version has been verified to have no bad behaviors, the original version also has no bad behaviors. 3. A `diff` invocation for checking that the version in `original` is identical to the original version in `library`. @@ -56,4 +57,4 @@ We then: Separating steps 2) and 3) lets us distinguish between CI failures caused by incorrect modifications to the verified files (failure in step 2) versus a proof that was once correct, but is just out of date (failure in step 3). Without the copy of the original file, when the `library/` files change, there would be no easy way to tell whether the VeriFast proofs are wrong or just stale. -The [VeriFast](../.github/workflows/verifast.yml) GitHub action will run `verifast-proofs/check-verifast-proofs.mysh`. Check that file to see which version of VeriFast is used. +The [VeriFast](../.github/workflows/verifast.yml) GitHub action will run `verifast-proofs/check-verifast-proofs.sh`. Check that file to see which version of VeriFast is used. diff --git a/verifast-proofs/check-verifast-proofs-negative.sh b/verifast-proofs/check-verifast-proofs-negative.sh index 89fa996463136..4a5cd3091cc30 100755 --- a/verifast-proofs/check-verifast-proofs-negative.sh +++ b/verifast-proofs/check-verifast-proofs-negative.sh @@ -12,3 +12,5 @@ cd alloc cd .. cd .. cd .. + +bash core/sync/atomic.rs-negative/verify.sh diff --git a/verifast-proofs/check-verifast-proofs.sh b/verifast-proofs/check-verifast-proofs.sh index 23bd82948efbd..27e5c8806dbdd 100755 --- a/verifast-proofs/check-verifast-proofs.sh +++ b/verifast-proofs/check-verifast-proofs.sh @@ -18,3 +18,5 @@ cd alloc cd .. cd .. cd .. + +bash core/sync/atomic.rs/verify.sh diff --git a/verifast-proofs/core/sync/atomic.rs-negative/verify.sh b/verifast-proofs/core/sync/atomic.rs-negative/verify.sh new file mode 100755 index 0000000000000..27c668b99281e --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs-negative/verify.sh @@ -0,0 +1,1588 @@ +#!/usr/bin/env bash +set -euo pipefail + +here=$(cd "$(dirname "$0")/../atomic.rs" && pwd) +bash "$here/check-sources.sh" +tools=$(bash "$here/build-linux-tools.sh") +export LD_LIBRARY_PATH="$tools/bin${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" +work=$(mktemp -d) +trap 'rm -rf -- "$work"' EXIT +export CARGO_BUILD_JOBS=1 CARGO_INCREMENTAL=0 RAYON_NUM_THREADS=1 MALLOC_ARENA_MAX=2 +ulimit -S -v 8388608 + +# shellcheck source=../atomic.rs/checks/common.sh +source "$here/checks/common.sh" +init_env "$here" "$tools" "$work" + +"$CHECK_MIR" patch-audit "$PROOF/verifast-core.patch" "$PROOF/TRUSTED-BASE.md" + +PROJ_ERR="Unsupported associated-type projection: " +ERASED_ERR="Unsupported erased Rust type in projection or generic substitution" + +run_negative_tool_tests() { + local folder="$PROOF/tool-tests" + local root_file="$WORK/diff-roots.txt" + local target export flags model native + + for target in "$HOST" "$ARM"; do + model="(target: $target (LP64))" + local layout_rlib="$WORK/liblayout_provider-${target}.rlib" + local direct_rlib="$WORK/libdirect_assoc-${target}.rlib" + run_expect "compile $target external layout provider" 0 0 -- \ + rustc "$TC" --edition=2024 "--target=$target" --crate-name=layout_provider \ + --crate-type=rlib "$folder/external_layout.rs" -o "$layout_rlib" + run_expect "compile $target direct associated constant" 0 0 -- \ + rustc "$TC" --edition=2024 "--target=$target" --crate-name=layout_provider \ + --crate-type=rlib "$folder/external_assoc_const.rs" -o "$direct_rlib" + + for export in normal scoped; do + flags="--edition=2024 --target=$target" + if [[ $export == scoped ]]; then + flags+=" --vf-rust-mir-exporter:roots=$root_file" + fi + native=0 + if [[ $target == "$HOST" && $export == normal ]]; then native=1; fi + + # 1. Consolidated local user-trait projections (projections.rs) + local proj="$folder/projections.rs" + printf 'case::client\n' > "$root_file" + for item in "case_slot:Kind::Storage" "case_nested_trait:case::NestedKind::Storage"; do + local cfg=${item%%:*} diag=${item#*:} + run_expect "projections $cfg $target $export rejects result == 4" 1 1 "${PROJ_ERR}${diag}" -- \ + "${VF_BASE[@]}" -rustc_args "$flags" -rustc_arg "--cfg=$cfg" "$proj" + if [[ $native -eq 1 ]]; then + run_expect "compile projections $cfg counterexample" 0 0 -- \ + rustc "$TC" --edition=2024 --test "--cfg=$cfg" "$proj" -o "$WORK/proj-test" + run_expect "native projections $cfg returns 1" 0 1 "1 passed" -- "$WORK/proj-test" + fi + done + + for item in \ + "case_field::direct" \ + "case_body::direct" \ + "case_body:two_hop:two-hop" \ + "case_param::direct" \ + "case_mapped::direct" \ + "case_mapped:two_hop:two-hop" + do + IFS=: read -r cfg sub label_kind <<< "$item" + if [[ $cfg == case_body ]]; then + printf 'case::client\ncase::outer\n' > "$root_file" + else + printf 'case::client\n' > "$root_file" + fi + local extra_vf=() extra_rc=() + if [[ -n $sub ]]; then + extra_vf=(-rustc_arg "--cfg=$sub") + extra_rc=("--cfg=$sub") + fi + run_expect "projections $cfg $target $export rejects $label_kind tail projection" 1 1 "${PROJ_ERR}Kind::Storage" -- \ + "${VF_BASE[@]}" -rustc_args "$flags" -rustc_arg "--cfg=$cfg" "${extra_vf[@]}" "$proj" + if [[ $native -eq 1 ]]; then + run_expect "compile projections $cfg $label_kind" 0 0 -- \ + rustc "$TC" --edition=2024 --test "--cfg=$cfg" "${extra_rc[@]}" "$proj" -o "$WORK/proj-offsets" + run_expect "native projections $cfg $label_kind has offsets 1 and 4" 0 1 "1 passed" -- "$WORK/proj-offsets" + elif [[ $target != "$HOST" && $export == normal ]]; then + run_expect "rustc $target checks projections $cfg $label_kind offsets 1 and 4" 0 0 -- \ + rustc "$TC" --edition=2024 "--target=$target" --test --emit=metadata \ + "--cfg=$cfg" "${extra_rc[@]}" "$proj" -o "$WORK/proj-offsets.rmeta" + fi + done + + printf 'case::client\n' > "$root_file" + run_expect "projections case_field_sync $target $export rejects direct fields" 1 1 "${PROJ_ERR}Kind::Storage" -- \ + "${VF_BASE[@]}" -rustc_args "$flags" -rustc_arg "--cfg=case_field_sync" "$proj" + run_expect "projections case_field_sync $target $export rejects nested fields" 1 1 "${PROJ_ERR}Kind::Storage" -- \ + "${VF_BASE[@]}" -rustc_args "$flags" -rustc_arg "--cfg=case_field_sync" -rustc_arg "--cfg=nested" "$proj" + if [[ $export == normal ]]; then + run_expect "rustc $target accepts Sync for projected u8" 0 0 -- \ + rustc "$TC" --edition=2024 "--target=$target" --test --emit=metadata \ + --cfg=case_field_sync "$proj" -o "$WORK/proj-sync.rmeta" + run_expect "rustc $target rejects Sync for projected UnsafeCell" 1 3 \ + "error[E0277]" "UnsafeCell" "require_sync::>()" -- \ + rustc "$TC" --edition=2024 "--target=$target" --test --emit=metadata \ + --cfg=case_field_sync --cfg=bad_sync "$proj" -o "$WORK/proj-sync.rmeta" + fi + + run_expect "projections case_const $target $export rejects const projection registration" 1 1 "${PROJ_ERR}case::ConstKind::Output" -- \ + "${VF_BASE[@]}" -rustc_args "$flags" -rustc_arg "--cfg=case_const" "$proj" + run_expect "projections case_const $target $export rejects projection in MIR constant" 1 1 "${PROJ_ERR}case::ConstKind::Output" -- \ + "${VF_BASE[@]}" -rustc_args "$flags" -rustc_arg "--cfg=case_const" -rustc_arg "--cfg=mir_operand" "$proj" + + # 2. External layout, foreign fake-core projections, AliasTyKind & ConstKind controls + local ext_client="$folder/external_layout_client.rs" + local ext_array="$folder/external_array_client.rs" + printf 'client\n' > "$root_file" + run_expect "external_array_client $target $export plain [u8; N]" 0 3 \ + "0 errors found" "$model" "Verifying function 'client'" -- \ + "${VF_BASE[@]}" -rustc_args "$flags" \ + -extern_spec "layout_provider=$folder/external_layout.rsspec" \ + -rustc_arg "--extern=layout_provider=$layout_rlib" "$ext_array" + run_expect "external_array_client $target $export rejects opaque return type" 1 1 \ + "Unsupported type alias in MIR export: impl core::marker::Copy" -- \ + "${VF_BASE[@]}" -rustc_args "$flags" \ + -extern_spec "layout_provider=$folder/external_layout.rsspec" \ + -rustc_arg "--extern=layout_provider=$layout_rlib" -rustc_arg "--cfg=opaque_result" "$ext_array" + + printf 'foreign::client\n' > "$root_file" + for carrier in ext_field ext_bound ext_inherited; do + run_expect "external_layout_client $target $export rejects $carrier" 1 2 \ + "$PROJ_ERR" "ptr::metadata::Pointee::Metadata" -- \ + "${VF_BASE[@]}" -rustc_args "$flags" \ + -rustc_arg "--extern=layout_provider=$layout_rlib" -rustc_arg "--cfg=$carrier" "$ext_client" + done + run_expect "external_layout_client $target $export rejects ext_erased" 1 2 \ + "$ERASED_ERR" "UnsafeCell" -- \ + "${VF_BASE[@]}" -rustc_args "$flags" \ + -rustc_arg "--extern=layout_provider=$layout_rlib" -rustc_arg "--cfg=ext_erased" "$ext_client" + + printf 'layout_case::client\n' > "$root_file" + local alias_err="Unsupported type alias in MIR export: layout_provider::" + local const_err="Unsupported constant in MIR export:" + for spec_case in \ + "inherent|${alias_err}Bridge<|>::Repr" \ + "opaque|${alias_err}Hidden<|Hidden<" \ + "width|${const_err}|Width::{constant#" \ + "associated|${const_err}|Associated::{constant#" \ + "direct|${const_err}|as layout_provider::Kind>::N" \ + "fixed|Unsupported anonymous constant body in MIR export:|Fixed::0::{constant#" + do + IFS='|' read -r ccase m1 m2 <<< "$spec_case" + local ext_rlib="$layout_rlib" + if [[ $ccase == direct ]]; then ext_rlib="$direct_rlib"; fi + run_expect "external_layout_client $target $export rejects $ccase" 1 2 "$m1" "$m2" -- \ + "${VF_BASE[@]}" -rustc_args "$flags" \ + -extern_spec "layout_provider=$folder/external_layout.rsspec" \ + -rustc_arg "--extern=layout_provider=$ext_rlib" -rustc_arg "--cfg=$ccase" "$ext_client" + if [[ $export == normal ]]; then + local offsets="1 and 4" eq="false" + if [[ $ccase == fixed ]]; then offsets="1 and 1"; eq="true"; fi + if [[ $native -eq 1 ]]; then + run_expect "rustc $target $ccase offsets $offsets" 0 0 -- \ + rustc "$TC" --edition=2024 --test "--target=$target" \ + "--extern=layout_provider=$ext_rlib" "--cfg=$ccase" "$ext_client" -o "$WORK/ext-layout" + run_expect "native $ccase tail equality is $eq" 0 2 "compare_tails ... ok" "1 passed" -- \ + "$WORK/ext-layout" + else + run_expect "rustc $target $ccase offsets $offsets" 0 0 -- \ + rustc "$TC" --edition=2024 --test "--target=$target" \ + "--extern=layout_provider=$ext_rlib" "--cfg=$ccase" "$ext_client" \ + --emit=metadata -o "$WORK/ext-layout.rmeta" + fi + fi + done + + # 3. projection_recursion.rs (Atomic<*const T> rejected by rustc) + printf 'round_trip\n' > "$root_file" + run_expect "projection_recursion $target $export" 0 3 \ + "0 errors found" "$model" "Verifying function 'round_trip'" -- \ + "${VF_BASE[@]}" -rustc_args "$flags" "$folder/projection_recursion.rs" + if [[ $export == normal ]]; then + local mut_rec="$WORK/projection_recursion.rs" + sed 's/Atomic<\*mut T>/Atomic<*const T>/g' "$folder/projection_recursion.rs" > "$mut_rec" + run_expect "rustc $target rejects Atomic<*const T>" 1 3 \ + "error[E0277]" "AtomicPrimitive" "*const T" -- \ + rustc "$TC" --edition=2024 "--target=$target" --crate-type=lib --emit=metadata \ + -o "$WORK/atomic-const.rmeta" "$mut_rec" + fi + + # 4. generic_projection.rs (erased types, metadata bounds, callsite ghost overrides) + printf 'projection_client\nborrow_bytes\n' > "$root_file" + run_expect "generic_projection $target $export" 0 4 \ + "0 errors found" "$model" "Verifying function 'projection_client'" "Verifying function 'borrow_bytes'" -- \ + "${VF_BASE[@]}" -rustc_args "$flags" "$folder/generic_projection.rs" + local mut_gen="$WORK/generic_projection.rs" + cp "$folder/generic_projection.rs" "$mut_gen" + replace_one "$mut_gen" "ens result == 1;" "ens result == 4;" + run_expect "generic_projection $target $export rejects wrong generic result" 1 3 \ + "Verifying function 'projection_client'" "error: Cannot prove" "ens result == 4;" -- \ + "${VF_BASE[@]}" -rustc_args "$flags" "$mut_gen" + + for pair in \ + "function pointer|inspect::<*const fn(u8)>(0 as *const _)" \ + "UnsafeCell|inspect::<*const core::cell::UnsafeCell>(0 as *const _)" \ + "ManuallyDrop|inspect::<*const core::mem::ManuallyDrop>(0 as *const _)" \ + "function item|inspect(projection_client)" \ + "closure|inspect(|| ())" + do + IFS='|' read -r ename ecall <<< "$pair" + cp "$folder/generic_projection.rs" "$mut_gen" + replace_one "$mut_gen" "inspect::(0)" "$ecall" + run_expect "generic_projection $target $export rejects erased $ename" 1 1 "$ERASED_ERR" -- \ + "${VF_BASE[@]}" -rustc_args "$flags" "$mut_gen" + done + + for pair in \ + "receiver|*const core::cell::UnsafeCell

: core::ptr::Pointee" \ + "right-hand side|P: core::ptr::Pointee" + do + IFS='|' read -r bname bound <<< "$pair" + { printf '#![feature(ptr_metadata)]\n'; cat "$folder/generic_projection.rs"; } > "$mut_gen" + replace_one "$mut_gen" "fn borrow_bytes(buffer: *const u8, length: usize)" \ + "fn borrow_bytes

(buffer: *const u8, length: usize) where $bound" + run_expect "generic_projection $target $export rejects erased metadata $bname" 1 1 "$ERASED_ERR" -- \ + "${VF_BASE[@]}" -rustc_args "$flags" "$mut_gen" + done + + for pair in \ + "type|inspect::(0)|inspect::/*@::@*/(0)" \ + "const|count::<1>(1)|count::<1>/*@::<2>@*/(1)" + do + IFS='|' read -r gname gcall gann <<< "$pair" + cp "$folder/generic_projection.rs" "$mut_gen" + replace_one "$mut_gen" "$gcall" "$gann" + run_expect "generic_projection $target $export rejects ghost $gname override" 1 2 \ + "Only lifetimes may be supplied at a Rust call. Use _ for MIR type and const arguments." "$gann" -- \ + "${VF_BASE[@]}" -rustc_args "$flags" "$mut_gen" + if [[ $native -eq 1 ]]; then + run_expect "compile ghost $gname override" 0 0 -- \ + rustc "$TC" --edition=2024 --test "$mut_gen" -o "$WORK/ghost-override" + run_expect "native ghost $gname override returns 1" 0 1 "1 passed" -- "$WORK/ghost-override" + fi + done + + # 5. auto_traits.rs (call-only !Send/!Sync + UnsafeCell structural + explicit unsafe impl) + local auto="$folder/auto_traits.rs" + local mut_auto="$WORK/auto_traits.rs" + printf 'send_client\nsync_client\nfield_traits\n' > "$root_file" + run_expect "auto_traits $target $export" 0 5 \ + "0 errors found" "$model" "Verifying function 'send_client'" "Verifying function 'sync_client'" "Verifying function 'field_traits'" -- \ + "${VF_BASE[@]}" -rustc_args "$flags" "$auto" + + for pair in \ + "send_client|is_Sync(typeid(Local))|is_Send(typeid(Local))" \ + "sync_client|is_Send(typeid(SyncLocal))|is_Sync(typeid(SyncLocal))" + do + IFS='|' read -r client old_t new_t <<< "$pair" + cp "$auto" "$mut_auto" + replace_one "$mut_auto" "$old_t" "$new_t" + run_expect "auto_traits $target $export rejects $new_t" 1 3 \ + "Verifying function '$client'" "error: Cannot prove" "$new_t == true;" -- \ + "${VF_BASE[@]}" -rustc_args "$flags" "$mut_auto" + done + + local assert_line + assert_line=$(grep -n -F '//@ assert is_Sync(typeid(Plain)) == true;' "$auto" | cut -d: -f1) + for claim in \ + "is_Sync(typeid(Wrapped)) == is_Sync(typeid(Plain))" \ + "is_Sync(typeid(Wrapped)) == true" \ + "is_Sync(typeid(Explicit)) == false" \ + "is_Sync(typeid(Explicit)) == true" \ + "is_Send(typeid(Explicit)) == false" \ + "is_Send(typeid(Explicit)) == true" + do + cp "$auto" "$mut_auto" + replace_one "$mut_auto" "//@ assert is_Sync(typeid(Plain)) == true;" "//@ assert $claim;" + run_expect "auto_traits $target $export rejects $claim" 1 3 \ + "Verifying function 'field_traits'" "error: Assertion might not hold." "$claim" -- \ + "${VF_BASE[@]}" -rustc_args "$flags" "$mut_auto" + "$CHECK_MIR" check-line-diag "$LAST_LOG" "$mut_auto" "$assert_line" error + done + + if [[ $export == normal ]]; then + run_expect "rustc $target accepts field trait bounds" 0 0 -- \ + rustc "$TC" --edition=2024 "--target=$target" --test --emit=metadata \ + -o "$WORK/field-traits.rmeta" "$auto" + cp "$auto" "$mut_auto" + replace_one "$mut_auto" "sync::();" \ + $'sync::();\n sync::();\n sync::();\n send::();\n sync::();\n send::();\n sync::();' + run_expect "rustc $target rejects seven invalid field trait bounds" 1 8 \ + "error[E0277]" "sync::();" "sync::();" "sync::();" \ + "send::();" "sync::();" "send::();" "sync::();" -- \ + rustc "$TC" --edition=2024 "--target=$target" --test --emit=metadata \ + -o "$WORK/field-traits.rmeta" "$mut_auto" + fi + + # 6. wide_pointer_comparison.rs + local wide="$folder/wide_pointer_comparison.rs" + local mut_wide="$WORK/wide_pointer_comparison.rs" + local wdiag="Raw pointer comparison requires a proven thin pointee" + printf 'compare\n' > "$root_file" + for qual in const mut; do + local qvf=() qrc=() + if [[ $qual == mut ]]; then qvf=(-rustc_arg "--cfg=mutable"); qrc=(--cfg=mutable); fi + run_expect "wide_pointer_comparison $target $export thin *$qual" 0 3 \ + "0 errors found" "$model" "Verifying function 'compare'" -- \ + "${VF_BASE[@]}" -rustc_args "$flags" -rustc_arg "--cfg=thin" "${qvf[@]}" "$wide" + local op + for op in "<" "<=" ">" ">=" "==" "!="; do + cp "$wide" "$mut_wide" + replace_one "$mut_wide" "{ a < b }" "{ a $op b }" + run_expect "wide_pointer_comparison $target $export rejects *$qual [u8] $op" 1 2 \ + "$wdiag" "{ a $op b }" -- \ + "${VF_BASE[@]}" -rustc_args "$flags" "${qvf[@]}" "$mut_wide" + done + if [[ $native -eq 1 ]]; then + run_expect "compile native *$qual slice comparison" 0 0 -- \ + rustc "$TC" --edition=2024 --test "${qrc[@]}" "$wide" -o "$WORK/wide-cmp" + run_expect "native *$qual slice of length 1 precedes length 2" 0 1 "1 passed" -- "$WORK/wide-cmp" + fi + for pair in "str|str|$wdiag" "dyn|dyn Send|Dynamic types are not yet supported"; do + IFS='|' read -r pname pty perr <<< "$pair" + cp "$wide" "$mut_wide" + replace_one "$mut_wide" "type Pointee = [u8];" "type Pointee = $pty;" + run_expect "wide_pointer_comparison $target $export rejects *$qual $pname" 1 1 "$perr" -- \ + "${VF_BASE[@]}" -rustc_args "$flags" "${qvf[@]}" "$mut_wide" + done + done + cp "$wide" "$mut_wide" + replace_one "$mut_wide" "fn compare(a: Raw, b: Raw)" "fn compare(a: *const T, b: *const T)" + run_expect "wide_pointer_comparison $target $export rejects unknown pointee width" 1 1 "$wdiag" -- \ + "${VF_BASE[@]}" -rustc_args "$flags" "$mut_wide" + done + done + + # 7. Core patch primitives & pointer qualifier negative controls + run_expect "ordering.rs" 0 2 "0 errors found" "Verifying function 'store_relaxed'" -- \ + "${VF_BASE[@]}" -rustc_arg "--edition=2021" "$folder/ordering.rs" + run_expect "macro_expansion.rs" 0 2 "0 errors found" "Verifying function 'Atomic::::expansion'" -- \ + "${VF_BASE[@]}" -skip_specless_fns -rustc_arg "--edition=2021" "$folder/macro_expansion.rs" + run_expect "drop.rs" 0 2 "0 errors found" "Verifying function 'finish'" -- \ + "${VF_BASE[@]}" -rustc_arg "--edition=2021" "$folder/drop.rs" + + printf 'concrete_value\n' > "$WORK/trait-roots.txt" + local trait_args=("${VF_BASE[@]}" -rustc_args "--edition=2024 --vf-rust-mir-exporter:roots=$WORK/trait-roots.txt --vf-rust-mir-exporter:scope-report=$WORK/trait-scope.tsv") + run_expect "concrete trait override" 0 2 "Verifying function 'concrete_value'" "0 errors found" -- \ + "${trait_args[@]}" "$folder/trait_dispatch.rs" + "$CHECK_MIR" edge-check "$WORK/trait-scope.tsv" "concrete_value" "{impl#0}::value" "-" 1 + + run_expect "panicking destructor" 0 0 -- \ + rustc "$TC" --test --edition=2021 "$folder/drop.rs" -o "$WORK/destructor" + run_expect "destructor unwind observed" 0 1 "1 passed" -- "$WORK/destructor" + + build_pointer_spec + cp "$POINTER_SPEC" "$WORK/pointer.rsspec.orig" + local rlib="$WORK/libslot_flags.rlib" + for target in "$HOST" "$ARM"; do + model="(target: $target (LP64))" + flags="--edition=2024 --target=$target" + run_expect "$target pointer qualifier provider" 0 4 \ + "$model" "0 errors found" "Slot::<*mut T>::tag" "Slot::<*const T>::tag" -- \ + "${VF_BASE[@]}" -rustc_args "$flags --crate-name slot_flags" "$folder/pointer_lib.rs" + run_expect "$target compile pointer qualifier provider" 0 0 -- \ + rustc "$TC" "--target=$target" --crate-type=rlib --crate-name=slot_flags "$folder/pointer_lib.rs" -o "$rlib" + local pcmd=("${VF_BASE[@]}" -rustc_args "$flags --extern slot_flags=$rlib" -extern_spec "slot_flags=$POINTER_SPEC" "$folder/pointer_client.rs") + run_expect "$target qualified external calls" 0 4 "$model" "0 errors found" "mut_client" "const_client" -- "${pcmd[@]}" + for pair in "mut:17:29" "const:29:17"; do + IFS=: read -r pty pold pnew <<< "$pair" + cp "$WORK/pointer.rsspec.orig" "$POINTER_SPEC" + replace_one "$POINTER_SPEC" "ens result == $pold" "ens result == $pnew" + run_expect "$target wrong *$pty interface" 1 2 "Verifying function '${pty}_client'" "error: Cannot prove" -- "${pcmd[@]}" + done + cp "$WORK/pointer.rsspec.orig" "$POINTER_SPEC" + done + + # Wrong dispatch, second macro expansion, generic destructor unwind + local mut_trait="$WORK/wrong_dispatch.rs" + awk '/pub unsafe fn concrete_value/ { in_fn = 1 } in_fn { sub(/ens result == 2;/, "ens result == 1;") } { print }' \ + "$folder/trait_dispatch.rs" > "$mut_trait" + run_expect "trait default cannot stand in for override" 1 3 \ + "Verifying function 'concrete_value'" "Cannot prove" "ens result == 1;" -- "${trait_args[@]}" "$mut_trait" + + local mut_macro="$WORK/bad_macro.rs" + cp "$folder/macro_expansion.rs" "$mut_macro" + replace_one "$mut_macro" "atomic_int_probe!(u32, 0);" "atomic_int_probe!(u32, 1);" + run_expect "second macro expansion" 1 2 \ + "Verifying function 'Atomic::::expansion'" "error: Cannot prove" -- \ + "${VF_BASE[@]}" -skip_specless_fns "$mut_macro" + + local mut_drop="$WORK/bad_drop.rs" + cp "$folder/drop.rs" "$mut_drop" + replace_one "$mut_drop" "on_unwind_ens thread_token(currentThread);" "on_unwind_ens false;" + run_expect "generic destructor can unwind" 1 3 \ + "Verifying function 'finish'" "error: Cannot prove condition" "Cannot prove false" -- \ + "${VF_BASE[@]}" -rustc_arg "--edition=2021" "$mut_drop" + + run_expect "byte range and CAS effects" 0 1 "0 errors found" -- \ + "${VF_BASE[@]}" -rustc_arg "--edition=2024" "$CHECKS/ranges.rs" + run_expect "overlapping byte separation" 0 1 "0 errors found" -- \ + "${VF_BASE[@]}" "$CHECKS/storage.rs" +} + +mutate_reject() { + local kind=$1 label=$2 file=$3 old=$4 new=$5 allow_dead=$6 nmarkers=$7; shift 7 + local backup="$WORK/mutate.bak" + cp "$file" "$backup" + replace_one "$file" "$old" "$new" + if [[ $kind == refine ]]; then + run_crate_refine "$label" 1 "$nmarkers" "$@" + else + run_crate_verifast "$allow_dead" "$label" 1 "$nmarkers" "$@" + fi + mv "$backup" "$file" +} + +run_production_controls() { + local allow=0 + if [[ $CRATE_FAMILY == rmw ]]; then allow=1; fi + check_dead_swap + run_crate_verifast "$allow" "$CRATE_FAMILY baseline" 0 1 "0 errors found" + cp "$CRATE_REPORT" "$WORK/baseline-report.tsv" + + if [[ $CRATE_FAMILY == access ]]; then + local store='intrinsics::atomic_store::(dst, val)' + local release='intrinsics::atomic_store::(dst, val)' + cp "$CRATE_ATOMIC" "$WORK/atomic.orig" + + # 1. Duplicate store callsites must both be exported and fail unique Relaxed edge check + replace_one "$CRATE_ATOMIC" "$store" "{ $store; $store }" + run_crate_verifast "$allow" "export duplicate store callsites" 0 1 "0 errors found" + "$CHECK_MIR" edge-check "$CRATE_REPORT" "${ATOMIC}atomic_store" "intrinsics::atomic_store" "Relaxed" 2 + run_expect "missing unique atomic_store -> atomic_store/Relaxed" 1 1 "edge count mismatch" -- \ + "$CHECK_MIR" edge-check "$CRATE_REPORT" "${ATOMIC}atomic_store" "intrinsics::atomic_store" "Relaxed" 1 + cp "$WORK/atomic.orig" "$CRATE_ATOMIC" + + # 2. Swapped Ordering branches + replace_one "$CRATE_ATOMIC" "Relaxed => $store" "Relaxed => $release" + replace_one "$CRATE_ATOMIC" "Release => $release" "Release => $store" + run_expect "compile swapped Ordering branches" 0 0 -- \ + rustc "$TC" $(core_flags_str "$CRATE_TARGET") --crate-type=lib \ + "-Zdump-mir=atomic_store & built" -Zdump-mir-exclude-pass-number \ + "-Zdump-mir-dir=$WORK/swapped-mir" --emit=metadata -o "$WORK/store.rmeta" "$CRATE_ROOT" + run_expect "atomic_store input Relaxed reached atomic_store/Release" 1 1 \ + "atomic_store input Relaxed reached atomic_store/Release" -- \ + "$CHECK_MIR" routes "$WORK/swapped-mir" "$PROOF/intrinsic-manifest.tsv" atomic_store Relaxed + cp "$WORK/atomic.orig" "$CRATE_ATOMIC" + + # 3. Shared Release tail (double store) + replace_one "$CRATE_ATOMIC" \ + "Relaxed => ${store},"$'\n'" Release => ${release}," \ + "Relaxed | Release => { match order { Relaxed => ${store}, _ => () }; ${release} }," + run_expect "compile shared Release tail" 0 0 -- \ + rustc "$TC" $(core_flags_str "$CRATE_TARGET") --crate-type=lib \ + "-Zdump-mir=atomic_store & built" -Zdump-mir-exclude-pass-number \ + "-Zdump-mir-dir=$WORK/shared-mir" --emit=metadata -o "$WORK/store.rmeta" "$CRATE_ROOT" + run_expect "second atomic call atomic_store" 1 1 "second atomic call atomic_store" -- \ + "$CHECK_MIR" routes "$WORK/shared-mir" "$PROOF/intrinsic-manifest.tsv" atomic_store Relaxed + mv "$WORK/atomic.orig" "$CRATE_ATOMIC" + + local cond='(int_of_const(typeid(ORD)) == 0 || int_of_const(typeid(ORD)) == 1 || int_of_const(typeid(ORD)) == 4)' + mutate_reject vf "exclude the Relaxed nonvolatile store" "$CRATE_INTR" "$cond" \ + "$cond &*& (int_of_const(typeid(ORD)) != 0 || int_of_const(typeid(VOLATILE)) != 0)" "$allow" 3 \ + "Verifying function '${ATOMIC}atomic_store'" "error: Cannot prove" \ + 'intrinsics::atomic_store::' + + mutate_reject vf "illegal store order can unwind" "$CRATE_ATOMIC" \ + "on_unwind_ens (order == Ordering::Acquire || order == Ordering::AcqRel) &*& thread_token(currentThread);" \ + "on_unwind_ens false;" "$allow" 3 \ + "Verifying function '${ATOMIC}atomic_store'" "error: Cannot prove" "on_unwind_ens false;" + + local msg='Acquire => panic!("there is no such thing as an acquire store"),' + mutate_reject vf "altered static panic" "$CRATE_ATOMIC" "$msg" \ + 'Acquire => panic!("changed store message"),' "$allow" 2 \ + "unapproved literal panic at sync::atomic::atomic_store" "changed store message" + + mutate_reject vf "nonliteral panic argument" "$CRATE_ATOMIC" "$msg" \ + 'Acquire => { let message = "there is no such thing as an acquire store"; crate::panicking::panic_fmt(crate::fmt::Arguments::from_str(message)) },' \ + "$allow" 2 "nonliteral panic input at" "sync::atomic::atomic_store" + + local bstore='atomic_store::<_, /* VOLATILE */ false>(self.v.get().cast::(), val as u8, order)' + mutate_reject vf "Bool store rejects byte 2" "$CRATE_ATOMIC" "$bstore" \ + 'atomic_store::<_, /* VOLATILE */ false>(self.v.get().cast::(), 2u8, order)' "$allow" 3 \ + "Verifying function '${ATOMIC}Atomic::::store'" "error: Cannot prove" "2u8, order)" + + mutate_reject vf "overlapping U16 and U8 borrow" "$CRATE_SRC/ch7_width.rs" \ + "close ordinary::(next)();" "close ordinary::(interior)();" "$allow" 3 \ + "Verifying function 'ch7_width::disjoint_views'" "No matching heap chunks: points_to" \ + "close ordinary::(interior)" + + local bclient="$CRATE_SRC/sync/atomic/ch7_bool_byte.rs" + local wline + wline=$(awk '/unsafe fn weak_byte/ { s = 1 } s && /^\/\/@ ens / && /Result::Err\(v\) => sync::atomic::valid_bool_byte\(v\) == true \}/ { print; exit }' "$bclient") + mutate_reject vf "spurious weak CAS failure" "$bclient" "$wline" \ + "${wline%\};} &*& (v != 0) != expected };" \ + "$allow" 3 "Verifying function '${ATOMIC}ch7_bool_byte::weak_byte'" "error: Cannot prove" "!= expected" + elif [[ $CRATE_FAMILY == rmw ]]; then + local bxor='unsafe { atomic_xor(self.v.get().cast::(), val as u8, order) != 0 }' + mutate_reject refine "inverted Bool XOR return" "$CRATE_ATOMIC" "$bxor" \ + "${bxor/!= 0/== 0}" "$allow" 2 \ + "Function bodies for ${ATOMIC}Atomic::::fetch_xor are different" "BinaryOp: The operators do not match" + mutate_reject vf "ordinary read inside Bool RMW" "$CRATE_ATOMIC" "$bxor" \ + $'let _ordinary = unsafe { *self.v.get().cast::() };\n '"$bxor" "$allow" 3 \ + "Verifying function '${ATOMIC}Atomic::::fetch_xor'" "No matching heap chunks: [_]points_to" "let _ordinary" + + # [R10-01] Commented-out or cfg-disabled duplicate witness with forged postcondition must fail. + dump_witness_mir + local bmod="$CRATE_SRC/ch7_bool.rs" + cp "$bmod" "$WORK/bmod.orig" + replace_one "$bmod" \ + "unsafe fn shared_bool_and(receiver: &AtomicBool, val: bool, order: crate::sync::atomic::Ordering) -> bool" \ + $'/*\nunsafe fn shared_bool_and(receiver: &AtomicBool, val: bool, order: crate::sync::atomic::Ordering) -> bool\n//@ req [?q]lifetime_token(?k) &*& [_]frac_borrow(k, sync::atomic::bool_slot_content(ref_origin(receiver))) &*& [_]frac_borrow(k, ref_initialized_(receiver));\n//@ ens [q]lifetime_token(k) &*& result == false;\n//@ on_unwind_ens false;\n{\n receiver.fetch_and(val, order)\n}\n*/\npub(crate) unsafe fn shared_bool_and(receiver: &AtomicBool, val: bool, order: crate::sync::atomic::Ordering) -> bool' + run_expect "commented witness with pub(crate) real fn rejected" 1 1 \ + "must be declared with qualifiers" -- \ + "$CHECK_MIR" thread-spec rmw "$CRATE_SRC" "$WORK/owners-${HOST}.tsv" \ + "$WORK/baseline-report.tsv" "$CHECKS/pointer-shape.rs" "$CRATE_WITNESS_MIR" + cp "$WORK/bmod.orig" "$bmod" + + replace_one "$bmod" \ + "unsafe fn shared_bool_and(receiver: &AtomicBool, val: bool, order: crate::sync::atomic::Ordering) -> bool" \ + $'#[cfg(any())]\nunsafe fn shared_bool_and(receiver: &AtomicBool, val: bool, order: crate::sync::atomic::Ordering) -> bool\n//@ req [?q]lifetime_token(?k) &*& [_]frac_borrow(k, sync::atomic::bool_slot_content(ref_origin(receiver))) &*& [_]frac_borrow(k, ref_initialized_(receiver));\n//@ ens [q]lifetime_token(k) &*& result == false;\n//@ on_unwind_ens false;\n{\n receiver.fetch_and(val, order)\n}\nunsafe fn shared_bool_and(receiver: &AtomicBool, val: bool, order: crate::sync::atomic::Ordering) -> bool' + run_expect "cfg-disabled duplicate witness rejected" 1 1 \ + "expected 1 top-level witness shared_bool_and, found 2" -- \ + "$CHECK_MIR" thread-spec rmw "$CRATE_SRC" "$WORK/owners-${HOST}.tsv" \ + "$WORK/baseline-report.tsv" "$CHECKS/pointer-shape.rs" "$CRATE_WITNESS_MIR" + cp "$WORK/bmod.orig" "$bmod" + + # [R11-08] U+0085 whitespace between #[cfg(any())] and duplicate witness + raw ident `r#shared_bool_and` must fail. + replace_one "$bmod" \ + "unsafe fn shared_bool_and(receiver: &AtomicBool, val: bool, order: crate::sync::atomic::Ordering) -> bool" \ + $'#[cfg(any())]\xc2\x85unsafe fn shared_bool_and(receiver: &AtomicBool, val: bool, order: crate::sync::atomic::Ordering) -> bool\n//@ req [?q]lifetime_token(?k) &*& [_]frac_borrow(k, sync::atomic::bool_slot_content(ref_origin(receiver))) &*& [_]frac_borrow(k, ref_initialized_(receiver));\n//@ ens [q]lifetime_token(k) &*& result == false;\n//@ on_unwind_ens false;\n{\n receiver.fetch_and(val, order)\n}\nunsafe fn r#shared_bool_and(receiver: &AtomicBool, val: bool, order: crate::sync::atomic::Ordering) -> bool' + run_expect "U+0085 cfg duplicate with raw ident real witness rejected" 1 1 \ + "expected 1 top-level witness shared_bool_and, found 2" -- \ + "$CHECK_MIR" thread-spec rmw "$CRATE_SRC" "$WORK/owners-${HOST}.tsv" \ + "$WORK/baseline-report.tsv" "$CHECKS/pointer-shape.rs" "$CRATE_WITNESS_MIR" + mv "$WORK/bmod.orig" "$bmod" + + # [R10-03 & R11-04] Bool fetch_not / fetch_nand extra RMW, extra store_volatile, and cleanup-path call must fail MIR check. + local bool_owner + bool_owner=$(owner_of "$HOST" bool) + cp "$CRATE_ATOMIC" "$WORK/atomic.bool.orig" + replace_one "$CRATE_ATOMIC" \ + $' //@ leak Atomic_share::(k, currentThread, self);\n self.fetch_xor(true, order)\n }' \ + $' //@ leak Atomic_share::(k, currentThread, self);\n let old = self.fetch_xor(true, order);\n let _ = self.fetch_xor(true, Relaxed);\n old\n }' + run_expect "compile fetch_not double RMW" 0 0 -- \ + rustc "$TC" $(core_flags_str "$CRATE_TARGET") --crate-type=lib \ + "-Zdump-mir=sync::atomic & built" -Zdump-mir-exclude-pass-number \ + "-Zdump-mir-dir=$WORK/fetch-not-double-mir" --emit=metadata -o "$WORK/fnot.rmeta" "$CRATE_ROOT" + run_expect "fetch_not second Relaxed RMW rejected" 1 1 "multiple helper calls on path" -- \ + "$CHECK_MIR" check-public-order "$WORK/fetch-not-double-mir" "$bool_owner" bool fetch_not fetch_xor + cp "$WORK/atomic.bool.orig" "$CRATE_ATOMIC" + + replace_one "$CRATE_ATOMIC" \ + $' //@ leak Atomic_share::(k, currentThread, self);\n self.fetch_xor(true, order)\n }' \ + $' //@ leak Atomic_share::(k, currentThread, self);\n let old = self.fetch_xor(true, order);\n unsafe { AtomicBool::store_volatile(self, false, Relaxed) };\n old\n }' + run_expect "compile fetch_not extra store_volatile" 0 0 -- \ + rustc "$TC" $(core_flags_str "$CRATE_TARGET") --crate-type=lib \ + "-Zdump-mir=sync::atomic & built" -Zdump-mir-exclude-pass-number \ + "-Zdump-mir-dir=$WORK/fetch-not-vol-mir" --emit=metadata -o "$WORK/fnot-vol.rmeta" "$CRATE_ROOT" + run_expect "fetch_not post-call store_volatile rejected" 1 1 "unapproved extra call" -- \ + "$CHECK_MIR" check-public-order "$WORK/fetch-not-vol-mir" "$bool_owner" bool fetch_not fetch_xor + cp "$WORK/atomic.bool.orig" "$CRATE_ATOMIC" + + # [R11-04] Cleanup/unwind path calling a helper function before resume must be rejected. + mkdir -p "$WORK/fetch-not-unwind-mir" + cat > "$WORK/fetch-not-unwind-mir/core.sync-atomic-${bool_owner}-fetch_not.built.after.mir" <<'MIR' +fn atomic::::fetch_not(_1: &Atomic, _2: atomic::Ordering) -> bool { + let mut _0: bool; + let mut _3: &sync::atomic::Atomic; + let mut _4: sync::atomic::Ordering; + let mut _5: (); + + bb0: { + _3 = &(*_1); + _4 = copy _2; + _0 = Atomic::::fetch_xor(move _3, const true, move _4) -> [return: bb1, unwind: bb2]; + } + + bb1: { + return; + } + + bb2 (cleanup): { + _5 = Atomic::::store_volatile(move _3, const false, const Relaxed) -> [return: bb3, unwind terminate(abi)]; + } + + bb3 (cleanup): { + resume; + } +} +MIR + run_expect "fetch_not unwind-path extra call rejected" 1 1 "unexpected call" -- \ + "$CHECK_MIR" check-public-order "$WORK/fetch-not-unwind-mir" "$bool_owner" bool fetch_not fetch_xor + + # [R12-08] Cleanup/unwind path containing a Drop terminator must be rejected. + mkdir -p "$WORK/fetch-not-drop-mir" + cat > "$WORK/fetch-not-drop-mir/core.sync-atomic-${bool_owner}-fetch_not.built.after.mir" <<'MIR' +fn atomic::::fetch_not(_1: &Atomic, _2: atomic::Ordering) -> bool { + let mut _0: bool; + let mut _3: &sync::atomic::Atomic; + let mut _4: sync::atomic::Ordering; + let mut _5: Guard; + + bb0: { + _3 = &(*_1); + _4 = copy _2; + _0 = Atomic::::fetch_xor(move _3, const true, move _4) -> [return: bb1, unwind: bb2]; + } + + bb1: { + return; + } + + bb2 (cleanup): { + drop(_5) -> [return: bb3, unwind terminate(abi)]; + } + + bb3 (cleanup): { + resume; + } +} +MIR + run_expect "fetch_not unwind-path drop rejected" 1 1 "drop on unwind path is forbidden" -- \ + "$CHECK_MIR" check-public-order "$WORK/fetch-not-drop-mir" "$bool_owner" bool fetch_not fetch_xor + + # [R12-02] Free function sharing suffix `fetch_xor` (e.g. `fallback::fetch_xor(order)`) must NOT match Atomic::::fetch_xor. + replace_one "$CRATE_ATOMIC" \ + $' //@ leak Atomic_share::(k, currentThread, self);\n self.fetch_xor(true, order)\n }' \ + $' //@ leak Atomic_share::(k, currentThread, self);\n mod fallback { pub const fn fetch_xor(_: super::Ordering) -> bool { false } }\n fallback::fetch_xor(order)\n }' + run_expect "compile fetch_not fake fallback::fetch_xor" 0 0 -- \ + rustc "$TC" $(core_flags_str "$CRATE_TARGET") --crate-type=lib \ + "-Zdump-mir=sync::atomic & built" -Zdump-mir-exclude-pass-number \ + "-Zdump-mir-dir=$WORK/fetch-not-fake-mir" --emit=metadata -o "$WORK/fnot-fake.rmeta" "$CRATE_ROOT" + run_expect "fetch_not calling fallback::fetch_xor rejected" 1 1 "unapproved extra call" -- \ + "$CHECK_MIR" check-public-order "$WORK/fetch-not-fake-mir" "$bool_owner" bool fetch_not fetch_xor + cp "$WORK/atomic.bool.orig" "$CRATE_ATOMIC" + + replace_one "$CRATE_ATOMIC" \ + $' // We must invert the bool.\n self.fetch_xor(true, order)' \ + $' // We must invert the bool.\n let old = self.fetch_xor(true, order);\n let _ = self.swap(true, Relaxed);\n old' + run_expect "compile fetch_nand double RMW" 0 0 -- \ + rustc "$TC" $(core_flags_str "$CRATE_TARGET") --crate-type=lib \ + "-Zdump-mir=sync::atomic & built" -Zdump-mir-exclude-pass-number \ + "-Zdump-mir-dir=$WORK/fetch-nand-double-mir" --emit=metadata -o "$WORK/fnand.rmeta" "$CRATE_ROOT" + run_expect "fetch_nand second Relaxed RMW rejected" 1 1 "multiple helper calls on path" -- \ + "$CHECK_MIR" check-public-order "$WORK/fetch-nand-double-mir" "$bool_owner" bool fetch_nand "fetch_xor|swap" + mv "$WORK/atomic.bool.orig" "$CRATE_ATOMIC" + elif [[ $CRATE_FAMILY == pointer-access ]]; then + local pswap=' unsafe { atomic_swap(self.as_ptr(), ptr, order) }' + mutate_reject refine "pointer swap returns replacement" "$CRATE_ATOMIC" "$pswap" \ + $' let _ = unsafe { atomic_swap(self.as_ptr(), ptr, order) };\n ptr' "$allow" 2 \ + "Function bodies for ${ATOMIC}Atomic::<*mut T>::swap are different" "ERROR:" + + local pclient="$CRATE_SRC/ch7_pointer.rs" + for pair in "slice_metadata|*[u8]|typeid(usize)" "reference_metadata|&'a u8|typeid(())"; do + IFS='|' read -r pname pty pold <<< "$pair" + local clause + clause=$(awk -v suf="== $pold;" '/^\/\/@ ens typeid\(/ && substr($0, length($0)-length(suf)+1) == suf { print; exit }' "$pclient") + local site="sync::atomic::thin_raw_slot_type::<${pty}>() == true" + mutate_reject vf "invalid slot type $pty" "$pclient" "$clause" \ + "${clause%;} &*& ${site};" "$allow" 3 \ + "Verifying function 'ch7_pointer::$pname'" "error: Cannot prove" "$site" + done + + local pshape_old=$'== typeid(M);\n//@ on_unwind_ens false;\n{}' + mutate_reject vf "wrong type projection" "$CRATE_INTR" "$pshape_old" \ + $'== typeid(M);\n//@ on_unwind_ens false;\n{\n //@ assert typeid(

::Metadata) == typeid(u32);\n}' \ + "$allow" 3 "Verifying function 'intrinsics::ch7_pointer_shape'" "Assertion might not hold" "Metadata) == typeid(u32);" + + # [R11-01] Monomorphic `type T = u8` pointer witness and extra trait bound `` must both be rejected. + dump_witness_mir + cp "$pclient" "$WORK/pclient.orig" + replace_one "$pclient" \ + "unsafe fn thread_pointer_swap(receiver: &AtomicPtr, val: *mut T, order: Ordering) -> *mut T" \ + $'type T = u8;\nunsafe fn thread_pointer_swap(receiver: &AtomicPtr, val: *mut T, order: Ordering) -> *mut T' + run_expect "compile monomorphic u8 pointer witness" 0 0 -- \ + rustc "$TC" $(core_flags_str "$CRATE_TARGET") --crate-type=lib \ + "-Zdump-mir=ch7_ & built" -Zdump-mir-exclude-pass-number \ + "-Zdump-mir-dir=$WORK/mono-ptr-mir" --emit=metadata -o "$WORK/mono-ptr.rmeta" "$CRATE_ROOT" + run_expect "monomorphic u8 pointer witness rejected by thread-spec" 1 1 \ + "must have exact unconstrained generics" -- \ + "$CHECK_MIR" thread-spec pointer-access "$CRATE_SRC" "$WORK/owners-${HOST}.tsv" \ + "$WORK/baseline-report.tsv" "$CHECKS/pointer-shape.rs" "$WORK/mono-ptr-mir" + cp "$WORK/pclient.orig" "$pclient" + + replace_one "$pclient" \ + "unsafe fn thread_pointer_swap(receiver: &AtomicPtr, val: *mut T, order: Ordering) -> *mut T" \ + "unsafe fn thread_pointer_swap(receiver: &AtomicPtr, val: *mut T, order: Ordering) -> *mut T" + run_expect "bounded generic pointer witness rejected by thread-spec" 1 1 \ + "must have exact unconstrained generics" -- \ + "$CHECK_MIR" thread-spec pointer-access "$CRATE_SRC" "$WORK/owners-${HOST}.tsv" \ + "$WORK/baseline-report.tsv" "$CHECKS/pointer-shape.rs" "$CRATE_WITNESS_MIR" + cp "$WORK/pclient.orig" "$pclient" + + # [R12-01] Non-empty ch7_pointer_shape (even with a trailing empty dummy function in file) must fail both source and MIR checks. + local bad_shape="$WORK/bad-pointer-shape.rs" + cp "$CHECKS/pointer-shape.rs" "$bad_shape" + replace_one "$bad_shape" "{}" $'{ while _slot.is_null() {} }\nunsafe fn trailing_dummy()\n//@ req true;\n//@ ens true;\n//@ on_unwind_ens false;\n{}' + run_expect "looping ch7_pointer_shape with trailing empty fn rejected by source check" 1 1 \ + "ch7_pointer_shape must have an empty source body" -- \ + "$CHECK_MIR" thread-spec pointer-access "$CRATE_SRC" "$WORK/owners-${HOST}.tsv" \ + "$WORK/baseline-report.tsv" "$bad_shape" "$CRATE_WITNESS_MIR" + + cp "$CRATE_INTR" "$WORK/intr.orig" + replace_one "$CRATE_INTR" $'//@ on_unwind_ens false;\n{}' \ + $'//@ on_unwind_ens false;\n{ while _slot.is_null() {} }' + run_expect "compile looping ch7_pointer_shape MIR" 0 0 -- \ + rustc "$TC" $(core_flags_str "$CRATE_TARGET") --crate-type=lib \ + "-Zdump-mir=ch7_ & built" -Zdump-mir-exclude-pass-number \ + "-Zdump-mir-dir=$WORK/loop-shape-mir" --emit=metadata -o "$WORK/loop-shape.rmeta" "$CRATE_ROOT" + run_expect "looping ch7_pointer_shape MIR rejected by thread-spec" 1 1 \ + "ch7_pointer_shape MIR must" -- \ + "$CHECK_MIR" thread-spec pointer-access "$CRATE_SRC" "$WORK/owners-${HOST}.tsv" \ + "$WORK/baseline-report.tsv" "$CHECKS/pointer-shape.rs" "$WORK/loop-shape-mir" + mv "$WORK/intr.orig" "$CRATE_INTR" + + # [R11-02 & R12-07] Parameter names containing `receiver` (e.g. `receiver_value`, `self_value`) must NOT be corrupted during export, + # AND the renamed witness with strengthened postcondition must actually verify under VeriFast first. + replace_one "$pclient" \ + $'unsafe fn thread_pointer_compare_exchange(receiver: &AtomicPtr, current: *mut T, new: *mut T, success: Ordering, failure: Ordering) -> Result<*mut T, *mut T>\n//@ req [?q]lifetime_token(?k) &*& [_]frac_borrow(k, thread_pointer_content::(ref_origin(receiver))) &*& [_]frac_borrow(k, ref_initialized_(receiver)) &*& success == sync::atomic::Ordering::Relaxed &*& failure == sync::atomic::Ordering::Relaxed;\n//@ ens [q]lifetime_token(k) &*& result::Result_own::<*T, *T>(currentThread, result);\n//@ on_unwind_ens false;\n{\n unsafe { crate::intrinsics::ch7_pointer_shape::(current as *mut *mut T) };\n //@ certify_thread_borrow::(ref_origin(receiver), k);\n //@ close exists(false);\n //@ close sync::atomic::Atomic_share::<*T>(k, currentThread, receiver);\n //@ leak sync::atomic::Atomic_share::<*T>(k, currentThread, receiver);\n //@ close sync::atomic::Ordering_own(currentThread, success);\n //@ close sync::atomic::Ordering_own(currentThread, failure);\n receiver.compare_exchange(current, new, success, failure)\n}' \ + $'unsafe fn thread_pointer_compare_exchange(receiver: &AtomicPtr, receiver_value: *mut T, self_value: *mut T, success: Ordering, failure: Ordering) -> Result<*mut T, *mut T>\n//@ req [?q]lifetime_token(?k) &*& [_]frac_borrow(k, thread_pointer_content::(ref_origin(receiver))) &*& [_]frac_borrow(k, ref_initialized_(receiver)) &*& success == sync::atomic::Ordering::Relaxed &*& failure == sync::atomic::Ordering::Relaxed;\n//@ ens [q]lifetime_token(k) &*& result::Result_own::<*T, *T>(currentThread, result) &*& match result { Result::Ok(v) => v as usize == receiver_value as usize, Result::Err(v) => true };\n//@ on_unwind_ens false;\n{\n unsafe { crate::intrinsics::ch7_pointer_shape::(receiver_value as *mut *mut T) };\n //@ certify_thread_borrow::(ref_origin(receiver), k);\n //@ close exists(false);\n //@ close sync::atomic::Atomic_share::<*T>(k, currentThread, receiver);\n //@ leak sync::atomic::Atomic_share::<*T>(k, currentThread, receiver);\n //@ close sync::atomic::Ordering_own(currentThread, success);\n //@ close sync::atomic::Ordering_own(currentThread, failure);\n receiver.compare_exchange(receiver_value, self_value, success, failure)\n}' + run_crate_verifast "$allow" "verify renamed receiver_value/self_value pointer witness" 0 2 \ + "0 errors found" "Verifying function 'ch7_pointer::thread_pointer_compare_exchange'" + cp "$CRATE_REPORT" "$WORK/rename-ptr-report.tsv" + run_expect "compile receiver_value/self_value pointer witness" 0 0 -- \ + rustc "$TC" $(core_flags_str "$CRATE_TARGET") --crate-type=lib \ + "-Zdump-mir=ch7_ & built" -Zdump-mir-exclude-pass-number \ + "-Zdump-mir-dir=$WORK/rename-ptr-mir" --emit=metadata -o "$WORK/rename-ptr.rmeta" "$CRATE_ROOT" + "$CHECK_MIR" thread-spec pointer-access "$CRATE_SRC" "$WORK/owners-${HOST}.tsv" \ + "$WORK/rename-ptr-report.tsv" "$CHECKS/pointer-shape.rs" "$WORK/rename-ptr-mir" > "$WORK/rename-ptr.rsspec" + grep -Fq 'v as usize == receiver_value as usize' "$WORK/rename-ptr.rsspec" + # [R13-06] Use an explicit if guard instead of `! grep` (which `set -e` ignores). + check_no_aliased_self_value() { + if grep -Fq 'v as usize == self_value as usize' "$1"; then + echo "FAIL thread-spec aliased receiver_value to self_value in $1" >&2 + return 1 + fi + } + check_no_aliased_self_value "$WORK/rename-ptr.rsspec" + printf '%s\n%s\n' \ + 'v as usize == receiver_value as usize' \ + 'v as usize == self_value as usize' > "$WORK/both-clauses.rsspec" + run_expect "R13-06 dual-clause guard rejects aliased self_value" 1 1 \ + "aliased receiver_value to self_value" -- \ + bash -c 'if grep -Fq "v as usize == self_value as usize" "$1"; then echo "FAIL thread-spec aliased receiver_value to self_value" >&2; exit 1; fi' _ "$WORK/both-clauses.rsspec" + echo "PASS thread-spec preserves receiver_value without aliasing self_value" + mv "$WORK/pclient.orig" "$pclient" + elif [[ $CRATE_FAMILY == u32 ]]; then + mutate_reject vf "owned Atomic cannot imply false" "$CRATE_ATOMIC" "lem Atomic_share_full" \ + $'lem atomic_own_absurd(t: thread_id_t, v: Atomic)\n req Atomic_own::(t, v);\n ens false;\n{ open Atomic_own::(t, v); }\nlem Atomic_share_full' \ + "$allow" 2 "atomic_own_absurd" "Cannot prove false" + + local uclient="$CRATE_SRC/ch7_public.rs" + local rt_body + rt_body=$(awk '/unsafe fn round_trip\(\)/ { p = 1 } p { print } p && /^\}$/ { exit }' "$uclient") + local rt_uninit="$rt_body" + rt_uninit="${rt_uninit/round_trip()/round_trip(p: *mut u32)}" + rt_uninit="${rt_uninit/\/\/@ req /\/\/@ req points_to_(p, none) &*& }" + rt_uninit="${rt_uninit/$' let mut word: u32 = 0;\n let p = &raw mut word;\n'/}" + rt_uninit="${rt_uninit/assert word == 30/assert *p == 30}" + mutate_reject vf "from_ptr requires initialized U32 storage" "$uclient" "$rt_body" "$rt_uninit" "$allow" 3 \ + "Verifying function 'ch7_public::round_trip'" "is not an instance of constructor 'none'" "close ordinary_word(p)()" + + mutate_reject vf "uninitialized slot cannot call AtomicU32::from_ptr" "$uclient" \ + " &*& [_]frac_borrow('a, sync::atomic::U32_atomic_content(ptr)) &*& ref_origin(ptr) == ptr;" \ + " &*& points_to_(ptr, none) &*& ref_origin(ptr) == ptr;" "$allow" 3 \ + "Verifying function 'ch7_public::borrowed_from_ptr'" "No matching heap chunks: [_]frac_borrow" \ + "AtomicU32::from_ptr/*@::<'a>@*/(ptr)" + + local uload=' unsafe { atomic_load::<_, /* VOLATILE */ false>(self.as_ptr(), order) }' + local ustore=' unsafe { atomic_store::<_, /* VOLATILE */ false>(self.as_ptr(), val, order); }' + local ucas=' unsafe { atomic_compare_exchange(self.as_ptr(), current, new, success, failure) }' + local upref="${ATOMIC}Atomic::::" + + mutate_reject vf "broken production U32 macro expansion" "$CRATE_ATOMIC" \ + $'\n self.v.get().cast()\n' \ + $'\n let _original = self.v.get().cast::<$int_type>();\n let mut other: $int_type = 0;\n &raw mut other\n' \ + "$allow" 3 "note: Verifying function '${upref}as_ptr'" "error: Cannot prove condition" \ + "result as pointer == ref_origin(self) as pointer" + + mutate_reject vf "ordinary access inside U32 store" "$CRATE_ATOMIC" "$ustore" \ + $' unsafe { *self.as_ptr() = val };\n'"$ustore" "$allow" 3 \ + "Verifying function '${upref}store'" "No matching heap chunks: points_to_" "unsafe { *self.as_ptr() = val };" + mutate_reject vf "ordinary access inside U32 load" "$CRATE_ATOMIC" "$uload" \ + $' let _ordinary = unsafe { *self.as_ptr() };\n'"$uload" "$allow" 3 \ + "Verifying function '${upref}load'" "No matching heap chunks: [_]points_to" "let _ordinary = unsafe { *self.as_ptr() };" + mutate_reject vf "ordinary access inside U32 compare_exchange" "$CRATE_ATOMIC" "$ucas" \ + $' let _ordinary = unsafe { *self.as_ptr() };\n'"$ucas" "$allow" 3 \ + "Verifying function '${upref}compare_exchange'" "No matching heap chunks: [_]points_to" "let _ordinary = unsafe { *self.as_ptr() };" + + mutate_reject refine "zero U32 load" "$CRATE_ATOMIC" "$uload" \ + "${uload};"$'\n'" 0" "$allow" 2 \ + "Function bodies for ${upref}load are different" "return values" + mutate_reject refine "fabricated U32 CAS result" "$CRATE_ATOMIC" "$ucas" \ + "${ucas};"$'\n'" Err(0)" "$allow" 2 \ + "Function bodies for ${upref}compare_exchange are different" "return values" + + # [B3] Witness with hidden store between line-comment /*@ / @*/ must be rejected lexically AND by MIR edges. + dump_witness_mir + cp "$uclient" "$WORK/uclient.orig" + replace_one "$uclient" " receiver.load(order)" \ + $' // /*@\n receiver.store(0, order);\n // @*/\n receiver.load(order)' + run_expect "witness with extra store in comment markers" 1 1 "method adapter changed" -- \ + "$CHECK_MIR" thread-spec u32 "$CRATE_SRC" "$WORK/owners-${HOST}.tsv" \ + "$WORK/baseline-report.tsv" "$CHECKS/pointer-shape.rs" "$CRATE_WITNESS_MIR" + mv "$WORK/uclient.orig" "$uclient" + + # [B3] Witness scope report with an extra MIR outgoing call edge must be rejected even if source matches. + cp "$WORK/baseline-report.tsv" "$WORK/extra-edge.tsv" + printf 'edge\tch7_public::borrowed_load\tsync::atomic::%s::store\tsync::atomic::Atomic::::store\tbb99\n' \ + "$(owner_of "$HOST" u32)" >> "$WORK/extra-edge.tsv" + run_expect "witness with extra MIR outgoing call edge" 1 1 "unexpected MIR call edges" -- \ + "$CHECK_MIR" thread-spec u32 "$CRATE_SRC" "$WORK/owners-${HOST}.tsv" \ + "$WORK/extra-edge.tsv" "$CHECKS/pointer-shape.rs" "$CRATE_WITNESS_MIR" + + # [B4 & R10-02] Public AtomicU32::swap hardcoding Relaxed, mutating order via &mut borrow, and compare_exchange swapping (failure, success) must fail MIR check. + local u32_owner + u32_owner=$(owner_of "$HOST" u32) + cp "$CRATE_ATOMIC" "$WORK/atomic.u32.orig" + replace_one "$CRATE_ATOMIC" \ + "unsafe { atomic_swap(self.as_ptr(), val, order) }" \ + "unsafe { atomic_swap(self.as_ptr(), val, Relaxed) }" + run_expect "compile swap hardcoded Relaxed" 0 0 -- \ + rustc "$TC" $(core_flags_str "$CRATE_TARGET") --crate-type=lib \ + "-Zdump-mir=sync::atomic & built" -Zdump-mir-exclude-pass-number \ + "-Zdump-mir-dir=$WORK/swap-relaxed-mir" --emit=metadata -o "$WORK/swap.rmeta" "$CRATE_ROOT" + run_expect "public swap hardcoding Relaxed rejected" 1 1 "did not forward Ordering parameter #0 unmodified" -- \ + "$CHECK_MIR" check-public-order "$WORK/swap-relaxed-mir" "$u32_owner" u32 swap atomic_swap + cp "$WORK/atomic.u32.orig" "$CRATE_ATOMIC" + + replace_one "$CRATE_ATOMIC" \ + "unsafe { atomic_swap(self.as_ptr(), val, order) }" \ + "{ let mut o = order; let p = &mut o; *p = Relaxed; unsafe { atomic_swap(self.as_ptr(), val, o) } }" + run_expect "compile swap mut-borrow overwrite Relaxed" 0 0 -- \ + rustc "$TC" $(core_flags_str "$CRATE_TARGET") --crate-type=lib \ + "-Zdump-mir=sync::atomic & built" -Zdump-mir-exclude-pass-number \ + "-Zdump-mir-dir=$WORK/swap-mutborrow-mir" --emit=metadata -o "$WORK/swap-mut.rmeta" "$CRATE_ROOT" + run_expect "public swap mut-borrow overwrite Ordering rejected" 1 1 "did not forward Ordering parameter #0 unmodified" -- \ + "$CHECK_MIR" check-public-order "$WORK/swap-mutborrow-mir" "$u32_owner" u32 swap atomic_swap + cp "$WORK/atomic.u32.orig" "$CRATE_ATOMIC" + + # [R11-03] Taking raw mut pointer BEFORE copying `order` into `o`, then overwriting `*p = Relaxed`, must fail. + replace_one "$CRATE_ATOMIC" \ + "unsafe { atomic_swap(self.as_ptr(), val, order) }" \ + "{ let mut o = Relaxed; let p = &raw mut o; o = order; unsafe { *p = Relaxed; atomic_swap(self.as_ptr(), val, o) } }" + run_expect "compile swap pre-aliased overwrite Relaxed" 0 0 -- \ + rustc "$TC" $(core_flags_str "$CRATE_TARGET") --crate-type=lib \ + "-Zdump-mir=sync::atomic & built" -Zdump-mir-exclude-pass-number \ + "-Zdump-mir-dir=$WORK/swap-prealias-mir" --emit=metadata -o "$WORK/swap-prealias.rmeta" "$CRATE_ROOT" + run_expect "public swap pre-aliased overwrite Ordering rejected" 1 1 "did not forward Ordering parameter #0 unmodified" -- \ + "$CHECK_MIR" check-public-order "$WORK/swap-prealias-mir" "$u32_owner" u32 swap atomic_swap + cp "$WORK/atomic.u32.orig" "$CRATE_ATOMIC" + + replace_one "$CRATE_ATOMIC" "$ucas" \ + " unsafe { atomic_compare_exchange(self.as_ptr(), current, new, failure, success) }" + run_expect "compile compare_exchange swapped orderings" 0 0 -- \ + rustc "$TC" $(core_flags_str "$CRATE_TARGET") --crate-type=lib \ + "-Zdump-mir=sync::atomic & built" -Zdump-mir-exclude-pass-number \ + "-Zdump-mir-dir=$WORK/cas-swapped-mir" --emit=metadata -o "$WORK/cas.rmeta" "$CRATE_ROOT" + run_expect "public compare_exchange swapped orderings rejected" 1 1 "did not forward Ordering parameter #0 unmodified" -- \ + "$CHECK_MIR" check-public-order "$WORK/cas-swapped-mir" "$u32_owner" u32 compare_exchange atomic_compare_exchange + mv "$WORK/atomic.u32.orig" "$CRATE_ATOMIC" + elif [[ $CRATE_FAMILY == readonly ]]; then + # [R13-01] Core-level read-only fractional borrow controls for both AtomicBool and AtomicU32: + # potentially-writing CAS (including same-value current == new), atomic_store on af=1/2, and concurrent ordinary writes must all fail. + local roclient="$CRATE_SRC/sync/atomic/ch7_readonly.rs" + mutate_reject vf "readonly bool strong CAS matching actual value rejected" "$roclient" \ + "let strong = unsafe { ro_bool_compare_exchange(view, !initial, next, Ordering::Relaxed, Ordering::Relaxed) };" \ + "let strong = unsafe { ro_bool_compare_exchange(view, initial, next, Ordering::Relaxed, Ordering::Relaxed) };" \ + "$allow" 2 "Verifying function '${ATOMIC}ch7_readonly::ro_bool_local_round_trip'" "error: Cannot prove" + mutate_reject vf "readonly bool same-value strong CAS rejected" "$roclient" \ + "let strong = unsafe { ro_bool_compare_exchange(view, !initial, next, Ordering::Relaxed, Ordering::Relaxed) };" \ + "let strong = unsafe { ro_bool_compare_exchange(view, initial, initial, Ordering::Relaxed, Ordering::Relaxed) };" \ + "$allow" 2 "Verifying function '${ATOMIC}ch7_readonly::ro_bool_local_round_trip'" "error: Cannot prove" + mutate_reject vf "readonly bool weak CAS matching actual value rejected" "$roclient" \ + "let weak = unsafe { ro_bool_compare_exchange_weak(view, !initial, next, Ordering::Relaxed, Ordering::Relaxed) };" \ + "let weak = unsafe { ro_bool_compare_exchange_weak(view, initial, next, Ordering::Relaxed, Ordering::Relaxed) };" \ + "$allow" 2 "Verifying function '${ATOMIC}ch7_readonly::ro_bool_local_round_trip'" "error: Cannot prove" + mutate_reject vf "readonly bool concurrent ordinary write rejected" "$roclient" \ + " // CH7_RO_BOOL_LIVE" \ + $' // CH7_RO_BOOL_LIVE\n unsafe { *p = !initial };' \ + "$allow" 2 "Verifying function '${ATOMIC}ch7_readonly::ro_bool_local_round_trip'" "No matching heap chunks:" + mutate_reject vf "readonly bool atomic_store on fractional share rejected" "$roclient" \ + " // CH7_RO_BOOL_LIVE" \ + $' // CH7_RO_BOOL_LIVE\n unsafe { ro_bool_store(view, next, Ordering::Relaxed) };' \ + "$allow" 2 "Verifying function '${ATOMIC}ch7_readonly::ro_bool_local_round_trip'" "No matching heap chunks:" + + mutate_reject vf "readonly u32 strong CAS matching actual value rejected" "$roclient" \ + "let strong = unsafe { ro_u32_compare_exchange(view, mismatch, next, Ordering::Relaxed, Ordering::Relaxed) };" \ + "let strong = unsafe { ro_u32_compare_exchange(view, initial, next, Ordering::Relaxed, Ordering::Relaxed) };" \ + "$allow" 2 "Verifying function '${ATOMIC}ch7_readonly::ro_u32_local_round_trip'" "error: Cannot prove" + mutate_reject vf "readonly u32 same-value strong CAS rejected" "$roclient" \ + "let strong = unsafe { ro_u32_compare_exchange(view, mismatch, next, Ordering::Relaxed, Ordering::Relaxed) };" \ + "let strong = unsafe { ro_u32_compare_exchange(view, initial, initial, Ordering::Relaxed, Ordering::Relaxed) };" \ + "$allow" 2 "Verifying function '${ATOMIC}ch7_readonly::ro_u32_local_round_trip'" "error: Cannot prove" + mutate_reject vf "readonly u32 weak CAS matching actual value rejected" "$roclient" \ + "let weak = unsafe { ro_u32_compare_exchange_weak(view, mismatch, next, Ordering::Relaxed, Ordering::Relaxed) };" \ + "let weak = unsafe { ro_u32_compare_exchange_weak(view, initial, next, Ordering::Relaxed, Ordering::Relaxed) };" \ + "$allow" 2 "Verifying function '${ATOMIC}ch7_readonly::ro_u32_local_round_trip'" "error: Cannot prove" + mutate_reject vf "readonly u32 concurrent ordinary write rejected" "$roclient" \ + " // CH7_RO_U32_LIVE" \ + $' // CH7_RO_U32_LIVE\n unsafe { *p = after };' \ + "$allow" 2 "Verifying function '${ATOMIC}ch7_readonly::ro_u32_local_round_trip'" "No matching heap chunks:" + mutate_reject vf "readonly u32 atomic_store on fractional share rejected" "$roclient" \ + " // CH7_RO_U32_LIVE" \ + $' // CH7_RO_U32_LIVE\n unsafe { ro_u32_store(view, next, Ordering::Relaxed) };' \ + "$allow" 2 "Verifying function '${ATOMIC}ch7_readonly::ro_u32_local_round_trip'" "No matching heap chunks:" + + # [R14-01] Fractional read-only ordinary share (e.g. &'static u32 in PROT_READ .rodata) without full [1] writable backing cannot construct ro_u32_content. + mutate_reject vf "readonly u32 fractional read share without writable backing rejected" "$roclient" \ + "pred_ctor writable_u32_slot(slot: *u32, value: u32)(;) ="$'\n'" *slot |-> value;" \ + "pred_ctor writable_u32_slot(slot: *u32, value: u32)(;) ="$'\n'" [1/2](*slot |-> value);" \ + "$allow" 2 "Verifying function '${ATOMIC}ch7_readonly::prepare_u32_readonly'" "No matching heap chunks:" + + # Altered readonly helper witness body must fail thread-spec readonly bridge check. + dump_witness_mir + cp "$roclient" "$WORK/roclient.orig" + replace_one "$roclient" \ + " atomic_compare_exchange(receiver.as_ptr().cast::(), current as u8, new as u8, success, failure)" \ + " atomic_compare_exchange(receiver.as_ptr().cast::(), new as u8, current as u8, success, failure)" + run_expect "altered readonly bool CAS witness body rejected" 1 1 \ + "readonly helper witness body (bool::compare_exchange) changed" -- \ + "$CHECK_MIR" thread-spec readonly "$CRATE_SRC" "$WORK/owners-${HOST}.tsv" \ + "$WORK/baseline-report.tsv" "$CHECKS/pointer-shape.rs" "$CRATE_WITNESS_MIR" "$WORK/${HOST}-mir" + mv "$WORK/roclient.orig" "$roclient" + fi + cp "$WORK/baseline-report.tsv" "$CRATE_REPORT" +} + +run_extra_checker_controls() { + # [B5] Mutating atomic_store_release -> Relaxed in both manifests must fail independent entry derivation. + local mdir="$WORK/bad-manifests" + mkdir -p "$mdir" + cp "$PROOF/intrinsic-manifest.tsv" "$PROOF/permission-inventory.tsv" "$mdir/" + replace_one "$mdir/intrinsic-manifest.tsv" \ + $'atomic_store_release\tAtomic::store\tatomic_store\tyes\tatomic_store\tRelease' \ + $'atomic_store_release\tAtomic::store\tatomic_store\tyes\tatomic_store\tRelaxed' + replace_one "$mdir/permission-inventory.tsv" \ + $'atomic_store_release\tatomic_store\tatomic_store\tRelease\t' \ + $'atomic_store_release\tatomic_store\tatomic_store\tRelaxed\t' + run_expect "duplicate ordering in both manifests rejected" 1 1 \ + "manifest entry atomic_store_release mismatch" -- \ + "$CHECK_MIR" check-manifest "$mdir" "$BOOK" + + # [B6 & R10-04] LLVM IR checks: dual-invoke unwinding to resume, passing panic_cannot_unwind as argument, and passing join as argument must all fail. + local bad_ir="$WORK/bad_join.ll" + cat > "$bad_ir" <<'LL' +define void @join_boundary() personality ptr @rust_eh_personality { +start: + invoke void @_RNvNtCs1234_8platform9threading4join() + to label %bb1 unwind label %resume_pad + +bb1: + invoke void @_RNvCs1234_5other6helper() + to label %bb2 unwind label %terminate + +resume_pad: + %lp0 = landingpad { ptr, i32 } + cleanup + resume { ptr, i32 } %lp0 + +terminate: + %lp1 = landingpad { ptr, i32 } + filter [0 x ptr] zeroinitializer + call void @_RNvNtCs924n2ZKbDq5_4core9panicking19panic_cannot_unwind() + unreachable + +bb2: + ret void +} +LL + run_expect "dual-invoke join unwinding to resume rejected" 1 1 \ + "unwind path from invoke reaches resume" -- \ + "$CHECK_MIR" check-ir "$bad_ir" join_boundary:join + + local arg_abort_ir="$WORK/bad_arg_abort.ll" + cat > "$arg_abort_ir" <<'LL' +define void @join_boundary() personality ptr @rust_eh_personality { +start: + invoke void @_RNvNtCs1234_8platform9threading4join() + to label %bb1 unwind label %terminate + +terminate: + %lp1 = landingpad { ptr, i32 } + filter [0 x ptr] zeroinitializer + call void @event(ptr @_RNvNtCs924n2ZKbDq5_4core9panicking19panic_cannot_unwind) + unreachable + +bb1: + ret void +} +LL + run_expect "panic_cannot_unwind passed as argument rejected" 1 1 \ + "reached unreachable without panic_cannot_unwind" -- \ + "$CHECK_MIR" check-ir "$arg_abort_ir" join_boundary:join + + local arg_join_ir="$WORK/bad_arg_join.ll" + cat > "$arg_join_ir" <<'LL' +define void @join_boundary() personality ptr @rust_eh_personality { +start: + invoke void @event(ptr @_RNvNtCs1234_8platform9threading4join) + to label %bb1 unwind label %terminate + +terminate: + %lp1 = landingpad { ptr, i32 } + filter [0 x ptr] zeroinitializer + call void @_RNvNtCs924n2ZKbDq5_4core9panicking19panic_cannot_unwind() + unreachable + +bb1: + ret void +} +LL + run_expect "platform join passed as argument rejected" 1 1 \ + "did not find platform join invoke" -- \ + "$CHECK_MIR" check-ir "$arg_join_ir" join_boundary:join + + # [R11-05] Real rustc-compiled Unicode homoglyph module (Punycode `u` tag in v0 mangling) must NOT match ASCII platform::threading::join. + local uni_dir="$WORK/unicode-platform" + mkdir -p "$uni_dir" + printf 'pub mod thread\xc4\xb1ng {\n #[inline(never)]\n pub fn join() { std::hint::black_box(()); }\n}\n' > "$uni_dir/plat.rs" + printf 'extern crate platform;\npub extern "C" fn join_boundary() {\n platform::thread\xc4\xb1ng::join();\n}\n' > "$uni_dir/caller.rs" + run_expect "compile Unicode homoglyph platform crate" 0 0 -- \ + rustc "$TC" --edition=2024 --crate-name=platform --crate-type=rlib -Cpanic=unwind \ + "$uni_dir/plat.rs" -o "$uni_dir/libplatform.rlib" + run_expect "emit LLVM IR calling Unicode homoglyph join" 0 0 -- \ + rustc "$TC" --edition=2024 --crate-type=rlib -Cpanic=unwind \ + --extern="platform=$uni_dir/libplatform.rlib" --emit=llvm-ir \ + "$uni_dir/caller.rs" -o "$uni_dir/caller.ll" + run_expect "rustc-compiled Unicode homoglyph module rejected by check-ir" 1 1 \ + "did not find platform join invoke" -- \ + "$CHECK_MIR" check-ir "$uni_dir/caller.ll" join_boundary:join + + local puny_ir="$WORK/bad_punycode_join.ll" + cat > "$puny_ir" <<'LL' +define void @join_boundary() personality ptr @rust_eh_personality { +start: + invoke void @_RNvNtCs1234_8platformu9threading4join() + to label %bb1 unwind label %terminate + +terminate: + %lp1 = landingpad { ptr, i32 } + filter [0 x ptr] zeroinitializer + call void @_RNvNtCs924n2ZKbDq5_4core9panicking19panic_cannot_unwind() + unreachable + +bb1: + ret void +} +LL + run_expect "Punycode u9threading v0 symbol rejected by check-ir" 1 1 \ + "did not find platform join invoke" -- \ + "$CHECK_MIR" check-ir "$puny_ir" join_boundary:join + + # [R12-04] Local function `join` inside `fn threading()` in crate `platform` must be rejected under BOTH v0 and legacy mangling. + local fn_mod_dir="$WORK/fn-local-join" + mkdir -p "$fn_mod_dir" + cat > "$fn_mod_dir/plat.rs" <<'RS' +pub fn threading() -> fn() { + #[inline(never)] + pub fn join() { std::hint::black_box(()); } + join +} +pub extern "C" fn join_boundary() { + threading()(); +} +RS + cat > "$fn_mod_dir/direct.rs" <<'RS' +pub fn threading() { + #[inline(never)] + fn join() { std::hint::black_box(()); } + #[unsafe(no_mangle)] + pub extern "C" fn join_boundary() { + join(); + } + std::hint::black_box(join_boundary as extern "C" fn()); +} +RS + for mv in v0 legacy; do + run_expect "emit $mv IR for local join inside fn threading" 0 0 -- \ + rustc "$TC" --edition=2024 --crate-name=platform --crate-type=rlib -Cpanic=unwind \ + -Z unstable-options "-Csymbol-mangling-version=$mv" --emit=llvm-ir \ + "$fn_mod_dir/direct.rs" -o "$fn_mod_dir/direct_${mv}.ll" + run_expect "$mv local fn threading::join rejected by check-ir" 1 1 \ + "did not find platform join invoke" -- \ + "$CHECK_MIR" check-ir "$fn_mod_dir/direct_${mv}.ll" join_boundary:join + done + + # [B2 & R10-05] Shared check-kani-log validator must reject entry-only cover, wrong location, wrong function suffix, and pre-call macro cover. + local kexp="$WORK/kani_one.expected.txt" + printf 'sync::atomic::verify::rmw_u32::swap\n' > "$kexp" + local swap_line + swap_line=$(grep -n -F 'integer_rmw_contracts!(rmw_u32, u32);' "$CORE/sync/atomic.rs" | cut -d: -f1) + + local entry_log="$WORK/entry_only.log" + cat > "$entry_log" < "$bad_loc_log" <<'LOG' +Checking harness sync::atomic::verify::rmw_u32::swap... +Check 1: sync::atomic::verify::rmw_u32::swap.cover.1 + - Status: SATISFIED + - Description: "atomic operation returned" + - Location: library/core/src/sync/atomic.rs:1:1 in function sync::atomic::verify::rmw_u32::swap +SUMMARY: + ** 1 of 1 cover properties satisfied +VERIFICATION:- SUCCESSFUL +LOG + run_expect "wrong source location Kani cover rejected by check-kani-log" 1 1 \ + "MISSING POST-CALL COVER sync::atomic::verify::rmw_u32::swap" -- \ + "$CHECK_MIR" check-kani-log "$bad_loc_log" "$kexp" "$CORE/sync/atomic.rs" "$CORE/intrinsics/mod.rs" + + local bad_fn_log="$WORK/bad_fn.log" + cat > "$bad_fn_log" < "$good_log" <() {\n let _ = cell.$method($($arg,)* any_ordering());\n return;\n }\n kani::cover(true, "atomic operation returned");' + run_expect "branching early-return macro cover rejected by check-kani-log" 1 1 \ + "control-flow keyword" -- \ + "$CHECK_MIR" check-kani-log "$good_log" "$kexp" "$branch_atomic" "$CORE/intrinsics/mod.rs" + + # [R12-03] Helper macro hiding a conditional branch and early return inside rmw_contract must also fail. + local helper_macro_atomic="$WORK/helper_macro_cover_atomic.rs" + cp "$CORE/sync/atomic.rs" "$helper_macro_atomic" + replace_one "$helper_macro_atomic" \ + $' macro_rules! rmw_contract {\n ($target:ty, $method:ident, $initial:expr $(, $arg:expr)*) => {\n #[allow(deprecated)]\n #[kani::proof_for_contract(Atomic::<$target>::$method)]\n pub fn $method() {\n let cell = $initial;\n let _ = cell.$method($($arg,)* any_ordering());\n kani::cover(true, "atomic operation returned");\n }\n };\n }' \ + $' macro_rules! sneaky_branch { ($e:expr) => { if kani::any::() { let _ = $e; return; } }; }\n macro_rules! rmw_contract {\n ($target:ty, $method:ident, $initial:expr $(, $arg:expr)*) => {\n #[allow(deprecated)]\n #[kani::proof_for_contract(Atomic::<$target>::$method)]\n pub fn $method() {\n let cell = $initial;\n sneaky_branch!(cell.$method($($arg,)* any_ordering()));\n kani::cover(true, "atomic operation returned");\n }\n };\n }' + run_expect "helper-macro branching cover rejected by check-kani-log" 1 1 \ + "unapproved macro invocation" -- \ + "$CHECK_MIR" check-kani-log "$good_log" "$kexp" "$helper_macro_atomic" "$CORE/intrinsics/mod.rs" + + # [R13-02] check-kani-log must reject dropped/misconfigured integer widths, swapped orderings, and omitted matrix calls in intrinsics/mod.rs. + local intr_exp="$WORK/kani_intr_load.expected.txt" + printf 'intrinsics::verify::harness_intrinsic_atomic_load_relaxed\n' > "$intr_exp" + local intr_load_line + intr_load_line=$(grep -n -F 'atomic_load_harness!(harness_intrinsic_atomic_load_relaxed, AtomicOrdering::Relaxed);' "$CORE/intrinsics/mod.rs" | cut -d: -f1) + local intr_good_log="$WORK/kani_intr_load_good.log" + cat > "$intr_good_log" < "$stale_vf/bin/$tbin" + chmod +x "$stale_vf/bin/$tbin" + done + : > "$stale_vf/bin/rust/std/lib.rsspec" + : > "$stale_vf/tests/rust/unverified/platform/spec/lib.rsspec" + printf '0000000000000000000000000000000000000000000000000000000000000000\n' > "$stale_vf/complete" + run_expect "stale ATOMIC_VERIFAST_DIR build key rejected" 1 1 \ + "Incomplete or stale ATOMIC_VERIFAST_DIR" -- \ + env ATOMIC_VERIFAST_DIR="$stale_vf" bash "$PROOF/build-linux-tools.sh" + + # [B7 & R10-06] Pure-Bash update.sh rollback (both tracked and untracked with missing file) and clean retry. + local udir="$WORK/update-fault" + rm -rf "$udir" + git clone --quiet --local --shared --sparse "$REPO" "$udir/repo" + local proof="$udir/repo/fixture/proofs/core/sync/atomic.rs" + local orig="$proof/original" + local up="$udir/repo/fixture/library/core/src" + mkdir -p "$orig/intrinsics" "$up/sync" "$up/intrinsics" + local p + for p in lib.rs sync/atomic.rs sync/atomic_load_volatile.md sync/atomic_store_volatile.md intrinsics/mod.rs; do + printf 'old %s\n' "$p" > "$orig/${p#sync/}" + printf 'new %s\n' "$p" > "$up/$p" + done + git -C "$udir/repo" show HEAD:library/core/src/lib.rs > "$orig/lib.rs" + cp "$PROOF/check-sources.sh" "$proof/check-sources.sh" + cp "$PROOF/update.sh" "$proof/update.sh" + git -C "$udir/repo" -c user.name=test -c user.email=test@example.com add --sparse -f fixture/proofs/core/sync/atomic.rs/original + git -C "$udir/repo" -c user.name=test -c user.email=test@example.com commit --quiet -m "seed snapshots" + find "$udir/repo/fixture" -type f -printf '/%P\n' | sed 's|^/|/fixture/|' >> "$udir/repo/.git/info/exclude" + test -z "$(git -C "$udir/repo" status --porcelain)" + + # Fault 1: 3rd temp-copy failure before any live publish + cp "$PROOF/update.sh" "$proof/update.sh" + replace_one "$proof/update.sh" ' cp -p "$stage/$rel" "$tmp"' \ + $' if [[ $rel == atomic_load_volatile.md ]]; then false; fi\n cp -p "$stage/$rel" "$tmp"' + run_expect "update.sh aborts cleanly on 3rd copy failure" 1 2 \ + "Previous snapshot retained. Recovery path: " "Snapshot update aborted and rolled back." -- \ + bash "$proof/update.sh" + test -z "$(git -C "$udir/repo" status --porcelain)" + + # Fault 2: 3rd mv failure mid-publish rolls back files 1..2 cleanly and allows immediate retry + cp "$PROOF/update.sh" "$proof/update.sh" + replace_one "$proof/update.sh" ' mv -f "${staged_temps[$rel]}" "$dest"' \ + $' if [[ $rel == atomic_load_volatile.md ]]; then false; fi\n mv -f "${staged_temps[$rel]}" "$dest"' + run_expect "update.sh rolls back cleanly on 3rd publish failure" 1 2 \ + "Previous snapshot retained. Recovery path: " "Snapshot update aborted and rolled back." -- \ + bash "$proof/update.sh" + test -z "$(git -C "$udir/repo" status --porcelain)" + for p in sync/atomic.rs sync/atomic_load_volatile.md sync/atomic_store_volatile.md intrinsics/mod.rs; do + grep -Fq "old $p" "$orig/${p#sync/}" + done + + # [R11-07] Fault 2b: SIGTERM immediately after the first mv on tracked existing files must roll back original/lib.rs cleanly. + cp "$PROOF/update.sh" "$proof/update.sh" + replace_one "$proof/update.sh" ' mv -f "${staged_temps[$rel]}" "$dest"' \ + $' mv -f "${staged_temps[$rel]}" "$dest"\n if [[ $rel == lib.rs ]]; then kill -TERM $$; fi' + run_expect "update.sh rolls back tracked files on SIGTERM after 1st mv" 143 2 \ + "Previous snapshot retained. Recovery path: " "Snapshot update aborted and rolled back." -- \ + bash "$proof/update.sh" + test -z "$(git -C "$udir/repo" status --porcelain)" + for p in sync/atomic.rs sync/atomic_load_volatile.md sync/atomic_store_volatile.md intrinsics/mod.rs; do + grep -Fq "old $p" "$orig/${p#sync/}" + done + + # [R12-05] Fault 2c: If restoring the 1st file fails during rollback, cleanup must continue restoring files 2..5, + # remove stray .restore temp files, and report rollback verification failure with the manual recovery path. + cp "$PROOF/update.sh" "$proof/update.sh" + replace_one "$proof/update.sh" ' mv -f "${staged_temps[$rel]}" "$dest"' \ + $' mv -f "${staged_temps[$rel]}" "$dest"\n if [[ $rel == atomic_load_volatile.md ]]; then kill -TERM $$; fi' + replace_one "$proof/update.sh" '&& cp -p "$backup/$rel" "$rtmp"' \ + '&& { [[ $rel != lib.rs ]] && cp -p "$backup/$rel" "$rtmp"; }' + run_expect "update.sh partial restore failure restores remaining files and reports manual recovery" 143 2 \ + "Previous snapshot retained. Recovery path: " "ERROR: Snapshot rollback verification failed. Manual recovery path: " -- \ + bash "$proof/update.sh" + test -z "$(find "$orig" -maxdepth 2 -name '.restore.*' -o -name '.update.*')" + for p in sync/atomic.rs sync/atomic_load_volatile.md sync/atomic_store_volatile.md intrinsics/mod.rs; do + grep -Fq "old $p" "$orig/${p#sync/}" + done + # Restore lib.rs from HEAD before clean retry test. + git -C "$udir/repo" checkout -- fixture/proofs/core/sync/atomic.rs/original/lib.rs + test -z "$(git -C "$udir/repo" status --porcelain)" + + # Clean retry after rollback must succeed immediately with zero manual cleanup + cp "$PROOF/update.sh" "$proof/update.sh" + run_expect "update.sh clean retry succeeds after rollback" 0 1 \ + "Previous snapshot retained. Recovery path: " -- \ + bash "$proof/update.sh" + for p in lib.rs sync/atomic.rs sync/atomic_load_volatile.md sync/atomic_store_volatile.md intrinsics/mod.rs; do + cmp -s "$orig/${p#sync/}" "$up/$p" + done + + # [R10-06 & R11-07] Fault 3 & 3b: Untracked original/ missing lib.rs + 3rd publish failure AND SIGTERM immediately after 1st mv must remove newly created lib.rs. + local udir2="$WORK/update-fault-missing" + rm -rf "$udir2" + git clone --quiet --local --shared --sparse "$REPO" "$udir2/repo" + local proof2="$udir2/repo/fixture/proofs/core/sync/atomic.rs" + local orig2="$proof2/original" + local up2="$udir2/repo/fixture/library/core/src" + mkdir -p "$orig2/intrinsics" "$up2/sync" "$up2/intrinsics" + for p in lib.rs sync/atomic.rs sync/atomic_load_volatile.md sync/atomic_store_volatile.md intrinsics/mod.rs; do + printf 'new %s\n' "$p" > "$up2/$p" + done + # Seed 4 untracked files matching upstream (so dirty check passes) and omit lib.rs! + for p in sync/atomic.rs sync/atomic_load_volatile.md sync/atomic_store_volatile.md intrinsics/mod.rs; do + cp "$up2/$p" "$orig2/${p#sync/}" + done + cp "$PROOF/check-sources.sh" "$proof2/check-sources.sh" + cp "$PROOF/update.sh" "$proof2/update.sh" + replace_one "$proof2/update.sh" ' mv -f "${staged_temps[$rel]}" "$dest"' \ + $' if [[ $rel == atomic_load_volatile.md ]]; then false; fi\n mv -f "${staged_temps[$rel]}" "$dest"' + local before_list after_list + before_list=$(cd "$orig2" && find . -mindepth 1 | sort) + run_expect "update.sh rolls back newly created file on 3rd publish failure" 1 2 \ + "Previous snapshot retained. Recovery path: " "Snapshot update aborted and rolled back." -- \ + bash "$proof2/update.sh" + after_list=$(cd "$orig2" && find . -mindepth 1 | sort) + test "$before_list" = "$after_list" + test ! -e "$orig2/lib.rs" + + cp "$PROOF/update.sh" "$proof2/update.sh" + replace_one "$proof2/update.sh" ' mv -f "${staged_temps[$rel]}" "$dest"' \ + $' mv -f "${staged_temps[$rel]}" "$dest"\n if [[ $rel == lib.rs ]]; then kill -TERM $$; fi' + run_expect "update.sh rolls back newly created file on SIGTERM after 1st mv" 143 2 \ + "Previous snapshot retained. Recovery path: " "Snapshot update aborted and rolled back." -- \ + bash "$proof2/update.sh" + after_list=$(cd "$orig2" && find . -mindepth 1 | sort) + test "$before_list" = "$after_list" + test ! -e "$orig2/lib.rs" + + cp "$PROOF/update.sh" "$proof2/update.sh" + run_expect "update.sh clean retry after missing-file rollback succeeds" 0 1 \ + "Previous snapshot retained. Recovery path: " -- \ + bash "$proof2/update.sh" + for p in lib.rs sync/atomic.rs sync/atomic_load_volatile.md sync/atomic_store_volatile.md intrinsics/mod.rs; do + cmp -s "$orig2/${p#sync/}" "$up2/$p" + done + + # [R13-03] Fault 4: Failing `git ls-files` during untracked preflight must abort before publishing + # and preserve untracked local edits in original/atomic.rs byte-for-byte. + local udir3="$WORK/update-fault-lsfiles" + rm -rf "$udir3" + git clone --quiet --local --shared --sparse "$REPO" "$udir3/repo" + local proof3="$udir3/repo/fixture/proofs/core/sync/atomic.rs" + local orig3="$proof3/original" + local up3="$udir3/repo/fixture/library/core/src" + mkdir -p "$orig3/intrinsics" "$up3/sync" "$up3/intrinsics" + for p in lib.rs sync/atomic.rs sync/atomic_load_volatile.md sync/atomic_store_volatile.md intrinsics/mod.rs; do + printf 'local-edit %s\n' "$p" > "$orig3/${p#sync/}" + printf 'upstream-new %s\n' "$p" > "$up3/$p" + done + cp "$PROOF/check-sources.sh" "$proof3/check-sources.sh" + cp "$PROOF/update.sh" "$proof3/update.sh" + local fake_git_dir="$WORK/fake-git-lsfiles" + rm -rf "$fake_git_dir" + mkdir -p "$fake_git_dir" + local real_git + real_git=$(command -v git) + cat > "$fake_git_dir/git" <&2 + exit 2 +fi +exec "$real_git" "\$@" +GITWRAP + chmod +x "$fake_git_dir/git" + local before_atomic_sha after_atomic_sha + before_atomic_sha=$(sha256sum "$orig3/atomic.rs" | cut -d' ' -f1) + run_expect "update.sh aborts without publishing when git ls-files fails" 2 1 \ + "simulated git ls-files failure" -- \ + env PATH="$fake_git_dir:$PATH" bash "$proof3/update.sh" + after_atomic_sha=$(sha256sum "$orig3/atomic.rs" | cut -d' ' -f1) + test "$before_atomic_sha" = "$after_atomic_sha" + if grep -Fq "Previous snapshot retained" "$LAST_LOG"; then + echo "FAIL update.sh entered publish phase after git ls-files failure" >&2 + exit 1 + fi +} + +run_thread_controls() { + local name=$1 parent=$2; shift 2 + local fixture="$CHECKS/threads/${name}.rs" + run_expect "$name two-worker proof" 0 2 "0 errors found" "Verifying function '$parent'" -- \ + "${THREAD_VF[@]}" "$fixture" + + local marker=" // CH7_B_OUTSTANDING" + local mline + mline=$(grep -n -F "$marker" "$fixture" | cut -d: -f1) + local target_line=$((mline + 1)) + + local spec + for spec in "$@" "early_end|//@ end_lifetime(k);|lifetime_token(k)"; do + IFS='|' read -r label stmt missing <<< "$spec" + local mpath="$WORK/${name}_${label}.rs" + cp "$fixture" "$mpath" + replace_one "$mpath" "$marker" "${marker}"$'\n'" ${stmt}" + run_expect "$name $label" 1 2 \ + "note: Verifying function '$parent'" "No matching heap chunks: $missing" -- \ + "${THREAD_VF[@]}" "$mpath" + "$CHECK_MIR" check-line-diag "$LAST_LOG" "$mpath" "$target_line" any + done + + if [[ $name == u32 ]]; then + local fpath="$WORK/full_token.rs" + awk ' + />>\(second_load\)\(transfer/ { in_blk = 1 } + /unsafe \{ fork_boundary/ { in_blk = 0 } + in_blk { n += gsub(/1\/8/, "1") } + { print } + END { if (n != 5) exit 2 } + ' "$fixture" > "$fpath" + run_expect "worker requests full token" 1 3 \ + "note: Verifying function 'borrowed_pair'" \ + "No matching heap chunks: [1]lifetime_token(k)" \ + "close transfer(k, 1, p)" -- "${THREAD_VF[@]}" "$fpath" + fi +} + +run_readonly_thread_controls() { + local fixture="$CHECKS/threads/readonly.rs" + run_expect "readonly two-worker proof" 0 3 \ + "0 errors found" "Verifying function 'bool_readonly_pair'" "Verifying function 'u32_readonly_pair'" -- \ + "${RO_THREAD_VF[@]}" "$fixture" + + # [R13-01] Two-worker concurrent read/CAS negative controls for BOTH AtomicBool and AtomicU32. + local ro_case + for ro_case in \ + "bool_strong_cas_write|let strong = slot.compare_exchange(false, false, Ordering::Relaxed, Ordering::Relaxed);|let strong = slot.compare_exchange(true, false, Ordering::Relaxed, Ordering::Relaxed);|ro_bool_worker_true|error: Cannot prove" \ + "bool_strong_cas_same_val|let strong = slot.compare_exchange(false, false, Ordering::Relaxed, Ordering::Relaxed);|let strong = slot.compare_exchange(true, true, Ordering::Relaxed, Ordering::Relaxed);|ro_bool_worker_true|error: Cannot prove" \ + "bool_weak_cas_write|let weak = slot.compare_exchange_weak(false, true, Ordering::Relaxed, Ordering::Relaxed);|let weak = slot.compare_exchange_weak(true, false, Ordering::Relaxed, Ordering::Relaxed);|ro_bool_worker_true|error: Cannot prove" \ + "bool_atomic_store|// CH7_RO_BOOL_WORKER_A|slot.store(false, Ordering::Relaxed);|ro_bool_worker_true|No matching heap chunks:" \ + "bool_ordinary_write|// CH7_RO_BOOL_WORKER_B|unsafe { *(ptr as *mut u8) = 1u8; };|ro_plain_u8_worker|No matching heap chunks:" \ + "bool_parent_write_live|// CH7_RO_BOOL_A_OUTSTANDING|unsafe { *p = !initial };|bool_readonly_pair|No matching heap chunks:" \ + "bool_early_end_live|// CH7_RO_BOOL_A_OUTSTANDING|//@ end_lifetime(k);|bool_readonly_pair|No matching heap chunks: lifetime_token(k)" \ + "u32_strong_cas_write|let strong = slot.compare_exchange(1, 0, Ordering::Relaxed, Ordering::Relaxed);|let strong = slot.compare_exchange(0, 2, Ordering::Relaxed, Ordering::Relaxed);|ro_u32_worker_zero|error: Cannot prove" \ + "u32_strong_cas_same_val|let strong = slot.compare_exchange(1, 0, Ordering::Relaxed, Ordering::Relaxed);|let strong = slot.compare_exchange(0, 0, Ordering::Relaxed, Ordering::Relaxed);|ro_u32_worker_zero|error: Cannot prove" \ + "u32_weak_cas_write|let weak = slot.compare_exchange_weak(1, 2, Ordering::Relaxed, Ordering::Relaxed);|let weak = slot.compare_exchange_weak(0, 2, Ordering::Relaxed, Ordering::Relaxed);|ro_u32_worker_zero|error: Cannot prove" \ + "u32_atomic_store|// CH7_RO_U32_WORKER_A|slot.store(2, Ordering::Relaxed);|ro_u32_worker_zero|No matching heap chunks:" \ + "u32_ordinary_write|// CH7_RO_U32_WORKER_B|unsafe { *(ptr as *mut u32) = 1u32; };|ro_plain_u32_worker|No matching heap chunks:" \ + "u32_parent_write_live|// CH7_RO_U32_A_OUTSTANDING|unsafe { *p = 99 };|u32_readonly_pair|No matching heap chunks:" \ + "u32_early_end_live|// CH7_RO_U32_A_OUTSTANDING|//@ end_lifetime(k);|u32_readonly_pair|No matching heap chunks: lifetime_token(k)"; do + IFS='|' read -r rlabel rold rnew rfn rerr <<< "$ro_case" + local rpath="$WORK/ro_${rlabel}.rs" + cp "$fixture" "$rpath" + replace_one "$rpath" "$rold" "$rnew" + run_expect "readonly $rlabel" 1 2 \ + "Verifying function '$rfn'" "$rerr" -- "${RO_THREAD_VF[@]}" "$rpath" + done +} + +run_negative_tool_tests +run_extra_checker_controls +build_safety_macro +: > "$WORK/interfaces.rsspec" + +dump_original_mir "$HOST" +for family in "${FAMILIES[@]}"; do + setup_crate "$HOST" "$family" + attach_clients + run_production_controls + if [[ $family == readonly ]]; then + dump_witness_mir + "$CHECK_MIR" thread-spec "$family" "$CRATE_SRC" "$WORK/owners-${HOST}.tsv" \ + "$CRATE_REPORT" "$CHECKS/pointer-shape.rs" "$CRATE_WITNESS_MIR" "$WORK/${HOST}-mir" > "$WORK/readonly.rsspec" + elif [[ $family != pointer-rmw ]]; then + dump_witness_mir + "$CHECK_MIR" thread-spec "$family" "$CRATE_SRC" "$WORK/owners-${HOST}.tsv" \ + "$CRATE_REPORT" "$CHECKS/pointer-shape.rs" "$CRATE_WITNESS_MIR" >> "$WORK/interfaces.rsspec" + fi +done + +build_platform_runtime +run_thread_controls u32 borrowed_pair \ + "word_read|let _old = unsafe { *p };|[_]points_to" \ + "word_write|unsafe { *p = 0 };|points_to_" \ + "byte_read|let _old = unsafe { *_byte };|[_]points_to" \ + "byte_write|unsafe { *_byte = 0 };|points_to_" +run_thread_controls boolean bool_pair \ + "bool_read|let _old = unsafe { *p };|[_]points_to" \ + "bool_write|unsafe { *p = true };|points_to_" \ + "byte_read|let _old = unsafe { *byte };|[_]points_to" +run_thread_controls pointer pointer_pair \ + "slot_read|let _old = unsafe { *p };|[_]points_to<*u8>" \ + "slot_write|unsafe { *p = initial };|points_to_<*u8>" +run_thread_controls width width_pair \ + "narrow_read|if mode == 0 { let _old = unsafe { *next }; }|[_]points_to" \ + "narrow_write|if mode == 1 { unsafe { *next = 2 }; }|points_to_" \ + "wide_write|if mode >= 2 { unsafe { *wide = 2 }; }|points_to_" +run_readonly_thread_controls + +# [R11-02] End-to-end VeriFast check on exported `receiver_value`/`self_value` pointer CAS interface. +RENAME_BIN="$WORK/bin-rename" +rm -rf "$RENAME_BIN" +cp -a "$TOOLS/bin" "$RENAME_BIN" +RENAME_SPEC="$RENAME_BIN/rust/std/lib.rsspec" +replace_one "$RENAME_SPEC" $'enum Ordering {\n Relaxed,\n SeqCst\n }' \ + 'enum Ordering { Relaxed, Release, Acquire, AcqRel, SeqCst }' +replace_one "$RENAME_SPEC" ' Ordering::Relaxed => false,' \ + $' Ordering::Relaxed => false,\n Ordering::Release => false,\n Ordering::Acquire => false,\n Ordering::AcqRel => false,' +cat "$WORK/rename-ptr.rsspec" >> "$RENAME_SPEC" +cat > "$WORK/rename_cas_client.rs" <<'RS' +#![no_std] +#![allow(dead_code)] +use core::sync::atomic::{AtomicPtr, Ordering}; + +unsafe fn check_old_ptr<'a>(atomic: &'a AtomicPtr, expected: *mut u8, replacement: *mut u8) +//@ req [?q]lifetime_token('a) &*& [_]frac_borrow('a, std::sync::atomic::thread_pointer_content::(ref_origin(atomic))) &*& [_]frac_borrow('a, ref_initialized_(atomic)) &*& expected as usize != replacement as usize; +//@ ens [q]lifetime_token('a); +//@ on_unwind_ens false; +{ + let outcome = atomic.compare_exchange(expected, replacement, Ordering::Relaxed, Ordering::Relaxed); + //@ open std::result::Result_own::<*u8, *u8>(currentThread, outcome); + /*@ match outcome { + Result::Ok(v) => { + assert v as usize == expected as usize; + open raw_ptr_own::()(currentThread, v); + } + Result::Err(v) => { + open raw_ptr_own::()(currentThread, v); + } + } @*/ +} +RS +RENAME_VF=( + "$RENAME_BIN/verifast" -shared -verbose 1 + -rustc_arg "@$THREAD_FLAGS" + -rustc_args "--edition=2024 -Cpanic=unwind -Cdebug-assertions=no" +) +run_expect "receiver_value/self_value CAS client proves old pointer" 0 2 \ + "0 errors found" "Verifying function 'check_old_ptr'" -- \ + "${RENAME_VF[@]}" "$WORK/rename_cas_client.rs" +replace_one "$WORK/rename_cas_client.rs" \ + "assert v as usize == expected as usize;" \ + "assert v as usize == replacement as usize;" +run_expect "receiver_value/self_value CAS client rejects replacement pointer" 1 2 \ + "Verifying function 'check_old_ptr'" "error: Assertion might not hold." -- \ + "${RENAME_VF[@]}" "$WORK/rename_cas_client.rs" diff --git a/verifast-proofs/core/sync/atomic.rs/README.md b/verifast-proofs/core/sync/atomic.rs/README.md new file mode 100644 index 0000000000000..312850c84ad7c --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/README.md @@ -0,0 +1,173 @@ +# Challenge 7 · Atomic storage and data races + +This proof accompanies the Kani contracts for PR #683. It checks how the public atomic methods acquire and return permission to a particular slot, from the `from_ptr` constructor through the ordered compiler intrinsic. It also verifies clients that share one reference between two POSIX workers and recover the ordinary storage. + +The suite verifies `x86_64-unknown-linux-gnu` and `aarch64-unknown-linux-gnu`. Both have native 8-bit CAS. AArch64 supplies the 128-bit cases. The thread proofs, linked examples and negative controls run on the x86-64 host. + +> **Real upstream stdlib bug found during verification ([`rust-lang/rust#166918`](https://github.com/rust-lang/rust/issues/166918)):** On `EMULATE_ATOMIC_BOOL` targets (`riscv32`, `riscv64`, `loongarch32`, `loongarch64`), `AtomicBool::compare_exchange` and `compare_exchange_weak` unconditionally perform an atomic RMW write (`fetch_or(false)` or `swap(new)`) even when the comparison fails and returns `Err(old)`. This contradicts Rust's documented atomic memory model (*"A `compare_exchange` or `compare_exchange_weak` that does not succeed is not considered a write"*) and triggers a Data Race UB under Miri when paired with a concurrent non-atomic read (reproduced on `rustc 1.102.0-nightly (852931e6d 2026-12-01)` for `riscv64gc` and `loongarch64`, while passing on `x86_64`). Per [General Rules](../../../../doc/src/general-rules.md#solution-requirements), runtime stdlib logic cannot be modified prior to upstream incorporation; this companion therefore restricts its target scope to native 8-bit CAS targets (`x86_64-unknown-linux-gnu` and `aarch64-unknown-linux-gnu`). See the standalone reproducer in [`checks/upstream_bug_166918_miri.rs`](checks/upstream_bug_166918_miri.rs). + +## Run from the repository root + +```sh +bash verifast-proofs/check-verifast-proofs.sh +bash verifast-proofs/check-verifast-proofs-negative.sh +``` + +To iterate on the atomic proof alone, use its [positive entrypoint](verify.sh) or [negative entrypoint](../atomic.rs-negative/verify.sh). Both compare the five [source snapshots](original/) with `library/core/src` via [check-sources.sh](check-sources.sh) before starting the toolchain, create disposable directories for the annotated crate, compiler output and mutations, and run all checks sequentially without Python dependencies. + +The [builder](build-linux-tools.sh) runs on Linux x86-64 with rustup, Cargo, GNU make, a C toolchain, Git, curl, tar, awk and jq. A cold run downloads and verifies the pinned VeriFast, decoder and OCaml dependencies, installs missing components of `nightly-2026-11-21` and builds the verifier, MIR exporter and refinement checker. `ATOMIC_TOOL_CACHE` selects the persistent build directory (default: `atomic-verifast-5b7d6f52` under `RUNNER_TEMP` or `$HOME/.verifast`). `ATOMIC_VERIFAST_DIR` selects an existing patched installation whose `complete` build key matches the current patch, builder and platform lockfile. + +After an intentional upstream source change, run `bash verifast-proofs/core/sync/atomic.rs/update.sh`, review the [annotation diffs](specs/) against the new sources and rerun both entrypoints. + +## Proof structure + +1. Pick a row in the [constructor manifest](part1-manifest.tsv), [permission inventory](permission-inventory.tsv) or [intrinsic manifest](intrinsic-manifest.tsv). The zero-dependency Rust checker [check_mir.rs](checks/check_mir.rs) verifies all entries against the [challenge specification](../../../../doc/src/challenges/0007-atomic-types.md), follows every public method to its helper and instantiated compiler intrinsic in the live MIR export (with calling basic blocks), and traces compiled `Ordering` branches and return/unwind tails. +2. Read the [layered annotations](specs/). Each run overlays only the contracts for one slot interpretation (`access`, `rmw`, `pointer-access`, `pointer-rmw`, `u32`, `readonly`) on a fresh copy of `core`, checks production token identity with [source_tokens.rs](tool-tests/source_tokens.rs), verifies native MIR refinement, and runs VeriFast on the selected production roots and clients. +3. Follow `borrowed_pair` through both joins in [checks/threads/](checks/threads/). Worker interfaces are extracted from verified single-call witnesses after checking exact forwarding bodies and single MIR call edges, and the host examples link and execute against repository `core`. +4. Read [TRUSTED-BASE.md](TRUSTED-BASE.md) for trusted boundaries, the 15-file / 124-hunk `verifast-core.patch` audit table, and CTFE/projection checks. The [negative entrypoint](../atomic.rs-negative/verify.sh) names the expected failure obligation for every mutation. + +## Challenge 7 requirements and coverage + +| Obligation | Verification | Evidence | +| --- | --- | --- | +| Part 1, all 12 unsafe constructors | `from_ptr` designates the input slot and `as_ptr` projects the same address across all 12 atomic types (including `AtomicI128` / `AtomicU128` on AArch64). Clients start from initialized, aligned storage, borrow it and recover ordinary access after returning all shares. | [part1-manifest.tsv](part1-manifest.tsv), [width.rs](checks/width.rs), [u32.rs](checks/u32.rs), [bool.rs](checks/bool.rs) | +| Part 1, `AtomicPtr` | For pointee sizes 0, 1, 2, 3 and 4 bytes, the pointer-sized slot stays the same and its payload may be null. Raw-slot type, pointee and metadata witnesses distinguish thin pointers, slices and references. | [pointer-view.rs](checks/pointer-view.rs), [pointer-shape.rs](checks/pointer-shape.rs) | +| T7, a harness for every Kani contract | Kani compiler metadata binds all 186 contracts in `sync/atomic.rs` on x86-64 (216 on AArch64) and all 41 in `intrinsics/mod.rs` (both targets) to at least one `proof_for_contract` harness. | [original/atomic.rs](original/atomic.rs), [original/intrinsics/mod.rs](original/intrinsics/mod.rs) | +| Part 2, 14 listed helpers | Verified generic `store`, `load`, `swap`, `add`, `sub`, strong/weak `compare_exchange`, `and`, `nand`, `or`, `xor`, `max`, `umax` and `umin` (plus signed `min` via Part 3) require permission at the actual destination. Public nonvolatile loads and stores forward `VOLATILE=false`. | [permission-inventory.tsv](permission-inventory.tsv), [check_mir.rs](checks/check_mir.rs) | +| Part 2, optional panics | Invalid store orders (`Acquire`, `AcqRel`), invalid load orders (`Release`, `AcqRel`), and invalid CAS failure orders (`Release`, `AcqRel`) retain the caller's lifetime share on continuing unwind. | [access.diff](specs/access.diff), [pointer-access.diff](specs/pointer-access.diff), [negative suite](../atomic.rs-negative/verify.sh) | +| Part 3, 91 intrinsic/ordering entries | Every challenge ordering (including all 15 legal pairs for strong and weak CAS) is joined to an instantiated MIR call and verified generic helper: 810 integer permissions on x86-64, 972 on AArch64, plus 25 pointer RMW edges. | [intrinsic-manifest.tsv](intrinsic-manifest.tsv), [check_mir.rs](checks/check_mir.rs) | +| UB, data races | Any positive ordinary fraction at any overlapping byte `0 <= i < 4` contradicts a writable atomic word permission (`frac == 1`). The dedicated `readonly` profile proves read-only fractional atomic borrows (`0 < af < 1`) coexist with concurrent ordinary non-atomic reads of the exact same address for both `AtomicBool` and `AtomicU32` (`load`, guaranteed-failing `compare_exchange`, and `compare_exchange_weak`, with `EMULATE_ATOMIC_BOOL == false` and compiled production MIR bridge checks) across single-threaded witnesses on x86-64/AArch64 and two-worker POSIX clients linked against repository `core`; potentially-writing CAS (including same-value `current == new`), `store`, and concurrent ordinary writes are rejected. Two POSIX workers also share full writable views and recover ordinary storage after both joins; disjoint U16/U8 and same-slot U16 load/load verify; early ordinary access, overlapping width borrows and premature lifetime end fail. | [storage.rs](checks/storage.rs), [ranges.rs](checks/ranges.rs), [readonly.rs](checks/readonly.rs), [checks/threads/](checks/threads/), [negative suite](../atomic.rs-negative/verify.sh) | +| UB, dangling or misaligned places | `from_ptr` consumes a borrow of live storage with atomic alignment; reference and raw projections preserve origin; host workers join before parent storage goes out of scope. | [borrow.diff](specs/borrow.diff), [layout.rs](checks/layout.rs), [pointer-slot.diff](specs/pointer-slot.diff) | +| UB, uninitialized loads | Borrows start from initialized typed storage; negative CI rejects both sealing an uninitialized U32 slot and passing it directly to `AtomicU32::from_ptr`. Local Kani runs also verify with `-Z uninit-checks`. | [u32.rs](checks/u32.rs), [owned-u32.rs](checks/owned-u32.rs), [negative suite](../atomic.rs-negative/verify.sh) | +| UB, invalid intrinsic use | Contracts constrain slot, scalar/pointer shape, width, legal ordering and value invariant. Kani intrinsic wrappers also restrict legal `AtomicOrdering` values (8 negative ordering checks). | [TRUSTED-BASE.md](TRUSTED-BASE.md), [kani-negative-ordering.sh](checks/kani-negative-ordering.sh) | +| UB, producing invalid values | Bool bytes stay `0`/`1`; strong CAS distinguishes mismatch while weak CAS admits spurious failure; returned pointers remain opaque payloads; `AtomicBool::compare_exchange(_weak)` native MIR branches are checked for all 8 `(Ok/Err) x (0/1)` outcomes; target-constant dead code in `AtomicBool::swap` is gated by [bool-swap.awk](checks/bool-swap.awk). | [bool-rmw.rs](checks/bool-rmw.rs), [bool_cas_byte_client.rs](checks/bool_cas_byte_client.rs), [pointer-access.rs](checks/pointer-access.rs) | + +### Verification summary by profile + +| Profile | x86-64 | AArch64 | Checks | +| --- | ---: | ---: | --- | +| Enabled scalar types | 10 integer, Bool, `*mut T` | 12 integer, Bool, `*mut T` | Target MIR inventory and compile-time size/alignment assertions | +| Challenge Part 1 constructors | 10 | 12 | `from_ptr` and `as_ptr` root receipts and clients (12 distinct types total) | +| Challenge Part 2 helpers | 14 | 14 | Generic helper contracts, plus `atomic_min` through Part 3 | +| Challenge Part 3 entries | 91 | 91 | Instantiated ordering calls and MIR route checks | +| Integer method permissions | 810 | 972 | Type-specific public method to helper and ordered intrinsic edges | +| Pointer RMW permissions | 25 | 25 | Five byte/bit methods across all five orderings; element-step MIR scaling | +| Two-worker clients | 5 verified, linked and executed | — | U32, Bool, pointer, mixed-width and read-only concurrent pairs on x86-64 host | + +On both targets, a by-value witness starts from an initialized `AtomicU32`, constructs `Atomic_own`, calls `Atomic_share_full`, ends the borrow and recovers the owned value; its companion negative control verifies `Atomic_own` cannot derive `false`. [owned-u32.rs](checks/owned-u32.rs) + +## Kani verification, OS page permissions, and reproduction + +**PR scope boundary for Kani CI.** Consistent with other `verify-rust-std` challenge PRs, this PR leaves `.github/workflows/` and shared upstream [run-kani.sh](../../../../scripts/run-kani.sh) unmodified (so PR Kani CI runs upstream `scripts/run-kani.sh` with `--output-format=terse --no-assert-contracts`). The local/reviewer verification recipe below runs full `--output-format=regular` cover checks (`check-kani-log`), `-Z uninit-checks`, T7 metadata completeness, and direct-callsite illegal-ordering rejection (`kani-negative-ordering.sh`). + +**Initialization.** Repository-wide Kani CI leaves `-Z uninit-checks` disabled (see [#733](https://github.com/model-checking/verify-rust-std/issues/733)). Local Kani verification exercises the load helpers, intrinsic wrappers, public loads, `compare_exchange` on `AtomicBool`, pointer-sized constructors and all `rmw_*` harnesses in both default mode and `-Z uninit-checks`. + +**OS page permissions for loads.** Under pinned Kani `87c87010`, `ub_checks::can_dereference(dst)` implies `ub_checks::can_write(dst as *mut T)`. Both check object bounds and alignment; `can_dereference` also checks initialization and value validity. Neither models OS page-table protections. On x86-64 and AArch64, `Relaxed` loads of at most 8 bytes rely on the target's documented guarantee for read-only pages. For every other supported atomic load (including `Acquire`/`SeqCst` on `u32` and AArch64 `Relaxed` on `u128`), the caller must provide a writable OS page mapping. VeriFast requires writable storage for every atomic load. [Pinned Kani predicates](https://github.com/model-checking/kani/blob/87c87010eda7797d7fa14033ca68bcbe17184a63/library/kani_core/src/mem.rs#L35-L79), [target load guarantees](original/atomic.rs#L159-L190) + +**Illegal ordering rejection on Kani intrinsic wrappers.** The four ordering-restricted wrappers (`atomic_load_wrapper`, `atomic_store_wrapper`, `atomic_cxchg_wrapper`, `atomic_cxchgweak_wrapper`) enforce legal `AtomicOrdering` preconditions. [kani-negative-ordering.sh](checks/kani-negative-ordering.sh) injects four positive controls and eight illegal-ordering callsite harnesses (with zero `#[kani::stub_verified]`) into a temporary copy of `library/` (excluding `library/target`) and runs Kani with direct callsite contract assertions, confirming legal orderings pass while `Release`/`AcqRel` on load and compare-exchange failure and `Acquire`/`AcqRel` on store fail at the corresponding `#[requires]` check. + +To reproduce the targeted Kani run (**176** harnesses / **174** non-panicking on `x86_64`; **200** harnesses / **198** non-panicking on `aarch64`), check exact expected harness set membership, verify every non-panicking harness's exact post-call `cover` description, source location and `SATISFIED` status, verify T7 metadata completeness (`186`/`41` on `x86_64`; `216`/`41` on `aarch64`), and run the positive/negative ordering checks with the same pinned Kani binary (`KANI`, defaulting to `kani_build/scripts/kani` built from [kani-version.toml](../../../../tool_config/kani-version.toml) per [run-kani.sh](../../../../scripts/run-kani.sh)): + +~~~bash +( + set -euo pipefail + ulimit -S -v 8388608 + export KANI="${KANI:-$PWD/kani_build/scripts/kani}" + expected_commit=$(awk -F'"' '/^commit[[:space:]]*=/{print $2; exit}' tool_config/kani-version.toml) + kani_root=$(cd "$(dirname "$KANI")/.." && pwd) + actual_commit=$(git -C "$kani_root" rev-parse --verify HEAD 2>/dev/null || true) + echo "Pinned Kani commit: $expected_commit; active checkout ($kani_root): ${actual_commit:-}" + test "$actual_commit" = "$expected_commit" + git -C "$kani_root" diff --quiet HEAD + "$KANI" --version + arch=$(uname -m) + case $arch in + x86_64) ints=(i8 u8 i16 u16 i32 u32 i64 u64 isize usize); exp_atomic=186 ;; + aarch64) ints=(i8 u8 i16 u16 i32 u32 i64 u64 isize usize i128 u128); exp_atomic=216 ;; + *) echo "Unsupported host architecture: $arch" >&2; exit 1 ;; + esac + exp_intr=41 + target_dir=$(mktemp -d) + trap 'rm -rf -- "$target_dir"' EXIT + { + printf 'sync::atomic::verify::%s\n' \ + harness_atomic_isize_from_ptr harness_atomic_usize_from_ptr \ + harness_atomic_load_ptr_u8 harness_safe_load_bool harness_safe_load_ptr \ + harness_safe_load_panics_on_release harness_safe_load_panics_on_acqrel \ + harness_safe_compare_exchange_bool + for t in "${ints[@]}"; do + printf 'sync::atomic::verify::harness_atomic_load_%s\n' "$t" + printf 'sync::atomic::verify::harness_safe_load_%s\n' "$t" + for m in compare_and_swap swap fetch_add fetch_sub fetch_and fetch_nand fetch_or fetch_xor fetch_max fetch_min; do + printf 'sync::atomic::verify::rmw_%s::%s\n' "$t" "$m" + done + done + for m in compare_and_swap swap fetch_and fetch_or fetch_xor fetch_nand fetch_not; do + printf 'sync::atomic::verify::rmw_bool::%s\n' "$m" + done + for m in compare_and_swap swap fetch_and fetch_or fetch_xor; do + printf 'sync::atomic::verify::rmw_ptr::%s\n' "$m" + done + for o in relaxed acquire seqcst; do + printf 'intrinsics::verify::harness_intrinsic_atomic_load_%s\n' "$o" + done + for o in relaxed release seqcst; do + printf 'intrinsics::verify::harness_intrinsic_atomic_store_%s\n' "$o" + done + for w in cxchg cxchgweak; do + for s in relaxed acquire release acqrel seqcst; do + for f in relaxed acquire seqcst; do + printf 'intrinsics::verify::harness_intrinsic_atomic_%s_%s_%s\n' "$w" "$s" "$f" + done + done + done + } | sort -u > "$target_dir/expected.txt" + export CARGO_BUILD_JOBS=1 RAYON_NUM_THREADS=1 CARGO_INCREMENTAL=0 + rustc --edition=2021 -O verifast-proofs/core/sync/atomic.rs/checks/check_mir.rs -o "$target_dir/check-mir" + for mode in default uninit; do + flags=() + if [[ $mode == uninit ]]; then flags=(-Z uninit-checks); fi + log="$target_dir/$mode.log" + "$KANI" verify-std library \ + -Z unstable-options -Z function-contracts -Z mem-predicates -Z float-lib \ + -Z c-ffi -Z loop-contracts -Z quantifiers -Z stubbing --no-assert-contracts \ + --jobs=1 --output-format=regular --target-dir "$target_dir/$mode" "${flags[@]}" \ + --harness harness_atomic_isize_from_ptr --harness harness_atomic_usize_from_ptr \ + --harness harness_atomic_load_ --harness harness_intrinsic_atomic_load_ \ + --harness harness_intrinsic_atomic_store_ \ + --harness harness_intrinsic_atomic_cxchg_ --harness harness_intrinsic_atomic_cxchgweak_ \ + --harness harness_safe_load_ --harness harness_safe_compare_exchange_bool \ + --harness verify::rmw_ --cbmc-args --object-bits 12 | tee "$log" + "$target_dir/check-mir" check-kani-log "$log" "$target_dir/expected.txt" \ + library/core/src/sync/atomic.rs library/core/src/intrinsics/mod.rs + meta=$(find "$target_dir/$mode" -name 'core-*.kani-metadata.json' | head -n 1) + test -n "$meta" + jq -e --argjson ea "$exp_atomic" --argjson ei "$exp_intr" ' + def check($rel; $exp): + ([.contracted_functions[] | select(.file | endswith($rel))]) as $all + | ($all | length) == $exp and all($all[]; (.harnesses | length) > 0); + check("sync/atomic.rs"; $ea) and check("intrinsics/mod.rs"; $ei) + ' "$meta" >/dev/null + done + bash verifast-proofs/core/sync/atomic.rs/checks/kani-negative-ordering.sh +) +~~~ + +## Borrow protocols and remaining limits + +The proof supports two complementary borrow protocols over suitably aligned, initialized ordinary storage: + +1. **Writable atomic borrow (`frac == 1`)**: seals all ordinary permissions for the borrowed range, transfers atomic read/write/RMW shares across POSIX workers, joins both workers, and ends the borrow to recover full ordinary access. Disjoint adjacent storage remains accessible throughout. +2. **Read-only fractional atomic borrow (`0 < af < 1`)**: splits full writable storage `[1](*p |-> val)` (`ro_bool_content` / `ro_u32_content` bundles `[af]atomic_points_to` with `[1 - af]` ordinary read permission, preventing read-only `.rodata` / `&'static` fractional shares from constructing a CAS-capable atomic borrow) while permitting concurrent ordinary non-atomic reads alongside atomic loads and guaranteed-failing `compare_exchange(_weak)` (where the slot invariant rules out `current == val`, guaranteeing zero writes) on the same address. Potentially-writing CAS (including same-value `current == new`), `store`, RMWs, and concurrent ordinary writes are rejected; after both workers join and the borrow ends, the split fractions merge back to full writable storage. + +Two legal Rust patterns remain outside these protocols and require a committee ruling on Challenge 7 coverage: + +1. Operation-level overlapping mixed-width views (Gate 3-B), including overlapping reads of different widths or accesses separated by synchronization (mixed-width clients cover disjoint slots and same-width loads). +2. Ordinary writes or post-writable-borrow ordinary reads after joining the last worker *before* executing the ghost borrow-end step (clients recover all shares and end the ghost borrow immediately after `join`, emitting zero runtime instructions). + +| Deferred obligation | Evidence supplied | +| --- | --- | +| Direct `AtomicU32::new` transmute verification | PR #683's Kani coverage and VeriFast clients starting from initialized U32 storage or an existing `AtomicU32`. | +| Generic `update`, `try_update` and `fetch_update` callback wrappers | Kani coverage and verified `load` and `compare_exchange_weak`. | +| Internal initialized-byte projection lemma immediately after word recovery | Ordinary U32 reads and writes after recovery, exclusion at every overlapping byte, and a separately initialized byte round trip. | +| Direct `usize::wrapping_mul` proof and general pointer provenance | Compiled element-step access footprint (`check_mir.rs`) and verified byte methods. Pointer payloads carry no permission to dereference the pointee. | diff --git a/verifast-proofs/core/sync/atomic.rs/TRUSTED-BASE.md b/verifast-proofs/core/sync/atomic.rs/TRUSTED-BASE.md new file mode 100644 index 0000000000000..84dca9bb39576 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/TRUSTED-BASE.md @@ -0,0 +1,115 @@ +# Trusted base and tool patch audit + +The proof uses the pinned Rust compiler, its MIR, VeriFast's Rust memory and lifetime model, its symbolic executor and bundled solver, and the native refinement checker. It relies on Linux's implementation of the compiler atomics and POSIX threads. The targets are `x86_64-unknown-linux-gnu` and `aarch64-unknown-linux-gnu`, little-endian LP64 with native 8-bit CAS. Only x86-64 executes the thread examples. + +> **Excluded emulated-bool targets ([`rust-lang/rust#166918`](https://github.com/rust-lang/rust/issues/166918)):** Targets with `EMULATE_ATOMIC_BOOL == true` (`riscv32`, `riscv64`, `loongarch32`, `loongarch64`) are excluded from the verified target set because `AtomicBool::compare_exchange(_weak)` currently lowers its failing branch to `intrinsics::atomic_or` / `intrinsics::atomic_and` (LLVM `atomicrmw`, always a write) rather than `intrinsics::atomic_cxchg` (LLVM `cmpxchg`, load on failure), causing a real data race with concurrent non-atomic reads (filed as [`rust-lang/rust#166918`](https://github.com/rust-lang/rust/issues/166918); standalone reproducer in [`checks/upstream_bug_166918_miri.rs`](checks/upstream_bug_166918_miri.rs)). + +## Imported contracts and platform boundaries + +| Boundary | Assumptions used by the proof | Check on the calling side | +| --- | --- | --- | +| VeriFast memory primitives | The upstream typed points-to, byte conversions, reference initialization, lifetime tokens, masks, borrows and `atomic_points_to` describe this Rust memory model. Closing the atomic predicate consumes initialized ordinary storage with the required alignment and invariant. Opening it for ordinary recovery requires the appropriate whole resource. | [Storage exclusion and recovery](checks/storage.rs), [production borrow](specs/borrow.diff) | +| `atomic_load` and `atomic_store` | A supported type, legal order and the permission on the precise slot authorize one atomic access. Loads return an invariant value. Stores require an admissible replacement. Nonvolatile public methods select `VOLATILE=false`. | [Annotations](specs/access.diff), [binding controls](../atomic.rs-negative/verify.sh) | +| `atomic_xchg`, `atomic_xadd`, `atomic_xsub` | The target performs an indivisible RMW on its operand slot and preserves the stated permission. Contracts constrain supported slot/operand combinations and the returned value where required. | [Integer RMW](specs/rmw.diff), [U32](specs/u32.diff), [pointer byte operations](specs/pointer-rmw.diff) | +| `atomic_and`, `atomic_nand`, `atomic_or`, `atomic_xor` | The specified integer operations preserve admissible values and slot permissions. Bool paths impose an additional byte invariant and operand restrictions. The pointer profiles constrain pointer-sized bit operations. | [Bool witnesses](checks/bool-rmw.rs), [pointer witnesses](checks/pointer-rmw.rs) | +| `atomic_min`, `atomic_max`, `atomic_umin`, `atomic_umax` | The compiler implements the signed or unsigned operation for the appropriate type at one slot. Each enabled width selects the corresponding declaration for all five orderings. | [Permission inventory](permission-inventory.tsv) | +| `atomic_cxchg` and `atomic_cxchgweak` | The observed old value satisfies the invariant. Success requires equality with the expected value. Strong failure implies a mismatch. Weak failure permits the expected value. Thin-pointer CAS tests address equality and supplies no pointee ownership. | [CAS and ordering contracts](specs/access.diff), [pointer contracts](specs/pointer-access.diff), [byte CAS](checks/bool_cas_byte_client.rs) | +| By-value `AtomicU32` storage | The U32 intrinsic contracts accept either an initialized scalar slot or an initialized `Atomic` at the same address. Each access returns permission for the same backing object at the same address. Stores and RMWs can replace its payload. The owned object has `UnsafeCell>` storage and accepts every U32 bit pattern. The by-value witness requires the verifier's atomic alignment to equal the Rust alignment of this object. The compiler checks the associated storage type and the target layout assertions check size and alignment. | [Owned round trip](checks/owned-u32.rs), [U32 intrinsic contracts](specs/u32.diff), [layout checks](checks/layout.rs) | +| Layout and provenance | `from_ptr` assumes live initialized storage meeting atomic alignment. `UnsafeCell::get` projects the reference origin on its actual receiver. The layout assertions compile against core metadata from this checkout for every enabled scalar. For slot proofs, `AtomicPtr` contains a thin raw pointer and payloads can be null. General aliasing/provenance semantics come from the verifier and compiler. | [Target layout](checks/layout.rs), [typed projection](checks/pointer-shape.rs), [pointer clients](checks/pointer-view.rs) | +| `abort_immediate` and `caller_location` | These bodyless compiler declarations respectively terminate the process and return an initialized shared static location with no continuing unwind. The latter grants only the specified location resources. | Explicit [panic declarations](specs/panic.diff). The frontend checks compatibility of their safe nullary interfaces. | +| `Arguments::from_str` and `panic_fmt` | The upstream contracts model formatting an approved static string and a panic which cannot return normally and can continue unwinding to the caller. The panic handler/runtime is trusted. The opt-in import checks the defining source hashes, lang items, target, helper identity, eight messages and actual MIR flow. Native refinement uses the real definitions. | [Tool patch](verifast-core.patch), [message and unwind controls](../atomic.rs-negative/verify.sh) | +| Fork, callback transfer and join | The upstream platform spec and its Unix implementation transfer the worker precondition through `pthread_create` and return the postcondition on successful `pthread_join`. Allocation, libc, the OS scheduler and the C ABI are trusted. An escaping panic at a C boundary terminates. The clients assume no fairness or bound on weak-CAS retries. | Host builds use the [locked platform dependencies](platform.Cargo.lock), repository core and the pinned backtrace source from rust-src. The runner checks the compiled C adapters' terminate paths, verifies each worker and executes the linked examples. [Thread driver](verify.sh), [common helpers](checks/common.sh) | +| External method specifications for workers | The platform crate sees std's public method names. The runner derives their three contract clauses from verified single-method witnesses and checks its executable forwarding body, arguments, return value and MIR edge to the production implementation. Compiler metadata selects the linked core. | [Interface extraction](checks/check_mir.rs), [pointer qualifier regression](tool-tests/pointer_client.rs) | + +The [intrinsic manifest](intrinsic-manifest.tsv) enumerates all 91 ordering instances of the compiler declarations above. The proof establishes safety and slot access under those contracts. Hardware memory ordering, linearizability of compiled machine instructions and operating-system internals remain trusted. + +Under pinned Kani `87c87010`, `ub_checks::can_dereference(dst)` implies `ub_checks::can_write(dst as *mut T)`. Both check object bounds and alignment. `can_dereference` also calls the initialization and value-validity predicates. Neither models OS page-table protections. On x86-64 and AArch64, `Relaxed` loads of at most 8 bytes rely on the target’s documented guarantee for read-only pages. For every other supported atomic load, including `Acquire` or `SeqCst` on `u32` and AArch64 `Relaxed` on `u128`, the caller must provide a writable OS page mapping. VeriFast requires writable storage for every atomic load. [Pinned Kani predicates](https://github.com/model-checking/kani/blob/87c87010eda7797d7fa14033ca68bcbe17184a63/library/kani_core/src/mem.rs#L35-L79), [target load guarantees](original/atomic.rs#L159-L190) + +## Borrow protocol boundary + +A writable atomic borrow (`frac == 1`) seals **all** ordinary permissions over its bytes to exclude conflicting reads and writes. A read-only fractional atomic borrow (`0 < af < 1`) splits full writable ownership `[1](*p |-> val)` into `atomic_points_to(p, af, inv_)` paired with `[1 - af]` ordinary read permission inside the borrow (`ro_bool_content` / `ro_u32_content`, preventing read-only `.rodata` / `&'static` shares without full writable backing from constructing the borrow) and admits concurrent ordinary non-atomic reads alongside atomic loads and guaranteed-failing `compare_exchange(_weak)` (where `inv_(current) == false` rules out any write), while still excluding potentially-writing CAS (including same-value `current == new`), `store`, RMWs, and ordinary writes. Two legal Rust patterns remain outside these protocols and require a committee ruling for Challenge 7: operation-level overlapping mixed-width views (Gate 3-B) and ordinary accesses after joining workers before ending the ghost borrow (ending the ghost borrow emits zero runtime instructions). Client recovery requires every lifetime share and the explicit end of the borrow. + +## Audit of `verifast-core.patch` + +The [builder](build-linux-tools.sh) applies the [single patch](verifast-core.patch) to VeriFast revision `5b7d6f529e673f0f59aa9c11d7e95a70a6fa6b50`. The proof suite compares all 15 filenames and 124 new-side hunk starts with this table. Each row groups hunks with a shared purpose. [Audit check](checks/check_mir.rs) + +| Patched upstream file | Hunk starts | Semantics to review | +| --- | --- | --- | +| `bin/rust/prelude_core.rsspec` | 298 | Adds a pure discriminant equation for the typed unit-enum const representation. Its precondition and conclusion contain no spatial resources. | +| `bin/rust/std/lib.rsspec` | 297 | Declares the five compiler `AtomicOrdering` variants in discriminant order. | +| `rust-toolchain.toml` | 1 | Pins the Rust nightly used to produce and consume MIR. | +| `src/refinement_checker/frontend.ml` | 100 | Selects the matching rustc driver for native refinement. | +| `src/refinement_checker/main.ml` | 64 | Compares the names, discriminant types and bits of local enum definitions from both exports. A mismatch fails refinement. | +| `src/refinement_checker/refinement_checker.ml` | 300, 329, 345, 367 | Decodes typed enum constants into distinct symbolic terms, prints them and preserves their identity during evaluation. | +| `src/refinement_checker/refinement_checker.ml` | 623, 721, 961, 1200, 1417, 1598 | Marks the checker's built-in synthetic bodies as ordinary definitions. | +| `src/refinement_checker/refinement_checker.ml` | 750, 989, 1227, 1441 | Records the existing concrete discriminant operands in synthetic MIR. | +| `src/refinement_checker/refinement_checker.ml` | 1621, 1642, 1671 | Retains the optional abstract discriminant operand in the internal comparison command, its printer and translation. | +| `src/refinement_checker/refinement_checker.ml` | 2124, 2710 | Requires matching discriminant layout information in both comparison paths. | +| `src/refinement_checker/refinement_checker.ml` | 2302 | Rejects a compiler declaration/body mismatch. | +| `src/refinement_checker/stringifier.ml` | 85 | Prints the new MIR arithmetic operator variants distinctly in diagnostics. | +| `src/rust_frontend/rust_fe.ml` | 103 | Uses the same pinned rustc driver as the exporter. | +| `src/rust_frontend/vf_mir/vf_mir.capnp` | 165, 269 | Serializes the unit-variant identity and the discriminant type and bit representation. | +| `src/rust_frontend/vf_mir/vf_mir.capnp` | 635, 658, 717, 883 | Carries the exact UnsafeCell receiver marker, distinct arithmetic opcodes, optional abstract discriminant operand and compiler declaration flag. | +| `src/rust_frontend/vf_mir/vf_mir.capnp` | 672 | Carries rustc’s proof that both comparison operands have a sized pointee wherever they are raw pointers. The default value fails the translator check. | +| `src/rust_frontend/vf_mir_exporter/src/atomic_literal_panic.rs` | 1 | Restricts the import to the two pinned definitions and the eight specific illegal-ordering sites. A constant UTF-8 `&str` must become an isolated format argument moved directly into the approved panic sink. A changed or additional message, nonliteral, reused or escaped temporary, or unmatched sink rejects the export. | +| `src/rust_frontend/vf_mir_exporter/src/lib.rs` | 49, 76, 112, 217 | Adds the scoped exporter options and opt-in literal-panic boundary. | +| `src/rust_frontend/vf_mir_exporter/src/lib.rs` | 120, 170, 193, 234 | Updates the rustc entrypoint and identifies the canonical crate root before preprocessing. | +| `src/rust_frontend/vf_mir_exporter/src/lib.rs` | 265 | Requires scoped proof/report mode for the literal-panic import. Checks exported declarations, original MIR bodies and resolved operands before replacing scoped trait calls. Distinct macro expansions keep their own DefIds. Unavailable MIR rejects the export. | +| `src/rust_frontend/vf_mir_exporter/src/lib.rs` | 333, 1001, 1012, 1018, 1045, 1059, 1112, 1155, 1301, 1344, 1413 | Passes scoped traits and optional literal-panic information through the export and encoding contexts. Ordinary exports leave the import disabled. | +| `src/rust_frontend/vf_mir_exporter/src/lib.rs` | 400 | Computes the scoped call graph from MIR and retains participating traits, impls of both polarities and ADTs. Before normalization, `ProjectionCheck` checks alias and const kinds in instantiated signatures, elaborated bounds, substitutions, MIR operands and local and external fields. It admits three core projections, const values, const parameters and checked anonymous constants as detailed below. Repeated definition/argument pairs terminate the type walk. | +| `src/rust_frontend/vf_mir_exporter/src/lib.rs` | 760 | Reads the rustc impl self type to identify the underlying ADT for struct, enum, union and aliased receivers. Keeps the polarity and generic arguments of each impl. | +| `src/rust_frontend/vf_mir_exporter/src/lib.rs` | 967, 1161 | Keeps submodule ghost declarations at their file spans and exports the participating trait interfaces. Required method declarations are selected from reachable calls and impl bodies. | +| `src/rust_frontend/vf_mir_exporter/src/lib.rs` | 1172 | Selects required trait method declarations using the original call and the resolved implementation IDs. | +| `src/rust_frontend/vf_mir_exporter/src/lib.rs` | 1208, 1650, 2455 | Preserves the pinned rustc spelling of named and anonymous lifetimes in definitions and use sites. | +| `src/rust_frontend/vf_mir_exporter/src/lib.rs` | 1395, 1431 | Checks that scoped impl selection accounts for every emitted local ADT. Identifies compiler types and the literal-panic interface by DefId. | +| `src/rust_frontend/vf_mir_exporter/src/lib.rs` | 1461, 1521, 1535 | Encodes variant definitions with their actual discriminant types and raw values. | +| `src/rust_frontend/vf_mir_exporter/src/lib.rs` | 1688 | Marks only an actual compiler intrinsic without a Rust body as a declaration. | +| `src/rust_frontend/vf_mir_exporter/src/lib.rs` | 2250, 2803, 2855, 2936 | Adapts rustc type, region, aggregate and binary-operation APIs to the pinned nightly. | +| `src/rust_frontend/vf_mir_exporter/src/lib.rs` | 2309 | Checks the alias kind, defining item and receiver again when encoding an alias type. | +| `src/rust_frontend/vf_mir_exporter/src/lib.rs` | 2316, 2768, 2897 | Explicitly rejects unsupported Rust view types, records unknown discriminant layout, and preserves distinct new MIR binary operators. | +| `src/rust_frontend/vf_mir_exporter/src/lib.rs` | 2367, 2416 | Uses the pinned compiler’s generic argument representation for ADT and function operands and exports the approved literal-panic interface name. | +| `src/rust_frontend/vf_mir_exporter/src/lib.rs` | 2477 | Checks type and const substitutions of bodies and ADT definitions before translating them. Function items, function pointers, closures, UnsafeCell and ManuallyDrop lose nominal identity there and reject the export. | +| `src/rust_frontend/vf_mir_exporter/src/lib.rs` | 2686 | Tags only the raw address of the actual shared receiver in the inherent `UnsafeCell::get` lang-item implementation. | +| `src/rust_frontend/vf_mir_exporter/src/lib.rs` | 2740 | For MIR equality, inequality and ordering, asks rustc whether each raw pointee is Sized in the body’s typing environment. A slice, str, trait object or unconstrained pointee lacks that guarantee. | +| `src/rust_frontend/vf_mir_exporter/src/lib.rs` | 3246, 3255, 3295 | Reads fieldless enum constants from rustc's validated type, variant index and actual representable discriminant. Preserves structural encoding for other values. | +| `src/rust_frontend/vf_mir_exporter/src/preprocessor.rs` | 153, 205, 737, 772 | Injects support declarations once at the crate root, qualifies their use and updates preprocessed source offsets. | +| `src/rust_frontend/vf_mir_translator/rust_parser.ml` | 1017, 1043 | Retains the written `*mut T` or `*const T` argument in a single-argument inherent receiver name such as `Slot<*const T>`. These method names select distinct external contracts. Raw pointer values use the upstream type representation. | +| `src/rust_frontend/vf_mir_translator/vf_mir_translator.ml` | 881, 1388 | Retains lifetime type arguments and represents unit-enum constants with their owning type and discriminant. | +| `src/rust_frontend/vf_mir_translator/vf_mir_translator.ml` | 1069, 1079 | Preserves the self type and ordered type, lifetime and representable const arguments in projection type expressions. The ownership predicate uses that projection typeid. The generated drop obligation must return the field owner. | +| `src/rust_frontend/vf_mir_translator/vf_mir_translator.ml` | 1177, 1831, 1913 | Models a sized string-reference slot separately from its pointee, expresses shared array ownership with its element count, and permits `str` as a type argument while rejecting by-value ownership. | +| `src/rust_frontend/vf_mir_translator/vf_mir_translator.ml` | 1944, 2802, 2929 | Moves a marked pure lemma call to each normal MIR return. VeriFast checks the lemma's actual precondition there. | +| `src/rust_frontend/vf_mir_translator/vf_mir_translator.ml` | 2367 | Regular calls take all type and const arguments from rustc MIR. Ghost annotations may instantiate lifetimes and use `_` to retain compiler arguments. | +| `src/rust_frontend/vf_mir_translator/vf_mir_translator.ml` | 2965 | Translates generic destructor results and unwind targets on the drop edge. The destructor fixture exercises a real panicking destructor and a rejected false unwind contract. | +| `src/rust_frontend/vf_mir_translator/vf_mir_translator.ml` | 3055, 3360, 3437 | Fails on unimplemented arithmetic and abstract discriminant layout. Uses `ref_origin` only for the exact tagged UnsafeCell receiver. | +| `src/rust_frontend/vf_mir_translator/vf_mir_translator.ml` | 3072 | Requires the exported thin-pointer check for MIR `Eq`, `Ne`, `Lt`, `Le`, `Gt` and `Ge` before constructing the VeriFast operation. | +| `src/rust_frontend/vf_mir_translator/vf_mir_translator.ml` | 4898, 4919 | Registers an associated-type equality on a type parameter with type-only trait arguments and a type right-hand side. Lifetime and const trait arguments produce a static diagnostic. The translator skips higher-ranked projection clauses. | +| `src/rust_frontend/vf_mir_translator/vf_mir_translator.ml` | 5224, 5272, 6292 | Requires an explicit intrinsic contract, checks both outcomes of safe nullary monomorphic declarations against the Rust interface, and preserves variant metadata when filtering PhantomData. | +| `src/rust_frontend/vf_mir_translator/vf_mir_translator.ml` | 6918, 6987 | Uses the original MIR fields for structural Send and Sync. Arrays and slices inherit their element condition. Shared references require a Sync referent. Mutable references inherit the corresponding trait. Raw pointers satisfy neither trait. UnsafeCell is never Sync and inherits Send from its contents. ManuallyDrop inherits both. Explicit impls or unsupported fields suppress the structural equivalence. | +| `src/verifast.ml` | 262, 276, 307, 357, 415, 437, 458 | Specializes a callback proof chunk for its one shared-reference lifetime and checks its parameter type, precondition, normal and exceptional postconditions using the same substitution. | +| `src/verifast.ml` | 1044, 1055, 1142 | Associates a fresh Rust stack address with its own origin at creation. This pure equality grants no points-to or borrow permission. | + +The tool fixtures also cover enum constants, later macro expansions, concrete trait overrides and destructor unwind. The negative suite checks call-only negative auto-trait impls and a shared-tail store against compiled MIR. [Tool fixtures](tool-tests/), [negative suite](../atomic.rs-negative/verify.sh) + +Both export modes match every `AliasTyKind`. The visitor and `encode_ty` reject `Inherent`, `Opaque` and `Free`. A `Projection` must belong to the crate defining the Sized lang item and match one of the three crate-relative paths below. Projection equality clauses undergo the same definition and receiver checks. + +| Core associated type | Why its identity survives raw-pointer qualifier erasure | +| --- | --- | +| `::intrinsics::bounds::BuiltinDeref::Pointee` | Both built-in raw-pointer dereferences yield the pointee type `P`. | +| `::ptr::metadata::Pointee::Metadata` | A raw pointer value is Sized. The metadata of `*mut P` and `*const P` as pointee types is therefore `()`, including when `P` itself is unsized. | +| `::sync::atomic::AtomicPrimitive::Storage` | Core seals this trait with `pub impl(self)`. Its only raw-pointer implementations are for `*mut T`. The exporter also rejects a concrete `*const T` receiver. | + +Projection arguments and equality right-hand sides retain the checks for erased function items, function pointers, closures, UnsafeCell and ManuallyDrop. The metadata controls exercise an erased receiver argument and an erased equality right-hand side. Both target architectures verify the pointer shape and owned U32 storage witnesses. [Pointer shape](checks/pointer-shape.rs), [owned U32](checks/owned-u32.rs) + +The pinned nightly represents unevaluated type-system constants as `ConstKind::Alias`. The visitor admits `Value` and `Param` and visits their children. A value carries its type. A parameter carries only an index and name, so the item walk visits the declared const parameter type with the actual substitutions. Of the const aliases, only `AliasConstKind::Anon` (an `AnonConst` definition) can pass. Trait and inherent associated constants, free constants, `Expr`, `Placeholder`, `Infer`, `Bound` and `Error` all reject the export. + +An anonymous constant must pass `const_eval_poly` with the definition's identity arguments. The visitor checks the original alias arguments as well. For rustc-trivial constants it checks the returned type and requires scalar bits or a zero-sized value. Otherwise it visits the CTFE MIR types and operands without constraining the final evaluated `ConstValue`. Each block must end in a return, goto, switch, assertion or unreachable terminator. Type-system constant operands go through the same visitor. Literal MIR operands must contain scalar bits or a zero-sized value. This excludes calls, unevaluated MIR operands, and literal MIR operands backed by another allocation, while still admitting non-trivial CTFE aggregates built from scalar literals under identity arguments (such as `{ [1u8; 32] }`) that cannot depend on generic parameters or raw-pointer qualifiers. The production `atomic_load` ordering argument `{ AO::Relaxed }` constructs a fieldless enum and passes with its inherited generic arguments. + +Both modes on both targets reject each external layout control. `Bridge::Repr` reaches `Inherent`. The named `Hidden = impl Copy` field reaches a `Free` alias first. A function item returning `impl Copy` exposes `Opaque` directly. The array controls exercise `width::()`, ordinary `T::N` behind an anonymous constant, and a directly represented associated constant. Rust checks tail offsets 1 and 4 on both targets, and the x86-64 executable observes unequal addresses. The fixed `width::<*mut u8>()` call gives offset 1 for both instantiations and still fails the CTFE body check. A generic client of an external `Bytes([u8; N])` verifies in all four configurations. The exporter also accepts a direct `[u8; N]` signature. Translating that signature into a VeriFast array type still requires a literal length in the OCaml translator. [External definitions](tool-tests/external_layout.rs), [direct associated constant](tool-tests/external_assoc_const.rs), [layout client](tool-tests/external_layout_client.rs), [const parameter and opaque-result client](tool-tests/external_array_client.rs) + +Both export modes on both targets reject local user-trait projections across signature equality, nested trait arguments, struct fields, generic bodies, two-hop mapped traits, parameterized slots, `Sync` bounds and const-generic projections, as well as an external crate shadowing `core::ptr::metadata::Pointee::Metadata` or wrapping an erased `UnsafeCell`. Native x86-64 checks observe unequal tail addresses and compile-time checks establish offsets 1 and 4 on both targets. The recursive function and struct with `Atomic<*mut T>` verify, and rustc rejects `Atomic<*const T>` on both targets. [Local projections](tool-tests/projections.rs), [external layout & foreign traits](tool-tests/external_layout.rs), [recursive Atomic](tool-tests/projection_recursion.rs) + +The callsite fixture uses a plain type parameter and a const parameter. Compiler-supplied arguments verify. Explicit ghost type and const overrides each produce the translator’s callsite diagnostic in all four configurations. Both annotated clients return 1 in native Rust. External inherent methods on the two raw-pointer qualifiers retain their distinct interfaces. [Callsite fixture](tool-tests/generic_projection.rs), [negative controls](../atomic.rs-negative/verify.sh) + +For a struct such as `Explicit(UnsafeCell)`, an explicit unsafe `Sync` or `Send` impl suppresses the structural equation for that trait. The translator computes necessary bounds on explicit impls. An unconditional positive impl supplies no such bounds and emits no positive ghost fact. Rust accepts the trait bound, while either Boolean assertion about the corresponding `is_Sync` or `is_Send` remains unprovable without another premise. The auto-trait fixture also checks call-only `!Send`/`!Sync` ADTs and structural inference on direct, array and nested `UnsafeCell` fields and ordinary fields. The comparison fixture exercises both raw-pointer qualifiers and all six comparison operators. In native Rust, two slices at the same address can compare unequal and be ordered by their lengths. Trait objects already fail during type translation. Slices, str and pointees of unknown size reach the comparison check. [Auto traits](tool-tests/auto_traits.rs), [wide comparisons](tool-tests/wide_pointer_comparison.rs) + +The snapshot updater locks the proof directory, refuses to clobber tracked or untracked local edits under `original/`, stages and verifies all five upstream files before modifying `original/`, saves and announces a permanent backup under `/atomic-snapshot-backups/` before any live write, prepares all five temporary files and replaces each snapshot via `mv -f`, rolls back any partial replacement and cleans temporary files on failure so retries stay clean, and runs `check-sources.sh`. [Updater](update.sh) diff --git a/verifast-proofs/core/sync/atomic.rs/build-linux-tools.sh b/verifast-proofs/core/sync/atomic.rs/build-linux-tools.sh new file mode 100755 index 0000000000000..fd10a408f3c2e --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/build-linux-tools.sh @@ -0,0 +1,122 @@ +#!/usr/bin/env bash +# Print the tool directory on stdout. Build messages go to stderr. +set -euo pipefail +here=$(cd "$(dirname "$0")" && pwd) +tc=nightly-2026-11-21 +base=5b7d6f529e673f0f59aa9c11d7e95a70a6fa6b50 +decoder=2d6606d9b59cd0c88a66729f3f076c10c0c8e0b2 +deps=/tmp/vfdeps-adf88dc +test "$(uname -sm)" = 'Linux x86_64' +valid_tools() { + local tool + for tool in verifast refinement-checker vf-rust-mir-exporter; do + [[ -x $1/bin/$tool ]] || return 1 + done + [[ -f $1/bin/rust/std/lib.rsspec && -f $1/tests/rust/unverified/platform/spec/lib.rsspec ]] +} + +if ! rustup run "$tc" rustc --version >/dev/null 2>&1; then + rustup toolchain install "$tc" --profile minimal >&2 +fi +installed=$(rustup component list --toolchain "$tc" --installed) +for component in rustc-dev rust-src llvm-tools-preview; do + if ! grep -Eq "^${component%-preview}(-x86_64-unknown-linux-gnu)?$" <<< "$installed"; then + rustup component add --toolchain "$tc" "$component" >&2 + fi +done +if ! rustup target list --toolchain "$tc" --installed | grep -Fxq aarch64-unknown-linux-gnu; then + rustup target add --toolchain "$tc" aarch64-unknown-linux-gnu >&2 +fi +key=$(cd "$here" && sha256sum verifast-core.patch build-linux-tools.sh platform.Cargo.lock | sha256sum | cut -d' ' -f1) +if [[ -n ${ATOMIC_VERIFAST_DIR:-} ]]; then + if [[ ! -f $ATOMIC_VERIFAST_DIR/complete || $(<"$ATOMIC_VERIFAST_DIR/complete") != "$key" ]] || ! valid_tools "$ATOMIC_VERIFAST_DIR"; then + echo "Incomplete or stale ATOMIC_VERIFAST_DIR (expected build key $key): $ATOMIC_VERIFAST_DIR" >&2 + exit 1 + fi + realpath "$ATOMIC_VERIFAST_DIR" + exit +fi + +cache=${ATOMIC_TOOL_CACHE:-${RUNNER_TEMP:-$HOME/.verifast}/atomic-verifast-5b7d6f52} +mkdir -p "$cache" +cache=$(realpath "$cache") +dest=$cache/$key +exec 9>"$cache/build.lock" +flock 9 +if [[ -f $dest/complete && $(<"$dest/complete") == "$key" ]] && valid_tools "$dest"; then + echo "$dest" + exit +fi +stage=$(mktemp -d "$cache/.build.XXXXXXXX") +deps_tmp= +cleanup() { + rm -rf -- "$stage" + if [[ -n $deps_tmp ]]; then rm -rf -- "$deps_tmp"; fi +} +trap cleanup EXIT +fetch() { + curl --fail --location --silent --show-error --retry 3 --proto '=https' "$1" -o "$stage/download" + printf '%s %s\n' "$2" "$stage/download" | sha256sum -c >&2 +} +mkdir "$stage/vf" "$stage/decoder" "$stage/commands" +fetch "https://codeload.github.com/verifast/verifast/tar.gz/$base" 8995b3cb008c9110c14284702f99cec91426c7547067c7c08fbab5f9b93eb0b1 +tar xf "$stage/download" --strip-components=1 -C "$stage/vf" +fetch "https://codeload.github.com/btj/capnpc-ocaml-decoder/tar.gz/$decoder" 29c8025b7fbf96213db5a07fef707e214a4f7547b84a89faf9816cd0ad117b59 +tar xf "$stage/download" --strip-components=1 -C "$stage/decoder" +# The prebuilt OCaml tools use this absolute prefix internally. +deps_sha=8d022c93d51a1d13ec1e782d767c60462405f6865d5ee416f82d6234e93ee580 +# The prefix is shared even by builds using different ATOMIC_TOOL_CACHE values. +# Check payload names, modes, symlinks and bytes against the verified release. +tree_sha=71c349ae1e2d471c404cce9880de25b73766bec3742e2de033a5c402402c6d10 +marker=.atomic-vfdeps-sha256 +verify_deps() { + local digest + [[ -d $1 && ! -L $1 ]] || return 1 + digest=$(LC_ALL=C tar --sort=name --mtime=@0 --owner=0 --group=0 --numeric-owner \ + --format=gnu --exclude="./$marker" -cf - -C "$1" . | sha256sum) + [[ ${digest%% *} == "$tree_sha" ]] +} +exec 8>>"$deps.lock" +flock 8 +if [[ ! -e $deps && ! -L $deps ]]; then + fetch https://github.com/verifast/vfdeps/releases/download/25.01/vfdeps-adf88dc-linux.txz "$deps_sha" + deps_tmp=$(mktemp -d /tmp/atomic-vfdeps.XXXXXXXX) + tar xpf "$stage/download" -C "$deps_tmp" + extracted=$deps_tmp/vfdeps-adf88dc + verify_deps "$extracted" || { echo 'Invalid extracted vfdeps payload' >&2; exit 1; } + printf '%s\n' "$deps_sha" > "$extracted/$marker" + mv -T "$extracted" "$deps" +else + verify_deps "$deps" || { echo "Invalid vfdeps payload in $deps" >&2; exit 1; } + if [[ ! -e $deps/$marker && ! -L $deps/$marker ]]; then + # Adopt an existing verified installation without replacing it. + printf '%s\n' "$deps_sha" > "$deps/$marker" + fi + [[ -f $deps/$marker && ! -L $deps/$marker && $(<"$deps/$marker") == "$deps_sha" ]] || + { echo "Invalid vfdeps marker in $deps" >&2; exit 1; } +fi +flock -u 8 +export GIT_CEILING_DIRECTORIES="$stage" +git -C "$stage/vf" apply --check "$here/verifast-core.patch" +git -C "$stage/vf" apply --whitespace=nowarn "$here/verifast-core.patch" +export PATH="$stage/commands:$deps/bin:$PATH" CAPNP_INC_DIR="$deps/include" +export LD_LIBRARY_PATH="$deps/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" +export CARGO_BUILD_JOBS=1 CARGO_INCREMENTAL=0 DUNE_CACHE=disabled +export RAYON_NUM_THREADS=1 MALLOC_ARENA_MAX=2 +ulimit -S -v 8388608 +printf '#!/bin/sh\nexec %s/bin/dune "$@" -j 1\n' "$deps" > "$stage/commands/dune" +chmod +x "$stage/commands/dune" +cargo "+$tc" build --release --locked -j1 --manifest-path "$stage/decoder/Cargo.toml" >&2 +export PATH="$stage/decoder/target/release:$PATH" +cargo "+$tc" build --release --locked -j1 --manifest-path "$stage/vf/src/rust_frontend/vf_mir_exporter/Cargo.toml" --target-dir "$stage/exporter" >&2 +cp "$stage/exporter/release/vf_mir_exporter" "$stage/vf/bin/vf-rust-mir-exporter" +make -C "$stage/vf/src" -j1 VFVERSION="atomic-${base:0:8}" WITHOUT_LABLGTK=1 ../bin/verifast ../bin/refinement-checker >&2 +mkdir -p "$stage/install/tests/rust/unverified" +cp -a "$stage/vf/bin" "$stage/install/bin" +cp -a "$stage/vf/tests/rust/unverified/platform" "$stage/install/tests/rust/unverified/" +cp "$here/platform.Cargo.lock" "$stage/install/tests/rust/unverified/platform/Cargo.lock" +valid_tools "$stage/install" +echo "$key" > "$stage/install/complete" +if [[ -e $dest ]]; then mv -T "$dest" "$stage/incomplete"; fi +mv -T "$stage/install" "$dest" +echo "$dest" diff --git a/verifast-proofs/core/sync/atomic.rs/check-sources.sh b/verifast-proofs/core/sync/atomic.rs/check-sources.sh new file mode 100755 index 0000000000000..d3227a33068f7 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/check-sources.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")" +src=../../../../library/core/src +for path in lib.rs sync/atomic.rs sync/atomic_load_volatile.md sync/atomic_store_volatile.md intrinsics/mod.rs; do + snapshot=original/${path#sync/} + if ! cmp "$snapshot" "$src/$path"; then + echo "::error title=VeriFast source snapshot is out of date::Run verifast-proofs/core/sync/atomic.rs/update.sh and review the proof annotations." >&2 + exit 1 + fi +done diff --git a/verifast-proofs/core/sync/atomic.rs/checks/bool-access.rs b/verifast-proofs/core/sync/atomic.rs/checks/bool-access.rs new file mode 100644 index 0000000000000..d35f7cd2c4b8c --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/checks/bool-access.rs @@ -0,0 +1,67 @@ +// This module also contains the checked ordinary_bool and prepare_bool lemmas. +unsafe fn borrowed_bool_access(initial: bool, replacement: bool) +//@ req true; +//@ ens true; +//@ on_unwind_ens false; +{ + use crate::sync::atomic::Ordering; + let mut value = initial; + let slot = &raw mut value; + //@ to_u8s_(slot); + //@ from_u8s_(slot); + //@ let k = begin_lifetime(); + //@ close ordinary_bool(slot)(); + //@ borrow(k, ordinary_bool(slot)); + //@ prepare_bool(slot, k); + { + //@ let_lft 'a = k; + let view = unsafe { AtomicBool::from_ptr/*@::<'a>@*/(slot) }; + //@ close sync::atomic::Ordering_own(currentThread, sync::atomic::Ordering::Relaxed); + view.store(replacement, Ordering::Relaxed); + //@ close sync::atomic::Ordering_own(currentThread, sync::atomic::Ordering::Acquire); + let _ = view.load(Ordering::Acquire); + } + //@ end_lifetime(k); + //@ borrow_end(k, ordinary_bool(slot)); + //@ open ordinary_bool(slot)(); + let recovered = unsafe { *slot }; + //@ points_to_bool_to_u8(slot); + let byte = unsafe { *slot.cast::() }; + //@ if recovered {} else {} + //@ assert byte == if recovered { 1 } else { 0 }; + //@ points_to_u8_to_bool(slot as *u8); + unsafe { *slot = replacement }; +} +unsafe fn shared_bool_view<'a>(ptr: *mut bool) -> &'a AtomicBool +//@ req [?q]lifetime_token('a) &*& [_]frac_borrow('a, sync::atomic::bool_slot_content(ptr)) &*& ref_origin(ptr) == ptr; +//@ ens [q]lifetime_token('a) &*& [_]frac_borrow('a, sync::atomic::bool_slot_content(ref_origin(result))) &*& [_]frac_borrow('a, ref_initialized_(result)) &*& ref_origin(result) as pointer == ptr as pointer; +//@ on_unwind_ens false; +{ + let result = unsafe { AtomicBool::from_ptr/*@::<'a>@*/(ptr) }; + //@ open sync::atomic::Atomic_share::('a, currentThread, result); + result +} + +unsafe fn shared_bool_store(receiver: &AtomicBool, val: bool, order: crate::sync::atomic::Ordering) +//@ req [?q]lifetime_token(?k) &*& [_]frac_borrow(k, sync::atomic::bool_slot_content(ref_origin(receiver))) &*& [_]frac_borrow(k, ref_initialized_(receiver)) &*& order != sync::atomic::Ordering::Acquire &*& order != sync::atomic::Ordering::AcqRel; +//@ ens [q]lifetime_token(k); +//@ on_unwind_ens false; +{ + //@ close exists(false); + //@ close sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ leak sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ close sync::atomic::Ordering_own(currentThread, order); + receiver.store(val, order) +} + +unsafe fn shared_bool_load(receiver: &AtomicBool, order: crate::sync::atomic::Ordering) -> bool +//@ req [?q]lifetime_token(?k) &*& [_]frac_borrow(k, sync::atomic::bool_slot_content(ref_origin(receiver))) &*& [_]frac_borrow(k, ref_initialized_(receiver)) &*& order != sync::atomic::Ordering::Release &*& order != sync::atomic::Ordering::AcqRel; +//@ ens [q]lifetime_token(k); +//@ on_unwind_ens false; +{ + //@ close exists(false); + //@ close sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ leak sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ close sync::atomic::Ordering_own(currentThread, order); + receiver.load(order) +} diff --git a/verifast-proofs/core/sync/atomic.rs/checks/bool-rmw.rs b/verifast-proofs/core/sync/atomic.rs/checks/bool-rmw.rs new file mode 100644 index 0000000000000..91152d11aa273 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/checks/bool-rmw.rs @@ -0,0 +1,89 @@ +// The enclosing proof module supplies ordinary_bool, prepare_bool and AtomicBool. +unsafe fn borrowed_bool_rmw(initial: bool, operand: bool, order: crate::sync::atomic::Ordering) -> (bool, u8) +//@ req true; +//@ ens result.1 == if result.0 { 1 } else { 0 }; +//@ on_unwind_ens false; +{ + let mut value = initial; + let slot = &raw mut value; + let byte = slot.cast::(); + //@ to_u8s_(slot); + //@ from_u8s_(slot); + //@ let k = begin_lifetime(); + //@ close ordinary_bool(slot)(); + //@ borrow(k, ordinary_bool(slot)); + //@ prepare_bool(slot, k); + { + //@ let_lft 'a = k; + let view = unsafe { AtomicBool::from_ptr/*@::<'a>@*/(slot) }; + //@ close sync::atomic::Ordering_own(currentThread, order); + let old = view.swap(operand, order); + //@ close sync::atomic::Ordering_own(currentThread, order); + let previous = view.fetch_and(old, order); + //@ close sync::atomic::Ordering_own(currentThread, order); + let previous = view.fetch_or(previous, order); + //@ close sync::atomic::Ordering_own(currentThread, order); + let previous = view.fetch_xor(previous, order); + //@ close sync::atomic::Ordering_own(currentThread, order); + let _ = view.fetch_nand(previous, order); + //@ close sync::atomic::Ordering_own(currentThread, order); + let _ = view.fetch_not(order); + } + //@ end_lifetime(k); + //@ borrow_end(k, ordinary_bool(slot)); + //@ open ordinary_bool(slot)(); + let recovered = unsafe { *slot }; + //@ points_to_bool_to_u8(slot); + let encoded = unsafe { *byte }; + //@ if recovered {} else {} + //@ points_to_u8_to_bool(byte); + (recovered, encoded) +} + +macro_rules! byte_row { + ($old:expr, $arg:expr) => {{ + const AND: u8 = $old & $arg; + const OR: u8 = $old | $arg; + const XOR: u8 = $old ^ $arg; + const NAND: u8 = !($old & $arg); + (AND, OR, XOR, NAND) + }}; +} + +// Each value comes from the fixed Rust compiler's byte arithmetic. +unsafe fn byte_results(old: u8, arg: u8) -> (u8, u8, u8, u8) +//@ req sync::atomic::valid_bool_byte(old) == true &*& sync::atomic::valid_bool_byte(arg) == true; +//@ ens result.0 == sync::atomic::bool_byte_after(sync::atomic::byte_and, old, arg) &*& result.1 == sync::atomic::bool_byte_after(sync::atomic::byte_or, old, arg) &*& result.2 == sync::atomic::bool_byte_after(sync::atomic::byte_xor, old, arg) &*& result.3 == sync::atomic::bool_byte_after(sync::atomic::byte_nand, old, arg); +//@ on_unwind_ens false; +{ + if old == 0 { + if arg == 0 { byte_row!(0u8, 0u8) } else { byte_row!(0u8, 1u8) } + } else if arg == 0 { + byte_row!(1u8, 0u8) + } else { + byte_row!(1u8, 1u8) + } +} +unsafe fn shared_bool_nand(receiver: &AtomicBool, val: bool, order: crate::sync::atomic::Ordering) -> bool +//@ req [?q]lifetime_token(?k) &*& [_]frac_borrow(k, sync::atomic::bool_slot_content(ref_origin(receiver))) &*& [_]frac_borrow(k, ref_initialized_(receiver)); +//@ ens [q]lifetime_token(k); +//@ on_unwind_ens false; +{ + //@ close exists(false); + //@ close sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ leak sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ close sync::atomic::Ordering_own(currentThread, order); + receiver.fetch_nand(val, order) +} + +unsafe fn shared_bool_and(receiver: &AtomicBool, val: bool, order: crate::sync::atomic::Ordering) -> bool +//@ req [?q]lifetime_token(?k) &*& [_]frac_borrow(k, sync::atomic::bool_slot_content(ref_origin(receiver))) &*& [_]frac_borrow(k, ref_initialized_(receiver)); +//@ ens [q]lifetime_token(k); +//@ on_unwind_ens false; +{ + //@ close exists(false); + //@ close sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ leak sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ close sync::atomic::Ordering_own(currentThread, order); + receiver.fetch_and(val, order) +} diff --git a/verifast-proofs/core/sync/atomic.rs/checks/bool-storage.gh b/verifast-proofs/core/sync/atomic.rs/checks/bool-storage.gh new file mode 100644 index 0000000000000..165b961842466 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/checks/bool-storage.gh @@ -0,0 +1,45 @@ +/*@ +pred_ctor ordinary_bool(slot: *bool)(;) = *slot |-> ?value; + +lem prepare_bool(slot: *bool, k: lifetime_t) + nonghost_callers_only + req [?q]lifetime_token(k) &*& full_borrow(k, ordinary_bool(slot)); + ens [q]lifetime_token(k) &*& [_]frac_borrow(k, sync::atomic::bool_slot_content(slot)); +{ + let long = open_full_borrow_strong(k, ordinary_bool(slot), q); + open ordinary_bool(slot)(); + { + pred Pre() = *slot |-> ?value; + pred Post() = sync::atomic::bool_slot_content(slot)(); + close Pre(); + produce_lem_ptr_chunk atomic_block(Pre, Post)() { + open Pre(); + assert *slot |-> ?value; + points_to_limits(slot); + points_to_bool_to_u8(slot); + if value {} else {} + std::intrinsics::atomic_align_of_u8(); + div_rem_nonneg(slot as usize, 1); + std::intrinsics::close_atomic_points_to_m(slot as *u8, sync::atomic::valid_bool_byte); + close sync::atomic::bool_slot_content(slot)(); + close Post(); + } { perform_atomically(); } + open Post(); + } + { + pred Ctx() = true; + produce_lem_ptr_chunk full_borrow_convert_strong(Ctx, sync::atomic::bool_slot_content(slot), long, ordinary_bool(slot))() { + open Ctx(); + open sync::atomic::bool_slot_content(slot)(); + std::intrinsics::open_atomic_points_to(slot as *u8); + points_to_u8_to_bool(slot as *u8); + close ordinary_bool(slot)(); + } { + close Ctx(); + close_full_borrow_strong(long, ordinary_bool(slot), sync::atomic::bool_slot_content(slot)); + full_borrow_mono(long, k, sync::atomic::bool_slot_content(slot)); + } + } + full_borrow_into_frac(k, sync::atomic::bool_slot_content(slot)); +} +@*/ diff --git a/verifast-proofs/core/sync/atomic.rs/checks/bool-swap.awk b/verifast-proofs/core/sync/atomic.rs/checks/bool-swap.awk new file mode 100644 index 0000000000000..b96c033d9ef89 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/checks/bool-swap.awk @@ -0,0 +1,28 @@ +# The strict verifier reports rustc's constant if span and subexpressions +# inside the unselected AtomicBool::swap arm. Any other range fails this gate. +FNR == NR { + if ($0 ~ /^ pub const fn swap\(&self, val: bool,/) { fn++ ; in_swap=1 } + if (in_swap && /^ if EMULATE_ATOMIC_BOOL \{$/) first=FNR + if (in_swap && /^ } else \{$/) middle=FNR + if (in_swap && middle && /^ }$/) last=FNR + if (in_swap && /^ }$/) in_swap=0 + next +} +/error:|Fatal error|Detected an inconsistency|panicked at/ { bad=1 } +/: dead code$/ { + count++ + if (!match($0, /\/sync\/atomic\.rs\([0-9]+,[0-9]+(-([0-9]+,)?[0-9]+)?\): dead code$/)) { bad=1; next } + coords=substr($0,RSTART+length("/sync/atomic.rs(")) + sub(/\): dead code$/, "", coords) + split(coords, ends, "-") + split(ends[1], start, ",") + split(ends[2], finish, ",") + a=start[1]+0; b=(finish[2]!="" ? finish[1]+0 : a) + if (a==first && b==last) header++ + else if (a>first && b "/dev/stderr"; bad=1} +} +END { + if (fn!=1 || !(first bool +//@ req true; +//@ ens result == replacement; +//@ on_unwind_ens false; +{ + let mut storage = initial; + let slot = &raw mut storage; + //@ to_u8s_(slot); + //@ from_u8s_(slot); + //@ close ordinary_bool(slot)(); + //@ let k = begin_lifetime(); + //@ borrow(k, ordinary_bool(slot)); + //@ prepare_bool(slot, k); + { + //@ let_lft 'a = k; + let view = unsafe { AtomicBool::from_ptr/*@::<'a>@*/(slot) }; + let address = view.as_ptr(); + //@ assert address as pointer == slot as pointer; + //@ open sync::atomic::Atomic_share::('a, currentThread, view); + //@ let f = open_frac_borrow(k, sync::atomic::bool_slot_content(slot), 1/4); + //@ open [f]sync::atomic::bool_slot_content(slot)(); + //@ close [f]sync::atomic::bool_slot_content(slot)(); + //@ close_frac_borrow(f, sync::atomic::bool_slot_content(slot)); + } + //@ end_lifetime(k); + //@ borrow_end(k, ordinary_bool(slot)); + //@ open ordinary_bool(slot)(); + let recovered = unsafe { *slot }; + //@ points_to_bool_to_u8(slot); + let byte = unsafe { *slot.cast::() }; + //@ if recovered {} else {} + //@ assert byte == if recovered { 1 } else { 0 }; + //@ points_to_u8_to_bool(slot as *u8); + unsafe { *slot = replacement }; + unsafe { *slot } +} + +// Rustc evaluates the two XOR entries on the entire valid byte domain. +// The production XOR(true) and swap(true) call edges are checked in MIR. +const XOR_FALSE_TRUE: u8 = 0u8 ^ 1; +const XOR_TRUE_TRUE: u8 = 1u8 ^ 1; +const _: () = assert!(!(0u8 & 0u8) == 255); + +unsafe fn nand_byte(old: u8, argument: u8) -> u8 +//@ req sync::atomic::valid_bool_byte(old) == true &*& sync::atomic::valid_bool_byte(argument) == true; +//@ ens sync::atomic::valid_bool_byte(result) == true &*& (result == 1) == !(old == 1 && argument == 1); +//@ on_unwind_ens false; +{ + if argument == 1 { + if old == 0 { XOR_FALSE_TRUE } else { XOR_TRUE_TRUE } + } else { + 1 + } +} diff --git a/verifast-proofs/core/sync/atomic.rs/checks/bool_cas_byte_client.rs b/verifast-proofs/core/sync/atomic.rs/checks/bool_cas_byte_client.rs new file mode 100644 index 0000000000000..e2968d86e91c8 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/checks/bool_cas_byte_client.rs @@ -0,0 +1,61 @@ +// A client of the two real unsafe helpers. The production Bool public bodies +// and their target-dependent accesses are independently tracked in the compiler receipts. +use super::{AtomicBool, Ordering, atomic_compare_exchange, atomic_compare_exchange_weak}; + +unsafe fn strong_byte(view: &AtomicBool, expected: bool, next: bool, success: Ordering, failure: Ordering) -> Result +//@ req [?q]lifetime_token(?k) &*& [_]sync::atomic::Atomic_share::(k, currentThread, view) &*& thread_token(currentThread); +//@ ens [q]lifetime_token(k) &*& thread_token(currentThread) &*& result::Result_own::(currentThread, result) &*& match result { Result::Ok(v) => sync::atomic::valid_bool_byte(v) == true &*& (v != 0) == expected, Result::Err(v) => sync::atomic::valid_bool_byte(v) == true &*& (v != 0) != expected }; +//@ on_unwind_ens [q]lifetime_token(k) &*& thread_token(currentThread) &*& (failure == sync::atomic::Ordering::Release || failure == sync::atomic::Ordering::AcqRel); +{ + //@ sync::atomic::begin_bool_access(view, k, currentThread, q/2, failure != sync::atomic::Ordering::Release && failure != sync::atomic::Ordering::AcqRel); + //@ if expected {} else {} + //@ if next {} else {} + //@ vf_on_normal_return(sync::atomic::end_bool_access(view)); + unsafe { atomic_compare_exchange(view.as_ptr().cast::(), expected as u8, next as u8, success, failure) } +} + +unsafe fn weak_byte(view: &AtomicBool, expected: bool, next: bool, success: Ordering, failure: Ordering) -> Result +//@ req [?q]lifetime_token(?k) &*& [_]sync::atomic::Atomic_share::(k, currentThread, view) &*& thread_token(currentThread); +//@ ens [q]lifetime_token(k) &*& thread_token(currentThread) &*& result::Result_own::(currentThread, result) &*& match result { Result::Ok(v) => sync::atomic::valid_bool_byte(v) == true &*& (v != 0) == expected, Result::Err(v) => sync::atomic::valid_bool_byte(v) == true }; +//@ on_unwind_ens [q]lifetime_token(k) &*& thread_token(currentThread) &*& (failure == sync::atomic::Ordering::Release || failure == sync::atomic::Ordering::AcqRel); +{ + //@ sync::atomic::begin_bool_access(view, k, currentThread, q/2, failure != sync::atomic::Ordering::Release && failure != sync::atomic::Ordering::AcqRel); + //@ if expected {} else {} + //@ if next {} else {} + //@ vf_on_normal_return(sync::atomic::end_bool_access(view)); + unsafe { atomic_compare_exchange_weak(view.as_ptr().cast::(), expected as u8, next as u8, success, failure) } +} + +unsafe fn recovered(initial: bool, expected: bool, next: bool, after: bool) -> (Result, Result, bool) +//@ req thread_token(currentThread); +//@ ens thread_token(currentThread) &*& result::Result_own::(currentThread, result.0) &*& result::Result_own::(currentThread, result.1) &*& result.2 == after; +//@ on_unwind_ens false; +{ + let mut value = initial; + let p = &raw mut value; + //@ to_u8s_(p); + //@ from_u8s_(p); + //@ close ordinary_bool(p)(); + //@ let k = begin_lifetime(); + //@ borrow(k, ordinary_bool(p)); + //@ prepare_bool(p, k); + let strong; + let weak; + { + //@ let_lft 'a = k; + let view = unsafe { AtomicBool::from_ptr/*@::<'a>@*/(p) }; + strong = unsafe { strong_byte(view, expected, next, Ordering::Relaxed, Ordering::Relaxed) }; + weak = unsafe { weak_byte(view, expected, next, Ordering::Relaxed, Ordering::Relaxed) }; + } + //@ end_lifetime(k); + //@ borrow_end(k, ordinary_bool(p)); + //@ open ordinary_bool(p)(); + let old = unsafe { *p }; + //@ points_to_bool_to_u8(p); + let byte = unsafe { *p.cast::() }; + //@ if old {} else {} + //@ assert byte == if old { 1 } else { 0 }; + //@ points_to_u8_to_bool(p as *u8); + unsafe { *p = after }; + (strong, weak, unsafe { *p }) +} diff --git a/verifast-proofs/core/sync/atomic.rs/checks/check_mir.rs b/verifast-proofs/core/sync/atomic.rs/checks/check_mir.rs new file mode 100644 index 0000000000000..81e4ef9234a12 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/checks/check_mir.rs @@ -0,0 +1,5265 @@ +//! Zero-dependency verification helper for Challenge 7 MIR, inventory, and interface checks. + +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; +use std::env; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process; + +const PREFIX: &str = "sync::atomic::"; + +fn fail(msg: impl AsRef) -> ! { + eprintln!("ERROR: {}", msg.as_ref()); + process::exit(1); +} + +fn require(cond: bool, msg: impl AsRef) { + if !cond { + fail(msg); + } +} + +fn read_text(path: &Path) -> String { + fs::read_to_string(path).unwrap_or_else(|e| fail(format!("read {}: {e}", path.display()))) +} + +fn is_digits(s: &str) -> bool { + !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()) +} + +fn is_local(s: &str) -> bool { + s.strip_prefix('_').is_some_and(is_digits) +} + +fn is_bb(s: &str) -> bool { + s.strip_prefix("bb").is_some_and(is_digits) +} + +fn is_ident(s: &str) -> bool { + !s.is_empty() && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') +} + +fn strip_move_or_copy(s: &str) -> Option<&str> { + s.strip_prefix("copy ").or_else(|| s.strip_prefix("move ")) +} + +fn mir_blocks(path: &Path) -> BTreeMap> { + let text = read_text(path); + let mut blocks = BTreeMap::new(); + let mut current: Option = None; + let mut lines: Vec = Vec::new(); + for raw in text.lines() { + if current.is_none() { + if let Some(rest) = raw.strip_prefix(" bb") { + if let Some(end) = rest.find(|c: char| !c.is_ascii_digit()) { + let digits = &rest[..end]; + let tail = &rest[end..]; + if !digits.is_empty() && (tail == ": {" || tail == " (cleanup): {") { + current = Some(format!("bb{digits}")); + lines.clear(); + } + } + } + } else if raw == " }" { + let name = current.take().unwrap(); + blocks.insert(name, std::mem::take(&mut lines)); + } else { + let code = raw.split("//").next().unwrap_or("").trim(); + if code.is_empty() { + continue; + } + if let Some(inner) = code + .strip_prefix("StorageLive(") + .or_else(|| code.strip_prefix("StorageDead(")) + .and_then(|s| s.strip_suffix(");")) + { + if is_local(inner) { + continue; + } + } + lines.push(code.to_string()); + } + } + require(current.is_none(), format!("unclosed MIR block in {}", path.display())); + blocks +} + +fn parse_tsv(path: &Path) -> Vec> { + let text = read_text(path); + let mut iter = text.lines().filter(|l| !l.is_empty()); + let header: Vec<&str> = iter + .next() + .unwrap_or_else(|| fail(format!("empty TSV {}", path.display()))) + .split('\t') + .collect(); + let mut out = Vec::new(); + for line in iter { + let fields: Vec<&str> = line.split('\t').collect(); + require(fields.len() == header.len(), format!("malformed TSV row in {}: {line}", path.display())); + let mut row = HashMap::new(); + for (k, v) in header.iter().zip(fields.iter()) { + row.insert((*k).to_string(), (*v).to_string()); + } + out.push(row); + } + out +} + +fn parse_owners(path: &Path) -> BTreeMap { + let mut map = BTreeMap::new(); + for line in read_text(path).lines().filter(|l| !l.is_empty()) { + let (k, v) = line + .split_once('\t') + .unwrap_or_else(|| fail(format!("bad owners row: {line}"))); + map.insert(k.to_string(), v.to_string()); + } + map +} + +fn parse_edges_with_outgoing( + report: &str, +) -> (HashMap<(String, String), Vec>, HashMap>) { + let mut calls: HashMap<(String, String), Vec> = HashMap::new(); + let mut outgoing: HashMap> = HashMap::new(); + let mut sites: HashSet<(String, String)> = HashSet::new(); + for line in report.lines() { + let cols: Vec<&str> = line.split('\t').collect(); + if cols.first().copied() == Some("edge") { + require( + cols.len() == 5 && is_bb(cols[4]), + format!("missing MIR callsite: {line}"), + ); + let site = (cols[1].to_string(), cols[4].to_string()); + require(sites.insert(site.clone()), format!("duplicate receipt for {:?}", site)); + calls + .entry((cols[1].to_string(), cols[2].to_string())) + .or_default() + .push(cols[3].to_string()); + outgoing + .entry(cols[1].to_string()) + .or_default() + .push(cols[2].to_string()); + } + } + (calls, outgoing) +} + +fn parse_edges(report: &str) -> HashMap<(String, String), Vec> { + parse_edges_with_outgoing(report).0 +} + +fn extract_atomic_orderings(s: &str) -> Vec { + let mut out = Vec::new(); + let needle = "AtomicOrdering::"; + let mut rest = s; + while let Some(idx) = rest.find(needle) { + let after = &rest[idx + needle.len()..]; + let end = after + .find(|c: char| !c.is_ascii_alphanumeric() && c != '_') + .unwrap_or(after.len()); + if end > 0 { + out.push(after[..end].to_string()); + } + rest = &after[end..]; + } + out +} + +fn order_discriminant(name: &str) -> &'static str { + match name { + "Relaxed" => "0", + "Release" => "1", + "Acquire" => "2", + "AcqRel" => "3", + "SeqCst" => "4", + other => fail(format!("unknown Ordering {other}")), + } +} + +fn parse_switch_targets(inner: &str) -> Vec<(String, String)> { + let mut out = Vec::new(); + for edge in inner.split(", ") { + let (k, v) = edge + .split_once(": ") + .unwrap_or_else(|| fail(format!("bad switch edge: {edge}"))); + require(is_bb(v), format!("bad switch target: {edge}")); + out.push((k.to_string(), v.to_string())); + } + out +} + +fn parse_goto_or_false_edge(line: &str) -> Option<&str> { + if let Some(bb) = line.strip_prefix("goto -> ").and_then(|s| s.strip_suffix(';')) { + if is_bb(bb) { + return Some(bb); + } + } + if let Some(rest) = line + .strip_prefix("falseEdge -> [real: ") + .and_then(|s| s.strip_suffix("];")) + { + if let Some((real, imag)) = rest.split_once(", imaginary: ") { + if is_bb(real) && is_bb(imag) { + return Some(real); + } + } + } + None +} + +fn is_supported_tail_stmt(line: &str) -> bool { + if let Some(inner) = line + .strip_prefix("PlaceMention(") + .and_then(|s| s.strip_suffix(");")) + { + return is_local(inner); + } + let Some((lhs, rhs)) = line.strip_suffix(';').and_then(|s| s.split_once(" = ")) else { + return false; + }; + if !is_local(lhs) { + return false; + } + if rhs == "const ()" { + return true; + } + if let Some(src) = strip_move_or_copy(rhs) { + if is_local(src) { + return true; + } + if let Some(inner) = src.strip_prefix('(').and_then(|s| s.strip_suffix(')')) { + for suffix in [".0: T", ".1: T", ".0: bool", ".1: bool"] { + if let Some(loc) = inner.strip_suffix(suffix) { + if is_local(loc) { + return true; + } + } + } + } + } + for prefix in [ + "result::Result::::Ok(move ", + "result::Result::::Err(move ", + ] { + if let Some(loc) = rhs.strip_prefix(prefix).and_then(|s| s.strip_suffix(')')) { + if is_local(loc) { + return true; + } + } + } + false +} + +fn parse_atomic_call_name(line: &str) -> Option { + let (_, rhs) = line.split_once(" = ")?; + let rhs = rhs.strip_prefix("intrinsics::").unwrap_or(rhs); + let (name, _) = rhs.split_once("::<")?; + if name.starts_with("atomic_") && is_ident(name) { + Some(name.to_string()) + } else { + None + } +} + +fn check_route_tail( + blocks: &BTreeMap>, + start: &str, + terminal: &str, + first_call: &str, +) { + fn visit( + blocks: &BTreeMap>, + block: &str, + terminal: &str, + first_call: &str, + active: &mut HashSet, + finished: &mut HashSet, + ) { + if finished.contains(block) { + return; + } + require(!active.contains(block), format!("{first_call}: loop after the call at {block}")); + active.insert(block.to_string()); + let stmts = blocks + .get(block) + .unwrap_or_else(|| fail(format!("{first_call}: missing block {block}"))); + let (end, body) = stmts + .split_last() + .unwrap_or_else(|| fail(format!("{first_call}: empty block {block}"))); + for line in body { + require( + is_supported_tail_stmt(line), + format!("{first_call}/{block}: unsupported tail statement {line}"), + ); + } + if end == terminal { + // Done + } else if let Some(next) = parse_goto_or_false_edge(end) { + visit(blocks, next, terminal, first_call, active, finished); + } else if let Some(inner) = end + .strip_prefix("switchInt(") + .and_then(|s| s.strip_suffix("];")) + .and_then(|s| s.split_once(") -> [")) + { + require( + strip_move_or_copy(inner.0).is_some_and(is_local), + format!("{first_call}/{block}: bad switchInt {end}"), + ); + for (_, tgt) in parse_switch_targets(inner.1) { + visit(blocks, &tgt, terminal, first_call, active, finished); + } + } else if let Some(callee) = parse_atomic_call_name(end) { + fail(format!("{first_call}: second atomic call {callee} at {block}")); + } else { + fail(format!("{first_call}/{block}: expected path to {terminal}, found {end}")); + } + active.remove(block); + finished.insert(block.to_string()); + } + + let mut active = HashSet::new(); + let mut finished = HashSet::new(); + visit(blocks, start, terminal, first_call, &mut active, &mut finished); +} + +#[derive(Clone)] +enum OrdVal { + Scalar(String), + Pair(String, String), + Unknown, +} + +fn ordering_route( + blocks: &BTreeMap>, + inputs: &[String], + helper: &str, + intrinsic: &str, + order: &str, +) { + let parts: Vec<&str> = order.split('/').collect(); + require( + inputs.len() == parts.len(), + format!("{helper}: expected {} ordering inputs, found {}", parts.len(), inputs.len()), + ); + let mut values: HashMap = HashMap::new(); + for (inp, ord) in inputs.iter().zip(parts.iter()) { + values.insert(inp.clone(), OrdVal::Scalar(order_discriminant(ord).to_string())); + } + let mut block = "bb0".to_string(); + let mut seen = HashSet::new(); + while seen.insert(block.clone()) { + let stmts = blocks + .get(&block) + .unwrap_or_else(|| fail(format!("{helper}: missing block {block}"))); + let mut advanced = false; + for line in stmts { + if let Some(inner) = line + .strip_prefix("PlaceMention(") + .and_then(|s| s.strip_suffix(");")) + { + if is_local(inner) { + continue; + } + } + if let Some(next) = parse_goto_or_false_edge(line) { + block = next.to_string(); + advanced = true; + break; + } + if let Some(rest) = line + .strip_prefix("switchInt(move ") + .and_then(|s| s.strip_suffix("];")) + { + if let Some((loc, branches)) = rest.split_once(") -> [") { + if is_local(loc) { + let targets = parse_switch_targets(branches); + let disc = match values.get(loc) { + Some(OrdVal::Scalar(s)) => s.as_str(), + _ => fail(format!("{helper}/{block}: non-scalar switch local {loc}")), + }; + let next = targets + .iter() + .find(|(k, _)| k == disc) + .or_else(|| targets.iter().find(|(k, _)| k == "otherwise")) + .map(|(_, v)| v.clone()) + .unwrap_or_else(|| fail(format!("{helper}/{block}: missing switch target for {disc}"))); + block = next; + advanced = true; + break; + } + } + } + if let Some((lhs, rhs)) = line.strip_suffix(';').and_then(|s| s.split_once(" = ")) { + if is_local(lhs) { + if let Some(src) = strip_move_or_copy(rhs).filter(|s| is_local(s)) { + let v = values.get(src).cloned().unwrap_or(OrdVal::Unknown); + values.insert(lhs.to_string(), v); + continue; + } + if let Some(inner) = rhs.strip_prefix("(move ").and_then(|s| s.strip_suffix(')')) { + if let Some((a, b)) = inner.split_once(", move ") { + if is_local(a) && is_local(b) { + let va = match values.get(a) { + Some(OrdVal::Scalar(s)) => s.clone(), + _ => fail(format!("{helper}/{block}: bad pair element {a}")), + }; + let vb = match values.get(b) { + Some(OrdVal::Scalar(s)) => s.clone(), + _ => fail(format!("{helper}/{block}: bad pair element {b}")), + }; + values.insert(lhs.to_string(), OrdVal::Pair(va, vb)); + continue; + } + } + } + if let Some(inner) = rhs.strip_prefix("discriminant(").and_then(|s| s.strip_suffix(')')) { + if is_local(inner) { + let v = values.get(inner).cloned().unwrap_or(OrdVal::Unknown); + values.insert(lhs.to_string(), v); + continue; + } + if let Some(tup) = inner + .strip_prefix('(') + .and_then(|s| s.strip_suffix(": sync::atomic::Ordering)")) + { + if let Some((base, idx)) = tup.rsplit_once('.') { + if is_local(base) && (idx == "0" || idx == "1") { + let val = match values.get(base) { + Some(OrdVal::Pair(a, b)) => { + if idx == "0" { + OrdVal::Scalar(a.clone()) + } else { + OrdVal::Scalar(b.clone()) + } + } + _ => fail(format!("{helper}/{block}: non-pair discriminant {inner}")), + }; + values.insert(lhs.to_string(), val); + continue; + } + } + } + } + if let Some((call_part, term_part)) = rhs.split_once(") -> [return: ") { + if let Some((ret_bb, unw_bb)) = + term_part.strip_suffix(']').and_then(|s| s.split_once(", unwind: ")) + { + if is_bb(ret_bb) && is_bb(unw_bb) { + let no_pref = call_part.strip_prefix("intrinsics::").unwrap_or(call_part); + if let Some((callee, after_lt)) = no_pref.split_once("::<") { + if callee.starts_with("atomic_") && is_ident(callee) { + if let Some((generics, _)) = after_lt.split_once(">(") { + let actual = extract_atomic_orderings(generics).join("/"); + require( + callee == intrinsic && actual == order, + format!( + "{helper} input {order} reached {callee}/{actual} at {block}" + ), + ); + let first_call = + format!("{helper} input {order} called {intrinsic} at {block}"); + check_route_tail(blocks, unw_bb, "resume;", &first_call); + check_route_tail(blocks, ret_bb, "return;", &first_call); + return; + } + } + } + } + } + } + } + } + fail(format!("{helper}/{block}: unsupported ordering path {line}")); + } + require(advanced, format!("{helper}/{block}: missing terminator")); + } + fail(format!("{helper}: loop in ordering dispatch")); +} + +fn extract_ordering_inputs(path: &Path) -> Vec { + let text = read_text(path); + let sig = text + .lines() + .find(|l| l.starts_with("fn ")) + .unwrap_or_else(|| fail(format!("missing fn signature in {}", path.display()))); + let mut out = Vec::new(); + let needle = ": atomic::Ordering"; + let mut start = 0; + while let Some(pos) = sig[start..].find(needle) { + let abs = start + pos; + let after = &sig[abs + needle.len()..]; + let boundary = after + .chars() + .next() + .is_none_or(|c| !c.is_ascii_alphanumeric() && c != '_'); + if boundary { + let before = &sig[..abs]; + let loc_start = before + .rfind(|c: char| !c.is_ascii_alphanumeric() && c != '_') + .map_or(0, |i| i + 1); + let loc = &before[loc_start..]; + if is_local(loc) { + out.push(loc.to_string()); + } + } + start = abs + needle.len(); + } + out +} + +fn check_routes(mir_dir: &Path, cases: &[HashMap]) { + let mut cache: HashMap>, Vec)> = HashMap::new(); + for case in cases { + let helper = &case["unsafe_helper"]; + let entry = cache.entry(helper.clone()).or_insert_with(|| { + let file = mir_dir.join(format!("core.sync-atomic-{helper}.built.after.mir")); + let inputs = extract_ordering_inputs(&file); + (mir_blocks(&file), inputs) + }); + ordering_route( + &entry.0, + &entry.1, + helper, + &case["compiler_intrinsic"], + &case["ordering"], + ); + } +} + +#[derive(Clone, PartialEq, Eq, Debug)] +enum BoolVal { + Str(&'static str), + Byte(&'static str), + Helper(String, u8), + U8(u8), + Bool(bool), + Public(String, bool), +} + +fn trace_bool_cas( + blocks: &BTreeMap>, + method: &str, + outcome: &str, + old: u8, +) { + let mut values: HashMap = HashMap::from([ + ("_1".into(), BoolVal::Str("receiver")), + ("_2".into(), BoolVal::Str("expected")), + ("_3".into(), BoolVal::Str("replacement")), + ("_4".into(), BoolVal::Str("success")), + ("_5".into(), BoolVal::Str("failure")), + ]); + let mut block = "bb0".to_string(); + let mut visited = HashSet::new(); + let mut calls: Vec = Vec::new(); + while visited.insert(block.clone()) { + let stmts = blocks + .get(&block) + .unwrap_or_else(|| fail(format!("{method}: missing block {block}"))); + let mut next_block: Option = None; + for (index, line) in stmts.iter().enumerate() { + let last = index + 1 == stmts.len(); + if let Some((dst, rhs)) = line.strip_suffix(';').and_then(|s| s.split_once(" = ")) { + if is_local(dst) { + if rhs == "const sync::atomic::EMULATE_ATOMIC_BOOL" { + values.insert(dst.into(), BoolVal::U8(0)); + } else if rhs == "const ()" { + values.insert(dst.into(), BoolVal::Str("unit")); + } else if rhs == "&((*_1).0: cell::UnsafeCell>)" { + values.insert(dst.into(), BoolVal::Str("receiver-cell")); + } else if let Some(src) = rhs.strip_prefix("copy ").filter(|s| is_local(s)) { + let v = values.get(src).cloned().unwrap_or_else(|| fail(format!("{method}: missing {src}"))); + values.insert(dst.into(), v); + } else if let Some(src) = rhs + .strip_prefix("move ") + .and_then(|s| s.strip_suffix(" as u8 (IntToInt)")) + .filter(|s| is_local(s)) + { + let v = values.get(src).unwrap_or_else(|| fail(format!("{method}: missing {src}"))); + match v { + BoolVal::Str("expected") => values.insert(dst.into(), BoolVal::Byte("expected")), + BoolVal::Str("replacement") => values.insert(dst.into(), BoolVal::Byte("replacement")), + _ => fail("cast did not consume an original bool operand"), + }; + } else if let Some(src) = rhs + .strip_prefix("discriminant(") + .and_then(|s| s.strip_suffix(')')) + .filter(|s| is_local(s)) + { + require( + values.get(src) == Some(&BoolVal::Helper(outcome.into(), old)), + "discriminator did not come from the helper", + ); + values.insert(dst.into(), BoolVal::U8(if outcome == "Ok" { 0 } else { 1 })); + } else if let Some(inner) = rhs + .strip_prefix("copy ((") + .and_then(|s| s.strip_suffix(").0: u8)")) + { + let (loc, tag) = inner + .split_once(" as ") + .unwrap_or_else(|| fail(format!("{method}/{block}: bad projection {line}"))); + require( + is_local(loc) + && (tag == "Ok" || tag == "Err") + && outcome == tag + && values.get(loc) == Some(&BoolVal::Helper(tag.into(), old)), + "wrong byte result projection", + ); + values.insert(dst.into(), BoolVal::U8(old)); + } else if let Some(src) = rhs + .strip_prefix("Ne(move ") + .and_then(|s| s.strip_suffix(", const 0_u8)")) + .filter(|s| is_local(s)) + { + require( + values.get(src) == Some(&BoolVal::U8(old)), + "boolean return does not use the observed byte", + ); + values.insert(dst.into(), BoolVal::Bool(old != 0)); + } else if let Some(rest) = rhs.strip_prefix("result::Result::::") { + let (tag, loc) = rest + .split_once("(move ") + .and_then(|(t, r)| r.strip_suffix(')').map(|l| (t, l))) + .unwrap_or_else(|| fail(format!("{method}/{block}: bad Result {line}"))); + require( + (tag == "Ok" || tag == "Err") && is_local(loc), + format!("{method}/{block}: bad Result {line}"), + ); + let b = match values.get(loc) { + Some(BoolVal::Bool(b)) => *b, + _ => fail("the public result must contain a bool"), + }; + values.insert(dst.into(), BoolVal::Public(tag.into(), b)); + } else if let Some((call_part, term_part)) = rhs.split_once(") -> [return: ") { + let (normal, unwind) = term_part + .strip_suffix(']') + .and_then(|s| s.split_once(", unwind: ")) + .unwrap_or_else(|| fail(format!("{method}/{block}: bad call {line}"))); + require(is_bb(normal) && is_bb(unwind), format!("{method}/{block}: bad call {line}")); + let (callee, operands) = call_part + .split_once('(') + .unwrap_or_else(|| fail(format!("{method}/{block}: bad call {line}"))); + let mut args = Vec::new(); + for operand in operands.split(", ") { + let loc = operand + .strip_prefix("move ") + .filter(|s| is_local(s)) + .unwrap_or_else(|| fail(format!("unexpected {callee} argument {operand}"))); + args.push( + values + .get(loc) + .cloned() + .unwrap_or_else(|| fail(format!("{method}: missing {loc}"))), + ); + } + require( + last && blocks.get(unwind).is_some_and(|b| b.as_slice() == ["resume;"]), + format!("{callee}: extra cleanup access"), + ); + if callee == "UnsafeCell::>::get" { + require(args == [BoolVal::Str("receiver-cell")], "wrong UnsafeCell field"); + values.insert(dst.into(), BoolVal::Str("raw-receiver")); + } else if callee == "ptr::mut_ptr::>::cast::" { + require(args == [BoolVal::Str("raw-receiver")], "cast changed slot identity"); + values.insert(dst.into(), BoolVal::Str("byte-slot")); + } else { + let expected_callee = format!("atomic_{method}::"); + let expected_args = vec![ + BoolVal::Str("byte-slot"), + BoolVal::Byte("expected"), + BoolVal::Byte("replacement"), + BoolVal::Str("success"), + BoolVal::Str("failure"), + ]; + require( + callee == expected_callee && args == expected_args, + format!("{method}: wrong CAS helper, slot, operand or Ordering"), + ); + values.insert(dst.into(), BoolVal::Helper(outcome.into(), old)); + } + calls.push(callee.to_string()); + next_block = Some(normal.to_string()); + break; + } else { + fail(format!("{method}/{block}: unsupported assignment {line}")); + } + require(!last, format!("{method}: block lacks a recognized terminator")); + continue; + } + } + if let Some(bb) = line.strip_prefix("goto -> ").and_then(|s| s.strip_suffix(';')) { + require(last && is_bb(bb), "nonterminal goto"); + next_block = Some(bb.to_string()); + break; + } else if let Some(rest) = line + .strip_prefix("switchInt(move ") + .and_then(|s| s.strip_suffix("];")) + { + let (loc, branches) = rest + .split_once(") -> [") + .unwrap_or_else(|| fail(format!("{method}/{block}: bad switchInt {line}"))); + require(last && is_local(loc), "nonterminal switch"); + let key = match values.get(loc) { + Some(BoolVal::U8(n)) => n.to_string(), + _ => fail(format!("{method}/{block}: non-u8 switch value {loc}")), + }; + let targets = parse_switch_targets(branches); + let tgt = targets + .into_iter() + .find(|(k, _)| k == &key) + .map(|(_, v)| v) + .unwrap_or_else(|| fail(format!("{method}/{block}: missing switch target {key}"))); + next_block = Some(tgt); + break; + } else if let Some(real) = line + .strip_prefix("falseEdge -> [real: ") + .and_then(|s| s.strip_suffix("];")) + .and_then(|s| s.split_once(", imaginary: ")) + .filter(|(r, i)| is_bb(r) && is_bb(i)) + .map(|(r, _)| r) + { + require(last, "nonterminal falseEdge"); + next_block = Some(real.to_string()); + break; + } else if let Some(loc) = line + .strip_prefix("PlaceMention(") + .and_then(|s| s.strip_suffix(");")) + .filter(|s| is_local(s)) + { + require( + !last && values.get(loc) == Some(&BoolVal::Helper(outcome.into(), old)), + "unexpected place mention", + ); + } else if line == "return;" { + require( + last && values.get("_0") == Some(&BoolVal::Public(outcome.into(), old != 0)), + format!("{method}: incorrect public return"), + ); + let expected_calls = vec![ + "UnsafeCell::>::get".to_string(), + "ptr::mut_ptr::>::cast::".to_string(), + format!("atomic_{method}::"), + ]; + require(calls == expected_calls, format!("{method}: wrong number or order of calls")); + return; + } else { + fail(format!("{method}/{block}: unsupported operation {line}")); + } + } + block = next_block.unwrap_or_else(|| fail(format!("{method}/{block}: missing terminator"))); + } + fail(format!("{method}: loop before the terminal return")); +} + +fn cmd_mir(mir_dir: &Path, target: &str, owners_out: &Path) { + // 1. Discover Atomic::from_ptr impl owners + let mut owners: BTreeMap = BTreeMap::new(); + for entry in fs::read_dir(mir_dir).unwrap_or_else(|e| fail(format!("read_dir: {e}"))) { + let path = entry.unwrap().path(); + let fname = path.file_name().unwrap().to_string_lossy(); + if fname.starts_with("core.sync-atomic-{impl#") && fname.ends_with("}-from_ptr.built.after.mir") { + let text = read_text(&path); + if let Some(pos) = text.find("::from_ptr(_1: *mut ") { + let after = &text[pos + "::from_ptr(_1: *mut ".len()..]; + if let Some((ty, rest)) = after.split_once(") -> &Atomic<") { + if rest.starts_with(&format!("{ty}>")) { + let impl_id = fname.split('-').nth(2).unwrap().to_string(); + require(!owners.contains_key(ty), format!("duplicate atomic impl for {ty}")); + owners.insert(ty.to_string(), impl_id); + } + } + } + } + } + let mut expected: BTreeSet<&str> = [ + "i8", "u8", "i16", "u16", "i32", "u32", "i64", "u64", "isize", "usize", "bool", "*mut T", + ] + .into_iter() + .collect(); + if target == "aarch64-unknown-linux-gnu" { + expected.insert("i128"); + expected.insert("u128"); + } + let actual: BTreeSet<&str> = owners.keys().map(String::as_str).collect(); + require(actual == expected, format!("unexpected enabled impls: {:?}", owners)); + let mut tsv = String::new(); + for (k, v) in &owners { + tsv.push_str(&format!("{k}\t{v}\n")); + } + fs::write(owners_out, tsv).unwrap_or_else(|e| fail(format!("write owners: {e}"))); + + // 2. EMULATE_ATOMIC_BOOL must be false + let emulate = mir_blocks(&mir_dir.join("core.sync-atomic-EMULATE_ATOMIC_BOOL.built.after.mir")); + let expected_emulate = BTreeMap::from([( + "bb0".to_string(), + vec!["_0 = const false;".to_string(), "return;".to_string()], + )]); + require(emulate == expected_emulate, "native byte CAS required (EMULATE_ATOMIC_BOOL != false)"); + + // 3. Atomic::as_ptr + let as_ptr_path = mir_dir.join("core.sync-atomic-{impl#4}-as_ptr.built.after.mir"); + require( + read_text(&as_ptr_path).contains("::as_ptr(_1: &Atomic) -> *mut bool"), + "wrong Bool slot signature", + ); + let expected_as_ptr = BTreeMap::from([ + ( + "bb0".into(), + vec![ + "_3 = &((*_1).0: cell::UnsafeCell>);".into(), + "_2 = UnsafeCell::>::get(move _3) -> [return: bb1, unwind: bb3];".into(), + ], + ), + ( + "bb1".into(), + vec!["_0 = ptr::mut_ptr::>::cast::(move _2) -> [return: bb2, unwind: bb3];".into()], + ), + ("bb2".into(), vec!["return;".into()]), + ("bb3".into(), vec!["resume;".into()]), + ]); + require(mir_blocks(&as_ptr_path) == expected_as_ptr, "as_ptr did not return the first field's original slot"); + + // 4. fetch_ptr_add, fetch_ptr_sub, mem::size_of, usize::wrapping_mul + for method in ["fetch_ptr_add", "fetch_ptr_sub"] { + let op = method.rsplit('_').next().unwrap(); + let file = mir_dir.join(format!("core.sync-atomic-{{impl#5}}-{method}.built.after.mir")); + require( + read_text(&file).contains(&format!( + "::{method}(_1: &Atomic<*mut T>, _2: usize, _3: atomic::Ordering) -> *mut T" + )), + format!("{method}: unexpected receiver or operand"), + ); + let expected_blocks = BTreeMap::from([ + ( + "bb0".into(), + vec![ + "_4 = &(*_1);".into(), + "_6 = copy _2;".into(), + "_7 = mem::size_of::() -> [return: bb1, unwind: bb4];".into(), + ], + ), + ( + "bb1".into(), + vec!["_5 = num::::wrapping_mul(move _6, move _7) -> [return: bb2, unwind: bb4];".into()], + ), + ( + "bb2".into(), + vec![ + "_8 = copy _3;".into(), + format!("_0 = Atomic::<*mut T>::fetch_byte_{op}(move _4, move _5, move _8) -> [return: bb3, unwind: bb4];"), + ], + ), + ("bb3".into(), vec!["return;".into()]), + ("bb4".into(), vec!["resume;".into()]), + ]); + require(mir_blocks(&file) == expected_blocks, format!("{method}: extra access or altered byte-method edge")); + println!("{}", file.file_name().unwrap().to_string_lossy()); + } + let size_file = mir_dir.join("core.mem-size_of.runtime-post-cleanup.after.mir"); + require(read_text(&size_file).contains("fn mem::size_of() -> usize {"), "unexpected size_of signature"); + require( + mir_blocks(&size_file) + == BTreeMap::from([( + "bb0".into(), + vec!["_0 = const ::SIZE;".into(), "return;".into()], + )]), + "size_of is not a single type-associated constant", + ); + println!("{}", size_file.file_name().unwrap().to_string_lossy()); + + let mut muls: Vec = Vec::new(); + for entry in fs::read_dir(mir_dir).unwrap() { + let p = entry.unwrap().path(); + let name = p.file_name().unwrap().to_string_lossy(); + if name.starts_with("core.num-") && name.ends_with("-wrapping_mul.runtime-post-cleanup.after.mir") { + let text = read_text(&p); + if text.lines().any(|l| { + l.starts_with("fn num::::wrapping_mul(_1: usize, _2: usize) -> usize {") + }) { + muls.push(p); + } + } + } + require(muls.len() == 1, format!("expected 1 usize::wrapping_mul MIR file, found {}", muls.len())); + let mul = &muls[0]; + require( + mir_blocks(mul) + == BTreeMap::from([( + "bb0".into(), + vec![ + "_3 = copy _1;".into(), + "_4 = copy _2;".into(), + "_0 = Mul(move _3, move _4);".into(), + "return;".into(), + ], + )]), + "usize::wrapping_mul must be a local multiplication with no call, unwind or shared access", + ); + println!("{}", mul.file_name().unwrap().to_string_lossy()); + + // 5. Native Bool CAS symbolic trace across all 8 (Ok/Err) x (0/1) outcomes + for method in ["compare_exchange", "compare_exchange_weak"] { + let file = mir_dir.join(format!("core.sync-atomic-{{impl#4}}-{method}.built.after.mir")); + require( + read_text(&file).contains(&format!( + "::{method}(_1: &Atomic, _2: bool, _3: bool, _4: atomic::Ordering, _5: atomic::Ordering) -> result::Result" + )), + "wrong public signature", + ); + let blocks = mir_blocks(&file); + for outcome in ["Ok", "Err"] { + for old in [0u8, 1u8] { + trace_bool_cas(&blocks, method, outcome, old); + println!("{method}\t{outcome}\t{old}\t{}\tsame-slot\toriginal-orderings\tcleanup-resumes", u8::from(old != 0)); + } + } + } +} + +fn check_intrinsic_site( + calls: &HashMap<(String, String), Vec>, + helper: &str, + intrinsic: &str, + order: &str, +) -> String { + let want: Vec = order.split('/').map(String::from).collect(); + let matches: Vec<&String> = calls + .get(&(format!("{PREFIX}{helper}"), format!("intrinsics::{intrinsic}"))) + .into_iter() + .flatten() + .filter(|e| extract_atomic_orderings(e) == want) + .collect(); + require(matches.len() == 1, format!("missing unique {helper} -> {intrinsic}/{order}")); + matches[0].clone() +} + +fn check_path( + functions: &HashSet, + calls: &HashMap<(String, String), Vec>, + owner: &str, + scalar: &str, + method: &str, + helper: &str, + intrinsic: &str, + order: &str, +) { + let qualified = format!("{PREFIX}{helper}"); + let fn_name = format!("{PREFIX}Atomic::<{scalar}>::{method}"); + require( + functions.contains(&fn_name) && functions.contains(&qualified), + format!("unchecked body in {fn_name} -> {qualified}"), + ); + let edge_list = calls + .get(&(format!("{PREFIX}{owner}::{method}"), qualified.clone())) + .unwrap_or_else(|| fail(format!("missing call edge {owner}::{method} -> {qualified}"))); + require(edge_list.len() == 1, format!("expected 1 call edge for {owner}::{method} -> {qualified}")); + let public = &edge_list[0]; + let args = match method { + "store" | "load" => format!("{scalar}, false"), + "swap" | "compare_exchange" | "compare_exchange_weak" | "fetch_max" | "fetch_min" => scalar.to_string(), + _ => format!("{scalar}, {}", if scalar == "*mut T" { "usize" } else { scalar }), + }; + require( + public.contains(&format!("{helper}::<{args}>")), + format!("wrong slot or operand in {public}"), + ); + let call = check_intrinsic_site(calls, helper, intrinsic, order); + if method == "store" || method == "load" { + require(call.ends_with(", VOLATILE>}"), format!("altered volatile forwarding in {call}")); + } +} + +fn canonical_ordering_token(tok: &str) -> &'static str { + match tok { + "relaxed" => "Relaxed", + "acquire" => "Acquire", + "release" => "Release", + "acqrel" => "AcqRel", + "seqcst" => "SeqCst", + other => fail(format!("unknown ordering token in challenge entry: {other}")), + } +} + +fn expected_from_challenge_entry(entry: &str) -> (String, String) { + let parts: Vec<&str> = entry.split('_').collect(); + require(parts.first().copied() == Some("atomic"), format!("unexpected challenge entry {entry}")); + match parts.as_slice() { + ["atomic", op, o1] => (format!("atomic_{op}"), canonical_ordering_token(o1).to_string()), + ["atomic", op @ ("cxchg" | "cxchgweak"), o1, o2] => ( + format!("atomic_{op}"), + format!("{}/{}", canonical_ordering_token(o1), canonical_ordering_token(o2)), + ), + _ => fail(format!("unexpected challenge entry format: {entry}")), + } +} + +fn extract_local_refs(expr: &str) -> Vec<&str> { + let bytes = expr.as_bytes(); + let mut out = Vec::new(); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'_' { + let prev_ident = i > 0 && (bytes[i - 1].is_ascii_alphanumeric() || bytes[i - 1] == b'_'); + if !prev_ident { + let mut j = i + 1; + while j < bytes.len() && bytes[j].is_ascii_digit() { + j += 1; + } + let next_ident = j < bytes.len() && (bytes[j].is_ascii_alphanumeric() || bytes[j] == b'_'); + if j > i + 1 && !next_ident { + out.push(&expr[i..j]); + i = j; + continue; + } + } + } + i += 1; + } + out +} + +fn split_call_terminator(rhs: &str) -> Option<(&str, &str, Option<&str>)> { + let (call_part, term_part) = rhs.split_once(") -> [return: ")?; + let inner = term_part.strip_suffix(']')?; + if let Some((ret_bb, unw_bb)) = inner.split_once(", unwind: ") { + Some((call_part, ret_bb, Some(unw_bb))) + } else if let Some((ret_bb, unw_tail)) = inner.split_once(", unwind ") { + if unw_tail == "continue" || unw_tail == "unreachable" || unw_tail.starts_with("terminate(") { + Some((call_part, ret_bb, None)) + } else { + None + } + } else { + None + } +} + +fn split_call_callee_operands(call_part: &str) -> Option<(&str, &str)> { + let mut angle = 0usize; + let bytes = call_part.as_bytes(); + for (i, &b) in bytes.iter().enumerate() { + match b { + b'<' => angle += 1, + b'>' => { + if !(i > 0 && bytes[i - 1] == b'-') { + angle = angle.saturating_sub(1); + } + } + b'(' if angle == 0 => return Some((&call_part[..i], &call_part[i + 1..])), + _ => {} + } + } + None +} + +fn extract_mir_callee_base(raw_callee: &str) -> &str { + let callee_no_pref = raw_callee.strip_prefix("atomic::").unwrap_or(raw_callee); + if let Some((before_gen, _)) = callee_no_pref.split_once("::<") { + if let Some((_, after_gen)) = callee_no_pref.rsplit_once(">::") { + after_gen.split_once("::<").map_or(after_gen, |(b, _)| b) + } else { + before_gen.rsplit_once("::").map_or(before_gen, |(_, b)| b) + } + } else { + callee_no_pref.rsplit_once("::").map_or(callee_no_pref, |(_, b)| b) + } +} + +/// Strict exact-callee matcher for the single allowed atomic helper called by a public method. +/// Rejects arbitrary free functions sharing only the final identifier suffix (e.g. `fallback::fetch_xor`) +/// and verifies exact argument arity. +fn match_expected_atomic_helper<'a>( + raw_callee: &str, + scalar: &str, + method: &str, + allowed_helpers: &[&'a str], + arg_count: usize, +) -> Option<&'a str> { + let expected_arity = match method { + "load" => 2, + "compare_exchange" | "compare_exchange_weak" => 5, + _ => 3, + }; + if arg_count != expected_arity { + return None; + } + let stripped = raw_callee.strip_prefix("atomic::").unwrap_or(raw_callee); + for &helper in allowed_helpers { + if helper.starts_with("atomic_") { + if stripped.starts_with(&format!("{helper}::<")) { + return Some(helper); + } + } else if scalar == "bool" && raw_callee == format!("Atomic::::{helper}") { + return Some(helper); + } + } + None +} + +/// Strict allowlist of pure, non-atomic address-computation helpers that legitimate +/// `core::sync::atomic` public methods may call alongside their single atomic helper. +/// Any other call (including `store_volatile`, `load_volatile`, indirect calls, or +/// unknown helper wrappers) is rejected fail-closed. +fn is_pure_address_helper(raw_callee: &str) -> bool { + (raw_callee.starts_with("Atomic::<") && raw_callee.ends_with(">::as_ptr")) + || (raw_callee.starts_with("UnsafeCell::<") && raw_callee.ends_with(">::get")) + || (raw_callee.starts_with("ptr::mut_ptr::::cast::<")) +} + +fn check_public_ordering_forwarding( + mir_dir: &Path, + owner: &str, + scalar: &str, + method: &str, + helpers_spec: &str, +) { + let allowed_helpers: Vec<&str> = helpers_spec.split('|').collect(); + let file = mir_dir.join(format!("core.sync-atomic-{owner}-{method}.built.after.mir")); + let inputs = extract_ordering_inputs(&file); + let expected_inputs = if matches!(method, "compare_exchange" | "compare_exchange_weak") { + 2 + } else { + 1 + }; + require( + inputs.len() == expected_inputs, + format!( + "Atomic::<{scalar}>::{method}: expected {expected_inputs} Ordering parameters, found {}", + inputs.len() + ), + ); + let blocks = mir_blocks(&file); + + // Flow-insensitive address-taken set: any local whose address/reference is taken anywhere + // in the function (e.g. `&o`, `&mut o`, `&raw mut o`, `&raw const o`) may be aliased and + // mutated through a pointer, so it can NEVER be trusted as an unmodified Ordering source. + let mut addr_taken: HashSet = HashSet::new(); + for stmts in blocks.values() { + for line in stmts { + if let Some((_, rhs)) = line.strip_suffix(';').and_then(|s| s.split_once(" = ")) { + if rhs.contains('&') { + for loc in extract_local_refs(rhs) { + addr_taken.insert(loc.to_string()); + } + } + } + } + } + + let initial_ord: BTreeMap = inputs + .iter() + .enumerate() + .filter(|(_, loc)| !addr_taken.contains(loc.as_str())) + .map(|(idx, loc)| (loc.clone(), idx)) + .collect(); + + type StateKey = (String, bool, usize, Vec<(String, usize)>, Vec); + + #[allow(clippy::too_many_arguments)] + fn visit( + blocks: &BTreeMap>, + addr_taken: &HashSet, + block: &str, + scalar: &str, + method: &str, + allowed_helpers: &[&str], + expected_inputs: usize, + unwind_mode: bool, + mut seen_helper: usize, + mut ord_origin: BTreeMap, + mut emulate_locals: BTreeSet, + active: &mut HashSet, + memo: &mut HashSet, + ) { + let key: StateKey = ( + block.to_string(), + unwind_mode, + seen_helper, + ord_origin.iter().map(|(k, v)| (k.clone(), *v)).collect(), + emulate_locals.iter().cloned().collect(), + ); + if memo.contains(&key) { + return; + } + require(!active.contains(block), format!("Atomic::<{scalar}>::{method}: loop at {block}")); + let stmts = blocks + .get(block) + .unwrap_or_else(|| fail(format!("Atomic::<{scalar}>::{method}: missing block {block}"))); + active.insert(block.to_string()); + for line in stmts { + // Non-assignment MIR statements that mutate/deinit places or are opaque. + if line.starts_with("asm!(") { + fail(format!("Atomic::<{scalar}>::{method}/{block}: unsupported asm statement {line}")); + } + if let Some(rest) = line + .strip_prefix("discriminant(") + .or_else(|| line.strip_prefix("SetDiscriminant(")) + .or_else(|| line.strip_prefix("Deinit(")) + { + for loc in extract_local_refs(rest) { + ord_origin.remove(loc); + emulate_locals.remove(loc); + } + continue; + } + if line.starts_with("FakeRead(") + || line.starts_with("AscribeUserType(") + || line.starts_with("PlaceMention(") + || line.starts_with("Retag(") + || line == "nop;" + || line.starts_with("Coverage::") + || line == "ConstEvalCounter;" + { + continue; + } + if let Some((lhs, rhs)) = line.strip_suffix(';').and_then(|s| s.split_once(" = ")) { + if let Some((call_part, ret_bb, unw_bb)) = split_call_terminator(rhs) { + require(is_local(lhs), format!("Atomic::<{scalar}>::{method}/{block}: non-local call dst {lhs}")); + require(is_bb(ret_bb), format!("bad return bb {ret_bb}")); + let (raw_callee, operands) = split_call_callee_operands(call_part).unwrap_or_else(|| { + fail(format!("Atomic::<{scalar}>::{method}/{block}: bad call {line}")) + }); + require( + !unwind_mode, + format!("Atomic::<{scalar}>::{method}: unexpected call {raw_callee} on unwind path at {block}"), + ); + let args: Vec<&str> = if operands.is_empty() { + Vec::new() + } else { + operands.split(", ").collect() + }; + if let Some(matched_helper) = + match_expected_atomic_helper(raw_callee, scalar, method, allowed_helpers, args.len()) + { + require( + seen_helper == 0, + format!( + "Atomic::<{scalar}>::{method}: multiple helper calls on path (second call {matched_helper} at {block})" + ), + ); + require( + args.len() >= expected_inputs, + format!("Atomic::<{scalar}>::{method}: too few args to {matched_helper}: {operands}"), + ); + let ord_args = &args[args.len() - expected_inputs..]; + for (idx, op) in ord_args.iter().enumerate() { + let origin = strip_move_or_copy(op) + .filter(|s| is_local(s)) + .and_then(|loc| ord_origin.get(loc).copied()); + require( + origin == Some(idx), + format!( + "Atomic::<{scalar}>::{method} did not forward Ordering parameter #{idx} unmodified to {matched_helper} (operand: {op})" + ), + ); + } + seen_helper += 1; + } else if !is_pure_address_helper(raw_callee) { + fail(format!( + "Atomic::<{scalar}>::{method}: unapproved extra call {raw_callee} at {block}" + )); + } + ord_origin.remove(lhs); + emulate_locals.remove(lhs); + visit( + blocks, + addr_taken, + ret_bb, + scalar, + method, + allowed_helpers, + expected_inputs, + unwind_mode, + seen_helper, + ord_origin.clone(), + emulate_locals.clone(), + active, + memo, + ); + if let Some(ubb) = unw_bb { + require(is_bb(ubb), format!("bad unwind bb {ubb}")); + visit( + blocks, + addr_taken, + ubb, + scalar, + method, + allowed_helpers, + expected_inputs, + true, + seen_helper, + ord_origin, + emulate_locals, + active, + memo, + ); + } + active.remove(block); + memo.insert(key); + return; + } + if is_local(lhs) { + if rhs == "const sync::atomic::EMULATE_ATOMIC_BOOL" && !addr_taken.contains(lhs) { + ord_origin.remove(lhs); + emulate_locals.insert(lhs.to_string()); + } else if let Some(src) = strip_move_or_copy(rhs).filter(|s| is_local(s)) { + if !addr_taken.contains(lhs) { + if let Some(&orig) = ord_origin.get(src) { + ord_origin.insert(lhs.to_string(), orig); + } else { + ord_origin.remove(lhs); + } + if emulate_locals.contains(src) { + emulate_locals.insert(lhs.to_string()); + } else { + emulate_locals.remove(lhs); + } + } else { + ord_origin.remove(lhs); + emulate_locals.remove(lhs); + } + } else { + ord_origin.remove(lhs); + emulate_locals.remove(lhs); + } + } else { + // Projected or dereferenced LHS (e.g. `(*_4) = ...`, `(_3.0) = ...`). + for loc in extract_local_refs(lhs) { + ord_origin.remove(loc); + emulate_locals.remove(loc); + } + } + continue; + } + if let Some(rest) = line.strip_prefix("drop(").and_then(|s| s.strip_suffix("];")) { + require( + !unwind_mode, + format!("Atomic::<{scalar}>::{method}/{block}: drop on unwind path is forbidden: {line}"), + ); + if let Some((_place, term_part)) = rest.split_once(") -> [return: ") { + let (ret_bb, unw_bb) = if let Some((r, u)) = term_part.split_once(", unwind: ") { + (r, Some(u)) + } else if let Some((r, _)) = term_part.split_once(", unwind ") { + (r, None) + } else { + fail(format!("Atomic::<{scalar}>::{method}/{block}: bad drop {line}")); + }; + require(is_bb(ret_bb), format!("bad drop return bb {ret_bb}")); + visit( + blocks, + addr_taken, + ret_bb, + scalar, + method, + allowed_helpers, + expected_inputs, + unwind_mode, + seen_helper, + ord_origin.clone(), + emulate_locals.clone(), + active, + memo, + ); + if let Some(ubb) = unw_bb { + require(is_bb(ubb), format!("bad drop unwind bb {ubb}")); + visit( + blocks, + addr_taken, + ubb, + scalar, + method, + allowed_helpers, + expected_inputs, + true, + seen_helper, + ord_origin, + emulate_locals, + active, + memo, + ); + } + active.remove(block); + memo.insert(key); + return; + } + } + if let Some(rest) = line + .strip_prefix("falseUnwind -> [real: ") + .and_then(|s| s.strip_suffix("];")) + { + let (real_bb, unw_bb) = if let Some((r, u)) = rest.split_once(", unwind: ") { + (r, Some(u)) + } else if let Some((r, _)) = rest.split_once(", unwind ") { + (r, None) + } else { + fail(format!("Atomic::<{scalar}>::{method}/{block}: bad falseUnwind {line}")); + }; + require(is_bb(real_bb), format!("bad falseUnwind real bb {real_bb}")); + visit( + blocks, + addr_taken, + real_bb, + scalar, + method, + allowed_helpers, + expected_inputs, + unwind_mode, + seen_helper, + ord_origin.clone(), + emulate_locals.clone(), + active, + memo, + ); + if let Some(ubb) = unw_bb { + require(is_bb(ubb), format!("bad falseUnwind unwind bb {ubb}")); + visit( + blocks, + addr_taken, + ubb, + scalar, + method, + allowed_helpers, + expected_inputs, + true, + seen_helper, + ord_origin, + emulate_locals, + active, + memo, + ); + } + active.remove(block); + memo.insert(key); + return; + } + if let Some(next) = parse_goto_or_false_edge(line) { + visit( + blocks, + addr_taken, + next, + scalar, + method, + allowed_helpers, + expected_inputs, + unwind_mode, + seen_helper, + ord_origin, + emulate_locals, + active, + memo, + ); + active.remove(block); + memo.insert(key); + return; + } + if let Some(rest) = line + .strip_prefix("switchInt(") + .and_then(|s| s.strip_suffix("];")) + { + if let Some((cond, branches)) = rest.split_once(") -> [") { + let loc = strip_move_or_copy(cond) + .filter(|s| is_local(s)) + .unwrap_or_else(|| { + fail(format!("Atomic::<{scalar}>::{method}/{block}: bad switchInt {line}")) + }); + let targets = parse_switch_targets(branches); + if emulate_locals.contains(loc) { + let tgt = targets + .into_iter() + .find(|(k, _)| k == "0") + .map(|(_, v)| v) + .unwrap_or_else(|| { + fail(format!("Atomic::<{scalar}>::{method}/{block}: missing false branch")) + }); + visit( + blocks, + addr_taken, + &tgt, + scalar, + method, + allowed_helpers, + expected_inputs, + unwind_mode, + seen_helper, + ord_origin, + emulate_locals, + active, + memo, + ); + } else { + for (_, tgt) in targets { + visit( + blocks, + addr_taken, + &tgt, + scalar, + method, + allowed_helpers, + expected_inputs, + unwind_mode, + seen_helper, + ord_origin.clone(), + emulate_locals.clone(), + active, + memo, + ); + } + } + active.remove(block); + memo.insert(key); + return; + } + } + if line == "return;" { + require( + !unwind_mode, + format!("Atomic::<{scalar}>::{method}/{block}: unwind path returned normally"), + ); + require( + seen_helper == 1, + format!( + "Atomic::<{scalar}>::{method}: path returned after {seen_helper} calls to {:?} (expected 1)", + allowed_helpers + ), + ); + active.remove(block); + memo.insert(key); + return; + } + if line == "resume;" { + require( + unwind_mode, + format!("Atomic::<{scalar}>::{method}/{block}: normal path reached resume"), + ); + active.remove(block); + memo.insert(key); + return; + } + if line == "unreachable;" { + require( + unwind_mode, + format!("Atomic::<{scalar}>::{method}/{block}: normal path reached unreachable"), + ); + active.remove(block); + memo.insert(key); + return; + } + fail(format!( + "Atomic::<{scalar}>::{method}/{block}: unrecognized MIR statement {line}" + )); + } + fail(format!("Atomic::<{scalar}>::{method}/{block}: missing terminator")); + } + + let mut active = HashSet::new(); + let mut memo = HashSet::new(); + visit( + &blocks, + &addr_taken, + "bb0", + scalar, + method, + &allowed_helpers, + expected_inputs, + false, + 0, + initial_ord, + BTreeSet::new(), + &mut active, + &mut memo, + ); +} + +fn validate_manifest_entries(pkg_dir: &Path, book_md: &Path) -> (Vec>, Vec>, String) { + let cases = parse_tsv(&pkg_dir.join("intrinsic-manifest.tsv")); + let permissions = parse_tsv(&pkg_dir.join("permission-inventory.tsv")); + let unique_entries: HashSet<&str> = cases.iter().map(|r| r["challenge_entry"].as_str()).collect(); + require(cases.len() == 91 && permissions.len() == 91 && unique_entries.len() == 91, "Part 3 identities"); + let part2_helpers: BTreeSet<&str> = cases + .iter() + .filter(|r| r["listed_part2"] == "yes") + .map(|r| r["unsafe_helper"].as_str()) + .collect(); + require(part2_helpers.len() == 14, "Part 2 helpers"); + + let book = read_text(book_md); + let part2_sec = book + .split_once("Write and verify safety contracts for the unsafe functions:") + .and_then(|(_, r)| r.split_once("##### Panicking")) + .map(|(s, _)| s) + .unwrap_or_else(|| fail("failed to parse Part 2 from challenge doc")); + let table_sec = book + .split_once("| Operations") + .and_then(|(_, r)| r.split_once("## List of UBs")) + .map(|(s, _)| s) + .unwrap_or_else(|| fail("failed to parse Part 3 table from challenge doc")); + + let mut book_helpers = BTreeSet::new(); + for line in part2_sec.lines() { + if let Some(name) = line.strip_prefix("- `").and_then(|s| s.strip_suffix('`')) { + if name.starts_with("atomic_") && is_ident(name) { + book_helpers.insert(name); + } + } + } + require(part2_helpers == book_helpers, "Challenge helper list"); + + let mut book_entries = Vec::new(); + let mut rest = table_sec; + while let Some(i) = rest.find("`atomic_") { + let after = &rest[i + 1..]; + if let Some(j) = after.find('`') { + let cand = &after[..j]; + if is_ident(cand) { + book_entries.push(cand); + } + rest = &after[j + 1..]; + } else { + break; + } + } + let manifest_entries: Vec<&str> = cases.iter().map(|r| r["challenge_entry"].as_str()).collect(); + require(manifest_entries == book_entries, "Challenge intrinsic list"); + + let expected_pairs: BTreeSet<(String, String)> = book_entries + .iter() + .map(|e| expected_from_challenge_entry(e)) + .collect(); + let mut actual_pairs: BTreeSet<(String, String)> = BTreeSet::new(); + for (case, item) in cases.iter().zip(permissions.iter()) { + let entry = &case["challenge_entry"]; + let (exp_intr, exp_ord) = expected_from_challenge_entry(entry); + require( + case["compiler_intrinsic"] == exp_intr && case["ordering"] == exp_ord, + format!( + "manifest entry {entry} mismatch: expected ({exp_intr}, {exp_ord}), got ({}, {})", + case["compiler_intrinsic"], case["ordering"] + ), + ); + require( + entry == &item["entry"] + && case["unsafe_helper"] == item["helper"] + && case["compiler_intrinsic"] == item["intrinsic"] + && case["ordering"] == item["ordering"] + && case["listed_part2"] == item["part2_required"], + format!("manifest mismatch for {entry}"), + ); + actual_pairs.insert((exp_intr, exp_ord)); + } + require( + actual_pairs.len() == 91 && actual_pairs == expected_pairs, + format!("expected 91 distinct (intrinsic, ordering) pairs, got {}", actual_pairs.len()), + ); + (cases, permissions, book) +} + +fn cmd_inventory(target: &str, mir_dir: &Path, owners_file: &Path, records_dir: &Path, pkg_dir: &Path, book_md: &Path) { + let owners = parse_owners(owners_file); + let (cases, permissions, book) = validate_manifest_entries(pkg_dir, book_md); + check_routes(mir_dir, &cases); + + let families = ["access", "rmw", "pointer-access", "pointer-rmw", "u32"]; + let mut parsed: HashMap<&str, (HashSet, HashMap<(String, String), Vec>, String)> = HashMap::new(); + let mut all_names: HashSet = HashSet::new(); + for fam in families { + let fns_text = read_text(&records_dir.join(format!("{fam}.fns"))); + let report_text = read_text(&records_dir.join(format!("{fam}.tsv"))); + let fns: HashSet = fns_text.lines().filter(|l| !l.is_empty()).map(String::from).collect(); + all_names.extend(fns.iter().cloned()); + let calls = parse_edges(&report_text); + parsed.insert(fam, (fns, calls, report_text)); + } + + let mut checked_public_order: HashSet<(String, String, String)> = HashSet::new(); + let mut verify_public_order = |owner: &str, scalar: &str, method: &str, helper: &str| { + let key = (owner.to_string(), method.to_string(), helper.to_string()); + if checked_public_order.insert(key) { + check_public_ordering_forwarding(mir_dir, owner, scalar, method, helper); + } + }; + + let integers: BTreeSet<&str> = owners + .keys() + .map(String::as_str) + .filter(|s| *s != "bool" && *s != "*mut T") + .collect(); + let mut total = 0usize; + for (case, item) in cases.iter().zip(permissions.iter()) { + let entry = &case["challenge_entry"]; + let helper = &case["unsafe_helper"]; + let intrinsic = &case["compiler_intrinsic"]; + let order = &case["ordering"]; + require( + entry == &item["entry"] + && helper == &item["helper"] + && intrinsic == &item["intrinsic"] + && order == &item["ordering"] + && case["listed_part2"] == item["part2_required"], + format!("manifest mismatch for {entry}"), + ); + let method = case["public_method"].rsplit("::").next().unwrap(); + let types: Vec<&str> = item[target].split(',').collect(); + let expected: BTreeSet<&str> = integers + .iter() + .copied() + .filter(|t| { + if helper == "atomic_umin" || helper == "atomic_umax" { + t.starts_with('u') + } else if helper == "atomic_min" || helper == "atomic_max" { + t.starts_with('i') + } else { + true + } + }) + .collect(); + let type_set: BTreeSet<&str> = types.iter().copied().collect(); + require(type_set == expected && types.len() == expected.len(), format!("{entry}: scalar inventory")); + let fam = if matches!(method, "load" | "store" | "compare_exchange" | "compare_exchange_weak") { + "access" + } else { + "rmw" + }; + let (fns, calls, _) = &parsed[fam]; + for scalar in types { + verify_public_order(&owners[scalar], scalar, method, helper); + check_path(fns, calls, &owners[scalar], scalar, method, helper, intrinsic, order); + total += 1; + } + } + let expected_total = if target.starts_with("aarch64") { 972 } else { 810 }; + require(total == expected_total, format!("integer permission count {total} != {expected_total}")); + + let ptr = "*mut T"; + let (prmw_fns, prmw_calls, _) = &parsed["pointer-rmw"]; + for (method, helper, intrinsic) in [ + ("fetch_byte_add", "atomic_add", "atomic_xadd"), + ("fetch_byte_sub", "atomic_sub", "atomic_xsub"), + ("fetch_and", "atomic_and", "atomic_and"), + ("fetch_or", "atomic_or", "atomic_or"), + ("fetch_xor", "atomic_xor", "atomic_xor"), + ] { + verify_public_order(&owners[ptr], ptr, method, helper); + for order in ["Relaxed", "Acquire", "Release", "AcqRel", "SeqCst"] { + check_path(prmw_fns, prmw_calls, &owners[ptr], ptr, method, helper, intrinsic, order); + } + } + let (pacc_fns, pacc_calls, _) = &parsed["pointer-access"]; + for case in &cases { + let method = case["public_method"].rsplit("::").next().unwrap(); + if matches!(method, "swap" | "load" | "store" | "compare_exchange" | "compare_exchange_weak") { + verify_public_order(&owners[ptr], ptr, method, &case["unsafe_helper"]); + check_path( + pacc_fns, + pacc_calls, + &owners[ptr], + ptr, + method, + &case["unsafe_helper"], + &case["compiler_intrinsic"], + &case["ordering"], + ); + } + } + // Also verify bool public ordering forwarding for all non-CAS methods (CAS already traced in cmd_mir). + for (method, helper) in [ + ("load", "atomic_load"), + ("store", "atomic_store"), + ("swap", "atomic_swap"), + ("fetch_and", "atomic_and"), + ("fetch_or", "atomic_or"), + ("fetch_xor", "atomic_xor"), + ("fetch_nand", "fetch_xor|swap"), + ("fetch_not", "fetch_xor"), + ] { + verify_public_order(&owners["bool"], "bool", method, helper); + } + + let part1 = parse_tsv(&pkg_dir.join("part1-manifest.tsv")); + let p1_types: HashSet<&str> = part1.iter().map(|r| r["required_type"].as_str()).collect(); + require(part1.len() == 12 && p1_types.len() == 12, "Part 1 identities"); + let mut constructors = Vec::new(); + for line in book.lines() { + if let Some(name) = line.strip_prefix("- `").and_then(|s| s.strip_suffix("::from_ptr`")) { + if name.starts_with("Atomic") && is_ident(name) { + constructors.push(name); + } + } + } + let manifest_ctors: Vec<&str> = part1.iter().map(|r| r["required_type"].as_str()).collect(); + require(manifest_ctors == constructors, "Challenge constructor list"); + for item in &part1 { + if item["target"] != target { + continue; + } + let needle = format!("root\t{}\t", item["production_mir_root"]); + let has_root = parsed.values().any(|(_, _, r)| r.contains(&needle)); + require(has_root && all_names.contains(&item["client"]), format!("unverified Part 1 entry {:?}", item)); + } + + let expected_sites: BTreeSet<(String, String)> = [ + ("atomic_load", "an acquire-release load"), + ("atomic_load", "a release load"), + ("atomic_store", "an acquire-release store"), + ("atomic_store", "an acquire store"), + ("atomic_compare_exchange", "an acquire-release failure ordering"), + ("atomic_compare_exchange", "a release failure ordering"), + ("atomic_compare_exchange_weak", "an acquire-release failure ordering"), + ("atomic_compare_exchange_weak", "a release failure ordering"), + ] + .into_iter() + .map(|(h, s)| (format!("{PREFIX}{h}"), format!("there is no such thing as {s}"))) + .collect(); + for fam in ["access", "pointer-access", "u32"] { + let (_, _, report) = &parsed[fam]; + let events: Vec> = report + .lines() + .filter(|l| l.starts_with("literal-panic\t")) + .map(|l| l.split('\t').collect()) + .collect(); + let actual_sites: BTreeSet<(String, String)> = events + .iter() + .map(|e| { + require(e.len() >= 5, "malformed literal-panic line"); + (e[1].to_string(), e[4].to_string()) + }) + .collect(); + require(events.len() == 8 && actual_sites == expected_sites, format!("static panic sites in {fam}")); + } + println!("PASS {target}: {total} integer permissions, 91 ordering entries, 25 pointer RMW edges"); +} + +/// Strip Rust line (`//...`) and nested block (`/*...*/`) comments lexically without +/// letting comment markers inside `//` line comments or string literals swallow code. +fn strip_ghost(body: &str) -> String { + let bytes = body.as_bytes(); + let mut clean = String::with_capacity(body.len()); + let mut i = 0; + while i < bytes.len() { + // Line comment: ends strictly at '\n'; never starts a block comment. + if i + 1 < bytes.len() && bytes[i] == b'/' && bytes[i + 1] == b'/' { + while i < bytes.len() && bytes[i] != b'\n' { + i += 1; + } + clean.push(' '); + continue; + } + // Nested Rust block comment (including /*@ ... @*/ ghost blocks). + if i + 1 < bytes.len() && bytes[i] == b'/' && bytes[i + 1] == b'*' { + let mut depth = 1usize; + i += 2; + while i < bytes.len() && depth > 0 { + if i + 1 < bytes.len() && bytes[i] == b'/' && bytes[i + 1] == b'*' { + depth += 1; + i += 2; + } else if i + 1 < bytes.len() && bytes[i] == b'*' && bytes[i + 1] == b'/' { + depth -= 1; + i += 2; + } else { + i += 1; + } + } + require(depth == 0, "unclosed Rust block comment in witness body"); + let prev_ident = clean.as_bytes().last().is_some_and(|c| c.is_ascii_alphanumeric() || *c == b'_'); + let next_ident = bytes.get(i).is_some_and(|c| c.is_ascii_alphanumeric() || *c == b'_'); + if prev_ident && next_ident { + clean.push(' '); + } + continue; + } + // Raw string literal r"..." / r#"..."# / br#"..."# + if bytes[i] == b'r' || (i + 1 < bytes.len() && bytes[i] == b'b' && bytes[i + 1] == b'r') { + let start = i; + let mut j = if bytes[i] == b'b' { i + 2 } else { i + 1 }; + let mut hashes = 0usize; + while j < bytes.len() && bytes[j] == b'#' { + hashes += 1; + j += 1; + } + if j < bytes.len() && bytes[j] == b'"' { + j += 1; + let mut closed = false; + while j < bytes.len() { + if bytes[j] == b'"' { + let mut k = 0; + while k < hashes && j + 1 + k < bytes.len() && bytes[j + 1 + k] == b'#' { + k += 1; + } + if k == hashes { + j += 1 + hashes; + closed = true; + break; + } + } + j += 1; + } + require(closed, "unclosed raw string literal in witness body"); + clean.push_str(&body[start..j]); + i = j; + continue; + } + } + // Quoted string literal + if bytes[i] == b'"' { + let start = i; + i += 1; + let mut closed = false; + while i < bytes.len() { + if bytes[i] == b'\\' { + i += 2; + } else if bytes[i] == b'"' { + i += 1; + closed = true; + break; + } else { + i += 1; + } + } + require(closed, "unclosed string literal in witness body"); + clean.push_str(&body[start..i]); + continue; + } + let ch = body[i..].chars().next().unwrap(); + clean.push(ch); + i += ch.len_utf8(); + } + clean.split_whitespace().collect::>().join(" ") +} + +fn replace_ident_whole(text: &str, from: &str, to: &str) -> String { + let bytes = text.as_bytes(); + let fbytes = from.as_bytes(); + let mut out = String::with_capacity(text.len()); + let mut i = 0; + while i < bytes.len() { + if i + fbytes.len() <= bytes.len() && &bytes[i..i + fbytes.len()] == fbytes { + let prev_ident = i > 0 && (bytes[i - 1].is_ascii_alphanumeric() || bytes[i - 1] == b'_'); + let next_ident = i + fbytes.len() < bytes.len() + && (bytes[i + fbytes.len()].is_ascii_alphanumeric() || bytes[i + fbytes.len()] == b'_'); + if !prev_ident && !next_ident { + out.push_str(to); + i += fbytes.len(); + continue; + } + } + let ch = text[i..].chars().next().unwrap(); + out.push(ch); + i += ch.len_utf8(); + } + out +} + +fn check_forwarding_body(sig: &str, body: &str, method: &str, ty: &str) { + let params_str = sig + .split_once('(') + .and_then(|(_, r)| r.split_once(')')) + .map(|(p, _)| p) + .unwrap_or_else(|| fail(format!("bad witness signature {sig}"))); + let mut args = Vec::new(); + let mut seen_args = HashSet::new(); + for part in params_str.split(',') { + let part = part.trim(); + if part.is_empty() { + continue; + } + let (name, _) = part + .split_once(':') + .unwrap_or_else(|| fail(format!("bad witness parameter {part}"))); + let name = name.trim(); + require(is_ident(name), format!("bad witness parameter name {name}")); + require(seen_args.insert(name), format!("duplicate witness parameter name {name}")); + args.push(name); + } + if method != "from_ptr" { + require( + !args.is_empty() && args[0] == "receiver", + format!("witness {method} first parameter must be `receiver`, found {:?}", args), + ); + for extra in &args[1..] { + require( + *extra != "self" && *extra != "receiver", + format!("witness {method} non-receiver parameter cannot be named `{extra}`"), + ); + } + } + let mut code = strip_ghost(body); + if ty == "*mut T" { + let operand = if method == "from_ptr" { + "ptr".to_string() + } else { + format!("{} as *mut *mut T", args[1]) + }; + let shape = format!("unsafe {{ crate::intrinsics::ch7_pointer_shape::({operand}) }}; "); + require(code.starts_with(&shape), "missing checked thin-pointer witness"); + code = code[shape.len()..].to_string(); + } + if method == "from_ptr" { + let result = sig + .split_once("-> &'a ") + .map(|(_, r)| r.split(|c: char| !c.is_ascii_alphanumeric() && c != '_').next().unwrap_or("")) + .unwrap_or(""); + let name = if ty == "*mut T" { format!("{result}::") } else { result.to_string() }; + let ok = code == format!("let view = unsafe {{ {name}::from_ptr(ptr) }}; view") + || code == format!("let result = unsafe {{ {name}::from_ptr(ptr) }}; result"); + require(args == ["ptr"] && ok, format!("constructor adapter changed: {code}")); + } else { + let call = format!("receiver.{method}({})", args[1..].join(", ")); + require( + !args.is_empty() && args[0] == "receiver" && (code == call || (method == "store" && code == format!("{call};"))), + format!("method adapter changed: {code}"), + ); + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +enum TokKind { + Ident, + RawIdent, + Lifetime, + Literal, + Punct(char), + GhostLine, + GhostBlock, +} + +#[derive(Clone, Debug)] +struct LexTok { + kind: TokKind, + start: usize, + end: usize, +} + +impl LexTok { + fn text<'a>(&self, src: &'a str) -> &'a str { + &src[self.start..self.end] + } + + fn ident_name<'a>(&self, src: &'a str) -> Option<&'a str> { + match self.kind { + TokKind::Ident => Some(&src[self.start..self.end]), + TokKind::RawIdent => Some(&src[self.start + 2..self.end]), + _ => None, + } + } +} + +fn is_rust_whitespace(ch: char) -> bool { + ch.is_whitespace() || matches!(ch, '\u{0085}' | '\u{200E}' | '\u{200F}' | '\u{2028}' | '\u{2029}') +} + +fn is_rust_ident_start(ch: char) -> bool { + ch == '_' || ch.is_alphabetic() +} + +fn is_rust_ident_continue(ch: char) -> bool { + ch == '_' || ch.is_alphanumeric() +} + +/// Lexical Rust tokenizer that skips ordinary `//` and nested `/* ... */` comments, +/// preserves VeriFast `//@ ...` and `/*@ ... @*/` annotations, handles Unicode +/// Pattern_White_Space and raw identifiers (`r#ident`), and respects all string/char literals. +fn lex_rust(src: &str) -> Vec { + let bytes = src.as_bytes(); + let mut toks = Vec::new(); + let mut i = 0; + while i < bytes.len() { + let ch = src[i..].chars().next().unwrap(); + if is_rust_whitespace(ch) { + i += ch.len_utf8(); + continue; + } + let b = bytes[i]; + // Line comment or VeriFast `//@` ghost line. + if i + 1 < bytes.len() && b == b'/' && bytes[i + 1] == b'/' { + let start = i; + let is_ghost = i + 2 < bytes.len() && bytes[i + 2] == b'@'; + while i < bytes.len() && bytes[i] != b'\n' { + i += 1; + } + if is_ghost { + toks.push(LexTok { kind: TokKind::GhostLine, start, end: i }); + } + continue; + } + // Block comment (nested) or VeriFast `/*@ ... @*/` ghost block. + if i + 1 < bytes.len() && b == b'/' && bytes[i + 1] == b'*' { + let start = i; + if i + 2 < bytes.len() && bytes[i + 2] == b'@' { + i += 3; + let mut closed = false; + while i + 2 < bytes.len() { + if bytes[i] == b'@' && bytes[i + 1] == b'*' && bytes[i + 2] == b'/' { + i += 3; + closed = true; + break; + } + i += 1; + } + require(closed, "unclosed VeriFast /*@ ... @*/ ghost block"); + toks.push(LexTok { kind: TokKind::GhostBlock, start, end: i }); + } else { + let mut depth = 1usize; + i += 2; + while i < bytes.len() && depth > 0 { + if i + 1 < bytes.len() && bytes[i] == b'/' && bytes[i + 1] == b'*' { + depth += 1; + i += 2; + } else if i + 1 < bytes.len() && bytes[i] == b'*' && bytes[i + 1] == b'/' { + depth -= 1; + i += 2; + } else { + i += 1; + } + } + require(depth == 0, "unclosed Rust block comment"); + } + continue; + } + // Raw string literal: r"...", r#"..."#, br#"..."#, cr#"..."#. + if b == b'r' || ((b == b'b' || b == b'c') && i + 1 < bytes.len() && bytes[i + 1] == b'r') { + let start = i; + let mut j = if b == b'r' { i + 1 } else { i + 2 }; + let mut hashes = 0usize; + while j < bytes.len() && bytes[j] == b'#' { + hashes += 1; + j += 1; + } + if j < bytes.len() && bytes[j] == b'"' { + j += 1; + let mut closed = false; + while j < bytes.len() { + if bytes[j] == b'"' { + let mut k = 0; + while k < hashes && j + 1 + k < bytes.len() && bytes[j + 1 + k] == b'#' { + k += 1; + } + if k == hashes { + j += 1 + hashes; + closed = true; + break; + } + } + j += 1; + } + require(closed, "unclosed raw string literal"); + toks.push(LexTok { kind: TokKind::Literal, start, end: j }); + i = j; + continue; + } + } + // Raw identifier: r#. + if b == b'r' && i + 2 < bytes.len() && bytes[i + 1] == b'#' { + if let Some(id_ch) = src[i + 2..].chars().next() { + if is_rust_ident_start(id_ch) { + let start = i; + i += 2 + id_ch.len_utf8(); + while i < bytes.len() { + let c = src[i..].chars().next().unwrap(); + if is_rust_ident_continue(c) { + i += c.len_utf8(); + } else { + break; + } + } + toks.push(LexTok { kind: TokKind::RawIdent, start, end: i }); + continue; + } + } + } + // Byte/C string literal or byte char literal: b"...", c"...", b'...'. + if (b == b'b' || b == b'c') && i + 1 < bytes.len() && bytes[i + 1] == b'"' { + let start = i; + i += 2; + let mut closed = false; + while i < bytes.len() { + if bytes[i] == b'\\' { + i += 2; + } else if bytes[i] == b'"' { + i += 1; + closed = true; + break; + } else { + i += 1; + } + } + require(closed, "unclosed byte/c string literal"); + toks.push(LexTok { kind: TokKind::Literal, start, end: i }); + continue; + } + if b == b'b' && i + 1 < bytes.len() && bytes[i + 1] == b'\'' { + let start = i; + i += 2; + let mut closed = false; + while i < bytes.len() { + if bytes[i] == b'\\' { + i += 2; + } else if bytes[i] == b'\'' { + i += 1; + closed = true; + break; + } else { + i += 1; + } + } + require(closed, "unclosed byte char literal"); + toks.push(LexTok { kind: TokKind::Literal, start, end: i }); + continue; + } + // Quoted string literal. + if b == b'"' { + let start = i; + i += 1; + let mut closed = false; + while i < bytes.len() { + if bytes[i] == b'\\' { + i += 2; + } else if bytes[i] == b'"' { + i += 1; + closed = true; + break; + } else { + i += 1; + } + } + require(closed, "unclosed string literal"); + toks.push(LexTok { kind: TokKind::Literal, start, end: i }); + continue; + } + // Char literal vs lifetime (`'a`). + if b == b'\'' { + let start = i; + if i + 1 < bytes.len() && bytes[i + 1] == b'\\' { + i += 2; + let mut closed = false; + while i < bytes.len() { + if bytes[i] == b'\\' { + i += 2; + } else if bytes[i] == b'\'' { + i += 1; + closed = true; + break; + } else { + i += 1; + } + } + require(closed, "unclosed escaped char literal"); + toks.push(LexTok { kind: TokKind::Literal, start, end: i }); + continue; + } + let after_quote = &src[i + 1..]; + if let Some(ch2) = after_quote.chars().next() { + let next_idx = i + 1 + ch2.len_utf8(); + if next_idx < bytes.len() && bytes[next_idx] == b'\'' && ch2 != '\n' { + i = next_idx + 1; + toks.push(LexTok { kind: TokKind::Literal, start, end: i }); + continue; + } + } + // Lifetime token. + i += 1; + while i < bytes.len() { + let c = src[i..].chars().next().unwrap(); + if is_rust_ident_continue(c) { + i += c.len_utf8(); + } else { + break; + } + } + toks.push(LexTok { kind: TokKind::Lifetime, start, end: i }); + continue; + } + // Identifier (ASCII or Unicode). + if is_rust_ident_start(ch) { + let start = i; + i += ch.len_utf8(); + while i < bytes.len() { + let c = src[i..].chars().next().unwrap(); + if is_rust_ident_continue(c) { + i += c.len_utf8(); + } else { + break; + } + } + toks.push(LexTok { kind: TokKind::Ident, start, end: i }); + continue; + } + // Numeric literal. + if b.is_ascii_digit() { + let start = i; + i += 1; + while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') { + i += 1; + } + toks.push(LexTok { kind: TokKind::Literal, start, end: i }); + continue; + } + // Punctuation (single UTF-8 char). + let start = i; + i += ch.len_utf8(); + toks.push(LexTok { kind: TokKind::Punct(ch), start, end: i }); + } + toks +} + +fn strip_comments_preserve_lines(src: &str) -> String { + let bytes = src.as_bytes(); + let mut out = String::with_capacity(src.len()); + let mut i = 0; + while i < bytes.len() { + if i + 1 < bytes.len() && bytes[i] == b'/' && bytes[i + 1] == b'/' { + while i < bytes.len() && bytes[i] != b'\n' { + i += 1; + } + continue; + } + if i + 1 < bytes.len() && bytes[i] == b'/' && bytes[i + 1] == b'*' { + let mut depth = 1usize; + i += 2; + while i < bytes.len() && depth > 0 { + if i + 1 < bytes.len() && bytes[i] == b'/' && bytes[i + 1] == b'*' { + depth += 1; + i += 2; + } else if i + 1 < bytes.len() && bytes[i] == b'*' && bytes[i + 1] == b'/' { + depth -= 1; + i += 2; + } else { + if bytes[i] == b'\n' { + out.push('\n'); + } + i += 1; + } + } + require(depth == 0, "unclosed block comment inside ghost block"); + continue; + } + let ch = src[i..].chars().next().unwrap(); + out.push(ch); + i += ch.len_utf8(); + } + out +} + +fn extract_ghost_decl(source: &str, decl: &str) -> String { + let toks = lex_rust(source); + let mut depth = 0usize; + let mut found = Vec::new(); + for tok in &toks { + match tok.kind { + TokKind::Punct('{') => depth += 1, + TokKind::Punct('}') => depth = depth.saturating_sub(1), + TokKind::GhostBlock if depth == 0 => { + let raw = tok.text(source); + let inner = &raw[3..raw.len() - 3]; + let cleaned = strip_comments_preserve_lines(inner); + let lines: Vec<&str> = cleaned.lines().collect(); + for (i, line) in lines.iter().enumerate() { + let trimmed = line.trim(); + if trimmed.starts_with(&format!("fix {decl}")) + && trimmed[4 + decl.len()..] + .chars() + .next() + .is_none_or(|c| !c.is_ascii_alphanumeric() && c != '_') + { + found.push(trimmed.to_string()); + } else if trimmed.starts_with(&format!("inductive {decl}")) + && trimmed[10 + decl.len()..] + .chars() + .next() + .is_none_or(|c| !c.is_ascii_alphanumeric() && c != '_') + { + require(trimmed.ends_with(';'), format!("incomplete inductive {decl}")); + found.push(trimmed.to_string()); + } else if trimmed.starts_with(&format!("pred {decl}")) + && trimmed[5 + decl.len()..] + .chars() + .next() + .is_none_or(|c| !c.is_ascii_alphanumeric() && c != '_') + { + require(trimmed.ends_with(';'), format!("incomplete pred {decl}")); + found.push(trimmed.to_string()); + } else if trimmed.starts_with(&format!("pred_ctor {decl}")) + && trimmed[10 + decl.len()..] + .chars() + .next() + .is_none_or(|c| !c.is_ascii_alphanumeric() && c != '_') + { + require( + i + 1 < lines.len() && lines[i + 1].trim_end().ends_with(';'), + format!("incomplete pred_ctor {decl}"), + ); + found.push(format!("{}\n{}", trimmed, lines[i + 1].trim_end())); + } + } + } + _ => {} + } + } + require(found.len() == 1, format!("expected 1 top-level ghost declaration of {decl}, found {}", found.len())); + found.pop().unwrap() +} + +/// Extract a unique, unattributed top-level `unsafe fn ` from Rust source using the +/// full Rust lexer so ordinary comments, string literals, nested modules, and `#[cfg(...)]` items +/// can never shadow or forge a witness contract. +fn extract_fn_with_quals(text: &str, witness: &str, expected_quals: &[&str]) -> (String, String, String) { + let toks = lex_rust(text); + let mut brace_depth = 0usize; + let mut paren_depth = 0usize; + let mut bracket_depth = 0usize; + + let mut pending_attrs: Vec = Vec::new(); + let mut pending_quals: Vec = Vec::new(); + let mut matches: Vec<(Vec, Vec, String, String, String)> = Vec::new(); + + let mut idx = 0usize; + while idx < toks.len() { + let tok = &toks[idx]; + let at_top = brace_depth == 0 && paren_depth == 0 && bracket_depth == 0; + + // Collect top-level outer/inner attributes `#[...]` / `#![...]`. + if at_top && tok.kind == TokKind::Punct('#') { + let mut j = idx + 1; + let is_inner = j < toks.len() && toks[j].kind == TokKind::Punct('!'); + if is_inner { + j += 1; + } + if j < toks.len() && toks[j].kind == TokKind::Punct('[') { + let start = tok.start; + let mut d = 1usize; + j += 1; + while j < toks.len() && d > 0 { + match toks[j].kind { + TokKind::Punct('[') => d += 1, + TokKind::Punct(']') => d -= 1, + _ => {} + } + j += 1; + } + require(d == 0, "unclosed attribute bracket"); + if !is_inner { + pending_attrs.push(text[start..toks[j - 1].end].to_string()); + } + idx = j; + continue; + } + } + + // Collect top-level function qualifiers (`pub`, `pub(...)`, `unsafe`, `const`, `async`, `extern ...`). + if at_top && tok.kind == TokKind::Ident { + let word = tok.text(text); + if matches!(word, "pub" | "unsafe" | "const" | "async" | "extern") { + let mut q = word.to_string(); + let mut j = idx + 1; + if word == "pub" && j < toks.len() && toks[j].kind == TokKind::Punct('(') { + let mut d = 1usize; + let s = toks[j].start; + j += 1; + while j < toks.len() && d > 0 { + match toks[j].kind { + TokKind::Punct('(') => d += 1, + TokKind::Punct(')') => d -= 1, + _ => {} + } + j += 1; + } + require(d == 0, "unclosed pub(...) qualifier"); + q.push_str(&text[s..toks[j - 1].end]); + } else if word == "extern" && j < toks.len() && toks[j].kind == TokKind::Literal { + q.push(' '); + q.push_str(toks[j].text(text)); + j += 1; + } + pending_quals.push(q); + idx = j; + continue; + } + } + + // Check ANY `fn ` (including `fn r#`) anywhere in the file (at any depth or visibility). + if tok.kind == TokKind::Ident + && tok.text(text) == "fn" + && idx + 1 < toks.len() + && toks[idx + 1].ident_name(text) == Some(witness) + { + require( + at_top, + format!("witness {witness} must be a top-level function (found nested at depth {brace_depth}/{paren_depth}/{bracket_depth})"), + ); + let attrs = std::mem::take(&mut pending_attrs); + let quals = std::mem::take(&mut pending_quals); + + // Scan from right after `witness` name up to the body's opening `{`. + let sig_start = toks[idx + 1].end; + let mut j = idx + 2; + let mut sig_end = sig_start; + let mut clauses: Vec = Vec::new(); + let mut saw_clause = false; + let mut sig_paren = 0usize; + let mut sig_bracket = 0usize; + let mut sig_angle = 0usize; + while j < toks.len() { + match toks[j].kind { + TokKind::GhostLine => { + clauses.push(toks[j].text(text).to_string()); + saw_clause = true; + j += 1; + } + TokKind::GhostBlock => { + if saw_clause { + fail(format!("unexpected ghost block inside contract clauses of {witness}")); + } + j += 1; + } + TokKind::Punct('{') if sig_paren == 0 && sig_bracket == 0 && sig_angle == 0 => { + break; + } + TokKind::Punct(';') if sig_paren == 0 && sig_bracket == 0 && sig_angle == 0 => { + fail(format!("witness {witness} has no body")); + } + TokKind::Punct('(') => { + require(!saw_clause, format!("unexpected tokens after ghost clauses in {witness}")); + sig_paren += 1; + sig_end = toks[j].end; + j += 1; + } + TokKind::Punct(')') => { + sig_paren = sig_paren.saturating_sub(1); + sig_end = toks[j].end; + j += 1; + } + TokKind::Punct('[') => { + require(!saw_clause, format!("unexpected tokens after ghost clauses in {witness}")); + sig_bracket += 1; + sig_end = toks[j].end; + j += 1; + } + TokKind::Punct(']') => { + sig_bracket = sig_bracket.saturating_sub(1); + sig_end = toks[j].end; + j += 1; + } + TokKind::Punct('<') => { + require(!saw_clause, format!("unexpected tokens after ghost clauses in {witness}")); + sig_angle += 1; + sig_end = toks[j].end; + j += 1; + } + TokKind::Punct('>') => { + // Do not decrement on `->` arrow. + let is_arrow = j > 0 + && toks[j - 1].kind == TokKind::Punct('-') + && toks[j - 1].end == toks[j].start; + if !is_arrow { + sig_angle = sig_angle.saturating_sub(1); + } + sig_end = toks[j].end; + j += 1; + } + _ => { + require(!saw_clause, format!("unexpected tokens after ghost clauses in {witness}")); + sig_end = toks[j].end; + j += 1; + } + } + } + require( + j < toks.len() && toks[j].kind == TokKind::Punct('{'), + format!("missing opening '{{' for witness {witness}"), + ); + require( + clauses.len() == 3 + && clauses[0].starts_with("//@ req ") + && clauses[1].starts_with("//@ ens ") + && clauses[2].starts_with("//@ on_unwind_ens "), + format!("unexpected witness contract clauses for {witness}: {:?}", clauses), + ); + let body_start = toks[j].end; + let mut bd = 1usize; + j += 1; + while j < toks.len() && bd > 0 { + match toks[j].kind { + TokKind::Punct('{') => bd += 1, + TokKind::Punct('}') => bd -= 1, + _ => {} + } + j += 1; + } + require(bd == 0, format!("unclosed body for witness {witness}")); + let body_end = toks[j - 1].start; + let fn_sig = strip_ghost(&text[sig_start..sig_end]); + let clauses_str = format!("{}\n{}\n{}\n", clauses[0], clauses[1], clauses[2]); + let body_str = text[body_start..body_end].to_string(); + matches.push((attrs, quals, fn_sig, clauses_str, body_str)); + idx = j; + continue; + } + + // Track delimiters and reset pending attributes/qualifiers on item boundaries. + match tok.kind { + TokKind::Punct('{') => { + brace_depth += 1; + pending_attrs.clear(); + pending_quals.clear(); + } + TokKind::Punct('}') => { + brace_depth = brace_depth.saturating_sub(1); + if brace_depth == 0 { + pending_attrs.clear(); + pending_quals.clear(); + } + } + TokKind::Punct('(') => paren_depth += 1, + TokKind::Punct(')') => paren_depth = paren_depth.saturating_sub(1), + TokKind::Punct('[') => bracket_depth += 1, + TokKind::Punct(']') => bracket_depth = bracket_depth.saturating_sub(1), + TokKind::Punct(';') if at_top => { + pending_attrs.clear(); + pending_quals.clear(); + } + TokKind::GhostLine | TokKind::GhostBlock => {} + _ if at_top => { + // Any other top-level item keyword (`use`, `struct`, `macro_rules`, `mod`, `fn` of another name) + // consumes pending qualifiers; if it's not a qualifier, clear qualifiers/attrs after skipping item. + pending_attrs.clear(); + pending_quals.clear(); + } + _ => {} + } + idx += 1; + } + + require(matches.len() == 1, format!("expected 1 top-level witness {witness}, found {}", matches.len())); + let (attrs, quals, fn_sig, clauses, body) = matches.pop().unwrap(); + require( + attrs.is_empty(), + format!("witness {witness} must not carry attributes (found {:?})", attrs), + ); + require( + quals.len() == expected_quals.len() + && quals.iter().zip(expected_quals.iter()).all(|(a, b)| a == b), + format!( + "witness {witness} must be declared with qualifiers {:?} (found {:?})", + expected_quals, quals + ), + ); + (fn_sig, clauses, body) +} + +fn extract_witness_fn(text: &str, witness: &str) -> (String, String, String) { + extract_fn_with_quals(text, witness, &["unsafe"]) +} + +fn normalize_mir_ty(s: &str) -> String { + let mut out = s + .split_whitespace() + .collect::>() + .join(" ") + .replace("core::sync::atomic::", "") + .replace("sync::atomic::", "") + .replace("atomic::", "") + .replace("core::result::", "") + .replace("result::", ""); + // Strip explicit lifetime on shared atomic references (e.g. `&'a Atomic<...>` -> `&Atomic<...>`). + if let Some(after_amp) = out.strip_prefix("&'") { + if let Some((_, rest)) = after_amp.split_once(' ') { + out = format!("&{rest}"); + } + } + out +} + +fn check_witness_generics(witness: &str, fn_sig: &str, ty: &str, method: &str) { + let sig_toks = lex_rust(fn_sig); + require( + !sig_toks.iter().any(|t| t.kind == TokKind::Ident && t.text(fn_sig) == "where"), + format!("witness {witness} must not carry a `where` clause: {fn_sig}"), + ); + let paren = fn_sig + .find('(') + .unwrap_or_else(|| fail(format!("missing '(' in witness signature {fn_sig}"))); + let gen_prefix: String = fn_sig[..paren].split_whitespace().collect::>().join(" "); + let expected_gen = match (ty == "*mut T", method == "from_ptr") { + (true, true) => "<'a, T>", + (true, false) => "", + (false, true) => "<'a>", + (false, false) => "", + }; + require( + gen_prefix == expected_gen, + format!( + "witness {witness} must have exact unconstrained generics `{expected_gen}`, found `{gen_prefix}`" + ), + ); +} + +fn verify_witness_mir( + witness_mir_dir: &Path, + module: &str, + witness: &str, + ty: &str, + method: &str, + expected_params: usize, +) { + let mir_mod = module.replace("::", "-"); + let mir_path = witness_mir_dir.join(format!("core.{mir_mod}-{witness}.built.after.mir")); + require( + mir_path.exists(), + format!("missing compiled witness MIR {} (witness may be commented out or cfg-disabled)", mir_path.display()), + ); + let text = read_text(&mir_path); + let mir_comment = format!("// MIR for `{module}::{witness}` after built"); + require( + text.lines().any(|l| l == mir_comment), + format!("missing MIR identity `{mir_comment}` in {}", mir_path.display()), + ); + let header_exact = format!("fn {witness}("); + let header_gen = format!("fn {witness}::<"); + let header = text + .lines() + .find(|l| l.starts_with(&header_exact) || l.starts_with(&header_gen)) + .unwrap_or_else(|| fail(format!("missing MIR header for {module}::{witness} in {}", mir_path.display()))); + let after_open = header + .split_once('(') + .map(|(_, r)| r) + .unwrap_or_else(|| fail(format!("malformed MIR witness header: {header}"))); + let (params_part, ret_part) = after_open + .split_once(") -> ") + .unwrap_or_else(|| fail(format!("malformed MIR witness header: {header}"))); + let ret_ty = normalize_mir_ty(ret_part.trim().strip_suffix('{').unwrap_or(ret_part).trim()); + + // Split top-level comma-separated parameters in MIR header and extract exact normalized types. + let mut param_tys: Vec = Vec::new(); + if !params_part.trim().is_empty() { + let mut depth = 0usize; + let mut start = 0usize; + for (idx, ch) in params_part.char_indices() { + match ch { + '<' | '(' | '[' => depth += 1, + '>' | ')' | ']' => depth = depth.saturating_sub(1), + ',' if depth == 0 => { + let item = params_part[start..idx].trim(); + let (_, pty) = item + .split_once(": ") + .unwrap_or_else(|| fail(format!("malformed MIR param `{item}` in {header}"))); + param_tys.push(normalize_mir_ty(pty)); + start = idx + 1; + } + _ => {} + } + } + let item = params_part[start..].trim(); + if !item.is_empty() { + let (_, pty) = item + .split_once(": ") + .unwrap_or_else(|| fail(format!("malformed MIR param `{item}` in {header}"))); + param_tys.push(normalize_mir_ty(pty)); + } + } + require( + param_tys.len() == expected_params, + format!("{module}::{witness}: MIR parameter count {} != source parameter count {expected_params}", param_tys.len()), + ); + + let (expected_param_tys, expected_ret_ty): (Vec, String) = match method { + "from_ptr" => (vec![format!("*mut {ty}")], format!("&Atomic<{ty}>")), + "store" => (vec![format!("&Atomic<{ty}>"), ty.to_string(), "Ordering".into()], "()".into()), + "load" => (vec![format!("&Atomic<{ty}>"), "Ordering".into()], ty.to_string()), + "compare_exchange" | "compare_exchange_weak" => ( + vec![ + format!("&Atomic<{ty}>"), + ty.to_string(), + ty.to_string(), + "Ordering".into(), + "Ordering".into(), + ], + format!("Result<{ty}, {ty}>"), + ), + _ => (vec![format!("&Atomic<{ty}>"), ty.to_string(), "Ordering".into()], ty.to_string()), + }; + require( + param_tys == expected_param_tys, + format!( + "{module}::{witness}: MIR parameter types {:?} != expected {:?}", + param_tys, expected_param_tys + ), + ); + require( + ret_ty == expected_ret_ty, + format!("{module}::{witness}: MIR return type `{ret_ty}` != expected `{expected_ret_ty}`"), + ); + + // Trace built MIR from bb0 to return verifying exact parameter & return forwarding. + let blocks = mir_blocks(&mir_path); + let mut initial_params: BTreeMap = BTreeMap::new(); + for i in 0..expected_params { + initial_params.insert(format!("_{}", i + 1), i); + } + + #[allow(clippy::too_many_arguments)] + fn trace( + blocks: &BTreeMap>, + block: &str, + module: &str, + witness: &str, + ty: &str, + method: &str, + expected_params: usize, + unwind_mode: bool, + mut seen_target: usize, + mut seen_shape: usize, + mut param_origin: BTreeMap, + mut result_locals: BTreeSet, + active: &mut HashSet, + ) { + require(!active.contains(block), format!("{module}::{witness}: loop at {block}")); + let stmts = blocks + .get(block) + .unwrap_or_else(|| fail(format!("{module}::{witness}: missing block {block}"))); + active.insert(block.to_string()); + for line in stmts { + if line.starts_with("FakeRead(") + || line.starts_with("AscribeUserType(") + || line.starts_with("PlaceMention(") + || line.starts_with("Retag(") + || line == "nop;" + { + continue; + } + if let Some((lhs, rhs)) = line.strip_suffix(';').and_then(|s| s.split_once(" = ")) { + if let Some((call_part, ret_bb, unw_bb)) = split_call_terminator(rhs) { + require(is_local(lhs), format!("{module}::{witness}/{block}: non-local call dst {lhs}")); + require(is_bb(ret_bb), format!("{module}::{witness}/{block}: bad return bb {ret_bb}")); + let (raw_callee, operands) = split_call_callee_operands(call_part).unwrap_or_else(|| { + fail(format!("{module}::{witness}/{block}: bad call {line}")) + }); + let callee_base = extract_mir_callee_base(raw_callee); + let expected_target = format!("Atomic::<{ty}>::{method}"); + let is_exact_target = raw_callee == expected_target + || raw_callee.starts_with(&format!("{expected_target}::<")); + if callee_base == "ch7_pointer_shape" && ty == "*mut T" { + require( + raw_callee.ends_with("ch7_pointer_shape::"), + format!("{module}::{witness}: ch7_pointer_shape must instantiate , got {raw_callee}"), + ); + require(!unwind_mode, format!("{module}::{witness}: ch7_pointer_shape on unwind path")); + require(seen_shape == 0, format!("{module}::{witness}: duplicate ch7_pointer_shape call")); + seen_shape += 1; + param_origin.remove(lhs); + result_locals.remove(lhs); + } else if is_exact_target { + require(!unwind_mode, format!("{module}::{witness}: target {method} on unwind path")); + require(seen_target == 0, format!("{module}::{witness}: duplicate target {method} call")); + let args: Vec<&str> = if operands.is_empty() { + Vec::new() + } else { + operands.split(", ").collect() + }; + require( + args.len() == expected_params, + format!("{module}::{witness}: target {method} got {} args, expected {expected_params}", args.len()), + ); + for (idx, op) in args.iter().enumerate() { + let origin = strip_move_or_copy(op) + .filter(|s| is_local(s)) + .and_then(|loc| param_origin.get(loc).copied()); + require( + origin == Some(idx), + format!("{module}::{witness}: argument #{idx} ({op}) to {method} is not unmodified parameter _{}", idx + 1), + ); + } + seen_target += 1; + param_origin.remove(lhs); + result_locals.clear(); + result_locals.insert(lhs.to_string()); + } else { + fail(format!("{module}::{witness}/{block}: unexpected MIR call {raw_callee}")); + } + trace( + blocks, + ret_bb, + module, + witness, + ty, + method, + expected_params, + unwind_mode, + seen_target, + seen_shape, + param_origin.clone(), + result_locals.clone(), + active, + ); + if let Some(ubb) = unw_bb { + require(is_bb(ubb), format!("{module}::{witness}/{block}: bad unwind bb {ubb}")); + trace( + blocks, + ubb, + module, + witness, + ty, + method, + expected_params, + true, + seen_target, + seen_shape, + param_origin, + result_locals, + active, + ); + } + active.remove(block); + return; + } + if rhs.contains("&mut ") || rhs.contains("&raw mut ") { + for loc in extract_local_refs(rhs) { + param_origin.remove(loc); + result_locals.remove(loc); + } + } + if is_local(lhs) { + if let Some(src) = strip_move_or_copy(rhs).filter(|s| is_local(s)) { + if let Some(&orig) = param_origin.get(src) { + param_origin.insert(lhs.to_string(), orig); + } else { + param_origin.remove(lhs); + } + if result_locals.contains(src) { + result_locals.insert(lhs.to_string()); + } else { + result_locals.remove(lhs); + } + } else if let Some(inner) = rhs.strip_prefix("&(*").and_then(|s| s.strip_suffix(')')) { + if is_local(inner) { + if let Some(&orig) = param_origin.get(inner) { + param_origin.insert(lhs.to_string(), orig); + } else { + param_origin.remove(lhs); + } + if result_locals.contains(inner) { + result_locals.insert(lhs.to_string()); + } else { + result_locals.remove(lhs); + } + } else { + param_origin.remove(lhs); + result_locals.remove(lhs); + } + } else { + param_origin.remove(lhs); + result_locals.remove(lhs); + } + } else { + for loc in extract_local_refs(lhs) { + param_origin.remove(loc); + result_locals.remove(loc); + } + } + continue; + } + if let Some(next) = parse_goto_or_false_edge(line) { + trace( + blocks, + next, + module, + witness, + ty, + method, + expected_params, + unwind_mode, + seen_target, + seen_shape, + param_origin, + result_locals, + active, + ); + active.remove(block); + return; + } + if line == "return;" { + require(!unwind_mode, format!("{module}::{witness}/{block}: unwind path returned normally")); + require(seen_target == 1, format!("{module}::{witness}: expected 1 call to {method}, saw {seen_target}")); + let need_shape = usize::from(ty == "*mut T"); + require(seen_shape == need_shape, format!("{module}::{witness}: expected {need_shape} ch7_pointer_shape calls, saw {seen_shape}")); + if method != "store" { + require( + result_locals.contains("_0"), + format!("{module}::{witness}: return value _0 is not the unmodified result of {method}"), + ); + } + active.remove(block); + return; + } + if line == "resume;" { + require(unwind_mode, format!("{module}::{witness}/{block}: normal path reached resume")); + active.remove(block); + return; + } + fail(format!("{module}::{witness}/{block}: unsupported witness MIR statement {line}")); + } + fail(format!("{module}::{witness}/{block}: missing terminator")); + } + + let mut active = HashSet::new(); + trace( + &blocks, + "bb0", + module, + witness, + ty, + method, + expected_params, + false, + 0, + 0, + initial_params, + BTreeSet::new(), + &mut active, + ); +} + +fn verify_pointer_shape_empty(pointer_shape: &Path, witness_mir_dir: &Path) { + // 1. Source check: unique unattributed `pub(crate) unsafe fn ch7_pointer_shape` with empty non-ghost body. + let src = read_text(pointer_shape); + let (_sig, _clauses, body) = extract_fn_with_quals(&src, "ch7_pointer_shape", &["pub(crate)", "unsafe"]); + require( + strip_ghost(&body).is_empty(), + format!("ch7_pointer_shape must have an empty source body, found `{}`", strip_ghost(&body)), + ); + + // 2. Compiled MIR check: `intrinsics::ch7_pointer_shape` must construct `()` and return immediately. + let mir_path = witness_mir_dir.join("core.intrinsics-ch7_pointer_shape.built.after.mir"); + require( + mir_path.exists(), + format!("missing compiled ch7_pointer_shape MIR {}", mir_path.display()), + ); + let text = read_text(&mir_path); + require( + text.lines().any(|l| l == "// MIR for `intrinsics::ch7_pointer_shape` after built"), + format!("missing MIR identity for intrinsics::ch7_pointer_shape in {}", mir_path.display()), + ); + let blocks = mir_blocks(&mir_path); + require( + blocks.len() == 1, + format!("ch7_pointer_shape MIR must have exactly 1 basic block, found {}", blocks.len()), + ); + let bb0 = blocks + .get("bb0") + .unwrap_or_else(|| fail("ch7_pointer_shape MIR missing bb0")); + let meaningful: Vec<&str> = bb0 + .iter() + .map(String::as_str) + .filter(|l| !l.starts_with("FakeRead(") && !l.starts_with("PlaceMention(") && *l != "nop;") + .collect(); + require( + meaningful == ["_0 = const ();", "return;"], + format!("ch7_pointer_shape MIR must only return (), found {:?}", meaningful), + ); +} + +fn verify_ro_helper_mir( + mir_path: &Path, + expected_comment: &str, + fn_name: &str, + ty: &str, + method: &str, + is_prod: bool, +) { + require(mir_path.exists(), format!("missing compiled MIR {}", mir_path.display())); + let text = read_text(mir_path); + if is_prod { + let sig_suffix = if method == "store" { + format!(">::store(_1: &Atomic<{ty}>, _2: {ty}, _3: atomic::Ordering) -> () {{") + } else { + format!(">::{method}(_1: &Atomic<{ty}>, _2: {ty}, _3: {ty}, _4: atomic::Ordering, _5: atomic::Ordering) -> result::Result<{ty}, {ty}> {{") + }; + require( + text.lines() + .any(|l| l.starts_with("fn atomic::::as_ptr -> cast::. + for outcome in ["Ok", "Err"] { + for old in [0u8, 1u8] { + let mut values: HashMap = HashMap::from([ + ("_1".into(), BoolVal::Str("receiver")), + ("_2".into(), BoolVal::Str("expected")), + ("_3".into(), BoolVal::Str("replacement")), + ("_4".into(), BoolVal::Str("success")), + ("_5".into(), BoolVal::Str("failure")), + ]); + let mut block = "bb0".to_string(); + let mut visited = HashSet::new(); + let mut calls: Vec = Vec::new(); + while visited.insert(block.clone()) { + let stmts = blocks + .get(&block) + .unwrap_or_else(|| fail(format!("{fn_name}: missing block {block}"))); + let mut next_block: Option = None; + for (index, line) in stmts.iter().enumerate() { + let last = index + 1 == stmts.len(); + if line.starts_with("FakeRead(") || line.starts_with("AscribeUserType(") || line == "nop;" { + continue; + } + if let Some((dst, rhs)) = line.strip_suffix(';').and_then(|s| s.split_once(" = ")) { + if is_local(dst) { + if rhs == "const ()" { + values.insert(dst.into(), BoolVal::Str("unit")); + } else if rhs == "&(*_1)" { + values.insert(dst.into(), BoolVal::Str("receiver")); + } else if let Some(src) = strip_move_or_copy(rhs).filter(|s| is_local(s)) { + let v = values.get(src).cloned().unwrap_or_else(|| fail(format!("{fn_name}: missing {src}"))); + values.insert(dst.into(), v); + } else if let Some(src) = rhs + .strip_prefix("move ") + .and_then(|s| s.strip_suffix(" as u8 (IntToInt)")) + .filter(|s| is_local(s)) + { + match values.get(src) { + Some(BoolVal::Str("expected")) => { + values.insert(dst.into(), BoolVal::Byte("expected")); + } + Some(BoolVal::Str("replacement")) => { + values.insert(dst.into(), BoolVal::Byte("replacement")); + } + _ => fail(format!("{fn_name}: cast did not consume original bool operand")), + } + } else if let Some(src) = rhs + .strip_prefix("discriminant(") + .and_then(|s| s.strip_suffix(')')) + .filter(|s| is_local(s)) + { + require( + values.get(src) == Some(&BoolVal::Helper(outcome.into(), old)), + format!("{fn_name}: discriminator did not come from helper"), + ); + values.insert(dst.into(), BoolVal::U8(if outcome == "Ok" { 0 } else { 1 })); + } else if let Some(inner) = rhs + .strip_prefix("copy ((") + .and_then(|s| s.strip_suffix(").0: u8)")) + { + let (loc, tag) = inner + .split_once(" as ") + .unwrap_or_else(|| fail(format!("{fn_name}/{block}: bad projection {line}"))); + require( + is_local(loc) + && (tag == "Ok" || tag == "Err") + && outcome == tag + && values.get(loc) == Some(&BoolVal::Helper(tag.into(), old)), + format!("{fn_name}: wrong byte result projection"), + ); + values.insert(dst.into(), BoolVal::U8(old)); + } else if let Some(src) = rhs + .strip_prefix("Ne(move ") + .and_then(|s| s.strip_suffix(", const 0_u8)")) + .filter(|s| is_local(s)) + { + require( + values.get(src) == Some(&BoolVal::U8(old)), + format!("{fn_name}: boolean return does not use observed byte"), + ); + values.insert(dst.into(), BoolVal::Bool(old != 0)); + } else if let Some(rest) = rhs.strip_prefix("result::Result::::") { + let (tag, loc) = rest + .split_once("(move ") + .and_then(|(t, r)| r.strip_suffix(')').map(|l| (t, l))) + .unwrap_or_else(|| fail(format!("{fn_name}/{block}: bad Result {line}"))); + require( + (tag == "Ok" || tag == "Err") && is_local(loc), + format!("{fn_name}/{block}: bad Result {line}"), + ); + let b = match values.get(loc) { + Some(BoolVal::Bool(b)) => *b, + _ => fail(format!("{fn_name}: public result must contain bool")), + }; + values.insert(dst.into(), BoolVal::Public(tag.into(), b)); + } else if let Some((call_part, term_part)) = rhs.split_once(") -> [return: ") { + let (normal, unwind) = term_part + .strip_suffix(']') + .and_then(|s| s.split_once(", unwind: ")) + .unwrap_or_else(|| fail(format!("{fn_name}/{block}: bad call {line}"))); + require(is_bb(normal) && is_bb(unwind), format!("{fn_name}/{block}: bad call {line}")); + let (callee, operands) = call_part + .split_once('(') + .unwrap_or_else(|| fail(format!("{fn_name}/{block}: bad call {line}"))); + let mut args = Vec::new(); + for operand in operands.split(", ") { + let loc = operand + .strip_prefix("move ") + .filter(|s| is_local(s)) + .unwrap_or_else(|| fail(format!("{fn_name}: unexpected {callee} arg {operand}"))); + args.push( + values + .get(loc) + .cloned() + .unwrap_or_else(|| fail(format!("{fn_name}: missing {loc}"))), + ); + } + require( + last && blocks.get(unwind).is_some_and(|b| b.as_slice() == ["resume;"]), + format!("{fn_name}/{callee}: extra cleanup access"), + ); + if callee == "Atomic::::as_ptr" { + require(args == [BoolVal::Str("receiver")], format!("{fn_name}: wrong as_ptr receiver")); + values.insert(dst.into(), BoolVal::Str("raw-receiver")); + } else if callee == "ptr::mut_ptr::::cast::" { + require(args == [BoolVal::Str("raw-receiver")], format!("{fn_name}: cast changed slot")); + values.insert(dst.into(), BoolVal::Str("byte-slot")); + } else { + let expected_callee = format!("atomic_{method}::"); + let expected_args = vec![ + BoolVal::Str("byte-slot"), + BoolVal::Byte("expected"), + BoolVal::Byte("replacement"), + BoolVal::Str("success"), + BoolVal::Str("failure"), + ]; + require( + callee == expected_callee && args == expected_args, + format!("{fn_name}: wrong CAS helper/args ({callee}, {:?})", args), + ); + values.insert(dst.into(), BoolVal::Helper(outcome.into(), old)); + } + calls.push(callee.to_string()); + next_block = Some(normal.to_string()); + break; + } else { + fail(format!("{fn_name}/{block}: unsupported assignment {line}")); + } + require(!last, format!("{fn_name}: block lacks terminator")); + continue; + } + } + if let Some(bb) = line.strip_prefix("goto -> ").and_then(|s| s.strip_suffix(';')) { + require(last && is_bb(bb), "nonterminal goto"); + next_block = Some(bb.to_string()); + break; + } else if let Some(rest) = line + .strip_prefix("switchInt(move ") + .and_then(|s| s.strip_suffix("];")) + { + let (loc, branches) = rest + .split_once(") -> [") + .unwrap_or_else(|| fail(format!("{fn_name}/{block}: bad switchInt {line}"))); + require(last && is_local(loc), "nonterminal switch"); + let key = match values.get(loc) { + Some(BoolVal::U8(n)) => n.to_string(), + _ => fail(format!("{fn_name}/{block}: non-u8 switch value {loc}")), + }; + let tgt = parse_switch_targets(branches) + .into_iter() + .find(|(k, _)| k == &key) + .map(|(_, v)| v) + .unwrap_or_else(|| fail(format!("{fn_name}/{block}: missing switch target {key}"))); + next_block = Some(tgt); + break; + } else if let Some(real) = line + .strip_prefix("falseEdge -> [real: ") + .and_then(|s| s.strip_suffix("];")) + .and_then(|s| s.split_once(", imaginary: ")) + .filter(|(r, i)| is_bb(r) && is_bb(i)) + .map(|(r, _)| r) + { + require(last, "nonterminal falseEdge"); + next_block = Some(real.to_string()); + break; + } else if let Some(loc) = line + .strip_prefix("PlaceMention(") + .and_then(|s| s.strip_suffix(");")) + .filter(|s| is_local(s)) + { + require( + !last && values.get(loc) == Some(&BoolVal::Helper(outcome.into(), old)), + "unexpected place mention", + ); + } else if line == "return;" { + require( + last && values.get("_0") == Some(&BoolVal::Public(outcome.into(), old != 0)), + format!("{fn_name}: incorrect public return"), + ); + let expected_calls = vec![ + "Atomic::::as_ptr".to_string(), + "ptr::mut_ptr::::cast::".to_string(), + format!("atomic_{method}::"), + ]; + require(calls == expected_calls, format!("{fn_name}: wrong calls {:?}", calls)); + next_block = None; + break; + } else { + fail(format!("{fn_name}/{block}: unsupported operation {line}")); + } + } + if let Some(nb) = next_block { + block = nb; + } else { + break; + } + } + } + } + return; + } + + // Straight-line helper wrapper tracer for: + // - Atomic::store / ro_bool_store + // - Atomic::{store, compare_exchange, compare_exchange_weak} / ro_u32_* + let mut values: HashMap = HashMap::from([("_1".into(), "receiver")]); + if method == "store" { + values.insert("_2".into(), "val"); + values.insert("_3".into(), "order"); + } else { + values.insert("_2".into(), "current"); + values.insert("_3".into(), "new"); + values.insert("_4".into(), "success"); + values.insert("_5".into(), "failure"); + } + let mut block = "bb0".to_string(); + let mut visited = HashSet::new(); + let mut calls: Vec = Vec::new(); + while visited.insert(block.clone()) { + let stmts = blocks + .get(&block) + .unwrap_or_else(|| fail(format!("{fn_name}: missing block {block}"))); + let mut next_block: Option = None; + for (index, line) in stmts.iter().enumerate() { + let last = index + 1 == stmts.len(); + if line.starts_with("FakeRead(") || line.starts_with("AscribeUserType(") || line == "nop;" { + continue; + } + if let Some((dst, rhs)) = line.strip_suffix(';').and_then(|s| s.split_once(" = ")) { + if is_local(dst) { + if rhs == "const ()" { + values.insert(dst.into(), "unit"); + } else if rhs == "&(*_1)" { + values.insert(dst.into(), "receiver"); + } else if rhs == "&((*_1).0: cell::UnsafeCell>)" + && ty == "bool" + && is_prod + { + values.insert(dst.into(), "receiver-cell"); + } else if let Some(src) = strip_move_or_copy(rhs).filter(|s| is_local(s)) { + let v = *values.get(src).unwrap_or_else(|| fail(format!("{fn_name}: missing {src}"))); + values.insert(dst.into(), v); + } else if let Some(src) = rhs + .strip_prefix("move ") + .and_then(|s| s.strip_suffix(" as u8 (IntToInt)")) + .filter(|s| is_local(s)) + { + require( + ty == "bool" && values.get(src) == Some(&"val"), + format!("{fn_name}: unexpected bool->u8 cast of {src}"), + ); + values.insert(dst.into(), "val-byte"); + } else if let Some((call_part, term_part)) = rhs.split_once(") -> [return: ") { + let (normal, unwind) = term_part + .strip_suffix(']') + .and_then(|s| s.split_once(", unwind: ")) + .unwrap_or_else(|| fail(format!("{fn_name}/{block}: bad call {line}"))); + require(is_bb(normal) && is_bb(unwind), format!("{fn_name}/{block}: bad call {line}")); + require( + last && blocks.get(unwind).is_some_and(|b| b.as_slice() == ["resume;"]), + format!("{fn_name}: extra cleanup access"), + ); + let (callee, operands) = call_part + .split_once('(') + .unwrap_or_else(|| fail(format!("{fn_name}/{block}: bad call {line}"))); + let mut args: Vec<&str> = Vec::new(); + for operand in operands.split(", ") { + let loc = operand + .strip_prefix("move ") + .filter(|s| is_local(s)) + .unwrap_or_else(|| fail(format!("{fn_name}: unexpected {callee} arg {operand}"))); + args.push(*values.get(loc).unwrap_or_else(|| fail(format!("{fn_name}: missing {loc}")))); + } + let norm_callee = callee.strip_prefix("atomic::").unwrap_or(callee); + if ty == "bool" && is_prod && callee == "UnsafeCell::>::get" { + require(args == ["receiver-cell"], format!("{fn_name}: wrong cell receiver")); + values.insert(dst.into(), "raw-receiver"); + } else if ty == "bool" && is_prod && callee == "ptr::mut_ptr::>::cast::" { + require(args == ["raw-receiver"], format!("{fn_name}: cast changed slot")); + values.insert(dst.into(), "slot"); + } else if ty == "bool" && !is_prod && callee == "Atomic::::as_ptr" { + require(args == ["receiver"], format!("{fn_name}: wrong as_ptr receiver")); + values.insert(dst.into(), "raw-receiver"); + } else if ty == "bool" && !is_prod && callee == "ptr::mut_ptr::::cast::" { + require(args == ["raw-receiver"], format!("{fn_name}: cast changed slot")); + values.insert(dst.into(), "slot"); + } else if ty == "u32" && callee == "Atomic::::as_ptr" { + require(args == ["receiver"], format!("{fn_name}: wrong as_ptr receiver")); + values.insert(dst.into(), "slot"); + } else if method == "store" { + let exp_callee = if ty == "bool" { + "atomic_store::" + } else { + "atomic_store::" + }; + let exp_args = if ty == "bool" { + vec!["slot", "val-byte", "order"] + } else { + vec!["slot", "val", "order"] + }; + require( + norm_callee == exp_callee && args == exp_args, + format!("{fn_name}: wrong store helper/args ({norm_callee}, {:?})", args), + ); + values.insert(dst.into(), "helper-unit"); + } else { + let exp_callee = format!("atomic_{method}::"); + let exp_args = vec!["slot", "current", "new", "success", "failure"]; + require( + norm_callee == exp_callee && args == exp_args, + format!("{fn_name}: wrong CAS helper/args ({norm_callee}, {:?})", args), + ); + values.insert(dst.into(), "helper-ret"); + } + calls.push(norm_callee.to_string()); + next_block = Some(normal.to_string()); + break; + } else { + fail(format!("{fn_name}/{block}: unsupported assignment {line}")); + } + require(!last, format!("{fn_name}: block lacks terminator")); + continue; + } + } + if line == "return;" { + require(last, "nonterminal return"); + let expected_calls: Vec = match (ty, is_prod, method) { + ("bool", true, "store") => vec![ + "UnsafeCell::>::get".into(), + "ptr::mut_ptr::>::cast::".into(), + "atomic_store::".into(), + ], + ("bool", false, "store") => vec![ + "Atomic::::as_ptr".into(), + "ptr::mut_ptr::::cast::".into(), + "atomic_store::".into(), + ], + ("u32", _, "store") => vec![ + "Atomic::::as_ptr".into(), + "atomic_store::".into(), + ], + ("u32", _, m) => vec![ + "Atomic::::as_ptr".into(), + format!("atomic_{m}::"), + ], + _ => unreachable!(), + }; + require(calls == expected_calls, format!("{fn_name}: wrong call sequence {:?}", calls)); + if method == "store" { + require(values.get("_0") == Some(&"unit"), format!("{fn_name}: store must return ()")); + } else { + require( + values.get("_0") == Some(&"helper-ret"), + format!("{fn_name}: CAS must return unmodified helper result"), + ); + } + return; + } + fail(format!("{fn_name}/{block}: unsupported operation {line}")); + } + block = next_block.unwrap_or_else(|| fail(format!("{fn_name}/{block}: missing terminator"))); + } + fail(format!("{fn_name}: loop before return")); +} + +fn check_ro_helper_source_body(ty: &str, method: &str, body: &str) { + let code = strip_ghost(body); + let expected = match (ty, method) { + ("bool", "store") => { + "unsafe { atomic_store::<_, false>(receiver.as_ptr().cast::(), val as u8, order); }" + } + ("bool", "compare_exchange") => { + "let raw = unsafe { atomic_compare_exchange(receiver.as_ptr().cast::(), current as u8, new as u8, success, failure) }; match raw { Ok(x) => Ok(x != 0), Err(x) => Err(x != 0), }" + } + ("bool", "compare_exchange_weak") => { + "let raw = unsafe { atomic_compare_exchange_weak(receiver.as_ptr().cast::(), current as u8, new as u8, success, failure) }; match raw { Ok(x) => Ok(x != 0), Err(x) => Err(x != 0), }" + } + ("u32", "store") => "unsafe { atomic_store::<_, false>(receiver.as_ptr(), val, order); }", + ("u32", "compare_exchange") => { + "let out = unsafe { atomic_compare_exchange(receiver.as_ptr(), current, new, success, failure) }; out" + } + ("u32", "compare_exchange_weak") => { + "let out = unsafe { atomic_compare_exchange_weak(receiver.as_ptr(), current, new, success, failure) }; out" + } + _ => fail(format!("unsupported readonly helper bridge ({ty}, {method})")), + }; + require( + code == expected, + format!("readonly helper witness body ({ty}::{method}) changed:\n got: {code}\n expected: {expected}"), + ); +} + +fn cmd_thread_spec( + family: &str, + src_dir: &Path, + owners_file: &Path, + scope_file: &Path, + pointer_shape: &Path, + witness_mir_dir: &Path, + prod_mir_dir: Option<&Path>, +) { + let owners = parse_owners(owners_file); + let mut declarations: Vec<&str> = Vec::new(); + // (ty, module, witness, method, direct_public) + let mut functions: Vec<(&str, &str, String, String, bool)> = Vec::new(); + match family { + "access" => { + for w in ["8", "16"] { + let ty = if w == "8" { "u8" } else { "u16" }; + for m in ["view", "load", "store"] { + let meth = if m == "view" { "from_ptr" } else { m }; + functions.push((ty, "ch7_width", format!("borrowed_{m}{w}"), meth.into(), true)); + } + } + for m in ["view", "load", "store"] { + let meth = if m == "view" { "from_ptr" } else { m }; + functions.push(("bool", "ch7_bool", format!("shared_bool_{m}"), meth.into(), true)); + } + declarations.extend(["accepts_unsigned", "unsigned_content", "valid_bool_byte", "bool_slot_content"]); + } + "rmw" => { + for m in ["nand", "and"] { + functions.push(("bool", "ch7_bool", format!("shared_bool_{m}"), format!("fetch_{m}"), true)); + } + } + "u32" => { + for m in ["from_ptr", "load", "store", "swap", "compare_exchange", "compare_exchange_weak", "fetch_add", "fetch_sub"] { + functions.push(("u32", "ch7_public", format!("borrowed_{m}"), m.into(), true)); + } + declarations.extend(["accepts_word", "U32_atomic_content"]); + } + "pointer-access" => { + verify_pointer_shape_empty(pointer_shape, witness_mir_dir); + for m in ["view", "swap", "compare_exchange", "compare_exchange_weak"] { + let meth = if m == "view" { "from_ptr" } else { m }; + functions.push(("*mut T", "ch7_pointer", format!("thread_pointer_{m}"), meth.into(), true)); + } + declarations.extend(["accepts_pointer", "thread_pointer_content"]); + } + "readonly" => { + let pmir = prod_mir_dir.unwrap_or_else(|| fail("thread-spec readonly requires ")); + // Verify EMULATE_ATOMIC_BOOL == false directly on host production MIR. + let emulate = mir_blocks(&pmir.join("core.sync-atomic-EMULATE_ATOMIC_BOOL.built.after.mir")); + let expected_emulate = BTreeMap::from([( + "bb0".to_string(), + vec!["_0 = const false;".to_string(), "return;".to_string()], + )]); + require(emulate == expected_emulate, "readonly bridge requires EMULATE_ATOMIC_BOOL == false"); + for ty in ["bool", "u32"] { + for m in ["from_ptr", "load"] { + functions.push((ty, "sync::atomic::ch7_readonly", format!("ro_{ty}_{m}"), m.into(), true)); + } + for m in ["store", "compare_exchange", "compare_exchange_weak"] { + functions.push((ty, "sync::atomic::ch7_readonly", format!("ro_{ty}_{m}"), m.into(), false)); + } + } + declarations.extend([ + "valid_bool_byte", + "is_bool_byte", + "is_u32_val", + "accepts_word", + "ro_bool_content", + "ro_u32_content", + "ro_bool_borrow", + "ro_u32_borrow", + "rw_bool_content", + "rw_u32_content", + ]); + } + _ => return, + } + + let atomic = read_text(&src_dir.join("sync/atomic.rs")); + let mut out = vec!["mod sync { mod atomic {".to_string(), "/*@".to_string()]; + for decl in declarations { + let source = if decl == "thread_pointer_content" { + read_text(&src_dir.join("ch7_pointer.rs")) + } else { + atomic.clone() + }; + let extracted = extract_ghost_decl(&source, decl); + out.push(extracted.replace("sync::atomic::accepts_pointer", "accepts_pointer")); + } + out.push("@*/".into()); + + let (calls, outgoing) = parse_edges_with_outgoing(&read_text(scope_file)); + for (ty, module, witness, method, direct_public) in functions { + let mod_path = module.replace("::", "/"); + let text = read_text(&src_dir.join(format!("{mod_path}.rs"))); + let (fn_sig, mut clauses, body) = extract_witness_fn(&text, &witness); + check_witness_generics(&witness, &fn_sig, ty, &method); + let expected_params = fn_sig + .split_once('(') + .and_then(|(_, r)| r.split_once(')')) + .map(|(p, _)| p.split(',').filter(|s| !s.trim().is_empty()).count()) + .unwrap_or_else(|| fail(format!("bad witness signature {fn_sig}"))); + let caller = format!("{module}::{witness}"); + let all_callees = outgoing.get(&caller).map(Vec::as_slice).unwrap_or(&[]); + let non_ghost: Vec<&str> = all_callees + .iter() + .map(String::as_str) + .filter(|c| *c != "VeriFast_ghost_command") + .collect(); + if direct_public { + check_forwarding_body(&fn_sig, &body, &method, ty); + verify_witness_mir(witness_mir_dir, module, &witness, ty, &method, expected_params); + let public = format!("{PREFIX}{}::{method}", owners[ty]); + let count = calls.get(&(caller.clone(), public.clone())).map_or(0, Vec::len); + require(count == 1, format!("{witness} must call {public}")); + if ty == "*mut T" { + let shape_count = calls + .get(&(caller.clone(), "intrinsics::ch7_pointer_shape".to_string())) + .map_or(0, Vec::len); + require( + non_ghost.len() == 2 && shape_count == 1, + format!( + "{witness} has unexpected MIR call edges {:?} (expected only ch7_pointer_shape and {public})", + non_ghost + ), + ); + } else { + require( + non_ghost.len() == 1 && non_ghost[0] == public, + format!( + "{witness} has unexpected MIR call edges {:?} (expected only {public})", + non_ghost + ), + ); + } + } else { + let pmir = prod_mir_dir.unwrap(); + check_ro_helper_source_body(ty, &method, &body); + let wmir_path = witness_mir_dir.join(format!("core.{}-{witness}.built.after.mir", module.replace("::", "-"))); + verify_ro_helper_mir( + &wmir_path, + &format!("// MIR for `{module}::{witness}` after built"), + &witness, + ty, + &method, + false, + ); + let owner = &owners[ty]; + let pmir_path = pmir.join(format!("core.sync-atomic-{owner}-{method}.built.after.mir")); + verify_ro_helper_mir( + &pmir_path, + &format!("// MIR for `sync::atomic::>::{method}` after built"), + &format!("Atomic::<{ty}>::{method}"), + ty, + &method, + true, + ); + let as_ptr = format!("{PREFIX}{owner}::as_ptr"); + let helper = format!("{PREFIX}atomic_{method}"); + let mut actual_edges: Vec<&str> = non_ghost.clone(); + actual_edges.sort(); + let mut expected_edges: Vec<&str> = if ty == "bool" { + vec![as_ptr.as_str(), "ptr::mut_ptr::{impl#0}::cast", helper.as_str()] + } else { + vec![as_ptr.as_str(), helper.as_str()] + }; + expected_edges.sort(); + require( + actual_edges == expected_edges, + format!( + "{witness} has unexpected MIR call edges {:?} (expected {:?})", + actual_edges, expected_edges + ), + ); + } + + let receiver = format!("Atomic<{ty}>"); + let mut sig = fn_sig + .split_whitespace() + .collect::>() + .join(" ") + .replace("crate::sync::atomic::", "") + .replace("crate::result::Result", "std::result::Result") + .replace("std::result::Result<", "Result<") + .replace("Result<", "std::result::Result<"); + for alias in ["AtomicU8", "AtomicU16", "AtomicU32", "AtomicBool", "AtomicPtr"] { + sig = sig.replace(alias, &receiver); + } + sig = sig.replace("( ", "("); + if method != "from_ptr" { + let old_recv = format!("(receiver: &{receiver}"); + let new_recv = format!("(self: &'a {receiver}"); + require( + sig.contains(&old_recv), + format!("expected receiver parameter `{old_recv}` in normalized signature `{sig}`"), + ); + sig = sig.replacen(&old_recv, &new_recv, 1); + } + let paren = sig.find('(').unwrap_or_else(|| fail(format!("missing '(' in {sig}"))); + let tail = sig[paren..].replace(", )", ")"); + let signature = if method == "from_ptr" { + format!("unsafe fn from_ptr<'a>{tail}") + } else { + format!("fn {method}<'a>{tail}") + }; + clauses = replace_ident_whole(&clauses, "receiver", "self") + .replace("sync::atomic::", "std::sync::atomic::") + .replace("result::Result_own", "std::result::Result_own") + .replace("thread_pointer_content", "std::sync::atomic::thread_pointer_content"); + let impl_hdr = if ty == "*mut T" { "impl" } else { "impl" }; + out.push(format!("{impl_hdr} {receiver} {{")); + out.push(format!("{signature};")); + out.push(clauses); + out.push("}".into()); + } + out.push("} }".into()); + println!("{}", out.join("\n")); +} + +fn cmd_patch_audit(patch_file: &Path, audit_md: &Path) { + let patch = read_text(patch_file); + let mut starts: Vec<(String, usize)> = Vec::new(); + let mut current_path: Option = None; + for line in patch.lines() { + if let Some(rest) = line.strip_prefix("diff --git ") { + let (_, b_path) = rest + .split_once(" b/") + .unwrap_or_else(|| fail(format!("bad diff header: {line}"))); + current_path = Some(b_path.to_string()); + } else if let Some(rest) = line.strip_prefix("@@ -") { + if let Some((_, after_plus)) = rest.split_once(" +") { + let num_str: String = after_plus.chars().take_while(|c| c.is_ascii_digit()).collect(); + let n: usize = num_str.parse().unwrap_or_else(|_| fail(format!("bad hunk header: {line}"))); + let path = current_path.clone().unwrap_or_else(|| fail("hunk before diff header")); + starts.push((path, n)); + } + } + } + let audit = read_text(audit_md); + let mut documented: Vec<(String, usize)> = Vec::new(); + for line in audit.lines() { + if let Some(rest) = line.strip_prefix("| `") { + if let Some((path, after)) = rest.split_once("` | ") { + if let Some((nums, _)) = after.split_once(" |") { + if nums.chars().all(|c| c.is_ascii_digit() || c == ',' || c == ' ') && nums.chars().any(|c| c.is_ascii_digit()) { + for n in nums.split(", ") { + let val: usize = n.trim().parse().unwrap_or_else(|_| fail(format!("bad audit line: {line}"))); + documented.push((path.to_string(), val)); + } + } + } + } + } + } + starts.sort(); + documented.sort(); + require(!starts.is_empty() && documented == starts, "tool patch hunk audit differs from the unified diff"); + let files: BTreeSet<&str> = starts.iter().map(|(p, _)| p.as_str()).collect(); + println!("PASS tool patch audit ({} files, {} hunks)", files.len(), starts.len()); +} + +fn parse_llvm_blocks(body: &str) -> BTreeMap> { + let mut blocks: BTreeMap> = BTreeMap::new(); + let mut cur_label = String::new(); + let mut cur_insts: Vec = Vec::new(); + for raw in body.lines() { + let no_comment = raw.split(';').next().unwrap_or(""); + let trimmed = no_comment.trim(); + if trimmed.is_empty() { + continue; + } + // Basic block label starts at column 0 and ends with ':' + if !no_comment.starts_with(' ') && !no_comment.starts_with('\t') { + if let Some(label) = trimmed.strip_suffix(':') { + if !cur_label.is_empty() { + blocks.insert(cur_label, std::mem::take(&mut cur_insts)); + } + cur_label = label.to_string(); + continue; + } + } + // Continuation line (e.g. "to label %bb1 unwind label %terminate" or landingpad clauses) + if (no_comment.starts_with(" ") + || no_comment.starts_with('\t') + || trimmed.starts_with("to label ") + || trimmed.starts_with("catch ") + || trimmed.starts_with("filter ") + || trimmed == "cleanup") + && !cur_insts.is_empty() + { + let prev = cur_insts.last_mut().unwrap(); + prev.push(' '); + prev.push_str(trimmed); + } else { + cur_insts.push(trimmed.to_string()); + } + } + if !cur_label.is_empty() { + blocks.insert(cur_label, cur_insts); + } + blocks +} + +/// Extract the direct `@symbol` callee from an LLVM IR `call` or `invoke` instruction. +/// Scans ONLY at delimiter depth 0 before the call argument list `(...)`, so global +/// symbols passed inside arguments (e.g. `call void @event(ptr @panic_cannot_unwind)`) +/// are never mistaken for the callee, and indirect `%fn(...)` calls return `None`. +fn extract_llvm_direct_callee(inst: &str) -> Option<&str> { + let mut rest = inst.trim(); + if let Some((_, rhs)) = rest.split_once(" = ") { + rest = rhs.trim_start(); + } + for prefix in ["musttail ", "tail ", "notail "] { + if let Some(after) = rest.strip_prefix(prefix) { + rest = after.trim_start(); + break; + } + } + let after_op = rest + .strip_prefix("call ") + .or_else(|| rest.strip_prefix("invoke "))?; + + let bytes = after_op.as_bytes(); + let mut depth = 0usize; + let mut i = 0; + while i < bytes.len() { + let b = bytes[i]; + if b == b'"' { + i += 1; + while i < bytes.len() { + if bytes[i] == b'\\' { + i += 2; + } else if bytes[i] == b'"' { + i += 1; + break; + } else { + i += 1; + } + } + continue; + } + if depth == 0 && (b == b'@' || b == b'%') { + let is_global = b == b'@'; + let mut j = i + 1; + let sym_start; + let sym_end; + if j < bytes.len() && bytes[j] == b'"' { + j += 1; + sym_start = j; + while j < bytes.len() && bytes[j] != b'"' { + if bytes[j] == b'\\' { + j += 2; + } else { + j += 1; + } + } + if j >= bytes.len() { + return None; + } + sym_end = j; + j += 1; + } else { + sym_start = j; + while j < bytes.len() + && (bytes[j].is_ascii_alphanumeric() + || matches!(bytes[j], b'_' | b'$' | b'.' | b'-')) + { + j += 1; + } + sym_end = j; + } + let mut k = j; + while k < bytes.len() && bytes[k].is_ascii_whitespace() { + k += 1; + } + if k < bytes.len() && bytes[k] == b'(' { + return if is_global && sym_end > sym_start { + Some(&after_op[sym_start..sym_end]) + } else { + None + }; + } + i = j; + continue; + } + match b { + b'(' | b'[' | b'{' | b'<' => depth += 1, + b')' | b']' | b'}' | b'>' => depth = depth.saturating_sub(1), + _ => {} + } + i += 1; + } + None +} + +/// Extract the defined `@symbol` name from an LLVM IR `define ... @name(...)` header. +fn extract_llvm_defined_symbol(header: &str) -> Option<&str> { + let after_def = header.trim().strip_prefix("define ")?; + let bytes = after_def.as_bytes(); + let mut depth = 0usize; + let mut i = 0; + while i < bytes.len() { + let b = bytes[i]; + if b == b'"' { + i += 1; + while i < bytes.len() && bytes[i] != b'"' { + i += if bytes[i] == b'\\' { 2 } else { 1 }; + } + i = (i + 1).min(bytes.len()); + continue; + } + if depth == 0 && b == b'@' { + let mut j = i + 1; + let (s, e) = if j < bytes.len() && bytes[j] == b'"' { + j += 1; + let s = j; + while j < bytes.len() && bytes[j] != b'"' { + j += if bytes[j] == b'\\' { 2 } else { 1 }; + } + let e = j; + if j < bytes.len() { + j += 1; + } + (s, e) + } else { + let s = j; + while j < bytes.len() + && (bytes[j].is_ascii_alphanumeric() + || matches!(bytes[j], b'_' | b'$' | b'.' | b'-')) + { + j += 1; + } + (s, j) + }; + let mut k = j; + while k < bytes.len() && bytes[k].is_ascii_whitespace() { + k += 1; + } + if k < bytes.len() && bytes[k] == b'(' && e > s { + return Some(&after_def[s..e]); + } + i = j; + continue; + } + match b { + b'(' | b'[' | b'{' | b'<' => depth += 1, + b')' | b']' | b'}' | b'>' => depth = depth.saturating_sub(1), + _ => {} + } + i += 1; + } + None +} + +/// Decode an ASCII-only Rust v0 (`_R...`) or legacy (`_ZN...E`) mangled symbol into +/// its exact `(namespace, segment)` path and whether it is a generic instantiation. +/// Rejects RFC 2603 Punycode (`u`) Unicode-encoded segments so homoglyph modules can +/// never impersonate fixed ASCII boundaries like `platform::threading::join` or +/// `core::panicking::panic_cannot_unwind`. +fn decode_rust_symbol_path(sym: &str) -> Option<(Vec<(char, String)>, bool)> { + fn parse_v0_ascii_ident(s: &str) -> Option<(String, &str)> { + let mut r = s; + if let Some(after_s) = r.strip_prefix('s') { + let pos = after_s.find('_')?; + if !after_s[..pos].bytes().all(|b| b.is_ascii_alphanumeric()) { + return None; + } + r = &after_s[pos + 1..]; + } + // Reject Punycode-encoded Unicode identifiers (`u...`). + if r.starts_with('u') { + return None; + } + let len_end = r.find(|c: char| !c.is_ascii_digit()).unwrap_or(r.len()); + if len_end == 0 { + return None; + } + let len: usize = r[..len_end].parse().ok()?; + if len == 0 { + return None; + } + r = &r[len_end..]; + if let Some(after_us) = r.strip_prefix('_') { + r = after_us; + } + if r.len() < len { + return None; + } + let ident = &r[..len]; + if !ident.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') { + return None; + } + Some((ident.to_string(), &r[len..])) + } + + fn parse_v0_path(s: &str) -> Option<(Vec<(char, String)>, &str)> { + let mut chars = s.chars(); + match chars.next()? { + 'C' => { + let (crate_name, rest) = parse_v0_ascii_ident(chars.as_str())?; + Some((vec![('C', crate_name)], rest)) + } + 'N' => { + let ns = chars.next()?; + if !matches!(ns, 'v' | 't' | 'C' | 'c' | 's') { + return None; + } + let (mut segs, rest) = parse_v0_path(chars.as_str())?; + let (ident, rest2) = parse_v0_ascii_ident(rest)?; + segs.push((ns, ident)); + Some((segs, rest2)) + } + _ => None, + } + } + + if let Some(rest) = sym.strip_prefix("_R") { + if let Some(after_i) = rest.strip_prefix('I') { + let (segs, tail) = parse_v0_path(after_i)?; + if tail.is_empty() { + return None; + } + if tail.ends_with('E') { + return Some((segs, true)); + } + // Cross-crate generic instantiation: `_RIE`. + if let Some((gen_args, inst_crate)) = tail.rsplit_once('E') { + if !gen_args.is_empty() { + if let Some((c_segs, c_rem)) = parse_v0_path(inst_crate) { + if c_segs.len() == 1 && c_segs[0].0 == 'C' && c_rem.is_empty() { + return Some((segs, true)); + } + } + } + } + return None; + } + let (segs, tail) = parse_v0_path(rest)?; + if tail.is_empty() { + return Some((segs, false)); + } + return None; + } + + None +} + +fn is_panic_cannot_unwind_sym(sym: &str) -> bool { + match decode_rust_symbol_path(sym) { + Some((segs, false)) if segs.len() == 3 => { + segs[0].0 == 'C' + && segs[1].0 == 't' + && segs[2].0 == 'v' + && segs[0].1 == "core" + && segs[1].1 == "panicking" + && segs[2].1 == "panic_cannot_unwind" + } + _ => false, + } +} + +fn is_platform_threading_sym(sym: &str, expected_callee: &str) -> bool { + match decode_rust_symbol_path(sym) { + Some((segs, _)) if segs.len() == 3 => { + segs[0].0 == 'C' + && segs[1].0 == 't' + && segs[2].0 == 'v' + && segs[0].1 == "platform" + && segs[1].1 == "threading" + && segs[2].1 == expected_callee + } + _ => false, + } +} + +fn check_unwind_terminates( + wrapper: &str, + blocks: &BTreeMap>, + start: &str, +) { + fn dfs( + wrapper: &str, + blocks: &BTreeMap>, + label: &str, + seen_abort: bool, + active: &mut HashSet, + ) { + require(!active.contains(label), format!("{wrapper}: cycle in unwind handler at %{label}")); + let insts = blocks + .get(label) + .unwrap_or_else(|| fail(format!("{wrapper}: missing unwind target block %{label}"))); + active.insert(label.to_string()); + let mut aborted = seen_abort; + let mut terminated = false; + for inst in insts { + if inst.starts_with("resume ") || inst == "resume" { + fail(format!("{wrapper}: unwind path from invoke reaches resume at %{label}")); + } + if inst.starts_with("ret ") || inst == "ret" { + fail(format!("{wrapper}: unwind path from invoke returns normally at %{label}")); + } + if let Some(callee) = extract_llvm_direct_callee(inst) { + if is_panic_cannot_unwind_sym(callee) { + aborted = true; + } + } + if inst == "unreachable" { + require( + aborted, + format!("{wrapper}: unwind path reached unreachable without panic_cannot_unwind at %{label}"), + ); + terminated = true; + break; + } + if inst.starts_with("br ") { + let mut targets = Vec::new(); + let mut rest = inst.as_str(); + while let Some(pos) = rest.find("label %") { + let after = &rest[pos + "label %".len()..]; + let end = after + .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '.')) + .unwrap_or(after.len()); + if end > 0 { + targets.push(&after[..end]); + } + rest = &after[end..]; + } + require(!targets.is_empty(), format!("{wrapper}: malformed branch in %{label}: {inst}")); + for t in targets { + dfs(wrapper, blocks, t, aborted, active); + } + terminated = true; + break; + } + } + require(terminated, format!("{wrapper}: unwind block %{label} did not terminate in abort/unreachable")); + active.remove(label); + } + + let mut active = HashSet::new(); + dfs(wrapper, blocks, start, false, &mut active); +} + +fn cmd_check_ir(ir_file: &Path, specs: &[String]) { + let text = read_text(ir_file); + let mut defs: Vec<(String, String)> = Vec::new(); + let mut cur_hdr: Option = None; + let mut cur_body = String::new(); + for line in text.lines() { + if cur_hdr.is_none() { + if line.starts_with("define ") && line.ends_with('{') { + cur_hdr = Some(line.to_string()); + cur_body.clear(); + } + } else if line == "}" { + defs.push((cur_hdr.take().unwrap(), std::mem::take(&mut cur_body))); + } else { + cur_body.push_str(line); + cur_body.push('\n'); + } + } + for spec in specs { + let (wrapper, expected_callee) = spec + .split_once(':') + .unwrap_or_else(|| fail(format!("check-ir expects wrapper:callee, got {spec}"))); + let matched: Vec<&(String, String)> = defs + .iter() + .filter(|(h, _)| { + extract_llvm_defined_symbol(h).is_some_and(|sym| { + sym == wrapper + || decode_rust_symbol_path(sym) + .is_some_and(|(segs, _)| segs.last().map(|(_, n)| n.as_str()) == Some(wrapper)) + }) + }) + .collect(); + require( + matched.len() == 1, + format!("expected 1 LLVM IR definition for {wrapper}, found {}", matched.len()), + ); + let blocks = parse_llvm_blocks(&matched[0].1); + let mut saw_platform_invoke = false; + let mut invoke_count = 0usize; + for insts in blocks.values() { + for inst in insts { + if inst.starts_with("invoke ") || inst.contains(" = invoke ") { + invoke_count += 1; + let unw_pos = inst + .find("unwind label %") + .unwrap_or_else(|| fail(format!("{wrapper}: invoke missing unwind label: {inst}"))); + let after_unw = &inst[unw_pos + "unwind label %".len()..]; + let end = after_unw + .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '.')) + .unwrap_or(after_unw.len()); + let unw_label = &after_unw[..end]; + require(!unw_label.is_empty(), format!("{wrapper}: empty unwind label: {inst}")); + check_unwind_terminates(wrapper, &blocks, unw_label); + if let Some(callee_sym) = extract_llvm_direct_callee(inst) { + if is_platform_threading_sym(callee_sym, expected_callee) { + saw_platform_invoke = true; + } + } + } + } + } + require( + invoke_count > 0 && saw_platform_invoke, + format!("{wrapper}: did not find platform {expected_callee} invoke with verified abort unwind"), + ); + } +} + +fn byte_offset_to_line_col(src: &str, offset: usize) -> (usize, usize) { + let prefix = &src[..offset]; + let line = prefix.bytes().filter(|&b| b == b'\n').count() + 1; + let col = match prefix.rfind('\n') { + Some(nl) => offset - nl, + None => offset + 1, + }; + (line, col) +} + +fn extract_delimited_body(src: &str, toks: &[LexTok], open_idx: usize) -> String { + require( + open_idx < toks.len() && toks[open_idx].kind == TokKind::Punct('{'), + "expected '{' to start body", + ); + let body_start = toks[open_idx].end; + let mut depth = 1usize; + let mut i = open_idx + 1; + while i < toks.len() && depth > 0 { + match toks[i].kind { + TokKind::Punct('{') => depth += 1, + TokKind::Punct('}') => depth -= 1, + _ => {} + } + i += 1; + } + require(depth == 0, "unclosed '{' body"); + src[body_start..toks[i - 1].start].to_string() +} + +fn check_straight_line_tokens(label: &str, body: &str, body_toks: &[LexTok], allowed_macros: &[&str]) { + for (idx, tok) in body_toks.iter().enumerate() { + if let Some(id) = tok.ident_name(body) { + if matches!( + id, + "if" | "else" + | "match" + | "loop" + | "while" + | "for" + | "return" + | "break" + | "continue" + | "fn" + | "async" + | "await" + ) { + fail(format!( + "{label}: control-flow keyword `{id}` is forbidden in straight-line post-call harness" + )); + } + } + if tok.kind == TokKind::Punct('?') || tok.kind == TokKind::Punct('|') { + fail(format!( + "{label}: operator `{}` is forbidden in straight-line post-call harness", + tok.text(body) + )); + } + if tok.kind == TokKind::Punct('&') + && idx + 1 < body_toks.len() + && body_toks[idx + 1].kind == TokKind::Punct('&') + && tok.end == body_toks[idx + 1].start + { + fail(format!("{label}: short-circuit `&&` is forbidden in straight-line post-call harness")); + } + // Reject ANY unapproved macro invocation (`foo!(...)` or `$m!(...)`) so helper macros + // cannot hide branching, early returns, or conditional execution. + if tok.kind == TokKind::Punct('!') + && idx + 1 < body_toks.len() + && matches!(body_toks[idx + 1].kind, TokKind::Punct('(' | '[' | '{')) + { + let mname = if idx >= 1 { + if let Some(id) = body_toks[idx - 1].ident_name(body) { + if idx >= 2 && body_toks[idx - 2].kind == TokKind::Punct('$') { + format!("${id}") + } else { + id.to_string() + } + } else { + String::from("") + } + } else { + String::from("") + }; + require( + allowed_macros.contains(&mname.as_str()), + format!( + "{label}: unapproved macro invocation `{mname}!` is forbidden in straight-line post-call harness" + ), + ); + } + } +} + +/// Split a straight-line Rust function body into top-level statements (at delimiter depth 0). +fn split_top_level_stmts(body: &str, toks: &[LexTok]) -> Vec { + let mut stmts = Vec::new(); + let mut brace = 0usize; + let mut paren = 0usize; + let mut bracket = 0usize; + let mut stmt_start: Option = None; + + for (i, tok) in toks.iter().enumerate() { + if matches!(tok.kind, TokKind::GhostLine | TokKind::GhostBlock) { + continue; + } + if stmt_start.is_none() { + stmt_start = Some(tok.start); + } + match tok.kind { + TokKind::Punct('{') => brace += 1, + TokKind::Punct('}') => { + brace = brace.saturating_sub(1); + if brace == 0 && paren == 0 && bracket == 0 { + // A top-level `{ ... }` block (e.g. `#[cfg(...)] { ... }`) terminates a statement + // unless immediately followed by `;` (e.g. `let _ = unsafe { ... };`). + let next_semi = toks + .get(i + 1) + .is_some_and(|t| t.kind == TokKind::Punct(';')); + if !next_semi { + if let Some(s) = stmt_start.take() { + let st = strip_ghost(&body[s..tok.end]); + if !st.is_empty() { + stmts.push(st); + } + } + } + } + } + TokKind::Punct('(') => paren += 1, + TokKind::Punct(')') => paren = paren.saturating_sub(1), + TokKind::Punct('[') => bracket += 1, + TokKind::Punct(']') => bracket = bracket.saturating_sub(1), + TokKind::Punct(';') if brace == 0 && paren == 0 && bracket == 0 => { + if let Some(s) = stmt_start.take() { + let st = strip_ghost(&body[s..tok.end]); + if !st.is_empty() { + stmts.push(st); + } + } + } + _ => {} + } + } + if let Some(s) = stmt_start { + let st = strip_ghost(&body[s..]); + if !st.is_empty() { + stmts.push(st); + } + } + stmts +} + +fn verify_post_call_cover_in_source( + src: &str, + toks: &[LexTok], + kind: &str, + name: &str, + fn_selector: &str, + call_needle: &str, + desc: &str, + allowed_macros: &[&str], +) { + let mut fn_bodies = Vec::new(); + let mut i = 0; + while i + 2 < toks.len() { + if kind == "macro" + && toks[i].kind == TokKind::Ident + && toks[i].text(src) == "macro_rules" + && toks[i + 1].kind == TokKind::Punct('!') + && toks[i + 2].kind == TokKind::Ident + && toks[i + 2].text(src) == name + { + let mut j = i + 3; + while j < toks.len() && toks[j].kind != TokKind::Punct('{') { + j += 1; + } + let macro_body = extract_delimited_body(src, toks, j); + let mtoks = lex_rust(¯o_body); + let mut k = 0; + while k + 1 < mtoks.len() { + if mtoks[k].kind == TokKind::Ident && mtoks[k].text(¯o_body) == "fn" { + let matched_fn = if let Some(var) = fn_selector.strip_prefix('$') { + k + 2 < mtoks.len() + && mtoks[k + 1].kind == TokKind::Punct('$') + && mtoks[k + 2].ident_name(¯o_body) == Some(var) + } else { + mtoks[k + 1].ident_name(¯o_body) == Some(fn_selector) + }; + if matched_fn { + let mut b = k + 2; + while b < mtoks.len() && mtoks[b].kind != TokKind::Punct('{') { + b += 1; + } + fn_bodies.push(extract_delimited_body(¯o_body, &mtoks, b)); + k = b + 1; + continue; + } + } + k += 1; + } + i = j + 1; + continue; + } + if kind == "fn" + && toks[i].kind == TokKind::Ident + && toks[i].text(src) == "fn" + && toks[i + 1].ident_name(src) == Some(name) + { + let mut j = i + 2; + while j < toks.len() && toks[j].kind != TokKind::Punct('{') { + j += 1; + } + fn_bodies.push(extract_delimited_body(src, toks, j)); + i = j + 1; + continue; + } + i += 1; + } + require( + fn_bodies.len() == 1, + format!( + "expected 1 {kind} harness body for {name} ({fn_selector}), found {}", + fn_bodies.len() + ), + ); + let body = &fn_bodies[0]; + let body_toks = lex_rust(body); + let label = format!("{kind} {name}"); + check_straight_line_tokens(&label, body, &body_toks, allowed_macros); + if allowed_macros.is_empty() { + require( + !body_toks.iter().any(|t| t.kind == TokKind::Punct('#')), + format!("{label}: attributes/cfg are forbidden inside straight-line atomic.rs harness body"), + ); + } + + let stmts = split_top_level_stmts(body, &body_toks); + require( + stmts.len() >= 2, + format!("{label}: expected at least call + post-call cover statements, found {}", stmts.len()), + ); + let expected_cover = format!("kani::cover(true, \"{desc}\");"); + require( + stmts.last().map(String::as_str) == Some(expected_cover.as_str()), + format!( + "{label}: final unconditional statement must be `{expected_cover}`, found `{}`", + stmts.last().map(String::as_str).unwrap_or("") + ), + ); + for earlier in &stmts[..stmts.len() - 1] { + require( + !earlier.contains("kani::cover"), + format!("{label}: unexpected earlier kani::cover before final statement: {earlier}"), + ); + } + let prev_stmt = &stmts[stmts.len() - 2]; + require( + prev_stmt.contains(call_needle), + format!( + "{label}: statement immediately preceding `{expected_cover}` must invoke `{call_needle}`, found `{prev_stmt}`" + ), + ); +} + +fn normalize_rust_tokens(src: &str) -> Vec { + lex_rust(src) + .into_iter() + .filter(|t| !matches!(t.kind, TokKind::GhostLine | TokKind::GhostBlock)) + .map(|t| t.text(src).to_string()) + .collect() +} + +fn extract_unique_macro_body(src: &str, toks: &[LexTok], macro_name: &str) -> String { + let mut hits = Vec::new(); + let mut i = 0; + while i + 2 < toks.len() { + if toks[i].kind == TokKind::Ident + && toks[i].text(src) == "macro_rules" + && toks[i + 1].kind == TokKind::Punct('!') + && toks[i + 2].kind == TokKind::Ident + && toks[i + 2].text(src) == macro_name + { + let mut j = i + 3; + while j < toks.len() && toks[j].kind != TokKind::Punct('{') { + j += 1; + } + hits.push(extract_delimited_body(src, toks, j)); + i = j + 1; + continue; + } + i += 1; + } + require(hits.len() == 1, format!("expected 1 helper macro {macro_name}, found {}", hits.len())); + hits.pop().unwrap() +} + +fn extract_macro_single_arm_rhs(macro_name: &str, macro_body: &str) -> String { + let toks = lex_rust(macro_body); + let mut rhs_bodies = Vec::new(); + let mut i = 0; + while i + 2 < toks.len() { + if toks[i].kind == TokKind::Punct('=') && toks[i + 1].kind == TokKind::Punct('>') { + let mut j = i + 2; + while j < toks.len() && matches!(toks[j].kind, TokKind::GhostLine | TokKind::GhostBlock) { + j += 1; + } + require( + j < toks.len() && toks[j].kind == TokKind::Punct('{'), + format!("macro {macro_name}: expected '{{' after '=>'"), + ); + rhs_bodies.push(extract_delimited_body(macro_body, &toks, j)); + i = j + 1; + continue; + } + i += 1; + } + require( + rhs_bodies.len() == 1, + format!("macro {macro_name}: expected exactly 1 rule arm, found {}", rhs_bodies.len()), + ); + rhs_bodies.pop().unwrap() +} + +fn verify_atomic_width_matrix_macro( + src: &str, + toks: &[LexTok], + macro_name: &str, + cfg_key: &str, + expected_int_types: &BTreeSet, +) { + let macro_body = extract_unique_macro_body(src, toks, macro_name); + let btoks = lex_rust(¯o_body); + check_straight_line_tokens(&format!("macro {macro_name}"), ¯o_body, &btoks, &["$call"]); + + let rhs = extract_macro_single_arm_rhs(macro_name, ¯o_body); + let rtoks = lex_rust(&rhs); + let stmts = split_top_level_stmts(&rhs, &rtoks); + let canonical = [ + ("8", "i8", "u8"), + ("16", "i16", "u16"), + ("32", "i32", "u32"), + ("64", "i64", "u64"), + ("128", "i128", "u128"), + ("ptr", "isize", "usize"), + ]; + require( + stmts.len() == canonical.len(), + format!("macro {macro_name}: expected {} width arms, found {}", canonical.len(), stmts.len()), + ); + + let mut seen_widths: BTreeSet = BTreeSet::new(); + let mut covered_types: BTreeSet = BTreeSet::new(); + for (idx, (width, signed_ty, unsigned_ty)) in canonical.iter().enumerate() { + let want_stmt = format!( + "#[cfg({cfg_key} = \"{width}\")] {{ $call!({signed_ty}, $($args)*); $call!({unsigned_ty}, $($args)*); }}" + ); + let got_toks = normalize_rust_tokens(&stmts[idx]); + let want_toks = normalize_rust_tokens(&want_stmt); + require( + got_toks == want_toks, + format!( + "macro {macro_name} arm {idx}: expected `{want_stmt}`, found `{}`", + stmts[idx] + ), + ); + require(seen_widths.insert((*width).to_string()), format!("macro {macro_name}: duplicate width {width}")); + covered_types.insert((*signed_ty).to_string()); + covered_types.insert((*unsigned_ty).to_string()); + } + for ty in expected_int_types { + require( + covered_types.contains(ty), + format!("macro {macro_name}: missing expected target integer type {ty}"), + ); + } +} + +fn verify_intrinsic_call_macro(src: &str, toks: &[LexTok], macro_name: &str, call_needle: &str) { + let macro_body = extract_unique_macro_body(src, toks, macro_name); + let btoks = lex_rust(¯o_body); + check_straight_line_tokens(&format!("macro {macro_name}"), ¯o_body, &btoks, &[]); + require( + !btoks.iter().any(|t| t.kind == TokKind::Punct('#')), + format!("macro {macro_name}: attributes/cfg are forbidden inside call helper"), + ); + let rhs = extract_macro_single_arm_rhs(macro_name, ¯o_body); + require( + normalize_rust_tokens(&rhs) + .windows(normalize_rust_tokens(call_needle).len()) + .any(|w| w == normalize_rust_tokens(call_needle).as_slice()), + format!("macro {macro_name}: missing expected call `{call_needle}`"), + ); +} + +fn verify_intrinsic_harness_macro( + src: &str, + toks: &[LexTok], + macro_name: &str, + matrix_macro: &str, + expected_matrix_stmt: &str, + ptr_cfg_key: &str, + expected_ptr_call: &str, + cover_desc: &str, +) { + let macro_body = extract_unique_macro_body(src, toks, macro_name); + let mtoks = lex_rust(¯o_body); + let mut fn_bodies = Vec::new(); + let mut k = 0; + while k + 2 < mtoks.len() { + if mtoks[k].kind == TokKind::Ident + && mtoks[k].text(¯o_body) == "fn" + && mtoks[k + 1].kind == TokKind::Punct('$') + && mtoks[k + 2].ident_name(¯o_body) == Some("name") + { + let mut b = k + 3; + while b < mtoks.len() && mtoks[b].kind != TokKind::Punct('{') { + b += 1; + } + fn_bodies.push(extract_delimited_body(¯o_body, &mtoks, b)); + k = b + 1; + continue; + } + k += 1; + } + require( + fn_bodies.len() == 1, + format!("macro {macro_name}: expected 1 fn $name body, found {}", fn_bodies.len()), + ); + let body = &fn_bodies[0]; + let btoks = lex_rust(body); + let label = format!("macro {macro_name}"); + check_straight_line_tokens(&label, body, &btoks, &[matrix_macro]); + let stmts = split_top_level_stmts(body, &btoks); + require( + stmts.len() == 3, + format!("{label}: expected exactly 3 statements (integer matrix + ptr block + cover), found {}", stmts.len()), + ); + require( + normalize_rust_tokens(&stmts[0]) == normalize_rust_tokens(expected_matrix_stmt), + format!("{label}: statement 0 must be `{expected_matrix_stmt}`, found `{}`", stmts[0]), + ); + + // Statement 1 must be `#[cfg( = "ptr")] { ... }` with no inner `#` and exact pointer wrapper call. + let ptoks = lex_rust(&stmts[1]); + let brace_idx = ptoks + .iter() + .position(|t| t.kind == TokKind::Punct('{')) + .unwrap_or_else(|| fail(format!("{label}: statement 1 missing ptr block '{{': {}", stmts[1]))); + let prefix_toks: Vec = ptoks[..brace_idx] + .iter() + .filter(|t| !matches!(t.kind, TokKind::GhostLine | TokKind::GhostBlock)) + .map(|t| t.text(&stmts[1]).to_string()) + .collect(); + let want_prefix = normalize_rust_tokens(&format!("#[cfg({ptr_cfg_key} = \"ptr\")]")); + require( + prefix_toks == want_prefix, + format!("{label}: statement 1 must start with `#[cfg({ptr_cfg_key} = \"ptr\")]`, found `{}`", stmts[1]), + ); + let ptr_body = extract_delimited_body(&stmts[1], &ptoks, brace_idx); + let ptr_body_toks = lex_rust(&ptr_body); + check_straight_line_tokens(&format!("{label} ptr block"), &ptr_body, &ptr_body_toks, &[]); + require( + !ptr_body_toks.iter().any(|t| t.kind == TokKind::Punct('#')), + format!("{label}: nested attributes/cfg are forbidden inside ptr block"), + ); + let ptr_norm = normalize_rust_tokens(&ptr_body); + let call_norm = normalize_rust_tokens(expected_ptr_call); + require( + ptr_norm.windows(call_norm.len()).any(|w| w == call_norm.as_slice()), + format!("{label}: ptr block missing expected call `{expected_ptr_call}`"), + ); + + let expected_cover = format!("kani::cover(true, \"{cover_desc}\");"); + require( + normalize_rust_tokens(&stmts[2]) == normalize_rust_tokens(&expected_cover), + format!("{label}: final unconditional statement must be `{expected_cover}`, found `{}`", stmts[2]), + ); +} + +fn kani_ordering_path(slug: &str) -> &'static str { + match slug { + "relaxed" => "AtomicOrdering::Relaxed", + "acquire" => "AtomicOrdering::Acquire", + "release" => "AtomicOrdering::Release", + "acqrel" => "AtomicOrdering::AcqRel", + "seqcst" => "AtomicOrdering::SeqCst", + _ => fail(format!("unknown Kani AtomicOrdering slug: {slug}")), + } +} + +fn find_macro_call_loc(src: &str, toks: &[LexTok], macro_name: &str, arg_prefixes: &[&str]) -> (usize, usize) { + let mut hits = Vec::new(); + let mut i = 0; + while i + 2 < toks.len() { + if toks[i].kind == TokKind::Ident + && toks[i].text(src) == macro_name + && toks[i + 1].kind == TokKind::Punct('!') + && toks[i + 2].kind == TokKind::Punct('(') + { + // Collect top-level comma-separated argument slices inside `(...)`. + let mut j = i + 3; + let mut depth = 1usize; + let mut arg_start = if j < toks.len() { toks[j].start } else { toks[i + 2].end }; + let mut args: Vec = Vec::new(); + while j < toks.len() && depth > 0 { + match toks[j].kind { + TokKind::Punct('(' | '[' | '{') => depth += 1, + TokKind::Punct(')' | ']' | '}') => { + depth -= 1; + if depth == 0 { + let s = strip_ghost(&src[arg_start..toks[j].start]); + if !s.is_empty() { + args.push(s); + } + } + } + TokKind::Punct(',') if depth == 1 => { + args.push(strip_ghost(&src[arg_start..toks[j].start])); + if j + 1 < toks.len() { + arg_start = toks[j + 1].start; + } + } + _ => {} + } + j += 1; + } + if args.len() >= arg_prefixes.len() + && arg_prefixes + .iter() + .enumerate() + .all(|(k, want)| args[k] == *want) + { + hits.push(byte_offset_to_line_col(src, toks[i].start)); + } + i = j; + continue; + } + i += 1; + } + require( + hits.len() == 1, + format!("expected 1 invocation of {macro_name}!({:?}), found {}", arg_prefixes, hits.len()), + ); + hits[0] +} + +fn find_direct_fn_cover_loc(src: &str, toks: &[LexTok], fn_name: &str, desc: &str) -> (usize, usize) { + let mut hits = Vec::new(); + let mut i = 0; + while i + 1 < toks.len() { + if toks[i].kind == TokKind::Ident + && toks[i].text(src) == "fn" + && toks[i + 1].kind == TokKind::Ident + && toks[i + 1].text(src) == fn_name + { + let mut j = i + 2; + while j < toks.len() && toks[j].kind != TokKind::Punct('{') { + j += 1; + } + let mut depth = 1usize; + j += 1; + let want_lit = format!("\"{desc}\""); + while j < toks.len() && depth > 0 { + match toks[j].kind { + TokKind::Punct('{') => depth += 1, + TokKind::Punct('}') => depth -= 1, + TokKind::Ident + if toks[j].text(src) == "kani" + && j + 7 < toks.len() + && toks[j + 1].kind == TokKind::Punct(':') + && toks[j + 2].kind == TokKind::Punct(':') + && toks[j + 3].kind == TokKind::Ident + && toks[j + 3].text(src) == "cover" + && toks[j + 4].kind == TokKind::Punct('(') + && toks[j + 5].kind == TokKind::Ident + && toks[j + 5].text(src) == "true" + && toks[j + 6].kind == TokKind::Punct(',') + && toks[j + 7].kind == TokKind::Literal + && toks[j + 7].text(src) == want_lit => + { + hits.push(byte_offset_to_line_col(src, toks[j].start)); + } + _ => {} + } + j += 1; + } + i = j; + continue; + } + i += 1; + } + require( + hits.len() == 1, + format!("expected 1 kani::cover(true, \"{desc}\") in fn {fn_name}, found {}", hits.len()), + ); + hits[0] +} + +fn expected_kani_cover( + harness: &str, + atomic_src: &str, + atomic_toks: &[LexTok], + intr_src: &str, + intr_toks: &[LexTok], +) -> (&'static str, &'static str, usize, usize) { + if let Some(short) = harness.strip_prefix("sync::atomic::verify::") { + if short == "harness_atomic_isize_from_ptr" || short == "harness_atomic_usize_from_ptr" { + let (line, col) = find_macro_call_loc(atomic_src, atomic_toks, "from_ptr_harness", &[short]); + return ("integer from_ptr: reached after call", "library/core/src/sync/atomic.rs", line, col); + } + if short == "harness_atomic_load_ptr_u8" { + let (line, col) = + find_direct_fn_cover_loc(atomic_src, atomic_toks, short, "atomic_load: reached after call"); + return ("atomic_load: reached after call", "library/core/src/sync/atomic.rs", line, col); + } + if short.starts_with("harness_atomic_load_") { + let (line, col) = find_macro_call_loc(atomic_src, atomic_toks, "load_harness", &[short]); + return ("atomic_load: reached after call", "library/core/src/sync/atomic.rs", line, col); + } + if let Some(method) = short.strip_prefix("rmw_bool::") { + let (line, col) = find_macro_call_loc(atomic_src, atomic_toks, "rmw_contract", &["bool", method]); + return ("atomic operation returned", "library/core/src/sync/atomic.rs", line, col); + } + if let Some(method) = short.strip_prefix("rmw_ptr::") { + let (line, col) = find_macro_call_loc(atomic_src, atomic_toks, "rmw_contract", &["*mut T", method]); + return ("atomic operation returned", "library/core/src/sync/atomic.rs", line, col); + } + if let Some((module, _method)) = short.split_once("::") { + if module.starts_with("rmw_") { + let (line, col) = + find_macro_call_loc(atomic_src, atomic_toks, "integer_rmw_contracts", &[module]); + return ("atomic operation returned", "library/core/src/sync/atomic.rs", line, col); + } + } + if short == "harness_safe_load_ptr" { + let (line, col) = find_direct_fn_cover_loc( + atomic_src, + atomic_toks, + short, + "safe atomic pointer load: reached after call", + ); + return ("safe atomic pointer load: reached after call", "library/core/src/sync/atomic.rs", line, col); + } + if short.starts_with("harness_safe_load_") { + let (line, col) = find_macro_call_loc(atomic_src, atomic_toks, "safe_load_store_harness", &[short]); + return ("safe atomic load: reached after call", "library/core/src/sync/atomic.rs", line, col); + } + if short == "harness_safe_compare_exchange_bool" { + let (line, col) = + find_macro_call_loc(atomic_src, atomic_toks, "safe_compare_exchange_harness", &[short]); + return ("safe atomic compare-exchange: reached after call", "library/core/src/sync/atomic.rs", line, col); + } + } else if let Some(short) = harness.strip_prefix("intrinsics::verify::") { + if let Some(ord) = short.strip_prefix("harness_intrinsic_atomic_store_") { + let ord_path = kani_ordering_path(ord); + let (line, col) = find_macro_call_loc(intr_src, intr_toks, "atomic_store_harness", &[short, ord_path]); + return ("atomic intrinsic store: reached after call", "library/core/src/intrinsics/mod.rs", line, col); + } + if let Some(ord) = short.strip_prefix("harness_intrinsic_atomic_load_") { + let ord_path = kani_ordering_path(ord); + let (line, col) = find_macro_call_loc(intr_src, intr_toks, "atomic_load_harness", &[short, ord_path]); + return ("atomic intrinsic load: reached after call", "library/core/src/intrinsics/mod.rs", line, col); + } + if let Some(rest) = short.strip_prefix("harness_intrinsic_atomic_cxchgweak_") { + let (succ, fail_ord) = rest + .split_once('_') + .unwrap_or_else(|| fail(format!("bad cxchgweak harness name: {short}"))); + let (line, col) = find_macro_call_loc( + intr_src, + intr_toks, + "atomic_cxchg_harness", + &[short, "atomic_cxchgweak_wrapper", kani_ordering_path(succ), kani_ordering_path(fail_ord)], + ); + return ("atomic intrinsic compare-exchange: reached after call", "library/core/src/intrinsics/mod.rs", line, col); + } + if let Some(rest) = short.strip_prefix("harness_intrinsic_atomic_cxchg_") { + let (succ, fail_ord) = rest + .split_once('_') + .unwrap_or_else(|| fail(format!("bad cxchg harness name: {short}"))); + let (line, col) = find_macro_call_loc( + intr_src, + intr_toks, + "atomic_cxchg_harness", + &[short, "atomic_cxchg_wrapper", kani_ordering_path(succ), kani_ordering_path(fail_ord)], + ); + return ("atomic intrinsic compare-exchange: reached after call", "library/core/src/intrinsics/mod.rs", line, col); + } + } + fail(format!("unexpected Kani harness without post-call cover specification: {harness}")); +} + +fn cmd_check_kani_log(log_path: &Path, expected_path: &Path, atomic_rs: &Path, intrinsics_rs: &Path) { + let atomic_src = read_text(atomic_rs); + let intr_src = read_text(intrinsics_rs); + let atomic_toks = lex_rust(&atomic_src); + let intr_toks = lex_rust(&intr_src); + + let expected_set: BTreeSet = read_text(expected_path) + .lines() + .map(str::trim) + .filter(|l| !l.is_empty()) + .map(String::from) + .collect(); + require(!expected_set.is_empty(), format!("empty expected harness list {}", expected_path.display())); + + let expected_int_types: BTreeSet = expected_set + .iter() + .filter_map(|h| h.strip_prefix("sync::atomic::verify::harness_atomic_load_")) + .filter(|t| *t != "ptr_u8") + .map(String::from) + .collect(); + + // Verify every harness macro and direct function is straight-line (zero branching/early return/unapproved macros) + // with the atomic call unconditionally preceding the final kani::cover statement. + verify_post_call_cover_in_source(&atomic_src, &atomic_toks, "macro", "from_ptr_harness", "$name", "from_ptr(ptr)", "integer from_ptr: reached after call", &[]); + verify_post_call_cover_in_source(&atomic_src, &atomic_toks, "macro", "load_harness", "$name", "atomic_load::<", "atomic_load: reached after call", &[]); + verify_post_call_cover_in_source(&atomic_src, &atomic_toks, "fn", "harness_atomic_load_ptr_u8", "harness_atomic_load_ptr_u8", "atomic_load::<*mut u8", "atomic_load: reached after call", &[]); + verify_post_call_cover_in_source(&atomic_src, &atomic_toks, "macro", "rmw_contract", "$method", "cell.$method(", "atomic operation returned", &[]); + verify_post_call_cover_in_source(&atomic_src, &atomic_toks, "macro", "safe_load_store_harness", "$load_name", "storage.load(", "safe atomic load: reached after call", &[]); + verify_post_call_cover_in_source(&atomic_src, &atomic_toks, "fn", "harness_safe_load_ptr", "harness_safe_load_ptr", "storage.load(", "safe atomic pointer load: reached after call", &[]); + verify_post_call_cover_in_source(&atomic_src, &atomic_toks, "macro", "safe_compare_exchange_harness", "$name", "storage.$method(", "safe atomic compare-exchange: reached after call", &[]); + + // Verify intrinsic width matrices, call helpers, and exact 3-statement harness macros so no enabled width, + // pointer call, wrapper, or ordering can be silently omitted while still hitting the trailing cover. + verify_atomic_width_matrix_macro( + &intr_src, + &intr_toks, + "atomic_integer_load_store_types", + "target_has_atomic_load_store", + &expected_int_types, + ); + verify_atomic_width_matrix_macro( + &intr_src, + &intr_toks, + "atomic_integer_types", + "target_has_atomic", + &expected_int_types, + ); + verify_intrinsic_call_macro( + &intr_src, + &intr_toks, + "atomic_store_call", + "atomic_store_wrapper::<$ty, { $ord }>(&mut dst, val)", + ); + verify_intrinsic_call_macro( + &intr_src, + &intr_toks, + "atomic_load_call", + "atomic_load_wrapper::<$ty, { $ord }>(&src)", + ); + verify_intrinsic_call_macro( + &intr_src, + &intr_toks, + "atomic_cxchg_call", + "$wrapper::<$ty, { $succ }, { $fail }>(&mut dst, old, new)", + ); + verify_intrinsic_harness_macro( + &intr_src, + &intr_toks, + "atomic_store_harness", + "atomic_integer_load_store_types", + "atomic_integer_load_store_types!(atomic_store_call, $ord);", + "target_has_atomic_load_store", + "atomic_store_wrapper::<*mut u8, { $ord }>(&mut dst, val)", + "atomic intrinsic store: reached after call", + ); + verify_intrinsic_harness_macro( + &intr_src, + &intr_toks, + "atomic_load_harness", + "atomic_integer_load_store_types", + "atomic_integer_load_store_types!(atomic_load_call, $ord);", + "target_has_atomic_load_store", + "atomic_load_wrapper::<*mut u8, { $ord }>(&src)", + "atomic intrinsic load: reached after call", + ); + verify_intrinsic_harness_macro( + &intr_src, + &intr_toks, + "atomic_cxchg_harness", + "atomic_integer_types", + "atomic_integer_types!(atomic_cxchg_call, $wrapper, $succ, $fail);", + "target_has_atomic", + "$wrapper::<*mut u8, { $succ }, { $fail }>(&mut dst, old, new)", + "atomic intrinsic compare-exchange: reached after call", + ); + + // Precompute exact expected (desc, file, line, col) for every non-panicking harness. + let mut specs: HashMap = HashMap::new(); + for h in &expected_set { + if !h.contains("_panics_on_") { + specs.insert( + h.clone(), + expected_kani_cover(h, &atomic_src, &atomic_toks, &intr_src, &intr_toks), + ); + } + } + + let log = read_text(log_path); + let mut actual_set: BTreeSet = BTreeSet::new(); + let mut cur_harness: Option = None; + let mut cur_ok = false; + let mut cur_cov_ok = false; + + let mut in_cov = false; + let mut st_ok = false; + let mut desc_ok = false; + let mut loc_ok = false; + + let flush_check = |in_cov: &mut bool, st_ok: &mut bool, desc_ok: &mut bool, loc_ok: &mut bool, cur_cov_ok: &mut bool| { + if *in_cov && *st_ok && *desc_ok && *loc_ok { + *cur_cov_ok = true; + } + *in_cov = false; + *st_ok = false; + *desc_ok = false; + *loc_ok = false; + }; + + let flush_harness = |cur_harness: &mut Option, + cur_ok: &mut bool, + cur_cov_ok: &mut bool, + actual_set: &mut BTreeSet| { + if let Some(h) = cur_harness.take() { + require(*cur_ok, format!("Kani harness failed: {h}")); + if !h.contains("_panics_on_") { + require(*cur_cov_ok, format!("MISSING POST-CALL COVER {h}")); + } + require(actual_set.insert(h.clone()), format!("duplicate Kani harness in log: {h}")); + *cur_ok = false; + *cur_cov_ok = false; + } + }; + + for raw in log.lines() { + let line = raw.trim_end_matches('\r'); + if let Some(rest) = line.strip_prefix("Checking harness ").and_then(|s| s.strip_suffix("...")) { + flush_check(&mut in_cov, &mut st_ok, &mut desc_ok, &mut loc_ok, &mut cur_cov_ok); + flush_harness(&mut cur_harness, &mut cur_ok, &mut cur_cov_ok, &mut actual_set); + cur_harness = Some(rest.to_string()); + continue; + } + if let Some(rest) = line.strip_prefix("Check ") { + flush_check(&mut in_cov, &mut st_ok, &mut desc_ok, &mut loc_ok, &mut cur_cov_ok); + if let Some((num, check_id)) = rest.split_once(": ") { + if is_digits(num) { + if let Some(h) = cur_harness.as_deref() { + if let Some(cov_idx) = check_id.strip_prefix(&format!("{h}.cover.")) { + if is_digits(cov_idx) { + in_cov = true; + } + } + } + } + } + continue; + } + if in_cov { + let trimmed = line.trim(); + if trimmed == "- Status: SATISFIED" { + st_ok = true; + continue; + } + if let Some(h) = cur_harness.as_deref() { + if let Some(&(exp_desc, exp_file, exp_line, exp_col)) = specs.get(h) { + if trimmed == format!("- Description: \"{exp_desc}\"") { + desc_ok = true; + continue; + } + if let Some(loc_rest) = trimmed.strip_prefix("- Location: ") { + if let Some((span, fn_name)) = loc_rest.split_once(" in function ") { + let parts: Vec<&str> = span.split(':').collect(); + if parts.len() == 3 + && parts[0] == exp_file + && parts[1].parse::().ok() == Some(exp_line) + && parts[2].parse::().ok() == Some(exp_col) + && fn_name == h + { + loc_ok = true; + } + } + continue; + } + } + } + } + if line.contains("VERIFICATION:- SUCCESSFUL") { + cur_ok = true; + } + } + flush_check(&mut in_cov, &mut st_ok, &mut desc_ok, &mut loc_ok, &mut cur_cov_ok); + flush_harness(&mut cur_harness, &mut cur_ok, &mut cur_cov_ok, &mut actual_set); + + if actual_set != expected_set { + let missing: Vec<&String> = expected_set.difference(&actual_set).collect(); + let extra: Vec<&String> = actual_set.difference(&expected_set).collect(); + fail(format!( + "Kani harness set mismatch (missing {:?}, extra {:?})", + missing, extra + )); + } + println!( + "PASS Kani log ({} harnesses, {} post-call covers verified)", + actual_set.len(), + specs.len() + ); +} + +fn cmd_replace(file: &Path) { + let old = env::var("CH7_OLD").unwrap_or_else(|_| fail("missing CH7_OLD env")); + let new = env::var("CH7_NEW").unwrap_or_else(|_| fail("missing CH7_NEW env")); + let text = read_text(file); + let count = text.matches(&old).count(); + require(count == 1, format!("expected 1 occurrence of {:?} in {}, found {count}", old, file.display())); + fs::write(file, text.replacen(&old, &new, 1)).unwrap_or_else(|e| fail(format!("write {}: {e}", file.display()))); +} + +fn cmd_edge_check(scope_file: &Path, caller: &str, callee: &str, order_filter: &str, expected: usize) { + let calls = parse_edges(&read_text(scope_file)); + let list = calls.get(&(caller.to_string(), callee.to_string())); + let count = if order_filter == "-" { + list.map_or(0, Vec::len) + } else { + let want: Vec = order_filter.split('/').map(String::from).collect(); + list.into_iter() + .flatten() + .filter(|e| extract_atomic_orderings(e) == want) + .count() + }; + require( + count == expected, + format!("edge count mismatch for {caller} -> {callee} ({order_filter}): got {count}, expected {expected}"), + ); +} + +fn cmd_check_line_diag(log_file: &Path, path_prefix: &str, line_num: usize, kind: &str) { + let text = read_text(log_file); + let needle = format!("{path_prefix}({line_num},"); + let matched = text.lines().any(|l| { + if let Some(after) = l.find(&needle).map(|i| &l[i + needle.len()..]) { + if let Some((_, rest)) = after.split_once("): ") { + return match kind { + "error" => rest.starts_with("error: Assertion"), + "any" => rest.starts_with("error:") || rest.starts_with("note:"), + _ => false, + }; + } + } + false + }); + require(matched, format!("missing diagnostic at {path_prefix}({line_num},...) ({kind})")); +} + +fn main() { + let args: Vec = env::args().collect(); + if args.len() < 2 { + fail("usage: check_mir ..."); + } + match args[1].as_str() { + "patch-audit" => { + require(args.len() == 4, "usage: patch-audit "); + cmd_patch_audit(Path::new(&args[2]), Path::new(&args[3])); + } + "mir" => { + require(args.len() == 5, "usage: mir "); + cmd_mir(Path::new(&args[2]), &args[3], Path::new(&args[4])); + } + "routes" => { + require(args.len() == 4 || args.len() == 6, "usage: routes [helper ordering]"); + let mut cases = parse_tsv(Path::new(&args[3])); + if args.len() == 6 { + cases.retain(|r| r["unsafe_helper"] == args[4] && r["ordering"] == args[5]); + require(cases.len() == 1, "filtered route case must be unique"); + } + check_routes(Path::new(&args[2]), &cases); + } + "inventory" => { + require(args.len() == 8, "usage: inventory "); + cmd_inventory( + &args[2], + Path::new(&args[3]), + Path::new(&args[4]), + Path::new(&args[5]), + Path::new(&args[6]), + Path::new(&args[7]), + ); + } + "thread-spec" => { + require( + args.len() == 8 || args.len() == 9, + "usage: thread-spec [prod-mir-dir]", + ); + cmd_thread_spec( + &args[2], + Path::new(&args[3]), + Path::new(&args[4]), + Path::new(&args[5]), + Path::new(&args[6]), + Path::new(&args[7]), + args.get(8).map(Path::new), + ); + } + "check-ir" => { + require(args.len() >= 4, "usage: check-ir ..."); + cmd_check_ir(Path::new(&args[2]), &args[3..]); + } + "check-kani-log" => { + require( + args.len() == 6, + "usage: check-kani-log ", + ); + cmd_check_kani_log( + Path::new(&args[2]), + Path::new(&args[3]), + Path::new(&args[4]), + Path::new(&args[5]), + ); + } + "check-public-order" => { + require(args.len() == 7, "usage: check-public-order "); + check_public_ordering_forwarding(Path::new(&args[2]), &args[3], &args[4], &args[5], &args[6]); + } + "check-manifest" => { + require(args.len() == 4, "usage: check-manifest "); + validate_manifest_entries(Path::new(&args[2]), Path::new(&args[3])); + } + "replace" => { + require(args.len() == 3, "usage: replace (with CH7_OLD / CH7_NEW env)"); + cmd_replace(Path::new(&args[2])); + } + "edge-check" => { + require(args.len() == 7, "usage: edge-check "); + let expected: usize = args[6].parse().unwrap_or_else(|_| fail("bad expected count")); + cmd_edge_check(Path::new(&args[2]), &args[3], &args[4], &args[5], expected); + } + "check-line-diag" => { + require(args.len() == 6, "usage: check-line-diag "); + let line_num: usize = args[4].parse().unwrap_or_else(|_| fail("bad line num")); + cmd_check_line_diag(Path::new(&args[2]), &args[3], line_num, &args[5]); + } + other => fail(format!("unknown subcommand: {other}")), + } +} diff --git a/verifast-proofs/core/sync/atomic.rs/checks/common.sh b/verifast-proofs/core/sync/atomic.rs/checks/common.sh new file mode 100644 index 0000000000000..fe157e7f3aaa6 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/checks/common.sh @@ -0,0 +1,508 @@ +# Shared pure-Bash helpers for Challenge 7 VeriFast positive and negative suites. +# Sourced by verify.sh and ../atomic.rs-negative/verify.sh. +shopt -u patsub_replacement 2>/dev/null || true + +TC="+nightly-2026-11-21" +HOST="x86_64-unknown-linux-gnu" +ARM="aarch64-unknown-linux-gnu" +ATOMIC="sync::atomic::" +FAMILIES=(access rmw pointer-access pointer-rmw u32 readonly) +ACCESS_METHODS=(load store compare_exchange compare_exchange_weak) +RMW_METHODS=(swap fetch_add fetch_sub fetch_and fetch_nand fetch_or fetch_xor fetch_max fetch_min) +PTR_RMW_METHODS=(fetch_byte_add fetch_byte_sub fetch_and fetch_or fetch_xor) +BOOL_RMW_METHODS=(swap fetch_and fetch_or fetch_xor fetch_nand fetch_not) +BACKTRACE_TAR_SHA="66f3d6097f3ef1ced7ee5f05ca1f3797cc4ee6ba3212af303c13ea8eb540d8d0" +BACKTRACE_GITLINK="160000 d902726a1dcdc1e1c66f73d1162181b5423c645b" + +init_env() { + PROOF=$(cd "$1" && pwd) + CHECKS="$PROOF/checks" + TOOLS=$(cd "$2" && pwd) + WORK=$(cd "$3" && pwd) + REPO=$(cd "$PROOF/../../../.." && pwd) + LIB="$REPO/library" + CORE="$LIB/core/src" + BOOK="$REPO/doc/src/challenges/0007-atomic-types.md" + LAST_LOG="$WORK/last.log" + + mkdir -p "$WORK/library" + ln -sfn "$LIB/stdarch" "$WORK/library/stdarch" + ln -sfn "$LIB/portable-simd" "$WORK/library/portable-simd" + + SYSROOT=$(rustc "$TC" --print sysroot) + TOKEN_LD="$SYSROOT/lib:$SYSROOT/lib/rustlib/$HOST/lib" + SOURCE_TOKENS="$WORK/source-tokens" + CHECK_MIR="$WORK/check-mir" + VF_BASE=("$TOOLS/bin/verifast" -shared -verbose 1) + + run_expect "build Rust token comparison" 0 0 -- \ + rustc "$TC" --edition=2024 -Cprefer-dynamic -L "native=$SYSROOT/lib" \ + "$PROOF/tool-tests/source_tokens.rs" -o "$SOURCE_TOKENS" + + run_expect "build MIR and inventory checker" 0 0 -- \ + rustc "$TC" --edition=2024 -O "$CHECKS/check_mir.rs" -o "$CHECK_MIR" +} + +build_safety_macro() { + run_expect "production safety proc macro" 0 0 -- \ + cargo "$TC" build --locked -j1 --manifest-path "$LIB/Cargo.toml" -p safety --target-dir "$WORK/deps" + SAFETY="$WORK/deps/debug/libsafety.so" +} + +run_expect() { + local label=$1 expected=$2 nmarkers=$3 + shift 3 + local markers=() + local i + for ((i = 0; i < nmarkers; i++)); do + markers+=("$1") + shift + done + if [[ ${1:-} != -- ]]; then + echo "Internal error: run_expect missing -- for $label" >&2 + exit 2 + fi + shift + + set +e + "$@" > "$LAST_LOG" 2>&1 + local rc=$? + set -e + + local missing=() + local m + for m in "${markers[@]}"; do + if ! grep -Fq -- "$m" "$LAST_LOG"; then + missing+=("$m") + fi + done + + local bad_incons=0 + if grep -Fq "Detected an inconsistency" "$LAST_LOG"; then + bad_incons=1 + fi + + if [[ $rc -ne $expected || ${#missing[@]} -gt 0 || $bad_incons -ne 0 ]]; then + echo "FAIL $label: exit $rc, expected $expected, missing (${missing[*]}), inconsistency=$bad_incons" >&2 + awk ' + /error:|panicked at|Fatal error|^ERROR:/ { if (!first) first = NR } + { lines[NR] = $0 } + END { + s = first ? (first > 2 ? first - 2 : 1) : (NR > 20 ? NR - 19 : 1) + e = first ? (first + 20 < NR ? first + 20 : NR) : NR + for (i = s; i <= e; i++) print lines[i] + if (e < NR) { + print "--- tail ---" + for (i = (NR > 10 ? NR - 9 : 1); i <= NR; i++) print lines[i] + } + } + ' "$LAST_LOG" >&2 + exit 1 + fi + + if [[ $expected -ne 0 ]]; then + echo "PASS $label (expected rejection)" + else + echo "PASS $label" + fi +} + +replace_one() { + local file=$1 old=$2 new=$3 + CH7_OLD="$old" CH7_NEW="$new" "$CHECK_MIR" replace "$file" +} + +core_flags_str() { + local target=$1 + printf '%s' "--target=$target --edition=2024 --crate-name=core -Awarnings -Cpanic=unwind -Cdebug-assertions=no --extern=safety=$SAFETY" +} + +dump_original_mir() { + local target=$1 + local mir="$WORK/${target}-mir" + local owners="$WORK/owners-${target}.tsv" + local filters="sync::atomic & built | wrapping_mul & runtime-post-cleanup | mem::size_of & runtime-post-cleanup" + rm -rf "$mir" + run_expect "$target production MIR" 0 0 -- \ + rustc "$TC" --target="$target" --edition=2024 --crate-name=core -Awarnings \ + -Cpanic=unwind -Cdebug-assertions=no "--extern=safety=$SAFETY" \ + --crate-type=lib "-Zdump-mir=$filters" -Zdump-mir-exclude-pass-number \ + "-Zdump-mir-dir=$mir" --emit=metadata -o "$WORK/libcore.rmeta" "$CORE/lib.rs" + run_expect "$target atomic layout" 0 0 -- \ + rustc "$TC" --target="$target" --edition=2024 "--extern=core=$WORK/libcore.rmeta" \ + "-Ldependency=$(dirname "$SAFETY")" --crate-type=lib --emit=metadata \ + -o "$WORK/layout.rmeta" "$CHECKS/layout.rs" + "$CHECK_MIR" mir "$mir" "$target" "$owners" +} + +dump_witness_mir() { + local wmir="$WORK/witness-mir-${CRATE_FAMILY}" + rm -rf "$wmir" + run_expect "$CRATE_TARGET $CRATE_FAMILY witness MIR" 0 0 -- \ + rustc "$TC" $(core_flags_str "$CRATE_TARGET") --crate-type=lib \ + "-Zdump-mir=ch7_ & built" -Zdump-mir-exclude-pass-number \ + "-Zdump-mir-dir=$wmir" --emit=metadata -o "$WORK/witness-${CRATE_FAMILY}.rmeta" "$CRATE_ROOT" + CRATE_WITNESS_MIR="$wmir" +} + +owner_of() { + local target=$1 scalar=$2 + awk -F'\t' -v k="$scalar" '$1 == k { print $2; found = 1; exit } END { if (!found) exit 1 }' "$WORK/owners-${target}.tsv" +} + +scalar_types_for() { + local target=$1 + if [[ $target == "$ARM" ]]; then + printf '%s\n' i8 u8 i16 u16 i32 u32 i64 u64 isize usize i128 u128 + else + printf '%s\n' i8 u8 i16 u16 i32 u32 i64 u64 isize usize + fi +} + +layer_diffs_for() { + case $1 in + access) printf '%s\n' borrow widths integer-storage panic access ;; + rmw) printf '%s\n' borrow widths integer-storage rmw ;; + pointer-access) printf '%s\n' borrow widths pointer-slot panic pointer-access ;; + pointer-rmw) printf '%s\n' borrow widths pointer-slot pointer-rmw ;; + u32) printf '%s\n' borrow panic u32 ;; + readonly) printf '%s\n' borrow panic readonly ;; + *) echo "Unknown family: $1" >&2; exit 2 ;; + esac +} + +setup_crate() { + local target=$1 family=$2 + CRATE_TARGET=$target + CRATE_FAMILY=$family + CRATE_SRC="$WORK/library/core/src" + CRATE_ATOMIC="$CRATE_SRC/sync/atomic.rs" + CRATE_INTR="$CRATE_SRC/intrinsics/mod.rs" + CRATE_ROOT="$CRATE_SRC/lib.rs" + CRATE_REPORT="$WORK/scope.tsv" + CRATE_ROOTFILE="$WORK/roots.txt" + CRATE_PANIC=0 + if [[ $family == access || $family == pointer-access || $family == u32 || $family == readonly ]]; then + CRATE_PANIC=1 + fi + + rm -rf "$CRATE_SRC" + mkdir -p "$(dirname "$CRATE_SRC")" + cp -a "$CORE" "$CRATE_SRC" + + local diff + while IFS= read -r diff; do + GIT_CEILING_DIRECTORIES="$WORK" git -C "$CRATE_SRC" apply --whitespace=nowarn "$PROOF/specs/${diff}.diff" + done < <(layer_diffs_for "$family") + if [[ $target == "$ARM" && ( $family == access || $family == rmw ) ]]; then + GIT_CEILING_DIRECTORIES="$WORK" git -C "$CRATE_SRC" apply "$PROOF/specs/i128.diff" + fi + + local rel + for rel in lib.rs sync/atomic.rs intrinsics/mod.rs cell.rs ptr/mod.rs ptr/mut_ptr.rs; do + LD_LIBRARY_PATH="$TOKEN_LD" "$SOURCE_TOKENS" "$CORE/$rel" "$CRATE_SRC/$rel" >/dev/null + done + + CRATE_PROD_ROOTS=() + CRATE_WANTED=() + CRATE_CLIENT_ROOTS=() + + add_methods() { + local scalar=$1; shift + local owner m + owner=$(owner_of "$target" "$scalar") + for m in "$@"; do + CRATE_PROD_ROOTS+=("${ATOMIC}${owner}::${m}") + CRATE_WANTED+=("${ATOMIC}Atomic::<${scalar}>::${m}") + done + } + + local scalar + if [[ $family == access || $family == rmw ]]; then + local methods=() + if [[ $family == access ]]; then methods=("${ACCESS_METHODS[@]}"); else methods=("${RMW_METHODS[@]}"); fi + while IFS= read -r scalar; do + add_methods "$scalar" from_ptr as_ptr "${methods[@]}" + done < <(scalar_types_for "$target") + if [[ $family == access ]]; then + add_methods bool from_ptr as_ptr load store + else + add_methods bool from_ptr as_ptr "${BOOL_RMW_METHODS[@]}" + fi + elif [[ $family == u32 ]]; then + CRATE_PROD_ROOTS+=("ptr::write" "ptr::mut_ptr::{impl#0}::write") + CRATE_WANTED+=("ptr::write") + add_methods u32 from_ptr as_ptr "${ACCESS_METHODS[@]}" swap fetch_add fetch_sub + elif [[ $family == readonly ]]; then + add_methods bool from_ptr as_ptr load + add_methods u32 from_ptr as_ptr load + CRATE_PROD_ROOTS+=("${ATOMIC}atomic_store" "${ATOMIC}atomic_compare_exchange" "${ATOMIC}atomic_compare_exchange_weak") + CRATE_WANTED+=("${ATOMIC}atomic_store" "${ATOMIC}atomic_compare_exchange" "${ATOMIC}atomic_compare_exchange_weak") + else + add_methods u8 from_ptr as_ptr + if [[ $family == pointer-access ]]; then + add_methods "*mut T" from_ptr as_ptr swap "${ACCESS_METHODS[@]}" + else + add_methods "*mut T" from_ptr as_ptr swap "${PTR_RMW_METHODS[@]}" + fi + fi + + if [[ $CRATE_PANIC -eq 1 ]]; then + CRATE_PROD_ROOTS+=("intrinsics::abort_immediate" "intrinsics::caller_location") + fi +} + +add_module() { + local name=$1 parent=$2 files_csv=$3; shift 3 + printf '\nmod %s;\n' "$name" >> "$parent" + local dir + if [[ $parent == "$CRATE_ROOT" ]]; then + dir="$CRATE_SRC" + else + dir="${parent%.rs}" + mkdir -p "$dir" + fi + : > "$dir/${name}.rs" + local f + IFS=, read -ra file_list <<< "$files_csv" + for f in "${file_list[@]}"; do + cat "$CHECKS/$f" >> "$dir/${name}.rs" + printf '\n' >> "$dir/${name}.rs" + done + local prefix="${name}::" + if [[ $parent == "$CRATE_ATOMIC" ]]; then + prefix="${ATOMIC}${name}::" + fi + local fn + for fn in "$@"; do + CRATE_CLIENT_ROOTS+=("${prefix}${fn}") + done +} + +attach_clients() { + local target=$CRATE_TARGET family=$CRATE_FAMILY + local types=() t + while IFS= read -r t; do types+=("$t"); done < <(scalar_types_for "$target") + + if [[ $family == access ]]; then + local width_fns=(disjoint_views) + for t in "${types[@]}"; do + case $t in i8|i16|i32|i64|u64|i128|u128) width_fns+=("${t}_view") ;; esac + done + local m w + for m in view store load; do + for w in 8 16; do width_fns+=("borrowed_${m}${w}"); done + done + add_module ch7_width "$CRATE_ROOT" "integer-storage.gh,width.rs" "${width_fns[@]}" + + local cas_fns=() + for t in "${types[@]}"; do cas_fns+=("cas_${t}"); done + add_module ch7_integer "$CRATE_ROOT" "integer-storage.gh,integer_cas_client.rs" "${cas_fns[@]}" + add_module ch7_bool "$CRATE_ROOT" "bool-storage.gh,bool.rs,bool-access.rs" \ + bool_round_trip nand_byte borrowed_bool_access shared_bool_view shared_bool_store shared_bool_load + add_module ch7_bool_byte "$CRATE_ATOMIC" "bool-storage.gh,bool_cas_byte_client.rs" \ + strong_byte weak_byte recovered + elif [[ $family == rmw ]]; then + local rmw_fns=() + for t in "${types[@]}"; do rmw_fns+=("swap_${t}" "rmw_${t}"); done + add_module ch7_integer "$CRATE_ROOT" "integer-storage.gh,integer_swap_client.rs,integer_rmw_client.rs" "${rmw_fns[@]}" + add_module ch7_bool "$CRATE_ROOT" "bool-storage.gh,bool.rs,bool-rmw.rs" \ + bool_round_trip nand_byte borrowed_bool_rmw byte_results shared_bool_nand shared_bool_and + elif [[ $family == u32 ]]; then + add_module ch7_owned "$CRATE_ATOMIC" "owned-u32.rs" owned_round_trip storage_type + add_module ch7_public "$CRATE_ROOT" "u32.rs" \ + round_trip public_round_trip \ + borrowed_from_ptr borrowed_load borrowed_store borrowed_compare_exchange borrowed_compare_exchange_weak \ + borrowed_swap borrowed_fetch_add borrowed_fetch_sub + elif [[ $family == readonly ]]; then + add_module ch7_readonly "$CRATE_ATOMIC" "readonly.rs" \ + ro_bool_from_ptr ro_bool_load ro_bool_store ro_bool_compare_exchange ro_bool_compare_exchange_weak \ + ro_u32_from_ptr ro_u32_load ro_u32_store ro_u32_compare_exchange ro_u32_compare_exchange_weak \ + ro_bool_local_round_trip ro_u32_local_round_trip + else + cat "$CHECKS/pointer-shape.rs" >> "$CRATE_INTR" + CRATE_CLIENT_ROOTS+=("intrinsics::ch7_pointer_shape") + local ptr_fns=(exchange zero one two three four slice_metadata reference_metadata) + if [[ $family == pointer-access ]]; then + ptr_fns+=(pointer_orders shared_load shared_store shared_strong shared_weak compare_borrowed + thread_pointer_view thread_pointer_swap thread_pointer_compare_exchange thread_pointer_compare_exchange_weak) + else + ptr_fns+=(admit_pointer_operand update_address) + fi + add_module ch7_pointer "$CRATE_ROOT" "pointer-view.rs,${family}.rs" "${ptr_fns[@]}" + fi +} + +write_roots_file() { + local mode=$1 + : > "$CRATE_ROOTFILE" + local r + for r in "${CRATE_PROD_ROOTS[@]}"; do printf '%s\n' "$r" >> "$CRATE_ROOTFILE"; done + if [[ $mode == refine ]]; then + if [[ $CRATE_FAMILY == access ]]; then + local bo; bo=$(owner_of "$CRATE_TARGET" bool) + printf '%s\n%s\n' "${ATOMIC}${bo}::compare_exchange" "${ATOMIC}${bo}::compare_exchange_weak" >> "$CRATE_ROOTFILE" + elif [[ $CRATE_FAMILY == pointer-rmw ]]; then + local po; po=$(owner_of "$CRATE_TARGET" "*mut T") + printf '%s\n%s\n' "${ATOMIC}${po}::fetch_ptr_add" "${ATOMIC}${po}::fetch_ptr_sub" >> "$CRATE_ROOTFILE" + fi + elif [[ $mode == verify ]]; then + for r in "${CRATE_CLIENT_ROOTS[@]}"; do printf '%s\n' "$r" >> "$CRATE_ROOTFILE"; done + fi +} + +run_crate_refine() { + local label=$1 expected=$2 nmarkers=$3; shift 3 + write_roots_file refine + local args="$(core_flags_str "$CRATE_TARGET") --vf-rust-mir-exporter:roots=$CRATE_ROOTFILE" + run_expect "$label" "$expected" "$nmarkers" "$@" -- \ + "$TOOLS/bin/refinement-checker" --verbose 0 --rustc-args "$args" "$CORE/lib.rs" "$CRATE_ROOT" +} + +run_crate_verifast() { + local allow_dead=$1 label=$2 expected=$3 nmarkers=$4; shift 4 + write_roots_file verify + local args="$(core_flags_str "$CRATE_TARGET") --vf-rust-mir-exporter:roots=$CRATE_ROOTFILE" + if [[ $CRATE_PANIC -eq 1 ]]; then + args+=" --vf-rust-mir-exporter:atomic-literal-panic" + fi + args+=" --vf-rust-mir-exporter:scope-report=$CRATE_REPORT" + local cmd=("${VF_BASE[@]}") + if [[ $allow_dead -eq 1 ]]; then cmd+=(-allow_dead_code); fi + cmd+=(-rustc_args "$args" "$CRATE_ROOT") + run_expect "$label" "$expected" "$nmarkers" "$@" -- "${cmd[@]}" +} + +check_dead_swap() { + if [[ $CRATE_FAMILY == rmw ]]; then + run_crate_verifast 0 "$CRATE_TARGET target-constant swap" 1 1 ": dead code" + cp "$LAST_LOG" "$WORK/dead.log" + awk -f "$CHECKS/bool-swap.awk" "$CRATE_ATOMIC" "$WORK/dead.log" + fi +} + +build_platform_runtime() { + PLAT="$WORK/platform" + rm -rf "$PLAT" + cp -a "$TOOLS/tests/rust/unverified/platform" "$PLAT" + cp "$PROOF/platform.Cargo.lock" "$PLAT/Cargo.lock" + + # Build a clean runtime-library copy with verified pinned backtrace/src. + RUNTIME_LIB="$WORK/runtime-library" + rm -rf "$RUNTIME_LIB" + mkdir -p "$RUNTIME_LIB" + git -C "$LIB" ls-files -z -- . > "$WORK/runtime-lib-files.nul" + while IFS= read -r -d '' rel; do + if [[ $rel == backtrace ]]; then continue; fi + mkdir -p "$RUNTIME_LIB/$(dirname "$rel")" + cp -a "$LIB/$rel" "$RUNTIME_LIB/$rel" + done < "$WORK/runtime-lib-files.nul" + + local bt="$SYSROOT/lib/rustlib/src/rust/library/backtrace" + local bt_sha + bt_sha=$(LC_ALL=C tar --sort=name --mtime=@0 --owner=0 --group=0 --numeric-owner \ + --format=gnu -cf - -C "$bt/src" . | sha256sum | cut -d' ' -f1) + if [[ $bt_sha != "$BACKTRACE_TAR_SHA" ]]; then + echo "Unexpected pinned backtrace source digest: $bt_sha" >&2 + exit 1 + fi + local bt_link + bt_link=$(git -C "$LIB" ls-files --stage backtrace | awk '{print $1, $2}') + if [[ $bt_link != "$BACKTRACE_GITLINK" ]]; then + echo "backtrace gitlink changed: $bt_link" >&2 + exit 1 + fi + ln -s "$bt" "$RUNTIME_LIB/backtrace" + + PLATFORM_CARGO=( + env "__CARGO_TESTS_ONLY_SRC_ROOT=$RUNTIME_LIB" CARGO_INCREMENTAL=0 CARGO_PROFILE_DEV_DEBUG=0 + cargo "$TC" build -j1 --locked -Zbuild-std=std,panic_unwind --target "$HOST" + --manifest-path "$PLAT/Cargo.toml" --target-dir "$WORK/platform-target" --message-format=json + ) + run_expect "build platform with repository core" 0 0 -- "${PLATFORM_CARGO[@]}" + + local core_uri="path+file://${RUNTIME_LIB}/core#" + grep '^{' "$LAST_LOG" > "$WORK/cargo.json" + jq -e --arg uri "$core_uri" ' + select(.reason == "compiler-artifact" and .target.name == "core" and (.package_id | startswith($uri))) + ' "$WORK/cargo.json" >/dev/null + + THREAD_FLAGS="$WORK/thread.flags" + { + jq -r ' + select(.reason == "compiler-artifact") | .filenames[] + | select(endswith(".so") or endswith(".rmeta")) + | sub("/[^/]+$"; "") + ' "$WORK/cargo.json" | sort -u | sed 's/^/-Ldependency=/' + local name meta + for name in platform compiler_builtins core; do + meta=$(jq -r --arg n "$name" ' + select(.reason == "compiler-artifact" and .target.name == $n) + | .filenames[] | select(endswith(".rmeta")) + ' "$WORK/cargo.json") + if [[ $(wc -l <<< "$meta") -ne 1 || -z $meta ]]; then + echo "Expected unique .rmeta for $name" >&2 + exit 1 + fi + printf -- '--extern=%s=%s\n' "$name" "$meta" + done + } > "$THREAD_FLAGS" + + THREAD_BIN="$WORK/bin" + rm -rf "$THREAD_BIN" + cp -a "$TOOLS/bin" "$THREAD_BIN" + local spec="$THREAD_BIN/rust/std/lib.rsspec" + replace_one "$spec" $'enum Ordering {\n Relaxed,\n SeqCst\n }' \ + 'enum Ordering { Relaxed, Release, Acquire, AcqRel, SeqCst }' + replace_one "$spec" ' Ordering::Relaxed => false,' \ + $' Ordering::Relaxed => false,\n Ordering::Release => false,\n Ordering::Acquire => false,\n Ordering::AcqRel => false,' + cat "$WORK/interfaces.rsspec" >> "$spec" + + THREAD_VF=( + "$THREAD_BIN/verifast" -shared -verbose 1 + -rustc_arg "@$THREAD_FLAGS" + -rustc_args "--edition=2024 -Cpanic=unwind -Cdebug-assertions=no" + -extern_spec "platform=$PLAT/spec/lib.rsspec" + ) + + RO_THREAD_BIN="$WORK/bin-readonly" + rm -rf "$RO_THREAD_BIN" + cp -a "$TOOLS/bin" "$RO_THREAD_BIN" + local ro_spec="$RO_THREAD_BIN/rust/std/lib.rsspec" + replace_one "$ro_spec" $'enum Ordering {\n Relaxed,\n SeqCst\n }' \ + 'enum Ordering { Relaxed, Release, Acquire, AcqRel, SeqCst }' + replace_one "$ro_spec" ' Ordering::Relaxed => false,' \ + $' Ordering::Relaxed => false,\n Ordering::Release => false,\n Ordering::Acquire => false,\n Ordering::AcqRel => false,' + cat "$WORK/readonly.rsspec" >> "$ro_spec" + + RO_THREAD_VF=( + "$RO_THREAD_BIN/verifast" -shared -verbose 1 + -rustc_arg "@$THREAD_FLAGS" + -rustc_args "--edition=2024 -Cpanic=unwind -Cdebug-assertions=no" + -extern_spec "platform=$PLAT/spec/lib.rsspec" + ) +} + +build_pointer_spec() { + local lib="$PROOF/tool-tests/pointer_lib.rs" + local spec="$WORK/pointer.rsspec" + awk ' + BEGIN { print "struct Slot;" } + /^impl / { + ty = $0 + getline sig + c1 = ""; c2 = ""; c3 = "" + getline c1; getline c2; getline c3 + sub(/^ pub /, "", sig) + print ty + print sig ";" + print c1 + print c2 + print c3 + print "}" + count++ + } + END { if (count != 2) exit 2 } + ' "$lib" > "$spec" + POINTER_SPEC="$spec" +} diff --git a/verifast-proofs/core/sync/atomic.rs/checks/integer-storage.gh b/verifast-proofs/core/sync/atomic.rs/checks/integer-storage.gh new file mode 100644 index 0000000000000..18620ac70757b --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/checks/integer-storage.gh @@ -0,0 +1,152 @@ +/*@ +pred_ctor ordinary(p: *T)(;) = *p |-> ?v; + +lem prepare_unsigned(p: *T, k: lifetime_t) + nonghost_callers_only + req [?q]lifetime_token(k) &*& full_borrow(k, ordinary::(p)) &*& + p as usize % std::intrinsics::atomic_align_of::() == 0; + ens [q]lifetime_token(k) &*& [_]frac_borrow(k, sync::atomic::unsigned_content::(p)); +{ + let long = open_full_borrow_strong(k, ordinary::(p), q); + open ordinary::(p)(); + { + pred Pre() = *p |-> ?v; + pred Post() = sync::atomic::unsigned_content::(p)(); + close Pre(); + produce_lem_ptr_chunk atomic_block(Pre, Post)() { + open Pre(); + std::intrinsics::close_atomic_points_to_m(p, sync::atomic::accepts_unsigned); + close sync::atomic::unsigned_content::(p)(); + close Post(); + } { perform_atomically(); } + open Post(); + } + { + pred Ctx() = true; + produce_lem_ptr_chunk full_borrow_convert_strong(Ctx, sync::atomic::unsigned_content::(p), long, ordinary::(p))() { + open Ctx(); + open sync::atomic::unsigned_content::(p)(); + std::intrinsics::open_atomic_points_to(p); + close ordinary::(p)(); + } { + close Ctx(); + close_full_borrow_strong(long, ordinary::(p), sync::atomic::unsigned_content::(p)); + full_borrow_mono(long, k, sync::atomic::unsigned_content::(p)); + } + } + full_borrow_into_frac(k, sync::atomic::unsigned_content::(p)); +} + +lem halfword_excludes_byte(wide: *u16, index: usize) + req *wide |-> ?v &*& 0 <= index &*& index < 2 &*& [?g]points_to_::((wide as *u8) + index, ?a) &*& 0 < g; + ens false; +{ + to_u8s_(wide); + let start = wide as *u8; + array__split(start, index); + open array_(start + index, 2 - index, _); + merge_fractions points_to_::(start + index, _); + points_to__limits(start + index); +} + +lem opened_halfword_excludes_byte(wide: *u16, k: lifetime_t, q: real, f: real, index: usize) + nonghost_callers_only + req 0 < q &*& q < 1 &*& [1-q]lifetime_token(k) &*& + [f]std::intrinsics::atomic_points_to::(wide, 1, sync::atomic::accepts_unsigned) &*& + close_frac_borrow_token(f, sync::atomic::unsigned_content::(wide), q, k) &*& + borrow_end_token(k, ordinary::(wide)) &*& 0 <= index &*& index < 2 &*& + [?g]points_to_::((wide as *u8) + index, ?v) &*& 0 < g; + ens false; +{ + close [f]sync::atomic::unsigned_content::(wide)(); + close_frac_borrow(f, sync::atomic::unsigned_content::(wide)); + end_lifetime(k); + borrow_end(k, ordinary::(wide)); + open ordinary::(wide)(); + halfword_excludes_byte(wide, index); +} +@*/ +/*@ +fix scalar_layout(value: T) -> bool { + std::intrinsics::atomic_align_of::() == std::mem::align_of::() +} + +pred open_scalar(p: *T, k: lifetime_t, q: real, f: real) = + [f]std::intrinsics::atomic_points_to::(p, 1, sync::atomic::accepts_unsigned) &*& + close_frac_borrow_token(f, sync::atomic::unsigned_content::(p), q, k); + +lem open_integer(p: *T, k: lifetime_t, q: real) + nonghost_callers_only + req [q]lifetime_token(k) &*& [_]frac_borrow(k, sync::atomic::unsigned_content::(p)); + ens open_scalar::(p, k, q, ?f); +{ + let f = open_frac_borrow(k, sync::atomic::unsigned_content::(p), q); + open [f]sync::atomic::unsigned_content::(p)(); + close open_scalar::(p,k,q,f); +} + +lem close_integer(p: *T, k: lifetime_t, q: real) + nonghost_callers_only + req open_scalar::(p, k, q, ?f); + ens [q]lifetime_token(k); +{ + open open_scalar::(p,k,q,f); + close [f]sync::atomic::unsigned_content::(p)(); + close_frac_borrow(f, sync::atomic::unsigned_content::(p)); +} + +lem open_view_fraction(p: *T, k: lifetime_t, t: thread_id_t, view: *sync::atomic::Atomic, q: real) + nonghost_callers_only + req [_]sync::atomic::Atomic_share::(k, t, view) &*& ref_origin(view) as pointer == p as pointer &*& + [q]lifetime_token(k) &*& .atomic_content(p) == sync::atomic::unsigned_content::(p); + ens open_scalar::(p, k, q, ?f); +{ + open sync::atomic::Atomic_share::(k, t, view); + open_integer(p, k, q); +} + +lem start_integer(p: *T, k: lifetime_t) + nonghost_callers_only + req *p |-> ?value &*& [?q]lifetime_token(k) &*& p as usize % std::intrinsics::atomic_align_of::() == 0; + ens [q]lifetime_token(k) &*& [_]frac_borrow(k, sync::atomic::unsigned_content::(p)) &*& borrow_end_token(k, ordinary::(p)); +{ + close ordinary::(p)(); + borrow(k, ordinary::(p)); + prepare_unsigned(p, k); +} + +lem finish_integer(p: *T, k: lifetime_t) + nonghost_callers_only + req lifetime_token(k) &*& borrow_end_token(k, ordinary::(p)); + ens *p |-> ?value; +{ + end_lifetime(k); + borrow_end(k, ordinary::(p)); + open ordinary::(p)(); +} + +lem integer_views_exclude_common_byte(p: *T, k: lifetime_t, qa: real, qb: real, other: *U, i: usize, j: usize) + nonghost_callers_only + req 0 < qa &*& 0 < qb &*& qa + qb < 1 &*& [1-qa-qb]lifetime_token(k) &*& + open_scalar::(p, k, qa, ?fa) &*& open_scalar::(p, k, qb, ?fb) &*& + borrow_end_token(k, ordinary::(p)) &*& [?g]points_to_(other, ?extra) &*& 0 < g &*& + 0 <= i &*& i < std::mem::size_of::() &*& 0 <= j &*& j < std::mem::size_of::() &*& + (p as *u8) + i == (other as *u8) + j; + ens false; +{ + close_integer(p, k, qa); + close_integer(p, k, qb); + finish_integer(p, k); + to_u8s_(other); + let base = other as *u8; + array__split(base, j); + open [g]array_(base + j, std::mem::size_of::() - j, _); + to_u8s_(p); + let first = p as *u8; + array__split(first, i); + open array_(first + i, std::mem::size_of::() - i, _); + assert first + i == base + j; + merge_fractions points_to_::(first + i, _); + points_to__limits(first + i); +} +@*/ diff --git a/verifast-proofs/core/sync/atomic.rs/checks/integer_cas_client.rs b/verifast-proofs/core/sync/atomic.rs/checks/integer_cas_client.rs new file mode 100644 index 0000000000000..79d1dd5e69e9a --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/checks/integer_cas_client.rs @@ -0,0 +1,53 @@ +use crate::sync::atomic::{self, Ordering}; + +// Each expansion retains the original pointer and recovers its storage after both calls. +macro_rules! compare_integer_slot { + ($client:ident, $ty:ty, $atomic:ident) => { + unsafe fn $client(initial: $ty, expected: $ty, next: $ty, after: $ty, + success: Ordering, failure: Ordering) -> (Result<$ty, $ty>, Result<$ty, $ty>, $ty) + //@ req scalar_layout(initial) == true &*& failure != sync::atomic::Ordering::Release &*& failure != sync::atomic::Ordering::AcqRel; + //@ ens result::Result_own(currentThread, result.0) &*& result::Result_own(currentThread, result.1) &*& result.2 == after; + //@ on_unwind_ens false; + { + let mut value = initial; + let ptr = &raw mut value; + //@ to_u8s_(ptr); + //@ from_u8s_(ptr); + //@ let k = begin_lifetime(); + //@ start_integer(ptr, k); + let strong; + let weak; + { + //@ let_lft 'a = k; + let slot = unsafe { atomic::$atomic::from_ptr/*@::<'a>@*/(ptr) }; + //@ close sync::atomic::Ordering_own(currentThread, success); + //@ close sync::atomic::Ordering_own(currentThread, failure); + strong = slot.compare_exchange(expected, next, success, failure); + //@ assert match strong { Result::Ok(v) => v == expected, Result::Err(v) => v != expected }; + //@ close sync::atomic::Ordering_own(currentThread, success); + //@ close sync::atomic::Ordering_own(currentThread, failure); + weak = slot.compare_exchange_weak(expected, next, success, failure); + //@ assert match weak { Result::Ok(v) => v == expected, Result::Err(v) => true }; + } + //@ finish_integer(ptr, k); + let _observed = unsafe { *ptr }; + unsafe { *ptr = after }; + (strong, weak, unsafe { *ptr }) + } + }; +} + +compare_integer_slot!(cas_i8, i8, AtomicI8); +compare_integer_slot!(cas_u8, u8, AtomicU8); +compare_integer_slot!(cas_i16, i16, AtomicI16); +compare_integer_slot!(cas_u16, u16, AtomicU16); +compare_integer_slot!(cas_i32, i32, AtomicI32); +compare_integer_slot!(cas_u32, u32, AtomicU32); +compare_integer_slot!(cas_i64, i64, AtomicI64); +compare_integer_slot!(cas_u64, u64, AtomicU64); +compare_integer_slot!(cas_isize, isize, AtomicIsize); +compare_integer_slot!(cas_usize, usize, AtomicUsize); +#[cfg(target_has_atomic = "128")] +compare_integer_slot!(cas_i128, i128, AtomicI128); +#[cfg(target_has_atomic = "128")] +compare_integer_slot!(cas_u128, u128, AtomicU128); diff --git a/verifast-proofs/core/sync/atomic.rs/checks/integer_rmw_client.rs b/verifast-proofs/core/sync/atomic.rs/checks/integer_rmw_client.rs new file mode 100644 index 0000000000000..2f6e5a670ae99 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/checks/integer_rmw_client.rs @@ -0,0 +1,61 @@ +use crate::sync::atomic::{AtomicI8, AtomicI16, AtomicI32, AtomicI64, AtomicU8, AtomicU16, AtomicU64}; +#[cfg(target_has_atomic = "128")] +use crate::sync::atomic::{AtomicI128, AtomicU128}; + +// The enclosing proof module supplies start_integer and finish_integer. +// Each expansion starts with a genuine initialized slot. +macro_rules! integer_rmw_client { + ($client:ident, $word:ty, $atomic:ty) => { + unsafe fn $client(initial: $word, operand: $word) -> $word + //@ req scalar_layout(initial) == true; + //@ ens result == operand; + //@ on_unwind_ens false; + { + let mut storage = initial; + let ptr = &raw mut storage; + //@ to_u8s_(ptr); + //@ from_u8s_(ptr); + //@ let k = begin_lifetime(); + //@ start_integer(ptr, k); + { + //@ let_lft 'a = k; + let slot = unsafe { <$atomic>::from_ptr/*@::<'a>@*/(ptr) }; + //@ close sync::atomic::Ordering_own(currentThread, sync::atomic::Ordering::Relaxed); + let a = slot.fetch_add(operand, crate::sync::atomic::Ordering::Relaxed); + //@ close sync::atomic::Ordering_own(currentThread, sync::atomic::Ordering::Acquire); + let b = slot.fetch_sub(a, crate::sync::atomic::Ordering::Acquire); + //@ close sync::atomic::Ordering_own(currentThread, sync::atomic::Ordering::Release); + let c = slot.fetch_and(b, crate::sync::atomic::Ordering::Release); + //@ close sync::atomic::Ordering_own(currentThread, sync::atomic::Ordering::AcqRel); + let d = slot.fetch_nand(c, crate::sync::atomic::Ordering::AcqRel); + //@ close sync::atomic::Ordering_own(currentThread, sync::atomic::Ordering::SeqCst); + let e = slot.fetch_or(d, crate::sync::atomic::Ordering::SeqCst); + //@ close sync::atomic::Ordering_own(currentThread, sync::atomic::Ordering::Relaxed); + let f = slot.fetch_xor(e, crate::sync::atomic::Ordering::Relaxed); + //@ close sync::atomic::Ordering_own(currentThread, sync::atomic::Ordering::Release); + let g = slot.fetch_max(f, crate::sync::atomic::Ordering::Release); + //@ close sync::atomic::Ordering_own(currentThread, sync::atomic::Ordering::Acquire); + let _ = slot.fetch_min(g, crate::sync::atomic::Ordering::Acquire); + } + //@ finish_integer(ptr, k); + let _previous = unsafe { *ptr }; + unsafe { *ptr = operand }; + unsafe { *ptr } + } + }; +} + +integer_rmw_client!(rmw_i8, i8, AtomicI8); +integer_rmw_client!(rmw_u8, u8, AtomicU8); +integer_rmw_client!(rmw_i16, i16, AtomicI16); +integer_rmw_client!(rmw_u16, u16, AtomicU16); +integer_rmw_client!(rmw_i32, i32, AtomicI32); +integer_rmw_client!(rmw_u32, u32, crate::sync::atomic::AtomicU32); +integer_rmw_client!(rmw_i64, i64, AtomicI64); +integer_rmw_client!(rmw_u64, u64, AtomicU64); +integer_rmw_client!(rmw_isize, isize, crate::sync::atomic::AtomicIsize); +integer_rmw_client!(rmw_usize, usize, crate::sync::atomic::AtomicUsize); +#[cfg(target_has_atomic = "128")] +integer_rmw_client!(rmw_i128, i128, AtomicI128); +#[cfg(target_has_atomic = "128")] +integer_rmw_client!(rmw_u128, u128, AtomicU128); diff --git a/verifast-proofs/core/sync/atomic.rs/checks/integer_swap_client.rs b/verifast-proofs/core/sync/atomic.rs/checks/integer_swap_client.rs new file mode 100644 index 0000000000000..3990f58f4b38d --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/checks/integer_swap_client.rs @@ -0,0 +1,41 @@ +macro_rules! borrow_and_swap { + ($name:ident, $word:ty, $atomic:ty) => { + unsafe fn $name(initial: $word, replacement: $word, order: crate::sync::atomic::Ordering) -> $word + //@ req scalar_layout(initial) == true; + //@ ens result == initial; + //@ on_unwind_ens false; + { + let mut value = initial; + let p = &raw mut value; + //@ to_u8s_(p); + //@ from_u8s_(p); + //@ let k = begin_lifetime(); + //@ start_integer(p, k); + { + //@ let_lft 'a = k; + let view = unsafe { <$atomic>::from_ptr/*@::<'a>@*/(p) }; + //@ close sync::atomic::Ordering_own(currentThread, order); + let _old = view.swap(replacement, order); + } + //@ finish_integer(p, k); + let _observed = unsafe { *p }; + unsafe { *p = initial }; + unsafe { *p } + } + }; +} + +borrow_and_swap!(swap_i8, i8, crate::sync::atomic::AtomicI8); +borrow_and_swap!(swap_u8, u8, crate::sync::atomic::AtomicU8); +borrow_and_swap!(swap_i16, i16, crate::sync::atomic::AtomicI16); +borrow_and_swap!(swap_u16, u16, crate::sync::atomic::AtomicU16); +borrow_and_swap!(swap_i32, i32, crate::sync::atomic::AtomicI32); +borrow_and_swap!(swap_u32, u32, crate::sync::atomic::AtomicU32); +borrow_and_swap!(swap_i64, i64, crate::sync::atomic::AtomicI64); +borrow_and_swap!(swap_u64, u64, crate::sync::atomic::AtomicU64); +borrow_and_swap!(swap_isize, isize, crate::sync::atomic::AtomicIsize); +borrow_and_swap!(swap_usize, usize, crate::sync::atomic::AtomicUsize); +#[cfg(target_has_atomic = "128")] +borrow_and_swap!(swap_i128, i128, crate::sync::atomic::AtomicI128); +#[cfg(target_has_atomic = "128")] +borrow_and_swap!(swap_u128, u128, crate::sync::atomic::AtomicU128); diff --git a/verifast-proofs/core/sync/atomic.rs/checks/kani-negative-ordering.sh b/verifast-proofs/core/sync/atomic.rs/checks/kani-negative-ordering.sh new file mode 100755 index 0000000000000..b427b41c71d0e --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/checks/kani-negative-ordering.sh @@ -0,0 +1,285 @@ +#!/usr/bin/env bash +# Verify that Kani atomic intrinsic wrapper contracts accept legal orderings and +# reject all 8 illegal AtomicOrdering instantiations using direct callsite contract +# assertions (zero #[kani::stub_verified]). +set -euo pipefail + +here=$(cd "$(dirname "$0")" && pwd) +repo=$(cd "$here/../../../../.." && pwd) +kani=${KANI:-"$repo/kani_build/scripts/kani"} +if [[ ! -f $kani ]]; then + echo "Kani script not found: $kani (set KANI=/path/to/kani_build/scripts/kani)" >&2 + exit 1 +fi +expected_commit=$(awk -F'"' '/^commit[[:space:]]*=/{print $2; exit}' "$repo/tool_config/kani-version.toml") +if [[ -z $expected_commit ]]; then + echo "Failed to read pinned Kani commit from $repo/tool_config/kani-version.toml" >&2 + exit 1 +fi +kani_root=$(cd "$(dirname "$kani")/.." && pwd) +actual_commit=$(git -C "$kani_root" rev-parse --verify HEAD 2>/dev/null || true) +echo "Pinned Kani commit: $expected_commit; active checkout ($kani_root): ${actual_commit:-}" +if [[ $actual_commit != "$expected_commit" ]]; then + echo "Refusing to run against unpinned Kani commit (expected $expected_commit, got ${actual_commit:-none})." >&2 + exit 1 +fi +if ! git -C "$kani_root" diff --quiet HEAD; then + echo "Refusing to run against dirty Kani checkout: $kani_root" >&2 + exit 1 +fi +"$kani" --version + +tmp=$(mktemp -d "${TMPDIR:-/tmp}/ch7-kani-neg-order.XXXXXXXX") +trap 'rm -rf -- "$tmp"' EXIT + +# Copy library/ excluding any ignored top-level library/target build cache. +lib_copy="$tmp/library" +mkdir -p "$lib_copy" +shopt -s dotglob nullglob +for entry in "$repo/library/"*; do + name=$(basename "$entry") + if [[ $name == target ]]; then + continue + fi + cp -a "$entry" "$lib_copy/$name" +done +shopt -u dotglob nullglob + +intrinsics="$lib_copy/core/src/intrinsics/mod.rs" +cat > "$tmp/harnesses.rs" <<'RS' + #[kani::proof] + fn pos_intrinsic_atomic_load_relaxed() { + let src: u32 = kani::any(); + let _ = unsafe { atomic_load_wrapper::(&src) }; + kani::cover(true, "direct positive atomic_load_wrapper: reached after call"); + } + + #[kani::proof] + fn pos_intrinsic_atomic_store_relaxed() { + let mut dst: u32 = kani::any(); + let val: u32 = kani::any(); + unsafe { atomic_store_wrapper::(&mut dst, val) }; + kani::cover(true, "direct positive atomic_store_wrapper: reached after call"); + } + + #[kani::proof] + fn pos_intrinsic_atomic_cxchg_relaxed_relaxed() { + let mut dst: u32 = kani::any(); + let old: u32 = kani::any(); + let new: u32 = kani::any(); + let _ = unsafe { + atomic_cxchg_wrapper::( + &mut dst, + old, + new, + ) + }; + kani::cover(true, "direct positive atomic_cxchg_wrapper: reached after call"); + } + + #[kani::proof] + fn pos_intrinsic_atomic_cxchgweak_relaxed_relaxed() { + let mut dst: u32 = kani::any(); + let old: u32 = kani::any(); + let new: u32 = kani::any(); + let _ = unsafe { + atomic_cxchgweak_wrapper::( + &mut dst, + old, + new, + ) + }; + kani::cover(true, "direct positive atomic_cxchgweak_wrapper: reached after call"); + } + + #[kani::proof] + fn neg_intrinsic_atomic_load_release() { + let src: u32 = 0; + let _ = unsafe { atomic_load_wrapper::(&src) }; + } + + #[kani::proof] + fn neg_intrinsic_atomic_load_acqrel() { + let src: u32 = 0; + let _ = unsafe { atomic_load_wrapper::(&src) }; + } + + #[kani::proof] + fn neg_intrinsic_atomic_store_acquire() { + let mut dst: u32 = 0; + unsafe { atomic_store_wrapper::(&mut dst, 1) }; + } + + #[kani::proof] + fn neg_intrinsic_atomic_store_acqrel() { + let mut dst: u32 = 0; + unsafe { atomic_store_wrapper::(&mut dst, 1) }; + } + + #[kani::proof] + fn neg_intrinsic_atomic_cxchg_fail_release() { + let mut dst: u32 = 0; + let _ = unsafe { + atomic_cxchg_wrapper::( + &mut dst, + 0, + 1, + ) + }; + } + + #[kani::proof] + fn neg_intrinsic_atomic_cxchg_fail_acqrel() { + let mut dst: u32 = 0; + let _ = unsafe { + atomic_cxchg_wrapper::( + &mut dst, + 0, + 1, + ) + }; + } + + #[kani::proof] + fn neg_intrinsic_atomic_cxchgweak_fail_release() { + let mut dst: u32 = 0; + let _ = unsafe { + atomic_cxchgweak_wrapper::( + &mut dst, + 0, + 1, + ) + }; + } + + #[kani::proof] + fn neg_intrinsic_atomic_cxchgweak_fail_acqrel() { + let mut dst: u32 = 0; + let _ = unsafe { + atomic_cxchgweak_wrapper::( + &mut dst, + 0, + 1, + ) + }; + } +RS + +# Insert the 12 direct callsite harnesses right before the closing brace after harness_intrinsic_atomic_cxchgweak_seqcst_seqcst. +awk -v hfile="$tmp/harnesses.rs" ' + /harness_intrinsic_atomic_cxchgweak_seqcst_seqcst,/ { armed = 1 } + armed && $0 == "}" { + while ((getline line < hfile) > 0) print line + close(hfile) + inserted++ + armed = 0 + } + { print } + END { if (inserted != 1) exit 2 } +' "$intrinsics" > "$tmp/mod.rs.patched" +mv "$tmp/mod.rs.patched" "$intrinsics" + +export CARGO_BUILD_JOBS=1 RAYON_NUM_THREADS=1 CARGO_INCREMENTAL=0 +log="$tmp/kani.log" +set +e +"$kani" verify-std "$lib_copy" \ + -Z unstable-options -Z function-contracts -Z mem-predicates -Z float-lib \ + -Z c-ffi -Z loop-contracts -Z quantifiers \ + --jobs=1 --output-format=regular --target-dir "$tmp/target" \ + --harness pos_intrinsic_atomic_ --harness neg_intrinsic_atomic_ \ + --cbmc-args --object-bits 12 > "$log" 2>&1 +rc=$? +set -e +if [[ $rc -eq 0 ]]; then + echo "Expected Kani negative ordering harnesses to fail, but command exited 0" >&2 + tail -n 40 "$log" >&2 + exit 1 +fi + +extract_block() { + awk -v h="Checking harness ${1}..." ' + $0 == h { p = 1 } + p && /^Checking harness / && $0 != h { exit } + p { print } + ' "$log" +} + +declare -A pos_cover=( + [intrinsics::verify::pos_intrinsic_atomic_load_relaxed]='direct positive atomic_load_wrapper: reached after call' + [intrinsics::verify::pos_intrinsic_atomic_store_relaxed]='direct positive atomic_store_wrapper: reached after call' + [intrinsics::verify::pos_intrinsic_atomic_cxchg_relaxed_relaxed]='direct positive atomic_cxchg_wrapper: reached after call' + [intrinsics::verify::pos_intrinsic_atomic_cxchgweak_relaxed_relaxed]='direct positive atomic_cxchgweak_wrapper: reached after call' +) + +for name in \ + intrinsics::verify::pos_intrinsic_atomic_load_relaxed \ + intrinsics::verify::pos_intrinsic_atomic_store_relaxed \ + intrinsics::verify::pos_intrinsic_atomic_cxchg_relaxed_relaxed \ + intrinsics::verify::pos_intrinsic_atomic_cxchgweak_relaxed_relaxed +do + block=$(extract_block "$name") + if [[ -z $block ]] || ! grep -Fq 'VERIFICATION:- SUCCESSFUL' <<< "$block"; then + echo "Positive ordering control failed: $name" >&2 + printf '%s\n' "$block" >&2 + exit 1 + fi + if ! awk -v desc="${pos_cover[$name]}" ' + /^Check [0-9]+: / { st = ""; ok_desc = 0 } + /^[[:space:]]*- Status: SATISFIED$/ { st = "SATISFIED" } + index($0, "- Description: \"" desc "\"") > 0 { ok_desc = 1 } + st == "SATISFIED" && ok_desc { found = 1 } + END { exit(found ? 0 : 1) } + ' <<< "$block"; then + echo "Missing satisfied post-call cover for positive control: $name" >&2 + printf '%s\n' "$block" >&2 + exit 1 + fi + echo "PASS accepted legal ordering: $name" +done + +declare -A expected=( + [intrinsics::verify::neg_intrinsic_atomic_load_release]='ORD == AtomicOrdering::Relaxed || ORD == AtomicOrdering::Acquire' + [intrinsics::verify::neg_intrinsic_atomic_load_acqrel]='ORD == AtomicOrdering::Relaxed || ORD == AtomicOrdering::Acquire' + [intrinsics::verify::neg_intrinsic_atomic_store_acquire]='ORD == AtomicOrdering::Relaxed || ORD == AtomicOrdering::Release' + [intrinsics::verify::neg_intrinsic_atomic_store_acqrel]='ORD == AtomicOrdering::Relaxed || ORD == AtomicOrdering::Release' + [intrinsics::verify::neg_intrinsic_atomic_cxchg_fail_release]='ORD_FAIL == AtomicOrdering :: Relaxed || ORD_FAIL == AtomicOrdering :: Acquire' + [intrinsics::verify::neg_intrinsic_atomic_cxchg_fail_acqrel]='ORD_FAIL == AtomicOrdering :: Relaxed || ORD_FAIL == AtomicOrdering :: Acquire' + [intrinsics::verify::neg_intrinsic_atomic_cxchgweak_fail_release]='ORD_FAIL == AtomicOrdering :: Relaxed || ORD_FAIL == AtomicOrdering :: Acquire' + [intrinsics::verify::neg_intrinsic_atomic_cxchgweak_fail_acqrel]='ORD_FAIL == AtomicOrdering :: Relaxed || ORD_FAIL == AtomicOrdering :: Acquire' +) + +for name in \ + intrinsics::verify::neg_intrinsic_atomic_load_release \ + intrinsics::verify::neg_intrinsic_atomic_load_acqrel \ + intrinsics::verify::neg_intrinsic_atomic_store_acquire \ + intrinsics::verify::neg_intrinsic_atomic_store_acqrel \ + intrinsics::verify::neg_intrinsic_atomic_cxchg_fail_release \ + intrinsics::verify::neg_intrinsic_atomic_cxchg_fail_acqrel \ + intrinsics::verify::neg_intrinsic_atomic_cxchgweak_fail_release \ + intrinsics::verify::neg_intrinsic_atomic_cxchgweak_fail_acqrel +do + block=$(extract_block "$name") + if [[ -z $block ]]; then + echo "Missing harness in Kani output: $name" >&2 + tail -n 60 "$log" >&2 + exit 1 + fi + if ! grep -Fq 'VERIFICATION:- FAILED' <<< "$block"; then + echo "Harness did not fail as expected: $name" >&2 + printf '%s\n' "$block" >&2 + exit 1 + fi + if ! grep -Fq "Failed Checks: ${expected[$name]}" <<< "$block"; then + echo "Unexpected failure check for $name" >&2 + printf '%s\n' "$block" >&2 + exit 1 + fi + echo "PASS rejected illegal ordering: $name" +done + +if ! grep -Fq 'Complete - 4 successfully verified harnesses, 8 failures, 12 total.' "$log"; then + echo "Unexpected Kani summary" >&2 + tail -n 30 "$log" >&2 + exit 1 +fi +echo "All 4/4 legal controls accepted and 8/8 Kani negative ordering contract checks rejected." diff --git a/verifast-proofs/core/sync/atomic.rs/checks/layout.rs b/verifast-proofs/core/sync/atomic.rs/checks/layout.rs new file mode 100644 index 0000000000000..cc0521b6d5bc7 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/checks/layout.rs @@ -0,0 +1,44 @@ +#![no_core] +#![feature(no_core)] +#![cfg_attr(target_has_atomic = "128", feature(integer_atomics))] + +extern crate core; +use core::assert; + +use core::mem::{align_of, size_of}; +use core::sync::atomic::*; + +macro_rules! slot { + ($atomic:ty, $ordinary:ty, $bytes:expr) => { + const _: () = { + assert!(size_of::<$ordinary>() == $bytes); + assert!(size_of::<$atomic>() == $bytes); + assert!(align_of::<$atomic>() == align_of::<$ordinary>()); + }; + }; +} + +slot!(AtomicBool, bool, 1); +slot!(AtomicI8, i8, 1); +slot!(AtomicU8, u8, 1); +slot!(AtomicI16, i16, 2); +slot!(AtomicU16, u16, 2); +slot!(AtomicI32, i32, 4); +slot!(AtomicU32, u32, 4); +slot!(AtomicI64, i64, 8); +slot!(AtomicU64, u64, 8); +slot!(AtomicIsize, isize, 8); +slot!(AtomicUsize, usize, 8); +slot!(AtomicPtr, *mut u8, 8); +#[cfg(target_has_atomic = "128")] +slot!(AtomicI128, i128, 16); +#[cfg(target_has_atomic = "128")] +slot!(AtomicU128, u128, 16); + +const _: () = { + assert!(Ordering::Relaxed as u8 == 0); + assert!(Ordering::Release as u8 == 1); + assert!(Ordering::Acquire as u8 == 2); + assert!(Ordering::AcqRel as u8 == 3); + assert!(Ordering::SeqCst as u8 == 4); +}; diff --git a/verifast-proofs/core/sync/atomic.rs/checks/owned-u32.rs b/verifast-proofs/core/sync/atomic.rs/checks/owned-u32.rs new file mode 100644 index 0000000000000..7943561677575 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/checks/owned-u32.rs @@ -0,0 +1,75 @@ +use super::{AtomicPrimitive, AtomicU32, private}; + +// The associated type equation is supplied by rustc at the concrete call below. +unsafe fn storage_type, S>() +//@ req true; +//@ ens typeid(::Storage) == typeid(S); +//@ on_unwind_ens false; +{} + +/*@ +fix word_layout() -> bool { + std::intrinsics::atomic_align_of::>() == std::mem::align_of::>() && + typeid(::Storage) == typeid(sync::atomic::private::Align4) +} +@*/ + +unsafe fn owned_round_trip(value: AtomicU32) -> AtomicU32 +//@ req std::intrinsics::atomic_align_of::>() == std::mem::align_of::>(); +//@ ens sync::atomic::Atomic_own::(currentThread, result); +//@ on_unwind_ens false; +{ + unsafe { storage_type::>() }; + let mut storage = value; + let p = &raw mut storage; + /*@{ + produce_lem_ptr_chunk sync::atomic::atomic_pack(sync::atomic::valid_word_value, word_layout(), true, sync::atomic::owned_word_content)(slot) { + open points_to(slot, ?v); + to_u8s_(slot); + from_u8s_(slot); + close points_to(slot, v); + std::intrinsics::close_atomic_points_to_m(slot, sync::atomic::valid_word_value); + close sync::atomic::owned_word_content(slot)(); + }; + produce_lem_ptr_chunk sync::atomic::atomic_unpack(sync::atomic::valid_word_value, word_layout(), true, sync::atomic::owned_word_content)(slot) { + open sync::atomic::owned_word_content(slot)(); + std::intrinsics::open_atomic_points_to(slot); + }; + produce_lem_ptr_chunk sync::atomic::atomic_drop_rep(sync::atomic::valid_word_value, word_layout(), >.storage_owner)(t, v) { + let bytes = u8s__of::< ::Storage>(v.v); + of_u8s__u8s__of::< ::Storage>(v.v); + match of_u8s_::>(bytes) { + none => {} + some(payload) => { + close u32_own(t, payload.0); + close sync::atomic::private::Align4_own::(t, payload); + close sync::atomic::Atomic_storage_owner::(t, v); + } + } + }; + let t = currentThread; + close sync::atomic::Atomic_own::(t, *p); + open_points_to(p); + close sync::atomic::Atomic_full_borrow_content::(t, p)(); + let k = begin_lifetime(); + borrow(k, sync::atomic::Atomic_full_borrow_content::(t, p)); + produce_type_interp::(); + { + pred Pre() = ref_origin(p) == p &*& type_interp::() &*& full_borrow(k, sync::atomic::Atomic_full_borrow_content::(t, p)) &*& lifetime_token(k); + pred Post() = type_interp::() &*& [_]sync::atomic::Atomic_share::(k, t, p) &*& lifetime_token(k); + close Pre(); + produce_lem_ptr_chunk atomic_block(Pre, Post)() { + open Pre(); + sync::atomic::Atomic_share_full::(k, t, p); + close Post(); + } { perform_atomically(); } + open Post(); + } + end_lifetime(k); + borrow_end(k, sync::atomic::Atomic_full_borrow_content::(t, p)); + open sync::atomic::Atomic_full_borrow_content::(t, p)(); + leak type_interp::(); + close_points_to(p); + }@*/ + storage +} diff --git a/verifast-proofs/core/sync/atomic.rs/checks/pointer-access.rs b/verifast-proofs/core/sync/atomic.rs/checks/pointer-access.rs new file mode 100644 index 0000000000000..9a4e6ebee1524 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/checks/pointer-access.rs @@ -0,0 +1,208 @@ +// This module already imports Ordering and the checked pointer-slot model. +unsafe fn pointer_orders

(initial: *mut P, write: *mut P, after: *mut P, store: Ordering, load: Ordering) -> *mut P +//@ req pointer_layout(initial) == true &*& store != sync::atomic::Ordering::Acquire &*& store != sync::atomic::Ordering::AcqRel &*& load != sync::atomic::Ordering::Release &*& load != sync::atomic::Ordering::AcqRel; +//@ ens result == after; +//@ on_unwind_ens false; +{ + let mut value = initial; + let slot = &raw mut value; + unsafe { crate::intrinsics::ch7_pointer_shape::(slot) }; + //@ to_u8s_(slot); + //@ from_u8s_(slot); + //@ close ordinary_slot::

(slot)(); + //@ let k = begin_lifetime(); + //@ borrow(k, ordinary_slot::

(slot)); + //@ prepare_slot(slot, k); + { + //@ let_lft 'a = k; + let view = unsafe { AtomicPtr::

::from_ptr/*@::<_, 'a>@*/(slot) }; + //@ close sync::atomic::Ordering_own(currentThread, store); + view.store(write, store); + //@ close sync::atomic::Ordering_own(currentThread, load); + let _value = view.load(load); + } + //@ end_lifetime(k); + //@ borrow_end(k, ordinary_slot::

(slot)); + //@ open ordinary_slot::

(slot)(); + let _value = unsafe { *slot }; + unsafe { *slot = after }; + unsafe { *slot } +} + +unsafe fn shared_store

(view: &AtomicPtr

, val: *mut P, order: Ordering) +//@ req [?q]lifetime_token(?k) &*& [_]sync::atomic::Atomic_share::<*P>(k, currentThread, view) &*& thread_token(currentThread); +//@ ens [q]lifetime_token(k) &*& thread_token(currentThread) &*& order != sync::atomic::Ordering::Acquire &*& order != sync::atomic::Ordering::AcqRel; +//@ on_unwind_ens [q]lifetime_token(k) &*& thread_token(currentThread) &*& (order == sync::atomic::Ordering::Acquire || order == sync::atomic::Ordering::AcqRel); +{ + //@ open sync::atomic::Atomic_share::<*P>(k, currentThread, view); + //@ close exists(false); + //@ close sync::atomic::Atomic_share::<*P>(k, currentThread, view); + //@ leak sync::atomic::Atomic_share::<*P>(k, currentThread, view); + //@ close sync::atomic::Ordering_own(currentThread, order); + view.store(val, order) +} + +unsafe fn shared_load

(view: &AtomicPtr

, order: Ordering) -> *mut P +//@ req [?q]lifetime_token(?k) &*& [_]sync::atomic::Atomic_share::<*P>(k, currentThread, view) &*& thread_token(currentThread); +//@ ens [q]lifetime_token(k) &*& thread_token(currentThread) &*& order != sync::atomic::Ordering::Release &*& order != sync::atomic::Ordering::AcqRel; +//@ on_unwind_ens [q]lifetime_token(k) &*& thread_token(currentThread) &*& (order == sync::atomic::Ordering::Release || order == sync::atomic::Ordering::AcqRel); +{ + //@ open sync::atomic::Atomic_share::<*P>(k, currentThread, view); + //@ close exists(false); + //@ close sync::atomic::Atomic_share::<*P>(k, currentThread, view); + //@ leak sync::atomic::Atomic_share::<*P>(k, currentThread, view); + //@ close sync::atomic::Ordering_own(currentThread, order); + view.load(order) +} +// An external caller's expectations for all Ordering inputs and both exits. +unsafe fn shared_strong

(view: &AtomicPtr

, expected: *mut P, new: *mut P, success: Ordering, failure: Ordering) -> Result<*mut P, *mut P> +//@ req [?q]lifetime_token(?k) &*& [_]sync::atomic::Atomic_share::<*P>(k, currentThread, view) &*& thread_token(currentThread); +//@ ens [q]lifetime_token(k) &*& thread_token(currentThread) &*& failure != sync::atomic::Ordering::Release &*& failure != sync::atomic::Ordering::AcqRel &*& result::Result_own::<*P, *P>(currentThread, result) &*& match result { Result::Ok(v) => v as usize == expected as usize, Result::Err(v) => v as usize != expected as usize }; +//@ on_unwind_ens [q]lifetime_token(k) &*& thread_token(currentThread) &*& (failure == sync::atomic::Ordering::Release || failure == sync::atomic::Ordering::AcqRel); +{ + //@ open sync::atomic::Atomic_share::<*P>(k, currentThread, view); + //@ close exists(false); + //@ close sync::atomic::Atomic_share::<*P>(k, currentThread, view); + //@ leak sync::atomic::Atomic_share::<*P>(k, currentThread, view); + //@ close sync::atomic::Ordering_own(currentThread, success); + //@ close sync::atomic::Ordering_own(currentThread, failure); + view.compare_exchange(expected, new, success, failure) +} + +unsafe fn shared_weak

(view: &AtomicPtr

, expected: *mut P, new: *mut P, success: Ordering, failure: Ordering) -> Result<*mut P, *mut P> +//@ req [?q]lifetime_token(?k) &*& [_]sync::atomic::Atomic_share::<*P>(k, currentThread, view) &*& thread_token(currentThread); +//@ ens [q]lifetime_token(k) &*& thread_token(currentThread) &*& failure != sync::atomic::Ordering::Release &*& failure != sync::atomic::Ordering::AcqRel &*& result::Result_own::<*P, *P>(currentThread, result) &*& match result { Result::Ok(v) => v as usize == expected as usize, Result::Err(v) => true }; +//@ on_unwind_ens [q]lifetime_token(k) &*& thread_token(currentThread) &*& (failure == sync::atomic::Ordering::Release || failure == sync::atomic::Ordering::AcqRel); +{ + //@ open sync::atomic::Atomic_share::<*P>(k, currentThread, view); + //@ close exists(false); + //@ close sync::atomic::Atomic_share::<*P>(k, currentThread, view); + //@ leak sync::atomic::Atomic_share::<*P>(k, currentThread, view); + //@ close sync::atomic::Ordering_own(currentThread, success); + //@ close sync::atomic::Ordering_own(currentThread, failure); + view.compare_exchange_weak(expected, new, success, failure) +} + +/*@ +lem discard_pointer_result(t: thread_id_t, value: result::Result<*P, *P>) + req result::Result_own::<*P, *P>(t, value); + ens true; +{ + open result::Result_own::<*P, *P>(t, value); + match value { + Result::Ok(v) => { open raw_ptr_own::

()(t, v); } + Result::Err(v) => { open raw_ptr_own::

()(t, v); } + } +} +@*/ + +unsafe fn compare_borrowed

(initial: *mut P, expected: *mut P, next: *mut P, after: *mut P, success: Ordering, failure: Ordering) -> *mut P +//@ req pointer_layout(initial) == true &*& failure != sync::atomic::Ordering::Release &*& failure != sync::atomic::Ordering::AcqRel; +//@ ens result as pointer == after as pointer; +//@ on_unwind_ens false; +{ + let mut value = initial; + let slot = &raw mut value; + unsafe { crate::intrinsics::ch7_pointer_shape::(slot) }; + //@ to_u8s_(slot); + //@ from_u8s_(slot); + //@ close ordinary_slot::

(slot)(); + //@ let k = begin_lifetime(); + //@ borrow(k, ordinary_slot::

(slot)); + //@ prepare_slot(slot, k); + { + //@ let_lft 'a = k; + let view = unsafe { AtomicPtr::

::from_ptr/*@::<_, 'a>@*/(slot) }; + //@ close sync::atomic::Ordering_own(currentThread, success); + //@ close sync::atomic::Ordering_own(currentThread, failure); + let first = view.compare_exchange(expected, next, success, failure); + //@ discard_pointer_result(currentThread, first); + //@ close sync::atomic::Ordering_own(currentThread, success); + //@ close sync::atomic::Ordering_own(currentThread, failure); + let second = view.compare_exchange_weak(expected, next, success, failure); + //@ discard_pointer_result(currentThread, second); + } + //@ end_lifetime(k); + //@ borrow_end(k, ordinary_slot::

(slot)); + //@ open ordinary_slot::

(slot)(); + let _observed = unsafe { *slot }; + unsafe { *slot = after }; + unsafe { *slot } +} +/*@ +pred_ctor thread_pointer_content(slot: *_)(;) = + std::intrinsics::atomic_points_to::<*T>(slot as **T, 1, sync::atomic::accepts_pointer); + +lem certify_thread_borrow(slot: *_, k: lifetime_t) + nonghost_callers_only + req [_]frac_borrow(k, thread_pointer_content::(slot)) &*& sync::atomic::thin_raw_slot_type::<*T>() == true; + ens [_]frac_borrow(k, sync::atomic::pointer_slot_content::(slot)); +{ + produce_lem_ptr_chunk implies_frac(thread_pointer_content::(slot), sync::atomic::pointer_slot_content::(slot))() { + open [?f]thread_pointer_content::(slot)(); + close [f]sync::atomic::pointer_slot_content::(slot)(); + } { + produce_lem_ptr_chunk implies_frac(sync::atomic::pointer_slot_content::(slot), thread_pointer_content::(slot))() { + open [?f]sync::atomic::pointer_slot_content::(slot)(); + close [f]thread_pointer_content::(slot)(); + } { + frac_borrow_implies(k, thread_pointer_content::(slot), sync::atomic::pointer_slot_content::(slot)); + } + } +} +@*/ + +unsafe fn thread_pointer_view<'a, T>(ptr: *mut *mut T) -> &'a AtomicPtr +//@ req [?q]lifetime_token('a) &*& [_]frac_borrow('a, thread_pointer_content::(ptr)) &*& ref_origin(ptr) == ptr; +//@ ens [q]lifetime_token('a) &*& [_]frac_borrow('a, thread_pointer_content::(ref_origin(result))) &*& [_]frac_borrow('a, ref_initialized_(result)) &*& ref_origin(result) as pointer == ptr as pointer; +//@ on_unwind_ens false; +{ + unsafe { crate::intrinsics::ch7_pointer_shape::(ptr) }; + //@ certify_thread_borrow::(ptr, 'a); + let result = unsafe { AtomicPtr::::from_ptr/*@::<_, 'a>@*/(ptr) }; + //@ open sync::atomic::Atomic_share::<*T>('a, currentThread, result); + result +} + +unsafe fn thread_pointer_swap(receiver: &AtomicPtr, val: *mut T, order: Ordering) -> *mut T +//@ req [?q]lifetime_token(?k) &*& [_]frac_borrow(k, thread_pointer_content::(ref_origin(receiver))) &*& [_]frac_borrow(k, ref_initialized_(receiver)); +//@ ens [q]lifetime_token(k); +//@ on_unwind_ens false; +{ + unsafe { crate::intrinsics::ch7_pointer_shape::(val as *mut *mut T) }; + //@ certify_thread_borrow::(ref_origin(receiver), k); + //@ close exists(false); + //@ close sync::atomic::Atomic_share::<*T>(k, currentThread, receiver); + //@ leak sync::atomic::Atomic_share::<*T>(k, currentThread, receiver); + //@ close sync::atomic::Ordering_own(currentThread, order); + receiver.swap(val, order) +} +unsafe fn thread_pointer_compare_exchange(receiver: &AtomicPtr, current: *mut T, new: *mut T, success: Ordering, failure: Ordering) -> Result<*mut T, *mut T> +//@ req [?q]lifetime_token(?k) &*& [_]frac_borrow(k, thread_pointer_content::(ref_origin(receiver))) &*& [_]frac_borrow(k, ref_initialized_(receiver)) &*& success == sync::atomic::Ordering::Relaxed &*& failure == sync::atomic::Ordering::Relaxed; +//@ ens [q]lifetime_token(k) &*& result::Result_own::<*T, *T>(currentThread, result); +//@ on_unwind_ens false; +{ + unsafe { crate::intrinsics::ch7_pointer_shape::(current as *mut *mut T) }; + //@ certify_thread_borrow::(ref_origin(receiver), k); + //@ close exists(false); + //@ close sync::atomic::Atomic_share::<*T>(k, currentThread, receiver); + //@ leak sync::atomic::Atomic_share::<*T>(k, currentThread, receiver); + //@ close sync::atomic::Ordering_own(currentThread, success); + //@ close sync::atomic::Ordering_own(currentThread, failure); + receiver.compare_exchange(current, new, success, failure) +} + +unsafe fn thread_pointer_compare_exchange_weak(receiver: &AtomicPtr, current: *mut T, new: *mut T, success: Ordering, failure: Ordering) -> Result<*mut T, *mut T> +//@ req [?q]lifetime_token(?k) &*& [_]frac_borrow(k, thread_pointer_content::(ref_origin(receiver))) &*& [_]frac_borrow(k, ref_initialized_(receiver)) &*& success == sync::atomic::Ordering::Relaxed &*& failure == sync::atomic::Ordering::Relaxed; +//@ ens [q]lifetime_token(k) &*& result::Result_own::<*T, *T>(currentThread, result); +//@ on_unwind_ens false; +{ + unsafe { crate::intrinsics::ch7_pointer_shape::(current as *mut *mut T) }; + //@ certify_thread_borrow::(ref_origin(receiver), k); + //@ close exists(false); + //@ close sync::atomic::Atomic_share::<*T>(k, currentThread, receiver); + //@ leak sync::atomic::Atomic_share::<*T>(k, currentThread, receiver); + //@ close sync::atomic::Ordering_own(currentThread, success); + //@ close sync::atomic::Ordering_own(currentThread, failure); + receiver.compare_exchange_weak(current, new, success, failure) +} diff --git a/verifast-proofs/core/sync/atomic.rs/checks/pointer-rmw.rs b/verifast-proofs/core/sync/atomic.rs/checks/pointer-rmw.rs new file mode 100644 index 0000000000000..5c982a87b5e00 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/checks/pointer-rmw.rs @@ -0,0 +1,50 @@ +// This caller is appended to the verified ordinary-slot borrow client. +//@ fix null_address_only

(value: *P) -> bool { value as usize == 0 } + +unsafe fn admit_pointer_operand

(slot: *mut *mut P) +//@ req true; +//@ ens true; +//@ on_unwind_ens false; +{ + unsafe { crate::intrinsics::ch7_pointer_shape::(slot) }; + //@ close sync::atomic::raw_rmw_pointer_invariant::

()(sync::atomic::accepts_pointer); + //@ leak sync::atomic::raw_rmw_pointer_invariant::

()(sync::atomic::accepts_pointer); + //@ close sync::atomic::pointer_usize_domain::<*P, usize>(sync::atomic::accepts_pointer); + //@ open sync::atomic::pointer_usize_domain::<*P, usize>(sync::atomic::accepts_pointer); +} + +unsafe fn update_address

(initial: *mut P, operand: usize, after: *mut P, order: Ordering) -> *mut P +//@ req pointer_layout(initial) == true; +//@ ens result == after; +//@ on_unwind_ens false; +{ + let mut value = initial; + let slot = &raw mut value; + unsafe { crate::intrinsics::ch7_pointer_shape::(slot) }; + //@ to_u8s_(slot); + //@ from_u8s_(slot); + //@ close ordinary_slot::

(slot)(); + //@ let k = begin_lifetime(); + //@ borrow(k, ordinary_slot::

(slot)); + //@ prepare_slot(slot, k); + { + //@ let_lft 'a = k; + let view = unsafe { AtomicPtr::

::from_ptr/*@::<_, 'a>@*/(slot) }; + //@ close sync::atomic::Ordering_own(currentThread, order); + let _ = view.fetch_byte_add(operand, order); + //@ close sync::atomic::Ordering_own(currentThread, order); + let _ = view.fetch_byte_sub(operand, order); + //@ close sync::atomic::Ordering_own(currentThread, order); + let _ = view.fetch_or(operand, order); + //@ close sync::atomic::Ordering_own(currentThread, order); + let _ = view.fetch_and(operand, order); + //@ close sync::atomic::Ordering_own(currentThread, order); + let _ = view.fetch_xor(operand, order); + } + //@ end_lifetime(k); + //@ borrow_end(k, ordinary_slot::

(slot)); + //@ open ordinary_slot::

(slot)(); + let _previous = unsafe { *slot }; + unsafe { *slot = after }; + unsafe { *slot } +} diff --git a/verifast-proofs/core/sync/atomic.rs/checks/pointer-shape.rs b/verifast-proofs/core/sync/atomic.rs/checks/pointer-shape.rs new file mode 100644 index 0000000000000..2c79bca5d209b --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/checks/pointer-shape.rs @@ -0,0 +1,8 @@ + +// The compiler supplies both projection equalities via these actual Rust bounds. +// The witness is a client of the production module and receives no storage rights. +pub(crate) unsafe fn ch7_pointer_shape, S: bounds::BuiltinDeref, M>(_slot: *mut S) +//@ req true; +//@ ens typeid(::Pointee) == typeid(P) &*& typeid(

::Metadata) == typeid(M); +//@ on_unwind_ens false; +{} diff --git a/verifast-proofs/core/sync/atomic.rs/checks/pointer-view.rs b/verifast-proofs/core/sync/atomic.rs/checks/pointer-view.rs new file mode 100644 index 0000000000000..826d849122275 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/checks/pointer-view.rs @@ -0,0 +1,114 @@ +use crate::sync::atomic::AtomicPtr; + +/*@ +pred_ctor ordinary_slot(slot: **T)(;) = *slot |-> ?value; + +lem prepare_slot(slot: **T, k: lifetime_t) + nonghost_callers_only + req [?q]lifetime_token(k) &*& full_borrow(k, ordinary_slot::(slot)) &*& + slot as usize % std::intrinsics::atomic_align_of::<*T>() == 0 &*& sync::atomic::thin_raw_slot_type::<*T>() == true; + ens [q]lifetime_token(k) &*& [_]frac_borrow(k, sync::atomic::pointer_slot_content::(slot)); +{ + let long = open_full_borrow_strong(k, ordinary_slot::(slot), q); + open ordinary_slot::(slot)(); + { + pred Pre() = *slot |-> ?value; + pred Post() = sync::atomic::pointer_slot_content::(slot)(); + close Pre(); + produce_lem_ptr_chunk atomic_block(Pre, Post)() { + open Pre(); + std::intrinsics::close_atomic_points_to_m(slot, sync::atomic::accepts_pointer); + close sync::atomic::pointer_slot_content::(slot)(); + close Post(); + } { perform_atomically(); } + open Post(); + } + { + pred Ctx() = true; + produce_lem_ptr_chunk full_borrow_convert_strong(Ctx, sync::atomic::pointer_slot_content::(slot), long, ordinary_slot::(slot))() { + open Ctx(); + open sync::atomic::pointer_slot_content::(slot)(); + std::intrinsics::open_atomic_points_to(slot); + close ordinary_slot::(slot)(); + } { + close Ctx(); + close_full_borrow_strong(long, ordinary_slot::(slot), sync::atomic::pointer_slot_content::(slot)); + full_borrow_mono(long, k, sync::atomic::pointer_slot_content::(slot)); + } + } + full_borrow_into_frac(k, sync::atomic::pointer_slot_content::(slot)); +} + +fix pointer_layout(payload: *T) -> bool { + std::intrinsics::atomic_align_of::<*T>() == std::mem::align_of::<*T>() +} + +@*/ +// Appended to the existing ordinary pointer-slot borrow projection in the proof crate. +use crate::sync::atomic::Ordering; + +unsafe fn exchange

(initial: *mut P, replacement: *mut P, after: *mut P, order: Ordering) -> *mut P +//@ req pointer_layout(initial) == true; +//@ ens result == after; +//@ on_unwind_ens false; +{ + let mut value = initial; + let slot = &raw mut value; + unsafe { crate::intrinsics::ch7_pointer_shape::(slot) }; + //@ assert sync::atomic::thin_raw_slot_type::<*P>() == true; + //@ to_u8s_(slot); + //@ from_u8s_(slot); + //@ close ordinary_slot::

(slot)(); + //@ let k = begin_lifetime(); + //@ borrow(k, ordinary_slot::

(slot)); + //@ prepare_slot(slot, k); + { + //@ let_lft 'a = k; + let receiver = unsafe { AtomicPtr::

::from_ptr/*@::<_, 'a>@*/(slot) }; + //@ close sync::atomic::Ordering_own(currentThread, order); + let _previous = receiver.swap(replacement, order); + } + //@ end_lifetime(k); + //@ borrow_end(k, ordinary_slot::

(slot)); + //@ open ordinary_slot::

(slot)(); + let _recovered = unsafe { *slot }; + unsafe { *slot = after }; + unsafe { *slot } +} + +macro_rules! exchange_case { + ($name:ident, $pointee:ty, $size:literal) => { + const _: () = { + assert!(crate::mem::size_of::<$pointee>() == $size); + assert!(crate::mem::size_of::<*mut $pointee>() == crate::mem::size_of::()); + }; + unsafe fn $name(first: *mut $pointee, next: *mut $pointee, last: *mut $pointee, order: Ordering) -> *mut $pointee + //@ req pointer_layout(first) == true; + //@ ens result == last; + //@ on_unwind_ens false; + { unsafe { exchange(first, next, last, order) } } + }; +} + +exchange_case!(zero, (), 0); +exchange_case!(one, u8, 1); +exchange_case!(two, u16, 2); +exchange_case!(three, [u8; 3], 3); +exchange_case!(four, u32, 4); + +unsafe fn slice_metadata(slot: *mut *mut [u8]) +//@ req true; +//@ ens typeid(<[u8] as ptr::metadata::Pointee>::Metadata) == typeid(usize); +//@ on_unwind_ens false; +{ + unsafe { crate::intrinsics::ch7_pointer_shape::<[u8], *mut [u8], usize>(slot) }; + unsafe { crate::intrinsics::ch7_pointer_shape::<[u8], *const [u8], usize>(slot as *mut *const [u8]) } +} + +unsafe fn reference_metadata<'a>(slot: *mut &'a u8) +//@ req true; +//@ ens typeid(::Metadata) == typeid(()); +//@ on_unwind_ens false; +{ + unsafe { crate::intrinsics::ch7_pointer_shape::(slot) } +} diff --git a/verifast-proofs/core/sync/atomic.rs/checks/ranges.rs b/verifast-proofs/core/sync/atomic.rs/checks/ranges.rs new file mode 100644 index 0000000000000..a54bdac686c43 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/checks/ranges.rs @@ -0,0 +1,136 @@ +/*@ +inductive kind = atomic_read | atomic_write | plain_read | plain_write; +inductive classification = permitted | ordinary_race | mixed_size; +fix writes(k: kind) -> bool { k == atomic_write || k == plain_write } +fix ordinary(k: kind) -> bool { k == plain_read || k == plain_write } +fix classify(a: i32, n: i32, op: kind, b: i32, m: i32, other: kind, ordered: bool) -> classification { + if ordered || a + n <= b || b + m <= a || !(writes(op) || writes(other)) { permitted } + else if ordinary(op) || ordinary(other) { ordinary_race } + else if a != b || n != m { mixed_size } + else { permitted } +} + +fix cas_kind(success: bool) -> kind { if success { atomic_write } else { atomic_read } } + + +// Addresses are coordinates in one live allocation, widened before adding +// lengths. The shared-byte witness comes from the actual two access ranges. +inductive effect = load_event | store_event | rmw_event | cas_success | cas_failure; +inductive width = one | two | four | eight | sixteen; + +fix bytes(w: width) -> i32 { + match w { one => 1, two => 2, four => 4, eight => 8, sixteen => 16 } +} + +fix access_kind(e: effect) -> kind { + match e { + load_event => atomic_read, + store_event => atomic_write, + rmw_event => atomic_write, + cas_success => cas_kind(true), + cas_failure => cas_kind(false) + } +} + +lem aligned_gap(a: i128, b: i128, n: i128) + req 0 <= a &*& a < b &*& 0 < n &*& a % n == 0 &*& b % n == 0; + ens a + n <= b; +{ + div_rem_nonneg(a, n); + div_rem_nonneg(b, n); + if b/n <= a/n { mul_mono_l(b/n, a/n, n); } + assert a/n + 1 <= b/n; + mul_mono_l(a/n + 1, b/n, n); +} + +lem disjoint_at_byte(a: i128, n: i32, b: i128, m: i32, at: i128) + req 0 < n &*& 0 < m &*& (a + n <= b || b + m <= a) == true; + ens (a <= at && at < a + n && b <= at && at < b + m) == false; +{} + +lem same_width(a: i128, b: i128, n: i32, shared: i128, left: effect, right: effect) + req 0 <= a &*& 0 <= b &*& 0 < n &*& a % n == 0 &*& b % n == 0 &*& + a <= shared &*& shared < a + n &*& b <= shared &*& shared < b + n; + ens a == b &*& classify(0, n, access_kind(left), 0, n, access_kind(right), false) == permitted; +{ + if a < b { aligned_gap(a, b, n); } + if b < a { aligned_gap(b, a, n); } + match left { load_event => {} store_event => {} rmw_event => {} cas_success => {} cas_failure => {} } + match right { load_event => {} store_event => {} rmw_event => {} cas_success => {} cas_failure => {} } +} + +// A larger naturally aligned power-of-two slot starts and ends on the +// smaller grid. The width and ratio range over all supported integer widths. +lem nested_on_grid(small: i128, unit: width, big: i128, ratio: width, shared: i128) + req 0 <= small &*& 0 <= big &*& bytes(unit) * bytes(ratio) <= 16 &*& + small % bytes(unit) == 0 &*& big % (bytes(unit) * bytes(ratio)) == 0 &*& + small <= shared &*& shared < small + bytes(unit) &*& + big <= shared &*& shared < big + bytes(unit) * bytes(ratio); + ens big <= small &*& small + bytes(unit) <= big + bytes(unit) * bytes(ratio); +{ + match unit { one => {} two => {} four => {} eight => {} sixteen => {} } + match ratio { one => {} two => {} four => {} eight => {} sixteen => {} } + let n = bytes(unit); + let pieces = bytes(ratio); + let total = n * pieces; + div_rem_nonneg(big, total); + let start = big / total; + div_rem_nonneg_unique(big, n, start * pieces, 0); + div_rem_nonneg_unique(big + total, n, (start + 1) * pieces, 0); + if small < big { aligned_gap(small, big, n); } + aligned_gap(small, big + total, n); +} + +lem high_address() + req true; + ens 0xffffffffffffffff + bytes(one) == 0xfffffffffffffff0 + bytes(sixteen) &*& + 0xfffffffffffffff0 + bytes(sixteen) == 0x10000000000000000; +{ + nested_on_grid(0xffffffffffffffff, one, 0xfffffffffffffff0, sixteen, 0xffffffffffffffff); + assert 0xfffffffffffffff0 + bytes(sixteen) == 0x10000000000000000; +} + +lem ordinary_byte(n: i32, j: i32, e: effect, plain_writes: bool, ordered: bool) + req 0 < n &*& 0 <= j &*& j < n; + ens classify(0, n, access_kind(e), j, 1, if plain_writes { plain_write } else { plain_read }, ordered) == + if !ordered && (plain_writes || (e != load_event && e != cas_failure)) { ordinary_race } else { permitted }; +{ + match e { load_event => {} store_event => {} rmw_event => {} cas_success => {} cas_failure => {} } +} + +// Both operations belong to the larger interval and share a byte. No +// unsigned-address end calculation enters the normalized classifier. +lem different_widths(n: i32, m: i32, offset: i32, left: effect, right: effect, ordered: bool) + req 0 < m &*& m < n &*& 0 <= offset &*& offset + m <= n; + ens classify(0, n, access_kind(left), offset, m, access_kind(right), ordered) == + if !ordered && (left != load_event && left != cas_failure || right != load_event && right != cas_failure) { + mixed_size + } else { permitted }; +{ + match left { load_event => {} store_event => {} rmw_event => {} cas_success => {} cas_failure => {} } + match right { load_event => {} store_event => {} rmw_event => {} cas_success => {} cas_failure => {} } +} + +lem integer_pair(small: i128, unit: width, big: i128, ratio: width, shared: i128, wide_op: effect, small_op: effect, ordered: bool) + req 0 <= small &*& 0 <= big &*& bytes(unit) * bytes(ratio) <= 16 &*& + small % bytes(unit) == 0 &*& big % (bytes(unit) * bytes(ratio)) == 0 &*& + small <= shared &*& shared < small + bytes(unit) &*& + big <= shared &*& shared < big + bytes(unit) * bytes(ratio); + ens big <= small &*& small + bytes(unit) <= big + bytes(unit) * bytes(ratio) &*& + (ratio != one || big == small) == true &*& + classify(0, bytes(unit) * bytes(ratio), access_kind(wide_op), small - big, bytes(unit), access_kind(small_op), ordered) == + if ratio != one && !ordered && (wide_op != load_event && wide_op != cas_failure || small_op != load_event && small_op != cas_failure) { + mixed_size + } else { permitted }; +{ + nested_on_grid(small, unit, big, ratio, shared); + match unit { one => {} two => {} four => {} eight => {} sixteen => {} } + match ratio { + one => { same_width(big, small, bytes(unit), shared, wide_op, small_op); } + two => { different_widths(bytes(unit) * 2, bytes(unit), small - big, wide_op, small_op, ordered); } + four => { different_widths(bytes(unit) * 4, bytes(unit), small - big, wide_op, small_op, ordered); } + eight => { different_widths(bytes(unit) * 8, bytes(unit), small - big, wide_op, small_op, ordered); } + sixteen => { different_widths(bytes(unit) * 16, bytes(unit), small - big, wide_op, small_op, ordered); } + } +} +@*/ diff --git a/verifast-proofs/core/sync/atomic.rs/checks/readonly.rs b/verifast-proofs/core/sync/atomic.rs/checks/readonly.rs new file mode 100644 index 0000000000000..b050573aad756 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/checks/readonly.rs @@ -0,0 +1,390 @@ +// Read-only fractional borrow witnesses for AtomicBool and AtomicU32. +// Models concurrent atomic loads and guaranteed-failing compare_exchange(_weak) +// alongside ordinary non-atomic reads on native 8-bit CAS targets. +use super::{ + AtomicBool, AtomicU32, Ordering, atomic_compare_exchange, atomic_compare_exchange_weak, + atomic_store, +}; + +/*@ +pred keep_u8(p: *u8, f: real, v: u8) = [f](*p |-> v); +pred keep_u32(p: *u32, f: real, v: u32) = [f](*p |-> v); +pred_ctor writable_bool_slot(slot: *bool, value: bool)(;) = + *slot |-> value; + +lem prepare_bool_readonly(slot: *bool, k: lifetime_t, af: real, value: bool) + nonghost_callers_only + req [?q]lifetime_token(k) &*& 0 < af &*& af < 1 &*& full_borrow(k, writable_bool_slot(slot, value)); + ens [q]lifetime_token(k) &*& [_]sync::atomic::ro_bool_borrow(k, slot, af, value); +{ + let long = open_full_borrow_strong(k, writable_bool_slot(slot, value), q); + open writable_bool_slot(slot, value)(); + { + pred Pre() = 0 < af &*& af < 1 &*& *slot |-> value; + pred Post() = sync::atomic::ro_bool_content(slot, af, value)(); + close Pre(); + produce_lem_ptr_chunk atomic_block(Pre, Post)() { + open Pre(); + points_to_limits(slot); + points_to_bool_to_u8(slot); + if value {} else {} + close keep_u8(slot as *u8, 1 - af, if value { 1 } else { 0 }); + std::intrinsics::atomic_align_of_u8(); + div_rem_nonneg(slot as usize, 1); + std::intrinsics::close_atomic_points_to_m(slot as *u8, (sync::atomic::is_bool_byte)(if value { 1 } else { 0 })); + open keep_u8(slot as *u8, 1 - af, if value { 1 } else { 0 }); + close sync::atomic::ro_bool_content(slot, af, value)(); + close Post(); + } { perform_atomically(); } + open Post(); + } + { + pred Ctx() = 0 < af &*& af < 1; + produce_lem_ptr_chunk full_borrow_convert_strong(Ctx, sync::atomic::ro_bool_content(slot, af, value), long, writable_bool_slot(slot, value))() { + open Ctx(); + open sync::atomic::ro_bool_content(slot, af, value)(); + std::intrinsics::open_atomic_points_to(slot as *u8); + if value {} else {} + merge_fractions points_to::(slot as *u8, _); + points_to_u8_to_bool(slot as *u8); + close writable_bool_slot(slot, value)(); + } { + close Ctx(); + close_full_borrow_strong(long, writable_bool_slot(slot, value), sync::atomic::ro_bool_content(slot, af, value)); + full_borrow_mono(long, k, sync::atomic::ro_bool_content(slot, af, value)); + } + } + full_borrow_into_frac(k, sync::atomic::ro_bool_content(slot, af, value)); + close sync::atomic::ro_bool_borrow(k, slot, af, value); + leak sync::atomic::ro_bool_borrow(k, slot, af, value); +} + +pred_ctor writable_u32_slot(slot: *u32, value: u32)(;) = + *slot |-> value; + +lem prepare_u32_readonly(slot: *u32, k: lifetime_t, af: real, value: u32) + nonghost_callers_only + req [?q]lifetime_token(k) &*& 0 < af &*& af < 1 &*& full_borrow(k, writable_u32_slot(slot, value)) &*& + slot as usize % std::intrinsics::atomic_align_of::() == 0; + ens [q]lifetime_token(k) &*& [_]sync::atomic::ro_u32_borrow(k, slot, af, value); +{ + let long = open_full_borrow_strong(k, writable_u32_slot(slot, value), q); + open writable_u32_slot(slot, value)(); + { + pred Pre() = 0 < af &*& af < 1 &*& *slot |-> value &*& + slot as usize % std::intrinsics::atomic_align_of::() == 0; + pred Post() = sync::atomic::ro_u32_content(slot, af, value)(); + close Pre(); + produce_lem_ptr_chunk atomic_block(Pre, Post)() { + open Pre(); + points_to_limits(slot); + close keep_u32(slot, 1 - af, value); + std::intrinsics::close_atomic_points_to_m(slot, (sync::atomic::is_u32_val)(value)); + open keep_u32(slot, 1 - af, value); + close sync::atomic::ro_u32_content(slot, af, value)(); + close Post(); + } { perform_atomically(); } + open Post(); + } + { + pred Ctx() = 0 < af &*& af < 1; + produce_lem_ptr_chunk full_borrow_convert_strong(Ctx, sync::atomic::ro_u32_content(slot, af, value), long, writable_u32_slot(slot, value))() { + open Ctx(); + open sync::atomic::ro_u32_content(slot, af, value)(); + std::intrinsics::open_atomic_points_to(slot); + merge_fractions points_to::(slot, _); + close writable_u32_slot(slot, value)(); + } { + close Ctx(); + close_full_borrow_strong(long, writable_u32_slot(slot, value), sync::atomic::ro_u32_content(slot, af, value)); + full_borrow_mono(long, k, sync::atomic::ro_u32_content(slot, af, value)); + } + } + full_borrow_into_frac(k, sync::atomic::ro_u32_content(slot, af, value)); + close sync::atomic::ro_u32_borrow(k, slot, af, value); + leak sync::atomic::ro_u32_borrow(k, slot, af, value); +} +@*/ + +unsafe fn ro_bool_from_ptr<'a>(ptr: *mut bool) -> &'a AtomicBool +//@ req [?q]lifetime_token('a) &*& [_]sync::atomic::ro_bool_borrow('a, ptr, ?af, ?val) &*& ref_origin(ptr) == ptr; +//@ ens [q]lifetime_token('a) &*& [_]sync::atomic::ro_bool_borrow('a, ref_origin(result), af, val) &*& [_]frac_borrow('a, ref_initialized_(result)) &*& ref_origin(result) as pointer == ptr as pointer; +//@ on_unwind_ens false; +{ + let view = unsafe { AtomicBool::from_ptr/*@::<'a>@*/(ptr) }; + view +} + +unsafe fn ro_bool_load(receiver: &AtomicBool, order: Ordering) -> bool +//@ req [?q]lifetime_token(?k) &*& [_]sync::atomic::ro_bool_borrow(k, ref_origin(receiver), ?af, ?val) &*& [_]frac_borrow(k, ref_initialized_(receiver)) &*& order != sync::atomic::Ordering::Release &*& order != sync::atomic::Ordering::AcqRel; +//@ ens [q]lifetime_token(k); +//@ on_unwind_ens false; +{ + //@ close sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ leak sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ close sync::atomic::Ordering_own(currentThread, order); + receiver.load(order) +} + +unsafe fn ro_bool_store(receiver: &AtomicBool, val: bool, order: Ordering) +//@ req [?q]lifetime_token(?k) &*& [_]frac_borrow(k, sync::atomic::rw_bool_content(ref_origin(receiver))) &*& [_]frac_borrow(k, ref_initialized_(receiver)) &*& order != sync::atomic::Ordering::Acquire &*& order != sync::atomic::Ordering::AcqRel; +//@ ens [q]lifetime_token(k); +//@ on_unwind_ens false; +{ + //@ let f = open_frac_borrow(k, sync::atomic::rw_bool_content(ref_origin(receiver)), q/2); + //@ open [f]sync::atomic::rw_bool_content(ref_origin(receiver))(); + //@ close sync::atomic::ordering_access(ref_origin(receiver) as *u8, true, f, 1, sync::atomic::valid_bool_byte); + //@ if val {} else {} + unsafe { + atomic_store::<_, /* VOLATILE */ false>(receiver.as_ptr().cast::(), val as u8, order); + } + //@ close [f]sync::atomic::rw_bool_content(ref_origin(receiver))(); + //@ close_frac_borrow(f, sync::atomic::rw_bool_content(ref_origin(receiver))); +} + +unsafe fn ro_bool_compare_exchange( + receiver: &AtomicBool, + current: bool, + new: bool, + success: Ordering, + failure: Ordering, +) -> Result +//@ req [?q]lifetime_token(?k) &*& [_]sync::atomic::ro_bool_borrow(k, ref_origin(receiver), ?af, ?actual) &*& [_]frac_borrow(k, ref_initialized_(receiver)) &*& (if af == 1 { new == actual || current != actual } else { current != actual }) &*& failure != sync::atomic::Ordering::Release &*& failure != sync::atomic::Ordering::AcqRel; +//@ ens [q]lifetime_token(k) &*& result::Result_own::(currentThread, result) &*& match result { Result::Ok(v) => af == 1 &*& v == actual &*& v == current, Result::Err(v) => v == actual &*& v != current }; +//@ on_unwind_ens false; +{ + //@ open sync::atomic::ro_bool_borrow(k, ref_origin(receiver), af, actual); + //@ let f = open_frac_borrow(k, sync::atomic::ro_bool_content(ref_origin(receiver), af, actual), q/2); + //@ open [f]sync::atomic::ro_bool_content(ref_origin(receiver), af, actual)(); + //@ if actual {} else {} + //@ if current {} else {} + //@ if new {} else {} + //@ close sync::atomic::ordering_access(ref_origin(receiver) as *u8, true, f, af, (sync::atomic::is_bool_byte)(if actual { 1 } else { 0 })); + let raw = unsafe { + atomic_compare_exchange(receiver.as_ptr().cast::(), current as u8, new as u8, success, failure) + }; + //@ close [f]sync::atomic::ro_bool_content(ref_origin(receiver), af, actual)(); + //@ close_frac_borrow(f, sync::atomic::ro_bool_content(ref_origin(receiver), af, actual)); + //@ open result::Result_own::(currentThread, raw); + /*@ match raw { + Result::Ok(v) => { + open u8_own(currentThread, v); + close bool_own(currentThread, v != 0); + close result::Result_own::(currentThread, result::Result::Ok(v != 0)); + } + Result::Err(v) => { + open u8_own(currentThread, v); + close bool_own(currentThread, v != 0); + close result::Result_own::(currentThread, result::Result::Err(v != 0)); + } + } @*/ + match raw { + Ok(x) => Ok(x != 0), + Err(x) => Err(x != 0), + } +} + +unsafe fn ro_bool_compare_exchange_weak( + receiver: &AtomicBool, + current: bool, + new: bool, + success: Ordering, + failure: Ordering, +) -> Result +//@ req [?q]lifetime_token(?k) &*& [_]sync::atomic::ro_bool_borrow(k, ref_origin(receiver), ?af, ?actual) &*& [_]frac_borrow(k, ref_initialized_(receiver)) &*& (if af == 1 { new == actual || current != actual } else { current != actual }) &*& failure != sync::atomic::Ordering::Release &*& failure != sync::atomic::Ordering::AcqRel; +//@ ens [q]lifetime_token(k) &*& result::Result_own::(currentThread, result) &*& match result { Result::Ok(v) => af == 1 &*& v == actual &*& v == current, Result::Err(v) => v == actual }; +//@ on_unwind_ens false; +{ + //@ open sync::atomic::ro_bool_borrow(k, ref_origin(receiver), af, actual); + //@ let f = open_frac_borrow(k, sync::atomic::ro_bool_content(ref_origin(receiver), af, actual), q/2); + //@ open [f]sync::atomic::ro_bool_content(ref_origin(receiver), af, actual)(); + //@ if actual {} else {} + //@ if current {} else {} + //@ if new {} else {} + //@ close sync::atomic::ordering_access(ref_origin(receiver) as *u8, true, f, af, (sync::atomic::is_bool_byte)(if actual { 1 } else { 0 })); + let raw = unsafe { + atomic_compare_exchange_weak(receiver.as_ptr().cast::(), current as u8, new as u8, success, failure) + }; + //@ close [f]sync::atomic::ro_bool_content(ref_origin(receiver), af, actual)(); + //@ close_frac_borrow(f, sync::atomic::ro_bool_content(ref_origin(receiver), af, actual)); + //@ open result::Result_own::(currentThread, raw); + /*@ match raw { + Result::Ok(v) => { + open u8_own(currentThread, v); + close bool_own(currentThread, v != 0); + close result::Result_own::(currentThread, result::Result::Ok(v != 0)); + } + Result::Err(v) => { + open u8_own(currentThread, v); + close bool_own(currentThread, v != 0); + close result::Result_own::(currentThread, result::Result::Err(v != 0)); + } + } @*/ + match raw { + Ok(x) => Ok(x != 0), + Err(x) => Err(x != 0), + } +} + +unsafe fn ro_u32_from_ptr<'a>(ptr: *mut u32) -> &'a AtomicU32 +//@ req [?q]lifetime_token('a) &*& [_]sync::atomic::ro_u32_borrow('a, ptr, ?af, ?val) &*& ref_origin(ptr) == ptr; +//@ ens [q]lifetime_token('a) &*& [_]sync::atomic::ro_u32_borrow('a, ref_origin(result), af, val) &*& [_]frac_borrow('a, ref_initialized_(result)) &*& ref_origin(result) as *_ == ptr as *_; +//@ on_unwind_ens false; +{ + let view = unsafe { AtomicU32::from_ptr/*@::<'a>@*/(ptr) }; + view +} + +unsafe fn ro_u32_load(receiver: &AtomicU32, order: Ordering) -> u32 +//@ req [?q]lifetime_token(?k) &*& [_]sync::atomic::ro_u32_borrow(k, ref_origin(receiver), ?af, ?val) &*& [_]frac_borrow(k, ref_initialized_(receiver)) &*& order != sync::atomic::Ordering::Release &*& order != sync::atomic::Ordering::AcqRel; +//@ ens [q]lifetime_token(k); +//@ on_unwind_ens false; +{ + //@ close sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ leak sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ close sync::atomic::Ordering_own(currentThread, order); + receiver.load(order) +} + +unsafe fn ro_u32_store(receiver: &AtomicU32, val: u32, order: Ordering) +//@ req [?q]lifetime_token(?k) &*& [_]frac_borrow(k, sync::atomic::rw_u32_content(ref_origin(receiver))) &*& [_]frac_borrow(k, ref_initialized_(receiver)) &*& order != sync::atomic::Ordering::Acquire &*& order != sync::atomic::Ordering::AcqRel; +//@ ens [q]lifetime_token(k); +//@ on_unwind_ens false; +{ + //@ let f = open_frac_borrow(k, sync::atomic::rw_u32_content(ref_origin(receiver)), q/2); + //@ open [f]sync::atomic::rw_u32_content(ref_origin(receiver))(); + //@ close sync::atomic::ordering_access(ref_origin(receiver) as *u32, true, f, 1, sync::atomic::accepts_word); + unsafe { + atomic_store::<_, /* VOLATILE */ false>(receiver.as_ptr(), val, order); + } + //@ close [f]sync::atomic::rw_u32_content(ref_origin(receiver))(); + //@ close_frac_borrow(f, sync::atomic::rw_u32_content(ref_origin(receiver))); +} + +unsafe fn ro_u32_compare_exchange( + receiver: &AtomicU32, + current: u32, + new: u32, + success: Ordering, + failure: Ordering, +) -> Result +//@ req [?q]lifetime_token(?k) &*& [_]sync::atomic::ro_u32_borrow(k, ref_origin(receiver), ?af, ?actual) &*& [_]frac_borrow(k, ref_initialized_(receiver)) &*& (if af == 1 { new == actual || current != actual } else { current != actual }) &*& failure != sync::atomic::Ordering::Release &*& failure != sync::atomic::Ordering::AcqRel; +//@ ens [q]lifetime_token(k) &*& result::Result_own::(currentThread, result) &*& match result { Result::Ok(v) => af == 1 &*& v == actual &*& v == current, Result::Err(v) => v == actual &*& v != current }; +//@ on_unwind_ens false; +{ + //@ open sync::atomic::ro_u32_borrow(k, ref_origin(receiver), af, actual); + //@ let f = open_frac_borrow(k, sync::atomic::ro_u32_content(ref_origin(receiver), af, actual), q/2); + //@ open [f]sync::atomic::ro_u32_content(ref_origin(receiver), af, actual)(); + //@ close sync::atomic::ordering_access(ref_origin(receiver) as *u32, true, f, af, (sync::atomic::is_u32_val)(actual)); + let out = unsafe { + atomic_compare_exchange(receiver.as_ptr(), current, new, success, failure) + }; + //@ close [f]sync::atomic::ro_u32_content(ref_origin(receiver), af, actual)(); + //@ close_frac_borrow(f, sync::atomic::ro_u32_content(ref_origin(receiver), af, actual)); + out +} + +unsafe fn ro_u32_compare_exchange_weak( + receiver: &AtomicU32, + current: u32, + new: u32, + success: Ordering, + failure: Ordering, +) -> Result +//@ req [?q]lifetime_token(?k) &*& [_]sync::atomic::ro_u32_borrow(k, ref_origin(receiver), ?af, ?actual) &*& [_]frac_borrow(k, ref_initialized_(receiver)) &*& (if af == 1 { new == actual || current != actual } else { current != actual }) &*& failure != sync::atomic::Ordering::Release &*& failure != sync::atomic::Ordering::AcqRel; +//@ ens [q]lifetime_token(k) &*& result::Result_own::(currentThread, result) &*& match result { Result::Ok(v) => af == 1 &*& v == actual &*& v == current, Result::Err(v) => v == actual }; +//@ on_unwind_ens false; +{ + //@ open sync::atomic::ro_u32_borrow(k, ref_origin(receiver), af, actual); + //@ let f = open_frac_borrow(k, sync::atomic::ro_u32_content(ref_origin(receiver), af, actual), q/2); + //@ open [f]sync::atomic::ro_u32_content(ref_origin(receiver), af, actual)(); + //@ close sync::atomic::ordering_access(ref_origin(receiver) as *u32, true, f, af, (sync::atomic::is_u32_val)(actual)); + let out = unsafe { + atomic_compare_exchange_weak(receiver.as_ptr(), current, new, success, failure) + }; + //@ close [f]sync::atomic::ro_u32_content(ref_origin(receiver), af, actual)(); + //@ close_frac_borrow(f, sync::atomic::ro_u32_content(ref_origin(receiver), af, actual)); + out +} + +unsafe fn ro_bool_local_round_trip(initial: bool, next: bool, after: bool) -> (bool, bool) +//@ req true; +//@ ens result.0 == initial &*& result.1 == after; +//@ on_unwind_ens false; +{ + let mut value = initial; + let p = &raw mut value; + //@ to_u8s_(p); + //@ from_u8s_(p); + //@ close writable_bool_slot(p, initial)(); + //@ let k = begin_lifetime(); + //@ borrow(k, writable_bool_slot(p, initial)); + //@ prepare_bool_readonly(p, k, 1/2, initial); + let plain; + { + //@ let_lft 'a = k; + let view = unsafe { AtomicBool::from_ptr/*@::<'a>@*/(p) }; + // CH7_RO_BOOL_LIVE + //@ open sync::atomic::ro_bool_borrow(k, p, 1/2, initial); + //@ let fp = open_frac_borrow(k, sync::atomic::ro_bool_content(p, 1/2, initial), 1/4); + //@ open [fp]sync::atomic::ro_bool_content(p, 1/2, initial)(); + //@ if initial {} else {} + plain = unsafe { *p.cast::() != 0 }; + //@ close [fp]sync::atomic::ro_bool_content(p, 1/2, initial)(); + //@ close_frac_borrow(fp, sync::atomic::ro_bool_content(p, 1/2, initial)); + //@ close sync::atomic::Ordering_own(currentThread, sync::atomic::Ordering::Relaxed); + let _loaded = view.load(Ordering::Relaxed); + let strong = unsafe { ro_bool_compare_exchange(view, !initial, next, Ordering::Relaxed, Ordering::Relaxed) }; + //@ open result::Result_own::(currentThread, strong); + /*@ match strong { Result::Ok(v) => {} Result::Err(v) => { open bool_own(currentThread, v); assert v == initial; } } @*/ + let weak = unsafe { ro_bool_compare_exchange_weak(view, !initial, next, Ordering::Relaxed, Ordering::Relaxed) }; + //@ open result::Result_own::(currentThread, weak); + /*@ match weak { Result::Ok(v) => {} Result::Err(v) => { open bool_own(currentThread, v); assert v == initial; } } @*/ + } + //@ end_lifetime(k); + //@ borrow_end(k, writable_bool_slot(p, initial)); + //@ open writable_bool_slot(p, initial)(); + unsafe { *p = after }; + (plain, unsafe { *p }) +} + +unsafe fn ro_u32_local_round_trip(initial: u32, next: u32, after: u32) -> (u32, u32) +//@ req std::intrinsics::atomic_align_of::() == std::mem::align_of::(); +//@ ens result.0 == initial &*& result.1 == after; +//@ on_unwind_ens false; +{ + let mut value = initial; + let p = &raw mut value; + //@ to_u8s_(p); + //@ from_u8s_(p); + //@ close writable_u32_slot(p, initial)(); + //@ let k = begin_lifetime(); + //@ borrow(k, writable_u32_slot(p, initial)); + //@ prepare_u32_readonly(p, k, 1/2, initial); + let mismatch = if initial == 0 { 1 } else { 0 }; + let plain; + { + //@ let_lft 'a = k; + let view = unsafe { AtomicU32::from_ptr/*@::<'a>@*/(p) }; + // CH7_RO_U32_LIVE + //@ open sync::atomic::ro_u32_borrow(k, p, 1/2, initial); + //@ let fp = open_frac_borrow(k, sync::atomic::ro_u32_content(p, 1/2, initial), 1/4); + //@ open [fp]sync::atomic::ro_u32_content(p, 1/2, initial)(); + plain = unsafe { *p }; + //@ close [fp]sync::atomic::ro_u32_content(p, 1/2, initial)(); + //@ close_frac_borrow(fp, sync::atomic::ro_u32_content(p, 1/2, initial)); + //@ close sync::atomic::Ordering_own(currentThread, sync::atomic::Ordering::Relaxed); + let _loaded = view.load(Ordering::Relaxed); + let strong = unsafe { ro_u32_compare_exchange(view, mismatch, next, Ordering::Relaxed, Ordering::Relaxed) }; + //@ open result::Result_own::(currentThread, strong); + /*@ match strong { Result::Ok(v) => {} Result::Err(v) => { open u32_own(currentThread, v); assert v == initial; } } @*/ + let weak = unsafe { ro_u32_compare_exchange_weak(view, mismatch, next, Ordering::Relaxed, Ordering::Relaxed) }; + //@ open result::Result_own::(currentThread, weak); + /*@ match weak { Result::Ok(v) => {} Result::Err(v) => { open u32_own(currentThread, v); assert v == initial; } } @*/ + } + //@ end_lifetime(k); + //@ borrow_end(k, writable_u32_slot(p, initial)); + //@ open writable_u32_slot(p, initial)(); + unsafe { *p = after }; + (plain, unsafe { *p }) +} diff --git a/verifast-proofs/core/sync/atomic.rs/checks/storage.rs b/verifast-proofs/core/sync/atomic.rs/checks/storage.rs new file mode 100644 index 0000000000000..fc2ea07c8ad62 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/checks/storage.rs @@ -0,0 +1,335 @@ +#![allow(dead_code)] + +/*@ +fix any_u32(v: u32) -> bool { true } + +pred_ctor Primitive_content(p: *u32)(;) = *p |-> ?v; +pred_ctor AtomicInt_content(p: *u32)(;) = + std::intrinsics::atomic_points_to::(p, 1, any_u32); + +pred opened_client(id: i32, p: *u32, k: lifetime_t, q: real, f: real) = + [f]std::intrinsics::atomic_points_to::(p, 1, any_u32) &*& + close_frac_borrow_token(f, AtomicInt_content(p), q, k); + +// The end token remains for Primitive_content. The only borrow returned to clients +// is for AtomicInt_content. Adapted from PR #803, full/verified/atomic.rs. +lem prepare_atomic_integer(p: *u32, k: lifetime_t) + nonghost_callers_only + req [?q]lifetime_token(k) &*& full_borrow(k, Primitive_content(p)) &*& + p as usize % std::intrinsics::atomic_align_of::() == 0; + ens [q]lifetime_token(k) &*& [_]frac_borrow(k, AtomicInt_content(p)); +{ + let klong = open_full_borrow_strong(k, Primitive_content(p), q); + open Primitive_content(p)(); + { + pred Pre() = *p |-> ?v; + pred Post() = AtomicInt_content(p)(); + close Pre(); + produce_lem_ptr_chunk atomic_block(Pre, Post)() { + open Pre(); + std::intrinsics::close_atomic_points_to_m(p, any_u32); + close AtomicInt_content(p)(); + close Post(); + } { perform_atomically(); } + open Post(); + } + { + pred Ctx() = true; + produce_lem_ptr_chunk full_borrow_convert_strong(Ctx, AtomicInt_content(p), klong, Primitive_content(p))() { + open Ctx(); + open AtomicInt_content(p)(); + std::intrinsics::open_atomic_points_to(p); + close Primitive_content(p)(); + } { + close Ctx(); + close_full_borrow_strong(klong, Primitive_content(p), AtomicInt_content(p)); + full_borrow_mono(klong, k, AtomicInt_content(p)); + } + } + full_borrow_into_frac(k, AtomicInt_content(p)); +} + +// A full word and even a fractional *possibly uninitialized* byte cannot +// coexist. An ordinary initialized read needs the stronger points_to chunk. +lem word_excludes_byte(p: *u32, i: usize) + req *p |-> ?v &*& 0 <= i &*& i < 4 &*& [?g]points_to_::((p as *u8) + i, ?extra) &*& 0 < g; + ens false; +{ + to_u8s_(p); + let base = p as *u8; + array__split(base, i); + open array_(base + i, 4 - i, _); + merge_fractions points_to_::(base + i, _); + points_to__limits(base + i); +} + +lem atomic_storage_excludes_byte(p: *u32, i: usize) + req std::intrinsics::atomic_points_to(p, 1, ?inv_) &*& 0 <= i &*& i < 4 &*& + [?g]points_to_::((p as *u8) + i, ?extra) &*& 0 < g; + ens false; +{ + std::intrinsics::open_atomic_points_to(p); + word_excludes_byte(p, i); +} + +// The ordinary access may start before the protected word or span its end. +// Equality is between pointers derived from the allocation, at the common byte. +lem word_excludes_overlapping_access(p: *u32, other: *T, i: usize, j: usize) + req *p |-> ?v &*& [?g]points_to_(other, ?other_value) &*& 0 < g &*& + 0 <= i &*& i < 4 &*& 0 <= j &*& j < std::mem::size_of::() &*& + (p as *u8) + i == (other as *u8) + j; + ens false; +{ + to_u8s_(other); + let base = other as *u8; + array__split(base, j); + open [g]array_(base + j, std::mem::size_of::() - j, _); + word_excludes_byte(p, i); +} + +lem sealed_word_excludes_byte(p: *u32, k: lifetime_t, i: usize) + nonghost_callers_only + req lifetime_token(k) &*& borrow_end_token(k, Primitive_content(p)) &*& + 0 <= i &*& i < 4 &*& [?g]points_to_::((p as *u8) + i, ?extra) &*& 0 < g; + ens false; +{ + end_lifetime(k); + borrow_end(k, Primitive_content(p)); + open Primitive_content(p)(); + word_excludes_byte(p, i); +} + +// Frame the alleged extra permission through closing B and recovering the +// ordinary word. These are precisely the resources built in storage_round_trip +// after A returned. This proves incompatibility for every positive g, not +// just that a particular raw read failed in the verifier. +lem outstanding_client_excludes_byte(p: *u32, k: lifetime_t, q: real, f: real, i: usize) + nonghost_callers_only + req 0 < q &*& q < 1 &*& [1 - q]lifetime_token(k) &*& + opened_client(1, p, k, q, f) &*& borrow_end_token(k, Primitive_content(p)) &*& + 0 <= i &*& i < 4 &*& [?g]points_to_::((p as *u8) + i, ?extra) &*& 0 < g; + ens false; +{ + open opened_client(1, p, k, q, f); + close [f]AtomicInt_content(p)(); + close_frac_borrow(f, AtomicInt_content(p)); + sealed_word_excludes_byte(p, k, i); +} + +lem two_open_clients_exclude_byte(p: *u32, k: lifetime_t, q: real, fa: real, fb: real, i: usize) + nonghost_callers_only + req 0 < q &*& q < 1 &*& opened_client(0, p, k, 1 - q, fa) &*& + opened_client(1, p, k, q, fb) &*& borrow_end_token(k, Primitive_content(p)) &*& + 0 <= i &*& i < 4 &*& [?g]points_to_::((p as *u8) + i, ?extra) &*& 0 < g; + ens false; +{ + open opened_client(0, p, k, 1 - q, fa); + close [fa]AtomicInt_content(p)(); + close_frac_borrow(fa, AtomicInt_content(p)); + outstanding_client_excludes_byte(p, k, q, fb, i); +} +@*/ + +unsafe fn ordinary_byte_read(p: *const u8) -> u8 +//@ req [?g](*p |-> ?v); +//@ ens [g](*p |-> v) &*& result == v; +//@ on_unwind_ens false; +{ + unsafe { *p } +} + +unsafe fn half_byte_read(p: *const u8) -> u8 +//@ req [1/2](*p |-> ?v); +//@ ens [1/2](*p |-> v) &*& result == v; +//@ on_unwind_ens false; +{ + unsafe { ordinary_byte_read(p) } +} + +unsafe fn initialized_byte_control(base: *mut u8, index: usize) -> u8 +//@ req base[..4] |-> ?vs &*& index < 4; +//@ ens base[..4] |-> vs &*& result == nth(index, vs); +//@ on_unwind_ens false; +{ + let byte = unsafe { base.add(index) }; + //@ array_split(base, index); + //@ open array(byte, 4 - index, _); + let result = unsafe { half_byte_read(byte) }; + //@ nth_append_r(take(index, vs), drop(index, vs), 0); + //@ close array(byte, 4 - index, _); + //@ array_join(base); + result +} + +unsafe fn storage_round_trip(p: *mut u32) +//@ req *p |-> ?v &*& p as usize % std::intrinsics::atomic_align_of::() == 0; +//@ ens *p |-> 30; +//@ on_unwind_ens false; +{ + //@ points_to_limits(p); + let _byte = unsafe { p.cast::().add(1) }; + //@ close Primitive_content(p)(); + //@ let k = begin_lifetime(); + //@ borrow(k, Primitive_content(p)); + //@ prepare_atomic_integer(p, k); + //@ let fa = open_frac_borrow(k, AtomicInt_content(p), 1/2); + //@ open [fa]AtomicInt_content(p)(); + //@ close opened_client(0, p, k, 1/2, fa); + //@ let fb = open_frac_borrow(k, AtomicInt_content(p), 1/2); + //@ open [fb]AtomicInt_content(p)(); + //@ close opened_client(1, p, k, 1/2, fb); + //@ open opened_client(0, p, k, 1/2, fa); + //@ close [fa]AtomicInt_content(p)(); + //@ close_frac_borrow(fa, AtomicInt_content(p)); + // CH7_OUTSTANDING_CLIENT + //@ open opened_client(1, p, k, 1/2, fb); + //@ close [fb]AtomicInt_content(p)(); + //@ close_frac_borrow(fb, AtomicInt_content(p)); + //@ end_lifetime(k); + //@ borrow_end(k, Primitive_content(p)); + //@ open Primitive_content(p)(); + let _after = unsafe { *p }; + unsafe { p.write(30) }; +} + +// The second word is deliberately accessed while the first borrow is open. +unsafe fn disjoint_word(p: *mut u32) +//@ req p[..2] |-> ?vs &*& p as usize % std::intrinsics::atomic_align_of::() == 0; +//@ ens p[..2] |-> ?after &*& nth(1, after) == 30; +//@ on_unwind_ens false; +{ + let second = unsafe { p.add(1) }; + //@ open array(p, 2, vs); + //@ open array(second, 1, _); + //@ close Primitive_content(p)(); + //@ let k = begin_lifetime(); + //@ borrow(k, Primitive_content(p)); + //@ prepare_atomic_integer(p, k); + //@ let fa = open_frac_borrow(k, AtomicInt_content(p), 1/2); + //@ open [fa]AtomicInt_content(p)(); + //@ close opened_client(0, p, k, 1/2, fa); + let _other = unsafe { *second }; + unsafe { second.write(30) }; + //@ open opened_client(0, p, k, 1/2, fa); + //@ close [fa]AtomicInt_content(p)(); + //@ close_frac_borrow(fa, AtomicInt_content(p)); + //@ end_lifetime(k); + //@ borrow_end(k, Primitive_content(p)); + //@ open Primitive_content(p)(); + //@ close array(second, 1, _); + //@ close array(p, 2, _); +} + +unsafe fn initialized_word_client() +//@ req std::intrinsics::atomic_align_of::() == std::mem::align_of::(); +//@ ens true; +//@ on_unwind_ens false; +{ + let mut word: u32 = 0; + let p = &raw mut word; + // The round trip retains the value and gives the alignment fact. + //@ to_u8s_(p); + //@ from_u8s_(p); + unsafe { storage_round_trip(p) }; + //@ assert word == 30; +} + +// At the recovered address an ordinary byte write needs full storage, but +// does not need the old byte value. The following read uses that explicit write. +unsafe fn recovered_byte_write_read(p: *mut u32) -> u8 +//@ req *p |-> ?v &*& p as usize % std::intrinsics::atomic_align_of::() == 0; +//@ ens array_(p as *u8, 4, ?bs) &*& result == 55; +//@ on_unwind_ens false; +{ + //@ points_to_limits(p); + let byte = unsafe { p.cast::().add(1) }; + unsafe { storage_round_trip(p) }; + //@ to_u8s_(p); + //@ array__split(p as *u8, 1); + //@ open array_(byte, 3, _); + unsafe { byte.write(55) }; + let value = unsafe { half_byte_read(byte) }; + //@ close array_(byte, 3, _); + //@ array__join(p as *u8); + value +} + +/*@ +fix is_exact_word(target: u32, v: u32) -> bool { v == target } +pred_ctor Readonly_half_word(p: *u32, v: u32)(;) = [1/2](*p |-> v); +pred_ctor Readonly_atomic_word(p: *u32, v: u32)(;) = + std::intrinsics::atomic_points_to::(p, 1/2, (is_exact_word)(v)); + +// A fractional atomic read-only view still excludes any ordinary write (fraction 1). +lem readonly_atomic_excludes_ordinary_write(p: *u32, af: real) + req 0 < af &*& std::intrinsics::atomic_points_to(p, af, ?inv_) &*& *p |-> ?w; + ens false; +{ + std::intrinsics::open_atomic_points_to(p); + merge_fractions points_to(p, _); + points_to_limits(p); +} + +// Conversely, any retained ordinary read fraction excludes a full writable atomic_points_to(_, 1, _). +lem ordinary_read_excludes_writable_atomic(p: *u32, g: real) + req 0 < g &*& [g](*p |-> ?v) &*& std::intrinsics::atomic_points_to(p, 1, ?inv_); + ens false; +{ + std::intrinsics::open_atomic_points_to(p); + merge_fractions points_to(p, _); + points_to_limits(p); +} +@*/ + +unsafe fn readonly_coexists_with_ordinary_read(p: *mut u32) -> u32 +//@ req *p |-> ?v &*& p as usize % std::intrinsics::atomic_align_of::() == 0; +//@ ens *p |-> 77 &*& result == v; +//@ on_unwind_ens false; +{ + //@ close Readonly_half_word(p, v)(); + //@ let k = begin_lifetime(); + //@ borrow(k, Readonly_half_word(p, v)); + /*@ + { + let klong = open_full_borrow_strong(k, Readonly_half_word(p, v), 1); + open Readonly_half_word(p, v)(); + { + pred Pre() = [1/2](*p |-> v); + pred Post() = Readonly_atomic_word(p, v)(); + close Pre(); + produce_lem_ptr_chunk atomic_block(Pre, Post)() { + open Pre(); + std::intrinsics::close_atomic_points_to_m(p, (is_exact_word)(v)); + close Readonly_atomic_word(p, v)(); + close Post(); + } { perform_atomically(); } + open Post(); + } + { + pred Ctx() = true; + produce_lem_ptr_chunk full_borrow_convert_strong(Ctx, Readonly_atomic_word(p, v), klong, Readonly_half_word(p, v))() { + open Ctx(); + open Readonly_atomic_word(p, v)(); + std::intrinsics::open_atomic_points_to(p); + close Readonly_half_word(p, v)(); + } { + close Ctx(); + close_full_borrow_strong(klong, Readonly_half_word(p, v), Readonly_atomic_word(p, v)); + full_borrow_mono(klong, k, Readonly_atomic_word(p, v)); + } + } + full_borrow_into_frac(k, Readonly_atomic_word(p, v)); + } + @*/ + //@ let f = open_frac_borrow(k, Readonly_atomic_word(p, v), 1/2); + //@ open [f]Readonly_atomic_word(p, v)(); + // Ordinary non-atomic read coexists with the live fractional atomic read-only view. + let plain = unsafe { *p }; + //@ close [f]Readonly_atomic_word(p, v)(); + //@ close_frac_borrow(f, Readonly_atomic_word(p, v)); + //@ end_lifetime(k); + //@ borrow_end(k, Readonly_half_word(p, v)); + //@ open Readonly_half_word(p, v)(); + unsafe { p.write(77) }; + plain +} diff --git a/verifast-proofs/core/sync/atomic.rs/checks/threads/boolean.rs b/verifast-proofs/core/sync/atomic.rs/checks/threads/boolean.rs new file mode 100644 index 0000000000000..042ebad74326e --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/checks/threads/boolean.rs @@ -0,0 +1,193 @@ +#![no_std] +#![allow(dead_code)] +extern crate platform; + +use core::sync::atomic::{AtomicBool, Ordering}; +use platform::threading::{fork_joinable, join, Thread}; + +/*@ +pred_ctor returned(k: lifetime_t, q: real)() = [q]lifetime_token(k); +pred_ctor transfer(k: lifetime_t, q: real, p: *bool)(arg: *std::sync::atomic::Atomic, post: pred()) = + [q]lifetime_token(k) &*& [_]frac_borrow(k, std::sync::atomic::bool_slot_content(ref_origin(arg))) &*& + [_]frac_borrow(k, ref_initialized_(arg)) &*& ref_origin(arg) as *bool == p &*& post == returned(k, q); +@*/ + +unsafe fn write_true<'a>(slot: &'a AtomicBool) +//@ req [?q]lifetime_token('a) &*& [_]frac_borrow('a, std::sync::atomic::bool_slot_content(ref_origin(slot))) &*& [_]frac_borrow('a, ref_initialized_(slot)); +//@ ens [q]lifetime_token('a); +//@ on_unwind_ens false; +{ + slot.store(true, Ordering::Relaxed); + let _ = slot.fetch_nand(true, Ordering::Relaxed); +} + +unsafe fn write_false<'a>(slot: &'a AtomicBool) +//@ req [?q]lifetime_token('a) &*& [_]frac_borrow('a, std::sync::atomic::bool_slot_content(ref_origin(slot))) &*& [_]frac_borrow('a, ref_initialized_(slot)); +//@ ens [q]lifetime_token('a); +//@ on_unwind_ens false; +{ + let _ = slot.fetch_and(false, Ordering::Relaxed); +} + +unsafe fn read_value<'a>(slot: &'a AtomicBool) +//@ req [?q]lifetime_token('a) &*& [_]frac_borrow('a, std::sync::atomic::bool_slot_content(ref_origin(slot))) &*& [_]frac_borrow('a, ref_initialized_(slot)); +//@ ens [q]lifetime_token('a); +//@ on_unwind_ens false; +{ + let _value = slot.load(Ordering::Relaxed); +} + +#[allow(improper_ctypes_definitions)] +unsafe extern "C" fn fork_bool<'a>(run: unsafe fn(&'a AtomicBool), data: &'a AtomicBool) -> Thread +//@ req [_]platform::threading::is_thread_run_joinable::<&'a std::sync::atomic::Atomic>(run, ?pre) &*& pre(data, ?post) &*& [_]frac_borrow('a, ref_initialized_(data)) &*& [?s]lifetime_token('a); +//@ ens platform::threading::Thread(result, post) &*& [s]lifetime_token('a); +//@ on_unwind_ens false; +{ + unsafe { fork_joinable(run, data) } +} + +#[allow(improper_ctypes_definitions)] +unsafe extern "C" fn join_bool(thread: Thread) +//@ req platform::threading::Thread(thread, ?post); +//@ ens post(); +//@ on_unwind_ens false; +{ + unsafe { join(thread) } +} + +#[repr(C)] +struct Fields { value: bool, spare: u8 } + +const _: () = assert!(core::mem::offset_of!(Fields, spare) == 1); + +// Mode 0 runs two writers, mode 1 runs a writer and a reader, and the +// remaining modes run two readers. All modes send the very same reference. +pub unsafe fn bool_pair(mode: u8, initial: bool) -> (bool, u8) +//@ req true; +//@ ens (result.1 == 0 || result.1 == 1) &*& (result.0 == (result.1 == 1)); +//@ on_unwind_ens false; +{ + let mut fields = Fields { value: initial, spare: 73 }; + let base = &raw mut fields; + let p = &raw mut fields.value; + let spare = &raw mut fields.spare; + let byte = p.cast::(); + //@ to_u8s_(p); + //@ from_u8s_(p); + //@ close ordinary_bool(p)(); + //@ let k = begin_lifetime(); + //@ borrow(k, ordinary_bool(p)); + //@ prepare_bool(p, k); + { + //@ let_lft 'a = k; + let view = unsafe { AtomicBool::from_ptr/*@::<'a>@*/(p) }; + let a = if mode < 2 { + /*@ + produce_fn_ptr_chunk platform::threading::thread_run_joinable<&'a std::sync::atomic::Atomic>(write_true)(transfer(k, 1/8, p))(arg) { + open transfer(k, 1/8, p)(arg, ?post); + call(); + close returned(k, 1/8)(); + } + @*/ + //@ close transfer(k, 1/8, p)(view, returned(k, 1/8)); + unsafe { fork_bool/*@::<'a>@*/(write_true, view) } + } else { + /*@ + produce_fn_ptr_chunk platform::threading::thread_run_joinable<&'a std::sync::atomic::Atomic>(read_value)(transfer(k, 1/8, p))(arg) { + open transfer(k, 1/8, p)(arg, ?post); + call(); + close returned(k, 1/8)(); + } + @*/ + //@ close transfer(k, 1/8, p)(view, returned(k, 1/8)); + unsafe { fork_bool/*@::<'a>@*/(read_value, view) } + }; + let b = if mode == 0 { + /*@ + produce_fn_ptr_chunk platform::threading::thread_run_joinable<&'a std::sync::atomic::Atomic>(write_false)(transfer(k, 1/8, p))(arg) { + open transfer(k, 1/8, p)(arg, ?post); + call(); + close returned(k, 1/8)(); + } + @*/ + //@ close transfer(k, 1/8, p)(view, returned(k, 1/8)); + unsafe { fork_bool/*@::<'a>@*/(write_false, view) } + } else { + /*@ + produce_fn_ptr_chunk platform::threading::thread_run_joinable<&'a std::sync::atomic::Atomic>(read_value)(transfer(k, 1/8, p))(arg) { + open transfer(k, 1/8, p)(arg, ?post); + call(); + close returned(k, 1/8)(); + } + @*/ + //@ close transfer(k, 1/8, p)(view, returned(k, 1/8)); + unsafe { fork_bool/*@::<'a>@*/(read_value, view) } + }; + unsafe { join_bool(a) }; + //@ open returned(k, 1/8)(); + // CH7_B_OUTSTANDING + let separate = unsafe { *spare }; + //@ assert separate == 73; + unsafe { *spare = 85 }; + unsafe { join_bool(b) }; + //@ open returned(k, 1/8)(); + } + //@ end_lifetime(k); + //@ borrow_end(k, ordinary_bool(p)); + //@ open ordinary_bool(p)(); + let recovered = unsafe { *p }; + //@ points_to_bool_to_u8(p); + let encoding = unsafe { *byte }; + //@ if recovered {} else {} + //@ assert encoding == if recovered { 1 } else { 0 }; + //@ points_to_u8_to_bool(byte); + unsafe { *p = initial }; + //@ close Fields_value_(base, _); + //@ close Fields_spare_(base, _); + (recovered, encoding) +} +/*@ +pred_ctor ordinary_bool(slot: *bool)(;) = *slot |-> ?value; + +lem prepare_bool(slot: *bool, k: lifetime_t) + nonghost_callers_only + req [?q]lifetime_token(k) &*& full_borrow(k, ordinary_bool(slot)); + ens [q]lifetime_token(k) &*& [_]frac_borrow(k, std::sync::atomic::bool_slot_content(slot)); +{ + let long = open_full_borrow_strong(k, ordinary_bool(slot), q); + open ordinary_bool(slot)(); + { + pred Pre() = *slot |-> ?value; + pred Post() = std::sync::atomic::bool_slot_content(slot)(); + close Pre(); + produce_lem_ptr_chunk atomic_block(Pre, Post)() { + open Pre(); + assert *slot |-> ?value; + points_to_limits(slot); + points_to_bool_to_u8(slot); + if value {} else {} + std::intrinsics::atomic_align_of_u8(); + div_rem_nonneg(slot as usize, 1); + std::intrinsics::close_atomic_points_to_m(slot as *u8, std::sync::atomic::valid_bool_byte); + close std::sync::atomic::bool_slot_content(slot)(); + close Post(); + } { perform_atomically(); } + open Post(); + } + { + pred Ctx() = true; + produce_lem_ptr_chunk full_borrow_convert_strong(Ctx, std::sync::atomic::bool_slot_content(slot), long, ordinary_bool(slot))() { + open Ctx(); + open std::sync::atomic::bool_slot_content(slot)(); + std::intrinsics::open_atomic_points_to(slot as *u8); + points_to_u8_to_bool(slot as *u8); + close ordinary_bool(slot)(); + } { + close Ctx(); + close_full_borrow_strong(long, ordinary_bool(slot), std::sync::atomic::bool_slot_content(slot)); + full_borrow_mono(long, k, std::sync::atomic::bool_slot_content(slot)); + } + } + full_borrow_into_frac(k, std::sync::atomic::bool_slot_content(slot)); +} +@*/ diff --git a/verifast-proofs/core/sync/atomic.rs/checks/threads/pointer.rs b/verifast-proofs/core/sync/atomic.rs/checks/threads/pointer.rs new file mode 100644 index 0000000000000..da574b9a9adc8 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/checks/threads/pointer.rs @@ -0,0 +1,166 @@ +#![no_std] +#![allow(dead_code)] +extern crate platform; + +use core::sync::atomic::{AtomicPtr, Ordering}; +use platform::threading::{fork_joinable, join, Thread}; + +/*@ +pred_ctor returned(k: lifetime_t, q: real)() = [q]lifetime_token(k); + +pred_ctor transfer(k: lifetime_t, q: real, slot: **u8)(arg: *std::sync::atomic::Atomic<*u8>, post: pred()) = + [q]lifetime_token(k) &*& [_]frac_borrow(k, std::sync::atomic::thread_pointer_content::(ref_origin(arg))) &*& + [_]frac_borrow(k, ref_initialized_(arg)) &*& ref_origin(arg) as pointer == slot as pointer &*& post == returned(k, q); +@*/ + +unsafe fn compare_null<'a>(slot: &'a AtomicPtr) +//@ req [?q]lifetime_token('a) &*& [_]frac_borrow('a, std::sync::atomic::thread_pointer_content::(ref_origin(slot))) &*& [_]frac_borrow('a, ref_initialized_(slot)); +//@ ens [q]lifetime_token('a); +//@ on_unwind_ens false; +{ + let _ = slot.swap(0 as *mut u8, Ordering::Relaxed); + let value = slot as *const AtomicPtr as *mut u8; + let outcome = slot.compare_exchange(0 as *mut u8, value, Ordering::Relaxed, Ordering::Relaxed); + //@ open std::result::Result_own::<*u8, *u8>(currentThread, outcome); + /*@ match outcome { + Result::Ok(v) => { open raw_ptr_own::()(currentThread, v); } + Result::Err(v) => { open raw_ptr_own::()(currentThread, v); } + } @*/ +} + +unsafe fn compare_own_address<'a>(slot: &'a AtomicPtr) +//@ req [?q]lifetime_token('a) &*& [_]frac_borrow('a, std::sync::atomic::thread_pointer_content::(ref_origin(slot))) &*& [_]frac_borrow('a, ref_initialized_(slot)); +//@ ens [q]lifetime_token('a); +//@ on_unwind_ens false; +{ + let value = slot as *const AtomicPtr as *mut u8; + let outcome = slot.compare_exchange_weak(value, 0 as *mut u8, Ordering::Relaxed, Ordering::Relaxed); + //@ open std::result::Result_own::<*u8, *u8>(currentThread, outcome); + /*@ match outcome { + Result::Ok(v) => { open raw_ptr_own::()(currentThread, v); } + Result::Err(v) => { open raw_ptr_own::()(currentThread, v); } + } @*/ +} + +#[allow(improper_ctypes_definitions)] +unsafe extern "C" fn fork_pointer<'a>(run: unsafe fn(&'a AtomicPtr), data: &'a AtomicPtr) -> Thread +//@ req [_]platform::threading::is_thread_run_joinable::<&'a std::sync::atomic::Atomic<*u8>>(run, ?pre) &*& pre(data, ?post) &*& [_]frac_borrow('a, ref_initialized_(data)) &*& [?s]lifetime_token('a); +//@ ens platform::threading::Thread(result, post) &*& [s]lifetime_token('a); +//@ on_unwind_ens false; +{ + unsafe { fork_joinable(run, data) } +} + +#[allow(improper_ctypes_definitions)] +unsafe extern "C" fn join_pointer(thread: Thread) +//@ req platform::threading::Thread(thread, ?post); +//@ ens post(); +//@ on_unwind_ens false; +{ + unsafe { join(thread) } +} + +#[repr(C)] +struct Fields { value: *mut u8, spare: u8 } +const _: () = { + assert!(core::mem::size_of::>() == core::mem::size_of::<*mut u8>()); + assert!(core::mem::align_of::>() == core::mem::align_of::<*mut u8>()); + assert!(core::mem::offset_of!(Fields, spare) == core::mem::size_of::<*mut u8>()); +}; + +pub unsafe fn pointer_pair(initial: *mut u8) -> (bool, bool) +//@ req std::intrinsics::atomic_align_of::<*u8>() == std::mem::align_of::<*u8>(); +//@ ens result.1 == true; +//@ on_unwind_ens false; +{ + let mut fields = Fields { value: initial, spare: 73 }; + let base = &raw mut fields; + let p = &raw mut fields.value; + let spare = &raw mut fields.spare; + //@ to_u8s_(p); + //@ from_u8s_(p); + //@ close ordinary_slot::(p)(); + //@ let k = begin_lifetime(); + //@ borrow(k, ordinary_slot::(p)); + //@ prepare_slot(p, k); + { + //@ let_lft 'a = k; + let view = unsafe { AtomicPtr::::from_ptr/*@::<_, 'a>@*/(p) }; + /*@ + produce_fn_ptr_chunk platform::threading::thread_run_joinable<&'a std::sync::atomic::Atomic<*u8>>(compare_null)(transfer(k, 1/8, p))(arg) { + open transfer(k, 1/8, p)(arg, ?post); + call(); + close returned(k, 1/8)(); + } + @*/ + //@ close transfer(k, 1/8, p)(view, returned(k, 1/8)); + let a = unsafe { fork_pointer/*@::<'a>@*/(compare_null, view) }; + /*@ + produce_fn_ptr_chunk platform::threading::thread_run_joinable<&'a std::sync::atomic::Atomic<*u8>>(compare_own_address)(transfer(k, 1/8, p))(arg) { + open transfer(k, 1/8, p)(arg, ?post); + call(); + close returned(k, 1/8)(); + } + @*/ + //@ close transfer(k, 1/8, p)(view, returned(k, 1/8)); + let b = unsafe { fork_pointer/*@::<'a>@*/(compare_own_address, view) }; + unsafe { join_pointer(a) }; + //@ open returned(k, 1/8)(); + // CH7_B_OUTSTANDING + let separate = unsafe { *spare }; + //@ assert separate == 73; + unsafe { *spare = 85 }; + unsafe { join_pointer(b) }; + //@ open returned(k, 1/8)(); + } + //@ end_lifetime(k); + //@ borrow_end(k, ordinary_slot::(p)); + //@ open ordinary_slot::(p)(); + let observed = unsafe { *p }; + let worker_value = observed == initial || observed == 0 as *mut u8 || observed == p as *mut u8; + unsafe { *p = initial }; + let recovered = unsafe { *p }; + //@ close Fields_value_(base, _); + //@ close Fields_spare_(base, _); + (worker_value, recovered == initial) +} +/*@ +pred_ctor ordinary_slot(slot: **T)(;) = *slot |-> ?value; + +lem prepare_slot(slot: **T, k: lifetime_t) + nonghost_callers_only + req [?q]lifetime_token(k) &*& full_borrow(k, ordinary_slot::(slot)) &*& + slot as usize % std::intrinsics::atomic_align_of::<*T>() == 0; + ens [q]lifetime_token(k) &*& [_]frac_borrow(k, std::sync::atomic::thread_pointer_content::(slot)); +{ + let long = open_full_borrow_strong(k, ordinary_slot::(slot), q); + open ordinary_slot::(slot)(); + { + pred Pre() = *slot |-> ?value; + pred Post() = std::sync::atomic::thread_pointer_content::(slot)(); + close Pre(); + produce_lem_ptr_chunk atomic_block(Pre, Post)() { + open Pre(); + std::intrinsics::close_atomic_points_to_m(slot, std::sync::atomic::accepts_pointer); + close std::sync::atomic::thread_pointer_content::(slot)(); + close Post(); + } { perform_atomically(); } + open Post(); + } + { + pred Ctx() = true; + produce_lem_ptr_chunk full_borrow_convert_strong(Ctx, std::sync::atomic::thread_pointer_content::(slot), long, ordinary_slot::(slot))() { + open Ctx(); + open std::sync::atomic::thread_pointer_content::(slot)(); + std::intrinsics::open_atomic_points_to(slot); + close ordinary_slot::(slot)(); + } { + close Ctx(); + close_full_borrow_strong(long, ordinary_slot::(slot), std::sync::atomic::thread_pointer_content::(slot)); + full_borrow_mono(long, k, std::sync::atomic::thread_pointer_content::(slot)); + } + } + full_borrow_into_frac(k, std::sync::atomic::thread_pointer_content::(slot)); +} + +@*/ diff --git a/verifast-proofs/core/sync/atomic.rs/checks/threads/readonly.rs b/verifast-proofs/core/sync/atomic.rs/checks/threads/readonly.rs new file mode 100644 index 0000000000000..2bcc21de7702f --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/checks/threads/readonly.rs @@ -0,0 +1,409 @@ +#![no_std] +#![allow(dead_code)] +extern crate platform; + +use core::sync::atomic::{AtomicBool, AtomicU32, Ordering}; +use platform::threading::{fork_joinable, join, Thread}; + +/*@ +pred_ctor returned_lft(k: lifetime_t, q: real)() = [q]lifetime_token(k); + +pred_ctor transfer_bool_ro(k: lifetime_t, q: real, p: *bool, val: bool)(arg: *std::sync::atomic::Atomic, post: pred()) = + [q]lifetime_token(k) &*& [_]std::sync::atomic::ro_bool_borrow(k, ref_origin(arg), 1/2, val) &*& + [_]frac_borrow(k, ref_initialized_(arg)) &*& ref_origin(arg) as *bool == p &*& post == returned_lft(k, q); + +pred_ctor transfer_plain_u8(k: lifetime_t, q: real, p: *u8, val: bool)(arg: *u8, post: pred()) = + arg == p &*& [q]lifetime_token(k) &*& [_]std::sync::atomic::ro_bool_borrow(k, p as *bool, 1/2, val) &*& + post == returned_lft(k, q); + +pred_ctor transfer_u32_ro(k: lifetime_t, q: real, p: *u32, val: u32)(arg: *std::sync::atomic::Atomic, post: pred()) = + [q]lifetime_token(k) &*& [_]std::sync::atomic::ro_u32_borrow(k, ref_origin(arg), 1/2, val) &*& + [_]frac_borrow(k, ref_initialized_(arg)) &*& ref_origin(arg) as *u32 == p &*& post == returned_lft(k, q); + +pred_ctor transfer_plain_u32(k: lifetime_t, q: real, p: *u32, val: u32)(arg: *u32, post: pred()) = + arg == p &*& [q]lifetime_token(k) &*& [_]std::sync::atomic::ro_u32_borrow(k, p, 1/2, val) &*& + post == returned_lft(k, q); +@*/ + +unsafe fn ro_bool_worker_true<'a>(slot: &'a AtomicBool) +//@ req [?q]lifetime_token('a) &*& [_]std::sync::atomic::ro_bool_borrow('a, ref_origin(slot), 1/2, true) &*& [_]frac_borrow('a, ref_initialized_(slot)); +//@ ens [q]lifetime_token('a); +//@ on_unwind_ens false; +{ + let _seen = slot.load(Ordering::Relaxed); + // CH7_RO_BOOL_WORKER_A + let strong = slot.compare_exchange(false, false, Ordering::Relaxed, Ordering::Relaxed); + //@ open std::result::Result_own::(currentThread, strong); + /*@ match strong { + Result::Ok(v) => {} + Result::Err(v) => { open bool_own(currentThread, v); assert v == true; } + } @*/ + let weak = slot.compare_exchange_weak(false, true, Ordering::Relaxed, Ordering::Relaxed); + //@ open std::result::Result_own::(currentThread, weak); + /*@ match weak { + Result::Ok(v) => {} + Result::Err(v) => { open bool_own(currentThread, v); assert v == true; } + } @*/ +} + +unsafe fn ro_bool_worker_false<'a>(slot: &'a AtomicBool) +//@ req [?q]lifetime_token('a) &*& [_]std::sync::atomic::ro_bool_borrow('a, ref_origin(slot), 1/2, false) &*& [_]frac_borrow('a, ref_initialized_(slot)); +//@ ens [q]lifetime_token('a); +//@ on_unwind_ens false; +{ + let _seen = slot.load(Ordering::Relaxed); + let strong = slot.compare_exchange(true, true, Ordering::Relaxed, Ordering::Relaxed); + //@ open std::result::Result_own::(currentThread, strong); + /*@ match strong { + Result::Ok(v) => {} + Result::Err(v) => { open bool_own(currentThread, v); assert v == false; } + } @*/ + let weak = slot.compare_exchange_weak(true, false, Ordering::Relaxed, Ordering::Relaxed); + //@ open std::result::Result_own::(currentThread, weak); + /*@ match weak { + Result::Ok(v) => {} + Result::Err(v) => { open bool_own(currentThread, v); assert v == false; } + } @*/ +} + +unsafe fn ro_plain_u8_worker(ptr: *const u8) +//@ req [?q]lifetime_token(?k) &*& [_]std::sync::atomic::ro_bool_borrow(k, ptr as *bool, 1/2, ?val); +//@ ens [q]lifetime_token(k); +//@ on_unwind_ens false; +{ + //@ open std::sync::atomic::ro_bool_borrow(k, ptr as *bool, 1/2, val); + //@ let fp = open_frac_borrow(k, std::sync::atomic::ro_bool_content(ptr as *bool, 1/2, val), q); + //@ open [fp]std::sync::atomic::ro_bool_content(ptr as *bool, 1/2, val)(); + let _plain = unsafe { *ptr }; + // CH7_RO_BOOL_WORKER_B + //@ close [fp]std::sync::atomic::ro_bool_content(ptr as *bool, 1/2, val)(); + //@ close_frac_borrow(fp, std::sync::atomic::ro_bool_content(ptr as *bool, 1/2, val)); +} + +unsafe fn ro_u32_worker_zero<'a>(slot: &'a AtomicU32) +//@ req [?q]lifetime_token('a) &*& [_]std::sync::atomic::ro_u32_borrow('a, ref_origin(slot), 1/2, 0) &*& [_]frac_borrow('a, ref_initialized_(slot)); +//@ ens [q]lifetime_token('a); +//@ on_unwind_ens false; +{ + let _seen = slot.load(Ordering::Relaxed); + // CH7_RO_U32_WORKER_A + let strong = slot.compare_exchange(1, 0, Ordering::Relaxed, Ordering::Relaxed); + //@ open std::result::Result_own::(currentThread, strong); + /*@ match strong { + Result::Ok(v) => {} + Result::Err(v) => { open u32_own(currentThread, v); assert v == 0; } + } @*/ + let weak = slot.compare_exchange_weak(1, 2, Ordering::Relaxed, Ordering::Relaxed); + //@ open std::result::Result_own::(currentThread, weak); + /*@ match weak { + Result::Ok(v) => {} + Result::Err(v) => { open u32_own(currentThread, v); assert v == 0; } + } @*/ +} + +unsafe fn ro_u32_worker_nonzero<'a>(slot: &'a AtomicU32) +//@ req [?q]lifetime_token('a) &*& [_]std::sync::atomic::ro_u32_borrow('a, ref_origin(slot), 1/2, ?val) &*& val != 0 &*& [_]frac_borrow('a, ref_initialized_(slot)); +//@ ens [q]lifetime_token('a); +//@ on_unwind_ens false; +{ + let _seen = slot.load(Ordering::Relaxed); + let strong = slot.compare_exchange(0, 0, Ordering::Relaxed, Ordering::Relaxed); + //@ open std::result::Result_own::(currentThread, strong); + /*@ match strong { + Result::Ok(v) => {} + Result::Err(v) => { open u32_own(currentThread, v); assert v == val; } + } @*/ + let weak = slot.compare_exchange_weak(0, 2, Ordering::Relaxed, Ordering::Relaxed); + //@ open std::result::Result_own::(currentThread, weak); + /*@ match weak { + Result::Ok(v) => {} + Result::Err(v) => { open u32_own(currentThread, v); assert v == val; } + } @*/ +} + +unsafe fn ro_plain_u32_worker(ptr: *const u32) +//@ req [?q]lifetime_token(?k) &*& [_]std::sync::atomic::ro_u32_borrow(k, ptr, 1/2, ?val); +//@ ens [q]lifetime_token(k); +//@ on_unwind_ens false; +{ + //@ open std::sync::atomic::ro_u32_borrow(k, ptr, 1/2, val); + //@ let fp = open_frac_borrow(k, std::sync::atomic::ro_u32_content(ptr, 1/2, val), q); + //@ open [fp]std::sync::atomic::ro_u32_content(ptr, 1/2, val)(); + let _plain = unsafe { *ptr }; + // CH7_RO_U32_WORKER_B + //@ close [fp]std::sync::atomic::ro_u32_content(ptr, 1/2, val)(); + //@ close_frac_borrow(fp, std::sync::atomic::ro_u32_content(ptr, 1/2, val)); +} + +#[allow(improper_ctypes_definitions)] +unsafe extern "C" fn fork_ro_bool<'a>(run: unsafe fn(&'a AtomicBool), data: &'a AtomicBool) -> Thread +//@ req [_]platform::threading::is_thread_run_joinable::<&'a std::sync::atomic::Atomic>(run, ?pre) &*& pre(data, ?post) &*& [_]frac_borrow('a, ref_initialized_(data)) &*& [?s]lifetime_token('a); +//@ ens platform::threading::Thread(result, post) &*& [s]lifetime_token('a); +//@ on_unwind_ens false; +{ + unsafe { fork_joinable(run, data) } +} + +#[allow(improper_ctypes_definitions)] +unsafe extern "C" fn fork_plain_u8(run: unsafe fn(*const u8), data: *const u8) -> Thread +//@ req [_]platform::threading::is_thread_run_joinable::<*u8>(run, ?pre) &*& pre(data, ?post); +//@ ens platform::threading::Thread(result, post); +//@ on_unwind_ens false; +{ + unsafe { fork_joinable(run, data) } +} + +#[allow(improper_ctypes_definitions)] +unsafe extern "C" fn fork_ro_u32<'a>(run: unsafe fn(&'a AtomicU32), data: &'a AtomicU32) -> Thread +//@ req [_]platform::threading::is_thread_run_joinable::<&'a std::sync::atomic::Atomic>(run, ?pre) &*& pre(data, ?post) &*& [_]frac_borrow('a, ref_initialized_(data)) &*& [?s]lifetime_token('a); +//@ ens platform::threading::Thread(result, post) &*& [s]lifetime_token('a); +//@ on_unwind_ens false; +{ + unsafe { fork_joinable(run, data) } +} + +#[allow(improper_ctypes_definitions)] +unsafe extern "C" fn fork_plain_u32(run: unsafe fn(*const u32), data: *const u32) -> Thread +//@ req [_]platform::threading::is_thread_run_joinable::<*u32>(run, ?pre) &*& pre(data, ?post); +//@ ens platform::threading::Thread(result, post); +//@ on_unwind_ens false; +{ + unsafe { fork_joinable(run, data) } +} + +#[allow(improper_ctypes_definitions)] +unsafe extern "C" fn join_ro(thread: Thread) +//@ req platform::threading::Thread(thread, ?post); +//@ ens post(); +//@ on_unwind_ens false; +{ + unsafe { join(thread) } +} + +// Worker A runs AtomicBool::{load, compare_exchange, compare_exchange_weak} (guaranteed failing) +// while Worker B concurrently reads the exact same byte non-atomically. +// Both draw from a single writable stack slot split via prepare_bool_readonly. +pub unsafe fn bool_readonly_pair(initial: bool) -> (bool, bool) +//@ req true; +//@ ens result.0 == initial &*& result.1 == !initial; +//@ on_unwind_ens false; +{ + let mut storage = initial; + let p = &raw mut storage; + let byte = p.cast::() as *const u8; + //@ to_u8s_(p); + //@ from_u8s_(p); + //@ close writable_bool_slot(p, initial)(); + //@ let k = begin_lifetime(); + //@ borrow(k, writable_bool_slot(p, initial)); + //@ prepare_bool_readonly(p, k, 1/2, initial); + { + //@ let_lft 'a = k; + let view = unsafe { AtomicBool::from_ptr/*@::<'a>@*/(p) }; + let a = if initial { + /*@ + produce_fn_ptr_chunk platform::threading::thread_run_joinable<&'a std::sync::atomic::Atomic>(ro_bool_worker_true)(transfer_bool_ro(k, 1/8, p, true))(arg) { + open transfer_bool_ro(k, 1/8, p, true)(arg, ?post); + call(); + close returned_lft(k, 1/8)(); + } + @*/ + //@ close transfer_bool_ro(k, 1/8, p, true)(view, returned_lft(k, 1/8)); + unsafe { fork_ro_bool/*@::<'a>@*/(ro_bool_worker_true, view) } + } else { + /*@ + produce_fn_ptr_chunk platform::threading::thread_run_joinable<&'a std::sync::atomic::Atomic>(ro_bool_worker_false)(transfer_bool_ro(k, 1/8, p, false))(arg) { + open transfer_bool_ro(k, 1/8, p, false)(arg, ?post); + call(); + close returned_lft(k, 1/8)(); + } + @*/ + //@ close transfer_bool_ro(k, 1/8, p, false)(view, returned_lft(k, 1/8)); + unsafe { fork_ro_bool/*@::<'a>@*/(ro_bool_worker_false, view) } + }; + /*@ + produce_fn_ptr_chunk platform::threading::thread_run_joinable<*u8>(ro_plain_u8_worker)(transfer_plain_u8(k, 1/8, byte, initial))(arg) { + open transfer_plain_u8(k, 1/8, byte, initial)(arg, ?post); + call(); + close returned_lft(k, 1/8)(); + } + @*/ + //@ close transfer_plain_u8(k, 1/8, byte, initial)(byte, returned_lft(k, 1/8)); + let b = unsafe { fork_plain_u8(ro_plain_u8_worker, byte) }; + unsafe { join_ro(b) }; + //@ open returned_lft(k, 1/8)(); + // CH7_RO_BOOL_A_OUTSTANDING + unsafe { join_ro(a) }; + //@ open returned_lft(k, 1/8)(); + } + //@ end_lifetime(k); + //@ borrow_end(k, writable_bool_slot(p, initial)); + //@ open writable_bool_slot(p, initial)(); + let plain = unsafe { *p }; + unsafe { *p = !initial }; + (plain, unsafe { *p }) +} + +// Worker A runs AtomicU32::{load, compare_exchange, compare_exchange_weak} (guaranteed failing) +// while Worker B concurrently reads the exact same word non-atomically. +// Both draw from a single writable stack slot split via prepare_u32_readonly. +pub unsafe fn u32_readonly_pair(initial: u32) -> (u32, u32) +//@ req std::intrinsics::atomic_align_of::() == std::mem::align_of::(); +//@ ens result.0 == initial &*& result.1 == 99; +//@ on_unwind_ens false; +{ + let mut storage = initial; + let p = &raw mut storage; + let cp = p as *const u32; + //@ to_u8s_(p); + //@ from_u8s_(p); + //@ close writable_u32_slot(p, initial)(); + //@ let k = begin_lifetime(); + //@ borrow(k, writable_u32_slot(p, initial)); + //@ prepare_u32_readonly(p, k, 1/2, initial); + { + //@ let_lft 'a = k; + let view = unsafe { AtomicU32::from_ptr/*@::<'a>@*/(p) }; + let a = if initial == 0 { + /*@ + produce_fn_ptr_chunk platform::threading::thread_run_joinable<&'a std::sync::atomic::Atomic>(ro_u32_worker_zero)(transfer_u32_ro(k, 1/8, p, 0))(arg) { + open transfer_u32_ro(k, 1/8, p, 0)(arg, ?post); + call(); + close returned_lft(k, 1/8)(); + } + @*/ + //@ close transfer_u32_ro(k, 1/8, p, 0)(view, returned_lft(k, 1/8)); + unsafe { fork_ro_u32/*@::<'a>@*/(ro_u32_worker_zero, view) } + } else { + /*@ + produce_fn_ptr_chunk platform::threading::thread_run_joinable<&'a std::sync::atomic::Atomic>(ro_u32_worker_nonzero)(transfer_u32_ro(k, 1/8, p, initial))(arg) { + open transfer_u32_ro(k, 1/8, p, initial)(arg, ?post); + call(); + close returned_lft(k, 1/8)(); + } + @*/ + //@ close transfer_u32_ro(k, 1/8, p, initial)(view, returned_lft(k, 1/8)); + unsafe { fork_ro_u32/*@::<'a>@*/(ro_u32_worker_nonzero, view) } + }; + /*@ + produce_fn_ptr_chunk platform::threading::thread_run_joinable<*u32>(ro_plain_u32_worker)(transfer_plain_u32(k, 1/8, cp, initial))(arg) { + open transfer_plain_u32(k, 1/8, cp, initial)(arg, ?post); + call(); + close returned_lft(k, 1/8)(); + } + @*/ + //@ close transfer_plain_u32(k, 1/8, cp, initial)(cp, returned_lft(k, 1/8)); + let b = unsafe { fork_plain_u32(ro_plain_u32_worker, cp) }; + unsafe { join_ro(b) }; + //@ open returned_lft(k, 1/8)(); + // CH7_RO_U32_A_OUTSTANDING + unsafe { join_ro(a) }; + //@ open returned_lft(k, 1/8)(); + } + //@ end_lifetime(k); + //@ borrow_end(k, writable_u32_slot(p, initial)); + //@ open writable_u32_slot(p, initial)(); + let plain = unsafe { *p }; + unsafe { *p = 99 }; + (plain, unsafe { *p }) +} + +/*@ +pred keep_u8(p: *u8, f: real, v: u8) = [f](*p |-> v); +pred keep_u32(p: *u32, f: real, v: u32) = [f](*p |-> v); +pred_ctor writable_bool_slot(slot: *bool, value: bool)(;) = + *slot |-> value; + +lem prepare_bool_readonly(slot: *bool, k: lifetime_t, af: real, value: bool) + nonghost_callers_only + req [?q]lifetime_token(k) &*& 0 < af &*& af < 1 &*& full_borrow(k, writable_bool_slot(slot, value)); + ens [q]lifetime_token(k) &*& [_]std::sync::atomic::ro_bool_borrow(k, slot, af, value); +{ + let long = open_full_borrow_strong(k, writable_bool_slot(slot, value), q); + open writable_bool_slot(slot, value)(); + { + pred Pre() = 0 < af &*& af < 1 &*& *slot |-> value; + pred Post() = std::sync::atomic::ro_bool_content(slot, af, value)(); + close Pre(); + produce_lem_ptr_chunk atomic_block(Pre, Post)() { + open Pre(); + points_to_limits(slot); + points_to_bool_to_u8(slot); + if value {} else {} + close keep_u8(slot as *u8, 1 - af, if value { 1 } else { 0 }); + std::intrinsics::atomic_align_of_u8(); + div_rem_nonneg(slot as usize, 1); + std::intrinsics::close_atomic_points_to_m(slot as *u8, (std::sync::atomic::is_bool_byte)(if value { 1 } else { 0 })); + open keep_u8(slot as *u8, 1 - af, if value { 1 } else { 0 }); + close std::sync::atomic::ro_bool_content(slot, af, value)(); + close Post(); + } { perform_atomically(); } + open Post(); + } + { + pred Ctx() = 0 < af &*& af < 1; + produce_lem_ptr_chunk full_borrow_convert_strong(Ctx, std::sync::atomic::ro_bool_content(slot, af, value), long, writable_bool_slot(slot, value))() { + open Ctx(); + open std::sync::atomic::ro_bool_content(slot, af, value)(); + std::intrinsics::open_atomic_points_to(slot as *u8); + if value {} else {} + merge_fractions points_to::(slot as *u8, _); + points_to_u8_to_bool(slot as *u8); + close writable_bool_slot(slot, value)(); + } { + close Ctx(); + close_full_borrow_strong(long, writable_bool_slot(slot, value), std::sync::atomic::ro_bool_content(slot, af, value)); + full_borrow_mono(long, k, std::sync::atomic::ro_bool_content(slot, af, value)); + } + } + full_borrow_into_frac(k, std::sync::atomic::ro_bool_content(slot, af, value)); + close std::sync::atomic::ro_bool_borrow(k, slot, af, value); + leak std::sync::atomic::ro_bool_borrow(k, slot, af, value); +} + +pred_ctor writable_u32_slot(slot: *u32, value: u32)(;) = + *slot |-> value; + +lem prepare_u32_readonly(slot: *u32, k: lifetime_t, af: real, value: u32) + nonghost_callers_only + req [?q]lifetime_token(k) &*& 0 < af &*& af < 1 &*& full_borrow(k, writable_u32_slot(slot, value)) &*& + slot as usize % std::intrinsics::atomic_align_of::() == 0; + ens [q]lifetime_token(k) &*& [_]std::sync::atomic::ro_u32_borrow(k, slot, af, value); +{ + let long = open_full_borrow_strong(k, writable_u32_slot(slot, value), q); + open writable_u32_slot(slot, value)(); + { + pred Pre() = 0 < af &*& af < 1 &*& *slot |-> value &*& + slot as usize % std::intrinsics::atomic_align_of::() == 0; + pred Post() = std::sync::atomic::ro_u32_content(slot, af, value)(); + close Pre(); + produce_lem_ptr_chunk atomic_block(Pre, Post)() { + open Pre(); + points_to_limits(slot); + close keep_u32(slot, 1 - af, value); + std::intrinsics::close_atomic_points_to_m(slot, (std::sync::atomic::is_u32_val)(value)); + open keep_u32(slot, 1 - af, value); + close std::sync::atomic::ro_u32_content(slot, af, value)(); + close Post(); + } { perform_atomically(); } + open Post(); + } + { + pred Ctx() = 0 < af &*& af < 1; + produce_lem_ptr_chunk full_borrow_convert_strong(Ctx, std::sync::atomic::ro_u32_content(slot, af, value), long, writable_u32_slot(slot, value))() { + open Ctx(); + open std::sync::atomic::ro_u32_content(slot, af, value)(); + std::intrinsics::open_atomic_points_to(slot); + merge_fractions points_to::(slot, _); + close writable_u32_slot(slot, value)(); + } { + close Ctx(); + close_full_borrow_strong(long, writable_u32_slot(slot, value), std::sync::atomic::ro_u32_content(slot, af, value)); + full_borrow_mono(long, k, std::sync::atomic::ro_u32_content(slot, af, value)); + } + } + full_borrow_into_frac(k, std::sync::atomic::ro_u32_content(slot, af, value)); + close std::sync::atomic::ro_u32_borrow(k, slot, af, value); + leak std::sync::atomic::ro_u32_borrow(k, slot, af, value); +} +@*/ diff --git a/verifast-proofs/core/sync/atomic.rs/checks/threads/runtime.rs b/verifast-proofs/core/sync/atomic.rs/checks/threads/runtime.rs new file mode 100644 index 0000000000000..e91c59cba47a5 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/checks/threads/runtime.rs @@ -0,0 +1,32 @@ +mod boolean; +mod pointer; +mod readonly; +#[path = "u32.rs"] mod word; +mod width; + +fn main() { + for initial in [0, 41, u32::MAX] { + for read in [false, true] { + unsafe { word::borrowed_pair(read, initial) }; + } + assert_eq!(unsafe { readonly::u32_readonly_pair(initial) }, (initial, 99)); + } + for initial in [false, true] { + for mode in 0..3 { + let (value, byte) = unsafe { boolean::bool_pair(mode, initial) }; + assert_eq!(byte, value as u8); + if mode == 2 { assert_eq!(value, initial); } + } + assert_eq!(unsafe { readonly::bool_readonly_pair(initial) }, (initial, !initial)); + } + let mut byte = 5u8; + for ptr in [std::ptr::null_mut(), &raw mut byte] { + assert!(unsafe { pointer::pointer_pair(ptr) }.1); + } + for (half, byte) in [(0, 0), (65535, 255), (0x3142, 0x27)] { + for (mode, expected) in [(0, (0x3e57, 0xa6)), (1, (0x3e57, byte)), (2, (half, byte))] { + assert_eq!(unsafe { width::width_pair(mode, half, byte) }, expected); + } + } + println!("POSIX worker pairs passed"); +} diff --git a/verifast-proofs/core/sync/atomic.rs/checks/threads/u32.rs b/verifast-proofs/core/sync/atomic.rs/checks/threads/u32.rs new file mode 100644 index 0000000000000..5d72a6312ad3a --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/checks/threads/u32.rs @@ -0,0 +1,322 @@ +#![no_std] +#![allow(dead_code)] +extern crate platform; +use core::sync::atomic::{AtomicU32, Ordering}; +use platform::threading::{fork_joinable, join, Thread}; + +/*@ +pred_ctor returned(k: lifetime_t, q: real)() = [q]lifetime_token(k); +pred_ctor transfer(k: lifetime_t, q: real, p: *u32)(arg: *std::sync::atomic::Atomic, post: pred()) = + [q]lifetime_token(k) &*& [_]frac_borrow(k, std::sync::atomic::U32_atomic_content(ref_origin(arg))) &*& + [_]frac_borrow(k, ref_initialized_(arg)) &*& ref_origin(arg) as *u32 == p &*& post == returned(k, q); +@*/ + + +unsafe fn second_store<'work>(atomic: &'work AtomicU32) +//@ req [?q]lifetime_token('work) &*& [_]frac_borrow('work, std::sync::atomic::U32_atomic_content(ref_origin(atomic))) &*& [_]frac_borrow('work, ref_initialized_(atomic)); +//@ ens [q]lifetime_token('work); +//@ on_unwind_ens false; +{ + let _ = atomic.fetch_add(7, Ordering::Relaxed); + let _ = atomic.fetch_sub(7, Ordering::AcqRel); +} + +unsafe fn second_load<'work>(atomic: &'work AtomicU32) +//@ req [?q]lifetime_token('work) &*& [_]frac_borrow('work, std::sync::atomic::U32_atomic_content(ref_origin(atomic))) &*& [_]frac_borrow('work, ref_initialized_(atomic)); +//@ ens [q]lifetime_token('work); +//@ on_unwind_ens false; +{ + let _observed = atomic.load(Ordering::Relaxed); +} + +#[allow(improper_ctypes_definitions)] +unsafe extern "C" fn fork_boundary<'a>(run: unsafe fn(&'a AtomicU32), data: &'a AtomicU32) -> Thread +//@ req [_]platform::threading::is_thread_run_joinable::<&'a std::sync::atomic::Atomic>(run, ?pre) &*& pre(data, ?post) &*& [_]frac_borrow('a, ref_initialized_(data)) &*& [?s]lifetime_token('a); +//@ ens platform::threading::Thread(result, post) &*& [s]lifetime_token('a); +//@ on_unwind_ens false; +{ + unsafe { fork_joinable(run, data) } +} + +#[allow(improper_ctypes_definitions)] +unsafe extern "C" fn join_boundary(thread: Thread) +//@ req platform::threading::Thread(thread, ?post); +//@ ens post(); +//@ on_unwind_ens false; +{ + unsafe { join(thread) } +} + +#[repr(C)] +struct Neighbors { + word: u32, + other: u32, +} + +pub unsafe fn borrowed_pair(read_in_b: bool, initial: u32) +//@ req std::intrinsics::atomic_align_of::() == std::mem::align_of::(); +//@ ens true; +//@ on_unwind_ens false; +{ + let mut pair = Neighbors { word: initial, other: 42 }; + let base = &raw mut pair; + let p = &raw mut pair.word; + let other = &raw mut pair.other; + //@ to_u8s_(p); + //@ from_u8s_(p); + //@ points_to_limits(p); + let _byte = unsafe { p.cast::().add(1) }; + //@ close ordinary_word(p)(); + //@ let k = begin_lifetime(); + //@ borrow(k, ordinary_word(p)); + //@ prepare_word(p, k); + { + //@ let_lft 'a = k; + let view = unsafe { AtomicU32::from_ptr/*@::<'a>@*/(p) }; + /*@ + produce_fn_ptr_chunk platform::threading::thread_run_joinable<&'a std::sync::atomic::Atomic>(first_retry)(transfer(k, 1/8, p))(arg) { + open transfer(k, 1/8, p)(arg, ?post); + call(); + close returned(k, 1/8)(); + } + @*/ + //@ close transfer(k, 1/8, p)(view, returned(k, 1/8)); + let a = unsafe { fork_boundary/*@::<'a>@*/(first_retry, view) }; + let b = if read_in_b { + /*@ + produce_fn_ptr_chunk platform::threading::thread_run_joinable<&'a std::sync::atomic::Atomic>(second_load)(transfer(k, 1/8, p))(arg) { + open transfer(k, 1/8, p)(arg, ?post); + call(); + close returned(k, 1/8)(); + } + @*/ + //@ close transfer(k, 1/8, p)(view, returned(k, 1/8)); + unsafe { fork_boundary/*@::<'a>@*/(second_load, view) } + } else { + /*@ + produce_fn_ptr_chunk platform::threading::thread_run_joinable<&'a std::sync::atomic::Atomic>(second_store)(transfer(k, 1/8, p))(arg) { + open transfer(k, 1/8, p)(arg, ?post); + call(); + close returned(k, 1/8)(); + } + @*/ + //@ close transfer(k, 1/8, p)(view, returned(k, 1/8)); + unsafe { fork_boundary/*@::<'a>@*/(second_store, view) } + }; + unsafe { join_boundary(a) }; + //@ open returned(k, 1/8)(); + // CH7_B_OUTSTANDING + let previous = unsafe { *other }; + //@ assert previous == 42; + unsafe { other.write(31) }; + let after = unsafe { *other }; + //@ assert after == 31; + unsafe { join_boundary(b) }; + //@ open returned(k, 1/8)(); + } + //@ end_lifetime(k); + //@ borrow_end(k, ordinary_word(p)); + //@ open ordinary_word(p)(); + let _restored = unsafe { *p }; + unsafe { p.write(30) }; + let updated = unsafe { *p }; + //@ assert updated == 30; + //@ close Neighbors_word_(base, _); + //@ close Neighbors_other_(base, _); +} +// These functions are compiled alongside the real typed thread entries. +// Every Ordering here is passed through the checked production interface. +unsafe fn read_order(index: u32) -> Ordering +//@ req true; +//@ ens result != std::sync::atomic::Ordering::Release &*& result != std::sync::atomic::Ordering::AcqRel; +//@ on_unwind_ens false; +{ + match index % 3 { + 0 => Ordering::Relaxed, + 1 => Ordering::Acquire, + _ => Ordering::SeqCst, + } +} + +unsafe fn write_order(index: u32) -> Ordering +//@ req true; +//@ ens result != std::sync::atomic::Ordering::Acquire &*& result != std::sync::atomic::Ordering::AcqRel; +//@ on_unwind_ens false; +{ + match index % 3 { + 0 => Ordering::Relaxed, + 1 => Ordering::Release, + _ => Ordering::SeqCst, + } +} + +unsafe fn modify_order(index: u32) -> Ordering +//@ req true; +//@ ens true; +//@ on_unwind_ens false; +{ + match index % 5 { + 0 => Ordering::Relaxed, + 1 => Ordering::Release, + 2 => Ordering::Acquire, + 3 => Ordering::AcqRel, + _ => Ordering::SeqCst, + } +} + +unsafe fn retry_cas<'work>( + atomic: &'work AtomicU32, expected: u32, new: u32, success: Ordering, failure: Ordering, +) -> u32 +//@ req [?q]lifetime_token('work) &*& [_]frac_borrow('work, std::sync::atomic::U32_atomic_content(ref_origin(atomic))) &*& [_]frac_borrow('work, ref_initialized_(atomic)) &*& failure != std::sync::atomic::Ordering::Release &*& failure != std::sync::atomic::Ordering::AcqRel; +//@ ens [q]lifetime_token('work); +//@ on_unwind_ens false; +{ + let mut current = expected; + loop { + //@ inv [q]lifetime_token('work) &*& [_]frac_borrow('work, std::sync::atomic::U32_atomic_content(ref_origin(atomic))) &*& [_]frac_borrow('work, ref_initialized_(atomic)) &*& failure != std::sync::atomic::Ordering::Release &*& failure != std::sync::atomic::Ordering::AcqRel; + let outcome = atomic.compare_exchange_weak(current, new, success, failure); + //@ open std::result::Result_own::(currentThread, outcome); + match outcome { + Ok(old) => { + //@ open u32_own(currentThread, old); + //@ assert old == current; + return old; + } + Err(seen) => { + //@ open u32_own(currentThread, seen); + current = seen; + } + } + } +} + +unsafe fn first_retry<'work>(atomic: &'work AtomicU32) +//@ req [?q]lifetime_token('work) &*& [_]frac_borrow('work, std::sync::atomic::U32_atomic_content(ref_origin(atomic))) &*& [_]frac_borrow('work, ref_initialized_(atomic)); +//@ ens [q]lifetime_token('work); +//@ on_unwind_ens false; +{ + let seed = atomic.load(Ordering::Acquire); + let success = unsafe { modify_order(seed) }; + let failure = unsafe { read_order(seed / 5) }; + let write = unsafe { write_order(seed / 15) }; + atomic.store(seed, write); + let before = atomic.load(failure); + let expected = atomic.swap(seed, success); + let strong = atomic.compare_exchange(expected, before, success, failure); + //@ open std::result::Result_own::(currentThread, strong); + /*@ match strong { + Result::Ok(seen) => { open u32_own(currentThread, seen); assert seen == expected; } + Result::Err(seen) => { open u32_own(currentThread, seen); assert seen != expected; } + } @*/ + let _old = unsafe { retry_cas/*@::<'work>@*/(atomic, expected, before, success, failure) }; +} +/*@ +pred_ctor ordinary_word(p: *u32)(;) = *p |-> ?v; + +lem prepare_word(p: *u32, k: lifetime_t) + nonghost_callers_only + req [?q]lifetime_token(k) &*& full_borrow(k, ordinary_word(p)) &*& + p as usize % std::intrinsics::atomic_align_of::() == 0; + ens [q]lifetime_token(k) &*& [_]frac_borrow(k, std::sync::atomic::U32_atomic_content(p)); +{ + let long = open_full_borrow_strong(k, ordinary_word(p), q); + open ordinary_word(p)(); + { + pred Pre() = *p |-> ?v; + pred Post() = std::sync::atomic::U32_atomic_content(p)(); + close Pre(); + produce_lem_ptr_chunk atomic_block(Pre, Post)() { + open Pre(); + std::intrinsics::close_atomic_points_to_m(p, std::sync::atomic::accepts_word); + close std::sync::atomic::U32_atomic_content(p)(); + close Post(); + } { perform_atomically(); } + open Post(); + } + { + pred Ctx() = true; + produce_lem_ptr_chunk full_borrow_convert_strong(Ctx, std::sync::atomic::U32_atomic_content(p), long, ordinary_word(p))() { + open Ctx(); + open std::sync::atomic::U32_atomic_content(p)(); + std::intrinsics::open_atomic_points_to(p); + close ordinary_word(p)(); + } { + close Ctx(); + close_full_borrow_strong(long, ordinary_word(p), std::sync::atomic::U32_atomic_content(p)); + full_borrow_mono(long, k, std::sync::atomic::U32_atomic_content(p)); + } + } + full_borrow_into_frac(k, std::sync::atomic::U32_atomic_content(p)); +} +@*/ + +/*@ +lem word_excludes_byte(p: *u32, i: usize) + req *p |-> ?v &*& 0 <= i &*& i < 4 &*& [?g]points_to_::((p as *u8) + i, ?extra) &*& 0 < g; + ens false; +{ + to_u8s_(p); + let base = p as *u8; + array__split(base, i); + open array_(base + i, 4 - i, _); + merge_fractions points_to_::(base + i, _); + points_to__limits(base + i); +} +lem word_excludes_overlapping_access(p: *u32, other: *T, i: usize, j: usize) + req *p |-> ?v &*& [?g]points_to_(other, ?other_value) &*& 0 < g &*& + 0 <= i &*& i < 4 &*& 0 <= j &*& j < std::mem::size_of::() &*& + (p as *u8) + i == (other as *u8) + j; + ens false; +{ + to_u8s_(other); + let base = other as *u8; + array__split(base, j); + open [g]array_(base + j, std::mem::size_of::() - j, _); + word_excludes_byte(p, i); +} +pred ordinary_common_byte(p: *u32, other: *T, i: usize, j: usize) = + [?g]points_to_(other, ?value) &*& 0 < g &*& + 0 <= i &*& i < 4 &*& 0 <= j &*& j < std::mem::size_of::() &*& + (p as *u8) + i == (other as *u8) + j; + +pred opened_production_word(p: *u32, k: lifetime_t, q: real, f: real) = + [f]std::intrinsics::atomic_points_to::(p, 1, std::sync::atomic::accepts_word) &*& + close_frac_borrow_token(f, std::sync::atomic::U32_atomic_content(p), q, k); + +lem production_closed_excludes_overlap(p: *u32, k: lifetime_t, other: *T, i: usize, j: usize) + nonghost_callers_only + req lifetime_token(k) &*& borrow_end_token(k, ordinary_word(p)) &*& ordinary_common_byte(p, other, i, j); + ens false; +{ + end_lifetime(k); + borrow_end(k, ordinary_word(p)); + open ordinary_word(p)(); + open ordinary_common_byte(p, other, i, j); + word_excludes_overlapping_access(p, other, i, j); +} + +lem production_open_excludes_overlap(p: *u32, k: lifetime_t, q: real, other: *T, i: usize, j: usize) + nonghost_callers_only + req 0 < q &*& q < 1 &*& [1-q]lifetime_token(k) &*& opened_production_word(p, k, q, ?f) &*& + borrow_end_token(k, ordinary_word(p)) &*& ordinary_common_byte(p, other, i, j); + ens false; +{ + open opened_production_word(p, k, q, f); + close [f]std::sync::atomic::U32_atomic_content(p)(); + close_frac_borrow(f, std::sync::atomic::U32_atomic_content(p)); + production_closed_excludes_overlap(p, k, other, i, j); +} + +lem production_two_open_exclude_overlap(p: *u32, k: lifetime_t, qa: real, qb: real, other: *T, i: usize, j: usize) + nonghost_callers_only + req 0 < qa &*& 0 < qb &*& qa+qb < 1 &*& [1-qa-qb]lifetime_token(k) &*& + opened_production_word(p, k, qa, ?fa) &*& opened_production_word(p, k, qb, ?fb) &*& + borrow_end_token(k, ordinary_word(p)) &*& ordinary_common_byte(p, other, i, j); + ens false; +{ + open opened_production_word(p, k, qa, fa); + close [fa]std::sync::atomic::U32_atomic_content(p)(); + close_frac_borrow(fa, std::sync::atomic::U32_atomic_content(p)); + production_open_excludes_overlap(p, k, qb, other, i, j); +} +@*/ diff --git a/verifast-proofs/core/sync/atomic.rs/checks/threads/width.rs b/verifast-proofs/core/sync/atomic.rs/checks/threads/width.rs new file mode 100644 index 0000000000000..3a36b05a94f52 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/checks/threads/width.rs @@ -0,0 +1,219 @@ +#![no_std] +#![allow(dead_code)] +extern crate platform; +use core::sync::atomic::{AtomicU8, AtomicU16, Ordering}; +use platform::threading::{fork_joinable, join, Thread}; + +/*@ +pred_ctor returned(k: lifetime_t, q: real)() = [q]lifetime_token(k); +pred_ctor transfer(k: lifetime_t, q: real, p: *T)(arg: *std::sync::atomic::Atomic, post: pred()) = + [q]lifetime_token(k) &*& [_]frac_borrow(k, std::sync::atomic::unsigned_content::(ref_origin(arg))) &*& + [_]frac_borrow(k, ref_initialized_(arg)) &*& ref_origin(arg) as *T == p &*& post == returned(k, q); +@*/ + +unsafe fn store16<'a>(slot: &'a AtomicU16) +//@ req [?q]lifetime_token('a) &*& [_]frac_borrow('a, std::sync::atomic::unsigned_content::(ref_origin(slot))) &*& [_]frac_borrow('a, ref_initialized_(slot)); +//@ ens [q]lifetime_token('a); +//@ on_unwind_ens false; +{ + slot.store(0x3e57, Ordering::Relaxed); +} + +unsafe fn load16<'a>(slot: &'a AtomicU16) +//@ req [?q]lifetime_token('a) &*& [_]frac_borrow('a, std::sync::atomic::unsigned_content::(ref_origin(slot))) &*& [_]frac_borrow('a, ref_initialized_(slot)); +//@ ens [q]lifetime_token('a); +//@ on_unwind_ens false; +{ + let _ = slot.load(Ordering::Relaxed); +} + +unsafe fn store8<'a>(slot: &'a AtomicU8) +//@ req [?q]lifetime_token('a) &*& [_]frac_borrow('a, std::sync::atomic::unsigned_content::(ref_origin(slot))) &*& [_]frac_borrow('a, ref_initialized_(slot)); +//@ ens [q]lifetime_token('a); +//@ on_unwind_ens false; +{ + slot.store(0xa6, Ordering::Relaxed); +} + +unsafe fn load8<'a>(slot: &'a AtomicU8) +//@ req [?q]lifetime_token('a) &*& [_]frac_borrow('a, std::sync::atomic::unsigned_content::(ref_origin(slot))) &*& [_]frac_borrow('a, ref_initialized_(slot)); +//@ ens [q]lifetime_token('a); +//@ on_unwind_ens false; +{ + let _ = slot.load(Ordering::Relaxed); +} + +#[allow(improper_ctypes_definitions)] +unsafe extern "C" fn fork16<'a>(run: unsafe fn(&'a AtomicU16), data: &'a AtomicU16) -> Thread +//@ req [_]platform::threading::is_thread_run_joinable::<&'a std::sync::atomic::Atomic>(run, ?pre) &*& pre(data, ?post) &*& [_]frac_borrow('a, ref_initialized_(data)) &*& [?s]lifetime_token('a); +//@ ens platform::threading::Thread(result, post) &*& [s]lifetime_token('a); +//@ on_unwind_ens false; +{ + unsafe { fork_joinable(run, data) } +} + +#[allow(improper_ctypes_definitions)] +unsafe extern "C" fn fork8<'a>(run: unsafe fn(&'a AtomicU8), data: &'a AtomicU8) -> Thread +//@ req [_]platform::threading::is_thread_run_joinable::<&'a std::sync::atomic::Atomic>(run, ?pre) &*& pre(data, ?post) &*& [_]frac_borrow('a, ref_initialized_(data)) &*& [?s]lifetime_token('a); +//@ ens platform::threading::Thread(result, post) &*& [s]lifetime_token('a); +//@ on_unwind_ens false; +{ + unsafe { fork_joinable(run, data) } +} + +#[allow(improper_ctypes_definitions)] +unsafe extern "C" fn join_width(thread: Thread) +//@ req platform::threading::Thread(thread, ?post); +//@ ens post(); +//@ on_unwind_ens false; +{ + unsafe { join(thread) } +} + +#[repr(C)] +struct Fields { wide: u16, next: u8, spare: u8 } + +const _: () = { + assert!(core::mem::size_of::() == 4); + assert!(core::mem::offset_of!(Fields, next) == 2); +}; + +// Mode 0 stores to disjoint fields. Mode 1 reads the adjacent byte while +// updating the wide field. Other modes give both readers the same U16. +pub unsafe fn width_pair(mode: u8, initial: u16, byte: u8) -> (u16, u8) +//@ req std::intrinsics::atomic_align_of::() == std::mem::align_of::(); +//@ ens true; +//@ on_unwind_ens false; +{ + let mut storage = Fields { wide: initial, next: byte, spare: 42 }; + let base = &raw mut storage; + let wide = &raw mut storage.wide; + let next = &raw mut storage.next; + let spare = &raw mut storage.spare; + //@ to_u8s_(wide); + //@ from_u8s_(wide); + //@ points_to_limits(wide); + //@ points_to_limits(next); + //@ std::intrinsics::atomic_align_of_u8(); + //@ div_rem_nonneg(next as usize, 1); + //@ let k = begin_lifetime(); + //@ close ordinary::(wide)(); + //@ borrow(k, ordinary::(wide)); + //@ prepare_unsigned(wide, k); + //@ close ordinary::(next)(); + //@ borrow(k, ordinary::(next)); + //@ prepare_unsigned(next, k); + { + //@ let_lft 'a = k; + let half = unsafe { AtomicU16::from_ptr/*@::<'a>@*/(wide) }; + let narrow = unsafe { AtomicU8::from_ptr/*@::<'a>@*/(next) }; + let a = if mode < 2 { + /*@ + produce_fn_ptr_chunk platform::threading::thread_run_joinable<&'a std::sync::atomic::Atomic>(store16)(transfer::(k, 1/8, wide))(arg) { + open transfer::(k, 1/8, wide)(arg, ?post); + call(); + close returned(k, 1/8)(); + } + @*/ + //@ close transfer::(k, 1/8, wide)(half, returned(k, 1/8)); + unsafe { fork16/*@::<'a>@*/(store16, half) } + } else { + /*@ + produce_fn_ptr_chunk platform::threading::thread_run_joinable<&'a std::sync::atomic::Atomic>(load16)(transfer::(k, 1/8, wide))(arg) { + open transfer::(k, 1/8, wide)(arg, ?post); + call(); + close returned(k, 1/8)(); + } + @*/ + //@ close transfer::(k, 1/8, wide)(half, returned(k, 1/8)); + unsafe { fork16/*@::<'a>@*/(load16, half) } + }; + let b = if mode == 0 { + /*@ + produce_fn_ptr_chunk platform::threading::thread_run_joinable<&'a std::sync::atomic::Atomic>(store8)(transfer::(k, 1/8, next))(arg) { + open transfer::(k, 1/8, next)(arg, ?post); + call(); + close returned(k, 1/8)(); + } + @*/ + //@ close transfer::(k, 1/8, next)(narrow, returned(k, 1/8)); + unsafe { fork8/*@::<'a>@*/(store8, narrow) } + } else if mode == 1 { + /*@ + produce_fn_ptr_chunk platform::threading::thread_run_joinable<&'a std::sync::atomic::Atomic>(load8)(transfer::(k, 1/8, next))(arg) { + open transfer::(k, 1/8, next)(arg, ?post); + call(); + close returned(k, 1/8)(); + } + @*/ + //@ close transfer::(k, 1/8, next)(narrow, returned(k, 1/8)); + unsafe { fork8/*@::<'a>@*/(load8, narrow) } + } else { + /*@ + produce_fn_ptr_chunk platform::threading::thread_run_joinable<&'a std::sync::atomic::Atomic>(load16)(transfer::(k, 1/8, wide))(arg) { + open transfer::(k, 1/8, wide)(arg, ?post); + call(); + close returned(k, 1/8)(); + } + @*/ + //@ close transfer::(k, 1/8, wide)(half, returned(k, 1/8)); + unsafe { fork16/*@::<'a>@*/(load16, half) } + }; + unsafe { join_width(a) }; + //@ open returned(k, 1/8)(); + // CH7_B_OUTSTANDING + let kept = unsafe { *spare }; + //@ assert kept == 42; + unsafe { join_width(b) }; + //@ open returned(k, 1/8)(); + } + //@ end_lifetime(k); + //@ borrow_end(k, ordinary::(next)); + //@ borrow_end(k, ordinary::(wide)); + //@ open ordinary::(next)(); + //@ open ordinary::(wide)(); + let old = unsafe { (*wide, *next) }; + unsafe { *next = 7; *wide = 23; } + //@ close Fields_wide_(base, _); + //@ close Fields_next_(base, _); + //@ close Fields_spare_(base, _); + old +} +/*@ +pred_ctor ordinary(p: *T)(;) = *p |-> ?v; +lem prepare_unsigned(p: *T, k: lifetime_t) + nonghost_callers_only + req [?q]lifetime_token(k) &*& full_borrow(k, ordinary::(p)) &*& + p as usize % std::intrinsics::atomic_align_of::() == 0; + ens [q]lifetime_token(k) &*& [_]frac_borrow(k, std::sync::atomic::unsigned_content::(p)); +{ + let long = open_full_borrow_strong(k, ordinary::(p), q); + open ordinary::(p)(); + { + pred Pre() = *p |-> ?v; + pred Post() = std::sync::atomic::unsigned_content::(p)(); + close Pre(); + produce_lem_ptr_chunk atomic_block(Pre, Post)() { + open Pre(); + std::intrinsics::close_atomic_points_to_m(p, std::sync::atomic::accepts_unsigned); + close std::sync::atomic::unsigned_content::(p)(); + close Post(); + } { perform_atomically(); } + open Post(); + } + { + pred Ctx() = true; + produce_lem_ptr_chunk full_borrow_convert_strong(Ctx, std::sync::atomic::unsigned_content::(p), long, ordinary::(p))() { + open Ctx(); + open std::sync::atomic::unsigned_content::(p)(); + std::intrinsics::open_atomic_points_to(p); + close ordinary::(p)(); + } { + close Ctx(); + close_full_borrow_strong(long, ordinary::(p), std::sync::atomic::unsigned_content::(p)); + full_borrow_mono(long, k, std::sync::atomic::unsigned_content::(p)); + } + } + full_borrow_into_frac(k, std::sync::atomic::unsigned_content::(p)); +} +@*/ diff --git a/verifast-proofs/core/sync/atomic.rs/checks/u32.rs b/verifast-proofs/core/sync/atomic.rs/checks/u32.rs new file mode 100644 index 0000000000000..741dcf106d5b4 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/checks/u32.rs @@ -0,0 +1,200 @@ +use crate::sync::atomic::AtomicU32; + +/*@ +pred_ctor ordinary_word(p: *u32)(;) = *p |-> ?v; + +lem prepare_word(p: *u32, k: lifetime_t) + nonghost_callers_only + req [?q]lifetime_token(k) &*& full_borrow(k, ordinary_word(p)) &*& + p as usize % std::intrinsics::atomic_align_of::() == 0; + ens [q]lifetime_token(k) &*& [_]frac_borrow(k, sync::atomic::U32_atomic_content(p)); +{ + let long = open_full_borrow_strong(k, ordinary_word(p), q); + open ordinary_word(p)(); + { + pred Pre() = *p |-> ?v; + pred Post() = sync::atomic::U32_atomic_content(p)(); + close Pre(); + produce_lem_ptr_chunk atomic_block(Pre, Post)() { + open Pre(); + std::intrinsics::close_atomic_points_to_m(p, sync::atomic::accepts_word); + close sync::atomic::U32_atomic_content(p)(); + close Post(); + } { perform_atomically(); } + open Post(); + } + { + pred Ctx() = true; + produce_lem_ptr_chunk full_borrow_convert_strong(Ctx, sync::atomic::U32_atomic_content(p), long, ordinary_word(p))() { + open Ctx(); + open sync::atomic::U32_atomic_content(p)(); + std::intrinsics::open_atomic_points_to(p); + close ordinary_word(p)(); + } { + close Ctx(); + close_full_borrow_strong(long, ordinary_word(p), sync::atomic::U32_atomic_content(p)); + full_borrow_mono(long, k, sync::atomic::U32_atomic_content(p)); + } + } + full_borrow_into_frac(k, sync::atomic::U32_atomic_content(p)); +} +@*/ + +// This witness constructs the real reference and recovers the allocation. +// Atomic access to the returned raw pointer is checked separately. +unsafe fn round_trip() +//@ req std::intrinsics::atomic_align_of::() == std::mem::align_of::(); +//@ ens true; +//@ on_unwind_ens false; +{ + let mut word: u32 = 0; + let p = &raw mut word; + //@ to_u8s_(p); + //@ from_u8s_(p); + //@ close ordinary_word(p)(); + //@ let k = begin_lifetime(); + //@ borrow(k, ordinary_word(p)); + //@ prepare_word(p, k); + { + //@ let_lft 'a = k; + let view = unsafe { AtomicU32::from_ptr/*@::<'a>@*/(p) }; + let dst = view.as_ptr(); + //@ assert dst as pointer == p as pointer; + } + //@ end_lifetime(k); + //@ borrow_end(k, ordinary_word(p)); + //@ open ordinary_word(p)(); + let _old = unsafe { *p }; + unsafe { *p = 30 }; + //@ assert word == 30; +} +// Compiled in the same proof-client module as the verified prepare_word lemma. +unsafe fn public_round_trip() +//@ req std::intrinsics::atomic_align_of::() == std::mem::align_of::(); +//@ ens true; +//@ on_unwind_ens false; +{ + let mut word = 0u32; + let p = &raw mut word; + //@ to_u8s_(p); + //@ from_u8s_(p); + //@ close ordinary_word(p)(); + //@ let k = begin_lifetime(); + //@ borrow(k, ordinary_word(p)); + //@ prepare_word(p, k); + { + //@ let_lft 'a = k; + let atomic = unsafe { AtomicU32::from_ptr/*@::<'a>@*/(p) }; + //@ close sync::atomic::Ordering_own(currentThread, sync::atomic::Ordering::Relaxed); + atomic.store(10, crate::sync::atomic::Ordering::Relaxed); + //@ close sync::atomic::Ordering_own(currentThread, sync::atomic::Ordering::Relaxed); + let _observed = atomic.load(crate::sync::atomic::Ordering::Relaxed); + } + //@ end_lifetime(k); + //@ borrow_end(k, ordinary_word(p)); + //@ open ordinary_word(p)(); + let _restored = unsafe { *p }; + unsafe { *p = 30 }; + //@ assert word == 30; +} +// These single-method witnesses check the external client's contracts against the real +// production methods. The client interface copies the clauses from this file. +unsafe fn borrowed_from_ptr<'a>(ptr: *mut u32) -> &'a AtomicU32 +//@ req [?q]lifetime_token('a) &*& [_]frac_borrow('a, sync::atomic::U32_atomic_content(ptr)) &*& ref_origin(ptr) == ptr; +//@ ens [q]lifetime_token('a) &*& [_]frac_borrow('a, sync::atomic::U32_atomic_content(ref_origin(result))) &*& [_]frac_borrow('a, ref_initialized_(result)) &*& ref_origin(result) as *_ == ptr as *_; +//@ on_unwind_ens false; +{ + let view = unsafe { AtomicU32::from_ptr/*@::<'a>@*/(ptr) }; + //@ open sync::atomic::Atomic_share::('a, currentThread, view); + view +} + +unsafe fn borrowed_store(receiver: &AtomicU32, val: u32, order: crate::sync::atomic::Ordering) +//@ req [?q]lifetime_token(?k) &*& [_]frac_borrow(k, sync::atomic::U32_atomic_content(ref_origin(receiver))) &*& [_]frac_borrow(k, ref_initialized_(receiver)) &*& order != sync::atomic::Ordering::Acquire &*& order != sync::atomic::Ordering::AcqRel; +//@ ens [q]lifetime_token(k); +//@ on_unwind_ens false; +{ + //@ close exists(false); + //@ close sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ leak sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ close sync::atomic::Ordering_own(currentThread, order); + receiver.store(val, order); +} + +unsafe fn borrowed_load(receiver: &AtomicU32, order: crate::sync::atomic::Ordering) -> u32 +//@ req [?q]lifetime_token(?k) &*& [_]frac_borrow(k, sync::atomic::U32_atomic_content(ref_origin(receiver))) &*& [_]frac_borrow(k, ref_initialized_(receiver)) &*& order != sync::atomic::Ordering::Release &*& order != sync::atomic::Ordering::AcqRel; +//@ ens [q]lifetime_token(k); +//@ on_unwind_ens false; +{ + //@ close exists(false); + //@ close sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ leak sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ close sync::atomic::Ordering_own(currentThread, order); + receiver.load(order) +} +unsafe fn borrowed_swap(receiver: &AtomicU32, val: u32, order: crate::sync::atomic::Ordering) -> u32 +//@ req [?q]lifetime_token(?k) &*& [_]frac_borrow(k, sync::atomic::U32_atomic_content(ref_origin(receiver))) &*& [_]frac_borrow(k, ref_initialized_(receiver)); +//@ ens [q]lifetime_token(k); +//@ on_unwind_ens false; +{ + //@ close exists(false); + //@ close sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ leak sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ close sync::atomic::Ordering_own(currentThread, order); + receiver.swap(val, order) +} +unsafe fn borrowed_compare_exchange( + receiver: &AtomicU32, current: u32, new: u32, + success: crate::sync::atomic::Ordering, failure: crate::sync::atomic::Ordering, +) -> crate::result::Result +//@ req [?q]lifetime_token(?k) &*& [_]frac_borrow(k, sync::atomic::U32_atomic_content(ref_origin(receiver))) &*& [_]frac_borrow(k, ref_initialized_(receiver)) &*& failure != sync::atomic::Ordering::Release &*& failure != sync::atomic::Ordering::AcqRel; +//@ ens [q]lifetime_token(k) &*& result::Result_own::(currentThread, result) &*& match result { Result::Ok(v) => v == current, Result::Err(v) => v != current }; +//@ on_unwind_ens false; +{ + //@ close exists(false); + //@ close sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ leak sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ close sync::atomic::Ordering_own(currentThread, success); + //@ close sync::atomic::Ordering_own(currentThread, failure); + receiver.compare_exchange(current, new, success, failure) +} + +unsafe fn borrowed_compare_exchange_weak( + receiver: &AtomicU32, current: u32, new: u32, + success: crate::sync::atomic::Ordering, failure: crate::sync::atomic::Ordering, +) -> crate::result::Result +//@ req [?q]lifetime_token(?k) &*& [_]frac_borrow(k, sync::atomic::U32_atomic_content(ref_origin(receiver))) &*& [_]frac_borrow(k, ref_initialized_(receiver)) &*& failure != sync::atomic::Ordering::Release &*& failure != sync::atomic::Ordering::AcqRel; +//@ ens [q]lifetime_token(k) &*& result::Result_own::(currentThread, result) &*& match result { Result::Ok(v) => v == current, Result::Err(v) => true }; +//@ on_unwind_ens false; +{ + //@ close exists(false); + //@ close sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ leak sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ close sync::atomic::Ordering_own(currentThread, success); + //@ close sync::atomic::Ordering_own(currentThread, failure); + receiver.compare_exchange_weak(current, new, success, failure) +} +unsafe fn borrowed_fetch_add(receiver: &AtomicU32, val: u32, order: crate::sync::atomic::Ordering) -> u32 +//@ req [?q]lifetime_token(?k) &*& [_]frac_borrow(k, sync::atomic::U32_atomic_content(ref_origin(receiver))) &*& [_]frac_borrow(k, ref_initialized_(receiver)); +//@ ens [q]lifetime_token(k); +//@ on_unwind_ens false; +{ + //@ close exists(false); + //@ close sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ leak sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ close sync::atomic::Ordering_own(currentThread, order); + receiver.fetch_add(val, order) +} + +unsafe fn borrowed_fetch_sub(receiver: &AtomicU32, val: u32, order: crate::sync::atomic::Ordering) -> u32 +//@ req [?q]lifetime_token(?k) &*& [_]frac_borrow(k, sync::atomic::U32_atomic_content(ref_origin(receiver))) &*& [_]frac_borrow(k, ref_initialized_(receiver)); +//@ ens [q]lifetime_token(k); +//@ on_unwind_ens false; +{ + //@ close exists(false); + //@ close sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ leak sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ close sync::atomic::Ordering_own(currentThread, order); + receiver.fetch_sub(val, order) +} + diff --git a/verifast-proofs/core/sync/atomic.rs/checks/upstream_bug_166918_miri.rs b/verifast-proofs/core/sync/atomic.rs/checks/upstream_bug_166918_miri.rs new file mode 100644 index 0000000000000..3bee25e7670f8 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/checks/upstream_bug_166918_miri.rs @@ -0,0 +1,42 @@ +// Standalone Miri reproducer for upstream Rust bug rust-lang/rust#166918 +// (not executed by verifast.yml CI; requires a nightly toolchain with Miri). +// +// On targets where `EMULATE_ATOMIC_BOOL` is true (`riscv32`, `riscv64`, +// `loongarch32`, `loongarch64`), `AtomicBool::compare_exchange` and +// `AtomicBool::compare_exchange_weak` unconditionally execute an atomic RMW +// (`fetch_or(false)` or `swap(new)`) even when the comparison fails and +// returns `Err(old)`. Per `core::sync::atomic`'s documented memory model, a +// failed compare-exchange is not a write and must not race with an +// unsynchronized non-atomic read of the same byte. +// +// Reproduce in a disposable Cargo binary crate containing this file as `src/main.rs`: +// cargo +nightly miri run --target x86_64-unknown-linux-gnu # PASS (exit 0) +// cargo +nightly miri run --target riscv64gc-unknown-linux-gnu # Data race UB (exit 1) +// cargo +nightly miri run --target loongarch64-unknown-linux-gnu # Data race UB (exit 1) +// +// Changing line 32 to `compare_exchange(true, false, Relaxed, Relaxed)` or +// `compare_exchange_weak(true, true, Relaxed, Relaxed)` reproduces the same +// data race on RISC-V 64 / LoongArch 64 while passing on x86-64. + +use std::sync::Barrier; +use std::sync::atomic::{AtomicBool, Ordering::Relaxed}; +use std::thread; + +fn main() { + let flag = AtomicBool::new(false); + let barrier = Barrier::new(2); + thread::scope(|s| { + s.spawn(|| { + barrier.wait(); + // `flag` is always `false`, so comparing against `true` is guaranteed to fail. + let res = flag.compare_exchange(true, true, Relaxed, Relaxed); + assert_eq!(res, Err(false)); + }); + s.spawn(|| { + barrier.wait(); + // Concurrent non-atomic read of the same byte; permitted with failed CAS per std docs. + let val = unsafe { *flag.as_ptr() }; + assert!(!val); + }); + }); +} diff --git a/verifast-proofs/core/sync/atomic.rs/checks/width.rs b/verifast-proofs/core/sync/atomic.rs/checks/width.rs new file mode 100644 index 0000000000000..48b65a4f72b88 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/checks/width.rs @@ -0,0 +1,194 @@ +use crate::sync::atomic::{AtomicU8, AtomicU16}; + + +#[repr(C)] +struct Neighbors { + wide: u16, + next: u8, + spare: u8, +} + +const _: () = { + assert!(crate::mem::size_of::() == 4); + assert!(crate::mem::offset_of!(Neighbors, wide) == 0); + assert!(crate::mem::offset_of!(Neighbors, next) == 2); +}; + +unsafe fn disjoint_views(initial: u16, byte: u8) +//@ req std::intrinsics::atomic_align_of::() == std::mem::align_of::(); +//@ ens true; +//@ on_unwind_ens false; +{ + let mut storage = Neighbors { wide: initial, next: byte, spare: 0 }; + let base = &raw mut storage; + let wide = &raw mut storage.wide; + let next = &raw mut storage.next; + //@ to_u8s_(wide); + //@ from_u8s_(wide); + //@ points_to_limits(wide); + //@ let interior = (wide as *u8) + 1; + //@ assert object_pointer_within_limits(interior, 1) == true; + //@ std::intrinsics::atomic_align_of_u8(); + //@ div_rem_nonneg(interior as usize, 1); + //@ assert interior as usize % std::intrinsics::atomic_align_of::() == 0; + //@ close ordinary::(wide)(); + //@ let k = begin_lifetime(); + //@ borrow(k, ordinary::(wide)); + //@ prepare_unsigned(wide, k); + //@ points_to_limits(next); + //@ div_rem_nonneg(next as usize, 1); + //@ close ordinary::(next)(); + //@ borrow(k, ordinary::(next)); + //@ prepare_unsigned(next, k); + { + //@ let_lft 'a = k; + let large = unsafe { AtomicU16::from_ptr/*@::<'a>@*/(wide) }; + let small = unsafe { AtomicU8::from_ptr/*@::<'a>@*/(next) }; + let first = large.as_ptr(); + let second = small.as_ptr(); + //@ assert first == wide; + //@ assert second == next; + //@ close sync::atomic::Ordering_own(currentThread, sync::atomic::Ordering::Relaxed); + large.store(initial, crate::sync::atomic::Ordering::Relaxed); + //@ close sync::atomic::Ordering_own(currentThread, sync::atomic::Ordering::Relaxed); + small.store(byte, crate::sync::atomic::Ordering::Relaxed); + //@ close sync::atomic::Ordering_own(currentThread, sync::atomic::Ordering::Relaxed); + let _ = small.load(crate::sync::atomic::Ordering::Relaxed); + // Both views exist before either atomic permission is opened. + //@ let f = open_frac_borrow(k, sync::atomic::unsigned_content::(wide), 1/4); + //@ let g = open_frac_borrow(k, sync::atomic::unsigned_content::(next), 1/4); + //@ open [f]sync::atomic::unsigned_content::(wide)(); + //@ open [g]sync::atomic::unsigned_content::(next)(); + //@ close [f]sync::atomic::unsigned_content::(wide)(); + //@ close [g]sync::atomic::unsigned_content::(next)(); + //@ close_frac_borrow(g, sync::atomic::unsigned_content::(next)); + //@ close_frac_borrow(f, sync::atomic::unsigned_content::(wide)); + } + //@ end_lifetime(k); + //@ borrow_end(k, ordinary::(wide)); + //@ borrow_end(k, ordinary::(next)); + //@ open ordinary::(wide)(); + //@ open ordinary::(next)(); + let _a = unsafe { *wide }; + let _b = unsafe { *next }; + unsafe { *wide = 19; *next = 74 }; + //@ close Neighbors_wide_(base, _); + //@ close Neighbors_next_(base, _); +} +unsafe fn borrowed_view8<'a>(ptr: *mut u8) -> &'a AtomicU8 +//@ req [?q]lifetime_token('a) &*& [_]frac_borrow('a, sync::atomic::unsigned_content::(ptr)) &*& ref_origin(ptr) == ptr; +//@ ens [q]lifetime_token('a) &*& [_]frac_borrow('a, sync::atomic::unsigned_content::(ref_origin(result))) &*& [_]frac_borrow('a, ref_initialized_(result)) &*& ref_origin(result) as *u8 == ptr; +//@ on_unwind_ens false; +{ + let view = unsafe { AtomicU8::from_ptr/*@::<'a>@*/(ptr) }; + //@ open sync::atomic::Atomic_share::('a, currentThread, view); + view +} + +unsafe fn borrowed_view16<'a>(ptr: *mut u16) -> &'a AtomicU16 +//@ req [?q]lifetime_token('a) &*& [_]frac_borrow('a, sync::atomic::unsigned_content::(ptr)) &*& ref_origin(ptr) == ptr; +//@ ens [q]lifetime_token('a) &*& [_]frac_borrow('a, sync::atomic::unsigned_content::(ref_origin(result))) &*& [_]frac_borrow('a, ref_initialized_(result)) &*& ref_origin(result) as *u16 == ptr; +//@ on_unwind_ens false; +{ + let view = unsafe { AtomicU16::from_ptr/*@::<'a>@*/(ptr) }; + //@ open sync::atomic::Atomic_share::('a, currentThread, view); + view +} +unsafe fn borrowed_store8(receiver: &AtomicU8, val: u8, order: crate::sync::atomic::Ordering) +//@ req [?q]lifetime_token(?k) &*& [_]frac_borrow(k, sync::atomic::unsigned_content::(ref_origin(receiver))) &*& [_]frac_borrow(k, ref_initialized_(receiver)) &*& order != sync::atomic::Ordering::Acquire &*& order != sync::atomic::Ordering::AcqRel; +//@ ens [q]lifetime_token(k); +//@ on_unwind_ens false; +{ + //@ close exists(false); + //@ close sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ leak sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ close sync::atomic::Ordering_own(currentThread, order); + receiver.store(val, order) +} + +unsafe fn borrowed_load8(receiver: &AtomicU8, order: crate::sync::atomic::Ordering) -> u8 +//@ req [?q]lifetime_token(?k) &*& [_]frac_borrow(k, sync::atomic::unsigned_content::(ref_origin(receiver))) &*& [_]frac_borrow(k, ref_initialized_(receiver)) &*& order != sync::atomic::Ordering::Release &*& order != sync::atomic::Ordering::AcqRel; +//@ ens [q]lifetime_token(k); +//@ on_unwind_ens false; +{ + //@ close exists(false); + //@ close sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ leak sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ close sync::atomic::Ordering_own(currentThread, order); + receiver.load(order) +} + +unsafe fn borrowed_store16(receiver: &AtomicU16, val: u16, order: crate::sync::atomic::Ordering) +//@ req [?q]lifetime_token(?k) &*& [_]frac_borrow(k, sync::atomic::unsigned_content::(ref_origin(receiver))) &*& [_]frac_borrow(k, ref_initialized_(receiver)) &*& order != sync::atomic::Ordering::Acquire &*& order != sync::atomic::Ordering::AcqRel; +//@ ens [q]lifetime_token(k); +//@ on_unwind_ens false; +{ + //@ close exists(false); + //@ close sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ leak sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ close sync::atomic::Ordering_own(currentThread, order); + receiver.store(val, order) +} + +unsafe fn borrowed_load16(receiver: &AtomicU16, order: crate::sync::atomic::Ordering) -> u16 +//@ req [?q]lifetime_token(?k) &*& [_]frac_borrow(k, sync::atomic::unsigned_content::(ref_origin(receiver))) &*& [_]frac_borrow(k, ref_initialized_(receiver)) &*& order != sync::atomic::Ordering::Release &*& order != sync::atomic::Ordering::AcqRel; +//@ ens [q]lifetime_token(k); +//@ on_unwind_ens false; +{ + //@ close exists(false); + //@ close sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ leak sync::atomic::Atomic_share::(k, currentThread, receiver); + //@ close sync::atomic::Ordering_own(currentThread, order); + receiver.load(order) +} + +use crate::sync::atomic::{AtomicI8, AtomicI16, AtomicI32, AtomicI64, AtomicU64}; +#[cfg(target_has_atomic_load_store = "128")] +use crate::sync::atomic::{AtomicI128, AtomicU128}; + + +macro_rules! check_integer_view { + ($name:ident, $ty:ty, $atomic:ident) => { + const _: () = { + assert!(crate::mem::size_of::<$atomic>() == crate::mem::size_of::<$ty>()); + assert!(crate::mem::align_of::<$atomic>() == crate::mem::align_of::<$ty>()); + }; + + unsafe fn $name(initial: $ty, replacement: $ty) -> $ty + //@ req scalar_layout(initial) == true; + //@ ens result == replacement; + //@ on_unwind_ens false; + { + let mut storage = initial; + let p = &raw mut storage; + //@ to_u8s_(p); + //@ from_u8s_(p); + //@ let k = begin_lifetime(); + //@ start_integer(p, k); + { + //@ let_lft 'a = k; + let view = unsafe { $atomic::from_ptr/*@::<'a>@*/(p) }; + let raw = view.as_ptr(); + //@ assert raw == p; + //@ open_view_fraction(p, k, currentThread, view, 1/4); + //@ open_view_fraction(p, k, currentThread, view, 1/8); + //@ close_integer(p, k, 1/8); + //@ close_integer(p, k, 1/4); + } + //@ finish_integer(p, k); + let _old = unsafe { *p }; + unsafe { *p = replacement }; + unsafe { *p } + } + }; +} + +check_integer_view!(i8_view, i8, AtomicI8); +check_integer_view!(i16_view, i16, AtomicI16); +check_integer_view!(i32_view, i32, AtomicI32); +check_integer_view!(i64_view, i64, AtomicI64); +check_integer_view!(u64_view, u64, AtomicU64); +#[cfg(target_has_atomic_load_store = "128")] +check_integer_view!(i128_view, i128, AtomicI128); +#[cfg(target_has_atomic_load_store = "128")] +check_integer_view!(u128_view, u128, AtomicU128); diff --git a/verifast-proofs/core/sync/atomic.rs/intrinsic-manifest.tsv b/verifast-proofs/core/sync/atomic.rs/intrinsic-manifest.tsv new file mode 100644 index 0000000000000..7d56b2906fb5d --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/intrinsic-manifest.tsv @@ -0,0 +1,92 @@ +challenge_entry public_method unsafe_helper listed_part2 compiler_intrinsic ordering +atomic_store_relaxed Atomic::store atomic_store yes atomic_store Relaxed +atomic_store_release Atomic::store atomic_store yes atomic_store Release +atomic_store_seqcst Atomic::store atomic_store yes atomic_store SeqCst +atomic_load_relaxed Atomic::load atomic_load yes atomic_load Relaxed +atomic_load_acquire Atomic::load atomic_load yes atomic_load Acquire +atomic_load_seqcst Atomic::load atomic_load yes atomic_load SeqCst +atomic_xchg_relaxed Atomic::swap atomic_swap yes atomic_xchg Relaxed +atomic_xchg_acquire Atomic::swap atomic_swap yes atomic_xchg Acquire +atomic_xchg_release Atomic::swap atomic_swap yes atomic_xchg Release +atomic_xchg_acqrel Atomic::swap atomic_swap yes atomic_xchg AcqRel +atomic_xchg_seqcst Atomic::swap atomic_swap yes atomic_xchg SeqCst +atomic_xadd_relaxed Atomic::fetch_add atomic_add yes atomic_xadd Relaxed +atomic_xadd_acquire Atomic::fetch_add atomic_add yes atomic_xadd Acquire +atomic_xadd_release Atomic::fetch_add atomic_add yes atomic_xadd Release +atomic_xadd_acqrel Atomic::fetch_add atomic_add yes atomic_xadd AcqRel +atomic_xadd_seqcst Atomic::fetch_add atomic_add yes atomic_xadd SeqCst +atomic_xsub_relaxed Atomic::fetch_sub atomic_sub yes atomic_xsub Relaxed +atomic_xsub_acquire Atomic::fetch_sub atomic_sub yes atomic_xsub Acquire +atomic_xsub_release Atomic::fetch_sub atomic_sub yes atomic_xsub Release +atomic_xsub_acqrel Atomic::fetch_sub atomic_sub yes atomic_xsub AcqRel +atomic_xsub_seqcst Atomic::fetch_sub atomic_sub yes atomic_xsub SeqCst +atomic_cxchg_relaxed_relaxed Atomic::compare_exchange atomic_compare_exchange yes atomic_cxchg Relaxed/Relaxed +atomic_cxchg_relaxed_acquire Atomic::compare_exchange atomic_compare_exchange yes atomic_cxchg Relaxed/Acquire +atomic_cxchg_relaxed_seqcst Atomic::compare_exchange atomic_compare_exchange yes atomic_cxchg Relaxed/SeqCst +atomic_cxchg_acquire_relaxed Atomic::compare_exchange atomic_compare_exchange yes atomic_cxchg Acquire/Relaxed +atomic_cxchg_acquire_acquire Atomic::compare_exchange atomic_compare_exchange yes atomic_cxchg Acquire/Acquire +atomic_cxchg_acquire_seqcst Atomic::compare_exchange atomic_compare_exchange yes atomic_cxchg Acquire/SeqCst +atomic_cxchg_release_relaxed Atomic::compare_exchange atomic_compare_exchange yes atomic_cxchg Release/Relaxed +atomic_cxchg_release_acquire Atomic::compare_exchange atomic_compare_exchange yes atomic_cxchg Release/Acquire +atomic_cxchg_release_seqcst Atomic::compare_exchange atomic_compare_exchange yes atomic_cxchg Release/SeqCst +atomic_cxchg_acqrel_relaxed Atomic::compare_exchange atomic_compare_exchange yes atomic_cxchg AcqRel/Relaxed +atomic_cxchg_acqrel_acquire Atomic::compare_exchange atomic_compare_exchange yes atomic_cxchg AcqRel/Acquire +atomic_cxchg_acqrel_seqcst Atomic::compare_exchange atomic_compare_exchange yes atomic_cxchg AcqRel/SeqCst +atomic_cxchg_seqcst_relaxed Atomic::compare_exchange atomic_compare_exchange yes atomic_cxchg SeqCst/Relaxed +atomic_cxchg_seqcst_acquire Atomic::compare_exchange atomic_compare_exchange yes atomic_cxchg SeqCst/Acquire +atomic_cxchg_seqcst_seqcst Atomic::compare_exchange atomic_compare_exchange yes atomic_cxchg SeqCst/SeqCst +atomic_cxchgweak_relaxed_relaxed Atomic::compare_exchange_weak atomic_compare_exchange_weak yes atomic_cxchgweak Relaxed/Relaxed +atomic_cxchgweak_relaxed_acquire Atomic::compare_exchange_weak atomic_compare_exchange_weak yes atomic_cxchgweak Relaxed/Acquire +atomic_cxchgweak_relaxed_seqcst Atomic::compare_exchange_weak atomic_compare_exchange_weak yes atomic_cxchgweak Relaxed/SeqCst +atomic_cxchgweak_acquire_relaxed Atomic::compare_exchange_weak atomic_compare_exchange_weak yes atomic_cxchgweak Acquire/Relaxed +atomic_cxchgweak_acquire_acquire Atomic::compare_exchange_weak atomic_compare_exchange_weak yes atomic_cxchgweak Acquire/Acquire +atomic_cxchgweak_acquire_seqcst Atomic::compare_exchange_weak atomic_compare_exchange_weak yes atomic_cxchgweak Acquire/SeqCst +atomic_cxchgweak_release_relaxed Atomic::compare_exchange_weak atomic_compare_exchange_weak yes atomic_cxchgweak Release/Relaxed +atomic_cxchgweak_release_acquire Atomic::compare_exchange_weak atomic_compare_exchange_weak yes atomic_cxchgweak Release/Acquire +atomic_cxchgweak_release_seqcst Atomic::compare_exchange_weak atomic_compare_exchange_weak yes atomic_cxchgweak Release/SeqCst +atomic_cxchgweak_acqrel_relaxed Atomic::compare_exchange_weak atomic_compare_exchange_weak yes atomic_cxchgweak AcqRel/Relaxed +atomic_cxchgweak_acqrel_acquire Atomic::compare_exchange_weak atomic_compare_exchange_weak yes atomic_cxchgweak AcqRel/Acquire +atomic_cxchgweak_acqrel_seqcst Atomic::compare_exchange_weak atomic_compare_exchange_weak yes atomic_cxchgweak AcqRel/SeqCst +atomic_cxchgweak_seqcst_relaxed Atomic::compare_exchange_weak atomic_compare_exchange_weak yes atomic_cxchgweak SeqCst/Relaxed +atomic_cxchgweak_seqcst_acquire Atomic::compare_exchange_weak atomic_compare_exchange_weak yes atomic_cxchgweak SeqCst/Acquire +atomic_cxchgweak_seqcst_seqcst Atomic::compare_exchange_weak atomic_compare_exchange_weak yes atomic_cxchgweak SeqCst/SeqCst +atomic_and_relaxed Atomic::fetch_and atomic_and yes atomic_and Relaxed +atomic_and_acquire Atomic::fetch_and atomic_and yes atomic_and Acquire +atomic_and_release Atomic::fetch_and atomic_and yes atomic_and Release +atomic_and_acqrel Atomic::fetch_and atomic_and yes atomic_and AcqRel +atomic_and_seqcst Atomic::fetch_and atomic_and yes atomic_and SeqCst +atomic_nand_relaxed Atomic::fetch_nand atomic_nand yes atomic_nand Relaxed +atomic_nand_acquire Atomic::fetch_nand atomic_nand yes atomic_nand Acquire +atomic_nand_release Atomic::fetch_nand atomic_nand yes atomic_nand Release +atomic_nand_acqrel Atomic::fetch_nand atomic_nand yes atomic_nand AcqRel +atomic_nand_seqcst Atomic::fetch_nand atomic_nand yes atomic_nand SeqCst +atomic_or_seqcst Atomic::fetch_or atomic_or yes atomic_or SeqCst +atomic_or_acquire Atomic::fetch_or atomic_or yes atomic_or Acquire +atomic_or_release Atomic::fetch_or atomic_or yes atomic_or Release +atomic_or_acqrel Atomic::fetch_or atomic_or yes atomic_or AcqRel +atomic_or_relaxed Atomic::fetch_or atomic_or yes atomic_or Relaxed +atomic_xor_seqcst Atomic::fetch_xor atomic_xor yes atomic_xor SeqCst +atomic_xor_acquire Atomic::fetch_xor atomic_xor yes atomic_xor Acquire +atomic_xor_release Atomic::fetch_xor atomic_xor yes atomic_xor Release +atomic_xor_acqrel Atomic::fetch_xor atomic_xor yes atomic_xor AcqRel +atomic_xor_relaxed Atomic::fetch_xor atomic_xor yes atomic_xor Relaxed +atomic_max_relaxed Atomic::fetch_max atomic_max yes atomic_max Relaxed +atomic_max_acquire Atomic::fetch_max atomic_max yes atomic_max Acquire +atomic_max_release Atomic::fetch_max atomic_max yes atomic_max Release +atomic_max_acqrel Atomic::fetch_max atomic_max yes atomic_max AcqRel +atomic_max_seqcst Atomic::fetch_max atomic_max yes atomic_max SeqCst +atomic_min_relaxed Atomic::fetch_min atomic_min no atomic_min Relaxed +atomic_min_acquire Atomic::fetch_min atomic_min no atomic_min Acquire +atomic_min_release Atomic::fetch_min atomic_min no atomic_min Release +atomic_min_acqrel Atomic::fetch_min atomic_min no atomic_min AcqRel +atomic_min_seqcst Atomic::fetch_min atomic_min no atomic_min SeqCst +atomic_umax_relaxed Atomic::fetch_max atomic_umax yes atomic_umax Relaxed +atomic_umax_acquire Atomic::fetch_max atomic_umax yes atomic_umax Acquire +atomic_umax_release Atomic::fetch_max atomic_umax yes atomic_umax Release +atomic_umax_acqrel Atomic::fetch_max atomic_umax yes atomic_umax AcqRel +atomic_umax_seqcst Atomic::fetch_max atomic_umax yes atomic_umax SeqCst +atomic_umin_relaxed Atomic::fetch_min atomic_umin yes atomic_umin Relaxed +atomic_umin_acquire Atomic::fetch_min atomic_umin yes atomic_umin Acquire +atomic_umin_release Atomic::fetch_min atomic_umin yes atomic_umin Release +atomic_umin_acqrel Atomic::fetch_min atomic_umin yes atomic_umin AcqRel +atomic_umin_seqcst Atomic::fetch_min atomic_umin yes atomic_umin SeqCst diff --git a/verifast-proofs/core/sync/atomic.rs/original/atomic.rs b/verifast-proofs/core/sync/atomic.rs/original/atomic.rs new file mode 100644 index 0000000000000..83042919c1aac --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/original/atomic.rs @@ -0,0 +1,6556 @@ +//! Atomic types +//! +//! Atomic types provide primitive shared-memory communication between +//! threads, and are the building blocks of other concurrent +//! types. +//! +//! This module defines atomic versions of a select number of primitive +//! types, including [`AtomicBool`], [`AtomicIsize`], [`AtomicUsize`], +//! [`AtomicI8`], [`AtomicU16`], etc. +//! Atomic types present operations that, when used correctly, synchronize +//! updates between threads. +//! +//! Atomic variables are safe to share between threads (they implement [`Sync`]) +//! but they do not themselves provide the mechanism for sharing and follow the +//! [threading model](../../../std/thread/index.html#the-threading-model) of Rust. +//! The most common way to share an atomic variable is to put it into an [`Arc`][arc] (an +//! atomically-reference-counted shared pointer). +//! +//! [arc]: ../../../std/sync/struct.Arc.html +//! +//! Atomic types may be stored in static variables, initialized using +//! the constant initializers like [`AtomicBool::new`]. Atomic statics +//! are often used for lazy global initialization. +//! +//! ## Memory model for atomic accesses +//! +//! Rust atomics currently follow the same rules as [C++20 atomics][cpp], specifically the rules +//! from the [`intro.races`][cpp-intro.races] section, without the "consume" memory ordering. Since +//! C++ uses an object-based memory model whereas Rust is access-based, a bit of translation work +//! has to be done to apply the C++ rules to Rust: whenever C++ talks about "the value of an +//! object", we understand that to mean the resulting bytes obtained when doing a read. When the C++ +//! standard talks about "the value of an atomic object", this refers to the result of doing an +//! atomic load (via the operations provided in this module). A "modification of an atomic object" +//! refers to an atomic store. +//! +//! The end result is *almost* equivalent to saying that creating a *shared reference* to one of the +//! Rust atomic types corresponds to creating an `atomic_ref` in C++, with the `atomic_ref` being +//! destroyed when the lifetime of the shared reference ends. The main difference is that Rust +//! permits concurrent atomic and non-atomic reads to the same memory as those cause no issue in the +//! C++ memory model, they are just forbidden in C++ because memory is partitioned into "atomic +//! objects" and "non-atomic objects" (with `atomic_ref` temporarily converting a non-atomic object +//! into an atomic object). +//! +//! The most important aspect of this model is that *data races* are undefined behavior. A data race +//! is defined as conflicting non-synchronized accesses where at least one of the accesses is +//! non-atomic. Here, accesses are *conflicting* if they affect overlapping regions of memory and at +//! least one of them is a write. (A `compare_exchange` or `compare_exchange_weak` that does not +//! succeed is not considered a write.) They are *non-synchronized* if neither of them +//! *happens-before* the other, according to the happens-before order of the memory model. +//! +//! The other possible cause of undefined behavior in the memory model are mixed-size accesses: Rust +//! inherits the C++ limitation that non-synchronized conflicting atomic accesses may not partially +//! overlap. In other words, every pair of non-synchronized atomic accesses must be either disjoint, +//! access the exact same memory (including using the same access size), or both be reads. +//! +//! Each atomic access takes an [`Ordering`] which defines how the operation interacts with the +//! happens-before order. These orderings behave the same as the corresponding [C++20 atomic +//! orderings][cpp_memory_order]. For more information, see the [nomicon]. +//! +//! [cpp]: https://en.cppreference.com/w/cpp/atomic +//! [cpp-intro.races]: https://timsong-cpp.github.io/cppwp/n4868/intro.multithread#intro.races +//! [cpp_memory_order]: https://en.cppreference.com/w/cpp/atomic/memory_order +//! [nomicon]: ../../../nomicon/atomics.html +//! +//! ```rust,no_run undefined_behavior +//! use std::sync::atomic::{AtomicU16, AtomicU8, Ordering}; +//! use std::mem::transmute; +//! use std::thread; +//! +//! let atomic = AtomicU16::new(0); +//! +//! thread::scope(|s| { +//! // This is UB: conflicting non-synchronized accesses, at least one of which is non-atomic. +//! s.spawn(|| atomic.store(1, Ordering::Relaxed)); // atomic store +//! s.spawn(|| unsafe { atomic.as_ptr().write(2) }); // non-atomic write +//! }); +//! +//! thread::scope(|s| { +//! // This is fine: the accesses do not conflict (as none of them performs any modification). +//! // In C++ this would be disallowed since creating an `atomic_ref` precludes +//! // further non-atomic accesses, but Rust does not have that limitation. +//! s.spawn(|| atomic.load(Ordering::Relaxed)); // atomic load +//! s.spawn(|| unsafe { atomic.as_ptr().read() }); // non-atomic read +//! }); +//! +//! thread::scope(|s| { +//! // This is fine: `join` synchronizes the code in a way such that the atomic +//! // store happens-before the non-atomic write. +//! let handle = s.spawn(|| atomic.store(1, Ordering::Relaxed)); // atomic store +//! handle.join().expect("thread won't panic"); // synchronize +//! s.spawn(|| unsafe { atomic.as_ptr().write(2) }); // non-atomic write +//! }); +//! +//! thread::scope(|s| { +//! // This is UB: non-synchronized conflicting differently-sized atomic accesses. +//! s.spawn(|| atomic.store(1, Ordering::Relaxed)); +//! s.spawn(|| unsafe { +//! let differently_sized = transmute::<&AtomicU16, &AtomicU8>(&atomic); +//! differently_sized.store(2, Ordering::Relaxed); +//! }); +//! }); +//! +//! thread::scope(|s| { +//! // This is fine: `join` synchronizes the code in a way such that +//! // the 1-byte store happens-before the 2-byte store. +//! let handle = s.spawn(|| atomic.store(1, Ordering::Relaxed)); +//! handle.join().expect("thread won't panic"); +//! s.spawn(|| unsafe { +//! let differently_sized = transmute::<&AtomicU16, &AtomicU8>(&atomic); +//! differently_sized.store(2, Ordering::Relaxed); +//! }); +//! }); +//! ``` +//! +//! # Portability +//! +//! All atomic types in this module are guaranteed to be [lock-free] if they're +//! available. This means they don't internally acquire a global mutex. Atomic +//! types and operations are not guaranteed to be wait-free. This means that +//! operations like `fetch_or` may be implemented with a compare-and-swap loop. +//! +//! Atomic operations may be implemented at the instruction layer with +//! larger-size atomics. For example some platforms use 4-byte atomic +//! instructions to implement `AtomicI8`. Note that this emulation should not +//! have an impact on correctness of code, it's just something to be aware of. +//! +//! The atomic types in this module might not be available on all platforms. The +//! atomic types here are all widely available, however, and can generally be +//! relied upon existing. Some notable exceptions are: +//! +//! * PowerPC and MIPS platforms with 32-bit pointers do not have `AtomicU64` or +//! `AtomicI64` types. +//! * Legacy ARM platforms like ARMv4T and ARMv5TE have very limited hardware +//! support for atomics. The bare-metal targets disable this module +//! entirely, but the Linux targets [use the kernel] to assist (which comes +//! with a performance penalty). It's not until ARMv6K onwards that ARM CPUs +//! have support for load/store and Compare and Swap (CAS) atomics in hardware. +//! * ARMv6-M targets (`thumbv6m-*`) only provide `load` and `store` operations, and do +//! not support Compare and Swap (CAS) operations, such as `swap`, +//! `fetch_add`, etc. Full CAS support is available on ARMv7-M and ARMv8-M +//! (`thumbv7m-*`, `thumbv7em*`, `thumbv8m.base-*` and `thumbv8m.main-*`). +//! +//! [use the kernel]: https://www.kernel.org/doc/Documentation/arm/kernel_user_helpers.txt +//! +//! Note that future platforms may be added that also do not have support for +//! some atomic operations. Maximally portable code will want to be careful +//! about which atomic types are used. `AtomicUsize` and `AtomicIsize` are +//! generally the most portable, but even then they're not available everywhere. +//! For reference, the `std` library requires `AtomicBool`s and pointer-sized atomics, although +//! `core` does not. +//! +//! The `#[cfg(target_has_atomic)]` attribute can be used to conditionally +//! compile based on the target's supported bit widths. It is a key-value +//! option set for each supported size, with values "8", "16", "32", "64", +//! "128", and "ptr" for pointer-sized atomics. +//! +//! [lock-free]: https://en.wikipedia.org/wiki/Non-blocking_algorithm +//! +//! # Atomic accesses to read-only memory +//! +//! In general, *all* atomic accesses on read-only memory are undefined behavior. For instance, attempting +//! to do a `compare_exchange` that will definitely fail (making it conceptually a read-only +//! operation) can still cause a segmentation fault if the underlying memory page is mapped read-only. Since +//! atomic `load`s might be implemented using compare-exchange operations, even a `load` can fault +//! on read-only memory. +//! +//! For the purpose of this section, "read-only memory" is defined as memory that is read-only in +//! the underlying target, i.e., the pages are mapped with a read-only flag and any attempt to write +//! will cause a page fault. In particular, an `&u128` reference that points to memory that is +//! read-write mapped is *not* considered to point to "read-only memory". In Rust, almost all memory +//! is read-write; the only exceptions are memory created by `const` items or `static` items without +//! interior mutability, and memory that was specifically marked as read-only by the operating +//! system via platform-specific APIs. +//! +//! As an exception from the general rule stated above, "sufficiently small" atomic loads with +//! `Ordering::Relaxed` are implemented in a way that works on read-only memory, and are hence not +//! undefined behavior. The exact size limit for what makes a load "sufficiently small" varies +//! depending on the target: +//! +//! | `target_arch` | Size limit | +//! |---------------|---------| +//! | `x86`, `arm`, `loongarch32`, `mips`, `mips32r6`, `powerpc`, `riscv32`, `sparc`, `hexagon` | 4 bytes | +//! | `x86_64`, `aarch64`, `loongarch64`, `mips64`, `mips64r6`, `powerpc64`, `riscv64`, `sparc64`, `s390x` | 8 bytes | +//! +//! Atomics loads that are larger than this limit as well as atomic loads with ordering other +//! than `Relaxed`, as well as *all* atomic loads on targets not listed in the table, might still be +//! read-only under certain conditions, but that is not a stable guarantee and should not be relied +//! upon. +//! +//! If you need to do an acquire load on read-only memory, you can do a relaxed load followed by an +//! acquire fence instead. +//! +//! # Examples +//! +//! A simple spinlock: +//! +//! ```ignore-wasm +//! use std::sync::Arc; +//! use std::sync::atomic::{AtomicUsize, Ordering}; +//! use std::{hint, thread}; +//! +//! fn main() { +//! let spinlock = Arc::new(AtomicUsize::new(1)); +//! +//! let spinlock_clone = Arc::clone(&spinlock); +//! +//! let thread = thread::spawn(move || { +//! spinlock_clone.store(0, Ordering::Release); +//! }); +//! +//! // Wait for the other thread to release the lock +//! while spinlock.load(Ordering::Acquire) != 0 { +//! hint::spin_loop(); +//! } +//! +//! if let Err(panic) = thread.join() { +//! println!("Thread had an error: {panic:?}"); +//! } +//! } +//! ``` +//! +//! Keep a global count of live threads: +//! +//! ``` +//! use std::sync::atomic::{AtomicUsize, Ordering}; +//! +//! static GLOBAL_THREAD_COUNT: AtomicUsize = AtomicUsize::new(0); +//! +//! // Note that Relaxed ordering doesn't synchronize anything +//! // except the global thread counter itself. +//! let old_thread_count = GLOBAL_THREAD_COUNT.fetch_add(1, Ordering::Relaxed); +//! // Note that this number may not be true at the moment of printing +//! // because some other thread may have changed static value already. +//! println!("live threads: {}", old_thread_count + 1); +//! ``` + +#![stable(feature = "rust1", since = "1.0.0")] +#![cfg_attr(not(target_has_atomic_load_store = "8"), allow(dead_code))] +#![cfg_attr(not(target_has_atomic_load_store = "8"), allow(unused_imports))] +// Clippy complains about the pattern of "safe function calling unsafe function taking pointers". +// This happens with AtomicPtr intrinsics but is fine, as the pointers clippy is concerned about +// are just normal values that get loaded/stored, but not dereferenced. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use safety::{ensures, requires}; + +use self::Ordering::*; +use crate::cell::UnsafeCell; +use crate::hint::spin_loop; +use crate::intrinsics::AtomicOrdering as AO; +#[cfg(kani)] +use crate::kani; +use crate::mem::transmute; +#[cfg(kani)] +use crate::ub_checks; +use crate::{fmt, intrinsics}; + +#[unstable( + feature = "atomic_internals", + reason = "implementation detail which may disappear or be replaced at any time", + issue = "none" +)] +#[expect(missing_debug_implementations)] +mod private { + #[cfg(target_has_atomic_load_store = "8")] + #[repr(C, align(1))] + pub struct Align1(T); + #[cfg(target_has_atomic_load_store = "16")] + #[repr(C, align(2))] + pub struct Align2(T); + #[cfg(target_has_atomic_load_store = "32")] + #[repr(C, align(4))] + pub struct Align4(T); + #[cfg(target_has_atomic_load_store = "64")] + #[repr(C, align(8))] + pub struct Align8(T); + #[cfg(any(target_has_atomic_load_store = "128", doc))] + #[repr(C, align(16))] + pub struct Align16(T); +} + +/// A marker trait for primitive types which can be modified atomically. +/// +/// This is an implementation detail for [Atomic]\ which may disappear or be replaced at any time. +// +// # Safety +// +// Types implementing this trait must be primitives that can be modified atomically. +// +// The associated `Self::Storage` type must have the same size, but may have fewer validity +// invariants or a higher alignment requirement than `Self`. +#[unstable( + feature = "atomic_internals", + reason = "implementation detail which may disappear or be replaced at any time", + issue = "none" +)] +pub impl(self) unsafe trait AtomicPrimitive: Sized + Copy { + /// Temporary implementation detail. + type Storage: Sized; +} + +macro impl_atomic_primitive { + ( + @impl [$($T:ident)?] $Primitive:ty as $Storage:ident<$Operand:ty>, + $cfg:meta + ) => { + #[unstable( + feature = "atomic_internals", + reason = "implementation detail which may disappear or be replaced at any time", + issue = "none" + )] + #[cfg($cfg)] + unsafe impl $(<$T>)? AtomicPrimitive for $Primitive { + type Storage = private::$Storage<$Operand>; + } + }, + + ( + [$($T:ident)?] $Primitive:ty as $Storage:ident<$Operand:ty>, + size($size:literal) + ) => { + impl_atomic_primitive!( + @impl [$($T)?] $Primitive as $Storage<$Operand>, + target_has_atomic_load_store = $size + ); + }, + + ( + [$($T:ident)?] $Primitive:ty as $Storage:ident<$Operand:ty>, + size($size:literal), + doc + ) => { + impl_atomic_primitive!( + @impl [$($T)?] $Primitive as $Storage<$Operand>, + any(target_has_atomic_load_store = $size, doc) + ); + }, +} + +impl_atomic_primitive!([] bool as Align1, size("8")); +impl_atomic_primitive!([] i8 as Align1, size("8")); +impl_atomic_primitive!([] u8 as Align1, size("8")); +impl_atomic_primitive!([] i16 as Align2, size("16")); +impl_atomic_primitive!([] u16 as Align2, size("16")); +impl_atomic_primitive!([] i32 as Align4, size("32")); +impl_atomic_primitive!([] u32 as Align4, size("32")); +impl_atomic_primitive!([] i64 as Align8, size("64")); +impl_atomic_primitive!([] u64 as Align8, size("64")); +impl_atomic_primitive!([] i128 as Align16, size("128"), doc); +impl_atomic_primitive!([] u128 as Align16, size("128"), doc); + +#[cfg(target_pointer_width = "16")] +impl_atomic_primitive!([] isize as Align2, size("ptr")); +#[cfg(target_pointer_width = "32")] +impl_atomic_primitive!([] isize as Align4, size("ptr")); +#[cfg(target_pointer_width = "64")] +impl_atomic_primitive!([] isize as Align8, size("ptr")); + +#[cfg(target_pointer_width = "16")] +impl_atomic_primitive!([] usize as Align2, size("ptr")); +#[cfg(target_pointer_width = "32")] +impl_atomic_primitive!([] usize as Align4, size("ptr")); +#[cfg(target_pointer_width = "64")] +impl_atomic_primitive!([] usize as Align8, size("ptr")); + +#[cfg(target_pointer_width = "16")] +impl_atomic_primitive!([T] *mut T as Align2<*mut T>, size("ptr")); +#[cfg(target_pointer_width = "32")] +impl_atomic_primitive!([T] *mut T as Align4<*mut T>, size("ptr")); +#[cfg(target_pointer_width = "64")] +impl_atomic_primitive!([T] *mut T as Align8<*mut T>, size("ptr")); + +/// A memory location which can be safely modified from multiple threads. +/// +/// This has the same size and bit validity as the underlying type `T`. However, +/// the alignment of this type is always equal to its size, even on targets where +/// `T` has alignment less than its size. +/// +/// For more about the differences between atomic types and non-atomic types as +/// well as information about the portability of this type, please see the +/// [module-level documentation]. +/// +/// **Note:** This type is only available on platforms that support atomic loads +/// and stores of `T`. +/// +/// [module-level documentation]: crate::sync::atomic +#[unstable(feature = "generic_atomic", issue = "130539")] +#[repr(C)] +#[rustc_diagnostic_item = "Atomic"] +pub struct Atomic { + v: UnsafeCell, +} + +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl Send for Atomic {} +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl Sync for Atomic {} + +// Some architectures don't have byte-sized atomics, which results in LLVM +// emulating them using a LL/SC loop. However for AtomicBool we can take +// advantage of the fact that it only ever contains 0 or 1 and use atomic OR/AND +// instead, which LLVM can emulate using a larger atomic OR/AND operation. +// +// This list should only contain architectures which have word-sized atomic-or/ +// atomic-and instructions but don't natively support byte-sized atomics. +#[cfg(target_has_atomic = "8")] +const EMULATE_ATOMIC_BOOL: bool = cfg!(any( + target_arch = "riscv32", + target_arch = "riscv64", + target_arch = "loongarch32", + target_arch = "loongarch64" +)); + +/// A boolean type which can be safely shared between threads. +/// +/// This type has the same size, alignment, and bit validity as a [`bool`]. +/// +/// **Note**: This type is only available on platforms that support atomic +/// loads and stores of `u8`. +#[cfg(target_has_atomic_load_store = "8")] +#[stable(feature = "rust1", since = "1.0.0")] +pub type AtomicBool = Atomic; + +#[cfg(target_has_atomic_load_store = "8")] +#[stable(feature = "rust1", since = "1.0.0")] +impl Default for AtomicBool { + /// Creates an `AtomicBool` initialized to `false`. + #[inline] + fn default() -> Self { + Self::new(false) + } +} + +/// A raw pointer type which can be safely shared between threads. +/// +/// This type has the same size and bit validity as a `*mut T`. +/// +/// **Note**: This type is only available on platforms that support atomic +/// loads and stores of pointers. Its size depends on the target pointer's size. +#[cfg(target_has_atomic_load_store = "ptr")] +#[stable(feature = "rust1", since = "1.0.0")] +pub type AtomicPtr = Atomic<*mut T>; + +#[cfg(target_has_atomic_load_store = "ptr")] +#[stable(feature = "rust1", since = "1.0.0")] +impl Default for AtomicPtr { + /// Creates a null `AtomicPtr`. + fn default() -> AtomicPtr { + AtomicPtr::new(crate::ptr::null_mut()) + } +} + +/// Atomic memory orderings +/// +/// Memory orderings specify the way atomic operations synchronize memory. +/// In its weakest [`Ordering::Relaxed`], only the memory directly touched by the +/// operation is synchronized. On the other hand, a store-load pair of [`Ordering::SeqCst`] +/// operations synchronize other memory while additionally preserving a total order of such +/// operations across all threads. +/// +/// Rust's memory orderings are [the same as those of +/// C++20](https://en.cppreference.com/w/cpp/atomic/memory_order). +/// +/// For more information see the [nomicon]. +/// +/// [nomicon]: ../../../nomicon/atomics.html +#[stable(feature = "rust1", since = "1.0.0")] +#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] +#[non_exhaustive] +#[rustc_diagnostic_item = "Ordering"] +pub enum Ordering { + /// No ordering constraints, only atomic operations. + /// + /// Corresponds to [`memory_order_relaxed`] in C++20. + /// + /// [`memory_order_relaxed`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Relaxed_ordering + #[stable(feature = "rust1", since = "1.0.0")] + Relaxed, + /// When coupled with a store, all previous operations become ordered + /// before any load of this value with [`Acquire`] (or stronger) ordering. + /// In particular, all previous writes become visible to all threads + /// that perform an [`Acquire`] (or stronger) load of this value. + /// + /// Notice that using this ordering for an operation that combines loads + /// and stores leads to a [`Relaxed`] load operation! + /// + /// This ordering is only applicable for operations that can perform a store. + /// + /// Corresponds to [`memory_order_release`] in C++20. + /// + /// [`memory_order_release`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Release-Acquire_ordering + #[stable(feature = "rust1", since = "1.0.0")] + Release, + /// When coupled with a load, if the loaded value was written by a store operation with + /// [`Release`] (or stronger) ordering, then all subsequent operations + /// become ordered after that store. In particular, all subsequent loads will see data + /// written before the store. + /// + /// Notice that using this ordering for an operation that combines loads + /// and stores leads to a [`Relaxed`] store operation! + /// + /// This ordering is only applicable for operations that can perform a load. + /// + /// Corresponds to [`memory_order_acquire`] in C++20. + /// + /// [`memory_order_acquire`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Release-Acquire_ordering + #[stable(feature = "rust1", since = "1.0.0")] + Acquire, + /// Has the effects of both [`Acquire`] and [`Release`] together: + /// For loads it uses [`Acquire`] ordering. For stores it uses the [`Release`] ordering. + /// + /// Notice that in the case of `compare_and_swap`, it is possible that the operation ends up + /// not performing any store and hence it has just [`Acquire`] ordering. However, + /// `AcqRel` will never perform [`Relaxed`] accesses. + /// + /// This ordering is only applicable for operations that combine both loads and stores. + /// + /// Corresponds to [`memory_order_acq_rel`] in C++20. + /// + /// [`memory_order_acq_rel`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Release-Acquire_ordering + #[stable(feature = "rust1", since = "1.0.0")] + AcqRel, + /// Like [`Acquire`]/[`Release`]/[`AcqRel`] (for load, store, and load-with-store + /// operations, respectively) with the additional guarantee that all threads see all + /// sequentially consistent operations in the same order. + /// + /// Corresponds to [`memory_order_seq_cst`] in C++20. + /// + /// [`memory_order_seq_cst`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Sequentially-consistent_ordering + #[stable(feature = "rust1", since = "1.0.0")] + SeqCst, +} + +/// An [`AtomicBool`] initialized to `false`. +#[cfg(target_has_atomic_load_store = "8")] +#[stable(feature = "rust1", since = "1.0.0")] +#[deprecated( + since = "1.34.0", + note = "the `new` function is now preferred", + suggestion = "AtomicBool::new(false)" +)] +#[expect(clippy::declare_interior_mutable_const, reason = "legacy atomic initializer")] +pub const ATOMIC_BOOL_INIT: AtomicBool = AtomicBool::new(false); + +#[cfg(target_has_atomic_load_store = "8")] +impl AtomicBool { + /// Creates a new `AtomicBool`. + /// + /// # Examples + /// + /// ``` + /// use std::sync::atomic::AtomicBool; + /// + /// let atomic_true = AtomicBool::new(true); + /// let atomic_false = AtomicBool::new(false); + /// ``` + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_const_stable(feature = "const_atomic_new", since = "1.24.0")] + #[must_use] + pub const fn new(v: bool) -> AtomicBool { + // SAFETY: + // `Atomic` is essentially a transparent wrapper around `T`. + unsafe { transmute(v) } + } + + /// Creates a new `AtomicBool` from a pointer. + /// + /// # Examples + /// + /// ``` + /// use std::sync::atomic::{self, AtomicBool}; + /// + /// // Get a pointer to an allocated value + /// let ptr: *mut bool = Box::into_raw(Box::new(false)); + /// + /// assert!(ptr.cast::().is_aligned()); + /// + /// { + /// // Create an atomic view of the allocated value + /// let atomic = unsafe { AtomicBool::from_ptr(ptr) }; + /// + /// // Use `atomic` for atomic operations, possibly share it with other threads + /// atomic.store(true, atomic::Ordering::Relaxed); + /// } + /// + /// // It's ok to non-atomically access the value behind `ptr`, + /// // since the reference to the atomic ended its lifetime in the block above + /// assert_eq!(unsafe { *ptr }, true); + /// + /// // Deallocate the value + /// unsafe { drop(Box::from_raw(ptr)) } + /// ``` + /// + /// # Safety + /// + /// * `ptr` must be aligned to `align_of::()` (note that this is always true, since + /// `align_of::() == 1`). + /// * `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`. + /// * You must adhere to the [Memory model for atomic accesses]. In particular, it is not + /// allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different + /// sizes, without synchronization. + /// + /// [valid]: crate::ptr#safety + /// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses + #[inline] + #[stable(feature = "atomic_from_ptr", since = "1.75.0")] + #[rustc_const_stable(feature = "const_atomic_from_ptr", since = "1.84.0")] + #[requires(ptr.cast::().is_aligned())] + #[requires(ub_checks::can_dereference(ptr))] + #[requires(ub_checks::can_write(ptr))] + #[ensures(|result: &&AtomicBool| { + core::ptr::eq(*result, ptr.cast::()) + })] + pub const unsafe fn from_ptr<'a>(ptr: *mut bool) -> &'a AtomicBool { + // SAFETY: guaranteed by the caller + unsafe { &*ptr.cast() } + } + + /// Creates a new pointer to `AtomicBool` from a pointer. + /// + /// This is useful if you want to do volatile atomic accesses, and thus avoid creating + /// a reference to the destination. + #[inline] + #[unstable(feature = "atomic_volatile", issue = "158947")] + pub const fn from_ptr_raw(ptr: *mut bool) -> *const AtomicBool { + ptr.cast_const().cast() + } + + /// Returns a mutable reference to the underlying [`bool`]. + /// + /// This is safe because the mutable reference guarantees that no other threads are + /// concurrently accessing the atomic data. + /// + /// # Examples + /// + /// ``` + /// use std::sync::atomic::{AtomicBool, Ordering}; + /// + /// let mut some_bool = AtomicBool::new(true); + /// assert_eq!(*some_bool.get_mut(), true); + /// *some_bool.get_mut() = false; + /// assert_eq!(some_bool.load(Ordering::SeqCst), false); + /// ``` + #[inline] + #[stable(feature = "atomic_access", since = "1.15.0")] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + pub const fn get_mut(&mut self) -> &mut bool { + // SAFETY: the mutable reference guarantees unique ownership. + unsafe { &mut *self.as_ptr() } + } + + /// Gets atomic access to a `&mut bool`. + /// + /// # Examples + /// + /// ``` + /// use std::sync::atomic::{AtomicBool, Ordering}; + /// + /// let mut some_bool = true; + /// let a = AtomicBool::from_mut(&mut some_bool); + /// a.store(false, Ordering::Relaxed); + /// assert_eq!(some_bool, false); + /// ``` + #[inline] + #[cfg(target_has_atomic_primitive_alignment = "8")] + #[stable(feature = "atomic_from_mut", since = "1.98.0")] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + pub const fn from_mut(v: &mut bool) -> &mut Self { + // SAFETY: the mutable reference guarantees unique ownership, and + // alignment of both `bool` and `Self` is 1. + unsafe { &mut *(v as *mut bool as *mut Self) } + } + + /// Gets non-atomic access to a `&mut [AtomicBool]` slice. + /// + /// This is safe because the mutable reference guarantees that no other threads are + /// concurrently accessing the atomic data. + /// + /// # Examples + /// + /// ```ignore-wasm + /// use std::sync::atomic::{AtomicBool, Ordering}; + /// + /// let mut some_bools = [const { AtomicBool::new(false) }; 10]; + /// + /// let view: &mut [bool] = AtomicBool::get_mut_slice(&mut some_bools); + /// assert_eq!(view, [false; 10]); + /// view[..5].copy_from_slice(&[true; 5]); + /// + /// std::thread::scope(|s| { + /// for t in &some_bools[..5] { + /// s.spawn(move || assert_eq!(t.load(Ordering::Relaxed), true)); + /// } + /// + /// for f in &some_bools[5..] { + /// s.spawn(move || assert_eq!(f.load(Ordering::Relaxed), false)); + /// } + /// }); + /// ``` + #[inline] + #[stable(feature = "atomic_from_mut", since = "1.98.0")] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + pub const fn get_mut_slice(this: &mut [Self]) -> &mut [bool] { + // SAFETY: the mutable reference guarantees unique ownership. + unsafe { &mut *(this as *mut [Self] as *mut [bool]) } + } + + /// Gets atomic access to a `&mut [bool]` slice. + /// + /// # Examples + /// + /// ```rust,ignore-wasm + /// use std::sync::atomic::{AtomicBool, Ordering}; + /// + /// let mut some_bools = [false; 10]; + /// let a = &*AtomicBool::from_mut_slice(&mut some_bools); + /// std::thread::scope(|s| { + /// for i in 0..a.len() { + /// s.spawn(move || a[i].store(true, Ordering::Relaxed)); + /// } + /// }); + /// assert_eq!(some_bools, [true; 10]); + /// ``` + #[inline] + #[cfg(target_has_atomic_primitive_alignment = "8")] + #[stable(feature = "atomic_from_mut", since = "1.98.0")] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + pub const fn from_mut_slice(v: &mut [bool]) -> &mut [Self] { + // SAFETY: the mutable reference guarantees unique ownership, and + // alignment of both `bool` and `Self` is 1. + unsafe { &mut *(v as *mut [bool] as *mut [Self]) } + } + + /// Consumes the atomic and returns the contained value. + /// + /// This is safe because passing `self` by value guarantees that no other threads are + /// concurrently accessing the atomic data. + /// + /// # Examples + /// + /// ``` + /// use std::sync::atomic::AtomicBool; + /// + /// let some_bool = AtomicBool::new(true); + /// assert_eq!(some_bool.into_inner(), true); + /// ``` + #[inline] + #[stable(feature = "atomic_access", since = "1.15.0")] + #[rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0")] + pub const fn into_inner(self) -> bool { + // SAFETY: + // * `Atomic` is essentially a transparent wrapper around `T`. + // * all operations on `Atomic` ensure that `T::Storage` remains + // a valid `bool`. + unsafe { transmute(self) } + } + + /// Loads a value from the bool. + /// + /// `load` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`]. + /// + /// # Panics + /// + /// Panics if `order` is [`Release`] or [`AcqRel`]. + /// + /// # Examples + /// + /// ``` + /// use std::sync::atomic::{AtomicBool, Ordering}; + /// + /// let some_bool = AtomicBool::new(true); + /// + /// assert_eq!(some_bool.load(Ordering::Relaxed), true); + /// ``` + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[requires(order == Relaxed || order == Acquire || order == SeqCst)] + pub const fn load(&self, order: Ordering) -> bool { + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { + atomic_load::<_, /* VOLATILE */ false>(self.v.get().cast::(), order) != 0 + } + } + + /// Perform a volatile atomic load from the bool. + /// + /// `load_volatile` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`]. + /// + #[doc = include_str!("./atomic_load_volatile.md")] + /// + /// # Safety + /// + /// Behavior is undefined if any of the following conditions are violated: + /// + /// * `self` must be [valid] for reads, or `self` must point to memory + /// outside of all Rust allocations and reading from that memory must: + /// - not trap, and + /// - not cause any memory inside a Rust allocation to be modified. + /// + /// * Reading from `self` must produce a properly initialized value of type `bool`. + /// + /// [valid]: core::ptr#safety + /// + /// # Panics + /// + /// Panics if `order` is [`Release`] or [`AcqRel`]. + #[inline] + #[unstable(feature = "atomic_volatile", issue = "158947")] + #[rustc_const_unstable(feature = "atomic_volatile", issue = "158947")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub const unsafe fn load_volatile(self: *const Self, order: Ordering) -> bool { + // SAFETY: follows from our own safety requirements. + unsafe { + atomic_load::<_, /* VOLATILE */ true>(self.cast::(), order) != 0 + } + } + + /// Stores a value into the bool. + /// + /// `store` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. Possible values are [`SeqCst`], [`Release`] and [`Relaxed`]. + /// + /// # Panics + /// + /// Panics if `order` is [`Acquire`] or [`AcqRel`]. + /// + /// # Examples + /// + /// ``` + /// use std::sync::atomic::{AtomicBool, Ordering}; + /// + /// let some_bool = AtomicBool::new(true); + /// + /// some_bool.store(false, Ordering::Relaxed); + /// assert_eq!(some_bool.load(Ordering::Relaxed), false); + /// ``` + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[requires(order == Relaxed || order == Release || order == SeqCst)] + #[cfg_attr(kani, kani::modifies(self))] + pub const fn store(&self, val: bool, order: Ordering) { + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { + atomic_store::<_, /* VOLATILE */ false>(self.v.get().cast::(), val as u8, order); + } + } + + /// Performs a volatile atomic store into the bool. + /// + /// `store_volatile` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. Possible values are [`SeqCst`], [`Release`] and [`Relaxed`]. + /// + #[doc = include_str!("./atomic_store_volatile.md")] + /// + /// # Safety + /// + /// Behavior is undefined if any of the following conditions are violated: + /// + /// * `self` must be either [valid] for writes, or `self` must point to memory + /// outside of all Rust allocations and writing to that memory must: + /// - not trap, and + /// - not cause any memory inside a Rust allocation to be modified. + /// + /// [valid]: core::ptr#safety + /// + /// # Panics + /// + /// Panics if `order` is [`Acquire`] or [`AcqRel`]. + #[inline] + #[unstable(feature = "atomic_volatile", issue = "158947")] + #[rustc_const_unstable(feature = "atomic_volatile", issue = "158947")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + pub const unsafe fn store_volatile(self: *const Self, val: bool, order: Ordering) { + // SAFETY: follows from our own safety requirements. + unsafe { + atomic_store::<_, /* VOLATILE */ true>(self.cast::().cast_mut(), val as u8, order); + } + } + + /// Stores a value into the bool, returning the previous value. + /// + /// `swap` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + /// + /// **Note:** This method is only available on platforms that support atomic + /// operations on `u8`. + /// + /// # Examples + /// + /// ``` + /// use std::sync::atomic::{AtomicBool, Ordering}; + /// + /// let some_bool = AtomicBool::new(true); + /// + /// assert_eq!(some_bool.swap(false, Ordering::Relaxed), true); + /// assert_eq!(some_bool.load(Ordering::Relaxed), false); + /// ``` + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[cfg(target_has_atomic = "8")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] + pub const fn swap(&self, val: bool, order: Ordering) -> bool { + if EMULATE_ATOMIC_BOOL { + if val { self.fetch_or(true, order) } else { self.fetch_and(false, order) } + } else { + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_swap(self.v.get().cast::(), val as u8, order) != 0 } + } + } + + /// Stores a value into the [`bool`] if the current value is the same as the `current` value. + /// + /// The return value is always the previous value. If it is equal to `current`, then the value + /// was updated. + /// + /// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory + /// ordering of this operation. Notice that even when using [`AcqRel`], the operation + /// might fail and hence just perform an `Acquire` load, but not have `Release` semantics. + /// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it + /// happens, and using [`Release`] makes the load part [`Relaxed`]. + /// + /// **Note:** This method is only available on platforms that support atomic + /// operations on `u8`. + /// + /// # Migrating to `compare_exchange` and `compare_exchange_weak` + /// + /// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for + /// memory orderings: + /// + /// Original | Success | Failure + /// -------- | ------- | ------- + /// Relaxed | Relaxed | Relaxed + /// Acquire | Acquire | Acquire + /// Release | Release | Relaxed + /// AcqRel | AcqRel | Acquire + /// SeqCst | SeqCst | SeqCst + /// + /// `compare_and_swap` and `compare_exchange` also differ in their return type. You can use + /// `compare_exchange(...).unwrap_or_else(|x| x)` to recover the behavior of `compare_and_swap`, + /// but in most cases it is more idiomatic to check whether the return value is `Ok` or `Err` + /// rather than to infer success vs failure based on the value that was read. + /// + /// During migration, consider whether it makes sense to use `compare_exchange_weak` instead. + /// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds, + /// which allows the compiler to generate better assembly code when the compare and swap + /// is used in a loop. + /// + /// # Examples + /// + /// ``` + /// use std::sync::atomic::{AtomicBool, Ordering}; + /// + /// let some_bool = AtomicBool::new(true); + /// + /// assert_eq!(some_bool.compare_and_swap(true, false, Ordering::Relaxed), true); + /// assert_eq!(some_bool.load(Ordering::Relaxed), false); + /// + /// assert_eq!(some_bool.compare_and_swap(true, true, Ordering::Relaxed), false); + /// assert_eq!(some_bool.load(Ordering::Relaxed), false); + /// ``` + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[deprecated( + since = "1.50.0", + note = "Use `compare_exchange` or `compare_exchange_weak` instead" + )] + #[cfg(target_has_atomic = "8")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] + pub const fn compare_and_swap(&self, current: bool, new: bool, order: Ordering) -> bool { + match self.compare_exchange(current, new, order, strongest_failure_ordering(order)) { + Ok(x) => x, + Err(x) => x, + } + } + + /// Stores a value into the [`bool`] if the current value is the same as the `current` value. + /// + /// The return value is a result indicating whether the new value was written and containing + /// the previous value. On success this value is guaranteed to be equal to `current`. + /// + /// `compare_exchange` takes two [`Ordering`] arguments to describe the memory + /// ordering of this operation. `success` describes the required ordering for the + /// read-modify-write operation that takes place if the comparison with `current` succeeds. + /// `failure` describes the required ordering for the load operation that takes place when + /// the comparison fails. Using [`Acquire`] as success ordering makes the store part + /// of this operation [`Relaxed`], and using [`Release`] makes the successful load + /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]. + /// + /// **Note:** This method is only available on platforms that support atomic + /// operations on `u8`. + /// + /// # Examples + /// + /// ``` + /// use std::sync::atomic::{AtomicBool, Ordering}; + /// + /// let some_bool = AtomicBool::new(true); + /// + /// assert_eq!(some_bool.compare_exchange(true, + /// false, + /// Ordering::Acquire, + /// Ordering::Relaxed), + /// Ok(true)); + /// assert_eq!(some_bool.load(Ordering::Relaxed), false); + /// + /// assert_eq!(some_bool.compare_exchange(true, true, + /// Ordering::SeqCst, + /// Ordering::Acquire), + /// Err(false)); + /// assert_eq!(some_bool.load(Ordering::Relaxed), false); + /// ``` + /// + /// # Considerations + /// + /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides + /// of CAS operations. In particular, a load of the value followed by a successful + /// `compare_exchange` with the previous load *does not ensure* that other threads have not + /// changed the value in the interim. This is usually important when the *equality* check in + /// the `compare_exchange` is being used to check the *identity* of a value, but equality + /// does not necessarily imply identity. In this case, `compare_exchange` can lead to the + /// [ABA problem]. + /// + /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem + /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap + #[inline] + #[stable(feature = "extended_compare_and_swap", since = "1.10.0")] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[doc(alias = "compare_and_swap")] + #[cfg(target_has_atomic = "8")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[requires(failure == Relaxed || failure == Acquire || failure == SeqCst)] + #[cfg_attr(kani, kani::modifies(self))] + pub const fn compare_exchange( + &self, + current: bool, + new: bool, + success: Ordering, + failure: Ordering, + ) -> Result { + if EMULATE_ATOMIC_BOOL { + // Pick the strongest ordering from success and failure. + let order = match (success, failure) { + (SeqCst, _) => SeqCst, + (_, SeqCst) => SeqCst, + (AcqRel, _) => AcqRel, + (_, AcqRel) => { + panic!("there is no such thing as an acquire-release failure ordering") + } + (Release, Acquire) => AcqRel, + (Acquire, _) => Acquire, + (_, Acquire) => Acquire, + (Release, Relaxed) => Release, + (_, Release) => panic!("there is no such thing as a release failure ordering"), + (Relaxed, Relaxed) => Relaxed, + }; + let old = if current == new { + // This is a no-op, but we still need to perform the operation + // for memory ordering reasons. + self.fetch_or(false, order) + } else { + // This sets the value to the new one and returns the old one. + self.swap(new, order) + }; + if old == current { Ok(old) } else { Err(old) } + } else { + // SAFETY: data races are prevented by atomic intrinsics. + match unsafe { + atomic_compare_exchange( + self.v.get().cast::(), + current as u8, + new as u8, + success, + failure, + ) + } { + Ok(x) => Ok(x != 0), + Err(x) => Err(x != 0), + } + } + } + + /// Stores a value into the [`bool`] if the current value is the same as the `current` value. + /// + /// Unlike [`AtomicBool::compare_exchange`], this function is allowed to spuriously fail even when the + /// comparison succeeds, which can result in more efficient code on some platforms. The + /// return value is a result indicating whether the new value was written and containing the + /// previous value. + /// + /// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory + /// ordering of this operation. `success` describes the required ordering for the + /// read-modify-write operation that takes place if the comparison with `current` succeeds. + /// `failure` describes the required ordering for the load operation that takes place when + /// the comparison fails. Using [`Acquire`] as success ordering makes the store part + /// of this operation [`Relaxed`], and using [`Release`] makes the successful load + /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]. + /// + /// **Note:** This method is only available on platforms that support atomic + /// operations on `u8`. + /// + /// # Examples + /// + /// ``` + /// use std::sync::atomic::{AtomicBool, Ordering}; + /// + /// let val = AtomicBool::new(false); + /// + /// let new = true; + /// let mut old = val.load(Ordering::Relaxed); + /// loop { + /// match val.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) { + /// Ok(_) => break, + /// Err(x) => old = x, + /// } + /// } + /// ``` + /// + /// # Considerations + /// + /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides + /// of CAS operations. In particular, a load of the value followed by a successful + /// `compare_exchange` with the previous load *does not ensure* that other threads have not + /// changed the value in the interim. This is usually important when the *equality* check in + /// the `compare_exchange` is being used to check the *identity* of a value, but equality + /// does not necessarily imply identity. In this case, `compare_exchange` can lead to the + /// [ABA problem]. + /// + /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem + /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap + #[inline] + #[stable(feature = "extended_compare_and_swap", since = "1.10.0")] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[doc(alias = "compare_and_swap")] + #[cfg(target_has_atomic = "8")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[requires(failure == Relaxed || failure == Acquire || failure == SeqCst)] + #[cfg_attr(kani, kani::modifies(self))] + pub const fn compare_exchange_weak( + &self, + current: bool, + new: bool, + success: Ordering, + failure: Ordering, + ) -> Result { + if EMULATE_ATOMIC_BOOL { + return self.compare_exchange(current, new, success, failure); + } + + // SAFETY: data races are prevented by atomic intrinsics. + match unsafe { + atomic_compare_exchange_weak( + self.v.get().cast::(), + current as u8, + new as u8, + success, + failure, + ) + } { + Ok(x) => Ok(x != 0), + Err(x) => Err(x != 0), + } + } + + /// Logical "and" with a boolean value. + /// + /// Performs a logical "and" operation on the current value and the argument `val`, and sets + /// the new value to the result. + /// + /// Returns the previous value. + /// + /// `fetch_and` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + /// + /// **Note:** This method is only available on platforms that support atomic + /// operations on `u8`. + /// + /// # Examples + /// + /// ``` + /// use std::sync::atomic::{AtomicBool, Ordering}; + /// + /// let foo = AtomicBool::new(true); + /// assert_eq!(foo.fetch_and(false, Ordering::SeqCst), true); + /// assert_eq!(foo.load(Ordering::SeqCst), false); + /// + /// let foo = AtomicBool::new(true); + /// assert_eq!(foo.fetch_and(true, Ordering::SeqCst), true); + /// assert_eq!(foo.load(Ordering::SeqCst), true); + /// + /// let foo = AtomicBool::new(false); + /// assert_eq!(foo.fetch_and(false, Ordering::SeqCst), false); + /// assert_eq!(foo.load(Ordering::SeqCst), false); + /// ``` + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[cfg(target_has_atomic = "8")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] + pub const fn fetch_and(&self, val: bool, order: Ordering) -> bool { + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_and(self.v.get().cast::(), val as u8, order) != 0 } + } + + /// Logical "nand" with a boolean value. + /// + /// Performs a logical "nand" operation on the current value and the argument `val`, and sets + /// the new value to the result. + /// + /// Returns the previous value. + /// + /// `fetch_nand` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + /// + /// **Note:** This method is only available on platforms that support atomic + /// operations on `u8`. + /// + /// # Examples + /// + /// ``` + /// use std::sync::atomic::{AtomicBool, Ordering}; + /// + /// let foo = AtomicBool::new(true); + /// assert_eq!(foo.fetch_nand(false, Ordering::SeqCst), true); + /// assert_eq!(foo.load(Ordering::SeqCst), true); + /// + /// let foo = AtomicBool::new(true); + /// assert_eq!(foo.fetch_nand(true, Ordering::SeqCst), true); + /// assert_eq!(foo.load(Ordering::SeqCst) as usize, 0); + /// assert_eq!(foo.load(Ordering::SeqCst), false); + /// + /// let foo = AtomicBool::new(false); + /// assert_eq!(foo.fetch_nand(false, Ordering::SeqCst), false); + /// assert_eq!(foo.load(Ordering::SeqCst), true); + /// ``` + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[cfg(target_has_atomic = "8")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] + pub const fn fetch_nand(&self, val: bool, order: Ordering) -> bool { + // We can't use atomic_nand here because it can result in a bool with + // an invalid value. This happens because the atomic operation is done + // with an 8-bit integer internally, which would set the upper 7 bits. + // So we just use fetch_xor or swap instead. + if val { + // !(x & true) == !x + // We must invert the bool. + self.fetch_xor(true, order) + } else { + // !(x & false) == true + // We must set the bool to true. + self.swap(true, order) + } + } + + /// Logical "or" with a boolean value. + /// + /// Performs a logical "or" operation on the current value and the argument `val`, and sets the + /// new value to the result. + /// + /// Returns the previous value. + /// + /// `fetch_or` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + /// + /// **Note:** This method is only available on platforms that support atomic + /// operations on `u8`. + /// + /// # Examples + /// + /// ``` + /// use std::sync::atomic::{AtomicBool, Ordering}; + /// + /// let foo = AtomicBool::new(true); + /// assert_eq!(foo.fetch_or(false, Ordering::SeqCst), true); + /// assert_eq!(foo.load(Ordering::SeqCst), true); + /// + /// let foo = AtomicBool::new(false); + /// assert_eq!(foo.fetch_or(true, Ordering::SeqCst), false); + /// assert_eq!(foo.load(Ordering::SeqCst), true); + /// + /// let foo = AtomicBool::new(false); + /// assert_eq!(foo.fetch_or(false, Ordering::SeqCst), false); + /// assert_eq!(foo.load(Ordering::SeqCst), false); + /// ``` + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[cfg(target_has_atomic = "8")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] + pub const fn fetch_or(&self, val: bool, order: Ordering) -> bool { + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_or(self.v.get().cast::(), val as u8, order) != 0 } + } + + /// Logical "xor" with a boolean value. + /// + /// Performs a logical "xor" operation on the current value and the argument `val`, and sets + /// the new value to the result. + /// + /// Returns the previous value. + /// + /// `fetch_xor` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + /// + /// **Note:** This method is only available on platforms that support atomic + /// operations on `u8`. + /// + /// # Examples + /// + /// ``` + /// use std::sync::atomic::{AtomicBool, Ordering}; + /// + /// let foo = AtomicBool::new(true); + /// assert_eq!(foo.fetch_xor(false, Ordering::SeqCst), true); + /// assert_eq!(foo.load(Ordering::SeqCst), true); + /// + /// let foo = AtomicBool::new(true); + /// assert_eq!(foo.fetch_xor(true, Ordering::SeqCst), true); + /// assert_eq!(foo.load(Ordering::SeqCst), false); + /// + /// let foo = AtomicBool::new(false); + /// assert_eq!(foo.fetch_xor(false, Ordering::SeqCst), false); + /// assert_eq!(foo.load(Ordering::SeqCst), false); + /// ``` + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[cfg(target_has_atomic = "8")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] + pub const fn fetch_xor(&self, val: bool, order: Ordering) -> bool { + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_xor(self.v.get().cast::(), val as u8, order) != 0 } + } + + /// Logical "not" with a boolean value. + /// + /// Performs a logical "not" operation on the current value, and sets + /// the new value to the result. + /// + /// Returns the previous value. + /// + /// `fetch_not` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + /// + /// **Note:** This method is only available on platforms that support atomic + /// operations on `u8`. + /// + /// # Examples + /// + /// ``` + /// use std::sync::atomic::{AtomicBool, Ordering}; + /// + /// let foo = AtomicBool::new(true); + /// assert_eq!(foo.fetch_not(Ordering::SeqCst), true); + /// assert_eq!(foo.load(Ordering::SeqCst), false); + /// + /// let foo = AtomicBool::new(false); + /// assert_eq!(foo.fetch_not(Ordering::SeqCst), false); + /// assert_eq!(foo.load(Ordering::SeqCst), true); + /// ``` + #[inline] + #[stable(feature = "atomic_bool_fetch_not", since = "1.81.0")] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[cfg(target_has_atomic = "8")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] + pub const fn fetch_not(&self, order: Ordering) -> bool { + self.fetch_xor(true, order) + } + + /// Returns a mutable pointer to the underlying [`bool`]. + /// + /// Doing non-atomic reads and writes on the resulting boolean can be a data race. + /// This method is mostly useful for FFI, where the function signature may use + /// `*mut bool` instead of `&AtomicBool`. + /// + /// Returning an `*mut` pointer from a shared reference to this atomic is safe because the + /// atomic types work with interior mutability. All modifications of an atomic change the value + /// through a shared reference, and can do so safely as long as they use atomic operations. Any + /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the + /// requirements of the [memory model]. + /// + /// # Examples + /// + /// ```ignore (extern-declaration) + /// # fn main() { + /// use std::sync::atomic::AtomicBool; + /// + /// extern "C" { + /// fn my_atomic_op(arg: *mut bool); + /// } + /// + /// let mut atomic = AtomicBool::new(true); + /// unsafe { + /// my_atomic_op(atomic.as_ptr()); + /// } + /// # } + /// ``` + /// + /// [memory model]: self#memory-model-for-atomic-accesses + #[inline] + #[stable(feature = "atomic_as_ptr", since = "1.70.0")] + #[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")] + #[lint::never_returns_null_ptr] + #[lint::should_not_be_called_on_const_items] + pub const fn as_ptr(&self) -> *mut bool { + self.v.get().cast() + } + + /// An alias for [`AtomicBool::try_update`]. + #[inline] + #[stable(feature = "atomic_fetch_update", since = "1.53.0")] + #[cfg(target_has_atomic = "8")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[deprecated( + since = "1.99.0", + note = "renamed to `try_update` for consistency", + suggestion = "try_update" + )] + pub fn fetch_update( + &self, + set_order: Ordering, + fetch_order: Ordering, + f: F, + ) -> Result + where + F: FnMut(bool) -> Option, + { + self.try_update(set_order, fetch_order, f) + } + + /// Fetches the value, and applies a function to it that returns an optional + /// new value. Returns a `Result` of `Ok(previous_value)` if the function + /// returned `Some(_)`, else `Err(previous_value)`. + /// + /// See also: [`update`](`AtomicBool::update`). + /// + /// Note: This may call the function multiple times if the value has been + /// changed from other threads in the meantime, as long as the function + /// returns `Some(_)`, but the function will have been applied only once to + /// the stored value. + /// + /// `try_update` takes two [`Ordering`] arguments to describe the memory + /// ordering of this operation. The first describes the required ordering for + /// when the operation finally succeeds while the second describes the + /// required ordering for loads. These correspond to the success and failure + /// orderings of [`AtomicBool::compare_exchange`] respectively. + /// + /// Using [`Acquire`] as success ordering makes the store part of this + /// operation [`Relaxed`], and using [`Release`] makes the final successful + /// load [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], + /// [`Acquire`] or [`Relaxed`]. + /// + /// **Note:** This method is only available on platforms that support atomic + /// operations on `u8`. + /// + /// # Considerations + /// + /// This method is not magic; it is not provided by the hardware, and does not act like a + /// critical section or mutex. + /// + /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to + /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]. + /// + /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem + /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap + /// + /// # Examples + /// + /// ```rust + /// use std::sync::atomic::{AtomicBool, Ordering}; + /// + /// let x = AtomicBool::new(false); + /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(false)); + /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(!x)), Ok(false)); + /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(!x)), Ok(true)); + /// assert_eq!(x.load(Ordering::SeqCst), false); + /// ``` + #[inline] + #[stable(feature = "atomic_try_update", since = "1.95.0")] + #[cfg(target_has_atomic = "8")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + pub fn try_update( + &self, + set_order: Ordering, + fetch_order: Ordering, + mut f: impl FnMut(bool) -> Option, + ) -> Result { + let mut prev = self.load(fetch_order); + while let Some(next) = f(prev) { + match self.compare_exchange_weak(prev, next, set_order, fetch_order) { + x @ Ok(_) => return x, + Err(next_prev) => prev = next_prev, + } + } + Err(prev) + } + + /// Fetches the value, and applies a function to it that returns a new value. + /// The new value is stored and the old value is returned. + /// + /// See also: [`try_update`](`AtomicBool::try_update`). + /// + /// Note: This may call the function multiple times if the value has been changed from other threads in + /// the meantime, but the function will have been applied only once to the stored value. + /// + /// `update` takes two [`Ordering`] arguments to describe the memory + /// ordering of this operation. The first describes the required ordering for + /// when the operation finally succeeds while the second describes the + /// required ordering for loads. These correspond to the success and failure + /// orderings of [`AtomicBool::compare_exchange`] respectively. + /// + /// Using [`Acquire`] as success ordering makes the store part + /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load + /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]. + /// + /// **Note:** This method is only available on platforms that support atomic operations on `u8`. + /// + /// # Considerations + /// + /// This method is not magic; it is not provided by the hardware, and does not act like a + /// critical section or mutex. + /// + /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to + /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]. + /// + /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem + /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap + /// + /// # Examples + /// + /// ```rust + /// + /// use std::sync::atomic::{AtomicBool, Ordering}; + /// + /// let x = AtomicBool::new(false); + /// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| !x), false); + /// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| !x), true); + /// assert_eq!(x.load(Ordering::SeqCst), false); + /// ``` + #[inline] + #[stable(feature = "atomic_try_update", since = "1.95.0")] + #[cfg(target_has_atomic = "8")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + pub fn update( + &self, + set_order: Ordering, + fetch_order: Ordering, + mut f: impl FnMut(bool) -> bool, + ) -> bool { + let mut prev = self.load(fetch_order); + loop { + match self.compare_exchange_weak(prev, f(prev), set_order, fetch_order) { + Ok(x) => break x, + Err(next_prev) => prev = next_prev, + } + } + } +} + +#[cfg(target_has_atomic_load_store = "ptr")] +impl AtomicPtr { + /// Creates a new `AtomicPtr`. + /// + /// # Examples + /// + /// ``` + /// use std::sync::atomic::AtomicPtr; + /// + /// let ptr = &mut 5; + /// let atomic_ptr = AtomicPtr::new(ptr); + /// ``` + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_const_stable(feature = "const_atomic_new", since = "1.24.0")] + pub const fn new(p: *mut T) -> AtomicPtr { + // SAFETY: + // `Atomic` is essentially a transparent wrapper around `T`. + unsafe { transmute(p) } + } + + /// Creates a new `AtomicPtr` from a pointer. + /// + /// # Examples + /// + /// ``` + /// use std::sync::atomic::{self, AtomicPtr}; + /// + /// // Get a pointer to an allocated value + /// let ptr: *mut *mut u8 = Box::into_raw(Box::new(std::ptr::null_mut())); + /// + /// assert!(ptr.cast::>().is_aligned()); + /// + /// { + /// // Create an atomic view of the allocated value + /// let atomic = unsafe { AtomicPtr::from_ptr(ptr) }; + /// + /// // Use `atomic` for atomic operations, possibly share it with other threads + /// atomic.store(std::ptr::NonNull::dangling().as_ptr(), atomic::Ordering::Relaxed); + /// } + /// + /// // It's ok to non-atomically access the value behind `ptr`, + /// // since the reference to the atomic ended its lifetime in the block above + /// assert!(!unsafe { *ptr }.is_null()); + /// + /// // Deallocate the value + /// unsafe { drop(Box::from_raw(ptr)) } + /// ``` + /// + /// # Safety + /// + /// * `ptr` must be aligned to `align_of::>()` (note that on some platforms this + /// can be bigger than `align_of::<*mut T>()`). + /// * `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`. + /// * You must adhere to the [Memory model for atomic accesses]. In particular, it is not + /// allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different + /// sizes, without synchronization. + /// + /// [valid]: crate::ptr#safety + /// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses + #[inline] + #[stable(feature = "atomic_from_ptr", since = "1.75.0")] + #[rustc_const_stable(feature = "const_atomic_from_ptr", since = "1.84.0")] + #[requires(ptr.cast::>().is_aligned())] + #[requires(ub_checks::can_dereference(ptr))] + #[requires(ub_checks::can_write(ptr))] + #[ensures(|result: &&AtomicPtr| { + core::ptr::eq(*result, ptr.cast::>()) + })] + pub const unsafe fn from_ptr<'a>(ptr: *mut *mut T) -> &'a AtomicPtr { + // SAFETY: guaranteed by the caller + unsafe { &*ptr.cast() } + } + + /// Creates a new pointer to `AtomicPtr` from a pointer. + /// + /// This is useful if you want to do volatile atomic accesses, and thus avoid creating + /// a reference to the destination. + #[inline] + #[unstable(feature = "atomic_volatile", issue = "158947")] + pub const fn from_ptr_raw(ptr: *mut *mut T) -> *const AtomicPtr { + ptr.cast_const().cast() + } + + /// Creates a new `AtomicPtr` initialized with a null pointer. + /// + /// # Examples + /// + /// ``` + /// #![feature(atomic_ptr_null)] + /// use std::sync::atomic::{AtomicPtr, Ordering}; + /// + /// let atomic_ptr = AtomicPtr::<()>::null(); + /// assert!(atomic_ptr.load(Ordering::Relaxed).is_null()); + /// ``` + #[inline] + #[must_use] + #[unstable(feature = "atomic_ptr_null", issue = "150733")] + pub const fn null() -> AtomicPtr { + AtomicPtr::new(crate::ptr::null_mut()) + } + + /// Returns a mutable reference to the underlying pointer. + /// + /// This is safe because the mutable reference guarantees that no other threads are + /// concurrently accessing the atomic data. + /// + /// # Examples + /// + /// ``` + /// use std::sync::atomic::{AtomicPtr, Ordering}; + /// + /// let mut data = 10; + /// let mut atomic_ptr = AtomicPtr::new(&mut data); + /// let mut other_data = 5; + /// *atomic_ptr.get_mut() = &mut other_data; + /// assert_eq!(unsafe { *atomic_ptr.load(Ordering::SeqCst) }, 5); + /// ``` + #[inline] + #[stable(feature = "atomic_access", since = "1.15.0")] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + pub const fn get_mut(&mut self) -> &mut *mut T { + // SAFETY: + // `Atomic` is essentially a transparent wrapper around `T`. + unsafe { &mut *self.as_ptr() } + } + + /// Gets atomic access to a pointer. + /// + /// **Note:** This function is only available on targets where `AtomicPtr` has the same alignment as `*const T` + /// + /// # Examples + /// + /// ``` + /// use std::sync::atomic::{AtomicPtr, Ordering}; + /// + /// let mut data = 123; + /// let mut some_ptr = &mut data as *mut i32; + /// let a = AtomicPtr::from_mut(&mut some_ptr); + /// let mut other_data = 456; + /// a.store(&mut other_data, Ordering::Relaxed); + /// assert_eq!(unsafe { *some_ptr }, 456); + /// ``` + #[inline] + #[cfg(target_has_atomic_primitive_alignment = "ptr")] + #[stable(feature = "atomic_from_mut", since = "1.98.0")] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + pub const fn from_mut(v: &mut *mut T) -> &mut Self { + let [] = [(); align_of::>() - align_of::<*mut ()>()]; + // SAFETY: + // - the mutable reference guarantees unique ownership. + // - the alignment of `*mut T` and `Self` is the same on all platforms + // supported by rust, as verified above. + unsafe { &mut *(v as *mut *mut T as *mut Self) } + } + + /// Gets non-atomic access to a `&mut [AtomicPtr]` slice. + /// + /// This is safe because the mutable reference guarantees that no other threads are + /// concurrently accessing the atomic data. + /// + /// # Examples + /// + /// ```ignore-wasm + /// use std::ptr::null_mut; + /// use std::sync::atomic::{AtomicPtr, Ordering}; + /// + /// let mut some_ptrs = [const { AtomicPtr::new(null_mut::()) }; 10]; + /// + /// let view: &mut [*mut String] = AtomicPtr::get_mut_slice(&mut some_ptrs); + /// assert_eq!(view, [null_mut::(); 10]); + /// view + /// .iter_mut() + /// .enumerate() + /// .for_each(|(i, ptr)| *ptr = Box::into_raw(Box::new(format!("iteration#{i}")))); + /// + /// std::thread::scope(|s| { + /// for ptr in &some_ptrs { + /// s.spawn(move || { + /// let ptr = ptr.load(Ordering::Relaxed); + /// assert!(!ptr.is_null()); + /// + /// let name = unsafe { Box::from_raw(ptr) }; + /// println!("Hello, {name}!"); + /// }); + /// } + /// }); + /// ``` + #[inline] + #[stable(feature = "atomic_from_mut", since = "1.98.0")] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + pub const fn get_mut_slice(this: &mut [Self]) -> &mut [*mut T] { + // SAFETY: the mutable reference guarantees unique ownership. + unsafe { &mut *(this as *mut [Self] as *mut [*mut T]) } + } + + /// Gets atomic access to a slice of pointers. + /// + /// **Note:** This function is only available on targets where `AtomicPtr` has the same alignment as `*const T` + /// + /// # Examples + /// + /// ```ignore-wasm + /// use std::ptr::null_mut; + /// use std::sync::atomic::{AtomicPtr, Ordering}; + /// + /// let mut some_ptrs = [null_mut::(); 10]; + /// let a = &*AtomicPtr::from_mut_slice(&mut some_ptrs); + /// std::thread::scope(|s| { + /// for i in 0..a.len() { + /// s.spawn(move || { + /// let name = Box::new(format!("thread{i}")); + /// a[i].store(Box::into_raw(name), Ordering::Relaxed); + /// }); + /// } + /// }); + /// for p in some_ptrs { + /// assert!(!p.is_null()); + /// let name = unsafe { Box::from_raw(p) }; + /// println!("Hello, {name}!"); + /// } + /// ``` + #[inline] + #[cfg(target_has_atomic_primitive_alignment = "ptr")] + #[stable(feature = "atomic_from_mut", since = "1.98.0")] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + pub const fn from_mut_slice(v: &mut [*mut T]) -> &mut [Self] { + // SAFETY: + // - the mutable reference guarantees unique ownership. + // - the alignment of `*mut T` and `Self` is the same on all platforms + // supported by rust, as verified above. + unsafe { &mut *(v as *mut [*mut T] as *mut [Self]) } + } + + /// Consumes the atomic and returns the contained value. + /// + /// This is safe because passing `self` by value guarantees that no other threads are + /// concurrently accessing the atomic data. + /// + /// # Examples + /// + /// ``` + /// use std::sync::atomic::AtomicPtr; + /// + /// let mut data = 5; + /// let atomic_ptr = AtomicPtr::new(&mut data); + /// assert_eq!(unsafe { *atomic_ptr.into_inner() }, 5); + /// ``` + #[inline] + #[stable(feature = "atomic_access", since = "1.15.0")] + #[rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0")] + pub const fn into_inner(self) -> *mut T { + // SAFETY: + // `Atomic` is essentially a transparent wrapper around `T`. + unsafe { transmute(self) } + } + + /// Loads a value from the pointer. + /// + /// `load` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`]. + /// + /// # Panics + /// + /// Panics if `order` is [`Release`] or [`AcqRel`]. + /// + /// # Examples + /// + /// ``` + /// use std::sync::atomic::{AtomicPtr, Ordering}; + /// + /// let ptr = &mut 5; + /// let some_ptr = AtomicPtr::new(ptr); + /// + /// let value = some_ptr.load(Ordering::Relaxed); + /// ``` + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[requires(order == Relaxed || order == Acquire || order == SeqCst)] + pub const fn load(&self, order: Ordering) -> *mut T { + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { + atomic_load::<_, /* VOLATILE */ false>(self.as_ptr(), order) + } + } + + /// Perform a volatile atomic load from the pointer. + /// + /// `load_volatile` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`]. + /// + #[doc = include_str!("./atomic_load_volatile.md")] + /// + /// # Safety + /// + /// Behavior is undefined if any of the following conditions are violated: + /// + /// * `self` must be [valid] for reads, or `self` must point to memory + /// outside of all Rust allocations and reading from that memory must: + /// - not trap, and + /// - not cause any memory inside a Rust allocation to be modified. + /// + /// * `self` must be aligned to `align_of::>()` (note that on some platforms this + /// can be bigger than `align_of::<*mut T>()`). + /// + /// * Reading from `self` must produce a properly initialized value of type `*mut T`. + /// + /// [valid]: core::ptr#safety + /// + /// # Panics + /// + /// Panics if `order` is [`Release`] or [`AcqRel`]. + /// + /// # Examples + /// + /// Assuming an MMIO region at `MMIO_ADDR` that belongs to a device with direct memory + /// access, we may receive a buffer in shared memory from that device as follows: + /// + /// ```rust,no_run + /// #![feature(atomic_volatile)] + /// use std::sync::atomic::{fence, AtomicPtr, Ordering}; + /// use std::ptr; + /// + /// const MMIO_ADDR: *mut *mut u8 = ptr::without_provenance_mut(0xCAF0); + /// let atomic_ptr = AtomicPtr::::from_ptr_raw(MMIO_ADDR); + /// + /// // Spin until we see a non-zero value. + /// let buf = 'buf: loop { + /// let buf = unsafe { atomic_ptr.load_volatile(Ordering::Relaxed) }; + /// if !buf.is_null() { + /// break 'buf buf; + /// } + /// }; + /// // Synchronize with the store whose value we just read. + /// // Note: a standard acquire fence may not be sufficient to synchronize with DMA devices. + /// // Depending on your target, you may have to use inline assembly to emit a special fence. + /// fence(Ordering::Acquire); + /// + /// // Now process the data in `buf`. + /// ``` + #[inline] + #[unstable(feature = "atomic_volatile", issue = "158947")] + #[rustc_const_unstable(feature = "atomic_volatile", issue = "158947")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub const unsafe fn load_volatile(self: *const Self, order: Ordering) -> *mut T { + // SAFETY: follows from our own safety requirements. + unsafe { + atomic_load::<_, /* VOLATILE */ true>(self.cast::<*mut T>(), order) + } + } + + /// Stores a value into the pointer. + /// + /// `store` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. Possible values are [`SeqCst`], [`Release`] and [`Relaxed`]. + /// + /// # Panics + /// + /// Panics if `order` is [`Acquire`] or [`AcqRel`]. + /// + /// # Examples + /// + /// ``` + /// use std::sync::atomic::{AtomicPtr, Ordering}; + /// + /// let ptr = &mut 5; + /// let some_ptr = AtomicPtr::new(ptr); + /// + /// let other_ptr = &mut 10; + /// + /// some_ptr.store(other_ptr, Ordering::Relaxed); + /// ``` + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[requires(order == Relaxed || order == Release || order == SeqCst)] + #[cfg_attr(kani, kani::modifies(self))] + pub const fn store(&self, ptr: *mut T, order: Ordering) { + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { + atomic_store::<_, /* VOLATILE */ false>(self.as_ptr(), ptr, order); + } + } + + /// Performs a volatile atomic store into the pointer. + /// + /// `store_volatile` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. Possible values are [`SeqCst`], [`Release`] and [`Relaxed`]. + /// + #[doc = include_str!("./atomic_store_volatile.md")] + /// + /// # Safety + /// + /// Behavior is undefined if any of the following conditions are violated: + /// + /// * `self` must be either [valid] for writes, or `self` must point to memory + /// outside of all Rust allocations and writing to that memory must: + /// - not trap, and + /// - not cause any memory inside a Rust allocation to be modified. + /// + /// * `self` must be aligned to `align_of::>()` (note that on some platforms this + /// can be bigger than `align_of::<*mut T>()`). + /// + /// [valid]: core::ptr#safety + /// + /// # Panics + /// + /// Panics if `order` is [`Acquire`] or [`AcqRel`]. + /// + /// # Examples + /// + /// Assuming an MMIO region at `MMIO_ADDR` that belongs to a device with direct memory + /// access, we may submit a buffer in shared memory to that device as follows: + /// + /// ```rust,no_run + /// #![feature(atomic_volatile)] + /// use std::sync::atomic::{fence, AtomicPtr, Ordering}; + /// use std::ptr; + /// + /// const MMIO_ADDR: *mut *mut u8 = ptr::without_provenance_mut(0xCAF0); + /// let atomic_ptr = AtomicPtr::::from_ptr_raw(MMIO_ADDR); + /// + /// // Prepare some data for the DMA device. + /// # fn get_dma_buffer() -> *mut u8 { panic!() } + /// let buf = get_dma_buffer(); + /// + /// // Ensure the other side can synchronize with the store we do below. + /// // Note: a standard release fence may not be sufficient to synchronize with DMA devices. + /// // Depending on your target, you may have to use inline assembly to emit a special fence. + /// fence(Ordering::Release); + /// + /// unsafe { atomic_ptr.store_volatile(buf, Ordering::Relaxed) }; + /// ``` + #[inline] + #[unstable(feature = "atomic_volatile", issue = "158947")] + #[rustc_const_unstable(feature = "atomic_volatile", issue = "158947")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + pub const unsafe fn store_volatile(self: *const Self, ptr: *mut T, order: Ordering) { + // SAFETY: follows from our own safety requirements. + unsafe { + atomic_store::<_, /* VOLATILE */ true>(self.cast::<*mut T>().cast_mut(), ptr, order); + } + } + + /// Stores a value into the pointer, returning the previous value. + /// + /// `swap` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + /// + /// **Note:** This method is only available on platforms that support atomic + /// operations on pointers. + /// + /// # Examples + /// + /// ``` + /// use std::sync::atomic::{AtomicPtr, Ordering}; + /// + /// let ptr = &mut 5; + /// let some_ptr = AtomicPtr::new(ptr); + /// + /// let other_ptr = &mut 10; + /// + /// let value = some_ptr.swap(other_ptr, Ordering::Relaxed); + /// ``` + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[cfg(target_has_atomic = "ptr")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] + pub const fn swap(&self, ptr: *mut T, order: Ordering) -> *mut T { + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_swap(self.as_ptr(), ptr, order) } + } + + /// Stores a value into the pointer if the current value is the same as the `current` value. + /// + /// The return value is always the previous value. If it is equal to `current`, then the value + /// was updated. + /// + /// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory + /// ordering of this operation. Notice that even when using [`AcqRel`], the operation + /// might fail and hence just perform an `Acquire` load, but not have `Release` semantics. + /// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it + /// happens, and using [`Release`] makes the load part [`Relaxed`]. + /// + /// **Note:** This method is only available on platforms that support atomic + /// operations on pointers. + /// + /// # Migrating to `compare_exchange` and `compare_exchange_weak` + /// + /// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for + /// memory orderings: + /// + /// Original | Success | Failure + /// -------- | ------- | ------- + /// Relaxed | Relaxed | Relaxed + /// Acquire | Acquire | Acquire + /// Release | Release | Relaxed + /// AcqRel | AcqRel | Acquire + /// SeqCst | SeqCst | SeqCst + /// + /// `compare_and_swap` and `compare_exchange` also differ in their return type. You can use + /// `compare_exchange(...).unwrap_or_else(|x| x)` to recover the behavior of `compare_and_swap`, + /// but in most cases it is more idiomatic to check whether the return value is `Ok` or `Err` + /// rather than to infer success vs failure based on the value that was read. + /// + /// During migration, consider whether it makes sense to use `compare_exchange_weak` instead. + /// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds, + /// which allows the compiler to generate better assembly code when the compare and swap + /// is used in a loop. + /// + /// # Examples + /// + /// ``` + /// use std::sync::atomic::{AtomicPtr, Ordering}; + /// + /// let ptr = &mut 5; + /// let some_ptr = AtomicPtr::new(ptr); + /// + /// let other_ptr = &mut 10; + /// + /// let value = some_ptr.compare_and_swap(ptr, other_ptr, Ordering::Relaxed); + /// ``` + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + #[deprecated( + since = "1.50.0", + note = "Use `compare_exchange` or `compare_exchange_weak` instead" + )] + #[cfg(target_has_atomic = "ptr")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] + pub fn compare_and_swap(&self, current: *mut T, new: *mut T, order: Ordering) -> *mut T { + match self.compare_exchange(current, new, order, strongest_failure_ordering(order)) { + Ok(x) => x, + Err(x) => x, + } + } + + /// Stores a value into the pointer if the current value is the same as the `current` value. + /// + /// The return value is a result indicating whether the new value was written and containing + /// the previous value. On success this value is guaranteed to be equal to `current`. + /// + /// `compare_exchange` takes two [`Ordering`] arguments to describe the memory + /// ordering of this operation. `success` describes the required ordering for the + /// read-modify-write operation that takes place if the comparison with `current` succeeds. + /// `failure` describes the required ordering for the load operation that takes place when + /// the comparison fails. Using [`Acquire`] as success ordering makes the store part + /// of this operation [`Relaxed`], and using [`Release`] makes the successful load + /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]. + /// + /// **Note:** This method is only available on platforms that support atomic + /// operations on pointers. + /// + /// # Examples + /// + /// ``` + /// use std::sync::atomic::{AtomicPtr, Ordering}; + /// + /// let ptr = &mut 5; + /// let some_ptr = AtomicPtr::new(ptr); + /// + /// let other_ptr = &mut 10; + /// + /// let value = some_ptr.compare_exchange(ptr, other_ptr, + /// Ordering::SeqCst, Ordering::Relaxed); + /// ``` + /// + /// # Considerations + /// + /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides + /// of CAS operations. In particular, a load of the value followed by a successful + /// `compare_exchange` with the previous load *does not ensure* that other threads have not + /// changed the value in the interim. This is usually important when the *equality* check in + /// the `compare_exchange` is being used to check the *identity* of a value, but equality + /// does not necessarily imply identity. This is a particularly common case for pointers, as + /// a pointer holding the same address does not imply that the same object exists at that + /// address! In this case, `compare_exchange` can lead to the [ABA problem]. + /// + /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem + /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap + #[inline] + #[stable(feature = "extended_compare_and_swap", since = "1.10.0")] + #[cfg(target_has_atomic = "ptr")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[requires(failure == Relaxed || failure == Acquire || failure == SeqCst)] + #[cfg_attr(kani, kani::modifies(self))] + pub fn compare_exchange( + &self, + current: *mut T, + new: *mut T, + success: Ordering, + failure: Ordering, + ) -> Result<*mut T, *mut T> { + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_compare_exchange(self.as_ptr(), current, new, success, failure) } + } + + /// Stores a value into the pointer if the current value is the same as the `current` value. + /// + /// Unlike [`AtomicPtr::compare_exchange`], this function is allowed to spuriously fail even when the + /// comparison succeeds, which can result in more efficient code on some platforms. The + /// return value is a result indicating whether the new value was written and containing the + /// previous value. + /// + /// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory + /// ordering of this operation. `success` describes the required ordering for the + /// read-modify-write operation that takes place if the comparison with `current` succeeds. + /// `failure` describes the required ordering for the load operation that takes place when + /// the comparison fails. Using [`Acquire`] as success ordering makes the store part + /// of this operation [`Relaxed`], and using [`Release`] makes the successful load + /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]. + /// + /// **Note:** This method is only available on platforms that support atomic + /// operations on pointers. + /// + /// # Examples + /// + /// ``` + /// use std::sync::atomic::{AtomicPtr, Ordering}; + /// + /// let some_ptr = AtomicPtr::new(&mut 5); + /// + /// let new = &mut 10; + /// let mut old = some_ptr.load(Ordering::Relaxed); + /// loop { + /// match some_ptr.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) { + /// Ok(_) => break, + /// Err(x) => old = x, + /// } + /// } + /// ``` + /// + /// # Considerations + /// + /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides + /// of CAS operations. In particular, a load of the value followed by a successful + /// `compare_exchange` with the previous load *does not ensure* that other threads have not + /// changed the value in the interim. This is usually important when the *equality* check in + /// the `compare_exchange` is being used to check the *identity* of a value, but equality + /// does not necessarily imply identity. This is a particularly common case for pointers, as + /// a pointer holding the same address does not imply that the same object exists at that + /// address! In this case, `compare_exchange` can lead to the [ABA problem]. + /// + /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem + /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap + #[inline] + #[stable(feature = "extended_compare_and_swap", since = "1.10.0")] + #[cfg(target_has_atomic = "ptr")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[requires(failure == Relaxed || failure == Acquire || failure == SeqCst)] + #[cfg_attr(kani, kani::modifies(self))] + pub fn compare_exchange_weak( + &self, + current: *mut T, + new: *mut T, + success: Ordering, + failure: Ordering, + ) -> Result<*mut T, *mut T> { + // SAFETY: This intrinsic is unsafe because it operates on a raw pointer + // but we know for sure that the pointer is valid (we just got it from + // an `UnsafeCell` that we have by reference) and the atomic operation + // itself allows us to safely mutate the `UnsafeCell` contents. + unsafe { atomic_compare_exchange_weak(self.as_ptr(), current, new, success, failure) } + } + + /// An alias for [`AtomicPtr::try_update`]. + #[inline] + #[stable(feature = "atomic_fetch_update", since = "1.53.0")] + #[cfg(target_has_atomic = "ptr")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[deprecated( + since = "1.99.0", + note = "renamed to `try_update` for consistency", + suggestion = "try_update" + )] + pub fn fetch_update( + &self, + set_order: Ordering, + fetch_order: Ordering, + f: F, + ) -> Result<*mut T, *mut T> + where + F: FnMut(*mut T) -> Option<*mut T>, + { + self.try_update(set_order, fetch_order, f) + } + /// Fetches the value, and applies a function to it that returns an optional + /// new value. Returns a `Result` of `Ok(previous_value)` if the function + /// returned `Some(_)`, else `Err(previous_value)`. + /// + /// See also: [`update`](`AtomicPtr::update`). + /// + /// Note: This may call the function multiple times if the value has been + /// changed from other threads in the meantime, as long as the function + /// returns `Some(_)`, but the function will have been applied only once to + /// the stored value. + /// + /// `try_update` takes two [`Ordering`] arguments to describe the memory + /// ordering of this operation. The first describes the required ordering for + /// when the operation finally succeeds while the second describes the + /// required ordering for loads. These correspond to the success and failure + /// orderings of [`AtomicPtr::compare_exchange`] respectively. + /// + /// Using [`Acquire`] as success ordering makes the store part of this + /// operation [`Relaxed`], and using [`Release`] makes the final successful + /// load [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], + /// [`Acquire`] or [`Relaxed`]. + /// + /// **Note:** This method is only available on platforms that support atomic + /// operations on pointers. + /// + /// # Considerations + /// + /// This method is not magic; it is not provided by the hardware, and does not act like a + /// critical section or mutex. + /// + /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to + /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem], + /// which is a particularly common pitfall for pointers! + /// + /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem + /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap + /// + /// # Examples + /// + /// ```rust + /// use std::sync::atomic::{AtomicPtr, Ordering}; + /// + /// let ptr: *mut _ = &mut 5; + /// let some_ptr = AtomicPtr::new(ptr); + /// + /// let new: *mut _ = &mut 10; + /// assert_eq!(some_ptr.try_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(ptr)); + /// let result = some_ptr.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| { + /// if x == ptr { + /// Some(new) + /// } else { + /// None + /// } + /// }); + /// assert_eq!(result, Ok(ptr)); + /// assert_eq!(some_ptr.load(Ordering::SeqCst), new); + /// ``` + #[inline] + #[stable(feature = "atomic_try_update", since = "1.95.0")] + #[cfg(target_has_atomic = "ptr")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + pub fn try_update( + &self, + set_order: Ordering, + fetch_order: Ordering, + mut f: impl FnMut(*mut T) -> Option<*mut T>, + ) -> Result<*mut T, *mut T> { + let mut prev = self.load(fetch_order); + while let Some(next) = f(prev) { + match self.compare_exchange_weak(prev, next, set_order, fetch_order) { + x @ Ok(_) => return x, + Err(next_prev) => prev = next_prev, + } + } + Err(prev) + } + + /// Fetches the value, and applies a function to it that returns a new value. + /// The new value is stored and the old value is returned. + /// + /// See also: [`try_update`](`AtomicPtr::try_update`). + /// + /// Note: This may call the function multiple times if the value has been changed from other threads in + /// the meantime, but the function will have been applied only once to the stored value. + /// + /// `update` takes two [`Ordering`] arguments to describe the memory + /// ordering of this operation. The first describes the required ordering for + /// when the operation finally succeeds while the second describes the + /// required ordering for loads. These correspond to the success and failure + /// orderings of [`AtomicPtr::compare_exchange`] respectively. + /// + /// Using [`Acquire`] as success ordering makes the store part + /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load + /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]. + /// + /// **Note:** This method is only available on platforms that support atomic + /// operations on pointers. + /// + /// # Considerations + /// + /// This method is not magic; it is not provided by the hardware, and does not act like a + /// critical section or mutex. + /// + /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to + /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem], + /// which is a particularly common pitfall for pointers! + /// + /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem + /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap + /// + /// # Examples + /// + /// ```rust + /// + /// use std::sync::atomic::{AtomicPtr, Ordering}; + /// + /// let ptr: *mut _ = &mut 5; + /// let some_ptr = AtomicPtr::new(ptr); + /// + /// let new: *mut _ = &mut 10; + /// let result = some_ptr.update(Ordering::SeqCst, Ordering::SeqCst, |_| new); + /// assert_eq!(result, ptr); + /// assert_eq!(some_ptr.load(Ordering::SeqCst), new); + /// ``` + #[inline] + #[stable(feature = "atomic_try_update", since = "1.95.0")] + #[cfg(target_has_atomic = "ptr")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + pub fn update( + &self, + set_order: Ordering, + fetch_order: Ordering, + mut f: impl FnMut(*mut T) -> *mut T, + ) -> *mut T { + let mut prev = self.load(fetch_order); + loop { + match self.compare_exchange_weak(prev, f(prev), set_order, fetch_order) { + Ok(x) => break x, + Err(next_prev) => prev = next_prev, + } + } + } + + /// Offsets the pointer's address by adding `val` (in units of `T`), + /// returning the previous pointer. + /// + /// This is equivalent to using [`wrapping_add`] to atomically perform the + /// equivalent of `ptr = ptr.wrapping_add(val);`. + /// + /// This method operates in units of `T`, which means that it cannot be used + /// to offset the pointer by an amount which is not a multiple of + /// `size_of::()`. This can sometimes be inconvenient, as you may want to + /// work with a deliberately misaligned pointer. In such cases, you may use + /// the [`fetch_byte_add`](Self::fetch_byte_add) method instead. + /// + /// `fetch_ptr_add` takes an [`Ordering`] argument which describes the + /// memory ordering of this operation. All ordering modes are possible. Note + /// that using [`Acquire`] makes the store part of this operation + /// [`Relaxed`], and using [`Release`] makes the load part [`Relaxed`]. + /// + /// **Note**: This method is only available on platforms that support atomic + /// operations on [`AtomicPtr`]. + /// + /// [`wrapping_add`]: pointer::wrapping_add + /// + /// # Examples + /// + /// ``` + /// use core::sync::atomic::{AtomicPtr, Ordering}; + /// + /// let atom = AtomicPtr::::new(core::ptr::null_mut()); + /// assert_eq!(atom.fetch_ptr_add(1, Ordering::Relaxed).addr(), 0); + /// // Note: units of `size_of::()`. + /// assert_eq!(atom.load(Ordering::Relaxed).addr(), 8); + /// ``` + #[inline] + #[cfg(target_has_atomic = "ptr")] + #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + pub fn fetch_ptr_add(&self, val: usize, order: Ordering) -> *mut T { + self.fetch_byte_add(val.wrapping_mul(size_of::()), order) + } + + /// Offsets the pointer's address by subtracting `val` (in units of `T`), + /// returning the previous pointer. + /// + /// This is equivalent to using [`wrapping_sub`] to atomically perform the + /// equivalent of `ptr = ptr.wrapping_sub(val);`. + /// + /// This method operates in units of `T`, which means that it cannot be used + /// to offset the pointer by an amount which is not a multiple of + /// `size_of::()`. This can sometimes be inconvenient, as you may want to + /// work with a deliberately misaligned pointer. In such cases, you may use + /// the [`fetch_byte_sub`](Self::fetch_byte_sub) method instead. + /// + /// `fetch_ptr_sub` takes an [`Ordering`] argument which describes the memory + /// ordering of this operation. All ordering modes are possible. Note that + /// using [`Acquire`] makes the store part of this operation [`Relaxed`], + /// and using [`Release`] makes the load part [`Relaxed`]. + /// + /// **Note**: This method is only available on platforms that support atomic + /// operations on [`AtomicPtr`]. + /// + /// [`wrapping_sub`]: pointer::wrapping_sub + /// + /// # Examples + /// + /// ``` + /// use core::sync::atomic::{AtomicPtr, Ordering}; + /// + /// let array = [1i32, 2i32]; + /// let atom = AtomicPtr::new(array.as_ptr().wrapping_add(1) as *mut _); + /// + /// assert!(core::ptr::eq( + /// atom.fetch_ptr_sub(1, Ordering::Relaxed), + /// &array[1], + /// )); + /// assert!(core::ptr::eq(atom.load(Ordering::Relaxed), &array[0])); + /// ``` + #[inline] + #[cfg(target_has_atomic = "ptr")] + #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + pub fn fetch_ptr_sub(&self, val: usize, order: Ordering) -> *mut T { + self.fetch_byte_sub(val.wrapping_mul(size_of::()), order) + } + + /// Offsets the pointer's address by adding `val` *bytes*, returning the + /// previous pointer. + /// + /// This is equivalent to using [`wrapping_byte_add`] to atomically + /// perform `ptr = ptr.wrapping_byte_add(val)`. + /// + /// `fetch_byte_add` takes an [`Ordering`] argument which describes the + /// memory ordering of this operation. All ordering modes are possible. Note + /// that using [`Acquire`] makes the store part of this operation + /// [`Relaxed`], and using [`Release`] makes the load part [`Relaxed`]. + /// + /// **Note**: This method is only available on platforms that support atomic + /// operations on [`AtomicPtr`]. + /// + /// [`wrapping_byte_add`]: pointer::wrapping_byte_add + /// + /// # Examples + /// + /// ``` + /// use core::sync::atomic::{AtomicPtr, Ordering}; + /// + /// let atom = AtomicPtr::::new(core::ptr::null_mut()); + /// assert_eq!(atom.fetch_byte_add(1, Ordering::Relaxed).addr(), 0); + /// // Note: in units of bytes, not `size_of::()`. + /// assert_eq!(atom.load(Ordering::Relaxed).addr(), 1); + /// ``` + #[inline] + #[cfg(target_has_atomic = "ptr")] + #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + pub fn fetch_byte_add(&self, val: usize, order: Ordering) -> *mut T { + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_add(self.as_ptr(), val, order).cast() } + } + + /// Offsets the pointer's address by subtracting `val` *bytes*, returning the + /// previous pointer. + /// + /// This is equivalent to using [`wrapping_byte_sub`] to atomically + /// perform `ptr = ptr.wrapping_byte_sub(val)`. + /// + /// `fetch_byte_sub` takes an [`Ordering`] argument which describes the + /// memory ordering of this operation. All ordering modes are possible. Note + /// that using [`Acquire`] makes the store part of this operation + /// [`Relaxed`], and using [`Release`] makes the load part [`Relaxed`]. + /// + /// **Note**: This method is only available on platforms that support atomic + /// operations on [`AtomicPtr`]. + /// + /// [`wrapping_byte_sub`]: pointer::wrapping_byte_sub + /// + /// # Examples + /// + /// ``` + /// use core::sync::atomic::{AtomicPtr, Ordering}; + /// + /// let mut arr = [0i64, 1]; + /// let atom = AtomicPtr::::new(&raw mut arr[1]); + /// assert_eq!(atom.fetch_byte_sub(8, Ordering::Relaxed).addr(), (&raw const arr[1]).addr()); + /// assert_eq!(atom.load(Ordering::Relaxed).addr(), (&raw const arr[0]).addr()); + /// ``` + #[inline] + #[cfg(target_has_atomic = "ptr")] + #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + pub fn fetch_byte_sub(&self, val: usize, order: Ordering) -> *mut T { + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_sub(self.as_ptr(), val, order).cast() } + } + + /// Performs a bitwise "or" operation on the address of the current pointer, + /// and the argument `val`, and stores a pointer with provenance of the + /// current pointer and the resulting address. + /// + /// This is equivalent to using [`map_addr`] to atomically perform + /// `ptr = ptr.map_addr(|a| a | val)`. This can be used in tagged + /// pointer schemes to atomically set tag bits. + /// + /// **Caveat**: This operation returns the previous value. To compute the + /// stored value without losing provenance, you may use [`map_addr`]. For + /// example: `a.fetch_or(val).map_addr(|a| a | val)`. + /// + /// `fetch_or` takes an [`Ordering`] argument which describes the memory + /// ordering of this operation. All ordering modes are possible. Note that + /// using [`Acquire`] makes the store part of this operation [`Relaxed`], + /// and using [`Release`] makes the load part [`Relaxed`]. + /// + /// **Note**: This method is only available on platforms that support atomic + /// operations on [`AtomicPtr`]. + /// + /// This API and its claimed semantics are part of the Strict Provenance + /// experiment, see the [module documentation for `ptr`][crate::ptr] for + /// details. + /// + /// [`map_addr`]: pointer::map_addr + /// + /// # Examples + /// + /// ``` + /// use core::sync::atomic::{AtomicPtr, Ordering}; + /// + /// let pointer = &mut 3i64 as *mut i64; + /// + /// let atom = AtomicPtr::::new(pointer); + /// // Tag the bottom bit of the pointer. + /// assert_eq!(atom.fetch_or(1, Ordering::Relaxed).addr() & 1, 0); + /// // Extract and untag. + /// let tagged = atom.load(Ordering::Relaxed); + /// assert_eq!(tagged.addr() & 1, 1); + /// assert_eq!(tagged.map_addr(|p| p & !1), pointer); + /// ``` + #[inline] + #[cfg(target_has_atomic = "ptr")] + #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] + pub fn fetch_or(&self, val: usize, order: Ordering) -> *mut T { + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_or(self.as_ptr(), val, order).cast() } + } + + /// Performs a bitwise "and" operation on the address of the current + /// pointer, and the argument `val`, and stores a pointer with provenance of + /// the current pointer and the resulting address. + /// + /// This is equivalent to using [`map_addr`] to atomically perform + /// `ptr = ptr.map_addr(|a| a & val)`. This can be used in tagged + /// pointer schemes to atomically unset tag bits. + /// + /// **Caveat**: This operation returns the previous value. To compute the + /// stored value without losing provenance, you may use [`map_addr`]. For + /// example: `a.fetch_and(val).map_addr(|a| a & val)`. + /// + /// `fetch_and` takes an [`Ordering`] argument which describes the memory + /// ordering of this operation. All ordering modes are possible. Note that + /// using [`Acquire`] makes the store part of this operation [`Relaxed`], + /// and using [`Release`] makes the load part [`Relaxed`]. + /// + /// **Note**: This method is only available on platforms that support atomic + /// operations on [`AtomicPtr`]. + /// + /// This API and its claimed semantics are part of the Strict Provenance + /// experiment, see the [module documentation for `ptr`][crate::ptr] for + /// details. + /// + /// [`map_addr`]: pointer::map_addr + /// + /// # Examples + /// + /// ``` + /// use core::sync::atomic::{AtomicPtr, Ordering}; + /// + /// let pointer = &mut 3i64 as *mut i64; + /// // A tagged pointer + /// let atom = AtomicPtr::::new(pointer.map_addr(|a| a | 1)); + /// assert_eq!(atom.fetch_or(1, Ordering::Relaxed).addr() & 1, 1); + /// // Untag, and extract the previously tagged pointer. + /// let untagged = atom.fetch_and(!1, Ordering::Relaxed) + /// .map_addr(|a| a & !1); + /// assert_eq!(untagged, pointer); + /// ``` + #[inline] + #[cfg(target_has_atomic = "ptr")] + #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] + pub fn fetch_and(&self, val: usize, order: Ordering) -> *mut T { + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_and(self.as_ptr(), val, order).cast() } + } + + /// Performs a bitwise "xor" operation on the address of the current + /// pointer, and the argument `val`, and stores a pointer with provenance of + /// the current pointer and the resulting address. + /// + /// This is equivalent to using [`map_addr`] to atomically perform + /// `ptr = ptr.map_addr(|a| a ^ val)`. This can be used in tagged + /// pointer schemes to atomically toggle tag bits. + /// + /// **Caveat**: This operation returns the previous value. To compute the + /// stored value without losing provenance, you may use [`map_addr`]. For + /// example: `a.fetch_xor(val).map_addr(|a| a ^ val)`. + /// + /// `fetch_xor` takes an [`Ordering`] argument which describes the memory + /// ordering of this operation. All ordering modes are possible. Note that + /// using [`Acquire`] makes the store part of this operation [`Relaxed`], + /// and using [`Release`] makes the load part [`Relaxed`]. + /// + /// **Note**: This method is only available on platforms that support atomic + /// operations on [`AtomicPtr`]. + /// + /// This API and its claimed semantics are part of the Strict Provenance + /// experiment, see the [module documentation for `ptr`][crate::ptr] for + /// details. + /// + /// [`map_addr`]: pointer::map_addr + /// + /// # Examples + /// + /// ``` + /// use core::sync::atomic::{AtomicPtr, Ordering}; + /// + /// let pointer = &mut 3i64 as *mut i64; + /// let atom = AtomicPtr::::new(pointer); + /// + /// // Toggle a tag bit on the pointer. + /// atom.fetch_xor(1, Ordering::Relaxed); + /// assert_eq!(atom.load(Ordering::Relaxed).addr() & 1, 1); + /// ``` + #[inline] + #[cfg(target_has_atomic = "ptr")] + #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] + pub fn fetch_xor(&self, val: usize, order: Ordering) -> *mut T { + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_xor(self.as_ptr(), val, order).cast() } + } + + /// Returns a mutable pointer to the underlying pointer. + /// + /// Doing non-atomic reads and writes on the resulting pointer can be a data race. + /// This method is mostly useful for FFI, where the function signature may use + /// `*mut *mut T` instead of `&AtomicPtr`. + /// + /// Returning an `*mut` pointer from a shared reference to this atomic is safe because the + /// atomic types work with interior mutability. All modifications of an atomic change the value + /// through a shared reference, and can do so safely as long as they use atomic operations. Any + /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the + /// requirements of the [memory model]. + /// + /// # Examples + /// + /// ```ignore (extern-declaration) + /// use std::sync::atomic::AtomicPtr; + /// + /// extern "C" { + /// fn my_atomic_op(arg: *mut *mut u32); + /// } + /// + /// let mut value = 17; + /// let atomic = AtomicPtr::new(&mut value); + /// + /// // SAFETY: Safe as long as `my_atomic_op` is atomic. + /// unsafe { + /// my_atomic_op(atomic.as_ptr()); + /// } + /// ``` + /// + /// [memory model]: self#memory-model-for-atomic-accesses + #[inline] + #[stable(feature = "atomic_as_ptr", since = "1.70.0")] + #[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")] + #[lint::never_returns_null_ptr] + pub const fn as_ptr(&self) -> *mut *mut T { + self.v.get().cast() + } +} + +#[cfg(target_has_atomic_load_store = "8")] +#[stable(feature = "atomic_bool_from", since = "1.24.0")] +#[rustc_const_unstable(feature = "const_convert", issue = "143773")] +const impl From for AtomicBool { + /// Converts a `bool` into an `AtomicBool`. + /// + /// # Examples + /// + /// ``` + /// use std::sync::atomic::AtomicBool; + /// let atomic_bool = AtomicBool::from(true); + /// assert_eq!(format!("{atomic_bool:?}"), "true") + /// ``` + #[inline] + fn from(b: bool) -> Self { + Self::new(b) + } +} + +#[cfg(target_has_atomic_load_store = "ptr")] +#[stable(feature = "atomic_from", since = "1.23.0")] +#[rustc_const_unstable(feature = "const_convert", issue = "143773")] +const impl From<*mut T> for AtomicPtr { + /// Converts a `*mut T` into an `AtomicPtr`. + #[inline] + fn from(p: *mut T) -> Self { + Self::new(p) + } +} + +#[allow(unused_macros)] // This macro ends up being unused on some architectures. +macro_rules! if_8_bit { + (u8, $( yes = [$($yes:tt)*], )? $( no = [$($no:tt)*], )? ) => { concat!("", $($($yes)*)?) }; + (i8, $( yes = [$($yes:tt)*], )? $( no = [$($no:tt)*], )? ) => { concat!("", $($($yes)*)?) }; + ($_:ident, $( yes = [$($yes:tt)*], )? $( no = [$($no:tt)*], )? ) => { concat!("", $($($no)*)?) }; +} + +#[cfg(target_has_atomic_load_store)] +macro_rules! atomic_int { + ($cfg_base:meta, + $cfg_cas:meta, + $cfg_align:meta, + $stable:meta, + $stable_cxchg:meta, + $stable_debug:meta, + $stable_access:meta, + $stable_from:meta, + $stable_nand:meta, + $const_stable_new:meta, + $const_stable_into_inner:meta, + $s_int_type:literal, + $extra_feature:expr, + $min_fn:ident, $max_fn:ident, + $align:expr, + $int_type:ident $atomic_type:ident) => { + /// An integer type which can be safely shared between threads. + /// + /// This type has the same + #[doc = if_8_bit!( + $int_type, + yes = ["size, alignment, and bit validity"], + no = ["size and bit validity"], + )] + /// as the underlying integer type, [` + #[doc = $s_int_type] + /// `]. + #[doc = if_8_bit! { + $int_type, + no = [ + "However, the alignment of this type is always equal to its ", + "size, even on targets where [`", $s_int_type, "`] has a ", + "lesser alignment." + ], + }] + /// + /// For more about the differences between atomic types and + /// non-atomic types as well as information about the portability of + /// this type, please see the [module-level documentation]. + /// + /// **Note:** This type is only available on platforms that support + /// atomic loads and stores of [` + #[doc = $s_int_type] + /// `]. + /// + /// [module-level documentation]: crate::sync::atomic + #[$stable] + pub type $atomic_type = Atomic<$int_type>; + + #[$stable] + impl Default for $atomic_type { + #[inline] + fn default() -> Self { + Self::new(Default::default()) + } + } + + #[$stable_from] + #[rustc_const_unstable(feature = "const_convert", issue = "143773")] + const impl From<$int_type> for $atomic_type { + #[doc = concat!("Converts an `", stringify!($int_type), "` into an `", stringify!($atomic_type), "`.")] + #[inline] + fn from(v: $int_type) -> Self { Self::new(v) } + } + + #[$stable_debug] + impl fmt::Debug for $atomic_type { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&self.load(Ordering::Relaxed), f) + } + } + + impl $atomic_type { + /// Creates a new atomic integer. + /// + /// # Examples + /// + #[cfg_attr($cfg_base, doc = "```")] + #[cfg_attr(not($cfg_base), doc = "```compile_fail")] + #[doc = concat!($extra_feature, "use std::sync::atomic::", stringify!($atomic_type), ";")] + /// + #[doc = concat!("let atomic_forty_two = ", stringify!($atomic_type), "::new(42);")] + /// ``` + #[inline] + #[$stable] + #[$const_stable_new] + #[must_use] + pub const fn new(v: $int_type) -> Self { + // SAFETY: + // `Atomic` is essentially a transparent wrapper around `T`. + unsafe { transmute(v) } + } + + /// Creates a new reference to an atomic integer from a pointer. + /// + /// # Examples + /// + #[cfg_attr($cfg_base, doc = "```rust")] + #[cfg_attr(not($cfg_base), doc = "```rust,compile_fail")] + #[doc = concat!($extra_feature, "use std::sync::atomic::{self, ", stringify!($atomic_type), "};")] + /// + /// // Get a pointer to an allocated value + #[doc = concat!("let ptr: *mut ", stringify!($int_type), " = Box::into_raw(Box::new(0));")] + /// + #[doc = concat!("assert!(ptr.cast::<", stringify!($atomic_type), ">().is_aligned());")] + /// + /// { + /// // Create an atomic view of the allocated value + // SAFETY: this is a doc comment, tidy, it can't hurt you (also guaranteed by the construction of `ptr` and the assert above) + #[doc = concat!(" let atomic = unsafe {", stringify!($atomic_type), "::from_ptr(ptr) };")] + /// + /// // Use `atomic` for atomic operations, possibly share it with other threads + /// atomic.store(1, atomic::Ordering::Relaxed); + /// } + /// + /// // It's ok to non-atomically access the value behind `ptr`, + /// // since the reference to the atomic ended its lifetime in the block above + /// assert_eq!(unsafe { *ptr }, 1); + /// + /// // Deallocate the value + /// unsafe { drop(Box::from_raw(ptr)) } + /// ``` + /// + /// # Safety + /// + /// * `ptr` must be aligned to + #[doc = concat!(" `align_of::<", stringify!($atomic_type), ">()`")] + #[doc = if_8_bit!{ + $int_type, + yes = [ + " (note that this is always true, since `align_of::<", + stringify!($atomic_type), ">() == 1`)." + ], + no = [ + " (note that on some platforms this can be bigger than `align_of::<", + stringify!($int_type), ">()`)." + ], + }] + /// * `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`. + /// * You must adhere to the [Memory model for atomic accesses]. In particular, it is not + /// allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different + /// sizes, without synchronization. + /// + /// [valid]: crate::ptr#safety + /// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses + #[inline] + #[stable(feature = "atomic_from_ptr", since = "1.75.0")] + #[rustc_const_stable(feature = "const_atomic_from_ptr", since = "1.84.0")] + #[requires(ptr.cast::<$atomic_type>().is_aligned())] + #[requires(!ptr.is_null())] + #[requires(ub_checks::can_dereference(ptr))] + #[requires(ub_checks::can_write(ptr))] + #[ensures(|result: &&$atomic_type| { + core::ptr::eq(*result, ptr.cast::<$atomic_type>()) + })] + #[ensures(|result: &&$atomic_type| { + ub_checks::can_dereference(*result as *const $atomic_type) + })] + #[ensures(|result: &&$atomic_type| { + ub_checks::can_write((*result).as_ptr()) + })] + pub const unsafe fn from_ptr<'a>(ptr: *mut $int_type) -> &'a $atomic_type { + // SAFETY: guaranteed by the caller + unsafe { &*ptr.cast() } + } + + /// Creates a new pointer to an atomic integer from a pointer. + /// + /// This is useful if you want to do volatile atomic accesses, and thus avoid creating + /// a reference to the destination. + #[inline] + #[unstable(feature = "atomic_volatile", issue = "158947")] + pub const fn from_ptr_raw(ptr: *mut $int_type) -> *const $atomic_type { + ptr.cast_const().cast() + } + + /// Returns a mutable reference to the underlying integer. + /// + /// This is safe because the mutable reference guarantees that no other threads are + /// concurrently accessing the atomic data. + /// + /// # Examples + /// + #[cfg_attr($cfg_base, doc = "```")] + #[cfg_attr(not($cfg_base), doc = "```compile_fail")] + #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")] + /// + #[doc = concat!("let mut some_var = ", stringify!($atomic_type), "::new(10);")] + /// assert_eq!(*some_var.get_mut(), 10); + /// *some_var.get_mut() = 5; + /// assert_eq!(some_var.load(Ordering::SeqCst), 5); + /// ``` + #[inline] + #[$stable_access] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + pub const fn get_mut(&mut self) -> &mut $int_type { + // SAFETY: + // `Atomic` is essentially a transparent wrapper around `T`. + unsafe { &mut *self.as_ptr() } + } + + #[doc = concat!("Get atomic access to a `&mut ", stringify!($int_type), "`.")] + /// + #[doc = if_8_bit! { + $int_type, + no = [ + "**Note:** This function is only available on targets where `", + stringify!($atomic_type), "` has the same alignment as `", stringify!($int_type), "`." + ], + }] + /// + /// # Examples + /// + #[cfg_attr($cfg_align, doc = "```rust")] + #[cfg_attr(not($cfg_align), doc = "```rust,compile_fail")] + #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")] + /// + /// let mut some_int = 123; + #[doc = concat!("let a = ", stringify!($atomic_type), "::from_mut(&mut some_int);")] + /// a.store(100, Ordering::Relaxed); + /// assert_eq!(some_int, 100); + /// ``` + /// + #[inline] + #[cfg(any($cfg_align, doc))] + #[stable(feature = "atomic_from_mut", since = "1.98.0")] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + pub const fn from_mut(v: &mut $int_type) -> &mut Self { + let [] = [(); align_of::() - align_of::<$int_type>()]; + // SAFETY: + // - the mutable reference guarantees unique ownership. + // - the alignment of `$int_type` and `Self` is the + // same, as promised by $cfg_align and verified above. + unsafe { &mut *(v as *mut $int_type as *mut Self) } + } + + #[doc = concat!("Get non-atomic access to a `&mut [", stringify!($atomic_type), "]` slice")] + /// + /// This is safe because the mutable reference guarantees that no other threads are + /// concurrently accessing the atomic data. + /// + /// # Examples + /// + #[cfg_attr($cfg_base, doc = "```ignore-wasm")] + #[cfg_attr(not($cfg_base), doc = "```ignore-wasm,compile_fail")] + #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")] + /// + #[doc = concat!("let mut some_ints = [const { ", stringify!($atomic_type), "::new(0) }; 10];")] + /// + #[doc = concat!("let view: &mut [", stringify!($int_type), "] = ", stringify!($atomic_type), "::get_mut_slice(&mut some_ints);")] + /// assert_eq!(view, [0; 10]); + /// view + /// .iter_mut() + /// .enumerate() + /// .for_each(|(idx, int)| *int = idx as _); + /// + /// std::thread::scope(|s| { + /// some_ints + /// .iter() + /// .enumerate() + /// .for_each(|(idx, int)| { + /// s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _)); + /// }) + /// }); + /// ``` + #[inline] + #[stable(feature = "atomic_from_mut", since = "1.98.0")] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + pub const fn get_mut_slice(this: &mut [Self]) -> &mut [$int_type] { + // SAFETY: the mutable reference guarantees unique ownership. + unsafe { &mut *(this as *mut [Self] as *mut [$int_type]) } + } + + #[doc = concat!("Get atomic access to a `&mut [", stringify!($int_type), "]` slice.")] + /// + #[doc = if_8_bit! { + $int_type, + no = [ + "**Note:** This function is only available on targets where `", + stringify!($atomic_type), "` has the same alignment as `", stringify!($int_type), "`." + ], + }] + /// + /// # Examples + /// + #[cfg_attr($cfg_align, doc = "```ignore-wasm")] + #[cfg_attr(not($cfg_align), doc = "```ignore-wasm,compile_fail")] + #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")] + /// + /// let mut some_ints = [0; 10]; + #[doc = concat!("let a = &*", stringify!($atomic_type), "::from_mut_slice(&mut some_ints);")] + /// std::thread::scope(|s| { + /// for i in 0..a.len() { + /// s.spawn(move || a[i].store(i as _, Ordering::Relaxed)); + /// } + /// }); + /// for (i, n) in some_ints.into_iter().enumerate() { + /// assert_eq!(i, n as usize); + /// } + /// ``` + #[inline] + #[cfg(any($cfg_align, doc))] + #[stable(feature = "atomic_from_mut", since = "1.98.0")] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + pub const fn from_mut_slice(v: &mut [$int_type]) -> &mut [Self] { + let [] = [(); align_of::() - align_of::<$int_type>()]; + // SAFETY: + // - the mutable reference guarantees unique ownership. + // - the alignment of `$int_type` and `Self` is the + // same, as promised by $cfg_align and verified above. + unsafe { &mut *(v as *mut [$int_type] as *mut [Self]) } + } + + /// Consumes the atomic and returns the contained value. + /// + /// This is safe because passing `self` by value guarantees that no other threads are + /// concurrently accessing the atomic data. + /// + /// # Examples + /// + #[cfg_attr($cfg_base, doc = "```")] + #[cfg_attr(not($cfg_base), doc = "```compile_fail")] + #[doc = concat!($extra_feature, "use std::sync::atomic::", stringify!($atomic_type), ";")] + /// + #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")] + /// assert_eq!(some_var.into_inner(), 5); + /// ``` + #[inline] + #[$stable_access] + #[$const_stable_into_inner] + pub const fn into_inner(self) -> $int_type { + // SAFETY: + // `Atomic` is essentially a transparent wrapper around `T`. + unsafe { transmute(self) } + } + + /// Loads a value from the atomic integer. + /// + /// `load` takes an [`Ordering`] argument which describes the memory ordering of this operation. + /// Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`]. + /// + /// # Panics + /// + /// Panics if `order` is [`Release`] or [`AcqRel`]. + /// + /// # Examples + /// + #[cfg_attr($cfg_base, doc = "```")] + #[cfg_attr(not($cfg_base), doc = "```compile_fail")] + #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")] + /// + #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")] + /// + /// assert_eq!(some_var.load(Ordering::Relaxed), 5); + /// ``` + #[inline] + #[$stable] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[requires(order == Relaxed || order == Acquire || order == SeqCst)] + pub const fn load(&self, order: Ordering) -> $int_type { + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_load::<_, /* VOLATILE */ false>(self.as_ptr(), order) } + } + + /// Perform a volatile load from the atomic integer. + /// + /// `load_volatile` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`]. + /// + #[doc = include_str!("./atomic_load_volatile.md")] + /// + /// # Safety + /// + /// Behavior is undefined if any of the following conditions are violated: + /// + /// * `self` must be [valid] for reads, or `self` must point to memory + /// outside of all Rust allocations and reading from that memory must: + /// - not trap, and + /// - not cause any memory inside a Rust allocation to be modified. + /// + /// * `self` must be aligned to + #[doc = concat!(" `align_of::<", stringify!($atomic_type), ">()`")] + #[doc = if_8_bit!{ + $int_type, + yes = [ + " (note that this is always true, since `align_of::<", + stringify!($atomic_type), ">() == 1`)." + ], + no = [ + " (note that on some platforms this can be bigger than `align_of::<", + stringify!($int_type), ">()`)." + ], + }] + /// + /// * Reading from `self` must produce a properly initialized value of the underlying + /// integer type. + /// + /// [valid]: core::ptr#safety + /// + /// # Panics + /// + /// Panics if `order` is [`Release`] or [`AcqRel`]. + #[inline] + #[unstable(feature = "atomic_volatile", issue = "158947")] + #[rustc_const_unstable(feature = "atomic_volatile", issue = "158947")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + pub const unsafe fn load_volatile(self: *const Self, order: Ordering) -> $int_type { + // SAFETY: follows from our own safety requirements. + unsafe { + atomic_load::<_, /* VOLATILE */ true>(self.cast::<$int_type>(), order) + } + } + + /// Stores a value into the atomic integer. + /// + /// `store` takes an [`Ordering`] argument which describes the memory ordering of this operation. + /// Possible values are [`SeqCst`], [`Release`] and [`Relaxed`]. + /// + /// # Panics + /// + /// Panics if `order` is [`Acquire`] or [`AcqRel`]. + /// + /// # Examples + /// + #[cfg_attr($cfg_base, doc = "```")] + #[cfg_attr(not($cfg_base), doc = "```compile_fail")] + #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")] + /// + #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")] + /// + /// some_var.store(10, Ordering::Relaxed); + /// assert_eq!(some_var.load(Ordering::Relaxed), 10); + /// ``` + #[inline] + #[$stable] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[requires(order == Relaxed || order == Release || order == SeqCst)] + #[cfg_attr(kani, kani::modifies(self))] + pub const fn store(&self, val: $int_type, order: Ordering) { + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_store::<_, /* VOLATILE */ false>(self.as_ptr(), val, order); } + } + + /// Performs a volatile store into the atomic integer. + /// + /// `store_volatile` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. Possible values are [`SeqCst`], [`Release`] and [`Relaxed`]. + /// + #[doc = include_str!("./atomic_store_volatile.md")] + /// + /// # Safety + /// + /// Behavior is undefined if any of the following conditions are violated: + /// + /// * `self` must be either [valid] for writes, or `self` must point to memory + /// outside of all Rust allocations and writing to that memory must: + /// - not trap, and + /// - not cause any memory inside a Rust allocation to be modified. + /// + /// * `self` must be aligned to + #[doc = concat!(" `align_of::<", stringify!($atomic_type), ">()`")] + #[doc = if_8_bit!{ + $int_type, + yes = [ + " (note that this is always true, since `align_of::<", + stringify!($atomic_type), ">() == 1`)." + ], + no = [ + " (note that on some platforms this can be bigger than `align_of::<", + stringify!($int_type), ">()`)." + ], + }] + /// + /// [valid]: core::ptr#safety + /// + /// # Panics + /// + /// Panics if `order` is [`Acquire`] or [`AcqRel`]. + #[inline] + #[unstable(feature = "atomic_volatile", issue = "158947")] + #[rustc_const_unstable(feature = "atomic_volatile", issue = "158947")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + pub const unsafe fn store_volatile(self: *const Self, val: $int_type, order: Ordering) { + // SAFETY: follows from our own safety requirements. + unsafe { + atomic_store::<_, /* VOLATILE */ true>(self.cast::<$int_type>().cast_mut(), val, order); + } + } + + /// Stores a value into the atomic integer, returning the previous value. + /// + /// `swap` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + /// + /// **Note**: This method is only available on platforms that support atomic operations on + #[doc = concat!("[`", $s_int_type, "`].")] + /// + /// # Examples + /// + #[cfg_attr($cfg_cas, doc = "```")] + #[cfg_attr(not($cfg_cas), doc = "```compile_fail")] + #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")] + /// + #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")] + /// + /// assert_eq!(some_var.swap(10, Ordering::Relaxed), 5); + /// ``` + #[inline] + #[$stable] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[cfg(any($cfg_cas, doc))] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] + pub const fn swap(&self, val: $int_type, order: Ordering) -> $int_type { + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_swap(self.as_ptr(), val, order) } + } + + /// Stores a value into the atomic integer if the current value is the same as + /// the `current` value. + /// + /// The return value is always the previous value. If it is equal to `current`, then the + /// value was updated. + /// + /// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory + /// ordering of this operation. Notice that even when using [`AcqRel`], the operation + /// might fail and hence just perform an `Acquire` load, but not have `Release` semantics. + /// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it + /// happens, and using [`Release`] makes the load part [`Relaxed`]. + /// + /// **Note**: This method is only available on platforms that support atomic operations on + #[doc = concat!("[`", $s_int_type, "`].")] + /// + /// # Migrating to `compare_exchange` and `compare_exchange_weak` + /// + /// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for + /// memory orderings: + /// + /// Original | Success | Failure + /// -------- | ------- | ------- + /// Relaxed | Relaxed | Relaxed + /// Acquire | Acquire | Acquire + /// Release | Release | Relaxed + /// AcqRel | AcqRel | Acquire + /// SeqCst | SeqCst | SeqCst + /// + /// `compare_and_swap` and `compare_exchange` also differ in their return type. You can use + /// `compare_exchange(...).unwrap_or_else(|x| x)` to recover the behavior of `compare_and_swap`, + /// but in most cases it is more idiomatic to check whether the return value is `Ok` or `Err` + /// rather than to infer success vs failure based on the value that was read. + /// + /// During migration, consider whether it makes sense to use `compare_exchange_weak` instead. + /// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds, + /// which allows the compiler to generate better assembly code when the compare and swap + /// is used in a loop. + /// + /// # Examples + /// + #[cfg_attr($cfg_cas, doc = "```")] + #[cfg_attr(not($cfg_cas), doc = "```compile_fail")] + #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")] + /// + #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")] + /// + /// assert_eq!(some_var.compare_and_swap(5, 10, Ordering::Relaxed), 5); + /// assert_eq!(some_var.load(Ordering::Relaxed), 10); + /// + /// assert_eq!(some_var.compare_and_swap(6, 12, Ordering::Relaxed), 10); + /// assert_eq!(some_var.load(Ordering::Relaxed), 10); + /// ``` + #[inline] + #[$stable] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[deprecated( + since = "1.50.0", + note = "Use `compare_exchange` or `compare_exchange_weak` instead") + ] + #[cfg(any($cfg_cas, doc))] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] + pub const fn compare_and_swap(&self, + current: $int_type, + new: $int_type, + order: Ordering) -> $int_type { + match self.compare_exchange(current, + new, + order, + strongest_failure_ordering(order)) { + Ok(x) => x, + Err(x) => x, + } + } + + /// Stores a value into the atomic integer if the current value is the same as + /// the `current` value. + /// + /// The return value is a result indicating whether the new value was written and + /// containing the previous value. On success this value is guaranteed to be equal to + /// `current`. + /// + /// `compare_exchange` takes two [`Ordering`] arguments to describe the memory + /// ordering of this operation. `success` describes the required ordering for the + /// read-modify-write operation that takes place if the comparison with `current` succeeds. + /// `failure` describes the required ordering for the load operation that takes place when + /// the comparison fails. Using [`Acquire`] as success ordering makes the store part + /// of this operation [`Relaxed`], and using [`Release`] makes the successful load + /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]. + /// + /// **Note**: This method is only available on platforms that support atomic operations on + #[doc = concat!("[`", $s_int_type, "`].")] + /// + /// # Examples + /// + #[cfg_attr($cfg_cas, doc = "```")] + #[cfg_attr(not($cfg_cas), doc = "```compile_fail")] + #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")] + /// + #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")] + /// + /// assert_eq!(some_var.compare_exchange(5, 10, + /// Ordering::Acquire, + /// Ordering::Relaxed), + /// Ok(5)); + /// assert_eq!(some_var.load(Ordering::Relaxed), 10); + /// + /// assert_eq!(some_var.compare_exchange(6, 12, + /// Ordering::SeqCst, + /// Ordering::Acquire), + /// Err(10)); + /// assert_eq!(some_var.load(Ordering::Relaxed), 10); + /// ``` + /// + /// # Considerations + /// + /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides + /// of CAS operations. In particular, a load of the value followed by a successful + /// `compare_exchange` with the previous load *does not ensure* that other threads have not + /// changed the value in the interim! This is usually important when the *equality* check in + /// the `compare_exchange` is being used to check the *identity* of a value, but equality + /// does not necessarily imply identity. This is a particularly common case for pointers, as + /// a pointer holding the same address does not imply that the same object exists at that + /// address! In this case, `compare_exchange` can lead to the [ABA problem]. + /// + /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem + /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap + #[inline] + #[$stable_cxchg] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[cfg(any($cfg_cas, doc))] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[requires(failure == Relaxed || failure == Acquire || failure == SeqCst)] + #[cfg_attr(kani, kani::modifies(self))] + pub const fn compare_exchange(&self, + current: $int_type, + new: $int_type, + success: Ordering, + failure: Ordering) -> Result<$int_type, $int_type> { + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_compare_exchange(self.as_ptr(), current, new, success, failure) } + } + + /// Stores a value into the atomic integer if the current value is the same as + /// the `current` value. + /// + #[doc = concat!("Unlike [`", stringify!($atomic_type), "::compare_exchange`],")] + /// this function is allowed to spuriously fail even + /// when the comparison succeeds, which can result in more efficient code on some + /// platforms. The return value is a result indicating whether the new value was + /// written and containing the previous value. + /// + /// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory + /// ordering of this operation. `success` describes the required ordering for the + /// read-modify-write operation that takes place if the comparison with `current` succeeds. + /// `failure` describes the required ordering for the load operation that takes place when + /// the comparison fails. Using [`Acquire`] as success ordering makes the store part + /// of this operation [`Relaxed`], and using [`Release`] makes the successful load + /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]. + /// + /// **Note**: This method is only available on platforms that support atomic operations on + #[doc = concat!("[`", $s_int_type, "`].")] + /// + /// # Examples + /// + #[cfg_attr($cfg_cas, doc = "```")] + #[cfg_attr(not($cfg_cas), doc = "```compile_fail")] + #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")] + /// + #[doc = concat!("let val = ", stringify!($atomic_type), "::new(4);")] + /// + /// let mut old = val.load(Ordering::Relaxed); + /// loop { + /// let new = old * 2; + /// match val.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) { + /// Ok(_) => break, + /// Err(x) => old = x, + /// } + /// } + /// ``` + /// + /// # Considerations + /// + /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides + /// of CAS operations. In particular, a load of the value followed by a successful + /// `compare_exchange` with the previous load *does not ensure* that other threads have not + /// changed the value in the interim. This is usually important when the *equality* check in + /// the `compare_exchange` is being used to check the *identity* of a value, but equality + /// does not necessarily imply identity. This is a particularly common case for pointers, as + /// a pointer holding the same address does not imply that the same object exists at that + /// address! In this case, `compare_exchange` can lead to the [ABA problem]. + /// + /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem + /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap + #[inline] + #[$stable_cxchg] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[cfg(any($cfg_cas, doc))] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[requires(failure == Relaxed || failure == Acquire || failure == SeqCst)] + #[cfg_attr(kani, kani::modifies(self))] + pub const fn compare_exchange_weak(&self, + current: $int_type, + new: $int_type, + success: Ordering, + failure: Ordering) -> Result<$int_type, $int_type> { + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { + atomic_compare_exchange_weak(self.as_ptr(), current, new, success, failure) + } + } + + /// Adds to the current value, returning the previous value. + /// + /// This operation wraps around on overflow. + /// + /// `fetch_add` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + /// + /// **Note**: This method is only available on platforms that support atomic operations on + #[doc = concat!("[`", $s_int_type, "`].")] + /// + /// # Examples + /// + #[cfg_attr($cfg_cas, doc = "```")] + #[cfg_attr(not($cfg_cas), doc = "```compile_fail")] + #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")] + /// + #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0);")] + /// assert_eq!(foo.fetch_add(10, Ordering::SeqCst), 0); + /// assert_eq!(foo.load(Ordering::SeqCst), 10); + /// ``` + #[inline] + #[$stable] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[cfg(any($cfg_cas, doc))] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] + pub const fn fetch_add(&self, val: $int_type, order: Ordering) -> $int_type { + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_add(self.as_ptr(), val, order) } + } + + /// Subtracts from the current value, returning the previous value. + /// + /// This operation wraps around on overflow. + /// + /// `fetch_sub` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + /// + /// **Note**: This method is only available on platforms that support atomic operations on + #[doc = concat!("[`", $s_int_type, "`].")] + /// + /// # Examples + /// + #[cfg_attr($cfg_cas, doc = "```")] + #[cfg_attr(not($cfg_cas), doc = "```compile_fail")] + #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")] + /// + #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(20);")] + /// assert_eq!(foo.fetch_sub(10, Ordering::SeqCst), 20); + /// assert_eq!(foo.load(Ordering::SeqCst), 10); + /// ``` + #[inline] + #[$stable] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[cfg(any($cfg_cas, doc))] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] + pub const fn fetch_sub(&self, val: $int_type, order: Ordering) -> $int_type { + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_sub(self.as_ptr(), val, order) } + } + + /// Bitwise "and" with the current value. + /// + /// Performs a bitwise "and" operation on the current value and the argument `val`, and + /// sets the new value to the result. + /// + /// Returns the previous value. + /// + /// `fetch_and` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + /// + /// **Note**: This method is only available on platforms that support atomic operations on + #[doc = concat!("[`", $s_int_type, "`].")] + /// + /// # Examples + /// + #[cfg_attr($cfg_cas, doc = "```")] + #[cfg_attr(not($cfg_cas), doc = "```compile_fail")] + #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")] + /// + #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0b101101);")] + /// assert_eq!(foo.fetch_and(0b110011, Ordering::SeqCst), 0b101101); + /// assert_eq!(foo.load(Ordering::SeqCst), 0b100001); + /// ``` + #[inline] + #[$stable] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[cfg(any($cfg_cas, doc))] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] + pub const fn fetch_and(&self, val: $int_type, order: Ordering) -> $int_type { + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_and(self.as_ptr(), val, order) } + } + + /// Bitwise "nand" with the current value. + /// + /// Performs a bitwise "nand" operation on the current value and the argument `val`, and + /// sets the new value to the result. + /// + /// Returns the previous value. + /// + /// `fetch_nand` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + /// + /// **Note**: This method is only available on platforms that support atomic operations on + #[doc = concat!("[`", $s_int_type, "`].")] + /// + /// # Examples + /// + #[cfg_attr($cfg_cas, doc = "```")] + #[cfg_attr(not($cfg_cas), doc = "```compile_fail")] + #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")] + /// + #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0x13);")] + /// assert_eq!(foo.fetch_nand(0x31, Ordering::SeqCst), 0x13); + /// assert_eq!(foo.load(Ordering::SeqCst), !(0x13 & 0x31)); + /// ``` + #[inline] + #[$stable_nand] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[cfg(any($cfg_cas, doc))] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] + pub const fn fetch_nand(&self, val: $int_type, order: Ordering) -> $int_type { + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_nand(self.as_ptr(), val, order) } + } + + /// Bitwise "or" with the current value. + /// + /// Performs a bitwise "or" operation on the current value and the argument `val`, and + /// sets the new value to the result. + /// + /// Returns the previous value. + /// + /// `fetch_or` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + /// + /// **Note**: This method is only available on platforms that support atomic operations on + #[doc = concat!("[`", $s_int_type, "`].")] + /// + /// # Examples + /// + #[cfg_attr($cfg_cas, doc = "```")] + #[cfg_attr(not($cfg_cas), doc = "```compile_fail")] + #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")] + /// + #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0b101101);")] + /// assert_eq!(foo.fetch_or(0b110011, Ordering::SeqCst), 0b101101); + /// assert_eq!(foo.load(Ordering::SeqCst), 0b111111); + /// ``` + #[inline] + #[$stable] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[cfg(any($cfg_cas, doc))] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] + pub const fn fetch_or(&self, val: $int_type, order: Ordering) -> $int_type { + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_or(self.as_ptr(), val, order) } + } + + /// Bitwise "xor" with the current value. + /// + /// Performs a bitwise "xor" operation on the current value and the argument `val`, and + /// sets the new value to the result. + /// + /// Returns the previous value. + /// + /// `fetch_xor` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + /// + /// **Note**: This method is only available on platforms that support atomic operations on + #[doc = concat!("[`", $s_int_type, "`].")] + /// + /// # Examples + /// + #[cfg_attr($cfg_cas, doc = "```")] + #[cfg_attr(not($cfg_cas), doc = "```compile_fail")] + #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")] + /// + #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0b101101);")] + /// assert_eq!(foo.fetch_xor(0b110011, Ordering::SeqCst), 0b101101); + /// assert_eq!(foo.load(Ordering::SeqCst), 0b011110); + /// ``` + #[inline] + #[$stable] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[cfg(any($cfg_cas, doc))] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] + pub const fn fetch_xor(&self, val: $int_type, order: Ordering) -> $int_type { + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_xor(self.as_ptr(), val, order) } + } + + /// An alias for + #[doc = concat!("[`", stringify!($atomic_type), "::try_update`]")] + /// . + #[inline] + #[stable(feature = "no_more_cas", since = "1.45.0")] + #[cfg(any($cfg_cas, doc))] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[deprecated( + since = "1.99.0", + note = "renamed to `try_update` for consistency", + suggestion = "try_update" + )] + pub fn fetch_update(&self, + set_order: Ordering, + fetch_order: Ordering, + f: F) -> Result<$int_type, $int_type> + where F: FnMut($int_type) -> Option<$int_type> { + self.try_update(set_order, fetch_order, f) + } + + /// Fetches the value, and applies a function to it that returns an optional + /// new value. Returns a `Result` of `Ok(previous_value)` if the function returned `Some(_)`, else + /// `Err(previous_value)`. + /// + #[doc = concat!("See also: [`update`](`", stringify!($atomic_type), "::update`).")] + /// + /// Note: This may call the function multiple times if the value has been changed from other threads in + /// the meantime, as long as the function returns `Some(_)`, but the function will have been applied + /// only once to the stored value. + /// + /// `try_update` takes two [`Ordering`] arguments to describe the memory ordering of this operation. + /// The first describes the required ordering for when the operation finally succeeds while the second + /// describes the required ordering for loads. These correspond to the success and failure orderings of + #[doc = concat!("[`", stringify!($atomic_type), "::compare_exchange`]")] + /// respectively. + /// + /// Using [`Acquire`] as success ordering makes the store part + /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load + /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]. + /// + /// **Note**: This method is only available on platforms that support atomic operations on + #[doc = concat!("[`", $s_int_type, "`].")] + /// + /// # Considerations + /// + /// This method is not magic; it is not provided by the hardware, and does not act like a + /// critical section or mutex. + /// + /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to + /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem] + /// if this atomic integer is an index or more generally if knowledge of only the *bitwise value* + /// of the atomic is not in and of itself sufficient to ensure any required preconditions. + /// + /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem + /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap + /// + /// # Examples + /// + #[cfg_attr($cfg_cas, doc = "```rust")] + #[cfg_attr(not($cfg_cas), doc = "```rust,compile_fail")] + #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")] + /// + #[doc = concat!("let x = ", stringify!($atomic_type), "::new(7);")] + /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(7)); + /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(7)); + /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(8)); + /// assert_eq!(x.load(Ordering::SeqCst), 9); + /// ``` + #[inline] + #[stable(feature = "atomic_try_update", since = "1.95.0")] + #[cfg(any($cfg_cas, doc))] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + pub fn try_update( + &self, + set_order: Ordering, + fetch_order: Ordering, + mut f: impl FnMut($int_type) -> Option<$int_type>, + ) -> Result<$int_type, $int_type> { + let mut prev = self.load(fetch_order); + while let Some(next) = f(prev) { + match self.compare_exchange_weak(prev, next, set_order, fetch_order) { + x @ Ok(_) => return x, + Err(next_prev) => prev = next_prev + } + } + Err(prev) + } + + /// Fetches the value, and applies a function to it that returns a new value. + /// The new value is stored and the old value is returned. + /// + #[doc = concat!("See also: [`try_update`](`", stringify!($atomic_type), "::try_update`).")] + /// + /// Note: This may call the function multiple times if the value has been changed from other threads in + /// the meantime, but the function will have been applied only once to the stored value. + /// + /// `update` takes two [`Ordering`] arguments to describe the memory ordering of this operation. + /// The first describes the required ordering for when the operation finally succeeds while the second + /// describes the required ordering for loads. These correspond to the success and failure orderings of + #[doc = concat!("[`", stringify!($atomic_type), "::compare_exchange`]")] + /// respectively. + /// + /// Using [`Acquire`] as success ordering makes the store part + /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load + /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]. + /// + /// **Note**: This method is only available on platforms that support atomic operations on + #[doc = concat!("[`", $s_int_type, "`].")] + /// + /// # Considerations + /// + /// [CAS operation]: https://en.wikipedia.org/wiki/Compare-and-swap + /// This method is not magic; it is not provided by the hardware, and does not act like a + /// critical section or mutex. + /// + /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to + /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem] + /// if this atomic integer is an index or more generally if knowledge of only the *bitwise value* + /// of the atomic is not in and of itself sufficient to ensure any required preconditions. + /// + /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem + /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap + /// + /// # Examples + /// + #[cfg_attr($cfg_cas, doc = "```rust")] + #[cfg_attr(not($cfg_cas), doc = "```rust,compile_fail")] + #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")] + /// + #[doc = concat!("let x = ", stringify!($atomic_type), "::new(7);")] + /// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 7); + /// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 8); + /// assert_eq!(x.load(Ordering::SeqCst), 9); + /// ``` + #[inline] + #[stable(feature = "atomic_try_update", since = "1.95.0")] + #[cfg(any($cfg_cas, doc))] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + pub fn update( + &self, + set_order: Ordering, + fetch_order: Ordering, + mut f: impl FnMut($int_type) -> $int_type, + ) -> $int_type { + let mut prev = self.load(fetch_order); + loop { + match self.compare_exchange_weak(prev, f(prev), set_order, fetch_order) { + Ok(x) => break x, + Err(next_prev) => prev = next_prev, + } + } + } + + /// Maximum with the current value. + /// + /// Finds the maximum of the current value and the argument `val`, and + /// sets the new value to the result. + /// + /// Returns the previous value. + /// + /// `fetch_max` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + /// + /// **Note**: This method is only available on platforms that support atomic operations on + #[doc = concat!("[`", $s_int_type, "`].")] + /// + /// # Examples + /// + #[cfg_attr($cfg_cas, doc = "```")] + #[cfg_attr(not($cfg_cas), doc = "```compile_fail")] + #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")] + /// + #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")] + /// assert_eq!(foo.fetch_max(42, Ordering::SeqCst), 23); + /// assert_eq!(foo.load(Ordering::SeqCst), 42); + /// ``` + /// + /// If you want to obtain the maximum value in one step, you can use the following: + /// + #[cfg_attr($cfg_cas, doc = "```")] + #[cfg_attr(not($cfg_cas), doc = "```compile_fail")] + #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")] + /// + #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")] + /// let bar = 42; + /// let max_foo = foo.fetch_max(bar, Ordering::SeqCst).max(bar); + /// assert!(max_foo == 42); + /// ``` + #[inline] + #[stable(feature = "atomic_min_max", since = "1.45.0")] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[cfg(any($cfg_cas, doc))] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] + pub const fn fetch_max(&self, val: $int_type, order: Ordering) -> $int_type { + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { $max_fn(self.as_ptr(), val, order) } + } + + /// Minimum with the current value. + /// + /// Finds the minimum of the current value and the argument `val`, and + /// sets the new value to the result. + /// + /// Returns the previous value. + /// + /// `fetch_min` takes an [`Ordering`] argument which describes the memory ordering + /// of this operation. All ordering modes are possible. Note that using + /// [`Acquire`] makes the store part of this operation [`Relaxed`], and + /// using [`Release`] makes the load part [`Relaxed`]. + /// + /// **Note**: This method is only available on platforms that support atomic operations on + #[doc = concat!("[`", $s_int_type, "`].")] + /// + /// # Examples + /// + #[cfg_attr($cfg_cas, doc = "```")] + #[cfg_attr(not($cfg_cas), doc = "```compile_fail")] + #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")] + /// + #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")] + /// assert_eq!(foo.fetch_min(42, Ordering::Relaxed), 23); + /// assert_eq!(foo.load(Ordering::Relaxed), 23); + /// assert_eq!(foo.fetch_min(22, Ordering::Relaxed), 23); + /// assert_eq!(foo.load(Ordering::Relaxed), 22); + /// ``` + /// + /// If you want to obtain the minimum value in one step, you can use the following: + /// + #[cfg_attr($cfg_cas, doc = "```")] + #[cfg_attr(not($cfg_cas), doc = "```compile_fail")] + #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")] + /// + #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")] + /// let bar = 12; + /// let min_foo = foo.fetch_min(bar, Ordering::SeqCst).min(bar); + /// assert_eq!(min_foo, 12); + /// ``` + #[inline] + #[stable(feature = "atomic_min_max", since = "1.45.0")] + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[cfg(any($cfg_cas, doc))] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] + pub const fn fetch_min(&self, val: $int_type, order: Ordering) -> $int_type { + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { $min_fn(self.as_ptr(), val, order) } + } + + /// Returns a mutable pointer to the underlying integer. + /// + /// Doing non-atomic reads and writes on the resulting integer can be a data race. + /// This method is mostly useful for FFI, where the function signature may use + #[doc = concat!("`*mut ", stringify!($int_type), "` instead of `&", stringify!($atomic_type), "`.")] + /// + /// Returning an `*mut` pointer from a shared reference to this atomic is safe because the + /// atomic types work with interior mutability. All modifications of an atomic change the value + /// through a shared reference, and can do so safely as long as they use atomic operations. Any + /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the + /// requirements of the [memory model]. + /// + /// # Examples + /// + /// ```ignore (extern-declaration) + /// # fn main() { + #[doc = concat!($extra_feature, "use std::sync::atomic::", stringify!($atomic_type), ";")] + /// + /// extern "C" { + #[doc = concat!(" fn my_atomic_op(arg: *mut ", stringify!($int_type), ");")] + /// } + /// + #[doc = concat!("let atomic = ", stringify!($atomic_type), "::new(1);")] + /// + /// // SAFETY: Safe as long as `my_atomic_op` is atomic. + /// unsafe { + /// my_atomic_op(atomic.as_ptr()); + /// } + /// # } + /// ``` + /// + /// [memory model]: self#memory-model-for-atomic-accesses + #[inline] + #[stable(feature = "atomic_as_ptr", since = "1.70.0")] + #[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")] + #[lint::never_returns_null_ptr] + pub const fn as_ptr(&self) -> *mut $int_type { + self.v.get().cast() + } + } + } +} + +#[cfg(target_has_atomic_load_store = "8")] +atomic_int! { + target_has_atomic_load_store = "8", + target_has_atomic = "8", + target_has_atomic_primitive_alignment = "8", + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"), + rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"), + "i8", + "", + atomic_min, atomic_max, + 1, + i8 AtomicI8 +} +#[cfg(target_has_atomic_load_store = "8")] +atomic_int! { + target_has_atomic_load_store = "8", + target_has_atomic = "8", + target_has_atomic_primitive_alignment = "8", + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"), + rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"), + "u8", + "", + atomic_umin, atomic_umax, + 1, + u8 AtomicU8 +} +#[cfg(target_has_atomic_load_store = "16")] +atomic_int! { + target_has_atomic_load_store = "16", + target_has_atomic = "16", + target_has_atomic_primitive_alignment = "16", + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"), + rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"), + "i16", + "", + atomic_min, atomic_max, + 2, + i16 AtomicI16 +} +#[cfg(target_has_atomic_load_store = "16")] +atomic_int! { + target_has_atomic_load_store = "16", + target_has_atomic = "16", + target_has_atomic_primitive_alignment = "16", + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"), + rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"), + "u16", + "", + atomic_umin, atomic_umax, + 2, + u16 AtomicU16 +} +#[cfg(target_has_atomic_load_store = "32")] +atomic_int! { + target_has_atomic_load_store = "32", + target_has_atomic = "32", + target_has_atomic_primitive_alignment = "32", + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"), + rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"), + "i32", + "", + atomic_min, atomic_max, + 4, + i32 AtomicI32 +} +#[cfg(target_has_atomic_load_store = "32")] +atomic_int! { + target_has_atomic_load_store = "32", + target_has_atomic = "32", + target_has_atomic_primitive_alignment = "32", + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"), + rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"), + "u32", + "", + atomic_umin, atomic_umax, + 4, + u32 AtomicU32 +} +#[cfg(target_has_atomic_load_store = "64")] +atomic_int! { + target_has_atomic_load_store = "64", + target_has_atomic = "64", + target_has_atomic_primitive_alignment = "64", + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"), + rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"), + "i64", + "", + atomic_min, atomic_max, + 8, + i64 AtomicI64 +} +#[cfg(target_has_atomic_load_store = "64")] +atomic_int! { + target_has_atomic_load_store = "64", + target_has_atomic = "64", + target_has_atomic_primitive_alignment = "64", + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + stable(feature = "integer_atomics_stable", since = "1.34.0"), + rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"), + rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"), + "u64", + "", + atomic_umin, atomic_umax, + 8, + u64 AtomicU64 +} +#[cfg(any(target_has_atomic_load_store = "128", doc))] +atomic_int! { + target_has_atomic_load_store = "128", + target_has_atomic = "128", + target_has_atomic_primitive_alignment = "128", + unstable(feature = "integer_atomics", issue = "99069"), + unstable(feature = "integer_atomics", issue = "99069"), + unstable(feature = "integer_atomics", issue = "99069"), + unstable(feature = "integer_atomics", issue = "99069"), + unstable(feature = "integer_atomics", issue = "99069"), + unstable(feature = "integer_atomics", issue = "99069"), + rustc_const_unstable(feature = "integer_atomics", issue = "99069"), + rustc_const_unstable(feature = "integer_atomics", issue = "99069"), + "i128", + "#![feature(integer_atomics)]\n\n", + atomic_min, atomic_max, + 16, + i128 AtomicI128 +} +#[cfg(any(target_has_atomic_load_store = "128", doc))] +atomic_int! { + target_has_atomic_load_store = "128", + target_has_atomic = "128", + target_has_atomic_primitive_alignment = "128", + unstable(feature = "integer_atomics", issue = "99069"), + unstable(feature = "integer_atomics", issue = "99069"), + unstable(feature = "integer_atomics", issue = "99069"), + unstable(feature = "integer_atomics", issue = "99069"), + unstable(feature = "integer_atomics", issue = "99069"), + unstable(feature = "integer_atomics", issue = "99069"), + rustc_const_unstable(feature = "integer_atomics", issue = "99069"), + rustc_const_unstable(feature = "integer_atomics", issue = "99069"), + "u128", + "#![feature(integer_atomics)]\n\n", + atomic_umin, atomic_umax, + 16, + u128 AtomicU128 +} + +#[cfg(target_has_atomic_load_store = "ptr")] +macro_rules! atomic_int_ptr_sized { + ( $($target_pointer_width:literal $align:literal)* ) => { $( + #[cfg(target_pointer_width = $target_pointer_width)] + atomic_int! { + target_has_atomic_load_store = "ptr", + target_has_atomic = "ptr", + target_has_atomic_primitive_alignment = "ptr", + stable(feature = "rust1", since = "1.0.0"), + stable(feature = "extended_compare_and_swap", since = "1.10.0"), + stable(feature = "atomic_debug", since = "1.3.0"), + stable(feature = "atomic_access", since = "1.15.0"), + stable(feature = "atomic_from", since = "1.23.0"), + stable(feature = "atomic_nand", since = "1.27.0"), + rustc_const_stable(feature = "const_ptr_sized_atomics", since = "1.24.0"), + rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"), + "isize", + "", + atomic_min, atomic_max, + $align, + isize AtomicIsize + } + #[cfg(target_pointer_width = $target_pointer_width)] + atomic_int! { + target_has_atomic_load_store = "ptr", + target_has_atomic = "ptr", + target_has_atomic_primitive_alignment = "ptr", + stable(feature = "rust1", since = "1.0.0"), + stable(feature = "extended_compare_and_swap", since = "1.10.0"), + stable(feature = "atomic_debug", since = "1.3.0"), + stable(feature = "atomic_access", since = "1.15.0"), + stable(feature = "atomic_from", since = "1.23.0"), + stable(feature = "atomic_nand", since = "1.27.0"), + rustc_const_stable(feature = "const_ptr_sized_atomics", since = "1.24.0"), + rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"), + "usize", + "", + atomic_umin, atomic_umax, + $align, + usize AtomicUsize + } + + /// An [`AtomicIsize`] initialized to `0`. + #[cfg(target_pointer_width = $target_pointer_width)] + #[stable(feature = "rust1", since = "1.0.0")] + #[deprecated( + since = "1.34.0", + note = "the `new` function is now preferred", + suggestion = "AtomicIsize::new(0)", + )] + #[expect(clippy::declare_interior_mutable_const, reason = "legacy atomic initializer")] + pub const ATOMIC_ISIZE_INIT: AtomicIsize = AtomicIsize::new(0); + + /// An [`AtomicUsize`] initialized to `0`. + #[cfg(target_pointer_width = $target_pointer_width)] + #[stable(feature = "rust1", since = "1.0.0")] + #[deprecated( + since = "1.34.0", + note = "the `new` function is now preferred", + suggestion = "AtomicUsize::new(0)", + )] + #[expect(clippy::declare_interior_mutable_const, reason = "legacy atomic initializer")] + pub const ATOMIC_USIZE_INIT: AtomicUsize = AtomicUsize::new(0); + )* }; +} + +#[cfg(target_has_atomic_load_store = "ptr")] +atomic_int_ptr_sized! { + "16" 2 + "32" 4 + "64" 8 +} + +#[inline] +#[cfg(target_has_atomic)] +const fn strongest_failure_ordering(order: Ordering) -> Ordering { + match order { + Release => Relaxed, + Relaxed => Relaxed, + SeqCst => SeqCst, + Acquire => Acquire, + AcqRel => Acquire, + } +} + +#[inline] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +#[rustc_const_unstable(feature = "const_atomic", issue = "160078")] +#[cfg_attr(kani, kani::modifies(dst))] +#[requires(ub_checks::can_write(dst))] +#[requires(order == Relaxed || order == Release || order == SeqCst)] +#[ensures(|_| ub_checks::can_dereference(dst as *const T))] +#[ensures(|_| ub_checks::can_write(dst))] +const unsafe fn atomic_store(dst: *mut T, val: T, order: Ordering) { + // SAFETY: the caller must uphold the safety contract for `atomic_store`. + unsafe { + match order { + Relaxed => intrinsics::atomic_store::(dst, val), + Release => intrinsics::atomic_store::(dst, val), + SeqCst => intrinsics::atomic_store::(dst, val), + Acquire => panic!("there is no such thing as an acquire store"), + AcqRel => panic!("there is no such thing as an acquire-release store"), + } + } +} + +#[inline] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +#[rustc_const_unstable(feature = "const_atomic", issue = "160078")] +// Kani models writable object bounds and alignment. Page protections belong to the OS. +#[requires((order == Relaxed && small_read_only_atomic_load::()) || ub_checks::can_write(dst as *mut T))] +#[requires(ub_checks::can_dereference(dst))] +#[requires(order == Relaxed || order == Acquire || order == SeqCst)] +#[ensures(|_| ub_checks::can_dereference(dst))] +const unsafe fn atomic_load(dst: *const T, order: Ordering) -> T { + // SAFETY: the caller must uphold the safety contract for `atomic_load`. + unsafe { + match order { + Relaxed => intrinsics::atomic_load::(dst), + Acquire => intrinsics::atomic_load::(dst), + SeqCst => intrinsics::atomic_load::(dst), + Release => panic!("there is no such thing as a release load"), + AcqRel => panic!("there is no such thing as an acquire-release load"), + } + } +} + +#[inline] +#[cfg(target_has_atomic)] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +#[rustc_const_unstable(feature = "const_atomic", issue = "160078")] +#[cfg_attr(kani, kani::modifies(dst))] +#[requires(ub_checks::can_dereference(dst as *const T))] +#[requires(ub_checks::can_write(dst))] +#[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) +})] +const unsafe fn atomic_swap(dst: *mut T, val: T, order: Ordering) -> T { + // SAFETY: the caller must uphold the safety contract for `atomic_swap`. + unsafe { + match order { + Relaxed => intrinsics::atomic_xchg::(dst, val), + Acquire => intrinsics::atomic_xchg::(dst, val), + Release => intrinsics::atomic_xchg::(dst, val), + AcqRel => intrinsics::atomic_xchg::(dst, val), + SeqCst => intrinsics::atomic_xchg::(dst, val), + } + } +} + +/// Returns the previous value (like __sync_fetch_and_add). +#[inline] +#[cfg(target_has_atomic)] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +#[rustc_const_unstable(feature = "const_atomic", issue = "160078")] +#[cfg_attr(kani, kani::modifies(dst))] +#[requires(ub_checks::can_dereference(dst as *const T))] +#[requires(ub_checks::can_write(dst))] +#[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) +})] +const unsafe fn atomic_add(dst: *mut T, val: U, order: Ordering) -> T { + // SAFETY: the caller must uphold the safety contract for `atomic_add`. + unsafe { + match order { + Relaxed => intrinsics::atomic_xadd::(dst, val), + Acquire => intrinsics::atomic_xadd::(dst, val), + Release => intrinsics::atomic_xadd::(dst, val), + AcqRel => intrinsics::atomic_xadd::(dst, val), + SeqCst => intrinsics::atomic_xadd::(dst, val), + } + } +} + +/// Returns the previous value (like __sync_fetch_and_sub). +#[inline] +#[cfg(target_has_atomic)] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +#[rustc_const_unstable(feature = "const_atomic", issue = "160078")] +#[cfg_attr(kani, kani::modifies(dst))] +#[requires(ub_checks::can_dereference(dst as *const T))] +#[requires(ub_checks::can_write(dst))] +#[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) +})] +const unsafe fn atomic_sub(dst: *mut T, val: U, order: Ordering) -> T { + // SAFETY: the caller must uphold the safety contract for `atomic_sub`. + unsafe { + match order { + Relaxed => intrinsics::atomic_xsub::(dst, val), + Acquire => intrinsics::atomic_xsub::(dst, val), + Release => intrinsics::atomic_xsub::(dst, val), + AcqRel => intrinsics::atomic_xsub::(dst, val), + SeqCst => intrinsics::atomic_xsub::(dst, val), + } + } +} + +/// Publicly exposed for stdarch; nobody else should use this. +#[inline] +#[cfg(target_has_atomic)] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +#[unstable(feature = "core_intrinsics", issue = "none")] +#[doc(hidden)] +#[rustc_const_unstable(feature = "const_atomic", issue = "160078")] +#[cfg_attr(kani, kani::modifies(dst))] +#[requires(ub_checks::can_dereference(dst as *const T))] +#[requires(ub_checks::can_write(dst))] +#[requires(failure != Release && failure != AcqRel)] +#[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) +})] +pub const unsafe fn atomic_compare_exchange( + dst: *mut T, + old: T, + new: T, + success: Ordering, + failure: Ordering, +) -> Result { + // SAFETY: the caller must uphold the safety contract for `atomic_compare_exchange`. + let (val, ok) = unsafe { + match (success, failure) { + (Relaxed, Relaxed) => { + intrinsics::atomic_cxchg::(dst, old, new) + } + (Relaxed, Acquire) => { + intrinsics::atomic_cxchg::(dst, old, new) + } + (Relaxed, SeqCst) => { + intrinsics::atomic_cxchg::(dst, old, new) + } + (Acquire, Relaxed) => { + intrinsics::atomic_cxchg::(dst, old, new) + } + (Acquire, Acquire) => { + intrinsics::atomic_cxchg::(dst, old, new) + } + (Acquire, SeqCst) => { + intrinsics::atomic_cxchg::(dst, old, new) + } + (Release, Relaxed) => { + intrinsics::atomic_cxchg::(dst, old, new) + } + (Release, Acquire) => { + intrinsics::atomic_cxchg::(dst, old, new) + } + (Release, SeqCst) => { + intrinsics::atomic_cxchg::(dst, old, new) + } + (AcqRel, Relaxed) => { + intrinsics::atomic_cxchg::(dst, old, new) + } + (AcqRel, Acquire) => { + intrinsics::atomic_cxchg::(dst, old, new) + } + (AcqRel, SeqCst) => { + intrinsics::atomic_cxchg::(dst, old, new) + } + (SeqCst, Relaxed) => { + intrinsics::atomic_cxchg::(dst, old, new) + } + (SeqCst, Acquire) => { + intrinsics::atomic_cxchg::(dst, old, new) + } + (SeqCst, SeqCst) => { + intrinsics::atomic_cxchg::(dst, old, new) + } + (_, AcqRel) => panic!("there is no such thing as an acquire-release failure ordering"), + (_, Release) => panic!("there is no such thing as a release failure ordering"), + } + }; + if ok { Ok(val) } else { Err(val) } +} + +#[inline] +#[cfg(target_has_atomic)] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +#[rustc_const_unstable(feature = "const_atomic", issue = "160078")] +#[cfg_attr(kani, kani::modifies(dst))] +#[requires(ub_checks::can_dereference(dst as *const T))] +#[requires(ub_checks::can_write(dst))] +#[requires(failure != Release && failure != AcqRel)] +#[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) +})] +const unsafe fn atomic_compare_exchange_weak( + dst: *mut T, + old: T, + new: T, + success: Ordering, + failure: Ordering, +) -> Result { + // SAFETY: the caller must uphold the safety contract for `atomic_compare_exchange_weak`. + let (val, ok) = unsafe { + match (success, failure) { + (Relaxed, Relaxed) => { + intrinsics::atomic_cxchgweak::(dst, old, new) + } + (Relaxed, Acquire) => { + intrinsics::atomic_cxchgweak::(dst, old, new) + } + (Relaxed, SeqCst) => { + intrinsics::atomic_cxchgweak::(dst, old, new) + } + (Acquire, Relaxed) => { + intrinsics::atomic_cxchgweak::(dst, old, new) + } + (Acquire, Acquire) => { + intrinsics::atomic_cxchgweak::(dst, old, new) + } + (Acquire, SeqCst) => { + intrinsics::atomic_cxchgweak::(dst, old, new) + } + (Release, Relaxed) => { + intrinsics::atomic_cxchgweak::(dst, old, new) + } + (Release, Acquire) => { + intrinsics::atomic_cxchgweak::(dst, old, new) + } + (Release, SeqCst) => { + intrinsics::atomic_cxchgweak::(dst, old, new) + } + (AcqRel, Relaxed) => { + intrinsics::atomic_cxchgweak::(dst, old, new) + } + (AcqRel, Acquire) => { + intrinsics::atomic_cxchgweak::(dst, old, new) + } + (AcqRel, SeqCst) => { + intrinsics::atomic_cxchgweak::(dst, old, new) + } + (SeqCst, Relaxed) => { + intrinsics::atomic_cxchgweak::(dst, old, new) + } + (SeqCst, Acquire) => { + intrinsics::atomic_cxchgweak::(dst, old, new) + } + (SeqCst, SeqCst) => { + intrinsics::atomic_cxchgweak::(dst, old, new) + } + (_, AcqRel) => panic!("there is no such thing as an acquire-release failure ordering"), + (_, Release) => panic!("there is no such thing as a release failure ordering"), + } + }; + if ok { Ok(val) } else { Err(val) } +} + +#[inline] +#[cfg(target_has_atomic)] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +#[rustc_const_unstable(feature = "const_atomic", issue = "160078")] +#[cfg_attr(kani, kani::modifies(dst))] +#[requires(ub_checks::can_dereference(dst as *const T))] +#[requires(ub_checks::can_write(dst))] +#[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) +})] +const unsafe fn atomic_and(dst: *mut T, val: U, order: Ordering) -> T { + // SAFETY: the caller must uphold the safety contract for `atomic_and` + unsafe { + match order { + Relaxed => intrinsics::atomic_and::(dst, val), + Acquire => intrinsics::atomic_and::(dst, val), + Release => intrinsics::atomic_and::(dst, val), + AcqRel => intrinsics::atomic_and::(dst, val), + SeqCst => intrinsics::atomic_and::(dst, val), + } + } +} + +#[inline] +#[cfg(target_has_atomic)] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +#[rustc_const_unstable(feature = "const_atomic", issue = "160078")] +#[cfg_attr(kani, kani::modifies(dst))] +#[requires(ub_checks::can_dereference(dst as *const T))] +#[requires(ub_checks::can_write(dst))] +#[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) +})] +const unsafe fn atomic_nand(dst: *mut T, val: U, order: Ordering) -> T { + // SAFETY: the caller must uphold the safety contract for `atomic_nand` + unsafe { + match order { + Relaxed => intrinsics::atomic_nand::(dst, val), + Acquire => intrinsics::atomic_nand::(dst, val), + Release => intrinsics::atomic_nand::(dst, val), + AcqRel => intrinsics::atomic_nand::(dst, val), + SeqCst => intrinsics::atomic_nand::(dst, val), + } + } +} + +#[inline] +#[cfg(target_has_atomic)] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +#[rustc_const_unstable(feature = "const_atomic", issue = "160078")] +#[cfg_attr(kani, kani::modifies(dst))] +#[requires(ub_checks::can_dereference(dst as *const T))] +#[requires(ub_checks::can_write(dst))] +#[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) +})] +const unsafe fn atomic_or(dst: *mut T, val: U, order: Ordering) -> T { + // SAFETY: the caller must uphold the safety contract for `atomic_or` + unsafe { + match order { + SeqCst => intrinsics::atomic_or::(dst, val), + Acquire => intrinsics::atomic_or::(dst, val), + Release => intrinsics::atomic_or::(dst, val), + AcqRel => intrinsics::atomic_or::(dst, val), + Relaxed => intrinsics::atomic_or::(dst, val), + } + } +} + +#[inline] +#[cfg(target_has_atomic)] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +#[rustc_const_unstable(feature = "const_atomic", issue = "160078")] +#[cfg_attr(kani, kani::modifies(dst))] +#[requires(ub_checks::can_dereference(dst as *const T))] +#[requires(ub_checks::can_write(dst))] +#[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) +})] +const unsafe fn atomic_xor(dst: *mut T, val: U, order: Ordering) -> T { + // SAFETY: the caller must uphold the safety contract for `atomic_xor` + unsafe { + match order { + SeqCst => intrinsics::atomic_xor::(dst, val), + Acquire => intrinsics::atomic_xor::(dst, val), + Release => intrinsics::atomic_xor::(dst, val), + AcqRel => intrinsics::atomic_xor::(dst, val), + Relaxed => intrinsics::atomic_xor::(dst, val), + } + } +} + +/// Updates `*dst` to the max value of `val` and the old value (signed comparison) +#[inline] +#[cfg(target_has_atomic)] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +#[rustc_const_unstable(feature = "const_atomic", issue = "160078")] +#[cfg_attr(kani, kani::modifies(dst))] +#[requires(ub_checks::can_dereference(dst as *const T))] +#[requires(ub_checks::can_write(dst))] +#[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) +})] +const unsafe fn atomic_max(dst: *mut T, val: T, order: Ordering) -> T { + // SAFETY: the caller must uphold the safety contract for `atomic_max` + unsafe { + match order { + Relaxed => intrinsics::atomic_max::(dst, val), + Acquire => intrinsics::atomic_max::(dst, val), + Release => intrinsics::atomic_max::(dst, val), + AcqRel => intrinsics::atomic_max::(dst, val), + SeqCst => intrinsics::atomic_max::(dst, val), + } + } +} + +/// Updates `*dst` to the min value of `val` and the old value (signed comparison) +#[inline] +#[cfg(target_has_atomic)] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +#[rustc_const_unstable(feature = "const_atomic", issue = "160078")] +const unsafe fn atomic_min(dst: *mut T, val: T, order: Ordering) -> T { + // SAFETY: the caller must uphold the safety contract for `atomic_min` + unsafe { + match order { + Relaxed => intrinsics::atomic_min::(dst, val), + Acquire => intrinsics::atomic_min::(dst, val), + Release => intrinsics::atomic_min::(dst, val), + AcqRel => intrinsics::atomic_min::(dst, val), + SeqCst => intrinsics::atomic_min::(dst, val), + } + } +} + +/// Updates `*dst` to the max value of `val` and the old value (unsigned comparison) +#[inline] +#[cfg(target_has_atomic)] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +#[rustc_const_unstable(feature = "const_atomic", issue = "160078")] +#[cfg_attr(kani, kani::modifies(dst))] +#[requires(ub_checks::can_dereference(dst as *const T))] +#[requires(ub_checks::can_write(dst))] +#[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) +})] +const unsafe fn atomic_umax(dst: *mut T, val: T, order: Ordering) -> T { + // SAFETY: the caller must uphold the safety contract for `atomic_umax` + unsafe { + match order { + Relaxed => intrinsics::atomic_umax::(dst, val), + Acquire => intrinsics::atomic_umax::(dst, val), + Release => intrinsics::atomic_umax::(dst, val), + AcqRel => intrinsics::atomic_umax::(dst, val), + SeqCst => intrinsics::atomic_umax::(dst, val), + } + } +} + +/// Updates `*dst` to the min value of `val` and the old value (unsigned comparison) +#[inline] +#[cfg(target_has_atomic)] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +#[rustc_const_unstable(feature = "const_atomic", issue = "160078")] +#[cfg_attr(kani, kani::modifies(dst))] +#[requires(ub_checks::can_dereference(dst as *const T))] +#[requires(ub_checks::can_write(dst))] +#[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) +})] +const unsafe fn atomic_umin(dst: *mut T, val: T, order: Ordering) -> T { + // SAFETY: the caller must uphold the safety contract for `atomic_umin` + unsafe { + match order { + Relaxed => intrinsics::atomic_umin::(dst, val), + Acquire => intrinsics::atomic_umin::(dst, val), + Release => intrinsics::atomic_umin::(dst, val), + AcqRel => intrinsics::atomic_umin::(dst, val), + SeqCst => intrinsics::atomic_umin::(dst, val), + } + } +} + +/// An atomic fence. +/// +/// Fences create synchronization between themselves and atomic operations or fences in other +/// threads. It can be helpful to think of a fence as preventing the compiler and CPU from +/// reordering certain types of memory operations around it, but that is a simplified model which +/// fails to capture some of the nuances. +/// +/// There are 3 different ways to use an atomic fence: +/// +/// - atomic - fence synchronization: an atomic operation with (at least) [`Release`] ordering +/// semantics synchronizes with a fence with (at least) [`Acquire`] ordering semantics. +/// - fence - atomic synchronization: a fence with (at least) [`Release`] ordering semantics +/// synchronizes with an atomic operation with (at least) [`Acquire`] ordering semantics. +/// - fence - fence synchronization: a fence with (at least) [`Release`] ordering semantics +/// synchronizes with a fence with (at least) [`Acquire`] ordering semantics. +/// +/// These 3 ways complement the regular, fence-less, atomic - atomic synchronization. +/// +/// ## Atomic - Fence +/// +/// An atomic operation on one thread will synchronize with a fence on another thread when: +/// +/// - on thread 1: +/// - an atomic operation 'X' with (at least) [`Release`] ordering semantics on some atomic +/// object 'm', +/// +/// - is paired on thread 2 with: +/// - an atomic read 'Y' with any order on 'm', +/// - followed by a fence 'B' with (at least) [`Acquire`] ordering semantics. +/// +/// This provides a happens-before dependence between X and B. +/// +/// ```text +/// Thread 1 Thread 2 +/// +/// m.store(3, Release); X --------- +/// | +/// | +/// -------------> Y if m.load(Relaxed) == 3 { +/// B fence(Acquire); +/// ... +/// } +/// ``` +/// +/// ## Fence - Atomic +/// +/// A fence on one thread will synchronize with an atomic operation on another thread when: +/// +/// - on thread: +/// - a fence 'A' with (at least) [`Release`] ordering semantics, +/// - followed by an atomic write 'X' with any ordering on some atomic object 'm', +/// +/// - is paired on thread 2 with: +/// - an atomic operation 'Y' with (at least) [`Acquire`] ordering semantics. +/// +/// This provides a happens-before dependence between A and Y. +/// +/// ```text +/// Thread 1 Thread 2 +/// +/// fence(Release); A +/// m.store(3, Relaxed); X --------- +/// | +/// | +/// -------------> Y if m.load(Acquire) == 3 { +/// ... +/// } +/// ``` +/// +/// ## Fence - Fence +/// +/// A fence on one thread will synchronize with a fence on another thread when: +/// +/// - on thread 1: +/// - a fence 'A' which has (at least) [`Release`] ordering semantics, +/// - followed by an atomic write 'X' with any ordering on some atomic object 'm', +/// +/// - is paired on thread 2 with: +/// - an atomic read 'Y' with any ordering on 'm', +/// - followed by a fence 'B' with (at least) [`Acquire`] ordering semantics. +/// +/// This provides a happens-before dependence between A and B. +/// +/// ```text +/// Thread 1 Thread 2 +/// +/// fence(Release); A -------------- +/// m.store(3, Relaxed); X --------- | +/// | | +/// | | +/// -------------> Y if m.load(Relaxed) == 3 { +/// |-------> B fence(Acquire); +/// ... +/// } +/// ``` +/// +/// ## Mandatory Atomic +/// +/// Note that in the examples above, it is crucial that the access to `m` are atomic. Fences cannot +/// be used to establish synchronization between non-atomic accesses in different threads. However, +/// thanks to the happens-before relationship, any non-atomic access that happen-before the atomic +/// operation or fence with (at least) [`Release`] ordering semantics are now also properly +/// synchronized with any non-atomic accesses that happen-after the atomic operation or fence with +/// (at least) [`Acquire`] ordering semantics. +/// +/// ## Memory Ordering +/// +/// A fence which has [`SeqCst`] ordering, in addition to having both [`Acquire`] and [`Release`] +/// semantics, participates in the global program order of the other [`SeqCst`] operations and/or +/// fences. +/// +/// Accepts [`Acquire`], [`Release`], [`AcqRel`] and [`SeqCst`] orderings. +/// +/// # Panics +/// +/// Panics if `order` is [`Relaxed`]. +/// +/// # Examples +/// +/// ``` +/// use std::sync::atomic::AtomicBool; +/// use std::sync::atomic::fence; +/// use std::sync::atomic::Ordering; +/// +/// // A mutual exclusion primitive based on spinlock. +/// pub struct Mutex { +/// flag: AtomicBool, +/// } +/// +/// impl Mutex { +/// pub fn new() -> Mutex { +/// Mutex { +/// flag: AtomicBool::new(false), +/// } +/// } +/// +/// pub fn lock(&self) { +/// // Wait until the old value is `false`. +/// while self +/// .flag +/// .compare_exchange_weak(false, true, Ordering::Relaxed, Ordering::Relaxed) +/// .is_err() +/// {} +/// // This fence synchronizes-with store in `unlock`. +/// fence(Ordering::Acquire); +/// } +/// +/// pub fn unlock(&self) { +/// self.flag.store(false, Ordering::Release); +/// } +/// } +/// ``` +#[inline] +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_const_unstable(feature = "const_atomic", issue = "160078")] +#[rustc_diagnostic_item = "fence"] +#[doc(alias = "atomic_thread_fence")] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +pub const fn fence(order: Ordering) { + // SAFETY: using an atomic fence is safe. + unsafe { + match order { + Acquire => intrinsics::atomic_fence::<{ AO::Acquire }>(), + Release => intrinsics::atomic_fence::<{ AO::Release }>(), + AcqRel => intrinsics::atomic_fence::<{ AO::AcqRel }>(), + SeqCst => intrinsics::atomic_fence::<{ AO::SeqCst }>(), + Relaxed => panic!("there is no such thing as a relaxed fence"), + } + } +} + +/// An atomic fence for synchronization within a single thread. +/// +/// Like [`fence`], this function establishes synchronization with other atomic operations and +/// fences. However, unlike [`fence`], `compiler_fence` only establishes synchronization with +/// operations *in the same thread*. This may at first sound rather useless, since code within a +/// thread is typically already totally ordered and does not need any further synchronization. +/// However, there are cases where code can run on the same thread without being synchronized: +/// - The most common case is that of a *signal handler*: a signal handler runs in the same thread +/// as the code it interrupted, but it is not synchronized with that code. `compiler_fence` +/// can be used to establish synchronization between a thread and its signal handler, the same way +/// that `fence` can be used to establish synchronization across threads. +/// - Similar situations can arise in embedded programming with interrupt handlers, or in custom +/// implementations of preemptive green threads. In general, `compiler_fence` can establish +/// synchronization with code that is guaranteed to run on the same hardware CPU. +/// +/// See [`fence`] for how a fence can be used to achieve synchronization. Note that just like +/// [`fence`], synchronization still requires atomic operations to be used in both threads -- it is +/// not possible to perform synchronization entirely with fences and non-atomic operations. +/// +/// `compiler_fence` does not emit any machine code. However, note that `compiler_fence` is also +/// *not* a "compiler barrier". It can be helpful to think of a `compiler_fence` as preventing the +/// compiler from reordering certain types of memory operations around it, but that is a simplified +/// model which fails to capture some of the nuances. The only actual guarantee made by +/// `compiler_fence` is establishing synchronization with signal handlers and similar kinds of code, +/// under the rules described in the [`fence`] documentation. +/// +/// `compiler_fence` corresponds to [`atomic_signal_fence`] in C and C++. +/// +/// [`atomic_signal_fence`]: https://en.cppreference.com/w/cpp/atomic/atomic_signal_fence +/// +/// # Panics +/// +/// Panics if `order` is [`Relaxed`]. +/// +/// # Examples +/// +/// Without the two `compiler_fence` calls, the read of `IMPORTANT_VARIABLE` in `signal_handler` +/// is *undefined behavior* due to a data race, despite everything happening in a single thread. +/// This is because the signal handler is considered to run concurrently with its associated +/// thread, and explicit synchronization is required to pass data between a thread and its +/// signal handler. The code below uses two `compiler_fence` calls to establish the usual +/// release-acquire synchronization pattern (see [`fence`] for an image). +/// +/// ``` +/// use std::sync::atomic::AtomicBool; +/// use std::sync::atomic::Ordering; +/// use std::sync::atomic::compiler_fence; +/// +/// static mut IMPORTANT_VARIABLE: usize = 0; +/// static IS_READY: AtomicBool = AtomicBool::new(false); +/// +/// fn main() { +/// unsafe { IMPORTANT_VARIABLE = 42 }; +/// // Marks earlier writes as being released with future relaxed stores. +/// compiler_fence(Ordering::Release); +/// IS_READY.store(true, Ordering::Relaxed); +/// } +/// +/// fn signal_handler() { +/// if IS_READY.load(Ordering::Relaxed) { +/// // Acquires writes that were released with relaxed stores that we read from. +/// compiler_fence(Ordering::Acquire); +/// assert_eq!(unsafe { IMPORTANT_VARIABLE }, 42); +/// } +/// } +/// ``` +#[inline] +#[stable(feature = "compiler_fences", since = "1.21.0")] +#[rustc_const_unstable(feature = "const_atomic", issue = "160078")] +#[rustc_diagnostic_item = "compiler_fence"] +#[doc(alias = "atomic_signal_fence")] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +pub const fn compiler_fence(order: Ordering) { + // SAFETY: using an atomic fence is safe. + unsafe { + match order { + Acquire => intrinsics::atomic_singlethreadfence::<{ AO::Acquire }>(), + Release => intrinsics::atomic_singlethreadfence::<{ AO::Release }>(), + AcqRel => intrinsics::atomic_singlethreadfence::<{ AO::AcqRel }>(), + SeqCst => intrinsics::atomic_singlethreadfence::<{ AO::SeqCst }>(), + Relaxed => panic!("there is no such thing as a relaxed fence"), + } + } +} + +#[cfg(target_has_atomic_load_store = "8")] +#[stable(feature = "atomic_debug", since = "1.3.0")] +impl fmt::Debug for AtomicBool { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&self.load(Ordering::Relaxed), f) + } +} + +#[cfg(target_has_atomic_load_store = "ptr")] +#[stable(feature = "atomic_debug", since = "1.3.0")] +impl fmt::Debug for AtomicPtr { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&self.load(Ordering::Relaxed), f) + } +} + +#[cfg(target_has_atomic_load_store = "ptr")] +#[stable(feature = "atomic_pointer", since = "1.24.0")] +impl fmt::Pointer for AtomicPtr { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Pointer::fmt(&self.load(Ordering::Relaxed), f) + } +} + +/// Signals the processor that it is inside a busy-wait spin-loop ("spin lock"). +/// +/// This function is deprecated in favor of [`hint::spin_loop`]. +/// +/// [`hint::spin_loop`]: crate::hint::spin_loop +#[inline] +#[stable(feature = "spin_loop_hint", since = "1.24.0")] +#[deprecated(since = "1.51.0", note = "use hint::spin_loop instead")] +pub fn spin_loop_hint() { + spin_loop() +} + +// The module's read-only memory guarantee applies only to these small Relaxed loads. +#[cfg(kani)] +pub(crate) const fn small_read_only_atomic_load() -> bool { + (crate::mem::size_of::() <= 8 && cfg!(any( + target_arch = "x86_64", target_arch = "aarch64", target_arch = "loongarch64", + target_arch = "mips64", target_arch = "mips64r6", target_arch = "powerpc64", + target_arch = "riscv64", target_arch = "sparc64", target_arch = "s390x", + ))) || (crate::mem::size_of::() <= 4 && cfg!(any( + target_arch = "x86", target_arch = "arm", target_arch = "loongarch32", + target_arch = "mips", target_arch = "mips32r6", target_arch = "powerpc", + target_arch = "riscv32", target_arch = "sparc", target_arch = "hexagon", + ))) +} + +#[cfg(kani)] +#[unstable(feature = "kani", issue = "none")] +mod verify { + use super::*; + + // Generate candidates across the allocation. Contract proofs assume the callee's + // preconditions, retaining only initialized, aligned, readable, and writable offsets. + fn ptr_at_offset(buf: &mut [u8; 100]) -> *mut T { + let offset = kani::any_where(|offset: &usize| *offset < 100); + buf.as_mut_ptr().wrapping_add(offset).cast::() + } + + fn any_ordering() -> Ordering { + match kani::any::() { + 0 => Relaxed, + 1 => Release, + 2 => Acquire, + 3 => AcqRel, + _ => SeqCst, + } + } + + // Use the concrete Atomic type in proof targets: Kani's contract resolver + // does not resolve methods through the AtomicBool/AtomicPtr/integer aliases. + // Calls below still exercise the corresponding public aliases. + // Part 1: from_ptr. + #[cfg(target_has_atomic_load_store = "8")] + #[kani::proof_for_contract(Atomic::::from_ptr)] + pub fn harness_atomic_bool_from_ptr() { + // Arbitrary bool arrays use a MaybeUninit array internally, whose layout + // is unsupported by uninit-checks. Use independent symbolic bytes instead; + // from_ptr's preconditions retain only valid bool values at the chosen offset. + let mut buf: [u8; 100] = kani::any(); + let ptr = ptr_at_offset::(&mut buf); + + let _ = unsafe { AtomicBool::from_ptr(ptr) }; + let byte = unsafe { ptr.cast::().read() }; + assert!(byte <= 1); + kani::cover(byte == 0, "AtomicBool::from_ptr: false is reachable"); + kani::cover(byte == 1, "AtomicBool::from_ptr: true is reachable"); + kani::cover(true, "AtomicBool::from_ptr: reached after call"); + } + + // Harnesses for integer Atomic*::from_ptr functions. + macro_rules! from_ptr_harness { + ($name:ident, $atomic:ty, $value:ty) => { + #[kani::proof_for_contract(Atomic::<$value>::from_ptr)] + pub fn $name() { + let mut buf: [u8; 100] = kani::any(); + let ptr = ptr_at_offset::<$value>(&mut buf); + + let _ = unsafe { <$atomic>::from_ptr(ptr) }; + kani::cover(true, "integer from_ptr: reached after call"); + } + }; + } + + #[cfg(target_has_atomic_load_store = "8")] + from_ptr_harness!(harness_atomic_i8_from_ptr, AtomicI8, i8); + #[cfg(target_has_atomic_load_store = "8")] + from_ptr_harness!(harness_atomic_u8_from_ptr, AtomicU8, u8); + #[cfg(target_has_atomic_load_store = "16")] + from_ptr_harness!(harness_atomic_i16_from_ptr, AtomicI16, i16); + #[cfg(target_has_atomic_load_store = "16")] + from_ptr_harness!(harness_atomic_u16_from_ptr, AtomicU16, u16); + #[cfg(target_has_atomic_load_store = "32")] + from_ptr_harness!(harness_atomic_i32_from_ptr, AtomicI32, i32); + #[cfg(target_has_atomic_load_store = "32")] + from_ptr_harness!(harness_atomic_u32_from_ptr, AtomicU32, u32); + #[cfg(target_has_atomic_load_store = "64")] + from_ptr_harness!(harness_atomic_i64_from_ptr, AtomicI64, i64); + #[cfg(target_has_atomic_load_store = "64")] + from_ptr_harness!(harness_atomic_u64_from_ptr, AtomicU64, u64); + #[cfg(target_has_atomic_load_store = "128")] + from_ptr_harness!(harness_atomic_i128_from_ptr, AtomicI128, i128); + #[cfg(target_has_atomic_load_store = "128")] + from_ptr_harness!(harness_atomic_u128_from_ptr, AtomicU128, u128); + #[cfg(target_has_atomic_load_store = "ptr")] + from_ptr_harness!(harness_atomic_isize_from_ptr, AtomicIsize, isize); + #[cfg(target_has_atomic_load_store = "ptr")] + from_ptr_harness!(harness_atomic_usize_from_ptr, AtomicUsize, usize); + + // Harnesses for AtomicPtr::from_ptr. + // Kani matches this selector against the generic impl's definition path. + // `T` names its type parameter, not the concrete pointee used by the proof; + // each harness call below still instantiates the requested $pointee. + macro_rules! atomic_ptr_from_ptr_harness { + ($name:ident, $pointee:ty) => { + #[cfg(target_has_atomic_load_store = "ptr")] + #[kani::proof_for_contract(Atomic::<*mut T>::from_ptr)] + pub fn $name() { + // The stored pointer is arbitrary; the outer pointer targets valid local storage. + let mut value = kani::any::() as *mut $pointee; + let ptr = &mut value as *mut *mut $pointee; + + let _ = unsafe { AtomicPtr::<$pointee>::from_ptr(ptr) }; + kani::cover(true, "AtomicPtr::from_ptr: reached after call"); + } + }; + } + + // Cover pointee sizes 0, 1, 2, 4, and the non-power-of-two size 3. + atomic_ptr_from_ptr_harness!(harness_atomic_ptr_from_ptr_unit, ()); + atomic_ptr_from_ptr_harness!(harness_atomic_ptr_from_ptr_u8, u8); + atomic_ptr_from_ptr_harness!(harness_atomic_ptr_from_ptr_u16, u16); + atomic_ptr_from_ptr_harness!(harness_atomic_ptr_from_ptr_u32, u32); + atomic_ptr_from_ptr_harness!(harness_atomic_ptr_from_ptr_u8_3, [u8; 3]); + + // Part 2: unsafe atomic helpers. + // Harnesses for ordinary (non-volatile) atomic_store and atomic_load. + // Volatile accesses have separate safety requirements and are not covered here. + macro_rules! store_harness { + ($name:ident, $atomic:ty, $value:ty) => { + #[kani::proof_for_contract(atomic_store::<$value, false>)] + pub fn $name() { + let initial: $value = kani::any(); + let storage = <$atomic>::new(initial); + let val: $value = kani::any(); + + unsafe { atomic_store::<$value, false>(storage.as_ptr(), val, any_ordering()) }; + kani::cover(true, "atomic_store: reached after call"); + } + }; + } + + #[cfg(target_has_atomic_load_store = "8")] + store_harness!(harness_atomic_store_i8, AtomicI8, i8); + #[cfg(target_has_atomic_load_store = "8")] + store_harness!(harness_atomic_store_u8, AtomicU8, u8); + #[cfg(target_has_atomic_load_store = "16")] + store_harness!(harness_atomic_store_i16, AtomicI16, i16); + #[cfg(target_has_atomic_load_store = "16")] + store_harness!(harness_atomic_store_u16, AtomicU16, u16); + #[cfg(target_has_atomic_load_store = "32")] + store_harness!(harness_atomic_store_i32, AtomicI32, i32); + #[cfg(target_has_atomic_load_store = "32")] + store_harness!(harness_atomic_store_u32, AtomicU32, u32); + #[cfg(target_has_atomic_load_store = "64")] + store_harness!(harness_atomic_store_i64, AtomicI64, i64); + #[cfg(target_has_atomic_load_store = "64")] + store_harness!(harness_atomic_store_u64, AtomicU64, u64); + #[cfg(target_has_atomic_load_store = "128")] + store_harness!(harness_atomic_store_i128, AtomicI128, i128); + #[cfg(target_has_atomic_load_store = "128")] + store_harness!(harness_atomic_store_u128, AtomicU128, u128); + #[cfg(target_has_atomic_load_store = "ptr")] + store_harness!(harness_atomic_store_isize, AtomicIsize, isize); + #[cfg(target_has_atomic_load_store = "ptr")] + store_harness!(harness_atomic_store_usize, AtomicUsize, usize); + + // Pointer harnesses for atomic_store. + #[cfg(target_has_atomic_load_store = "ptr")] + #[kani::proof_for_contract(atomic_store::<*mut u8, false>)] + pub fn harness_atomic_store_ptr() { + let initial = kani::any::() as *mut u8; + let storage = AtomicPtr::::new(initial); + let val = kani::any::() as *mut u8; + + unsafe { atomic_store::<*mut u8, false>(storage.as_ptr(), val, any_ordering()) }; + kani::cover(true, "atomic_store: reached after call"); + } + + // Harnesses for atomic_load. + macro_rules! load_harness { + ($name:ident, $atomic:ty, $value:ty) => { + #[kani::proof_for_contract(atomic_load::<$value, false>)] + pub fn $name() { + let initial: $value = kani::any(); + let storage = <$atomic>::new(initial); + + let _ = unsafe { + atomic_load::<$value, false>(storage.as_ptr().cast_const(), any_ordering()) + }; + kani::cover(true, "atomic_load: reached after call"); + } + }; + } + + // Load helpers. + #[cfg(target_has_atomic_load_store = "8")] + load_harness!(harness_atomic_load_i8, AtomicI8, i8); + #[cfg(target_has_atomic_load_store = "8")] + load_harness!(harness_atomic_load_u8, AtomicU8, u8); + #[cfg(target_has_atomic_load_store = "16")] + load_harness!(harness_atomic_load_i16, AtomicI16, i16); + #[cfg(target_has_atomic_load_store = "16")] + load_harness!(harness_atomic_load_u16, AtomicU16, u16); + #[cfg(target_has_atomic_load_store = "32")] + load_harness!(harness_atomic_load_i32, AtomicI32, i32); + #[cfg(target_has_atomic_load_store = "32")] + load_harness!(harness_atomic_load_u32, AtomicU32, u32); + #[cfg(target_has_atomic_load_store = "64")] + load_harness!(harness_atomic_load_i64, AtomicI64, i64); + #[cfg(target_has_atomic_load_store = "64")] + load_harness!(harness_atomic_load_u64, AtomicU64, u64); + #[cfg(target_has_atomic_load_store = "128")] + load_harness!(harness_atomic_load_i128, AtomicI128, i128); + #[cfg(target_has_atomic_load_store = "128")] + load_harness!(harness_atomic_load_u128, AtomicU128, u128); + #[cfg(target_has_atomic_load_store = "ptr")] + load_harness!(harness_atomic_load_isize, AtomicIsize, isize); + #[cfg(target_has_atomic_load_store = "ptr")] + load_harness!(harness_atomic_load_usize, AtomicUsize, usize); + + // Pointer harness for atomic_load. + #[cfg(target_has_atomic_load_store = "ptr")] + #[kani::proof_for_contract(atomic_load::<*mut u8, false>)] + pub fn harness_atomic_load_ptr_u8() { + let initial = kani::any::() as *mut u8; + let storage = AtomicPtr::::new(initial); + + let _ = + unsafe { atomic_load::<*mut u8, false>(storage.as_ptr().cast_const(), any_ordering()) }; + kani::cover(true, "atomic_load: reached after call"); + } + + // Harnesses for atomic_swap, atomic_max, atomic_umax, and atomic_umin. + macro_rules! rmw_harness { + ($name:ident, $operation:ident, $atomic:ty, $value:ty) => { + #[kani::proof_for_contract($operation::<$value>)] + pub fn $name() { + let initial: $value = kani::any(); + let storage = <$atomic>::new(initial); + let val: $value = kani::any(); + + let _ = unsafe { $operation(storage.as_ptr(), val, any_ordering()) }; + kani::cover(true, "atomic_swap/max/umax/umin: reached after call"); + } + }; + } + + // Exchange helpers. + #[cfg(target_has_atomic = "8")] + rmw_harness!(harness_atomic_swap_i8, atomic_swap, AtomicI8, i8); + #[cfg(target_has_atomic = "8")] + rmw_harness!(harness_atomic_swap_u8, atomic_swap, AtomicU8, u8); + #[cfg(target_has_atomic = "16")] + rmw_harness!(harness_atomic_swap_i16, atomic_swap, AtomicI16, i16); + #[cfg(target_has_atomic = "16")] + rmw_harness!(harness_atomic_swap_u16, atomic_swap, AtomicU16, u16); + #[cfg(target_has_atomic = "32")] + rmw_harness!(harness_atomic_swap_i32, atomic_swap, AtomicI32, i32); + #[cfg(target_has_atomic = "32")] + rmw_harness!(harness_atomic_swap_u32, atomic_swap, AtomicU32, u32); + #[cfg(target_has_atomic = "64")] + rmw_harness!(harness_atomic_swap_i64, atomic_swap, AtomicI64, i64); + #[cfg(target_has_atomic = "64")] + rmw_harness!(harness_atomic_swap_u64, atomic_swap, AtomicU64, u64); + #[cfg(target_has_atomic = "128")] + rmw_harness!(harness_atomic_swap_i128, atomic_swap, AtomicI128, i128); + #[cfg(target_has_atomic = "128")] + rmw_harness!(harness_atomic_swap_u128, atomic_swap, AtomicU128, u128); + #[cfg(target_has_atomic = "ptr")] + rmw_harness!(harness_atomic_swap_isize, atomic_swap, AtomicIsize, isize); + #[cfg(target_has_atomic = "ptr")] + rmw_harness!(harness_atomic_swap_usize, atomic_swap, AtomicUsize, usize); + + // Signed maximum helpers. + #[cfg(target_has_atomic = "8")] + rmw_harness!(harness_atomic_max_i8, atomic_max, AtomicI8, i8); + #[cfg(target_has_atomic = "16")] + rmw_harness!(harness_atomic_max_i16, atomic_max, AtomicI16, i16); + #[cfg(target_has_atomic = "32")] + rmw_harness!(harness_atomic_max_i32, atomic_max, AtomicI32, i32); + #[cfg(target_has_atomic = "64")] + rmw_harness!(harness_atomic_max_i64, atomic_max, AtomicI64, i64); + #[cfg(target_has_atomic = "128")] + rmw_harness!(harness_atomic_max_i128, atomic_max, AtomicI128, i128); + #[cfg(target_has_atomic = "ptr")] + rmw_harness!(harness_atomic_max_isize, atomic_max, AtomicIsize, isize); + + // Unsigned maximum helpers. + #[cfg(target_has_atomic = "8")] + rmw_harness!(harness_atomic_umax_u8, atomic_umax, AtomicU8, u8); + #[cfg(target_has_atomic = "16")] + rmw_harness!(harness_atomic_umax_u16, atomic_umax, AtomicU16, u16); + #[cfg(target_has_atomic = "32")] + rmw_harness!(harness_atomic_umax_u32, atomic_umax, AtomicU32, u32); + #[cfg(target_has_atomic = "64")] + rmw_harness!(harness_atomic_umax_u64, atomic_umax, AtomicU64, u64); + #[cfg(target_has_atomic = "128")] + rmw_harness!(harness_atomic_umax_u128, atomic_umax, AtomicU128, u128); + #[cfg(target_has_atomic = "ptr")] + rmw_harness!(harness_atomic_umax_usize, atomic_umax, AtomicUsize, usize); + + // Unsigned minimum helpers. + #[cfg(target_has_atomic = "8")] + rmw_harness!(harness_atomic_umin_u8, atomic_umin, AtomicU8, u8); + #[cfg(target_has_atomic = "16")] + rmw_harness!(harness_atomic_umin_u16, atomic_umin, AtomicU16, u16); + #[cfg(target_has_atomic = "32")] + rmw_harness!(harness_atomic_umin_u32, atomic_umin, AtomicU32, u32); + #[cfg(target_has_atomic = "64")] + rmw_harness!(harness_atomic_umin_u64, atomic_umin, AtomicU64, u64); + #[cfg(target_has_atomic = "128")] + rmw_harness!(harness_atomic_umin_u128, atomic_umin, AtomicU128, u128); + #[cfg(target_has_atomic = "ptr")] + rmw_harness!(harness_atomic_umin_usize, atomic_umin, AtomicUsize, usize); + + // Pointer harnesses for atomic_swap. + #[cfg(target_has_atomic = "ptr")] + #[kani::proof_for_contract(atomic_swap::<*mut u8>)] + pub fn harness_atomic_swap_ptr() { + let initial = kani::any::() as *mut u8; + let storage = AtomicPtr::::new(initial); + let val = kani::any::() as *mut u8; + + let _ = unsafe { atomic_swap(storage.as_ptr(), val, any_ordering()) }; + kani::cover(true, "atomic_swap: reached after call"); + } + + // Harnesses for atomic_add, atomic_sub, atomic_and, atomic_nand, atomic_or, and atomic_xor. + macro_rules! binary_rmw_harness { + ($name:ident, $operation:ident, $atomic:ty, $value:ty) => { + #[kani::proof_for_contract($operation::<$value, $value>)] + pub fn $name() { + let initial: $value = kani::any(); + let storage = <$atomic>::new(initial); + let val: $value = kani::any(); + + let _ = unsafe { $operation(storage.as_ptr(), val, any_ordering()) }; + kani::cover(true, "atomic_add/sub/and/nand/or/xor: reached after call"); + } + }; + } + + // Pointer versions use a usize operand; raw pointers do not implement kani::Arbitrary. + macro_rules! binary_rmw_ptr_harness { + ($name:ident, $operation:ident, $pointee:ty) => { + #[kani::proof_for_contract($operation::<*mut $pointee, usize>)] + pub fn $name() { + let initial = kani::any::() as *mut $pointee; + let storage = AtomicPtr::<$pointee>::new(initial); + let val: usize = kani::any(); + + let _ = unsafe { $operation(storage.as_ptr(), val, any_ordering()) }; + kani::cover(true, "atomic pointer binary RMW: reached after call"); + } + }; + } + + // Add helpers. + #[cfg(target_has_atomic = "8")] + binary_rmw_harness!(harness_atomic_add_i8, atomic_add, AtomicI8, i8); + #[cfg(target_has_atomic = "8")] + binary_rmw_harness!(harness_atomic_add_u8, atomic_add, AtomicU8, u8); + #[cfg(target_has_atomic = "16")] + binary_rmw_harness!(harness_atomic_add_i16, atomic_add, AtomicI16, i16); + #[cfg(target_has_atomic = "16")] + binary_rmw_harness!(harness_atomic_add_u16, atomic_add, AtomicU16, u16); + #[cfg(target_has_atomic = "32")] + binary_rmw_harness!(harness_atomic_add_i32, atomic_add, AtomicI32, i32); + #[cfg(target_has_atomic = "32")] + binary_rmw_harness!(harness_atomic_add_u32, atomic_add, AtomicU32, u32); + #[cfg(target_has_atomic = "64")] + binary_rmw_harness!(harness_atomic_add_i64, atomic_add, AtomicI64, i64); + #[cfg(target_has_atomic = "64")] + binary_rmw_harness!(harness_atomic_add_u64, atomic_add, AtomicU64, u64); + #[cfg(target_has_atomic = "128")] + binary_rmw_harness!(harness_atomic_add_i128, atomic_add, AtomicI128, i128); + #[cfg(target_has_atomic = "128")] + binary_rmw_harness!(harness_atomic_add_u128, atomic_add, AtomicU128, u128); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_harness!(harness_atomic_add_isize, atomic_add, AtomicIsize, isize); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_harness!(harness_atomic_add_usize, atomic_add, AtomicUsize, usize); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_ptr_harness!(harness_atomic_add_ptr, atomic_add, u8); + + // Subtract helpers. + #[cfg(target_has_atomic = "8")] + binary_rmw_harness!(harness_atomic_sub_i8, atomic_sub, AtomicI8, i8); + #[cfg(target_has_atomic = "8")] + binary_rmw_harness!(harness_atomic_sub_u8, atomic_sub, AtomicU8, u8); + #[cfg(target_has_atomic = "16")] + binary_rmw_harness!(harness_atomic_sub_i16, atomic_sub, AtomicI16, i16); + #[cfg(target_has_atomic = "16")] + binary_rmw_harness!(harness_atomic_sub_u16, atomic_sub, AtomicU16, u16); + #[cfg(target_has_atomic = "32")] + binary_rmw_harness!(harness_atomic_sub_i32, atomic_sub, AtomicI32, i32); + #[cfg(target_has_atomic = "32")] + binary_rmw_harness!(harness_atomic_sub_u32, atomic_sub, AtomicU32, u32); + #[cfg(target_has_atomic = "64")] + binary_rmw_harness!(harness_atomic_sub_i64, atomic_sub, AtomicI64, i64); + #[cfg(target_has_atomic = "64")] + binary_rmw_harness!(harness_atomic_sub_u64, atomic_sub, AtomicU64, u64); + #[cfg(target_has_atomic = "128")] + binary_rmw_harness!(harness_atomic_sub_i128, atomic_sub, AtomicI128, i128); + #[cfg(target_has_atomic = "128")] + binary_rmw_harness!(harness_atomic_sub_u128, atomic_sub, AtomicU128, u128); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_harness!(harness_atomic_sub_isize, atomic_sub, AtomicIsize, isize); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_harness!(harness_atomic_sub_usize, atomic_sub, AtomicUsize, usize); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_ptr_harness!(harness_atomic_sub_ptr, atomic_sub, u8); + + // Bitwise AND helpers. + #[cfg(target_has_atomic = "8")] + binary_rmw_harness!(harness_atomic_and_i8, atomic_and, AtomicI8, i8); + #[cfg(target_has_atomic = "8")] + binary_rmw_harness!(harness_atomic_and_u8, atomic_and, AtomicU8, u8); + #[cfg(target_has_atomic = "16")] + binary_rmw_harness!(harness_atomic_and_i16, atomic_and, AtomicI16, i16); + #[cfg(target_has_atomic = "16")] + binary_rmw_harness!(harness_atomic_and_u16, atomic_and, AtomicU16, u16); + #[cfg(target_has_atomic = "32")] + binary_rmw_harness!(harness_atomic_and_i32, atomic_and, AtomicI32, i32); + #[cfg(target_has_atomic = "32")] + binary_rmw_harness!(harness_atomic_and_u32, atomic_and, AtomicU32, u32); + #[cfg(target_has_atomic = "64")] + binary_rmw_harness!(harness_atomic_and_i64, atomic_and, AtomicI64, i64); + #[cfg(target_has_atomic = "64")] + binary_rmw_harness!(harness_atomic_and_u64, atomic_and, AtomicU64, u64); + #[cfg(target_has_atomic = "128")] + binary_rmw_harness!(harness_atomic_and_i128, atomic_and, AtomicI128, i128); + #[cfg(target_has_atomic = "128")] + binary_rmw_harness!(harness_atomic_and_u128, atomic_and, AtomicU128, u128); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_harness!(harness_atomic_and_isize, atomic_and, AtomicIsize, isize); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_harness!(harness_atomic_and_usize, atomic_and, AtomicUsize, usize); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_ptr_harness!(harness_atomic_and_ptr, atomic_and, u8); + + // Bitwise NAND helpers. + #[cfg(target_has_atomic = "8")] + binary_rmw_harness!(harness_atomic_nand_i8, atomic_nand, AtomicI8, i8); + #[cfg(target_has_atomic = "8")] + binary_rmw_harness!(harness_atomic_nand_u8, atomic_nand, AtomicU8, u8); + #[cfg(target_has_atomic = "16")] + binary_rmw_harness!(harness_atomic_nand_i16, atomic_nand, AtomicI16, i16); + #[cfg(target_has_atomic = "16")] + binary_rmw_harness!(harness_atomic_nand_u16, atomic_nand, AtomicU16, u16); + #[cfg(target_has_atomic = "32")] + binary_rmw_harness!(harness_atomic_nand_i32, atomic_nand, AtomicI32, i32); + #[cfg(target_has_atomic = "32")] + binary_rmw_harness!(harness_atomic_nand_u32, atomic_nand, AtomicU32, u32); + #[cfg(target_has_atomic = "64")] + binary_rmw_harness!(harness_atomic_nand_i64, atomic_nand, AtomicI64, i64); + #[cfg(target_has_atomic = "64")] + binary_rmw_harness!(harness_atomic_nand_u64, atomic_nand, AtomicU64, u64); + #[cfg(target_has_atomic = "128")] + binary_rmw_harness!(harness_atomic_nand_i128, atomic_nand, AtomicI128, i128); + #[cfg(target_has_atomic = "128")] + binary_rmw_harness!(harness_atomic_nand_u128, atomic_nand, AtomicU128, u128); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_harness!(harness_atomic_nand_isize, atomic_nand, AtomicIsize, isize); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_harness!(harness_atomic_nand_usize, atomic_nand, AtomicUsize, usize); + + // Bitwise OR helpers. + #[cfg(target_has_atomic = "8")] + binary_rmw_harness!(harness_atomic_or_i8, atomic_or, AtomicI8, i8); + #[cfg(target_has_atomic = "8")] + binary_rmw_harness!(harness_atomic_or_u8, atomic_or, AtomicU8, u8); + #[cfg(target_has_atomic = "16")] + binary_rmw_harness!(harness_atomic_or_i16, atomic_or, AtomicI16, i16); + #[cfg(target_has_atomic = "16")] + binary_rmw_harness!(harness_atomic_or_u16, atomic_or, AtomicU16, u16); + #[cfg(target_has_atomic = "32")] + binary_rmw_harness!(harness_atomic_or_i32, atomic_or, AtomicI32, i32); + #[cfg(target_has_atomic = "32")] + binary_rmw_harness!(harness_atomic_or_u32, atomic_or, AtomicU32, u32); + #[cfg(target_has_atomic = "64")] + binary_rmw_harness!(harness_atomic_or_i64, atomic_or, AtomicI64, i64); + #[cfg(target_has_atomic = "64")] + binary_rmw_harness!(harness_atomic_or_u64, atomic_or, AtomicU64, u64); + #[cfg(target_has_atomic = "128")] + binary_rmw_harness!(harness_atomic_or_i128, atomic_or, AtomicI128, i128); + #[cfg(target_has_atomic = "128")] + binary_rmw_harness!(harness_atomic_or_u128, atomic_or, AtomicU128, u128); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_harness!(harness_atomic_or_isize, atomic_or, AtomicIsize, isize); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_harness!(harness_atomic_or_usize, atomic_or, AtomicUsize, usize); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_ptr_harness!(harness_atomic_or_ptr, atomic_or, u8); + + // Bitwise XOR helpers. + #[cfg(target_has_atomic = "8")] + binary_rmw_harness!(harness_atomic_xor_i8, atomic_xor, AtomicI8, i8); + #[cfg(target_has_atomic = "8")] + binary_rmw_harness!(harness_atomic_xor_u8, atomic_xor, AtomicU8, u8); + #[cfg(target_has_atomic = "16")] + binary_rmw_harness!(harness_atomic_xor_i16, atomic_xor, AtomicI16, i16); + #[cfg(target_has_atomic = "16")] + binary_rmw_harness!(harness_atomic_xor_u16, atomic_xor, AtomicU16, u16); + #[cfg(target_has_atomic = "32")] + binary_rmw_harness!(harness_atomic_xor_i32, atomic_xor, AtomicI32, i32); + #[cfg(target_has_atomic = "32")] + binary_rmw_harness!(harness_atomic_xor_u32, atomic_xor, AtomicU32, u32); + #[cfg(target_has_atomic = "64")] + binary_rmw_harness!(harness_atomic_xor_i64, atomic_xor, AtomicI64, i64); + #[cfg(target_has_atomic = "64")] + binary_rmw_harness!(harness_atomic_xor_u64, atomic_xor, AtomicU64, u64); + #[cfg(target_has_atomic = "128")] + binary_rmw_harness!(harness_atomic_xor_i128, atomic_xor, AtomicI128, i128); + #[cfg(target_has_atomic = "128")] + binary_rmw_harness!(harness_atomic_xor_u128, atomic_xor, AtomicU128, u128); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_harness!(harness_atomic_xor_isize, atomic_xor, AtomicIsize, isize); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_harness!(harness_atomic_xor_usize, atomic_xor, AtomicUsize, usize); + #[cfg(target_has_atomic = "ptr")] + binary_rmw_ptr_harness!(harness_atomic_xor_ptr, atomic_xor, u8); + + // Harnesses for atomic_compare_exchange and atomic_compare_exchange_weak. + macro_rules! compare_exchange_harness { + ($name:ident, $operation:ident, $atomic:ty, $value:ty) => { + #[kani::proof_for_contract($operation::<$value>)] + pub fn $name() { + let initial: $value = kani::any(); + let storage = <$atomic>::new(initial); + let old: $value = kani::any(); + let new: $value = kani::any(); + + let _ = unsafe { + $operation(storage.as_ptr(), old, new, any_ordering(), any_ordering()) + }; + kani::cover(true, "atomic_compare_exchange/weak: reached after call"); + } + }; + } + + // Strong compare-exchange helpers. + #[cfg(target_has_atomic = "8")] + compare_exchange_harness!( + harness_atomic_compare_exchange_i8, + atomic_compare_exchange, + AtomicI8, + i8 + ); + #[cfg(target_has_atomic = "8")] + compare_exchange_harness!( + harness_atomic_compare_exchange_u8, + atomic_compare_exchange, + AtomicU8, + u8 + ); + #[cfg(target_has_atomic = "16")] + compare_exchange_harness!( + harness_atomic_compare_exchange_i16, + atomic_compare_exchange, + AtomicI16, + i16 + ); + #[cfg(target_has_atomic = "16")] + compare_exchange_harness!( + harness_atomic_compare_exchange_u16, + atomic_compare_exchange, + AtomicU16, + u16 + ); + #[cfg(target_has_atomic = "32")] + compare_exchange_harness!( + harness_atomic_compare_exchange_i32, + atomic_compare_exchange, + AtomicI32, + i32 + ); + #[cfg(target_has_atomic = "32")] + compare_exchange_harness!( + harness_atomic_compare_exchange_u32, + atomic_compare_exchange, + AtomicU32, + u32 + ); + #[cfg(target_has_atomic = "64")] + compare_exchange_harness!( + harness_atomic_compare_exchange_i64, + atomic_compare_exchange, + AtomicI64, + i64 + ); + #[cfg(target_has_atomic = "64")] + compare_exchange_harness!( + harness_atomic_compare_exchange_u64, + atomic_compare_exchange, + AtomicU64, + u64 + ); + #[cfg(target_has_atomic = "128")] + compare_exchange_harness!( + harness_atomic_compare_exchange_i128, + atomic_compare_exchange, + AtomicI128, + i128 + ); + #[cfg(target_has_atomic = "128")] + compare_exchange_harness!( + harness_atomic_compare_exchange_u128, + atomic_compare_exchange, + AtomicU128, + u128 + ); + #[cfg(target_has_atomic = "ptr")] + compare_exchange_harness!( + harness_atomic_compare_exchange_isize, + atomic_compare_exchange, + AtomicIsize, + isize + ); + #[cfg(target_has_atomic = "ptr")] + compare_exchange_harness!( + harness_atomic_compare_exchange_usize, + atomic_compare_exchange, + AtomicUsize, + usize + ); + + // Weak compare-exchange helpers. + #[cfg(target_has_atomic = "8")] + compare_exchange_harness!( + harness_atomic_compare_exchange_weak_i8, + atomic_compare_exchange_weak, + AtomicI8, + i8 + ); + #[cfg(target_has_atomic = "8")] + compare_exchange_harness!( + harness_atomic_compare_exchange_weak_u8, + atomic_compare_exchange_weak, + AtomicU8, + u8 + ); + #[cfg(target_has_atomic = "16")] + compare_exchange_harness!( + harness_atomic_compare_exchange_weak_i16, + atomic_compare_exchange_weak, + AtomicI16, + i16 + ); + #[cfg(target_has_atomic = "16")] + compare_exchange_harness!( + harness_atomic_compare_exchange_weak_u16, + atomic_compare_exchange_weak, + AtomicU16, + u16 + ); + #[cfg(target_has_atomic = "32")] + compare_exchange_harness!( + harness_atomic_compare_exchange_weak_i32, + atomic_compare_exchange_weak, + AtomicI32, + i32 + ); + #[cfg(target_has_atomic = "32")] + compare_exchange_harness!( + harness_atomic_compare_exchange_weak_u32, + atomic_compare_exchange_weak, + AtomicU32, + u32 + ); + #[cfg(target_has_atomic = "64")] + compare_exchange_harness!( + harness_atomic_compare_exchange_weak_i64, + atomic_compare_exchange_weak, + AtomicI64, + i64 + ); + #[cfg(target_has_atomic = "64")] + compare_exchange_harness!( + harness_atomic_compare_exchange_weak_u64, + atomic_compare_exchange_weak, + AtomicU64, + u64 + ); + #[cfg(target_has_atomic = "128")] + compare_exchange_harness!( + harness_atomic_compare_exchange_weak_i128, + atomic_compare_exchange_weak, + AtomicI128, + i128 + ); + #[cfg(target_has_atomic = "128")] + compare_exchange_harness!( + harness_atomic_compare_exchange_weak_u128, + atomic_compare_exchange_weak, + AtomicU128, + u128 + ); + #[cfg(target_has_atomic = "ptr")] + compare_exchange_harness!( + harness_atomic_compare_exchange_weak_isize, + atomic_compare_exchange_weak, + AtomicIsize, + isize + ); + #[cfg(target_has_atomic = "ptr")] + compare_exchange_harness!( + harness_atomic_compare_exchange_weak_usize, + atomic_compare_exchange_weak, + AtomicUsize, + usize + ); + + // Pointer harnesses for atomic_compare_exchange and atomic_compare_exchange_weak. + macro_rules! compare_exchange_ptr_harness { + ($name:ident, $operation:ident, $pointee:ty) => { + #[kani::proof_for_contract($operation::<*mut $pointee>)] + pub fn $name() { + let initial = kani::any::() as *mut $pointee; + let storage = AtomicPtr::<$pointee>::new(initial); + let old = kani::any::() as *mut $pointee; + let new = kani::any::() as *mut $pointee; + + let _ = unsafe { + $operation(storage.as_ptr(), old, new, any_ordering(), any_ordering()) + }; + kani::cover(true, "atomic_compare_exchange/weak: reached after call"); + } + }; + } + + #[cfg(target_has_atomic = "ptr")] + compare_exchange_ptr_harness!(harness_atomic_compare_exchange_ptr, atomic_compare_exchange, u8); + #[cfg(target_has_atomic = "ptr")] + compare_exchange_ptr_harness!( + harness_atomic_compare_exchange_weak_ptr, + atomic_compare_exchange_weak, + u8 + ); + + // Part 2 (optional): safe atomic abstractions and ordering contracts. + fn any_load_order() -> Ordering { + match kani::any::() % 3 { + 0 => Relaxed, + 1 => Acquire, + _ => SeqCst, + } + } + + fn any_store_order() -> Ordering { + match kani::any::() % 3 { + 0 => Relaxed, + 1 => Release, + _ => SeqCst, + } + } + + fn any_failure_order() -> Ordering { + any_load_order() + } + + // Check the frame of each public method carrying a modifies(self) contract. + macro_rules! rmw_contract { + ($target:ty, $method:ident, $initial:expr $(, $arg:expr)*) => { + #[allow(deprecated)] + #[kani::proof_for_contract(Atomic::<$target>::$method)] + pub fn $method() { + let cell = $initial; + let _ = cell.$method($($arg,)* any_ordering()); + kani::cover(true, "atomic operation returned"); + } + }; + } + + macro_rules! integer_rmw_contracts { + ($module:ident, $value:ty) => { + mod $module { + use super::*; + + fn cell() -> Atomic<$value> { + Atomic::<$value>::new(kani::any()) + } + + rmw_contract!($value, compare_and_swap, cell(), kani::any(), kani::any()); + rmw_contract!($value, swap, cell(), kani::any()); + rmw_contract!($value, fetch_add, cell(), kani::any()); + rmw_contract!($value, fetch_sub, cell(), kani::any()); + rmw_contract!($value, fetch_and, cell(), kani::any()); + rmw_contract!($value, fetch_nand, cell(), kani::any()); + rmw_contract!($value, fetch_or, cell(), kani::any()); + rmw_contract!($value, fetch_xor, cell(), kani::any()); + rmw_contract!($value, fetch_max, cell(), kani::any()); + rmw_contract!($value, fetch_min, cell(), kani::any()); + } + }; + } + + #[cfg(target_has_atomic = "8")] + integer_rmw_contracts!(rmw_i8, i8); + #[cfg(target_has_atomic = "8")] + integer_rmw_contracts!(rmw_u8, u8); + #[cfg(target_has_atomic = "16")] + integer_rmw_contracts!(rmw_i16, i16); + #[cfg(target_has_atomic = "16")] + integer_rmw_contracts!(rmw_u16, u16); + #[cfg(target_has_atomic = "32")] + integer_rmw_contracts!(rmw_i32, i32); + #[cfg(target_has_atomic = "32")] + integer_rmw_contracts!(rmw_u32, u32); + #[cfg(target_has_atomic = "64")] + integer_rmw_contracts!(rmw_i64, i64); + #[cfg(target_has_atomic = "64")] + integer_rmw_contracts!(rmw_u64, u64); + #[cfg(target_has_atomic = "128")] + integer_rmw_contracts!(rmw_i128, i128); + #[cfg(target_has_atomic = "128")] + integer_rmw_contracts!(rmw_u128, u128); + #[cfg(target_has_atomic = "ptr")] + integer_rmw_contracts!(rmw_isize, isize); + #[cfg(target_has_atomic = "ptr")] + integer_rmw_contracts!(rmw_usize, usize); + + #[cfg(target_has_atomic = "8")] + mod rmw_bool { + use super::*; + + fn cell() -> AtomicBool { + AtomicBool::new(kani::any()) + } + + rmw_contract!(bool, compare_and_swap, cell(), kani::any(), kani::any()); + rmw_contract!(bool, swap, cell(), kani::any()); + rmw_contract!(bool, fetch_and, cell(), kani::any()); + rmw_contract!(bool, fetch_or, cell(), kani::any()); + rmw_contract!(bool, fetch_xor, cell(), kani::any()); + rmw_contract!(bool, fetch_nand, cell(), kani::any()); + rmw_contract!(bool, fetch_not, cell()); + } + + #[cfg(target_has_atomic = "ptr")] + mod rmw_ptr { + use super::*; + + fn pointer() -> *mut u8 { + kani::any::() as *mut u8 + } + + fn cell() -> AtomicPtr { + AtomicPtr::new(pointer()) + } + + rmw_contract!(*mut T, compare_and_swap, cell(), pointer(), pointer()); + rmw_contract!(*mut T, swap, cell(), pointer()); + rmw_contract!(*mut T, fetch_and, cell(), kani::any()); + rmw_contract!(*mut T, fetch_or, cell(), kani::any()); + rmw_contract!(*mut T, fetch_xor, cell(), kani::any()); + } + + // Harnesses for load and store methods of atomic types, with safe abstractions. + macro_rules! safe_load_store_harness { + ($load_name:ident, $store_name:ident, $atomic:ty, $value:ty) => { + #[kani::proof_for_contract(Atomic::<$value>::load)] + pub fn $load_name() { + let storage = <$atomic>::new(kani::any::<$value>()); + let _ = storage.load(any_load_order()); + kani::cover(true, "safe atomic load: reached after call"); + } + + #[kani::proof_for_contract(Atomic::<$value>::store)] + pub fn $store_name() { + let storage = <$atomic>::new(kani::any::<$value>()); + storage.store(kani::any::<$value>(), any_store_order()); + kani::cover(true, "safe atomic store: reached after call"); + } + }; + } + + #[cfg(target_has_atomic_load_store = "8")] + safe_load_store_harness!(harness_safe_load_bool, harness_safe_store_bool, AtomicBool, bool); + #[cfg(target_has_atomic_load_store = "8")] + safe_load_store_harness!(harness_safe_load_i8, harness_safe_store_i8, AtomicI8, i8); + #[cfg(target_has_atomic_load_store = "8")] + safe_load_store_harness!(harness_safe_load_u8, harness_safe_store_u8, AtomicU8, u8); + #[cfg(target_has_atomic_load_store = "16")] + safe_load_store_harness!(harness_safe_load_i16, harness_safe_store_i16, AtomicI16, i16); + #[cfg(target_has_atomic_load_store = "16")] + safe_load_store_harness!(harness_safe_load_u16, harness_safe_store_u16, AtomicU16, u16); + #[cfg(target_has_atomic_load_store = "32")] + safe_load_store_harness!(harness_safe_load_i32, harness_safe_store_i32, AtomicI32, i32); + #[cfg(target_has_atomic_load_store = "32")] + safe_load_store_harness!(harness_safe_load_u32, harness_safe_store_u32, AtomicU32, u32); + #[cfg(target_has_atomic_load_store = "64")] + safe_load_store_harness!(harness_safe_load_i64, harness_safe_store_i64, AtomicI64, i64); + #[cfg(target_has_atomic_load_store = "64")] + safe_load_store_harness!(harness_safe_load_u64, harness_safe_store_u64, AtomicU64, u64); + #[cfg(target_has_atomic_load_store = "128")] + safe_load_store_harness!(harness_safe_load_i128, harness_safe_store_i128, AtomicI128, i128); + #[cfg(target_has_atomic_load_store = "128")] + safe_load_store_harness!(harness_safe_load_u128, harness_safe_store_u128, AtomicU128, u128); + #[cfg(target_has_atomic_load_store = "ptr")] + safe_load_store_harness!(harness_safe_load_isize, harness_safe_store_isize, AtomicIsize, isize); + #[cfg(target_has_atomic_load_store = "ptr")] + safe_load_store_harness!(harness_safe_load_usize, harness_safe_store_usize, AtomicUsize, usize); + + #[cfg(target_has_atomic_load_store = "ptr")] + #[kani::proof_for_contract(Atomic::<*mut T>::load)] + pub fn harness_safe_load_ptr() { + let storage = AtomicPtr::::new(kani::any::() as *mut u8); + let _ = storage.load(any_load_order()); + kani::cover(true, "safe atomic pointer load: reached after call"); + } + + #[cfg(target_has_atomic_load_store = "ptr")] + #[kani::proof_for_contract(Atomic::<*mut T>::store)] + pub fn harness_safe_store_ptr() { + let storage = AtomicPtr::::new(kani::any::() as *mut u8); + storage.store(kani::any::() as *mut u8, any_store_order()); + kani::cover(true, "safe atomic pointer store: reached after call"); + } + + macro_rules! safe_compare_exchange_harness { + ($name:ident, $atomic:ty, $value:ty, $method:ident) => { + #[kani::proof_for_contract(Atomic::<$value>::$method)] + pub fn $name() { + let storage = <$atomic>::new(kani::any::<$value>()); + let _ = storage.$method( + kani::any::<$value>(), + kani::any::<$value>(), + any_ordering(), + any_failure_order(), + ); + kani::cover(true, "safe atomic compare-exchange: reached after call"); + } + }; + } + + #[cfg(target_has_atomic = "8")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_bool, + AtomicBool, + bool, + compare_exchange + ); + #[cfg(target_has_atomic = "8")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_weak_bool, + AtomicBool, + bool, + compare_exchange_weak + ); + #[cfg(target_has_atomic = "ptr")] + #[kani::proof_for_contract(Atomic::<*mut T>::compare_exchange)] + pub fn harness_safe_compare_exchange_ptr() { + let storage = AtomicPtr::::new(kani::any::() as *mut u8); + let _ = storage.compare_exchange( + kani::any::() as *mut u8, + kani::any::() as *mut u8, + any_ordering(), + any_failure_order(), + ); + kani::cover(true, "safe atomic pointer compare-exchange: reached after call"); + } + #[cfg(target_has_atomic = "ptr")] + #[kani::proof_for_contract(Atomic::<*mut T>::compare_exchange_weak)] + pub fn harness_safe_compare_exchange_weak_ptr() { + let storage = AtomicPtr::::new(kani::any::() as *mut u8); + let _ = storage.compare_exchange_weak( + kani::any::() as *mut u8, + kani::any::() as *mut u8, + any_ordering(), + any_failure_order(), + ); + kani::cover(true, "safe atomic pointer weak compare-exchange: reached after call"); + } + #[cfg(target_has_atomic = "8")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_u8, + AtomicU8, + u8, + compare_exchange + ); + #[cfg(target_has_atomic = "8")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_weak_u8, + AtomicU8, + u8, + compare_exchange_weak + ); + #[cfg(target_has_atomic = "8")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_i8, + AtomicI8, + i8, + compare_exchange + ); + #[cfg(target_has_atomic = "8")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_weak_i8, + AtomicI8, + i8, + compare_exchange_weak + ); + #[cfg(target_has_atomic = "16")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_i16, + AtomicI16, + i16, + compare_exchange + ); + #[cfg(target_has_atomic = "16")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_weak_i16, + AtomicI16, + i16, + compare_exchange_weak + ); + #[cfg(target_has_atomic = "16")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_u16, + AtomicU16, + u16, + compare_exchange + ); + #[cfg(target_has_atomic = "16")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_weak_u16, + AtomicU16, + u16, + compare_exchange_weak + ); + #[cfg(target_has_atomic = "32")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_i32, + AtomicI32, + i32, + compare_exchange + ); + #[cfg(target_has_atomic = "32")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_weak_i32, + AtomicI32, + i32, + compare_exchange_weak + ); + #[cfg(target_has_atomic = "32")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_u32, + AtomicU32, + u32, + compare_exchange + ); + #[cfg(target_has_atomic = "32")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_weak_u32, + AtomicU32, + u32, + compare_exchange_weak + ); + #[cfg(target_has_atomic = "64")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_i64, + AtomicI64, + i64, + compare_exchange + ); + #[cfg(target_has_atomic = "64")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_weak_i64, + AtomicI64, + i64, + compare_exchange_weak + ); + #[cfg(target_has_atomic = "64")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_u64, + AtomicU64, + u64, + compare_exchange + ); + #[cfg(target_has_atomic = "64")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_weak_u64, + AtomicU64, + u64, + compare_exchange_weak + ); + #[cfg(target_has_atomic = "128")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_i128, + AtomicI128, + i128, + compare_exchange + ); + #[cfg(target_has_atomic = "128")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_weak_i128, + AtomicI128, + i128, + compare_exchange_weak + ); + #[cfg(target_has_atomic = "128")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_u128, + AtomicU128, + u128, + compare_exchange + ); + #[cfg(target_has_atomic = "128")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_weak_u128, + AtomicU128, + u128, + compare_exchange_weak + ); + #[cfg(target_has_atomic = "ptr")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_isize, + AtomicIsize, + isize, + compare_exchange + ); + #[cfg(target_has_atomic = "ptr")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_weak_isize, + AtomicIsize, + isize, + compare_exchange_weak + ); + #[cfg(target_has_atomic = "ptr")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_usize, + AtomicUsize, + usize, + compare_exchange + ); + #[cfg(target_has_atomic = "ptr")] + safe_compare_exchange_harness!( + harness_safe_compare_exchange_weak_usize, + AtomicUsize, + usize, + compare_exchange_weak + ); + + // Callback-taking methods use ordinary proofs: a callback may legally write to + // captured state or other memory, so `modifies(self)` is not a valid general + // contract for these APIs. Keep the former ordering precondition explicit in + // each harness instead. The callbacks below mutate captured state to exercise + // this case; the proofs cover these callbacks, not every possible FnMut. + // As with the other harnesses, this is single-threaded verification. + macro_rules! safe_update_harness { + ($name:ident, $atomic:ty, $value:ty, $method:ident) => { + #[kani::proof] + #[kani::unwind(2)] + pub fn $name() { + let initial: $value = kani::any(); + let storage = <$atomic>::new(initial); + let new: $value = kani::any(); + let should_update: bool = kani::any(); + let set_order = any_ordering(); + let fetch_order = any_ordering(); + kani::assume(matches!(fetch_order, Relaxed | Acquire | SeqCst)); + let mut calls = 0u32; + let result = storage.$method(set_order, fetch_order, |_| { + calls += 1; + if should_update { Some(new) } else { None } + }); + assert!(calls > 0); + assert_eq!(result, if should_update { Ok(initial) } else { Err(initial) }); + assert_eq!(storage.load(Relaxed), if should_update { new } else { initial }); + kani::cover(result.is_ok(), "safe atomic update: Some branch completed"); + kani::cover(result.is_err(), "safe atomic update: None branch completed"); + kani::cover(true, "safe atomic update: reached after call"); + } + }; + } + + #[cfg(target_has_atomic = "8")] + safe_update_harness!(harness_safe_fetch_update_bool, AtomicBool, bool, fetch_update); + #[cfg(target_has_atomic = "8")] + safe_update_harness!(harness_safe_try_update_bool, AtomicBool, bool, try_update); + #[cfg(target_has_atomic = "ptr")] + #[kani::proof] + #[kani::unwind(2)] + pub fn harness_safe_fetch_update_ptr() { + let initial = kani::any::() as *mut u8; + let storage = AtomicPtr::::new(initial); + let new = kani::any::() as *mut u8; + let should_update: bool = kani::any(); + let set_order = any_ordering(); + let fetch_order = any_ordering(); + kani::assume(matches!(fetch_order, Relaxed | Acquire | SeqCst)); + let mut calls = 0u32; + let result = storage.fetch_update(set_order, fetch_order, |_| { + calls += 1; + if should_update { Some(new) } else { None } + }); + assert!(calls > 0); + assert_eq!(result, if should_update { Ok(initial) } else { Err(initial) }); + assert_eq!(storage.load(Relaxed), if should_update { new } else { initial }); + kani::cover(result.is_ok(), "safe pointer fetch-update: Some branch completed"); + kani::cover(result.is_err(), "safe pointer fetch-update: None branch completed"); + kani::cover(true, "safe atomic pointer fetch-update: reached after call"); + } + #[cfg(target_has_atomic = "ptr")] + #[kani::proof] + #[kani::unwind(2)] + pub fn harness_safe_try_update_ptr() { + let initial = kani::any::() as *mut u8; + let storage = AtomicPtr::::new(initial); + let new = kani::any::() as *mut u8; + let should_update: bool = kani::any(); + let set_order = any_ordering(); + let fetch_order = any_ordering(); + kani::assume(matches!(fetch_order, Relaxed | Acquire | SeqCst)); + let mut calls = 0u32; + let result = storage.try_update(set_order, fetch_order, |_| { + calls += 1; + if should_update { Some(new) } else { None } + }); + assert!(calls > 0); + assert_eq!(result, if should_update { Ok(initial) } else { Err(initial) }); + assert_eq!(storage.load(Relaxed), if should_update { new } else { initial }); + kani::cover(result.is_ok(), "safe pointer try-update: Some branch completed"); + kani::cover(result.is_err(), "safe pointer try-update: None branch completed"); + kani::cover(true, "safe atomic pointer try-update: reached after call"); + } + #[cfg(target_has_atomic = "8")] + safe_update_harness!(harness_safe_fetch_update_i8, AtomicI8, i8, fetch_update); + #[cfg(target_has_atomic = "8")] + safe_update_harness!(harness_safe_try_update_i8, AtomicI8, i8, try_update); + #[cfg(target_has_atomic = "8")] + safe_update_harness!(harness_safe_fetch_update_u8, AtomicU8, u8, fetch_update); + #[cfg(target_has_atomic = "8")] + safe_update_harness!(harness_safe_try_update_u8, AtomicU8, u8, try_update); + #[cfg(target_has_atomic = "16")] + safe_update_harness!(harness_safe_fetch_update_i16, AtomicI16, i16, fetch_update); + #[cfg(target_has_atomic = "16")] + safe_update_harness!(harness_safe_try_update_i16, AtomicI16, i16, try_update); + #[cfg(target_has_atomic = "16")] + safe_update_harness!(harness_safe_fetch_update_u16, AtomicU16, u16, fetch_update); + #[cfg(target_has_atomic = "16")] + safe_update_harness!(harness_safe_try_update_u16, AtomicU16, u16, try_update); + #[cfg(target_has_atomic = "32")] + safe_update_harness!(harness_safe_fetch_update_i32, AtomicI32, i32, fetch_update); + #[cfg(target_has_atomic = "32")] + safe_update_harness!(harness_safe_try_update_i32, AtomicI32, i32, try_update); + #[cfg(target_has_atomic = "32")] + safe_update_harness!(harness_safe_fetch_update_u32, AtomicU32, u32, fetch_update); + #[cfg(target_has_atomic = "32")] + safe_update_harness!(harness_safe_try_update_u32, AtomicU32, u32, try_update); + #[cfg(target_has_atomic = "64")] + safe_update_harness!(harness_safe_fetch_update_i64, AtomicI64, i64, fetch_update); + #[cfg(target_has_atomic = "64")] + safe_update_harness!(harness_safe_try_update_i64, AtomicI64, i64, try_update); + #[cfg(target_has_atomic = "64")] + safe_update_harness!(harness_safe_fetch_update_u64, AtomicU64, u64, fetch_update); + #[cfg(target_has_atomic = "64")] + safe_update_harness!(harness_safe_try_update_u64, AtomicU64, u64, try_update); + #[cfg(target_has_atomic = "128")] + safe_update_harness!(harness_safe_fetch_update_i128, AtomicI128, i128, fetch_update); + #[cfg(target_has_atomic = "128")] + safe_update_harness!(harness_safe_try_update_i128, AtomicI128, i128, try_update); + #[cfg(target_has_atomic = "128")] + safe_update_harness!(harness_safe_fetch_update_u128, AtomicU128, u128, fetch_update); + #[cfg(target_has_atomic = "128")] + safe_update_harness!(harness_safe_try_update_u128, AtomicU128, u128, try_update); + #[cfg(target_has_atomic = "ptr")] + safe_update_harness!(harness_safe_fetch_update_isize, AtomicIsize, isize, fetch_update); + #[cfg(target_has_atomic = "ptr")] + safe_update_harness!(harness_safe_try_update_isize, AtomicIsize, isize, try_update); + #[cfg(target_has_atomic = "ptr")] + safe_update_harness!(harness_safe_fetch_update_usize, AtomicUsize, usize, fetch_update); + #[cfg(target_has_atomic = "ptr")] + safe_update_harness!(harness_safe_try_update_usize, AtomicUsize, usize, try_update); + + // Kani does not infer a finite bound for this CAS retry loop automatically. + // An unwind bound of 2 is sufficient for this single-threaded harness under + // Kani's current atomic intrinsic model. + macro_rules! safe_update_loop_harness { + ($name:ident, $atomic:ty, $value:ty) => { + #[kani::proof] + #[kani::unwind(2)] + pub fn $name() { + let initial: $value = kani::any(); + let storage = <$atomic>::new(initial); + let new: $value = kani::any(); + let set_order = any_ordering(); + let fetch_order = any_ordering(); + kani::assume(matches!(fetch_order, Relaxed | Acquire | SeqCst)); + let mut calls = 0u32; + let previous = storage.update(set_order, fetch_order, |_| { + calls += 1; + new + }); + assert!(calls > 0); + assert_eq!(previous, initial); + assert_eq!(storage.load(Relaxed), new); + kani::cover(true, "safe atomic update: reached after call"); + } + }; + } + #[cfg(target_has_atomic = "8")] + safe_update_loop_harness!(harness_safe_update_bool, AtomicBool, bool); + #[cfg(target_has_atomic = "8")] + safe_update_loop_harness!(harness_safe_update_i8, AtomicI8, i8); + #[cfg(target_has_atomic = "8")] + safe_update_loop_harness!(harness_safe_update_u8, AtomicU8, u8); + #[cfg(target_has_atomic = "16")] + safe_update_loop_harness!(harness_safe_update_i16, AtomicI16, i16); + #[cfg(target_has_atomic = "16")] + safe_update_loop_harness!(harness_safe_update_u16, AtomicU16, u16); + #[cfg(target_has_atomic = "32")] + safe_update_loop_harness!(harness_safe_update_i32, AtomicI32, i32); + #[cfg(target_has_atomic = "32")] + safe_update_loop_harness!(harness_safe_update_u32, AtomicU32, u32); + #[cfg(target_has_atomic = "64")] + safe_update_loop_harness!(harness_safe_update_i64, AtomicI64, i64); + #[cfg(target_has_atomic = "64")] + safe_update_loop_harness!(harness_safe_update_u64, AtomicU64, u64); + #[cfg(target_has_atomic = "128")] + safe_update_loop_harness!(harness_safe_update_i128, AtomicI128, i128); + #[cfg(target_has_atomic = "128")] + safe_update_loop_harness!(harness_safe_update_u128, AtomicU128, u128); + #[cfg(target_has_atomic = "ptr")] + safe_update_loop_harness!(harness_safe_update_isize, AtomicIsize, isize); + #[cfg(target_has_atomic = "ptr")] + safe_update_loop_harness!(harness_safe_update_usize, AtomicUsize, usize); + + #[cfg(target_has_atomic = "ptr")] + #[kani::proof] + #[kani::unwind(2)] + pub fn harness_safe_update_ptr() { + let initial = kani::any::() as *mut u8; + let storage = AtomicPtr::::new(initial); + let new = kani::any::() as *mut u8; + let set_order = any_ordering(); + let fetch_order = any_ordering(); + kani::assume(matches!(fetch_order, Relaxed | Acquire | SeqCst)); + let mut calls = 0u32; + let previous = storage.update(set_order, fetch_order, |_| { + calls += 1; + new + }); + assert!(calls > 0); + assert_eq!(previous, initial); + assert_eq!(storage.load(Relaxed), new); + kani::cover(true, "safe atomic pointer update: reached after call"); + } + + #[cfg(target_has_atomic_load_store = "8")] + #[kani::proof] + #[kani::should_panic] + pub fn harness_safe_load_panics_on_release() { + let storage = AtomicBool::new(false); + let _ = storage.load(Release); + } + + #[cfg(target_has_atomic_load_store = "8")] + #[kani::proof] + #[kani::should_panic] + pub fn harness_safe_load_panics_on_acqrel() { + let storage = AtomicBool::new(false); + let _ = storage.load(AcqRel); + } + + #[cfg(target_has_atomic_load_store = "8")] + #[kani::proof] + #[kani::should_panic] + pub fn harness_safe_store_panics_on_acquire() { + let storage = AtomicBool::new(false); + storage.store(true, Acquire); + } + + #[cfg(target_has_atomic_load_store = "8")] + #[kani::proof] + #[kani::should_panic] + pub fn harness_safe_store_panics_on_acqrel() { + let storage = AtomicBool::new(false); + storage.store(true, AcqRel); + } + + macro_rules! safe_compare_exchange_panics_harness { + ($name:ident, $method:ident, $failure:expr) => { + #[cfg(target_has_atomic = "8")] + #[kani::proof] + #[kani::should_panic] + pub fn $name() { + let storage = AtomicBool::new(false); + let _ = storage.$method(false, true, Relaxed, $failure); + } + }; + } + + safe_compare_exchange_panics_harness!( + harness_safe_compare_exchange_panics_on_release, + compare_exchange, + Release + ); + safe_compare_exchange_panics_harness!( + harness_safe_compare_exchange_panics_on_acqrel, + compare_exchange, + AcqRel + ); + safe_compare_exchange_panics_harness!( + harness_safe_compare_exchange_weak_panics_on_release, + compare_exchange_weak, + Release + ); + safe_compare_exchange_panics_harness!( + harness_safe_compare_exchange_weak_panics_on_acqrel, + compare_exchange_weak, + AcqRel + ); + + macro_rules! safe_update_panics_harness { + ($name:ident, $method:ident, $failure:expr, $closure:expr) => { + #[cfg(target_has_atomic = "8")] + #[kani::proof] + #[kani::should_panic] + pub fn $name() { + let storage = AtomicBool::new(false); + let _ = storage.$method(Relaxed, $failure, $closure); + } + }; + } + + safe_update_panics_harness!( + harness_safe_fetch_update_panics_on_release, + fetch_update, + Release, + |_| None + ); + safe_update_panics_harness!( + harness_safe_fetch_update_panics_on_acqrel, + fetch_update, + AcqRel, + |_| None + ); + safe_update_panics_harness!( + harness_safe_try_update_panics_on_release, + try_update, + Release, + |_| None + ); + safe_update_panics_harness!( + harness_safe_try_update_panics_on_acqrel, + try_update, + AcqRel, + |_| None + ); + safe_update_panics_harness!(harness_safe_update_panics_on_release, update, Release, |x| x); + safe_update_panics_harness!(harness_safe_update_panics_on_acqrel, update, AcqRel, |x| x); +} diff --git a/verifast-proofs/core/sync/atomic.rs/original/atomic_load_volatile.md b/verifast-proofs/core/sync/atomic.rs/original/atomic_load_volatile.md new file mode 100644 index 0000000000000..a2cc3275f41a8 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/original/atomic_load_volatile.md @@ -0,0 +1,30 @@ +Volatile operations are intended to act on I/O memory. As such, they are considered externally +observable events (just like syscalls, but less opaque), and are guaranteed to not be elided or +reordered by the compiler across other externally observable events. With this in mind, there +are two cases of usage that need to be distinguished: + +- When a volatile operation is used for memory inside an [allocation], it behaves exactly + like [`load`][Self::load], except for the additional guarantee that it won't be elided or + reordered across other externally observable events (see above). This implies that the + operation will actually access memory and not e.g. be lowered to reusing data from a + previous load. Other than that, all the usual rules for memory accesses apply (including + provenance). + +- Volatile operations, however, may also be used to access memory that is _outside_ of any Rust + allocation. In this use-case, the pointer does *not* have to be [valid] for reads. This is + typically used for CPU and peripheral registers that must be accessed via an I/O memory mapping, + most commonly at fixed addresses reserved by the hardware. These often have special semantics + associated to their manipulation, and cannot be used as general purpose memory. Here, any address + value is possible, including 0 and [`usize::MAX`], so long as the semantics of such a read are + well-defined by the target hardware. The provenance of the pointer is irrelevant, and it can be + created with [`without_provenance`][crate::ptr::without_provenance]. The access is allowed to + trap, which must immediately abort the process. It can also cause other side-effects, but those + must not affect Rust-allocated memory in any way. + +In both cases, the access is also considered atomic with the given `order`. This allows +synchronization with other threads or devices that share memory with this program. + +When invoked during const evaluation, this behaves like a regular atomic load. In +particular, such reads must always follow the first of the two cases above. + +[allocation]: crate::ptr#allocated-object diff --git a/verifast-proofs/core/sync/atomic.rs/original/atomic_store_volatile.md b/verifast-proofs/core/sync/atomic.rs/original/atomic_store_volatile.md new file mode 100644 index 0000000000000..e72622dea86bb --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/original/atomic_store_volatile.md @@ -0,0 +1,29 @@ +Volatile operations are intended to act on I/O memory. As such, they are considered externally +observable events (just like syscalls), and are guaranteed to not be elided or reordered by the +compiler across other externally observable events. With this in mind, there are two cases of +usage that need to be distinguished: + +- When a volatile operation is used for memory inside an [allocation], it behaves exactly like + [`store`][Self::store], except for the additional guarantee that it won't be elided or reordered + across other externally observable events (see above). This implies that the operation will + actually access memory and not e.g. be lowered to a register access. Other than that, all the + usual rules for memory accesses apply (including provenance). + +- Volatile operations, however, may also be used to access memory that is _outside_ of any Rust + allocation. In this use-case, the pointer does *not* have to be [valid] for writes. This is + typically used for CPU and peripheral registers that must be accessed via an I/O memory mapping, + most commonly at fixed addresses reserved by the hardware. These often have special semantics + associated to their manipulation, and cannot be used as general purpose memory. Here, any address + value is possible, including 0 and [`usize::MAX`], so long as the semantics of such a write are + well-defined by the target hardware. The provenance of the pointer is irrelevant, and it can be + created with [`without_provenance_mut`][crate::ptr::without_provenance_mut]. The access is allowed + to trap, which must immediately abort the process. It can also cause other side-effects, but those + must not affect Rust-allocated memory in any way. + +In both cases, the access is also considered atomic with the given `order`. This allows +synchronization with other threads or devices that share memory with this program. + +When invoked during const evaluation, this behaves like a regular atomic store. In +particular, such reads must always follow the first of the two cases above. + +[allocation]: crate::ptr#allocated-object diff --git a/verifast-proofs/core/sync/atomic.rs/original/intrinsics/mod.rs b/verifast-proofs/core/sync/atomic.rs/original/intrinsics/mod.rs new file mode 100644 index 0000000000000..f74fd9e2c1fec --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/original/intrinsics/mod.rs @@ -0,0 +1,5712 @@ +//! Compiler intrinsics. +//! +//! The functions in this module are implementation details of `core` and should +//! not be used outside of the standard library. We generally provide access to +//! intrinsics via stable wrapper functions. Use these instead. +//! +//! These are the imports making intrinsics available to Rust code. The actual implementations live in the compiler. +//! Some of these intrinsics are lowered to MIR in . +//! The remaining intrinsics are implemented for the LLVM backend in +//! and , +//! and for const evaluation in . +//! +//! Intrinsics don't need a body. However, they optionally can have a body, which we call the +//! "fallback body". This will be used by codegen backends that do not have a dedicated +//! implementation of the intrinsic, making it easier to add new intrinsics for specific operations +//! without having to implement them in each codegen backend. The fallback body obviously has to be +//! a valid implementation of the documented specification of the intrinsic. In some cases, the +//! fallback body will be *equivalent* to the specification. Note that this is a strong requirement: +//! if the spec says "UB if input `x` is even", then a valid implementation can just ignore this and +//! do whatever it wants in that case; an *equivalent* implementation needs to actually check this +//! condition and trigger UB in that case (e.g. by using `hint::assert_unchecked()`). Similar, if +//! the spec says "returns `x` or `y` non-deterministically", then an *equivalent* implementation +//! must actually do non-deterministic choice and return either value (e.g. by invoking some other +//! language operation that has the same non-determinism). Intrinsics with such a fallback body that +//! is equivalent to the spec may be marked with `#[miri::intrinsic_fallback_is_spec]`; the fallback +//! body will then also be used by Miri for UB checking. When in doubt, do not use this attribute or +//! ask the Miri maintainers for advice. +//! +//! Intrinsics are, in general, language extensions. Therefore, t-lang should be involved whenever a +//! new intrinsic is exposed to stable code. However, if an intrinsic is marked +//! `#[miri::intrinsic_fallback_is_spec]` with a fallback body that only uses stable features (or if +//! such a fallback body could be written, but for one reason or another the actual fallback body is +//! different), and if it also does not make other promises that go beyond observable program +//! behavior (such as steering the optimizer in a particular direction), then an intrinsic may be +//! used without t-lang involvement. +//! +//! # Const intrinsics +//! +//! In order to make an intrinsic unstable usable at compile-time, copy the implementation from +//! to +//! +//! and make the intrinsic declaration below a `const fn`. This should be done in coordination with +//! wg-const-eval. +//! +//! If an intrinsic is supposed to be used from a `const fn` with a `rustc_const_stable` attribute, +//! `#[rustc_intrinsic_const_stable_indirect]` needs to be added to the intrinsic. Such a change +//! requires T-lang approval, because it may bake a feature into the language that cannot be +//! replicated in user code without compiler support. The same exception as above applies for +//! `#[miri::intrinsic_fallback_is_spec]` intrinsics. +//! +//! # Volatiles +//! +//! The volatile intrinsics provide operations intended to act on I/O +//! memory, which are guaranteed to not be reordered by the compiler +//! across other volatile intrinsics. See [`read_volatile`][ptr::read_volatile] +//! and [`write_volatile`][ptr::write_volatile]. +//! +//! # Atomics +//! +//! The atomic intrinsics provide common atomic operations on machine +//! words, with multiple possible memory orderings. See the +//! [atomic types][atomic] docs for details. +//! +//! # Unwinding +//! +//! Rust intrinsics may, in general, unwind. If an intrinsic can never unwind, add the +//! `#[rustc_nounwind]` attribute so that the compiler can make use of this fact. +//! +//! However, even for intrinsics that may unwind, rustc assumes that a Rust intrinsics will never +//! initiate a foreign (non-Rust) unwind, and thus for panic=abort we can always assume that these +//! intrinsics cannot unwind. + +#![unstable( + feature = "core_intrinsics", + reason = "intrinsics are unlikely to ever be stabilized, instead \ + they should be used through stabilized interfaces \ + in the rest of the standard library", + issue = "none" +)] + +use safety::{ensures, requires}; + +use crate::ffi::{VaArgSafe, VaList}; +#[cfg(kani)] +use crate::kani; +use crate::marker::{ConstParamTy, DiscriminantKind, PointeeSized, Tuple}; +use crate::num::imp::libm; +#[cfg(kani)] +use crate::ub_checks; +use crate::{mem, ptr}; + +mod bounds; +pub mod fallback; +pub mod gpu; +mod macros; +pub mod mir; +pub mod reflection; +pub mod simd; + +use macros::intrinsic_dispatch_on_type; + +// These imports are used for simplifying intra-doc links +#[allow(unused_imports)] +#[cfg(all(target_has_atomic = "8", target_has_atomic = "32", target_has_atomic = "ptr"))] +use crate::sync::atomic::{ + self, AtomicBool, AtomicI32, AtomicIsize, AtomicPtr, AtomicU32, Ordering, +}; + +/// A type for atomic ordering parameters for intrinsics. This is a separate type from +/// `atomic::Ordering` so that we can make it `ConstParamTy` and fix the values used here without a +/// risk of leaking that to stable code. +#[derive(Debug, ConstParamTy, PartialEq, Eq)] +pub enum AtomicOrdering { + // These values must match the compiler's `AtomicOrdering` defined in + // `rustc_middle/src/ty/consts/int.rs`! + /// [`Ordering::Relaxed`][`crate::sync::atomic::Ordering::Relaxed`] + Relaxed = 0, + /// [`Ordering::Release`][`crate::sync::atomic::Ordering::Release`] + Release = 1, + /// [`Ordering::Acquire`][`crate::sync::atomic::Ordering::Acquire`] + Acquire = 2, + /// [`Ordering::AcqRel`][`crate::sync::atomic::Ordering::AcqRel`] + AcqRel = 3, + /// [`Ordering::SeqCst`][`crate::sync::atomic::Ordering::SeqCst`] + SeqCst = 4, +} + +// N.B., these intrinsics take raw pointers because they mutate aliased +// memory, which is not valid for either `&` or `&mut`. + +/// Stores a value if the current value is the same as the `old` value, +/// with the returned `T` being the previous value and the returned `bool` being +/// whether the exchange was successful. +/// `T` must be an integer or pointer type. +/// +/// # Safety +/// +/// * If `T` is an integer type, this is equivalent to [`Atomic::from_ptr`] followed by [`Atomic::compare_exchange`]. +/// Refer to the documentation of [`Atomic::from_ptr`] for safety requirements. +/// +/// * If `T` is a pointer type, this is equivalent to [`AtomicPtr

::from_ptr`] followed by [`AtomicPtr

::compare_exchange`], +/// where `P` is the pointee type of the pointer. +/// Refer to the documentation of [`AtomicPtr

::from_ptr`] for safety requirements. +/// +/// The stabilized version of this intrinsic is available on the +/// [`atomic`] types via the `compare_exchange` method. +/// For example, [`AtomicBool::compare_exchange`]. +/// +/// [`Atomic::from_ptr`]: AtomicI32::from_ptr +/// [`Atomic::compare_exchange`]: AtomicI32::compare_exchange +/// [`AtomicPtr

::from_ptr`]: AtomicPtr::from_ptr +/// [`AtomicPtr

::compare_exchange`]: AtomicPtr::compare_exchange +#[rustc_intrinsic] +#[rustc_nounwind] +pub const unsafe fn atomic_cxchg< + T: Copy, + const ORD_SUCC: AtomicOrdering, + const ORD_FAIL: AtomicOrdering, +>( + dst: *mut T, + old: T, + src: T, +) -> (T, bool); + +/// Stores a value if the current value is the same as the `old` value, +/// with the returned `T` being the previous value and the returned `bool` being +/// whether the exchange was successful. +/// `T` must be an integer or pointer type. The comparison may spuriously fail. +/// +/// # Safety +/// +/// * If `T` is an integer type, this is equivalent to [`Atomic::from_ptr`] followed by [`Atomic::compare_exchange_weak`]. +/// Refer to the documentation of [`Atomic::from_ptr`] for safety requirements. +/// +/// * If `T` is a pointer type, this is equivalent to [`AtomicPtr

::from_ptr`] followed by [`AtomicPtr

::compare_exchange_weak`], +/// where `P` is the pointee type of the pointer. +/// Refer to the documentation of [`AtomicPtr

::from_ptr`] for safety requirements. +/// +/// The stabilized version of this intrinsic is available on the +/// [`atomic`] types via the `compare_exchange_weak` method. +/// For example, [`AtomicBool::compare_exchange_weak`]. +/// +/// [`Atomic::from_ptr`]: AtomicI32::from_ptr +/// [`Atomic::compare_exchange_weak`]: AtomicI32::compare_exchange_weak +/// [`AtomicPtr

::from_ptr`]: AtomicPtr::from_ptr +/// [`AtomicPtr

::compare_exchange_weak`]: AtomicPtr::compare_exchange_weak +#[rustc_intrinsic] +#[rustc_nounwind] +pub const unsafe fn atomic_cxchgweak< + T: Copy, + const ORD_SUCC: AtomicOrdering, + const ORD_FAIL: AtomicOrdering, +>( + _dst: *mut T, + _old: T, + _src: T, +) -> (T, bool); + +/// Loads the current value of the pointer. +/// `T` must be an integer or pointer type. +/// +/// # Safety +/// +/// * If `VOLATILE` is `true`, this is equivalent to [`Atomic::load_volatile`]. +/// Refer to the documentation of that method for safety requirements. +/// +/// * If `VOLATILE` is `false`, this is equivalent to [`Atomic::from_ptr`] followed +/// by [`Atomic::load`]. Refer to the documentation of [`Atomic::from_ptr`] for safety requirements. +/// +/// The stabilized version of this intrinsic is available on the +/// [`atomic`] types via the `load` method. For example, [`AtomicBool::load`]. +/// +/// [`Atomic::load_volatile`]: AtomicI32::load_volatile +/// [`Atomic::from_ptr`]: AtomicI32::from_ptr +/// [`Atomic::load`]: AtomicI32::load +#[rustc_intrinsic] +#[rustc_nounwind] +pub const unsafe fn atomic_load( + src: *const T, +) -> T; + +/// Stores the value at the specified memory location. +/// `T` must be an integer or pointer type. +/// +/// # Safety +/// +/// * If `VOLATILE` is `true`, this is equivalent to [`Atomic::store_volatile`]. +/// Refer to the documentation of that method for safety requirements. +/// +/// * If `VOLATILE` is `false`, this is equivalent to [`Atomic::from_ptr`] followed +/// by [`Atomic::store`]. Refer to the documentation of [`Atomic::from_ptr`] for safety requirements. +/// +/// The stabilized version of this intrinsic is available on the +/// [`atomic`] types via the `store` method. For example, [`AtomicBool::store`]. +/// +/// [`Atomic::store_volatile`]: AtomicI32::store_volatile +/// [`Atomic::from_ptr`]: AtomicI32::from_ptr +/// [`Atomic::store`]: AtomicI32::store +#[rustc_intrinsic] +#[rustc_nounwind] +pub const unsafe fn atomic_store( + dst: *mut T, + val: T, +); + +/// Stores the value at the specified memory location, returning the old value. +/// `T` must be an integer or pointer type. +/// +/// # Safety +/// +/// * If `T` is an integer type, this is equivalent to [`Atomic::from_ptr`] followed by [`Atomic::swap`]. +/// Refer to the documentation of [`Atomic::from_ptr`] for safety requirements. +/// +/// * If `T` is a pointer type, this is equivalent to [`AtomicPtr

::from_ptr`] followed by [`AtomicPtr

::swap`], +/// where `P` is the pointee type of the pointer. +/// Refer to the documentation of [`AtomicPtr

::from_ptr`] for safety requirements. +/// +/// The stabilized version of this intrinsic is available on the +/// [`atomic`] types via the `swap` method. For example, [`AtomicBool::swap`]. +/// +/// [`Atomic::from_ptr`]: AtomicI32::from_ptr +/// [`Atomic::swap`]: AtomicI32::swap +/// [`AtomicPtr

::from_ptr`]: AtomicPtr::from_ptr +/// [`AtomicPtr

::swap`]: AtomicPtr::swap +#[rustc_intrinsic] +#[rustc_nounwind] +pub const unsafe fn atomic_xchg(dst: *mut T, src: T) -> T; + +/// Adds to the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// `U` must be the same as `T` if that is an integer type, or `usize` if `T` is a pointer type. +/// +/// # Safety +/// +/// * If `T` is an integer type, this is equivalent to [`Atomic::from_ptr`] followed by [`Atomic::fetch_add`]. +/// Refer to the documentation of [`Atomic::from_ptr`] for safety requirements. +/// +/// * If `T` is a pointer type, this is equivalent to [`AtomicPtr

::from_ptr`] followed by [`AtomicPtr

::fetch_byte_add`], +/// where `P` is the pointee type of the pointer. +/// Refer to the documentation of [`AtomicPtr

::from_ptr`] for safety requirements. +/// +/// The stabilized version of this intrinsic is available on the +/// [`atomic`] types via the `fetch_add` method. For example, [`AtomicIsize::fetch_add`]. +/// +/// [`Atomic::from_ptr`]: AtomicI32::from_ptr +/// [`Atomic::fetch_add`]: AtomicI32::fetch_add +/// [`AtomicPtr

::from_ptr`]: AtomicPtr::from_ptr +/// [`AtomicPtr

::fetch_byte_add`]: AtomicPtr::fetch_byte_add +#[rustc_intrinsic] +#[rustc_nounwind] +pub const unsafe fn atomic_xadd( + dst: *mut T, + src: U, +) -> T; + +/// Subtract from the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// `U` must be the same as `T` if that is an integer type, or `usize` if `T` is a pointer type. +/// +/// # Safety +/// +/// * If `T` is an integer type, this is equivalent to [`Atomic::from_ptr`] followed by [`Atomic::fetch_sub`]. +/// Refer to the documentation of [`Atomic::from_ptr`] for safety requirements. +/// +/// * If `T` is a pointer type, this is equivalent to [`AtomicPtr

::from_ptr`] followed by [`AtomicPtr

::fetch_byte_sub`], +/// where `P` is the pointee type of the pointer. +/// Refer to the documentation of [`AtomicPtr

::from_ptr`] for safety requirements. +/// +/// The stabilized version of this intrinsic is available on the +/// [`atomic`] types via the `fetch_sub` method. For example, [`AtomicIsize::fetch_sub`]. +/// +/// [`Atomic::from_ptr`]: AtomicI32::from_ptr +/// [`Atomic::fetch_sub`]: AtomicI32::fetch_sub +/// [`AtomicPtr

::from_ptr`]: AtomicPtr::from_ptr +/// [`AtomicPtr

::fetch_byte_sub`]: AtomicPtr::fetch_byte_sub +#[rustc_intrinsic] +#[rustc_nounwind] +pub const unsafe fn atomic_xsub( + dst: *mut T, + src: U, +) -> T; + +/// Bitwise and with the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// `U` must be the same as `T` if that is an integer type, or `usize` if `T` is a pointer type. +/// +/// # Safety +/// +/// * If `T` is an integer type, this is equivalent to [`Atomic::from_ptr`] followed by [`Atomic::fetch_and`]. +/// Refer to the documentation of [`Atomic::from_ptr`] for safety requirements. +/// +/// * If `T` is a pointer type, this is equivalent to [`AtomicPtr

::from_ptr`] followed by [`AtomicPtr

::fetch_and`], +/// where `P` is the pointee type of the pointer. +/// Refer to the documentation of [`AtomicPtr

::from_ptr`] for safety requirements. +/// +/// The stabilized version of this intrinsic is available on the +/// [`atomic`] types via the `fetch_and` method. For example, [`AtomicBool::fetch_and`]. +/// +/// [`Atomic::from_ptr`]: AtomicI32::from_ptr +/// [`Atomic::fetch_and`]: AtomicI32::fetch_and +/// [`AtomicPtr

::from_ptr`]: AtomicPtr::from_ptr +/// [`AtomicPtr

::fetch_and`]: AtomicPtr::fetch_and +#[rustc_intrinsic] +#[rustc_nounwind] +pub const unsafe fn atomic_and( + dst: *mut T, + src: U, +) -> T; + +/// Bitwise nand with the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// `U` must be the same as `T` if that is an integer type, or `usize` if `T` is a pointer type. +/// +/// # Safety +/// +/// This is equivalent to [`Atomic::from_ptr`] followed by [`Atomic::fetch_nand`]. +/// Refer to the documentation of [`Atomic::from_ptr`] for safety requirements. +/// +/// The stabilized version of this intrinsic is available on the +/// [`atomic`] types via the `fetch_nand` method. For example, [`AtomicBool::fetch_nand`]. +/// +/// [`Atomic::from_ptr`]: AtomicI32::from_ptr +/// [`Atomic::fetch_nand`]: AtomicI32::fetch_nand +#[rustc_intrinsic] +#[rustc_nounwind] +pub const unsafe fn atomic_nand( + dst: *mut T, + src: U, +) -> T; + +/// Bitwise or with the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// `U` must be the same as `T` if that is an integer type, or `usize` if `T` is a pointer type. +/// +/// # Safety +/// +/// * If `T` is an integer type, this is equivalent to [`Atomic::from_ptr`] followed by [`Atomic::fetch_or`]. +/// Refer to the documentation of [`Atomic::from_ptr`] for safety requirements. +/// +/// * If `T` is a pointer type, this is equivalent to [`AtomicPtr

::from_ptr`] followed by [`AtomicPtr

::fetch_or`], +/// where `P` is the pointee type of the pointer. +/// Refer to the documentation of [`AtomicPtr

::from_ptr`] for safety requirements. +/// +/// The stabilized version of this intrinsic is available on the +/// [`atomic`] types via the `fetch_or` method. For example, [`AtomicBool::fetch_or`]. +/// +/// [`Atomic::from_ptr`]: AtomicI32::from_ptr +/// [`Atomic::fetch_or`]: AtomicI32::fetch_or +/// [`AtomicPtr

::from_ptr`]: AtomicPtr::from_ptr +/// [`AtomicPtr

::fetch_or`]: AtomicPtr::fetch_or +#[rustc_intrinsic] +#[rustc_nounwind] +pub const unsafe fn atomic_or( + dst: *mut T, + src: U, +) -> T; + +/// Bitwise xor with the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// `U` must be the same as `T` if that is an integer type, or `usize` if `T` is a pointer type. +/// +/// # Safety +/// +/// * If `T` is an integer type, this is equivalent to [`Atomic::from_ptr`] followed by [`Atomic::fetch_xor`]. +/// Refer to the documentation of [`Atomic::from_ptr`] for safety requirements. +/// +/// * If `T` is a pointer type, this is equivalent to [`AtomicPtr

::from_ptr`] followed by [`AtomicPtr

::fetch_xor`], +/// where `P` is the pointee type of the pointer. +/// Refer to the documentation of [`AtomicPtr

::from_ptr`] for safety requirements. +/// +/// The stabilized version of this intrinsic is available on the +/// [`atomic`] types via the `fetch_xor` method. For example, [`AtomicBool::fetch_xor`]. +/// +/// [`Atomic::from_ptr`]: AtomicI32::from_ptr +/// [`Atomic::fetch_xor`]: AtomicI32::fetch_xor +/// [`AtomicPtr

::from_ptr`]: AtomicPtr::from_ptr +/// [`AtomicPtr

::fetch_xor`]: AtomicPtr::fetch_xor +#[rustc_intrinsic] +#[rustc_nounwind] +pub const unsafe fn atomic_xor( + dst: *mut T, + src: U, +) -> T; + +/// Maximum with the current value using a signed comparison. +/// `T` must be a signed integer type. +/// +/// # Safety +/// +/// This is equivalent to [`Atomic::from_ptr`] followed by [`Atomic::fetch_max`]. +/// Refer to the documentation of [`Atomic::from_ptr`] for safety requirements. +/// +/// The stabilized version of this intrinsic is available on the +/// [`atomic`] signed integer types via the `fetch_max` method. For example, [`AtomicI32::fetch_max`]. +/// +/// [`Atomic::from_ptr`]: AtomicI32::from_ptr +/// [`Atomic::fetch_max`]: AtomicI32::fetch_max +#[rustc_intrinsic] +#[rustc_nounwind] +pub const unsafe fn atomic_max(dst: *mut T, src: T) -> T; + +/// Minimum with the current value using a signed comparison. +/// `T` must be a signed integer type. +/// +/// # Safety +/// +/// This is equivalent to [`Atomic::from_ptr`] followed by [`Atomic::fetch_min`]. +/// Refer to the documentation of [`Atomic::from_ptr`] for safety requirements. +/// +/// The stabilized version of this intrinsic is available on the +/// [`atomic`] signed integer types via the `fetch_min` method. For example, [`AtomicI32::fetch_min`]. +/// +/// [`Atomic::from_ptr`]: AtomicI32::from_ptr +/// [`Atomic::fetch_min`]: AtomicI32::fetch_min +#[rustc_intrinsic] +#[rustc_nounwind] +pub const unsafe fn atomic_min(dst: *mut T, src: T) -> T; + +/// Minimum with the current value using an unsigned comparison. +/// `T` must be an unsigned integer type. +/// +/// # Safety +/// +/// This is equivalent to [`Atomic::from_ptr`] followed by [`Atomic::fetch_min`]. +/// Refer to the documentation of [`Atomic::from_ptr`] for safety requirements. +/// +/// The stabilized version of this intrinsic is available on the +/// [`atomic`] unsigned integer types via the `fetch_min` method. For example, [`AtomicU32::fetch_min`]. +/// +/// [`Atomic::from_ptr`]: AtomicU32::from_ptr +/// [`Atomic::fetch_min`]: AtomicU32::fetch_min +#[rustc_intrinsic] +#[rustc_nounwind] +pub const unsafe fn atomic_umin(dst: *mut T, src: T) -> T; + +/// Maximum with the current value using an unsigned comparison. +/// `T` must be an unsigned integer type. +/// +/// # Safety +/// +/// This is equivalent to [`Atomic::from_ptr`] followed by [`Atomic::fetch_max`]. +/// Refer to the documentation of [`Atomic::from_ptr`] for safety requirements. +/// +/// The stabilized version of this intrinsic is available on the +/// [`atomic`] unsigned integer types via the `fetch_max` method. For example, [`AtomicU32::fetch_max`]. +/// +/// [`Atomic::from_ptr`]: AtomicU32::from_ptr +/// [`Atomic::fetch_max`]: AtomicU32::fetch_max +#[rustc_intrinsic] +#[rustc_nounwind] +pub const unsafe fn atomic_umax(dst: *mut T, src: T) -> T; + +/// An atomic fence. +/// +/// The stabilized version of this intrinsic is available in +/// [`atomic::fence`]. +#[rustc_intrinsic] +#[rustc_nounwind] +pub const unsafe fn atomic_fence(); + +/// An atomic fence for synchronization within a single thread. +/// +/// The stabilized version of this intrinsic is available in +/// [`atomic::compiler_fence`]. +#[rustc_intrinsic] +#[rustc_nounwind] +pub const unsafe fn atomic_singlethreadfence(); + +/// The `prefetch` intrinsic is a hint to the code generator to insert a prefetch instruction +/// for the given address if supported; otherwise, it is a no-op. +/// Prefetches have no effect on the behavior of the program but can change its performance +/// characteristics. +/// +/// The `LOCALITY` argument is a temporal locality specifier ranging from (0) - no locality, +/// to (3) - extremely local keep in cache. +/// +/// This intrinsic does not have a stable counterpart. +#[rustc_intrinsic] +#[rustc_nounwind] +#[miri::intrinsic_fallback_is_spec] +pub const fn prefetch_read_data(data: *const T) { + // This operation is a no-op, unless it is overridden by the backend. + let _ = data; +} + +/// The `prefetch` intrinsic is a hint to the code generator to insert a prefetch instruction +/// for the given address if supported; otherwise, it is a no-op. +/// Prefetches have no effect on the behavior of the program but can change its performance +/// characteristics. +/// +/// The `LOCALITY` argument is a temporal locality specifier ranging from (0) - no locality, +/// to (3) - extremely local keep in cache. +/// +/// This intrinsic does not have a stable counterpart. +#[rustc_intrinsic] +#[rustc_nounwind] +#[miri::intrinsic_fallback_is_spec] +pub const fn prefetch_write_data(data: *const T) { + // This operation is a no-op, unless it is overridden by the backend. + let _ = data; +} + +/// The `prefetch` intrinsic is a hint to the code generator to insert a prefetch instruction +/// for the given address if supported; otherwise, it is a no-op. +/// Prefetches have no effect on the behavior of the program but can change its performance +/// characteristics. +/// +/// The `LOCALITY` argument is a temporal locality specifier ranging from (0) - no locality, +/// to (3) - extremely local keep in cache. +/// +/// This intrinsic does not have a stable counterpart. +#[rustc_intrinsic] +#[rustc_nounwind] +#[miri::intrinsic_fallback_is_spec] +pub const fn prefetch_read_instruction(data: *const T) { + // This operation is a no-op, unless it is overridden by the backend. + let _ = data; +} + +/// The `prefetch` intrinsic is a hint to the code generator to insert a prefetch instruction +/// for the given address if supported; otherwise, it is a no-op. +/// Prefetches have no effect on the behavior of the program but can change its performance +/// characteristics. +/// +/// The `LOCALITY` argument is a temporal locality specifier ranging from (0) - no locality, +/// to (3) - extremely local keep in cache. +/// +/// This intrinsic does not have a stable counterpart. +#[rustc_intrinsic] +#[rustc_nounwind] +#[miri::intrinsic_fallback_is_spec] +pub const fn prefetch_write_instruction(data: *const T) { + // This operation is a no-op, unless it is overridden by the backend. + let _ = data; +} + +/// Executes a breakpoint trap, for inspection by a debugger. +/// +/// The public version of this intrinsic is [`core::arch::breakpoint`]. +#[rustc_intrinsic] +#[rustc_nounwind] +pub fn breakpoint(); + +/// Executes a breakpoint trap, for inspection by a debugger. This is allowed to resume. +/// +/// The public version of this intrinsic is [`core::process::resumable_breakpoint`]. +#[rustc_intrinsic] +#[rustc_nounwind] +#[miri::intrinsic_fallback_is_spec] +pub const fn resumable_breakpoint() {} + +/// A container for the string arguments passed to [`codeview_annotation`]. +#[unstable(feature = "codeview_annotation", issue = "163964")] +pub trait CodeViewAnnotationArgs { + /// The string arguments to `codeview_annotation`. + const ARGS: &[&str]; +} + +/// Emits a call to [`llvm.codeview.annotation`](https://llvm.org/docs/LangRef.html#llvm-codeview-annotation-intrinsic) +/// which results in [`CodeViewAnnotationArgs::ARGS`] being written to the +/// PDB as an `S_ANNOTATION` record. +/// +/// Works only with targets that use PDB debuginfo and with the LLVM backend. +/// Is a no-op on other targets and backends. +#[rustc_intrinsic] +#[rustc_nounwind] +#[miri::intrinsic_fallback_is_spec] +pub fn codeview_annotation() { + // const block to catch any errors in `T::ARGS` + const { + let _ignore = T::ARGS; + } +} + +/// Magic intrinsic that derives its meaning from attributes +/// attached to the function. +/// +/// For example, dataflow uses this to inject static assertions so +/// that `rustc_peek(potentially_uninitialized)` would actually +/// double-check that dataflow did indeed compute that it is +/// uninitialized at that point in the control flow. +/// +/// This intrinsic should not be used outside of the compiler. +#[rustc_nounwind] +#[rustc_intrinsic] +pub fn rustc_peek(_: T) -> T; + +/// Ungracefully aborts the execution of the process. +/// +/// This is the intrinsic for directly implementing [`core::process::crash`] which, on most +/// platforms, will invoke an invalid instruction. On Unix, the process will probably terminate with +/// a signal like `SIGABRT`, `SIGILL`, `SIGTRAP`, `SIGSEGV` or `SIGBUS`. The precise behavior is not +/// guaranteed and not stable. +/// +/// [`std::process::abort`](../../std/process/fn.abort.html) is to be preferred if possible, +/// as its behavior is more user-friendly and more stable. +/// +/// Note that, unlike most intrinsics, this is safe to call; it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold any safety invariants. +/// +/// The stabilized version of this intrinsic is [`core::process::crash`]. +#[rustc_nounwind] +#[rustc_intrinsic] +pub const fn abort_immediate() -> !; + +/// Informs the optimizer that this point in the code is not reachable, +/// enabling further optimizations. +/// +/// N.B., this is very different from the `unreachable!()` macro: Unlike the +/// macro, which panics when it is executed, it is *undefined behavior* to +/// reach code marked with this function. +/// +/// The stabilized version of this intrinsic is [`core::hint::unreachable_unchecked`]. +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const unsafe fn unreachable() -> !; + +/// Informs the optimizer that a condition is always true. +/// If the condition is false, the behavior is undefined. +/// +/// No code is generated for this intrinsic, but the optimizer will try +/// to preserve it (and its condition) between passes, which may interfere +/// with optimization of surrounding code and reduce performance. It should +/// not be used if the invariant can be discovered by the optimizer on its +/// own, or if it does not enable any significant optimizations. +/// +/// The stabilized version of this intrinsic is [`core::hint::assert_unchecked`]. +#[rustc_nounwind] +#[rustc_intrinsic] +pub const unsafe fn assume(b: bool) { + if !b { + // SAFETY: the caller must guarantee the argument is never `false` + unsafe { unreachable() } + } +} + +/// Hints to the compiler that current code path is cold. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// The stabilized version of this intrinsic is [`core::hint::cold_path`]. +#[rustc_intrinsic] +#[rustc_nounwind] +#[miri::intrinsic_fallback_is_spec] +#[cold] +pub const fn cold_path() {} + +/// Hints to the compiler that branch condition is likely to be true. +/// Returns the value passed to it. +/// +/// Any use other than with `if` statements will probably not have an effect. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// This intrinsic does not have a stable counterpart. +#[rustc_nounwind] +#[inline(always)] +pub const fn likely(b: bool) -> bool { + if b { + true + } else { + cold_path(); + false + } +} + +/// Hints to the compiler that branch condition is likely to be false. +/// Returns the value passed to it. +/// +/// Any use other than with `if` statements will probably not have an effect. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// This intrinsic does not have a stable counterpart. +#[rustc_nounwind] +#[inline(always)] +pub const fn unlikely(b: bool) -> bool { + if b { + cold_path(); + true + } else { + false + } +} + +/// Returns either `true_val` or `false_val` depending on condition `b` with a +/// hint to the compiler that this condition is unlikely to be correctly +/// predicted by a CPU's branch predictor (e.g. a binary search). +/// +/// This is otherwise functionally equivalent to `if b { true_val } else { false_val }`. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// The public form of this intrinsic is [`core::hint::select_unpredictable`]. +/// However unlike the public form, the intrinsic will not drop the value that +/// is not selected. +#[rustc_const_unstable(feature = "core_intrinsics", issue = "none")] +#[rustc_intrinsic] +#[rustc_nounwind] +#[miri::intrinsic_fallback_is_spec] +#[inline] +pub const fn select_unpredictable(b: bool, true_val: T, false_val: T) -> T { + if b { + forget(false_val); + true_val + } else { + forget(true_val); + false_val + } +} + +/// A guard for unsafe functions that cannot ever be executed if `T` is uninhabited: +/// This will statically either panic, or do nothing. It does not *guarantee* to ever panic, +/// and should only be called if an assertion failure will imply language UB in the following code. +/// +/// This intrinsic does not have a stable counterpart. +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const fn assert_inhabited(); + +/// A guard for unsafe functions that cannot ever be executed if `T` does not permit +/// zero-initialization: This will statically either panic, or do nothing. It does not *guarantee* +/// to ever panic, and should only be called if an assertion failure will imply language UB in the +/// following code. +/// +/// This intrinsic does not have a stable counterpart. +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const fn assert_zero_valid(); + +/// A guard for `std::mem::uninitialized`. This will statically either panic, or do nothing. It does +/// not *guarantee* to ever panic, and should only be called if an assertion failure will imply +/// language UB in the following code. +/// +/// This intrinsic does not have a stable counterpart. +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const fn assert_mem_uninitialized_valid(); + +/// Gets a reference to a static `Location` indicating where it was called. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// Consider using [`core::panic::Location::caller`] instead. +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const fn caller_location() -> &'static crate::panic::Location<'static>; + +/// Moves a value out of scope without running drop glue. +/// +/// This exists solely for [`crate::mem::forget_unsized`]; normal `forget` uses +/// `ManuallyDrop` instead. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const fn forget(_: T); + +/// Reinterprets the bits of a value of one type as another type. +/// +/// Both types must have the same size. Compilation will fail if this is not guaranteed. +/// +/// `transmute` is semantically equivalent to a bitwise move of one type +/// into another. It copies the bits from the source value into the +/// destination value, then forgets the original. Note that source and destination +/// are passed by-value, which means if `Src` or `Dst` contain padding, that padding +/// is *not* guaranteed to be preserved by `transmute`. +/// +/// Both the argument and the result must be [valid](../../nomicon/what-unsafe-does.html) at +/// their given type. Violating this condition leads to [undefined behavior][ub]. The compiler +/// will generate code *assuming that you, the programmer, ensure that there will never be +/// undefined behavior*. It is therefore your responsibility to guarantee that every value +/// passed to `transmute` is valid at both types `Src` and `Dst`. Failing to uphold this condition +/// may lead to unexpected and unstable compilation results. This makes `transmute` **incredibly +/// unsafe**. `transmute` should be the absolute last resort. +/// +/// Because `transmute` is a by-value operation, alignment of the *transmuted values +/// themselves* is not a concern. As with any other function, the compiler already ensures +/// both `Src` and `Dst` are properly aligned. However, when transmuting values that *point +/// elsewhere* (such as pointers, references, boxes…), the caller has to ensure proper +/// alignment of the pointed-to values. +/// +/// The [nomicon](../../nomicon/transmutes.html) has additional documentation. +/// +/// [ub]: ../../reference/behavior-considered-undefined.html +/// +/// # Transmutation between pointers and integers +/// +/// Special care has to be taken when transmuting between pointers and integers, e.g. +/// transmuting between `*const ()` and `usize`. +/// +/// Transmuting *pointers to integers* in a `const` context is [undefined behavior][ub], unless +/// the pointer was originally created *from* an integer. (That includes this function +/// specifically, integer-to-pointer casts, and helpers like [`dangling`][crate::ptr::dangling], +/// but also semantically-equivalent conversions such as punning through `repr(C)` union +/// fields.) Any attempt to use the resulting value for integer operations will abort +/// const-evaluation. (And even outside `const`, such transmutation is touching on many +/// unspecified aspects of the Rust memory model and should be avoided. See below for +/// alternatives.) +/// +/// Transmuting *integers to pointers* is a largely unspecified operation. It is likely *not* +/// equivalent to an `as` cast. Doing non-zero-sized memory accesses with a pointer constructed +/// this way is currently considered undefined behavior. +/// +/// All this also applies when the integer is nested inside an array, tuple, struct, or enum. +/// However, `MaybeUninit` is not considered an integer type for the purpose of this +/// section. Transmuting `*const ()` to `MaybeUninit` is fine---but then calling +/// `assume_init()` on that result is considered as completing the pointer-to-integer transmute +/// and thus runs into the issues discussed above. +/// +/// In particular, doing a pointer-to-integer-to-pointer roundtrip via `transmute` is *not* a +/// lossless process. If you want to round-trip a pointer through an integer in a way that you +/// can get back the original pointer, you need to use `as` casts, or replace the integer type +/// by `MaybeUninit<$int>` (and never call `assume_init()`). If you are looking for a way to +/// store data of arbitrary type, also use `MaybeUninit` (that will also handle uninitialized +/// memory due to padding). If you specifically need to store something that is "either an +/// integer or a pointer", use `*mut ()`: integers can be converted to pointers and back without +/// any loss (via `as` casts or via `transmute`). +/// +/// # Examples +/// +/// There are a few things that `transmute` is really useful for. +/// +/// Turning a pointer into a function pointer. This is *not* portable to +/// machines where function pointers and data pointers have different sizes. +/// +/// ``` +/// fn foo() -> i32 { +/// 0 +/// } +/// // Crucially, we `as`-cast to a raw pointer before `transmute`ing to a function pointer. +/// // This avoids an integer-to-pointer `transmute`, which can be problematic. +/// // Transmuting between raw pointers and function pointers (i.e., two pointer types) is fine. +/// let pointer = foo as fn() -> i32 as *const (); +/// let function = unsafe { +/// std::mem::transmute::<*const (), fn() -> i32>(pointer) +/// }; +/// assert_eq!(function(), 0); +/// ``` +/// +/// Extending a lifetime, or shortening an invariant lifetime. This is +/// advanced, very unsafe Rust! +/// +/// ``` +/// struct R<'a>(&'a i32); +/// unsafe fn extend_lifetime<'b>(r: R<'b>) -> R<'static> { +/// unsafe { std::mem::transmute::, R<'static>>(r) } +/// } +/// +/// unsafe fn shorten_invariant_lifetime<'b, 'c>(r: &'b mut R<'static>) +/// -> &'b mut R<'c> { +/// unsafe { std::mem::transmute::<&'b mut R<'static>, &'b mut R<'c>>(r) } +/// } +/// ``` +/// +/// # Alternatives +/// +/// Don't despair: many uses of `transmute` can be achieved through other means. +/// Below are common applications of `transmute` which can be replaced with safer +/// constructs. +/// +/// Turning raw bytes (`[u8; SZ]`) into `u32`, `f64`, etc.: +/// +/// ``` +/// # #![allow(unnecessary_transmutes)] +/// let raw_bytes = [0x78, 0x56, 0x34, 0x12]; +/// +/// let num = unsafe { +/// std::mem::transmute::<[u8; 4], u32>(raw_bytes) +/// }; +/// +/// // use `u32::from_ne_bytes` instead +/// let num = u32::from_ne_bytes(raw_bytes); +/// // or use `u32::from_le_bytes` or `u32::from_be_bytes` to specify the endianness +/// let num = u32::from_le_bytes(raw_bytes); +/// assert_eq!(num, 0x12345678); +/// let num = u32::from_be_bytes(raw_bytes); +/// assert_eq!(num, 0x78563412); +/// ``` +/// +/// Turning a pointer into a `usize`: +/// +/// ```no_run +/// let ptr = &0; +/// let ptr_num_transmute = unsafe { +/// std::mem::transmute::<&i32, usize>(ptr) +/// }; +/// +/// // Use an `as` cast instead +/// let ptr_num_cast = ptr as *const i32 as usize; +/// ``` +/// +/// Note that using `transmute` to turn a pointer to a `usize` is (as noted above) [undefined +/// behavior][ub] in `const` contexts. Also outside of consts, this operation might not behave +/// as expected -- this is touching on many unspecified aspects of the Rust memory model. +/// Depending on what the code is doing, the following alternatives are preferable to +/// pointer-to-integer transmutation: +/// - If the code just wants to store data of arbitrary type in some buffer and needs to pick a +/// type for that buffer, it can use [`MaybeUninit`][crate::mem::MaybeUninit]. +/// - If the code actually wants to work on the address the pointer points to, it can use `as` +/// casts or [`ptr.addr()`][pointer::addr]. +/// +/// Turning a `*mut T` into a `&mut T`: +/// +/// ``` +/// let ptr: *mut i32 = &mut 0; +/// let ref_transmuted = unsafe { +/// std::mem::transmute::<*mut i32, &mut i32>(ptr) +/// }; +/// +/// // Use a reborrow instead +/// let ref_casted = unsafe { &mut *ptr }; +/// ``` +/// +/// Turning a `&mut T` into a `&mut U`: +/// +/// ``` +/// let ptr = &mut 0; +/// let val_transmuted = unsafe { +/// std::mem::transmute::<&mut i32, &mut u32>(ptr) +/// }; +/// +/// // Now, put together `as` and reborrowing - note the chaining of `as` +/// // `as` is not transitive +/// let val_casts = unsafe { &mut *(ptr as *mut i32 as *mut u32) }; +/// ``` +/// +/// Turning a `&str` into a `&[u8]`: +/// +/// ``` +/// // this is not a good way to do this. +/// let slice = unsafe { std::mem::transmute::<&str, &[u8]>("Rust") }; +/// assert_eq!(slice, &[82, 117, 115, 116]); +/// +/// // You could use `str::as_bytes` +/// let slice = "Rust".as_bytes(); +/// assert_eq!(slice, &[82, 117, 115, 116]); +/// +/// // Or, just use a byte string, if you have control over the string +/// // literal +/// assert_eq!(b"Rust", &[82, 117, 115, 116]); +/// ``` +/// +/// Turning a `Vec<&T>` into a `Vec>`. +/// +/// To transmute the inner type of the contents of a container, you must make sure to not +/// violate any of the container's invariants. For `Vec`, this means that both the size +/// *and alignment* of the inner types have to match. Other containers might rely on the +/// size of the type, alignment, or even the `TypeId`, in which case transmuting wouldn't +/// be possible at all without violating the container invariants. +/// +/// ``` +/// let store = [0, 1, 2, 3]; +/// let v_orig = store.iter().collect::>(); +/// +/// // clone the vector as we will reuse them later +/// let v_clone = v_orig.clone(); +/// +/// // Using transmute: this relies on the unspecified data layout of `Vec`, which is a +/// // bad idea and could cause Undefined Behavior. +/// // However, it is no-copy. +/// let v_transmuted = unsafe { +/// std::mem::transmute::, Vec>>(v_clone) +/// }; +/// +/// let v_clone = v_orig.clone(); +/// +/// // This is the suggested, safe way. +/// // It may copy the entire vector into a new one though, but also may not. +/// let v_collected = v_clone.into_iter() +/// .map(Some) +/// .collect::>>(); +/// +/// let v_clone = v_orig.clone(); +/// +/// // This is the proper no-copy, unsafe way of "transmuting" a `Vec`, without relying on the +/// // data layout. Instead of literally calling `transmute`, we perform a pointer cast, but +/// // in terms of converting the original inner type (`&i32`) to the new one (`Option<&i32>`), +/// // this has all the same caveats. Besides the information provided above, also consult the +/// // [`from_raw_parts`] documentation. +/// let (ptr, len, capacity) = v_clone.into_raw_parts(); +/// let v_from_raw = unsafe { +/// Vec::from_raw_parts(ptr.cast::<*mut Option<&i32>>(), len, capacity) +/// }; +/// ``` +/// +/// [`from_raw_parts`]: ../../std/vec/struct.Vec.html#method.from_raw_parts +/// +/// Implementing `split_at_mut`: +/// +/// ``` +/// use std::{slice, mem}; +/// +/// // There are multiple ways to do this, and there are multiple problems +/// // with the following (transmute) way. +/// fn split_at_mut_transmute(slice: &mut [T], mid: usize) +/// -> (&mut [T], &mut [T]) { +/// let len = slice.len(); +/// assert!(mid <= len); +/// unsafe { +/// let slice2 = mem::transmute::<&mut [T], &mut [T]>(slice); +/// // first: transmute is not type safe; all it checks is that T and +/// // U are of the same size. Second, right here, you have two +/// // mutable references pointing to the same memory. +/// (&mut slice[0..mid], &mut slice2[mid..len]) +/// } +/// } +/// +/// // This gets rid of the type safety problems; `&mut *` will *only* give +/// // you a `&mut T` from a `&mut T` or `*mut T`. +/// fn split_at_mut_casts(slice: &mut [T], mid: usize) +/// -> (&mut [T], &mut [T]) { +/// let len = slice.len(); +/// assert!(mid <= len); +/// unsafe { +/// let slice2 = &mut *(slice as *mut [T]); +/// // however, you still have two mutable references pointing to +/// // the same memory. +/// (&mut slice[0..mid], &mut slice2[mid..len]) +/// } +/// } +/// +/// // This is how the standard library does it. This is the best method, if +/// // you need to do something like this +/// fn split_at_stdlib(to_split: &mut [T], mid: usize) +/// -> (&mut [T], &mut [T]) { +/// let len = to_split.len(); +/// assert!(mid <= len); +/// unsafe { +/// let ptr = to_split.as_mut_ptr(); +/// let fst = slice::from_raw_parts_mut(ptr, mid); +/// let snd = slice::from_raw_parts_mut(ptr.add(mid), len - mid); +/// // The function now has three mutable references to overlapping memory: +/// // `to_split`, `fst`, and `snd`. +/// // `to_split` is never used after `let ptr = ...` so it can be treated as "dead". +/// // This leaves two "live" mutable slice references, `fst` and `snd`, with no overlap. +/// (fst, snd) +/// } +/// } +/// ``` +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_allowed_through_unstable_modules( + message = "import this function via the `mem` module instead", + module = "mem" +)] +#[rustc_const_stable(feature = "const_transmute", since = "1.56.0")] +#[rustc_diagnostic_item = "transmute"] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const unsafe fn transmute(src: Src) -> Dst; + +/// Like [`transmute`], but even less checked at compile-time: rather than +/// giving an error for `size_of::() != size_of::()`, it's +/// **Undefined Behavior** at runtime. +/// +/// Prefer normal `transmute` where possible, for the extra checking, since +/// both do exactly the same thing at runtime, if they both compile. +/// +/// This is not expected to ever be exposed directly to users, rather it +/// may eventually be exposed through some more-constrained API. +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const unsafe fn transmute_unchecked(src: Src) -> Dst; + +/// Returns `true` if the actual type given as `T` requires drop +/// glue; returns `false` if the actual type provided for `T` +/// implements `Copy`. +/// +/// If the actual type neither requires drop glue nor implements +/// `Copy`, then the return value of this function is unspecified. +/// +/// Note that, unlike most intrinsics, this can only be called at compile-time +/// as backends do not have an implementation for it. The only caller (its +/// stable counterpart) wraps this intrinsic call in a `const` block so that +/// backends only see an evaluated constant. +/// +/// The stabilized version of this intrinsic is [`mem::needs_drop`](crate::mem::needs_drop). +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +#[rustc_comptime] +pub fn needs_drop() -> bool; + +/// Calculates the offset from a pointer. +/// +/// This is implemented as an intrinsic to avoid converting to and from an +/// integer, since the conversion would throw away aliasing information. +/// +/// This can only be used with `Ptr` as a raw pointer type (`*mut` or `*const`) +/// to a `Sized` pointee and with `Delta` as `usize` or `isize`. Any other +/// instantiations may arbitrarily misbehave, and that's *not* a compiler bug. +/// +/// # Safety +/// +/// If the computed offset is non-zero, then both the starting and resulting pointer must be +/// either in bounds or at the end of an allocation. If either pointer is out +/// of bounds or arithmetic overflow occurs then this operation is undefined behavior. +/// +/// The stabilized version of this intrinsic is [`pointer::offset`]. +#[must_use = "returns a new pointer rather than modifying its argument"] +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const unsafe fn offset(dst: Ptr, offset: Delta) -> Ptr; + +/// Calculates the offset from a pointer, potentially wrapping. +/// +/// This is implemented as an intrinsic to avoid converting to and from an +/// integer, since the conversion inhibits certain optimizations. +/// +/// # Safety +/// +/// Unlike the `offset` intrinsic, this intrinsic does not restrict the +/// resulting pointer to point into or at the end of an allocated +/// object, and it wraps with two's complement arithmetic. The resulting +/// value is not necessarily valid to be used to actually access memory. +/// +/// The stabilized version of this intrinsic is [`pointer::wrapping_offset`]. +#[must_use = "returns a new pointer rather than modifying its argument"] +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const unsafe fn arith_offset(dst: *const T, offset: isize) -> *const T; + +/// Projects to the `index`-th element of `slice_ptr`, as the same kind of pointer +/// as the slice was provided -- so `&mut [T] → &mut T`, `&[T] → &T`, +/// `*mut [T] → *mut T`, or `*const [T] → *const T` -- without a bounds check. +/// +/// This is exposed via `::get(_unchecked)(_mut)`, +/// and isn't intended to be used elsewhere. +/// +/// Expands in MIR to `{&, &mut, &raw const, &raw mut} (*slice_ptr)[index]`, +/// depending on the types involved, so no backend support is needed. +/// +/// # Safety +/// +/// - `index < PtrMetadata(slice_ptr)`, so the indexing is in-bounds for the slice +/// - the resulting offsetting is in-bounds of the allocation, which is +/// always the case for references, but needs to be upheld manually for pointers +#[rustc_nounwind] +#[rustc_intrinsic] +pub const unsafe fn slice_get_unchecked< + ItemPtr: bounds::ChangePointee<[T], Pointee = T, Output = SlicePtr>, + SlicePtr, + T, +>( + slice_ptr: SlicePtr, + index: usize, +) -> ItemPtr; + +/// Masks out bits of the pointer according to a mask. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// Consider using [`pointer::mask`] instead. +#[rustc_nounwind] +#[rustc_intrinsic] +pub fn ptr_mask(ptr: *const T, mask: usize) -> *const T; + +/// Equivalent to the appropriate `llvm.memcpy.p0i8.0i8.*` intrinsic, with +/// a size of `count` * `size_of::()` and an alignment of `align_of::()`. +/// +/// This intrinsic does not have a stable counterpart. +/// # Safety +/// +/// The safety requirements are consistent with [`copy_nonoverlapping`] +/// while the read and write behaviors are volatile, +/// which means it will not be optimized out unless `_count` or `size_of::()` is equal to zero. +/// +/// [`copy_nonoverlapping`]: ptr::copy_nonoverlapping +#[rustc_intrinsic] +#[rustc_nounwind] +pub unsafe fn volatile_copy_nonoverlapping_memory(dst: *mut T, src: *const T, count: usize); +/// Equivalent to the appropriate `llvm.memmove.p0i8.0i8.*` intrinsic, with +/// a size of `count * size_of::()` and an alignment of `align_of::()`. +/// +/// The volatile parameter is set to `true`, so it will not be optimized out +/// unless size is equal to zero. +/// +/// This intrinsic does not have a stable counterpart. +#[rustc_intrinsic] +#[rustc_nounwind] +pub unsafe fn volatile_copy_memory(dst: *mut T, src: *const T, count: usize); +/// Equivalent to the appropriate `llvm.memset.p0i8.*` intrinsic, with a +/// size of `count * size_of::()` and an alignment of `align_of::()`. +/// +/// This intrinsic does not have a stable counterpart. +/// # Safety +/// +/// The safety requirements are consistent with [`write_bytes`] while the write behavior is volatile, +/// which means it will not be optimized out unless `_count` or `size_of::()` is equal to zero. +/// +/// [`write_bytes`]: ptr::write_bytes +#[rustc_intrinsic] +#[rustc_nounwind] +pub const unsafe fn volatile_set_memory(dst: *mut T, val: u8, count: usize); + +/// Performs a volatile load from the `src` pointer. +/// +/// The stabilized version of this intrinsic is [`core::ptr::read_volatile`]. +#[rustc_intrinsic] +#[rustc_nounwind] +pub const unsafe fn volatile_load(src: *const T) -> T; +/// Performs a volatile store to the `dst` pointer. +/// +/// The stabilized version of this intrinsic is [`core::ptr::write_volatile`]. +#[rustc_intrinsic] +#[rustc_nounwind] +pub const unsafe fn volatile_store(dst: *mut T, val: T); + +/// Performs a volatile load from the `src` pointer +/// The pointer is not required to be aligned. +/// +/// This intrinsic does not have a stable counterpart. +#[rustc_intrinsic] +#[rustc_nounwind] +#[rustc_diagnostic_item = "intrinsics_unaligned_volatile_load"] +pub unsafe fn unaligned_volatile_load(src: *const T) -> T; +/// Performs a volatile store to the `dst` pointer. +/// The pointer is not required to be aligned. +/// +/// This intrinsic does not have a stable counterpart. +#[rustc_intrinsic] +#[rustc_nounwind] +#[rustc_diagnostic_item = "intrinsics_unaligned_volatile_store"] +pub unsafe fn unaligned_volatile_store(dst: *mut T, val: T); + +intrinsic_dispatch_on_type! { + /// Returns the square root of a floating-point value. + /// + /// The stabilized versions of this intrinsic are available on the float primitives via the + /// `sqrt` method. For example, [`f32::sqrt`](../../std/primitive.f32.html#method.sqrt). + #[rustc_nounwind] + #[rustc_intrinsic] + pub fn sqrt(x: T) -> T; + + f16 => { libm::sqrtf16(x) } + f32 => { libm::sqrtf(x) } + f64 => { libm::sqrt(x) } + f128 => { libm::sqrtf128(x) } +} + +intrinsic_dispatch_on_type! { + /// Raises a floating-point value to an integer power. + /// + /// The stabilized versions of this intrinsic are available on the float primitives via the + /// `powi` method. For example, [`f32::powi`](../../std/primitive.f32.html#method.powi). + #[rustc_nounwind] + #[inline] + #[rustc_intrinsic] + pub fn powi(a: T, x: i32) -> T; + + f16 => { powi(a as f32, x) as f16 } + f32 => { libm::__powisf2(a, x) } + f64 => { libm::__powidf2(a, x) } + f128 => { libm::__powitf2(a, x) } +} + +intrinsic_dispatch_on_type! { + /// Returns the sine of a floating-point value. + /// + /// The stabilized versions of this intrinsic are available on the float primitives via the + /// `sin` method. For example, [`f32::sin`](../../std/primitive.f32.html#method.sin). + #[rustc_nounwind] + #[inline] + #[rustc_intrinsic] + pub fn sin(x: T) -> T; + + f16 => { sin(x as f32) as f16 } + f32 => { + cfg_select! { + all(target_env = "msvc", target_arch = "x86") => sin(x as f64) as f32, + _ => libm::likely_available::sinf(x), + } + } + f64 => { libm::likely_available::sin(x) } + f128 => { libm::maybe_available::sinf128(x) } +} + +intrinsic_dispatch_on_type! { + /// Returns the cosine of a floating-point value. + /// + /// The stabilized versions of this intrinsic are available on the float primitives via the + /// `cos` method. For example, [`f32::cos`](../../std/primitive.f32.html#method.cos). + #[rustc_nounwind] + #[inline] + #[rustc_intrinsic] + pub fn cos(x: T) -> T; + + f16 => { cos(x as f32) as f16 } + f32 => { + cfg_select! { + all(target_env = "msvc", target_arch = "x86") => cos(x as f64) as f32, + _ => libm::likely_available::cosf(x), + } + } + f64 => { libm::likely_available::cos(x) } + f128 => { libm::maybe_available::cosf128(x) } +} + +intrinsic_dispatch_on_type! { + /// Raises a floating-point value to a power of the same type. + /// + /// The stabilized versions of this intrinsic are available on the float primitives via the + /// `powf` method. For example, [`f32::powf`](../../std/primitive.f32.html#method.powf). + #[rustc_nounwind] + #[inline] + #[rustc_intrinsic] + pub fn powf(a: T, x: T) -> T; + + f16 => { powf(a as f32, x as f32) as f16 } + f32 => { + cfg_select! { + all(target_env = "msvc", target_arch = "x86") => powf(a as f64, x as f64) as f32, + _ => libm::likely_available::powf(a, x), + } + } + f64 => { libm::likely_available::pow(a, x) } + f128 => { libm::maybe_available::powf128(a, x) } +} + +intrinsic_dispatch_on_type! { + /// Returns the exponential of a floating-point value. + /// + /// The stabilized versions of this intrinsic are available on the float primitives via the + /// `exp` method. For example, [`f32::exp`](../../std/primitive.f32.html#method.exp). + #[rustc_nounwind] + #[inline] + #[rustc_intrinsic] + pub fn exp(x: T) -> T; + + f16 => { exp(x as f32) as f16 } + f32 => { + cfg_select! { + all(target_env = "msvc", target_arch = "x86") => exp(x as f64) as f32, + _ => libm::likely_available::expf(x), + } + } + f64 => { libm::likely_available::exp(x) } + f128 => { libm::maybe_available::expf128(x) } +} + +intrinsic_dispatch_on_type! { + /// Returns 2 raised to the power of a floating-point value. + /// + /// The stabilized versions of this intrinsic are available on the float primitives via the + /// `exp2` method. For example, [`f32::exp2`](../../std/primitive.f32.html#method.exp2). + #[rustc_nounwind] + #[inline] + #[rustc_intrinsic] + pub fn exp2(x: T) -> T; + + f16 => { exp2(x as f32) as f16 } + f32 => { + cfg_select! { + all(target_env = "msvc", target_arch = "x86") => exp2(x as f64) as f32, + _ => libm::likely_available::exp2f(x), + } + } + f64 => { libm::likely_available::exp2(x) } + f128 => { libm::maybe_available::exp2f128(x) } +} + +intrinsic_dispatch_on_type! { + /// Returns the natural logarithm of a floating-point value. + /// + /// The stabilized versions of this intrinsic are available on the float primitives via the + /// `ln` method. For example, [`f32::ln`](../../std/primitive.f32.html#method.ln). + #[rustc_nounwind] + #[inline] + #[rustc_intrinsic] + pub fn log(x: T) -> T; + + f16 => { log(x as f32) as f16 } + f32 => { + cfg_select! { + all(target_env = "msvc", target_arch = "x86") => log(x as f64) as f32, + _ => libm::likely_available::logf(x), + } + } + f64 => { libm::likely_available::log(x) } + f128 => { libm::maybe_available::logf128(x) } +} + +intrinsic_dispatch_on_type! { + /// Returns the base 10 logarithm of a floating-point value. + /// + /// The stabilized versions of this intrinsic are available on the float primitives via the + /// `log10` method. For example, [`f32::log10`](../../std/primitive.f32.html#method.log10). + #[rustc_nounwind] + #[inline] + #[rustc_intrinsic] + pub fn log10(x: T) -> T; + + f16 => { log10(x as f32) as f16 } + f32 => { + cfg_select! { + all(target_env = "msvc", target_arch = "x86") => log10(x as f64) as f32, + _ => libm::likely_available::log10f(x), + } + } + f64 => { libm::likely_available::log10(x) } + f128 => { libm::maybe_available::log10f128(x) } +} + +intrinsic_dispatch_on_type! { + /// Returns the base 2 logarithm of a floating-point value. + /// + /// The stabilized versions of this intrinsic are available on the float primitives via the + /// `log2` method. For example, [`f32::log2`](../../std/primitive.f32.html#method.log2). + #[rustc_nounwind] + #[inline] + #[rustc_intrinsic] + pub fn log2(x: T) -> T; + + f16 => { log2(x as f32) as f16 } + f32 => { + cfg_select! { + all(target_env = "msvc", target_arch = "x86") => log2(x as f64) as f32, + _ => libm::likely_available::log2f(x), + } + } + f64 => { libm::likely_available::log2(x) } + f128 => { libm::maybe_available::log2f128(x) } +} + +intrinsic_dispatch_on_type! { + /// Returns `a * b + c` without rounding the intermediate result. + /// + /// The stabilized versions of this intrinsic are available on the float primitives via the + /// `mul_add` method. For example, + /// [`f32::mul_add`](../../std/primitive.f32.html#method.mul_add). + #[rustc_nounwind] + #[inline] + #[rustc_intrinsic_const_stable_indirect] + #[rustc_intrinsic] + // The fallback bodies call into `libm`, which is not available at compile time. This is fine + // because const-eval implements this intrinsic itself and never runs the fallback body. + #[rustc_do_not_const_check] + pub const fn fma(a: T, b: T, c: T) -> T; + + f16 => { libm::fmaf16(a, b, c) } + f32 => { libm::fmaf(a, b, c) } + f64 => { libm::fma(a, b, c) } + f128 => { libm::fmaf128(a, b, c) } +} + +/// Returns `a * b + c`, non-deterministically executing either a fused multiply-add or two +/// operations with rounding of the intermediate result. +/// +/// The operation is fused if the code generator determines that target +/// instruction set has support for a fused operation, and that the fused +/// operation is more efficient than the equivalent, separate pair of mul +/// and add instructions. It is unspecified whether or not a fused operation +/// is selected, and that may depend on optimization level and context, for +/// example. +/// +/// The stabilized versions of this intrinsic are available on the float primitives via the +/// `mul_add_relaxed` method. For example, +/// [`f32::mul_add_relaxed`](../../std/primitive.f32.html#method.mul_add_relaxed). +#[inline] +#[rustc_intrinsic_const_stable_indirect] +#[rustc_intrinsic] +#[rustc_nounwind] +#[rustc_do_not_const_check] +pub const fn fmuladd(a: T, b: T, c: T) -> T { + a * b + c +} + +intrinsic_dispatch_on_type! { + /// Returns the largest integer less than or equal to a floating-point value. + /// + /// The stabilized versions of this intrinsic are available on the float primitives via the + /// `floor` method. For example, [`f32::floor`](../../std/primitive.f32.html#method.floor). + #[rustc_nounwind] + #[inline] + #[rustc_intrinsic_const_stable_indirect] + #[rustc_intrinsic] + // The fallback bodies call into `libm`, which is not available at compile time. This is fine + // because const-eval implements this intrinsic itself and never runs the fallback body. + #[rustc_do_not_const_check] + pub const fn floor(x: T) -> T; + + f16 => { libm::floorf16(x) } + f32 => { libm::floorf(x) } + f64 => { libm::floor(x) } + f128 => { libm::floorf128(x) } +} + +intrinsic_dispatch_on_type! { + /// Returns the smallest integer greater than or equal to a floating-point value. + /// + /// The stabilized versions of this intrinsic are available on the float primitives via the + /// `ceil` method. For example, [`f32::ceil`](../../std/primitive.f32.html#method.ceil). + #[rustc_nounwind] + #[inline] + #[rustc_intrinsic_const_stable_indirect] + #[rustc_intrinsic] + // The fallback bodies call into `libm`, which is not available at compile time. This is fine + // because const-eval implements this intrinsic itself and never runs the fallback body. + #[rustc_do_not_const_check] + pub const fn ceil(x: T) -> T; + + f16 => { libm::ceilf16(x) } + f32 => { libm::ceilf(x) } + f64 => { libm::ceil(x) } + f128 => { libm::ceilf128(x) } +} + +intrinsic_dispatch_on_type! { + /// Returns the integer part of a floating-point value. + /// + /// The stabilized versions of this intrinsic are available on the float primitives via the + /// `trunc` method. For example, [`f32::trunc`](../../std/primitive.f32.html#method.trunc). + #[rustc_nounwind] + #[inline] + #[rustc_intrinsic_const_stable_indirect] + #[rustc_intrinsic] + // The fallback bodies call into `libm`, which is not available at compile time. This is fine + // because const-eval implements this intrinsic itself and never runs the fallback body. + #[rustc_do_not_const_check] + pub const fn trunc(x: T) -> T; + + f16 => { libm::truncf16(x) } + f32 => { libm::truncf(x) } + f64 => { libm::trunc(x) } + f128 => { libm::truncf128(x) } +} + +intrinsic_dispatch_on_type! { + /// Returns the nearest integer to a floating-point value. Rounds half-way cases to the number + /// with an even least significant digit. + /// + /// The stabilized versions of this intrinsic are available on the float primitives via the + /// `round_ties_even` method. For example, + /// [`f32::round_ties_even`](../../std/primitive.f32.html#method.round_ties_even). + #[rustc_nounwind] + #[inline] + #[rustc_intrinsic_const_stable_indirect] + #[rustc_intrinsic] + // The fallback bodies call into `libm`, which is not available at compile time. This is fine + // because const-eval implements this intrinsic itself and never runs the fallback body. + #[rustc_do_not_const_check] + pub const fn round_ties_even(x: T) -> T; + + f16 => { libm::roundevenf16(x) } + f32 => { libm::roundevenf(x) } + f64 => { libm::roundeven(x) } + f128 => { libm::roundevenf128(x) } +} + +intrinsic_dispatch_on_type! { + /// Returns the nearest integer to a floating-point value. Rounds half-way cases away from + /// zero. + /// + /// The stabilized versions of this intrinsic are available on the float primitives via the + /// `round` method. For example, [`f32::round`](../../std/primitive.f32.html#method.round). + #[rustc_nounwind] + #[inline] + #[rustc_intrinsic_const_stable_indirect] + #[rustc_intrinsic] + // The fallback bodies call into `libm`, which is not available at compile time. This is fine + // because const-eval implements this intrinsic itself and never runs the fallback body. + #[rustc_do_not_const_check] + pub const fn round(x: T) -> T; + + f16 => { libm::roundf16(x) } + f32 => { libm::roundf(x) } + f64 => { libm::round(x) } + f128 => { libm::roundf128(x) } +} + +/// Float addition that allows optimizations based on algebraic rules. +/// Requires that inputs and output of the operation are finite, causing UB otherwise. +/// +/// This intrinsic does not have a stable counterpart. +#[rustc_intrinsic] +#[rustc_nounwind] +pub unsafe fn fadd_fast(a: T, b: T) -> T; + +/// Float subtraction that allows optimizations based on algebraic rules. +/// Requires that inputs and output of the operation are finite, causing UB otherwise. +/// +/// This intrinsic does not have a stable counterpart. +#[rustc_intrinsic] +#[rustc_nounwind] +pub unsafe fn fsub_fast(a: T, b: T) -> T; + +/// Float multiplication that allows optimizations based on algebraic rules. +/// Requires that inputs and output of the operation are finite, causing UB otherwise. +/// +/// This intrinsic does not have a stable counterpart. +#[rustc_intrinsic] +#[rustc_nounwind] +pub unsafe fn fmul_fast(a: T, b: T) -> T; + +/// Float division that allows optimizations based on algebraic rules. +/// Requires that inputs and output of the operation are finite, causing UB otherwise. +/// +/// This intrinsic does not have a stable counterpart. +#[rustc_intrinsic] +#[rustc_nounwind] +pub unsafe fn fdiv_fast(a: T, b: T) -> T; + +/// Float remainder that allows optimizations based on algebraic rules. +/// Requires that inputs and output of the operation are finite, causing UB otherwise. +/// +/// This intrinsic does not have a stable counterpart. +#[rustc_intrinsic] +#[rustc_nounwind] +pub unsafe fn frem_fast(a: T, b: T) -> T; + +/// Converts with LLVM’s fptoui/fptosi, which may return undef for values out of range +/// () +/// +/// Stabilized as [`f32::to_int_unchecked`] and [`f64::to_int_unchecked`]. +#[rustc_intrinsic] +#[rustc_nounwind] +pub unsafe fn float_to_int_unchecked(value: Float) +-> Int; + +/// Float addition that allows optimizations based on algebraic rules. +/// +/// Stabilized as [`f16::algebraic_add`], [`f32::algebraic_add`], [`f64::algebraic_add`] and [`f128::algebraic_add`]. +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const fn fadd_algebraic(a: T, b: T) -> T; + +/// Float subtraction that allows optimizations based on algebraic rules. +/// +/// Stabilized as [`f16::algebraic_sub`], [`f32::algebraic_sub`], [`f64::algebraic_sub`] and [`f128::algebraic_sub`]. +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const fn fsub_algebraic(a: T, b: T) -> T; + +/// Float multiplication that allows optimizations based on algebraic rules. +/// +/// Stabilized as [`f16::algebraic_mul`], [`f32::algebraic_mul`], [`f64::algebraic_mul`] and [`f128::algebraic_mul`]. +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const fn fmul_algebraic(a: T, b: T) -> T; + +/// Float division that allows optimizations based on algebraic rules. +/// +/// Stabilized as [`f16::algebraic_div`], [`f32::algebraic_div`], [`f64::algebraic_div`] and [`f128::algebraic_div`]. +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const fn fdiv_algebraic(a: T, b: T) -> T; + +/// Float remainder that allows optimizations based on algebraic rules. +/// +/// Stabilized as [`f16::algebraic_rem`], [`f32::algebraic_rem`], [`f64::algebraic_rem`] and [`f128::algebraic_rem`]. +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const fn frem_algebraic(a: T, b: T) -> T; + +/// Integer `min`imum, signed or unsigned depending on `T`. +/// +/// Allowed only on `uN`, `iN`, `usize`, and `isize`. +/// (Not on `bool` nor on `char`.) +/// +/// Stabilized as [`u16::min`] and [`i64::min`] and similar. +#[rustc_const_unstable(feature = "const_cmp", issue = "143800")] +#[rustc_nounwind] +#[rustc_intrinsic] +#[miri::intrinsic_fallback_is_spec] +pub const fn integer_min(a: T, b: T) -> T { + if a < b { a } else { b } +} + +/// Integer `max`imum, signed or unsigned depending on `T`. +/// +/// Allowed only on `uN`, `iN`, `usize`, and `isize`. +/// (Not on `bool` nor on `char`.) +/// +/// Stabilized as [`u16::max`] and [`i64::max`] and similar. +#[rustc_const_unstable(feature = "const_cmp", issue = "143800")] +#[rustc_nounwind] +#[rustc_intrinsic] +#[miri::intrinsic_fallback_is_spec] +pub const fn integer_max(a: T, b: T) -> T { + if a < b { b } else { a } +} + +/// Returns the number of bits set in an integer type `T` +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// The stabilized versions of this intrinsic are available on the integer +/// primitives via the `count_ones` method. For example, +/// [`u32::count_ones`] +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const fn ctpop(x: T) -> u32; + +/// Returns the number of leading unset bits (zeroes) in an integer type `T`. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// The stabilized versions of this intrinsic are available on the integer +/// primitives via the `leading_zeros` method. For example, +/// [`u32::leading_zeros`] +/// +/// # Examples +/// +/// ``` +/// #![feature(core_intrinsics)] +/// # #![allow(internal_features)] +/// +/// use std::intrinsics::ctlz; +/// +/// let x = 0b0001_1100_u8; +/// let num_leading = ctlz(x); +/// assert_eq!(num_leading, 3); +/// ``` +/// +/// An `x` with value `0` will return the bit width of `T`. +/// +/// ``` +/// #![feature(core_intrinsics)] +/// # #![allow(internal_features)] +/// +/// use std::intrinsics::ctlz; +/// +/// let x = 0u16; +/// let num_leading = ctlz(x); +/// assert_eq!(num_leading, 16); +/// ``` +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const fn ctlz(x: T) -> u32; + +/// Like `ctlz`, but extra-unsafe as it returns `undef` when +/// given an `x` with value `0`. +/// +/// This intrinsic does not have a stable counterpart. +/// +/// # Examples +/// +/// ``` +/// #![feature(core_intrinsics)] +/// # #![allow(internal_features)] +/// +/// use std::intrinsics::ctlz_nonzero; +/// +/// let x = 0b0001_1100_u8; +/// let num_leading = unsafe { ctlz_nonzero(x) }; +/// assert_eq!(num_leading, 3); +/// ``` +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const unsafe fn ctlz_nonzero(x: T) -> u32; + +/// Returns the number of trailing unset bits (zeroes) in an integer type `T`. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// The stabilized versions of this intrinsic are available on the integer +/// primitives via the `trailing_zeros` method. For example, +/// [`u32::trailing_zeros`] +/// +/// # Examples +/// +/// ``` +/// #![feature(core_intrinsics)] +/// # #![allow(internal_features)] +/// +/// use std::intrinsics::cttz; +/// +/// let x = 0b0011_1000_u8; +/// let num_trailing = cttz(x); +/// assert_eq!(num_trailing, 3); +/// ``` +/// +/// An `x` with value `0` will return the bit width of `T`: +/// +/// ``` +/// #![feature(core_intrinsics)] +/// # #![allow(internal_features)] +/// +/// use std::intrinsics::cttz; +/// +/// let x = 0u16; +/// let num_trailing = cttz(x); +/// assert_eq!(num_trailing, 16); +/// ``` +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const fn cttz(x: T) -> u32; + +/// Like `cttz`, but extra-unsafe as it returns `undef` when +/// given an `x` with value `0`. +/// +/// This intrinsic does not have a stable counterpart. +/// +/// # Examples +/// +/// ``` +/// #![feature(core_intrinsics)] +/// # #![allow(internal_features)] +/// +/// use std::intrinsics::cttz_nonzero; +/// +/// let x = 0b0011_1000_u8; +/// let num_trailing = unsafe { cttz_nonzero(x) }; +/// assert_eq!(num_trailing, 3); +/// ``` +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const unsafe fn cttz_nonzero(x: T) -> u32; + +/// Reverses the bytes in an integer type `T`. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// The stabilized versions of this intrinsic are available on the integer +/// primitives via the `swap_bytes` method. For example, +/// [`u32::swap_bytes`] +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const fn bswap(x: T) -> T; + +/// Reverses the bits in an integer type `T`. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// The stabilized versions of this intrinsic are available on the integer +/// primitives via the `reverse_bits` method. For example, +/// [`u32::reverse_bits`] +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const fn bitreverse(x: T) -> T; + +/// Does a three-way comparison between the two arguments, +/// which must be of character or integer (signed or unsigned) type. +/// +/// This was originally added because it greatly simplified the MIR in `cmp` +/// implementations, and then LLVM 20 added a backend intrinsic for it too. +/// +/// The stabilized version of this intrinsic is [`Ord::cmp`]. +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const fn three_way_compare(lhs: T, rhss: T) -> crate::cmp::Ordering; + +/// Combine two values which have no bits in common. +/// +/// This allows the backend to implement it as `a + b` *or* `a | b`, +/// depending which is easier to implement on a specific target. +/// +/// # Safety +/// +/// Requires that `(a & b) == 0`, or equivalently that `(a | b) == (a + b)`. +/// +/// Otherwise it's immediate UB. +#[rustc_const_unstable(feature = "disjoint_bitor", issue = "135758")] +#[rustc_nounwind] +#[rustc_intrinsic] +#[track_caller] +#[miri::intrinsic_fallback_is_spec] // the fallbacks all `assume` to tell Miri +pub const unsafe fn disjoint_bitor(a: T, b: T) -> T { + // SAFETY: same preconditions as this function. + unsafe { fallback::DisjointBitOr::disjoint_bitor(a, b) } +} + +/// Performs checked integer addition. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// The stabilized versions of this intrinsic are available on the integer +/// primitives via the `overflowing_add` method. For example, +/// [`u32::overflowing_add`] +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const fn add_with_overflow(x: T, y: T) -> (T, bool); + +/// Performs checked integer subtraction +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// The stabilized versions of this intrinsic are available on the integer +/// primitives via the `overflowing_sub` method. For example, +/// [`u32::overflowing_sub`] +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const fn sub_with_overflow(x: T, y: T) -> (T, bool); + +/// Performs checked integer multiplication +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// The stabilized versions of this intrinsic are available on the integer +/// primitives via the `overflowing_mul` method. For example, +/// [`u32::overflowing_mul`] +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const fn mul_with_overflow(x: T, y: T) -> (T, bool); + +/// Performs full-width multiplication and addition with a carry: +/// `multiplier * multiplicand + addend + carry`. +/// +/// This is possible without any overflow. For `uN`: +/// MAX * MAX + MAX + MAX +/// => (2ⁿ-1) × (2ⁿ-1) + (2ⁿ-1) + (2ⁿ-1) +/// => (2²ⁿ - 2ⁿ⁺¹ + 1) + (2ⁿ⁺¹ - 2) +/// => 2²ⁿ - 1 +/// +/// For `iN`, the upper bound is MIN * MIN + MAX + MAX => 2²ⁿ⁻² + 2ⁿ - 2, +/// and the lower bound is MAX * MIN + MIN + MIN => -2²ⁿ⁻² - 2ⁿ + 2ⁿ⁺¹. +/// +/// This currently supports unsigned integers *only*, no signed ones. +/// The stabilized versions of this intrinsic are available on integers. +#[rustc_const_unstable(feature = "core_intrinsics", issue = "none")] +#[rustc_nounwind] +#[rustc_intrinsic] +#[miri::intrinsic_fallback_is_spec] +pub const fn carrying_mul_add, U>( + multiplier: T, + multiplicand: T, + addend: T, + carry: T, +) -> (U, T) { + multiplier.carrying_mul_add(multiplicand, addend, carry) +} + +/// Performs an exact division, resulting in undefined behavior where +/// `x % y != 0` or `y == 0` or `x == T::MIN && y == -1` +/// +/// This intrinsic does not have a stable counterpart. +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const unsafe fn exact_div(x: T, y: T) -> T; + +/// Performs an unchecked division, resulting in undefined behavior +/// where `y == 0` or `x == T::MIN && y == -1` +/// +/// Safe wrappers for this intrinsic are available on the integer +/// primitives via the `checked_div` method. For example, +/// [`u32::checked_div`] +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const unsafe fn unchecked_div(x: T, y: T) -> T; +/// Returns the remainder of an unchecked division, resulting in +/// undefined behavior when `y == 0` or `x == T::MIN && y == -1` +/// +/// Safe wrappers for this intrinsic are available on the integer +/// primitives via the `checked_rem` method. For example, +/// [`u32::checked_rem`] +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const unsafe fn unchecked_rem(x: T, y: T) -> T; + +/// Performs an unchecked left shift, resulting in undefined behavior when +/// `y < 0` or `y >= N`, where N is the width of T in bits. +/// +/// Safe wrappers for this intrinsic are available on the integer +/// primitives via the `checked_shl` method. For example, +/// [`u32::checked_shl`] +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const unsafe fn unchecked_shl(x: T, y: U) -> T; +/// Performs an unchecked right shift, resulting in undefined behavior when +/// `y < 0` or `y >= N`, where N is the width of T in bits. +/// +/// Safe wrappers for this intrinsic are available on the integer +/// primitives via the `checked_shr` method. For example, +/// [`u32::checked_shr`] +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const unsafe fn unchecked_shr(x: T, y: U) -> T; + +/// Returns the result of an unchecked addition, resulting in +/// undefined behavior when `x + y > T::MAX` or `x + y < T::MIN`. +/// +/// The stable counterpart of this intrinsic is `unchecked_add` on the various +/// integer types, such as [`u16::unchecked_add`] and [`i64::unchecked_add`]. +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const unsafe fn unchecked_add(x: T, y: T) -> T; + +/// Returns the result of an unchecked subtraction, resulting in +/// undefined behavior when `x - y > T::MAX` or `x - y < T::MIN`. +/// +/// The stable counterpart of this intrinsic is `unchecked_sub` on the various +/// integer types, such as [`u16::unchecked_sub`] and [`i64::unchecked_sub`]. +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const unsafe fn unchecked_sub(x: T, y: T) -> T; + +/// Returns the result of an unchecked multiplication, resulting in +/// undefined behavior when `x * y > T::MAX` or `x * y < T::MIN`. +/// +/// The stable counterpart of this intrinsic is `unchecked_mul` on the various +/// integer types, such as [`u16::unchecked_mul`] and [`i64::unchecked_mul`]. +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const unsafe fn unchecked_mul(x: T, y: T) -> T; + +/// Performs rotate left. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// The stabilized versions of this intrinsic are available on the integer +/// primitives via the `rotate_left` method. For example, +/// [`u32::rotate_left`] +#[rustc_nounwind] +#[rustc_intrinsic] +#[rustc_allow_const_fn_unstable(const_trait_impl)] +#[cfg_attr(miri, track_caller)] +#[miri::intrinsic_fallback_is_spec] +pub const fn rotate_left(x: T, shift: u32) -> T { + // Make sure to call the intrinsic for `funnel_shl`, not the fallback impl. + // SAFETY: we modulo `shift` so that the result is definitely less than the size of + // `T` in bits. + unsafe { unchecked_funnel_shl(x, x, shift % (mem::size_of::() as u32 * 8)) } +} + +/// Performs rotate right. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// The stabilized versions of this intrinsic are available on the integer +/// primitives via the `rotate_right` method. For example, +/// [`u32::rotate_right`] +#[rustc_nounwind] +#[rustc_intrinsic] +#[rustc_allow_const_fn_unstable(const_trait_impl)] +#[cfg_attr(miri, track_caller)] +#[miri::intrinsic_fallback_is_spec] +pub const fn rotate_right(x: T, shift: u32) -> T { + // Make sure to call the intrinsic for `funnel_shr`, not the fallback impl. + // SAFETY: we modulo `shift` so that the result is definitely less than the size of + // `T` in bits. + unsafe { unchecked_funnel_shr(x, x, shift % (mem::size_of::() as u32 * 8)) } +} + +/// Wrapping (modular) addition. Computes `a + b`, +/// wrapping around at the boundary of the type. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// The stabilized versions of this intrinsic are available on the integer +/// primitives via the `wrapping_add` method. For example, +/// [`u32::wrapping_add`] +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const fn wrapping_add(a: T, b: T) -> T; +/// Wrapping (modular) subtraction. Computes `a - b`, +/// wrapping around at the boundary of the type. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// The stabilized versions of this intrinsic are available on the integer +/// primitives via the `wrapping_sub` method. For example, +/// [`u32::wrapping_sub`] +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const fn wrapping_sub(a: T, b: T) -> T; +/// Wrapping (modular) multiplication. Computes `a * +/// b`, wrapping around at the boundary of the type. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// The stabilized versions of this intrinsic are available on the integer +/// primitives via the `wrapping_mul` method. For example, +/// [`u32::wrapping_mul`] +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const fn wrapping_mul(a: T, b: T) -> T; + +/// Computes `a + b`, saturating at numeric bounds. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// The stabilized versions of this intrinsic are available on the integer +/// primitives via the `saturating_add` method. For example, +/// [`u32::saturating_add`] +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const fn saturating_add(a: T, b: T) -> T; +/// Computes `a - b`, saturating at numeric bounds. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// The stabilized versions of this intrinsic are available on the integer +/// primitives via the `saturating_sub` method. For example, +/// [`u32::saturating_sub`] +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const fn saturating_sub(a: T, b: T) -> T; + +/// Funnel Shift left. +/// +/// Concatenates `a` and `b` (with `a` in the most significant half), +/// creating an integer twice as wide. Then shift this integer left +/// by `shift`), and extract the most significant half. If `a` and `b` +/// are the same, this is equivalent to a rotate left operation. +/// +/// It is undefined behavior if `shift` is greater than or equal to the +/// bit size of `T`. +/// +/// Safe versions of this intrinsic are available on the integer primitives +/// via the `funnel_shl` method. For example, [`u32::funnel_shl`]. +#[rustc_intrinsic] +#[rustc_nounwind] +#[rustc_intrinsic_const_stable_indirect] +#[rustc_do_not_const_check] // Use built-in impl to avoid const-checks in the fallback body. +pub const unsafe fn unchecked_funnel_shl(a: T, b: T, shift: u32) -> T { + // SAFETY: caller ensures that `shift` is in-range + unsafe { a.unchecked_funnel_shl(b, shift) } +} + +/// Funnel Shift right. +/// +/// Concatenates `a` and `b` (with `a` in the most significant half), +/// creating an integer twice as wide. Then shift this integer right +/// by `shift` (taken modulo the bit size of `T`), and extract the +/// least significant half. If `a` and `b` are the same, this is equivalent +/// to a rotate right operation. +/// +/// It is undefined behavior if `shift` is greater than or equal to the +/// bit size of `T`. +/// +/// Safer versions of this intrinsic are available on the integer primitives +/// via the `funnel_shr` method. For example, [`u32::funnel_shr`] +#[rustc_intrinsic] +#[rustc_nounwind] +#[rustc_intrinsic_const_stable_indirect] +#[rustc_do_not_const_check] // Ise built-in impl to avoid const-checks in the fallback body. +pub const unsafe fn unchecked_funnel_shr(a: T, b: T, shift: u32) -> T { + // SAFETY: caller ensures that `shift` is in-range + unsafe { a.unchecked_funnel_shr(b, shift) } +} + +/// Carryless multiply. +/// +/// Safe versions of this intrinsic are available on the integer primitives +/// via the `carryless_mul` method. For example, [`u32::carryless_mul`]. +#[rustc_intrinsic] +#[rustc_nounwind] +#[rustc_const_unstable(feature = "core_intrinsics", issue = "none")] +#[miri::intrinsic_fallback_is_spec] +pub const fn carryless_mul(a: T, b: T) -> T { + a.carryless_mul(b) +} + +/// This is an implementation detail of [`crate::ptr::read`] and should +/// not be used anywhere else. See its comments for why this exists. +/// +/// This intrinsic can *only* be called where the pointer is a local without +/// projections (`read_via_copy(ptr)`, not `read_via_copy(*ptr)`) so that it +/// trivially obeys runtime-MIR rules about derefs in operands. +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const unsafe fn read_via_copy(ptr: *const T) -> T; + +/// This is an implementation detail of [`crate::ptr::write`] and should +/// not be used anywhere else. See its comments for why this exists. +/// +/// This intrinsic can *only* be called where the pointer is a local without +/// projections (`write_via_move(ptr, x)`, not `write_via_move(*ptr, x)`) so +/// that it trivially obeys runtime-MIR rules about derefs in operands. +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const unsafe fn write_via_move(ptr: *mut T, value: T); + +/// Returns the value of the discriminant for the variant in 'v'; +/// if `T` has no discriminant, returns `0`. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// The stabilized version of this intrinsic is [`core::mem::discriminant`]. +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const fn discriminant_value(v: &T) -> ::Discriminant; + +/// Rust's "try catch" construct for unwinding. Invokes the function pointer `try_fn` with the +/// data pointer `data`, and calls `catch_fn` if unwinding occurs while `try_fn` runs. +/// Returns `true` if unwinding occurred and `catch_fn` was called; returns `false` otherwise. +/// +/// `catch_fn` must not unwind. +/// +/// The third argument is a function called if an unwind occurs (both Rust `panic` and foreign +/// unwinds). This function takes the data pointer and a pointer to the target- and +/// runtime-specific exception object that was caught. +/// +/// Note that in the case of a foreign unwinding operation, the exception object data may not be +/// safely usable from Rust, and should not be directly exposed via the standard library. To +/// prevent unsafe access, the library implementation may either abort the process or present an +/// opaque error type to the user. +/// +/// For more information, see the compiler's source, as well as the documentation for the stable +/// version of this intrinsic, `std::panic::catch_unwind`. +#[rustc_intrinsic] +#[rustc_nounwind] +pub unsafe fn catch_unwind( + _try_fn: unsafe fn(*mut Data), + _data: *mut Data, + _catch_fn: unsafe fn(*mut Data, *mut u8), +) -> bool; + +/// Emits a `nontemporal` store, which gives a hint to the CPU that the data should not be held +/// in cache. Except for performance, this is fully equivalent to `ptr.write(val)`. +/// +/// Not all architectures provide such an operation. For instance, x86 does not: while `MOVNT` +/// exists, that operation is *not* equivalent to `ptr.write(val)` (`MOVNT` writes can be reordered +/// in ways that are not allowed for regular writes). +#[rustc_intrinsic] +#[rustc_nounwind] +pub unsafe fn nontemporal_store(ptr: *mut T, val: T); + +/// See documentation of `<*const T>::offset_from` for details. +#[rustc_intrinsic_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const unsafe fn ptr_offset_from(ptr: *const T, base: *const T) -> isize; + +/// See documentation of `<*const T>::offset_from_unsigned` for details. +#[rustc_nounwind] +#[rustc_intrinsic] +#[rustc_intrinsic_const_stable_indirect] +pub const unsafe fn ptr_offset_from_unsigned(ptr: *const T, base: *const T) -> usize; + +/// See documentation of `<*const T>::guaranteed_eq` for details. +/// Returns `2` if the result is unknown. +/// Returns `1` if the pointers are guaranteed equal. +/// Returns `0` if the pointers are guaranteed inequal. +#[rustc_intrinsic] +#[rustc_nounwind] +#[rustc_do_not_const_check] +#[inline] +#[miri::intrinsic_fallback_is_spec] +pub const fn ptr_guaranteed_cmp(ptr: *const T, other: *const T) -> u8 { + (ptr == other) as u8 +} + +/// Determines whether the raw bytes of the two values are equal. +/// +/// This is particularly handy for arrays, since it allows things like just +/// comparing `i96`s instead of forcing `alloca`s for `[6 x i16]`. +/// +/// Above some backend-decided threshold this will emit calls to `memcmp`, +/// like slice equality does, instead of causing massive code size. +/// +/// Since this works by comparing the underlying bytes, the actual `T` is +/// not particularly important. It will be used for its size and alignment, +/// but any validity restrictions will be ignored, not enforced. +/// +/// # Safety +/// +/// It's UB to call this if any of the *bytes* in `*a` or `*b` are uninitialized. +/// Note that this is a stricter criterion than just the *values* being +/// fully-initialized: if `T` has padding, it's UB to call this intrinsic. +/// +/// At compile-time, it is furthermore UB to call this if any of the bytes +/// in `*a` or `*b` have provenance. +/// +/// (The implementation is allowed to branch on the results of comparisons, +/// which is UB if any of their inputs are `undef`.) +#[rustc_nounwind] +#[rustc_intrinsic] +pub const unsafe fn raw_eq(a: &T, b: &T) -> bool; + +/// Lexicographically compare `[left, left + bytes)` and `[right, right + bytes)` +/// as unsigned bytes, returning negative if `left` is less, zero if all the +/// bytes match, or positive if `left` is greater. +/// +/// This underlies things like `<[u8]>::cmp`, and will usually lower to `memcmp`. +/// +/// # Safety +/// +/// `left` and `right` must each be [valid] for reads of `bytes` bytes. +/// +/// Note that this applies to the whole range, not just until the first byte +/// that differs. That allows optimizations that can read in large chunks. +/// +/// [valid]: crate::ptr#safety +#[rustc_nounwind] +#[rustc_intrinsic] +#[rustc_const_unstable(feature = "const_cmp", issue = "143800")] +pub const unsafe fn compare_bytes(left: *const u8, right: *const u8, bytes: usize) -> i32; + +/// See documentation of [`std::hint::black_box`] for details. +/// +/// [`std::hint::black_box`]: crate::hint::black_box +#[rustc_nounwind] +#[rustc_intrinsic] +#[rustc_intrinsic_const_stable_indirect] +pub const fn black_box(dummy: T) -> T; + +/// Selects which function to call depending on the context. +/// +/// If this function is evaluated at compile-time, then a call to this +/// intrinsic will be replaced with a call to `called_in_const`. It gets +/// replaced with a call to `called_at_rt` otherwise. +/// +/// This function is safe to call, but note the stability concerns below. +/// +/// # Type Requirements +/// +/// The two functions must be both function items. They cannot be function +/// pointers or closures. The first function must be a `const fn`. +/// +/// `arg` will be the tupled arguments that will be passed to either one of +/// the two functions, therefore, both functions must accept the same type of +/// arguments. Both functions must return RET. +/// +/// # Stability concerns +/// +/// Rust has not yet decided that `const fn` are allowed to tell whether +/// they run at compile-time or at runtime. Therefore, when using this +/// intrinsic anywhere that can be reached from stable, it is crucial that +/// the end-to-end behavior of the stable `const fn` is the same for both +/// modes of execution. (Here, Undefined Behavior is considered "the same" +/// as any other behavior, so if the function exhibits UB at runtime then +/// it may do whatever it wants at compile-time.) +/// +/// Here is an example of how this could cause a problem: +/// ```no_run +/// #![feature(const_eval_select)] +/// #![feature(core_intrinsics)] +/// # #![allow(internal_features)] +/// use std::intrinsics::const_eval_select; +/// +/// // Standard library +/// pub const fn inconsistent() -> i32 { +/// fn runtime() -> i32 { 1 } +/// const fn compiletime() -> i32 { 2 } +/// +/// // ⚠ This code violates the required equivalence of `compiletime` +/// // and `runtime`. +/// const_eval_select((), compiletime, runtime) +/// } +/// +/// // User Crate +/// const X: i32 = inconsistent(); +/// let x = inconsistent(); +/// assert_eq!(x, X); +/// ``` +/// +/// Currently such an assertion would always succeed; until Rust decides +/// otherwise, that principle should not be violated. +#[rustc_const_unstable(feature = "const_eval_select", issue = "124625")] +#[rustc_intrinsic] +pub const fn const_eval_select( + _arg: ARG, + _called_in_const: F, + _called_at_rt: G, +) -> RET +where + G: FnOnce, + F: const FnOnce; + +/// A macro to make it easier to invoke const_eval_select. Use as follows: +/// ```rust,ignore (just a macro example) +/// const_eval_select!( +/// @capture { arg1: i32 = some_expr, arg2: T = other_expr } -> U: +/// if const #[attributes_for_const_arm] { +/// // Compile-time code goes here. +/// } else #[attributes_for_runtime_arm] { +/// // Run-time code goes here. +/// } +/// ) +/// ``` +/// The `@capture` block declares which surrounding variables / expressions can be +/// used inside the `if const`. +/// Note that the two arms of this `if` really each become their own function, which is why the +/// macro supports setting attributes for those functions. Both functions are marked as `#[inline]`. +/// +/// See [`const_eval_select()`] for the rules and requirements around that intrinsic. +pub(crate) macro const_eval_select { + ( + @capture$([$($binders:tt)*])? { $($arg:ident : $ty:ty = $val:expr),* $(,)? } $( -> $ret:ty )? : + if const + $(#[$compiletime_attr:meta])* $compiletime:block + else + $(#[$runtime_attr:meta])* $runtime:block + ) => {{ + #[inline] + $(#[$runtime_attr])* + fn runtime$(<$($binders)*>)?($($arg: $ty),*) $( -> $ret )? { + $runtime + } + + #[inline] + $(#[$compiletime_attr])* + const fn compiletime$(<$($binders)*>)?($($arg: $ty),*) $( -> $ret )? { + // Don't warn if one of the arguments is unused. + $(let _ = $arg;)* + + $compiletime + } + + const_eval_select(($($val,)*), compiletime, runtime) + }}, + // We support leaving away the `val` expressions for *all* arguments + // (but not for *some* arguments, that's too tricky). + ( + @capture$([$($binders:tt)*])? { $($arg:ident : $ty:ty),* $(,)? } $( -> $ret:ty )? : + if const + $(#[$compiletime_attr:meta])* $compiletime:block + else + $(#[$runtime_attr:meta])* $runtime:block + ) => { + $crate::intrinsics::const_eval_select!( + @capture$([$($binders)*])? { $($arg : $ty = $arg),* } $(-> $ret)? : + if const + $(#[$compiletime_attr])* $compiletime + else + $(#[$runtime_attr])* $runtime + ) + }, +} + +/// Returns whether the argument's value is statically known at +/// compile-time. +/// +/// This is useful when there is a way of writing the code that will +/// be *faster* when some variables have known values, but *slower* +/// in the general case: an `if is_val_statically_known(var)` can be used +/// to select between these two variants. The `if` will be optimized away +/// and only the desired branch remains. +/// +/// Formally speaking, this function non-deterministically returns `true` +/// or `false`, and the caller has to ensure sound behavior for both cases. +/// In other words, the following code has *Undefined Behavior*: +/// +/// ```no_run +/// #![feature(core_intrinsics)] +/// # #![allow(internal_features)] +/// use std::hint::unreachable_unchecked; +/// use std::intrinsics::is_val_statically_known; +/// +/// if !is_val_statically_known(0) { unsafe { unreachable_unchecked(); } } +/// ``` +/// +/// This also means that the following code's behavior is unspecified; it +/// may panic, or it may not: +/// +/// ```no_run +/// #![feature(core_intrinsics)] +/// # #![allow(internal_features)] +/// use std::intrinsics::is_val_statically_known; +/// +/// assert_eq!(is_val_statically_known(0), is_val_statically_known(0)); +/// ``` +/// +/// Unsafe code may not rely on `is_val_statically_known` returning any +/// particular value, ever. However, the compiler will generally make it +/// return `true` only if the value of the argument is actually known. +/// +/// # Type Requirements +/// +/// `T` must be either a `bool`, a `char`, a primitive numeric type (e.g. `f32`, +/// but not `NonZeroISize`), or any thin pointer (e.g. `*mut String`). +/// Any other argument types *may* cause a compiler error. +/// +/// ## Pointers +/// +/// When the input is a pointer, only the pointer itself is +/// ever considered. The pointee has no effect. Currently, these functions +/// behave identically: +/// +/// ``` +/// #![feature(core_intrinsics)] +/// # #![allow(internal_features)] +/// use std::intrinsics::is_val_statically_known; +/// +/// fn foo(x: &i32) -> bool { +/// is_val_statically_known(x) +/// } +/// +/// fn bar(x: &i32) -> bool { +/// is_val_statically_known( +/// (x as *const i32).addr() +/// ) +/// } +/// # _ = foo(&5_i32); +/// # _ = bar(&5_i32); +/// ``` +#[rustc_const_stable_indirect] +#[rustc_nounwind] +#[rustc_intrinsic] +pub const fn is_val_statically_known(_arg: T) -> bool { + false +} + +/// Non-overlapping *typed* swap of a single value. +/// +/// The codegen backends will replace this with a better implementation when +/// `T` is a simple type that can be loaded and stored as an immediate. +/// +/// The stabilized form of this intrinsic is [`crate::mem::swap`]. +/// +/// # Safety +/// Behavior is undefined if any of the following conditions are violated: +/// +/// * Both `x` and `y` must be [valid] for both reads and writes. +/// +/// * Both `x` and `y` must be properly aligned. +/// +/// * The region of memory beginning at `x` must *not* overlap with the region of memory +/// beginning at `y`. +/// +/// * The memory pointed by `x` and `y` must both contain values of type `T`. +/// +/// [valid]: crate::ptr#safety +#[rustc_nounwind] +#[inline] +#[rustc_intrinsic] +#[cfg_attr(kani, kani::modifies(x))] +#[cfg_attr(kani, kani::modifies(y))] +#[requires(ub_checks::can_dereference(x) && ub_checks::can_write(x))] +#[requires(ub_checks::can_dereference(y) && ub_checks::can_write(y))] +#[requires(x.addr() != y.addr() || core::mem::size_of::() == 0)] +#[requires(ub_checks::maybe_is_nonoverlapping(x as *const (), y as *const (), const { size_of::() }, 1))] +#[ensures(|_| ub_checks::can_dereference(x) && ub_checks::can_dereference(y))] +pub const unsafe fn typed_swap_nonoverlapping(x: *mut T, y: *mut T) { + // SAFETY: The caller provided single non-overlapping items behind + // pointers, so swapping them with `count: 1` is fine. + unsafe { ptr::swap_nonoverlapping(x, y, 1) }; +} + +/// Returns whether we should perform some UB-checking at runtime. This eventually evaluates to +/// `cfg!(ub_checks)`, but behaves different from `cfg!` when mixing crates built with different +/// flags: if the crate has UB checks enabled or carries the `#[rustc_preserve_ub_checks]` +/// attribute, evaluation is delayed until monomorphization (or until the call gets inlined into +/// a crate that does not delay evaluation further); otherwise it can happen any time. +/// +/// The common case here is a user program built with ub_checks linked against the distributed +/// sysroot which is built without ub_checks but with `#[rustc_preserve_ub_checks]`. +/// For code that gets monomorphized in the user crate (i.e., generic functions and functions with +/// `#[inline]`), gating assertions on `ub_checks()` rather than `cfg!(ub_checks)` means that +/// assertions are enabled whenever the *user crate* has UB checks enabled. However, if the +/// user has UB checks disabled, the checks will still get optimized out. This intrinsic is +/// primarily used by [`crate::ub_checks::assert_unsafe_precondition`]. +/// +/// # Consteval +/// +/// In consteval, this function currently returns `true`. This is because the value of the `ub_checks` +/// configuration can differ across crates, but we need this function to always return the same +/// value in consteval in order to avoid unsoundness. +#[inline(always)] +#[rustc_intrinsic] +pub const fn ub_checks() -> bool { + cfg!(ub_checks) +} + +/// Returns whether we should perform some overflow-checking at runtime. This eventually evaluates to +/// `cfg!(overflow_checks)`, but behaves different from `cfg!` when mixing crates built with different +/// flags: if the crate has overflow checks enabled or carries the `#[rustc_inherit_overflow_checks]` +/// attribute, evaluation is delayed until monomorphization (or until the call gets inlined into +/// a crate that does not delay evaluation further); otherwise it can happen any time. +/// +/// The common case here is a user program built with overflow_checks linked against the distributed +/// sysroot which is built without overflow_checks but with `#[rustc_inherit_overflow_checks]`. +/// For code that gets monomorphized in the user crate (i.e., generic functions and functions with +/// `#[inline]`), gating assertions on `overflow_checks()` rather than `cfg!(overflow_checks)` means that +/// assertions are enabled whenever the *user crate* has overflow checks enabled. However if the +/// user has overflow checks disabled, the checks will still get optimized out. +/// +/// # Consteval +/// +/// In consteval, this function currently returns `true`. This is because the value of the `overflow_checks` +/// configuration can differ across crates, but we need this function to always return the same +/// value in consteval in order to avoid unsoundness. +#[inline(always)] +#[rustc_intrinsic] +pub const fn overflow_checks() -> bool { + cfg!(debug_assertions) +} + +/// Allocates a block of memory at compile time. +/// At runtime, just returns a null pointer. +/// +/// # Safety +/// +/// - The `align` argument must be a power of two. +/// - At compile time, a compile error occurs if this constraint is violated. +/// - At runtime, it is not checked. +#[rustc_const_unstable(feature = "const_heap", issue = "79597")] +#[rustc_nounwind] +#[rustc_intrinsic] +#[miri::intrinsic_fallback_is_spec] +pub const unsafe fn const_allocate(_size: usize, _align: usize) -> *mut u8 { + // const eval overrides this function, but runtime code for now just returns null pointers. + // See . + crate::ptr::null_mut() +} + +/// Deallocates a memory which allocated by `intrinsics::const_allocate` at compile time. +/// At runtime, it does nothing. +/// +/// # Safety +/// +/// - The `align` argument must be a power of two. +/// - At compile time, a compile error occurs if this constraint is violated. +/// - At runtime, it is not checked. +/// - If the `ptr` is created in an another const, this intrinsic doesn't deallocate it. +/// - If the `ptr` is pointing to a local variable, this intrinsic doesn't deallocate it. +#[rustc_const_unstable(feature = "core_intrinsics", issue = "none")] +#[rustc_nounwind] +#[rustc_intrinsic] +#[miri::intrinsic_fallback_is_spec] +pub const unsafe fn const_deallocate(_ptr: *mut u8, _size: usize, _align: usize) { + // Runtime NOP +} + +/// Convert the allocation this pointer points to into immutable global memory. +/// The pointer must point to the beginning of a heap allocation. +/// This operation only makes sense during compile time. At runtime, it does nothing. +#[rustc_const_unstable(feature = "const_heap", issue = "79597")] +#[rustc_nounwind] +#[rustc_intrinsic] +#[miri::intrinsic_fallback_is_spec] +pub const unsafe fn const_make_global(ptr: *mut u8) -> *const u8 { + // const eval overrides this function; at runtime, it is a NOP. + ptr +} + +/// Check if the pre-condition `cond` has been met. +/// +/// By default, if `contract_checks` is enabled, this will panic with no unwind if the condition +/// returns false. +/// +/// Note that this function is a no-op during constant evaluation. +#[unstable(feature = "contracts_internals", issue = "128044")] +// Calls to this function get inserted by an AST expansion pass, which uses the equivalent of +// `#[allow_internal_unstable]` to allow using `contracts_internals` functions. Const-checking +// doesn't honor `#[allow_internal_unstable]`, so for the const feature gate we use the user-facing +// `contracts` feature rather than the perma-unstable `contracts_internals` +#[rustc_const_unstable(feature = "contracts", issue = "128044")] +#[lang = "contract_check_requires"] +#[rustc_intrinsic] +pub const fn contract_check_requires bool + Copy>(cond: C) { + const_eval_select!( + @capture[C: Fn() -> bool + Copy] { cond: C } : + if const { + // Do nothing + } else { + if !cond() { + // Emit no unwind panic in case this was a safety requirement. + crate::panicking::panic_nounwind("failed requires check"); + } + } + ) +} + +/// Check if the post-condition `cond` has been met. +/// +/// By default, if `contract_checks` is enabled, this will panic with no unwind if the condition +/// returns false. +/// +/// If `cond` is `None`, then no postcondition checking is performed. +/// +/// Note that this function is a no-op during constant evaluation. +#[unstable(feature = "contracts_internals", issue = "128044")] +// Similar to `contract_check_requires`, we need to use the user-facing +// `contracts` feature rather than the perma-unstable `contracts_internals`. +// Const-checking doesn't honor allow_internal_unstable logic used by contract expansion. +#[rustc_const_unstable(feature = "contracts", issue = "128044")] +#[lang = "contract_check_ensures"] +#[rustc_intrinsic] +pub const fn contract_check_ensures bool + Copy, Ret>( + cond: Option, + ret: Ret, +) -> Ret { + const_eval_select!( + @capture[C: Fn(&Ret) -> bool + Copy, Ret] { cond: Option, ret: Ret } -> Ret : + if const { + // Do nothing + ret + } else { + if let crate::option::Option::Some(cond) = cond && !cond(&ret) { + // Emit no unwind panic in case this was a safety requirement. + crate::panicking::panic_nounwind("failed ensures check"); + } + ret + } + ) +} + +/// The intrinsic will return the size stored in that vtable. +/// +/// # Safety +/// +/// `ptr` must point to a vtable. +#[rustc_nounwind] +#[rustc_intrinsic] +// VTable pointers must be valid for dereferencing at least 3 `usize` (size, alignment and drop): +// +// TODO: we can no longer do this given https://github.com/model-checking/kani/issues/3325 (this +// function used to have a dummy body, but no longer has since +// https://github.com/rust-lang/rust/pull/137489 has been merged). +// #[requires(ub_checks::can_dereference(_ptr as *const [usize; 3]))] +pub unsafe fn vtable_size(_ptr: *const ()) -> usize; + +/// The intrinsic will return the alignment stored in that vtable. +/// +/// # Safety +/// +/// `ptr` must point to a vtable. +#[rustc_nounwind] +#[rustc_intrinsic] +// VTable pointers must be valid for dereferencing at least 3 `usize` (size, alignment and drop): +// +// TODO: we can no longer do this given https://github.com/model-checking/kani/issues/3325 (this +// function used to have a dummy body, but no longer has since +// https://github.com/rust-lang/rust/pull/137489 has been merged). +// #[requires(ub_checks::can_dereference(_ptr as *const [usize; 3]))] +pub unsafe fn vtable_align(_ptr: *const ()) -> usize; + +/// The size of a type in bytes. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// More specifically, this is the offset in bytes between successive +/// items of the same type, including alignment padding. +/// +/// Note that, unlike most intrinsics, this can only be called at compile-time +/// as backends do not have an implementation for it. The only caller (its +/// stable counterpart) wraps this intrinsic call in a `const` block so that +/// backends only see an evaluated constant. +/// +/// The stabilized version of this intrinsic is [`core::mem::size_of`]. +#[rustc_nounwind] +#[rustc_intrinsic_const_stable_indirect] +#[rustc_intrinsic] +#[rustc_comptime] +pub fn size_of() -> usize; + +/// The minimum alignment of a type. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// Note that, unlike most intrinsics, this can only be called at compile-time +/// as backends do not have an implementation for it. The only caller (its +/// stable counterpart) wraps this intrinsic call in a `const` block so that +/// backends only see an evaluated constant. +/// +/// The stabilized version of this intrinsic is [`core::mem::align_of`]. +#[rustc_nounwind] +#[rustc_intrinsic_const_stable_indirect] +#[rustc_intrinsic] +#[rustc_comptime] +pub fn align_of() -> usize; + +/// The offset of a field inside a type. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// This intrinsic can only be evaluated at compile-time, and should only appear in +/// constants or inline const blocks. +/// +/// The stabilized version of this intrinsic is [`core::mem::offset_of`]. +/// This intrinsic is also a lang item so `offset_of!` can desugar to calls to it. +#[rustc_nounwind] +#[rustc_intrinsic_const_stable_indirect] +#[rustc_intrinsic] +#[lang = "offset_of"] +#[rustc_comptime] +pub fn offset_of(variant: u32, field: u32) -> usize; + +/// The offset of a field queried by its field representing type. +/// +/// Returns the offset of the field represented by `F`. This function essentially does the same as +/// the [`offset_of`] intrinsic, but expects the field to be represented by a generic rather than +/// the variant and field indices. This also is a safe intrinsic and can only be evaluated at +/// compile-time, so it should only appear in constants or inline const blocks. +/// +/// There should be no need to call this intrinsic manually, as its value is used to define +/// [`Field::OFFSET`](crate::field::Field::OFFSET), which is publicly accessible. +#[rustc_intrinsic] +#[rustc_comptime] +pub fn field_offset() -> usize; + +/// Returns the number of variants of the type `T` cast to a `usize`; +/// if `T` has no variants, returns `0`. Uninhabited variants will be counted. +/// +/// Note that, unlike most intrinsics, this can only be called at compile-time +/// as backends do not have an implementation for it. The only caller (its +/// stable counterpart) wraps this intrinsic call in a `const` block so that +/// backends only see an evaluated constant. +/// +/// The to-be-stabilized version of this intrinsic is [`crate::mem::variant_count`]. +#[rustc_nounwind] +#[rustc_intrinsic] +#[rustc_comptime] +pub fn variant_count() -> usize; + +/// The size of the referenced value in bytes. +/// +/// The stabilized version of this intrinsic is [`core::mem::size_of_val`]. +/// +/// # Safety +/// +/// See [`crate::mem::size_of_val_raw`] for safety conditions. +#[rustc_nounwind] +#[rustc_intrinsic] +#[rustc_intrinsic_const_stable_indirect] +pub const unsafe fn size_of_val(ptr: *const T) -> usize; + +/// The required alignment of the referenced value. +/// +/// The stabilized version of this intrinsic is [`core::mem::align_of_val`]. +/// +/// # Safety +/// +/// See [`crate::mem::align_of_val_raw`] for safety conditions. +#[rustc_nounwind] +#[rustc_intrinsic] +#[rustc_intrinsic_const_stable_indirect] +pub const unsafe fn align_of_val(ptr: *const T) -> usize; + +/// Gets a static string slice containing the name of a type. +/// +/// Note that, unlike most intrinsics, this can only be called at compile-time +/// as backends do not have an implementation for it. The only caller (its +/// stable counterpart) wraps this intrinsic call in a `const` block so that +/// backends only see an evaluated constant. +/// +/// The stabilized version of this intrinsic is [`core::any::type_name`]. +#[rustc_nounwind] +#[rustc_intrinsic] +#[rustc_comptime] +pub fn type_name() -> &'static str; + +/// Gets the actual field `TypeId` of the [`FieldRepresentingType`]'s `TypeId`. +/// +/// The more user-friendly version of this intrinsic is [`core::mem::type_info::FieldId::type_id`]. +/// +/// [`FieldRepresentingType`]: crate::field::FieldRepresentingType +#[rustc_intrinsic] +#[rustc_comptime] +pub fn field_representing_type_actual_type_id( + _frt_type_id: crate::any::TypeId, +) -> crate::any::TypeId; + +/// Gets the name of the field represented by the [`FieldRepresentingType`]'s `TypeId`. +/// +/// The more user-friendly version of this intrinsic is [`core::mem::type_info::FieldId::name`]. +/// +/// [`FieldRepresentingType`]: crate::field::FieldRepresentingType +#[rustc_intrinsic] +#[rustc_comptime] +pub fn field_representing_type_name(_frt_type_id: crate::any::TypeId) -> &'static str; + +/// Gets the name of the field represented by the [`FieldRepresentingType`]'s `TypeId`. +/// +/// The more user-friendly version of this intrinsic is [`core::mem::type_info::FieldId::name`]. +/// +/// [`FieldRepresentingType`]: crate::field::FieldRepresentingType +#[rustc_intrinsic] +#[rustc_comptime] +pub fn field_representing_type_offset(_frt_type_id: crate::any::TypeId) -> usize; + +/// Lowers in MIR to `Rvalue::Aggregate` with `AggregateKind::RawPtr`. +/// +/// This is used to implement functions like `slice::from_raw_parts_mut` and +/// `ptr::from_raw_parts` in a way compatible with the compiler being able to +/// change the possible layouts of pointers. +#[rustc_nounwind] +#[rustc_intrinsic_const_stable_indirect] +#[rustc_intrinsic] +pub const fn aggregate_raw_ptr(data: D, meta: M) -> P +where +

::Pointee: ptr::Pointee; + +/// Lowers in MIR to `Rvalue::UnaryOp` with `UnOp::PtrMetadata`. +/// +/// This is used to implement functions like `ptr::metadata`. +#[rustc_nounwind] +#[rustc_intrinsic_const_stable_indirect] +#[rustc_intrinsic] +pub const fn ptr_metadata + PointeeSized, M>(ptr: *const P) -> M; + +/// Return whether the initialization state is preserved. +/// +/// For untyped copy, done via `copy` and `copy_nonoverlapping`, the copies of non-initialized +/// bytes (such as padding bytes) should result in a non-initialized copy, while copies of +/// initialized bytes result in initialized bytes. +/// +/// It is UB to read the uninitialized bytes, so we cannot compare their values only their +/// initialization state. +/// +/// The comparison goes through `ub_checks::can_dereference`, which checks initialization only +/// when Kani runs with `-Z uninit-checks`. Without that flag, as in CI, `can_dereference` treats +/// every byte as initialized, so this function does not check initialization. +/// +/// This is used for contracts only. +#[allow(dead_code)] +#[allow(unused_variables)] +fn check_copy_untyped(src: *const T, dst: *mut T, count: usize) -> bool { + #[cfg(kani)] + if count > 0 { + // Inspect a non-deterministically chosen byte in the copy. + let byte = kani::any_where(|sz: &usize| *sz < const { size_of::() }); + // Instead of checking each of the `count`-many copies, non-deterministically pick one of + // them and check it. Using quantifiers would not add value as we can rely on the solver to + // pick an uninitialized element if such an element exists. + let elem = kani::any_where(|val: &usize| *val < count); + // Offset *both* sides by `elem`: comparing `dst[elem]` against `src[0]` + // would be wrong whenever initialization differs across elements. + // (Oracle fix independently found by #643.) + let src_data = unsafe { src.add(elem) } as *const u8; + let dst_data = unsafe { dst.add(elem) } as *const u8; + ub_checks::can_dereference(unsafe { src_data.add(byte) }) + == ub_checks::can_dereference(unsafe { dst_data.add(byte) }) + } else { + true + } + #[cfg(not(kani))] + false +} + +/// This is an accidentally-stable alias to [`ptr::copy_nonoverlapping`]; use that instead. +// Note (intentionally not in the doc comment): `ptr::copy_nonoverlapping` adds some extra +// debug assertions; if you are writing compiler tests or code inside the standard library +// that wants to avoid those debug assertions, directly call this intrinsic instead. +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_allowed_through_unstable_modules( + message = "import this function via the `ptr` module instead", + module = "ptr" +)] +#[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")] +#[rustc_nounwind] +#[rustc_intrinsic] +// Copy is "untyped". +// TODO: we can no longer do this given https://github.com/model-checking/kani/issues/3325 (this +// function used to have a dummy body, but no longer has) +// #[cfg_attr(kani, kani::modifies(crate::ptr::slice_from_raw_parts(dst, count)))] +// #[requires(!count.overflowing_mul(size_of::()).1 +// && ub_checks::can_dereference(core::ptr::slice_from_raw_parts(src as *const crate::mem::MaybeUninit, count)) +// && ub_checks::can_write(core::ptr::slice_from_raw_parts_mut(dst, count)) +// && ub_checks::maybe_is_nonoverlapping(src as *const (), dst as *const (), size_of::(), count))] +// #[ensures(|_| { check_copy_untyped(src, dst, count)})] +pub const unsafe fn copy_nonoverlapping(src: *const T, dst: *mut T, count: usize); + +/// This is an accidentally-stable alias to [`ptr::copy`]; use that instead. +// Note (intentionally not in the doc comment): `ptr::copy` adds some extra +// debug assertions; if you are writing compiler tests or code inside the standard library +// that wants to avoid those debug assertions, directly call this intrinsic instead. +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_allowed_through_unstable_modules( + message = "import this function via the `ptr` module instead", + module = "ptr" +)] +#[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")] +#[rustc_nounwind] +#[rustc_intrinsic] +// TODO: we can no longer do this given https://github.com/model-checking/kani/issues/3325 (this +// function used to have a dummy body, but no longer has) +// #[requires(!count.overflowing_mul(size_of::()).1 +// && ub_checks::can_dereference(core::ptr::slice_from_raw_parts(src as *const crate::mem::MaybeUninit, count)) +// && ub_checks::can_write(core::ptr::slice_from_raw_parts_mut(dst, count)))] +// #[ensures(|_| { check_copy_untyped(src, dst, count) })] +// #[cfg_attr(kani, kani::modifies(crate::ptr::slice_from_raw_parts(dst, count)))] +pub const unsafe fn copy(src: *const T, dst: *mut T, count: usize); + +/// This is an accidentally-stable alias to [`ptr::write_bytes`]; use that instead. +// Note (intentionally not in the doc comment): `ptr::write_bytes` adds some extra +// debug assertions; if you are writing compiler tests or code inside the standard library +// that wants to avoid those debug assertions, directly call this intrinsic instead. +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_allowed_through_unstable_modules( + message = "import this function via the `ptr` module instead", + module = "ptr" +)] +#[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")] +#[rustc_nounwind] +#[rustc_intrinsic] +// TODO: we can no longer do this given https://github.com/model-checking/kani/issues/3325 (this +// function used to have a dummy body, but no longer has) +// #[requires(!count.overflowing_mul(size_of::()).1 +// && ub_checks::can_write(core::ptr::slice_from_raw_parts_mut(dst, count)))] +// #[requires(ub_checks::maybe_is_aligned_and_not_null(dst as *const (), align_of::(), T::IS_ZST || count == 0))] +// #[ensures(|_| +// ub_checks::can_dereference(crate::ptr::slice_from_raw_parts(dst as *const u8, count * size_of::())))] +// #[cfg_attr(kani, kani::modifies(crate::ptr::slice_from_raw_parts(dst, count)))] +pub const unsafe fn write_bytes(dst: *mut T, val: u8, count: usize); + +/// Returns the minimum of two floating-point values, ignoring NaN. +/// +/// This behaves like IEEE 754-2019 minimumNumber, *except* that it does not order signed +/// zeros deterministically. In particular: +/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If +/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0` +/// and `-0.0`), either input may be returned non-deterministically. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// The stabilized versions of this intrinsic are available on the float primitives via the +/// `min` method. For example, [`f32::min`]. +#[rustc_nounwind] +#[rustc_intrinsic_const_stable_indirect] +#[rustc_intrinsic] +#[rustc_do_not_const_check] +pub const fn minimum_number_nsz(x: T, y: T) -> T { + if x.is_nan() || y <= x { + y + } else { + // Either y > x or y is a NaN. + x + } +} + +/// Returns the maximum of two floating-point values, ignoring NaN. +/// +/// This behaves like IEEE 754-2019 maximumNumber, *except* that it does not order signed +/// zeros deterministically. In particular: +/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If +/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0` +/// and `-0.0`), either input may be returned non-deterministically. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// The stabilized versions of this intrinsic are available on the float primitives via the +/// `max` method. For example, [`f32::max`]. +#[rustc_nounwind] +#[rustc_intrinsic_const_stable_indirect] +#[rustc_intrinsic] +#[rustc_do_not_const_check] +pub const fn maximum_number_nsz(x: T, y: T) -> T { + if x.is_nan() || y >= x { + y + } else { + // Either y < x or y is a NaN. + x + } +} + +/// Returns the minimum of two floating-point values, propagating NaN. +/// +/// This behaves like IEEE 754-2019 minimum. In particular: +/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules. +/// For this operation, -0.0 is considered to be strictly less than +0.0. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +#[rustc_nounwind] +#[rustc_const_unstable(feature = "core_intrinsics", issue = "none")] +#[rustc_intrinsic] +#[rustc_do_not_const_check] +pub const fn minimum(x: T, y: T) -> T { + if x < y { + x + } else if y < x { + y + } else if x == y { + if x.is_sign_negative() && y.is_sign_positive() { x } else { y } + } else { + // At least one input is NaN. Use `+` to perform NaN propagation and quieting. + x + y + } +} + +/// Returns the maximum of two floating-point values, propagating NaN. +/// +/// This behaves like IEEE 754-2019 maximum. In particular: +/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules. +/// For this operation, -0.0 is considered to be strictly less than +0.0. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +#[rustc_nounwind] +#[rustc_const_unstable(feature = "core_intrinsics", issue = "none")] +#[rustc_intrinsic] +#[rustc_do_not_const_check] +pub const fn maximum(x: T, y: T) -> T { + if x > y { + x + } else if y > x { + y + } else if x == y { + if x.is_sign_positive() && y.is_sign_negative() { x } else { y } + } else { + // At least one input is NaN. Use `+` to perform NaN propagation and quieting. + x + y + } +} + +/// Returns the absolute value of a floating-point value. +/// +/// The stabilized versions of this intrinsic are available on the float +/// primitives via the `abs` method. For example, [`f32::abs`]. +#[rustc_nounwind] +#[rustc_intrinsic] +#[rustc_intrinsic_const_stable_indirect] +#[rustc_do_not_const_check] // Use built-in impl to avoid const-checks in the fallback body. +#[miri::intrinsic_fallback_is_spec] +pub const fn fabs(x: T) -> T { + T::from_bits(x.to_bits() & !T::SIGN_MASK) +} + +/// Copies the sign from `y` to `x` for floating-point values. +/// +/// The stabilized versions of this intrinsic are available on the float +/// primitives via the `copysign` method. For example, [`f32::copysign`]. +#[inline] +#[rustc_nounwind] +#[rustc_intrinsic_const_stable_indirect] +#[rustc_intrinsic] +#[rustc_do_not_const_check] +#[miri::intrinsic_fallback_is_spec] +pub const fn copysign(x: T, y: T) -> T { + T::from_bits((x.to_bits() & !T::SIGN_MASK) | (y.to_bits() & T::SIGN_MASK)) +} + +/// Generates the LLVM body for the automatic differentiation of `f` using Enzyme, +/// with `df` as the derivative function and `args` as its arguments. +/// +/// Used internally as the body of `df` when expanding the `#[autodiff_forward]` +/// and `#[autodiff_reverse]` attribute macros. +/// +/// Type Parameters: +/// - `F`: The original function to differentiate. Must be a function item. +/// - `G`: The derivative function. Must be a function item. +/// - `T`: A tuple of arguments passed to `df`. +/// - `R`: The return type of the derivative function. +/// +/// This shows where the `autodiff` intrinsic is used during macro expansion: +/// +/// ```rust,ignore (macro example) +/// #[autodiff_forward(df1, Dual, Const, Dual)] +/// pub fn f1(x: &[f64], y: f64) -> f64 { +/// unimplemented!() +/// } +/// ``` +/// +/// expands to: +/// +/// ```rust,ignore (macro example) +/// #[rustc_autodiff] +/// #[inline(never)] +/// pub fn f1(x: &[f64], y: f64) -> f64 { +/// ::core::panicking::panic("not implemented") +/// } +/// #[rustc_autodiff(Forward, 1, Dual, Const, Dual)] +/// pub fn df1(x: &[f64], bx_0: &[f64], y: f64) -> (f64, f64) { +/// ::core::intrinsics::autodiff(f1::<>, df1::<>, (x, bx_0, y)) +/// } +/// ``` +#[rustc_nounwind] +#[rustc_intrinsic] +pub const fn autodiff(f: F, df: G, args: T) -> R; + +/// Generates the LLVM body of a wrapper function to offload a kernel `f`. +/// +/// Type Parameters: +/// - `F`: The kernel to offload. Must be a function item. +/// - `T`: A tuple of arguments passed to `f`. +/// - `R`: The return type of the kernel. +/// +/// Arguments: +/// - `f`: The kernel function to offload. +/// - `workgroup_dim`: A 3D size specifying the number of workgroups to launch. +/// - `thread_dim`: A 3D size specifying the number of threads per workgroup. +/// - `dyn_cache`: The amount of dynamic shared memory to request for the kernel. +/// - `device_id`: The device to offload to. Use `-1` to select the default device. +/// - `args`: A tuple of arguments forwarded to `f`. +/// +/// Example usage (pseudocode): +/// +/// ```rust,ignore (pseudocode) +/// fn kernel(x: *mut [f64; 128]) { +/// core::intrinsics::offload(kernel_1, [256, 1, 1], [32, 1, 1], 0, -1, (x,)) +/// } +/// +/// #[cfg(target_os = "linux")] +/// extern "C" { +/// pub fn kernel_1(array_b: *mut [f64; 128]); +/// } +/// +/// #[cfg(not(target_os = "linux"))] +/// #[rustc_offload_kernel] +/// extern "gpu-kernel" fn kernel_1(x: *mut [f64; 128]) { +/// unsafe { (*x)[0] = 21.0 }; +/// } +/// ``` +/// +/// For reference, see the Clang documentation on offloading: +/// . +#[rustc_nounwind] +#[rustc_intrinsic] +pub const fn offload( + f: F, + workgroup_dim: [u32; 3], + thread_dim: [u32; 3], + dyn_cache: u32, + device_id: i32, + args: T, +) -> R; + +/// Returns the number of offload devices available on the system. +/// +/// Use this to discover which `device_id` values are valid to pass to +/// [`offload`]. Devices are numbered from `0` to the returned value minus one. +/// +/// Returns `0` if no offloading devices are present. +#[rustc_nounwind] +#[rustc_intrinsic] +pub const fn offload_get_num_devices() -> i32; + +/// Inform Miri that a given pointer definitely has a certain alignment. +#[cfg(miri)] +#[rustc_allow_const_fn_unstable(const_eval_select)] +pub(crate) const fn miri_promise_symbolic_alignment(ptr: *const (), align: usize) { + unsafe extern "Rust" { + /// Miri-provided extern function to promise that a given pointer is properly aligned for + /// "symbolic" alignment checks. Will fail if the pointer is not actually aligned or `align` is + /// not a power of two. Has no effect when alignment checks are concrete (which is the default). + fn miri_promise_symbolic_alignment(ptr: *const (), align: usize); + } + + const_eval_select!( + @capture { ptr: *const (), align: usize}: + if const { + // Do nothing. + } else { + // SAFETY: this call is always safe. + unsafe { + miri_promise_symbolic_alignment(ptr, align); + } + } + ) +} + +/// Loads an argument of type `T` from the `va_list` `ap` and increment the +/// argument `ap` points to. +/// +/// # Safety +/// +/// This function is only sound to call when: +/// +/// - there is a next variable argument available. +/// - the next argument's type must be ABI-compatible with the type `T`. +/// - the next argument must have a properly initialized value of type `T`. +/// +/// Calling this function with an incompatible type, an invalid value, or when there +/// are no more variable arguments, is unsound. +/// +#[rustc_intrinsic] +#[rustc_nounwind] +pub const unsafe fn va_arg(ap: &mut VaList<'_>) -> T; + +/// Duplicates a variable argument list. The returned list is initially at the same position as +/// the one in `src`, but can be advanced independently. +/// +/// Codegen backends should not have custom behavior for this intrinsic, they should always use +/// this fallback implementation. This intrinsic *does not* map to the LLVM `va_copy` intrinsic. +/// +/// This intrinsic exists only as a hook for Miri and constant evaluation, and is used to detect UB +/// when a variable argument list is used incorrectly. +#[rustc_intrinsic] +#[rustc_nounwind] +pub const fn va_copy<'f>(src: &VaList<'f>) -> VaList<'f> { + // This fallback body exploits the fact that our codegen backends all just use + // a plain memcpy to duplicate VaList. This assumption is wrong for Miri. + assert!(!cfg!(miri), "fallback body is incorrect under Miri"); + + src.duplicate() +} + +/// Destroy the variable argument list `ap` after initialization with `va_start` (part of the +/// desugaring of `...`) or `va_copy`. +/// +/// Code generation backends should not provide a custom implementation for this intrinsic. This +/// intrinsic *does not* map to the LLVM `va_end` intrinsic. +/// +/// This function is a no-op on all current targets, but used as a hook for const evaluation to +/// detect UB when a variable argument list is used incorrectly. +/// +/// # Safety +/// +/// `ap` must not be used to access variable arguments after this call. +/// +#[rustc_intrinsic] +#[rustc_nounwind] +pub const unsafe fn va_end(ap: &mut VaList<'_>) { + /* deliberately does nothing */ +} + +#[cfg(kani)] +#[unstable(feature = "kani", issue = "none")] +mod verify { + use core::mem::MaybeUninit; + + use kani::{AllocationStatus, Arbitrary, ArbitraryPointer, PointerGenerator}; + + use super::*; + use crate::kani; + + #[kani::proof_for_contract(typed_swap_nonoverlapping)] + pub fn check_typed_swap_u8() { + run_with_arbitrary_ptrs::(|x, y| unsafe { typed_swap_nonoverlapping(x, y) }); + } + + #[kani::proof_for_contract(typed_swap_nonoverlapping)] + pub fn check_typed_swap_char() { + run_with_arbitrary_ptrs::(|x, y| unsafe { typed_swap_nonoverlapping(x, y) }); + } + + #[kani::proof_for_contract(typed_swap_nonoverlapping)] + pub fn check_typed_swap_non_zero() { + run_with_arbitrary_ptrs::(|x, y| unsafe { + typed_swap_nonoverlapping(x, y) + }); + } + + // ---- vtable_size ---- + // Wrapper pattern, used throughout: Kani cannot attach contracts to body-less + // `#[rustc_intrinsic]`s (rust-lang/rust#137489, model-checking/kani#3325), so + // each contract lives on a thin wrapper (or `*_model`) fn; harnesses verify that. + // `[usize; 3]`: vtable = (size, align, drop-in-place), per rust-lang/unsafe-code-guidelines#166. + #[requires(ub_checks::can_dereference(ptr as *const [usize; 3]))] + #[ensures(|result: &usize| *result <= isize::MAX as usize)] + #[allow(dead_code)] + unsafe fn vtable_size_wrapper(ptr: *const ()) -> usize { + // SAFETY: guaranteed by the precondition (`ptr` points to a vtable). + unsafe { vtable_size(ptr) } + } + + // Real vtable pointer via `dyn Debug`; the `assert_eq!` pins Kani's model + // and witnesses non-vacuity. + macro_rules! check_vtable_size_for { + ($harness:ident, $ty:ty) => { + #[kani::proof_for_contract(vtable_size_wrapper)] + fn $harness() { + let val: $ty = kani::any(); + let obj: &dyn core::fmt::Debug = &val; + let fat: *const dyn core::fmt::Debug = obj; + let meta = core::ptr::metadata(fat); + // Same transmute `DynMetadata::vtable_ptr` performs (layout-compatible). + let vptr = unsafe { + core::mem::transmute::, *const ()>( + meta, + ) + }; + let size = unsafe { vtable_size_wrapper(vptr) }; + kani::cover(true, "vtable_size call is reachable"); + assert_eq!(size, core::mem::size_of::<$ty>()); + } + }; + } + + check_vtable_size_for!(check_vtable_size_u8, u8); + check_vtable_size_for!(check_vtable_size_u32, u32); + check_vtable_size_for!(check_vtable_size_u64, u64); + check_vtable_size_for!(check_vtable_size_i128, i128); + + // ---- vtable_align ---- + // As `vtable_size`; the ensures encodes non-zero power of two. + #[requires(ub_checks::can_dereference(ptr as *const [usize; 3]))] + #[ensures(|result: &usize| result.is_power_of_two())] + #[allow(dead_code)] + unsafe fn vtable_align_wrapper(ptr: *const ()) -> usize { + // SAFETY: guaranteed by the precondition (`ptr` points to a vtable). + unsafe { vtable_align(ptr) } + } + + macro_rules! check_vtable_align_for { + ($harness:ident, $ty:ty) => { + #[kani::proof_for_contract(vtable_align_wrapper)] + fn $harness() { + let val: $ty = kani::any(); + let obj: &dyn core::fmt::Debug = &val; + let fat: *const dyn core::fmt::Debug = obj; + let meta = core::ptr::metadata(fat); + // Same transmute `DynMetadata::vtable_ptr` performs. + let vptr = unsafe { + core::mem::transmute::, *const ()>( + meta, + ) + }; + let align = unsafe { vtable_align_wrapper(vptr) }; + kani::cover(true, "vtable_align call is reachable"); + assert_eq!(align, core::mem::align_of::<$ty>()); + } + }; + } + + check_vtable_align_for!(check_vtable_align_u8, u8); + check_vtable_align_for!(check_vtable_align_u32, u32); + check_vtable_align_for!(check_vtable_align_u64, u64); + check_vtable_align_for!(check_vtable_align_i128, i128); + + // ---- size_of_val ---- + // Kani models this intrinsic (no fallback body); harness asserts pin it. + // `size_of_val_raw` documents per-case safety, so each case gets its own + // wrapper: `Sized` is always safe; a slice needs total size <= `isize::MAX`. + #[ensures(|result: &usize| *result <= isize::MAX as usize)] + #[allow(dead_code)] + unsafe fn size_of_val_sized_wrapper(ptr: *const T) -> usize { + // SAFETY: `Sized` case never reads `*ptr`; safe for any pointer. + unsafe { size_of_val(ptr) } + } + + // Division-first so the check never overflows; a ZST element makes it 0. + #[requires(crate::mem::size_of::() == 0 || ptr.len() <= (isize::MAX as usize) / crate::mem::size_of::())] + #[ensures(|result: &usize| *result <= isize::MAX as usize)] + #[allow(dead_code)] + unsafe fn size_of_val_slice_wrapper(ptr: *const [E]) -> usize { + // SAFETY: only the length metadata is read; precondition bounds the size. + unsafe { size_of_val(ptr) } + } + + // Model must return `size_of::()`, pointer-independent. + macro_rules! check_size_of_val_sized_for { + ($harness:ident, $ty:ty) => { + #[kani::proof_for_contract(size_of_val_sized_wrapper)] + fn $harness() { + let val: $ty = kani::any(); + let ptr: *const $ty = &val; + let size = unsafe { size_of_val_sized_wrapper(ptr) }; + kani::cover(true, "size_of_val (sized) call is reachable"); + assert_eq!(size, core::mem::size_of::<$ty>()); + } + }; + } + + check_size_of_val_sized_for!(check_size_of_val_u8, u8); + check_size_of_val_sized_for!(check_size_of_val_u32, u32); + check_size_of_val_sized_for!(check_size_of_val_u64, u64); + check_size_of_val_sized_for!(check_size_of_val_i128, i128); + check_size_of_val_sized_for!(check_size_of_val_char, char); + + // In-bounds `len` over a real array; model must return `len * size_of::()`. + macro_rules! check_size_of_val_slice_for { + ($harness:ident, $ty:ty) => { + #[kani::proof_for_contract(size_of_val_slice_wrapper)] + fn $harness() { + const N: usize = 4; + let arr: [$ty; N] = kani::any(); + let len: usize = kani::any_where(|l: &usize| *l <= N); + let ptr: *const [$ty] = core::ptr::slice_from_raw_parts(arr.as_ptr(), len); + let size = unsafe { size_of_val_slice_wrapper(ptr) }; + kani::cover(len > 0, "size_of_val measures a non-empty slice"); + assert_eq!(size, len * core::mem::size_of::<$ty>()); + } + }; + } + + check_size_of_val_slice_for!(check_size_of_val_slice_u8, u8); + check_size_of_val_slice_for!(check_size_of_val_slice_u32, u32); + check_size_of_val_slice_for!(check_size_of_val_slice_i64, i64); + + // ---- align_of_val (historically `min_align_of_val`) ---- + // Same modeling and per-case wrapper split as `size_of_val`; the slice + // contract keeps the documented size-fits-`isize` condition. + #[ensures(|result: &usize| result.is_power_of_two())] + #[allow(dead_code)] + unsafe fn align_of_val_sized_wrapper(ptr: *const T) -> usize { + // SAFETY: `Sized` case never reads `*ptr`; safe for any pointer. + unsafe { align_of_val(ptr) } + } + + #[requires(crate::mem::size_of::() == 0 || ptr.len() <= (isize::MAX as usize) / crate::mem::size_of::())] + #[ensures(|result: &usize| result.is_power_of_two())] + #[allow(dead_code)] + unsafe fn align_of_val_slice_wrapper(ptr: *const [E]) -> usize { + // SAFETY: only the length metadata is read; precondition bounds the size. + unsafe { align_of_val(ptr) } + } + + // Model must return `align_of::()`, pointer-independent. + macro_rules! check_align_of_val_sized_for { + ($harness:ident, $ty:ty) => { + #[kani::proof_for_contract(align_of_val_sized_wrapper)] + fn $harness() { + let val: $ty = kani::any(); + let ptr: *const $ty = &val; + let align = unsafe { align_of_val_sized_wrapper(ptr) }; + kani::cover(true, "align_of_val (sized) call is reachable"); + assert_eq!(align, core::mem::align_of::<$ty>()); + } + }; + } + + check_align_of_val_sized_for!(check_align_of_val_u8, u8); + check_align_of_val_sized_for!(check_align_of_val_u32, u32); + check_align_of_val_sized_for!(check_align_of_val_u64, u64); + check_align_of_val_sized_for!(check_align_of_val_i128, i128); + check_align_of_val_sized_for!(check_align_of_val_char, char); + + // In-bounds `len`; model must return `align_of::()` regardless of `len`. + macro_rules! check_align_of_val_slice_for { + ($harness:ident, $ty:ty) => { + #[kani::proof_for_contract(align_of_val_slice_wrapper)] + fn $harness() { + const N: usize = 4; + let arr: [$ty; N] = kani::any(); + let len: usize = kani::any_where(|l: &usize| *l <= N); + let ptr: *const [$ty] = core::ptr::slice_from_raw_parts(arr.as_ptr(), len); + let align = unsafe { align_of_val_slice_wrapper(ptr) }; + kani::cover(len > 0, "align_of_val measures a non-empty slice"); + assert_eq!(align, core::mem::align_of::<$ty>()); + } + }; + } + + check_align_of_val_slice_for!(check_align_of_val_slice_u8, u8); + check_align_of_val_slice_for!(check_align_of_val_slice_u32, u32); + check_align_of_val_slice_for!(check_align_of_val_slice_i64, i64); + + // ---- size_of_val / align_of_val: trait-object (`dyn`) tails ---- + // Third documented case of `size_of_val_raw` / `align_of_val_raw`: the + // vtable must be valid. Kani has no vtable predicate, so (exactly as for + // `vtable_size_wrapper`) dereferenceability of the three metadata words is + // the necessary approximation; harnesses supply real compiler-produced + // vtables, so the precondition is satisfied non-vacuously. + #[allow(dead_code)] + fn dyn_vtable_ptr(ptr: *const dyn core::fmt::Debug) -> *const () { + let meta = core::ptr::metadata(ptr); + // Same transmute `DynMetadata::vtable_ptr` performs (layout-compatible). + unsafe { + core::mem::transmute::, *const ()>(meta) + } + } + + #[requires(ub_checks::can_dereference(dyn_vtable_ptr(ptr) as *const [usize; 3]))] + #[ensures(|result: &usize| *result <= isize::MAX as usize)] + #[allow(dead_code)] + unsafe fn size_of_val_dyn_wrapper(ptr: *const dyn core::fmt::Debug) -> usize { + // SAFETY: only the vtable is read; readable by the precondition. + unsafe { size_of_val(ptr) } + } + + #[requires(ub_checks::can_dereference(dyn_vtable_ptr(ptr) as *const [usize; 3]))] + #[ensures(|result: &usize| result.is_power_of_two())] + #[allow(dead_code)] + unsafe fn align_of_val_dyn_wrapper(ptr: *const dyn core::fmt::Debug) -> usize { + // SAFETY: only the vtable is read; readable by the precondition. + unsafe { align_of_val(ptr) } + } + + // Erased-type fidelity: the model must return the *underlying* type's + // size/align through the vtable, not a fixture value. + macro_rules! check_size_of_val_dyn_for { + ($harness:ident, $ty:ty) => { + #[kani::proof_for_contract(size_of_val_dyn_wrapper)] + fn $harness() { + let val: $ty = kani::any(); + let obj: &dyn core::fmt::Debug = &val; + let size = unsafe { size_of_val_dyn_wrapper(obj) }; + kani::cover(true, "size_of_val (dyn) call is reachable"); + assert_eq!(size, core::mem::size_of::<$ty>()); + } + }; + } + + check_size_of_val_dyn_for!(check_size_of_val_dyn_u8, u8); + check_size_of_val_dyn_for!(check_size_of_val_dyn_u32, u32); + check_size_of_val_dyn_for!(check_size_of_val_dyn_i128, i128); + + macro_rules! check_align_of_val_dyn_for { + ($harness:ident, $ty:ty) => { + #[kani::proof_for_contract(align_of_val_dyn_wrapper)] + fn $harness() { + let val: $ty = kani::any(); + let obj: &dyn core::fmt::Debug = &val; + let align = unsafe { align_of_val_dyn_wrapper(obj) }; + kani::cover(true, "align_of_val (dyn) call is reachable"); + assert_eq!(align, core::mem::align_of::<$ty>()); + } + }; + } + + check_align_of_val_dyn_for!(check_align_of_val_dyn_u8, u8); + check_align_of_val_dyn_for!(check_align_of_val_dyn_u32, u32); + check_align_of_val_dyn_for!(check_align_of_val_dyn_i128, i128); + + // ---- copy_nonoverlapping ---- + // Restores the pre-body-removal contract. `MaybeUninit` because the copy is + // untyped; the ensures compares per-byte initialization state, which Kani + // checks only with `-Z uninit-checks` (see `check_copy_untyped`). + #[requires(!count.overflowing_mul(crate::mem::size_of::()).1 + && ub_checks::can_dereference(core::ptr::slice_from_raw_parts(src as *const crate::mem::MaybeUninit, count)) + && ub_checks::can_write(core::ptr::slice_from_raw_parts_mut(dst, count)) + && ub_checks::maybe_is_nonoverlapping(src as *const (), dst as *const (), crate::mem::size_of::(), count))] + #[ensures(|_| check_copy_untyped(src, dst, count))] + #[cfg_attr(kani, kani::modifies(crate::ptr::slice_from_raw_parts(dst, count)))] + #[allow(dead_code)] + unsafe fn copy_nonoverlapping_wrapper(src: *const T, dst: *mut T, count: usize) { + // SAFETY: guaranteed by the precondition. + unsafe { copy_nonoverlapping(src, dst, count) } + } + + // No `ArbitraryPointer`: it initializes memory via the function under + // verification. Non-deterministic `src` init gives the untyped-copy ensures + // teeth; `dst` may alias `buffer1` so non-overlap is genuinely exercised. + macro_rules! check_copy_nonoverlapping_for { + ($harness:ident, $ty:ty) => { + #[kani::proof_for_contract(copy_nonoverlapping_wrapper)] + fn $harness() { + const N: usize = 100; + let gen_any_ptr = |buf: &mut [MaybeUninit<$ty>; N]| -> *mut $ty { + let base = buf.as_mut_ptr() as *mut u8; + base.wrapping_add(kani::any_where(|o: &usize| { + *o < N * core::mem::size_of::<$ty>() + })) as *mut $ty + }; + let mut buffer1 = [MaybeUninit::<$ty>::uninit(); N]; + for i in 0..N { + if kani::any() { + buffer1[i] = MaybeUninit::new(kani::any()); + } + } + let mut buffer2 = [MaybeUninit::<$ty>::uninit(); N]; + let src = gen_any_ptr(&mut buffer1) as *const $ty; + let dst = + if kani::any() { gen_any_ptr(&mut buffer2) } else { gen_any_ptr(&mut buffer1) }; + let count: usize = kani::any(); + kani::cover(count > 0, "copy_nonoverlapping copies a non-empty range"); + unsafe { copy_nonoverlapping_wrapper(src, dst, count) }; + } + }; + } + + check_copy_nonoverlapping_for!(check_copy_nonoverlapping_u8, u8); + check_copy_nonoverlapping_for!(check_copy_nonoverlapping_char, char); + check_copy_nonoverlapping_for!(check_copy_nonoverlapping_u32, u32); + + // ---- copy ---- + // Memmove: overlap permitted, so `copy_nonoverlapping`'s contract minus the + // non-overlap clause. + #[requires(!count.overflowing_mul(crate::mem::size_of::()).1 + && ub_checks::can_dereference(core::ptr::slice_from_raw_parts(src as *const crate::mem::MaybeUninit, count)) + && ub_checks::can_write(core::ptr::slice_from_raw_parts_mut(dst, count)))] + #[ensures(|_| check_copy_untyped(src, dst, count))] + #[cfg_attr(kani, kani::modifies(crate::ptr::slice_from_raw_parts(dst, count)))] + #[allow(dead_code)] + unsafe fn copy_wrapper(src: *const T, dst: *mut T, count: usize) { + // SAFETY: guaranteed by the precondition. + unsafe { copy(src, dst, count) } + } + + // Same setup as `copy_nonoverlapping`, but the aliasing `dst` now exercises + // the overlapping case `copy` permits. + macro_rules! check_copy_for { + ($harness:ident, $ty:ty) => { + #[kani::proof_for_contract(copy_wrapper)] + fn $harness() { + const N: usize = 100; + let gen_any_ptr = |buf: &mut [MaybeUninit<$ty>; N]| -> *mut $ty { + let base = buf.as_mut_ptr() as *mut u8; + base.wrapping_add(kani::any_where(|o: &usize| { + *o < N * core::mem::size_of::<$ty>() + })) as *mut $ty + }; + let mut buffer1 = [MaybeUninit::<$ty>::uninit(); N]; + for i in 0..N { + if kani::any() { + buffer1[i] = MaybeUninit::new(kani::any()); + } + } + let mut buffer2 = [MaybeUninit::<$ty>::uninit(); N]; + let src = gen_any_ptr(&mut buffer1) as *const $ty; + // `dst` may alias `buffer1` (overlap is permitted by `copy`). + let dst = + if kani::any() { gen_any_ptr(&mut buffer2) } else { gen_any_ptr(&mut buffer1) }; + let count: usize = kani::any(); + kani::cover(count > 0, "copy copies a non-empty range"); + unsafe { copy_wrapper(src, dst, count) }; + } + }; + } + + check_copy_for!(check_copy_u8, u8); + check_copy_for!(check_copy_char, char); + check_copy_for!(check_copy_u32, u32); + + // ---- write_bytes ---- + // C `memset`; contract is the pre-body-removal one. Supersedes the old + // harness parked on . + // Ensures is over `*const u8`: arbitrary `val` bytes need not form a valid `T`. + #[requires(!count.overflowing_mul(crate::mem::size_of::()).1 + && ub_checks::can_write(core::ptr::slice_from_raw_parts_mut(dst, count)))] + #[requires(ub_checks::maybe_is_aligned_and_not_null( + dst as *const (), + crate::mem::align_of::(), + crate::mem::size_of::() == 0 || count == 0, + ))] + #[ensures(|_| ub_checks::can_dereference( + core::ptr::slice_from_raw_parts(dst as *const u8, count * crate::mem::size_of::())))] + #[cfg_attr(kani, kani::modifies(crate::ptr::slice_from_raw_parts(dst, count)))] + #[allow(dead_code)] + unsafe fn write_bytes_wrapper(dst: *mut T, val: u8, count: usize) { + // SAFETY: guaranteed by the precondition. + unsafe { write_bytes(dst, val, count) } + } + + // `dst` stays inside a real stack allocation; the byte-granular offset + // generates misaligned pointers the alignment clause must prune. + macro_rules! check_write_bytes_for { + ($harness:ident, $ty:ty) => { + #[kani::proof_for_contract(write_bytes_wrapper)] + fn $harness() { + const N: usize = 100; + let mut buffer = [MaybeUninit::<$ty>::uninit(); N]; + let base = buffer.as_mut_ptr() as *mut u8; + let dst = base + .wrapping_add(kani::any_where(|o: &usize| *o < N * core::mem::size_of::<$ty>())) + as *mut $ty; + let val: u8 = kani::any(); + let count: usize = kani::any(); + kani::cover(count > 0, "write_bytes writes a non-empty range"); + unsafe { write_bytes_wrapper(dst, val, count) }; + } + }; + } + + check_write_bytes_for!(check_write_bytes_u8, u8); + check_write_bytes_for!(check_write_bytes_char, char); + check_write_bytes_for!(check_write_bytes_u32, u32); + + //We need this wrapper because transmute_unchecked is an intrinsic, for which Kani does + //not currently support contracts (https://github.com/model-checking/kani/issues/3345) + #[requires(crate::mem::size_of::() == crate::mem::size_of::())] //T and U have same size (transmute_unchecked does not guarantee this) + #[requires(ub_checks::can_dereference(&input as *const T as *const U))] //output can be deref'd as value of type U + #[allow(dead_code)] + unsafe fn transmute_unchecked_wrapper(input: T) -> U { + unsafe { transmute_unchecked(input) } + } + + //generates harness that transmutes arbitrary values of input type to output type + macro_rules! proof_of_contract_for_transmute_unchecked { + ($harness:ident, $src:ty, $dst:ty) => { + #[kani::proof_for_contract(transmute_unchecked_wrapper)] + fn $harness() { + let src: $src = kani::any(); + let dst: $dst = unsafe { transmute_unchecked_wrapper(src) }; + } + }; + } + + //We check the contract for all combinations of primitives + //transmute between 1-byte primitives + proof_of_contract_for_transmute_unchecked!(transmute_unchecked_i8_to_u8, i8, u8); + proof_of_contract_for_transmute_unchecked!(transmute_unchecked_u8_to_i8, u8, i8); + proof_of_contract_for_transmute_unchecked!(transmute_unchecked_bool_to_i8, bool, i8); + proof_of_contract_for_transmute_unchecked!(transmute_unchecked_bool_to_u8, bool, u8); + //transmute between 2-byte primitives + proof_of_contract_for_transmute_unchecked!(transmute_unchecked_i16_to_u16, i16, u16); + proof_of_contract_for_transmute_unchecked!(transmute_unchecked_u16_to_i16, u16, i16); + //transmute between 4-byte primitives + proof_of_contract_for_transmute_unchecked!(transmute_unchecked_i32_to_u32, i32, u32); + proof_of_contract_for_transmute_unchecked!(transmute_unchecked_i32_to_f32, i32, f32); + proof_of_contract_for_transmute_unchecked!(transmute_unchecked_u32_to_i32, u32, i32); + proof_of_contract_for_transmute_unchecked!(transmute_unchecked_u32_to_f32, u32, f32); + proof_of_contract_for_transmute_unchecked!(transmute_unchecked_char_to_i32, char, i32); + proof_of_contract_for_transmute_unchecked!(transmute_unchecked_char_to_u32, char, u32); + proof_of_contract_for_transmute_unchecked!(transmute_unchecked_char_to_f32, char, f32); + proof_of_contract_for_transmute_unchecked!(transmute_unchecked_f32_to_i32, f32, i32); + proof_of_contract_for_transmute_unchecked!(transmute_unchecked_f32_to_u32, f32, u32); + //transmute between 8-byte primitives + proof_of_contract_for_transmute_unchecked!(transmute_unchecked_i64_to_u64, i64, u64); + proof_of_contract_for_transmute_unchecked!(transmute_unchecked_i64_to_f64, i64, f64); + proof_of_contract_for_transmute_unchecked!(transmute_unchecked_u64_to_i64, u64, i64); + proof_of_contract_for_transmute_unchecked!(transmute_unchecked_u64_to_f64, u64, f64); + proof_of_contract_for_transmute_unchecked!(transmute_unchecked_f64_to_i64, f64, i64); + proof_of_contract_for_transmute_unchecked!(transmute_unchecked_f64_to_u64, f64, u64); + //transmute between 16-byte primitives + proof_of_contract_for_transmute_unchecked!(transmute_unchecked_i128_to_u128, i128, u128); + proof_of_contract_for_transmute_unchecked!(transmute_unchecked_u128_to_i128, u128, i128); + //transmute to type with potentially invalid bit patterns + proof_of_contract_for_transmute_unchecked!(transmute_unchecked_i8_to_bool, i8, bool); + proof_of_contract_for_transmute_unchecked!(transmute_unchecked_u8_to_bool, u8, bool); + proof_of_contract_for_transmute_unchecked!(transmute_unchecked_i32_to_char, i32, char); + proof_of_contract_for_transmute_unchecked!(transmute_unchecked_u32_to_char, u32, char); + proof_of_contract_for_transmute_unchecked!(transmute_unchecked_f32_to_char, f32, char); + + //The follow are harnesses that check our function contract (specifically the weakness/strength + //of our generic validity precondition) + //In particular, should_succeed harnesses check that type-specific validity preconditions imply our generic precondition + // The `should_fail_*` harnesses show that `transmute_unchecked_wrapper`'s precondition + // rejects every input whose bytes aren't a valid value of the output type. They assert that + // the precondition is false rather than calling the wrapper under `should_panic`: Kani + // doesn't count a failed contract condition as a panic. + + #[kani::proof] + #[kani::stub_verified(transmute_unchecked_wrapper)] + fn should_succeed_u32_to_char() { + let src: u32 = kani::any_where(|x| core::char::from_u32(*x).is_some()); + let dst: char = unsafe { transmute_unchecked_wrapper(src) }; + } + + #[kani::proof] + fn should_fail_u32_to_char() { + let src: u32 = kani::any_where(|x| !core::char::from_u32(*x).is_some()); + assert!(!ub_checks::can_dereference(&src as *const u32 as *const char)); + } + + #[kani::proof] + #[kani::stub_verified(transmute_unchecked_wrapper)] + fn should_succeed_f32_to_char() { + let src: f32 = kani::any_where(|x| { + char::from_u32(unsafe { *(x as *const f32 as *const u32) }).is_some() + }); + let dst: char = unsafe { transmute_unchecked_wrapper(src) }; + } + + #[kani::proof] + fn should_fail_f32_to_char() { + let src: f32 = kani::any_where(|x| { + !char::from_u32(unsafe { *(x as *const f32 as *const u32) }).is_some() + }); + assert!(!ub_checks::can_dereference(&src as *const f32 as *const char)); + } + + #[kani::proof] + #[kani::stub_verified(transmute_unchecked_wrapper)] + fn should_succeed_i32_to_char() { + let src: i32 = kani::any_where(|x| char::from_u32(*x as u32).is_some()); + let dst: char = unsafe { transmute_unchecked_wrapper(src) }; + } + + #[kani::proof] + fn should_fail_i32_to_char() { + let src: i32 = kani::any_where(|x| !char::from_u32(*x as u32).is_some()); + assert!(!ub_checks::can_dereference(&src as *const i32 as *const char)); + } + + #[kani::proof] + #[kani::stub_verified(transmute_unchecked_wrapper)] + fn should_succeed_u8_to_bool() { + let src: u8 = kani::any_where(|x| *x <= 1); + let dst: bool = unsafe { transmute_unchecked_wrapper(src) }; + } + + #[kani::proof] + fn should_fail_u8_to_bool() { + let src: u8 = kani::any_where(|x| *x > 1); + assert!(!ub_checks::can_dereference(&src as *const u8 as *const bool)); + } + + #[kani::proof] + #[kani::stub_verified(transmute_unchecked_wrapper)] + fn should_succeed_i8_to_bool() { + let src: i8 = kani::any_where(|x| *x == 0 || *x == 1); + let dst: bool = unsafe { transmute_unchecked_wrapper(src) }; + } + + #[kani::proof] + fn should_fail_i8_to_bool() { + let src: i8 = kani::any_where(|x| *x != 0 && *x != 1); + assert!(!ub_checks::can_dereference(&src as *const i8 as *const bool)); + } + + //The following harnesses do the same as above, but for compound types + //Since the goal is just to show that the generic precondition can work + //with compound types, we keep the examples of compound types simple, rather + //than attempting to enumerate them. + + //This is 2-bytes large + #[cfg_attr(kani, derive(kani::Arbitrary))] + #[cfg_attr(kani, derive(PartialEq, Debug))] + #[derive(Clone, Copy)] + #[repr(C)] + struct struct_A { + x: u8, + y: bool, + } + + #[kani::proof] + #[kani::stub_verified(transmute_unchecked_wrapper)] + fn should_succeed_tuple_to_struct() { + let src: (u8, u8) = (kani::any(), kani::any_where(|x| *x <= 1)); + let dst: struct_A = unsafe { transmute_unchecked_wrapper(src) }; + } + + #[kani::proof] + fn should_fail_tuple_to_struct() { + let src: (u8, u8) = (kani::any(), kani::any_where(|x| *x > 1)); + assert!(!ub_checks::can_dereference(&src as *const (u8, u8) as *const struct_A)); + } + + #[kani::proof] + #[kani::stub_verified(transmute_unchecked_wrapper)] + fn should_succeed_tuple_to_tuple() { + let src: (u8, u8) = (kani::any(), kani::any_where(|x| *x <= 1)); + let dst: (u8, bool) = unsafe { transmute_unchecked_wrapper(src) }; + } + + #[kani::proof] + fn should_fail_tuple_to_tuple() { + let src: (u8, u8) = (kani::any(), kani::any_where(|x| *x > 1)); + assert!(!ub_checks::can_dereference(&src as *const (u8, u8) as *const (u8, bool))); + } + + #[kani::proof] + #[kani::stub_verified(transmute_unchecked_wrapper)] + fn should_succeed_tuple_to_array() { + let src: (u8, u8) = (kani::any_where(|x| *x <= 1), kani::any_where(|x| *x <= 1)); + let dst: [bool; 2] = unsafe { transmute_unchecked_wrapper(src) }; + } + + #[kani::proof] + fn should_fail_tuple_to_array() { + let src: (u8, u8) = (kani::any_where(|x| *x > 1), kani::any_where(|x| *x > 1)); + assert!(!ub_checks::can_dereference(&src as *const (u8, u8) as *const [bool; 2])); + } + + //generates should_succeed harnesses when the output type has no possible invalid values, like ints + macro_rules! should_succeed_no_validity_reqs { + ($harness:ident, $src:ty, $dst:ty) => { + #[kani::proof] + #[kani::stub_verified(transmute_unchecked_wrapper)] + fn $harness() { + let src: $src = kani::any(); + let dst: $dst = unsafe { transmute_unchecked_wrapper(src) }; + } + }; + } + + //call the above macro for all combinations of primitives where the output value cannot be invalid + //transmute between 1-byte primitives + should_succeed_no_validity_reqs!(should_succeed_i8_to_u8, i8, u8); + should_succeed_no_validity_reqs!(should_succeed_u8_to_i8, u8, i8); + should_succeed_no_validity_reqs!(should_succeed_bool_to_i8, bool, i8); + should_succeed_no_validity_reqs!(should_succeed_bool_to_u8, bool, u8); + //transmute between 2-byte primitives + should_succeed_no_validity_reqs!(should_succeed_i16_to_u16, i16, u16); + should_succeed_no_validity_reqs!(should_succeed_u16_to_i16, u16, i16); + //transmute between 4-byte primitives + should_succeed_no_validity_reqs!(should_succeed_i32_to_u32, i32, u32); + should_succeed_no_validity_reqs!(should_succeed_i32_to_f32, i32, f32); + should_succeed_no_validity_reqs!(should_succeed_u32_to_i32, u32, i32); + should_succeed_no_validity_reqs!(should_succeed_u32_to_f32, u32, f32); + should_succeed_no_validity_reqs!(should_succeed_char_to_i32, char, i32); + should_succeed_no_validity_reqs!(should_succeed_char_to_u32, char, u32); + should_succeed_no_validity_reqs!(should_succeed_char_to_f32, char, f32); + should_succeed_no_validity_reqs!(should_succeed_f32_to_i32, f32, i32); + should_succeed_no_validity_reqs!(should_succeed_f32_to_u32, f32, u32); + //transmute between 8-byte primitives + should_succeed_no_validity_reqs!(should_succeed_i64_to_u64, i64, u64); + should_succeed_no_validity_reqs!(should_succeed_i64_to_f64, i64, f64); + should_succeed_no_validity_reqs!(should_succeed_u64_to_i64, u64, i64); + should_succeed_no_validity_reqs!(should_succeed_u64_to_f64, u64, f64); + should_succeed_no_validity_reqs!(should_succeed_f64_to_i64, f64, i64); + should_succeed_no_validity_reqs!(should_succeed_f64_to_u64, f64, u64); + //transmute between 16-byte primitives + should_succeed_no_validity_reqs!(should_succeed_i128_to_u128, i128, u128); + should_succeed_no_validity_reqs!(should_succeed_u128_to_i128, u128, i128); + + //Note: the following harness fails when it in theory should not + //The problem is that ub_checks::can_dereference(), used in a validity precondition + //for transmute_unchecked_wrapper, doesn't catch references that refer to invalid values. + //Thus, this harness transmutes u8's to invalid bool values + //Maybe we can augment can_dereference() to handle this + /* + #[kani::proof_for_contract(transmute_unchecked_wrapper)] + fn transmute_unchecked_refs() { + let my_int: u8 = kani::any(); + let int_ref = &my_int; + let bool_ref: &bool = unsafe { transmute_unchecked_wrapper(int_ref) }; + let int_ref2: &u8 = unsafe { transmute_unchecked_wrapper(int_ref) }; + assert!(*int_ref2 == 0 || *int_ref2 == 1); + }*/ + + //tests that transmute works correctly when transmuting something with zero size + #[kani::proof_for_contract(transmute_unchecked_wrapper)] + fn transmute_zero_size() { + let empty_arr: [u8; 0] = []; + let unit_val: () = unsafe { transmute_unchecked_wrapper(empty_arr) }; + assert!(unit_val == ()); + } + + //generates harness that transmuted (unchecked) values, and casts them back to the original type + //i.e. (src -> dest) then (dest -> src) + //we then assert that the resulting value is equal to the initial value + macro_rules! transmute_unchecked_two_ways { + ($harness:ident, $src:ty, $dst:ty) => { + #[kani::proof] + fn $harness() { + let src: $src = kani::any(); + kani::assume(ub_checks::can_dereference(&src as *const $src as *const $dst)); + let dst: $dst = unsafe { transmute_unchecked_wrapper(src) }; + let src2: $src = unsafe { *(&dst as *const $dst as *const $src) }; + assert_eq!(src, src2); + } + }; + } + + //generates 2-way harnesses again, but handles the [float => X => float] cases + //This is because kani::any can generate NaN floats, so we treat those + //separately rather than testing for equality like any other value + macro_rules! transmute_unchecked_two_ways_from_float { + ($harness:ident, $src:ty, $dst:ty) => { + #[kani::proof] + fn $harness() { + let src: $src = kani::any(); + kani::assume(ub_checks::can_dereference(&src as *const $src as *const $dst)); + let dst: $dst = unsafe { transmute_unchecked_wrapper(src) }; + let src2: $src = unsafe { *(&dst as *const $dst as *const $src) }; + if src.is_nan() { + assert!(src2.is_nan()); + } else { + assert_eq!(src, src2); + } + } + }; + } + + //The following invoke transmute_unchecked_two_ways for all the main primitives + //transmute 2-ways between 1-byte primitives + transmute_unchecked_two_ways!(transmute_unchecked_2ways_i8_to_u8, i8, u8); + transmute_unchecked_two_ways!(transmute_unchecked_2ways_i8_to_bool, i8, bool); + transmute_unchecked_two_ways!(transmute_unchecked_2ways_u8_to_i8, u8, i8); + transmute_unchecked_two_ways!(transmute_unchecked_2ways_u8_to_bool, u8, bool); + transmute_unchecked_two_ways!(transmute_unchecked_2ways_bool_to_i8, bool, i8); + transmute_unchecked_two_ways!(transmute_unchecked_2ways_bool_to_u8, bool, u8); + //transmute 2-ways between 2-byte primitives + transmute_unchecked_two_ways!(transmute_unchecked_2ways_i16_to_u16, i16, u16); + transmute_unchecked_two_ways!(transmute_unchecked_2ways_u16_to_i16, u16, i16); + //transmute 2-ways between 4-byte primitives + transmute_unchecked_two_ways!(transmute_unchecked_2ways_i32_to_u32, i32, u32); + transmute_unchecked_two_ways!(transmute_unchecked_2ways_i32_to_f32, i32, f32); + transmute_unchecked_two_ways!(transmute_unchecked_2ways_i32_to_char, i32, char); + transmute_unchecked_two_ways!(transmute_unchecked_2ways_u32_to_i32, u32, i32); + transmute_unchecked_two_ways!(transmute_unchecked_2ways_u32_to_f32, u32, f32); + transmute_unchecked_two_ways!(transmute_unchecked_2ways_u32_to_char, u32, char); + transmute_unchecked_two_ways!(transmute_unchecked_2ways_char_to_i32, char, i32); + transmute_unchecked_two_ways!(transmute_unchecked_2ways_char_to_u32, char, u32); + transmute_unchecked_two_ways!(transmute_unchecked_2ways_char_to_f32, char, f32); + transmute_unchecked_two_ways_from_float!(transmute_unchecked_2ways_f32_to_i32, f32, i32); + transmute_unchecked_two_ways_from_float!(transmute_unchecked_2ways_f32_to_u32, f32, u32); + transmute_unchecked_two_ways_from_float!(transmute_unchecked_2ways_f32_to_char, f32, char); + //transmute 2-ways between 8-byte primitives + transmute_unchecked_two_ways!(transmute_unchecked_2ways_i64_to_u64, i64, u64); + transmute_unchecked_two_ways!(transmute_unchecked_2ways_i64_to_f64, i64, f64); + transmute_unchecked_two_ways!(transmute_unchecked_2ways_u64_to_i64, u64, i64); + transmute_unchecked_two_ways!(transmute_unchecked_2ways_u64_to_f64, u64, f64); + transmute_unchecked_two_ways_from_float!(transmute_unchecked_2ways_f64_to_i64, f64, i64); + transmute_unchecked_two_ways_from_float!(transmute_unchecked_2ways_f64_to_u64, f64, u64); + //transmute 2-ways between 16-byte primitives + transmute_unchecked_two_ways!(transmute_unchecked_2ways_i128_to_u128, i128, u128); + transmute_unchecked_two_ways!(transmute_unchecked_2ways_u128_to_i128, u128, i128); + + //Tests that transmuting (unchecked) a ptr does not mutate the stored address + //Note: the types being pointed to are intentionally small to avoid alignment issues + //The types are otherwise arbitrary -- the point of these harnesses is just to test + //that the value passed to transmute_unchecked (i.e., an address) is not mutated + #[kani::proof] + fn check_transmute_unchecked_ptr_address() { + let mut generator = PointerGenerator::<10000>::new(); + let arb_ptr: *const bool = generator.any_in_bounds().ptr; + let arb_ptr_2: *const u8 = unsafe { transmute_unchecked(arb_ptr) }; + assert_eq!(arb_ptr as *const bool, arb_ptr_2 as *const u8 as *const bool); + } + + //Tests that transmuting (unchecked) a ref does not mutate the stored address + #[kani::proof] + fn check_transmute_unchecked_ref_address() { + let mut generator = PointerGenerator::<10000>::new(); + let arb_ptr: *const bool = generator.any_in_bounds().ptr; + let arb_ref: &bool = unsafe { &*(arb_ptr) }; + let arb_ref_2: &u8 = unsafe { transmute_unchecked(arb_ref) }; + assert_eq!(arb_ref as *const bool, arb_ref_2 as *const u8 as *const bool); + } + + //Tests that transmuting (unchecked) a slice does not mutate the slice metadata (address and length) + //Here, both the address and length of the slices are non-deterministic + #[kani::proof] + fn check_transmute_unchecked_slice_metadata() { + const MAX_SIZE: usize = 32; + let mut generator = PointerGenerator::<10000>::new(); + let arb_arr_ptr: *const [bool; MAX_SIZE] = generator.any_in_bounds().ptr; + let arb_slice = kani::slice::any_slice_of_array(unsafe { &*(arb_arr_ptr) }); + //The following prevents taking redundant slices: + kani::assume(arb_slice.as_ptr() == arb_arr_ptr as *const bool); + let arb_slice_2: &[u8] = unsafe { transmute_unchecked(arb_slice) }; + assert_eq!(arb_slice.as_ptr(), arb_slice_2.as_ptr() as *const bool); + assert_eq!(arb_slice.len(), arb_slice_2.len()); + } + + //generates harness that transmutes values, and casts them back to the original type + //i.e. (src -> dest) then (dest -> src) + //we then assert that the resulting value is equal to the initial value + macro_rules! transmute_two_ways { + ($harness:ident, $src:ty, $dst:ty) => { + #[kani::proof] + fn $harness() { + let src: $src = kani::any(); + kani::assume(ub_checks::can_dereference(&src as *const $src as *const $dst)); + let dst: $dst = unsafe { transmute(src) }; + let src2: $src = unsafe { *(&dst as *const $dst as *const $src) }; + assert_eq!(src, src2); + } + }; + } + + //generates 2-way harnesses again, but handles the [float => X => float] cases + //This is because kani::any can generate NaN floats, so we treat those + //separately rather than testing for equality like any other value + macro_rules! transmute_two_ways_from_float { + ($harness:ident, $src:ty, $dst:ty) => { + #[kani::proof] + fn $harness() { + let src: $src = kani::any(); + kani::assume(ub_checks::can_dereference(&src as *const $src as *const $dst)); + let dst: $dst = unsafe { transmute(src) }; + let src2: $src = unsafe { *(&dst as *const $dst as *const $src) }; + if src.is_nan() { + assert!(src2.is_nan()); + } else { + assert_eq!(src, src2); + } + } + }; + } + + //The following invoke transmute_two_ways for all the main primitives + //transmute 2-ways between 1-byte primitives + transmute_two_ways!(transmute_2ways_i8_to_u8, i8, u8); + transmute_two_ways!(transmute_2ways_i8_to_bool, i8, bool); + transmute_two_ways!(transmute_2ways_u8_to_i8, u8, i8); + transmute_two_ways!(transmute_2ways_u8_to_bool, u8, bool); + transmute_two_ways!(transmute_2ways_bool_to_i8, bool, i8); + transmute_two_ways!(transmute_2ways_bool_to_u8, bool, u8); + //transmute 2-ways between 2-byte primitives + transmute_two_ways!(transmute_2ways_i16_to_u16, i16, u16); + transmute_two_ways!(transmute_2ways_u16_to_i16, u16, i16); + //transmute 2-ways between 4-byte primitives + transmute_two_ways!(transmute_2ways_i32_to_u32, i32, u32); + transmute_two_ways!(transmute_2ways_i32_to_f32, i32, f32); + transmute_two_ways!(transmute_2ways_i32_to_char, i32, char); + transmute_two_ways!(transmute_2ways_u32_to_i32, u32, i32); + transmute_two_ways!(transmute_2ways_u32_to_f32, u32, f32); + transmute_two_ways!(transmute_2ways_u32_to_char, u32, char); + transmute_two_ways!(transmute_2ways_char_to_i32, char, i32); + transmute_two_ways!(transmute_2ways_char_to_u32, char, u32); + transmute_two_ways!(transmute_2ways_char_to_f32, char, f32); + transmute_two_ways_from_float!(transmute_2ways_f32_to_i32, f32, i32); + transmute_two_ways_from_float!(transmute_2ways_f32_to_u32, f32, u32); + transmute_two_ways_from_float!(transmute_2ways_f32_to_char, f32, char); + //transmute 2-ways between 8-byte primitives + transmute_two_ways!(transmute_2ways_i64_to_u64, i64, u64); + transmute_two_ways!(transmute_2ways_i64_to_f64, i64, f64); + transmute_two_ways!(transmute_2ways_u64_to_i64, u64, i64); + transmute_two_ways!(transmute_2ways_u64_to_f64, u64, f64); + transmute_two_ways_from_float!(transmute_2ways_f64_to_i64, f64, i64); + transmute_two_ways_from_float!(transmute_2ways_f64_to_u64, f64, u64); + //transmute 2-ways between 16-byte primitives + transmute_two_ways!(transmute_2ways_i128_to_u128, i128, u128); + transmute_two_ways!(transmute_2ways_u128_to_i128, u128, i128); + + //Tests that transmuting a ptr does not mutate the stored address + //Note: the types being pointed to are intentionally small to avoid alignment issues + //The types are otherwise arbitrary -- the point of these harnesses is just to test + //that the value passed to transmute (i.e., an address) is not mutated + #[kani::proof] + fn check_transmute_ptr_address() { + let mut generator = PointerGenerator::<10000>::new(); + let arb_ptr: *const bool = generator.any_in_bounds().ptr; + let arb_ptr_2: *const u8 = unsafe { transmute(arb_ptr) }; + assert_eq!(arb_ptr as *const bool, arb_ptr_2 as *const u8 as *const bool); + } + + //Tests that transmuting a ref does not mutate the stored address + #[kani::proof] + fn check_transmute_ref_address() { + let mut generator = PointerGenerator::<10000>::new(); + let arb_ptr: *const bool = generator.any_in_bounds().ptr; + let arb_ref: &bool = unsafe { &*(arb_ptr) }; + let arb_ref_2: &u8 = unsafe { transmute(arb_ref) }; + assert_eq!(arb_ref as *const bool, arb_ref_2 as *const u8 as *const bool); + } + + //Tests that transmuting a slice does not mutate the slice metadata (address and length) + //Here, both the address and length of the slices are non-deterministic + #[kani::proof] + fn check_transmute_slice_metadata() { + const MAX_SIZE: usize = 32; + let mut generator = PointerGenerator::<10000>::new(); + let arb_arr_ptr: *const [bool; MAX_SIZE] = generator.any_in_bounds().ptr; + let arb_slice = kani::slice::any_slice_of_array(unsafe { &*(arb_arr_ptr) }); + //The following prevents taking redundant slices: + kani::assume(arb_slice.as_ptr() == arb_arr_ptr as *const bool); + let arb_slice_2: &[u8] = unsafe { transmute(arb_slice) }; + assert_eq!(arb_slice.as_ptr(), arb_slice_2.as_ptr() as *const bool); + assert_eq!(arb_slice.len(), arb_slice_2.len()); + } + + //tests that transmutes between compound data structures (currently structs, + //arrays, and tuples) do not mutate the underlying data. + //To keep things simple, we limit these structures to containing two of whatever + //the input type is, since that's the smallest non-trivial amount. + macro_rules! gen_compound_harnesses { + ($mod_name:ident, $base_type:ty) => { + mod $mod_name { + use super::*; + + #[cfg_attr(kani, derive(kani::Arbitrary))] + #[derive(Debug, PartialEq, Clone, Copy)] + #[repr(packed)] + struct generated_struct { + f1: $base_type, + f2: $base_type, + } + + //transmute harnesses + transmute_two_ways!( + transmute_2ways_struct_to_arr, + generated_struct, + [$base_type; 2] + ); + transmute_two_ways!( + transmute_2ways_struct_to_tuple, + generated_struct, + ($base_type, $base_type) + ); + transmute_two_ways!( + transmute_2ways_arr_to_struct, + [$base_type; 2], + generated_struct + ); + transmute_two_ways!( + transmute_2ways_arr_to_tuple, + [$base_type; 2], + ($base_type, $base_type) + ); + transmute_two_ways!( + transmute_2ways_tuple_to_struct, + ($base_type, $base_type), + generated_struct + ); + transmute_two_ways!( + transmute_2ways_tuple_to_arr, + ($base_type, $base_type), + [$base_type; 2] + ); + //transmute_unchecked harnesses + transmute_unchecked_two_ways!( + transmute_unchecked_2ways_struct_to_arr, + generated_struct, + [$base_type; 2] + ); + transmute_unchecked_two_ways!( + transmute_unchecked_2ways_struct_to_tuple, + generated_struct, + ($base_type, $base_type) + ); + transmute_unchecked_two_ways!( + transmute_unchecked_2ways_arr_to_struct, + [$base_type; 2], + generated_struct + ); + transmute_unchecked_two_ways!( + transmute_unchecked_2ways_arr_to_tuple, + [$base_type; 2], + ($base_type, $base_type) + ); + transmute_unchecked_two_ways!( + transmute_unchecked_2ways_tuple_to_struct, + ($base_type, $base_type), + generated_struct + ); + transmute_unchecked_two_ways!( + transmute_unchecked_2ways_tuple_to_arr, + ($base_type, $base_type), + [$base_type; 2] + ); + } + }; + } + + #[cfg_attr(kani, derive(kani::Arbitrary))] + #[derive(Debug, PartialEq, Clone, Copy)] + #[repr(packed)] + struct u8_struct { + f1: u8, + f2: u8, + } + + //generate compound harnesses for main primitive types, as well as with + //some compound types (to obtain nested compound types) + gen_compound_harnesses!(u8_mod, u8); + gen_compound_harnesses!(u16_mod, u16); + gen_compound_harnesses!(u32_mod, u32); + gen_compound_harnesses!(u64_mod, u64); + gen_compound_harnesses!(u128_mod, u128); + gen_compound_harnesses!(i8_mod, i8); + gen_compound_harnesses!(i16_mod, i16); + gen_compound_harnesses!(i32_mod, i32); + gen_compound_harnesses!(i64_mod, i64); + gen_compound_harnesses!(i128_mod, i128); + gen_compound_harnesses!(char_mod, char); + gen_compound_harnesses!(bool_mod, bool); + gen_compound_harnesses!(tuple_mod, (u8, u8)); + gen_compound_harnesses!(arr_mod, [u8; 2]); + gen_compound_harnesses!(struct_mod, u8_struct); + + // ---- arith_offset ---- + // Kani models this as wrapping pointer arithmetic; no safety precondition, + // hence no `requires`. Ensures: address displaced by `offset` elements, + // wrapping over the pointer width (unlike the bounds-restricted `offset`). + #[ensures(|result: &*const T| + (*result).addr() + == dst.addr().wrapping_add((offset as usize).wrapping_mul(crate::mem::size_of::())))] + #[allow(dead_code)] + unsafe fn arith_offset_wrapper(dst: *const T, offset: isize) -> *const T { + // SAFETY: no preconditions; pure wrapping arithmetic, no memory access. + unsafe { arith_offset(dst, offset) } + } + + // Nothing is dereferenced, so a provenance-free integer address is the most + // general base. CBMC encodes a pointer's address in the bits left over after + // the object ID; CI runs with `--object-bits 12`, leaving 52 bits. The + // harness therefore keeps the base and the result below 2^52; results that + // wrap around past `usize::MAX` are out of reach with 12 object bits. + macro_rules! check_arith_offset_for { + ($harness:ident, $ty:ty) => { + #[kani::proof_for_contract(arith_offset_wrapper)] + fn $harness() { + // Every base below 2^52, and every offset whose result lands there. + let base_addr: usize = kani::any(); + kani::assume(base_addr >= 1 && base_addr < (1usize << 52)); + let offset: isize = kani::any(); + let r = + base_addr as i128 + (offset as i128) * (crate::mem::size_of::<$ty>() as i128); + kani::assume(r >= 0 && r < (1i128 << 52)); + + let dst: *const $ty = crate::ptr::without_provenance(base_addr); + kani::cover(offset > 0, "arith_offset applies a forward displacement"); + kani::cover(offset < 0, "arith_offset applies a backward displacement"); + let _ = unsafe { arith_offset_wrapper::<$ty>(dst, offset) }; + } + }; + } + + check_arith_offset_for!(check_arith_offset_u8, u8); + check_arith_offset_for!(check_arith_offset_u32, u32); + check_arith_offset_for!(check_arith_offset_u64, u64); + check_arith_offset_for!(check_arith_offset_i128, i128); + + // ---- volatile_copy_nonoverlapping_memory ---- + // As for `volatile_load`/`volatile_store`, the contract lives on a thin + // `*_model` wrapper that calls the real intrinsic (Kani supports all five + // volatile/unaligned-volatile intrinsics since model-checking/kani#4672 and + // #4673). Contract as for `copy_nonoverlapping`, whose safety it shares. + #[requires(!count.overflowing_mul(crate::mem::size_of::()).1 + && ub_checks::can_dereference(core::ptr::slice_from_raw_parts(src as *const crate::mem::MaybeUninit, count)) + && ub_checks::can_write(core::ptr::slice_from_raw_parts_mut(dst, count)) + && ub_checks::maybe_is_nonoverlapping(src as *const (), dst as *const (), crate::mem::size_of::(), count))] + #[ensures(|_| check_copy_untyped(src, dst, count))] + #[cfg_attr(kani, kani::modifies(crate::ptr::slice_from_raw_parts(dst, count)))] + #[allow(dead_code)] + unsafe fn volatile_copy_nonoverlapping_memory_model( + dst: *mut T, + src: *const T, + count: usize, + ) { + // SAFETY: guaranteed by the precondition. + unsafe { volatile_copy_nonoverlapping_memory(dst, src, count) } + } + + // Same setup rationale as `check_copy_nonoverlapping_for`. + macro_rules! check_volatile_copy_nonoverlapping_memory_for { + ($harness:ident, $ty:ty) => { + #[kani::proof_for_contract(volatile_copy_nonoverlapping_memory_model)] + fn $harness() { + const N: usize = 100; + let gen_any_ptr = |buf: &mut [MaybeUninit<$ty>; N]| -> *mut $ty { + let base = buf.as_mut_ptr() as *mut u8; + base.wrapping_add(kani::any_where(|o: &usize| { + *o < N * core::mem::size_of::<$ty>() + })) as *mut $ty + }; + let mut buffer1 = [MaybeUninit::<$ty>::uninit(); N]; + for i in 0..N { + if kani::any() { + buffer1[i] = MaybeUninit::new(kani::any()); + } + } + let mut buffer2 = [MaybeUninit::<$ty>::uninit(); N]; + let src = gen_any_ptr(&mut buffer1) as *const $ty; + // `dst` may point into a separate buffer or alias `buffer1`. + let dst = + if kani::any() { gen_any_ptr(&mut buffer2) } else { gen_any_ptr(&mut buffer1) }; + let count: usize = kani::any(); + kani::cover( + count > 0, + "volatile_copy_nonoverlapping_memory copies a non-empty range", + ); + unsafe { volatile_copy_nonoverlapping_memory_model(dst, src, count) }; + } + }; + } + + check_volatile_copy_nonoverlapping_memory_for!( + check_volatile_copy_nonoverlapping_memory_u8, + u8 + ); + check_volatile_copy_nonoverlapping_memory_for!( + check_volatile_copy_nonoverlapping_memory_char, + char + ); + check_volatile_copy_nonoverlapping_memory_for!( + check_volatile_copy_nonoverlapping_memory_u32, + u32 + ); + + // ---- volatile_copy_memory ---- + // Calls the real intrinsic (memmove): the contract is + // `volatile_copy_nonoverlapping_memory`'s minus the non-overlap clause. + #[requires(!count.overflowing_mul(crate::mem::size_of::()).1 + && ub_checks::can_dereference(core::ptr::slice_from_raw_parts(src as *const crate::mem::MaybeUninit, count)) + && ub_checks::can_write(core::ptr::slice_from_raw_parts_mut(dst, count)))] + #[ensures(|_| check_copy_untyped(src, dst, count))] + #[cfg_attr(kani, kani::modifies(crate::ptr::slice_from_raw_parts(dst, count)))] + #[allow(dead_code)] + unsafe fn volatile_copy_memory_model(dst: *mut T, src: *const T, count: usize) { + // SAFETY: guaranteed by the precondition. + unsafe { volatile_copy_memory(dst, src, count) } + } + + // Same setup as `check_copy_for`, including the aliasing `dst`. + macro_rules! check_volatile_copy_memory_for { + ($harness:ident, $ty:ty) => { + #[kani::proof_for_contract(volatile_copy_memory_model)] + fn $harness() { + const N: usize = 100; + let gen_any_ptr = |buf: &mut [MaybeUninit<$ty>; N]| -> *mut $ty { + let base = buf.as_mut_ptr() as *mut u8; + base.wrapping_add(kani::any_where(|o: &usize| { + *o < N * core::mem::size_of::<$ty>() + })) as *mut $ty + }; + let mut buffer1 = [MaybeUninit::<$ty>::uninit(); N]; + for i in 0..N { + if kani::any() { + buffer1[i] = MaybeUninit::new(kani::any()); + } + } + let mut buffer2 = [MaybeUninit::<$ty>::uninit(); N]; + let src = gen_any_ptr(&mut buffer1) as *const $ty; + let dst = + if kani::any() { gen_any_ptr(&mut buffer2) } else { gen_any_ptr(&mut buffer1) }; + let count: usize = kani::any(); + kani::cover(count > 0, "volatile_copy_memory copies a non-empty range"); + unsafe { volatile_copy_memory_model(dst, src, count) }; + } + }; + } + + check_volatile_copy_memory_for!(check_volatile_copy_memory_u8, u8); + check_volatile_copy_memory_for!(check_volatile_copy_memory_char, char); + check_volatile_copy_memory_for!(check_volatile_copy_memory_u32, u32); + + // ---- volatile_set_memory ---- + // Calls the real intrinsic (memset); contract is `write_bytes`'s verbatim, + // including the bytes-only ensures. + #[requires(!count.overflowing_mul(crate::mem::size_of::()).1 + && ub_checks::can_write(core::ptr::slice_from_raw_parts_mut(dst, count)))] + #[requires(ub_checks::maybe_is_aligned_and_not_null( + dst as *const (), + crate::mem::align_of::(), + crate::mem::size_of::() == 0 || count == 0, + ))] + #[ensures(|_| ub_checks::can_dereference( + core::ptr::slice_from_raw_parts(dst as *const u8, count * crate::mem::size_of::())))] + #[cfg_attr(kani, kani::modifies(crate::ptr::slice_from_raw_parts(dst, count)))] + #[allow(dead_code)] + unsafe fn volatile_set_memory_model(dst: *mut T, val: u8, count: usize) { + // SAFETY: guaranteed by the precondition. + unsafe { volatile_set_memory(dst, val, count) } + } + + // Same setup rationale as `check_write_bytes_for`. + macro_rules! check_volatile_set_memory_for { + ($harness:ident, $ty:ty) => { + #[kani::proof_for_contract(volatile_set_memory_model)] + fn $harness() { + const N: usize = 100; + let mut buffer = [MaybeUninit::<$ty>::uninit(); N]; + let base = buffer.as_mut_ptr() as *mut u8; + let dst = base + .wrapping_add(kani::any_where(|o: &usize| *o < N * core::mem::size_of::<$ty>())) + as *mut $ty; + let val: u8 = kani::any(); + let count: usize = kani::any(); + kani::cover(count > 0, "volatile_set_memory sets a non-empty range"); + unsafe { volatile_set_memory_model(dst, val, count) }; + } + }; + } + + check_volatile_set_memory_for!(check_volatile_set_memory_u8, u8); + check_volatile_set_memory_for!(check_volatile_set_memory_char, char); + check_volatile_set_memory_for!(check_volatile_set_memory_u32, u32); + + // ---- volatile_load ---- + // Backs `ptr::read_volatile`; Kani models it as the same read. Requires is + // verbatim from `read_volatile`; a read has no `modifies` and no ensures. + #[requires(ub_checks::can_dereference(src))] + #[allow(dead_code)] + unsafe fn volatile_load_model(src: *const T) -> T { + // SAFETY: guaranteed by the precondition. + unsafe { volatile_load(src) } + } + + // `src` stays inside a fully initialized stack allocation. `can_dereference` + // checks initialization only with `-Z uninit-checks`, which CI does not pass. + // The byte-granular offset generates misaligned pointers the alignment clause + // must prune. + macro_rules! check_volatile_load_for { + ($harness:ident, $ty:ty) => { + #[kani::proof_for_contract(volatile_load_model)] + fn $harness() { + const N: usize = 100; + let mut buffer = [MaybeUninit::<$ty>::uninit(); N]; + for i in 0..N { + buffer[i] = MaybeUninit::new(kani::any()); + } + let base = buffer.as_ptr() as *const u8; + let src = base + .wrapping_add(kani::any_where(|o: &usize| *o < N * core::mem::size_of::<$ty>())) + as *const $ty; + kani::cover(true, "volatile_load reaches a dereferenceable src"); + let _val = unsafe { volatile_load_model(src) }; + } + }; + } + + check_volatile_load_for!(check_volatile_load_u8, u8); + check_volatile_load_for!(check_volatile_load_char, char); + check_volatile_load_for!(check_volatile_load_u32, u32); + + // ---- volatile_store ---- + // Backs `ptr::write_volatile`; Kani models it as the same write. Requires is + // verbatim from `write_volatile`; `modifies(dst)` scopes the write. No + // ensures: `dst` may be write-only I/O memory, so asserting post-state + // readability would over-claim; fidelity is pinned by the harness read-back. + #[requires(ub_checks::can_write(dst))] + #[cfg_attr(kani, kani::modifies(dst))] + #[allow(dead_code)] + unsafe fn volatile_store_model(dst: *mut T, val: T) { + // SAFETY: guaranteed by the precondition. + unsafe { volatile_store(dst, val) } + } + + // `dst` need not be initialized (the store only writes); misaligned pointers + // from the byte-granular offset must be pruned by the alignment clause. + macro_rules! check_volatile_store_for { + ($harness:ident, $ty:ty) => { + #[kani::proof_for_contract(volatile_store_model)] + fn $harness() { + const N: usize = 100; + let mut buffer = [MaybeUninit::<$ty>::uninit(); N]; + let base = buffer.as_mut_ptr() as *mut u8; + let dst = base + .wrapping_add(kani::any_where(|o: &usize| *o < N * core::mem::size_of::<$ty>())) + as *mut $ty; + let val: $ty = kani::any(); + kani::cover(true, "volatile_store reaches a writeable dst"); + unsafe { volatile_store_model(dst, val) }; + // Fidelity: the model actually stored `val` at `dst`. + let read_back = unsafe { volatile_load(dst) }; + assert!(read_back == val); + } + }; + } + + check_volatile_store_for!(check_volatile_store_u8, u8); + check_volatile_store_for!(check_volatile_store_char, char); + check_volatile_store_for!(check_volatile_store_u32, u32); + + // ---- unaligned_volatile_load ---- + // Volatile analogue of `ptr::read_unaligned`; calls the real intrinsic. + // Requires `can_read_unaligned(src)`: dropping the alignment obligation is + // the whole difference from `volatile_load`. + #[requires(ub_checks::can_read_unaligned(src))] + #[allow(dead_code)] + unsafe fn unaligned_volatile_load_model(src: *const T) -> T { + // SAFETY: guaranteed by the precondition. + unsafe { unaligned_volatile_load(src) } + } + + // As `check_volatile_load_for`, but misaligned pointers are NOT pruned; the + // cover witnesses that a misaligned read is actually reachable. + macro_rules! check_unaligned_volatile_load_for { + ($harness:ident, $ty:ty) => { + #[kani::proof_for_contract(unaligned_volatile_load_model)] + fn $harness() { + const N: usize = 100; + let mut buffer = [MaybeUninit::<$ty>::uninit(); N]; + for i in 0..N { + buffer[i] = MaybeUninit::new(kani::any()); + } + let base = buffer.as_ptr() as *const u8; + let src = base + .wrapping_add(kani::any_where(|o: &usize| *o < N * core::mem::size_of::<$ty>())) + as *const $ty; + kani::cover( + src.addr() % core::mem::align_of::<$ty>() != 0, + "unaligned_volatile_load reaches a misaligned src", + ); + let _val = unsafe { unaligned_volatile_load_model(src) }; + } + }; + } + + // `char`/`u32` (alignment > 1) make the misaligned cover satisfiable; `u8` + // is handled separately since every address is 1-aligned. + check_unaligned_volatile_load_for!(check_unaligned_volatile_load_char, char); + check_unaligned_volatile_load_for!(check_unaligned_volatile_load_u32, u32); + + #[kani::proof_for_contract(unaligned_volatile_load_model)] + fn check_unaligned_volatile_load_u8() { + const N: usize = 100; + let mut buffer = [MaybeUninit::::uninit(); N]; + for i in 0..N { + buffer[i] = MaybeUninit::new(kani::any()); + } + let base = buffer.as_ptr(); + let src = base.wrapping_add(kani::any_where(|o: &usize| *o < N)) as *const u8; + // `u8` is always aligned; just witness a dereferenceable read (non-vacuity). + kani::cover(true, "unaligned_volatile_load reaches a dereferenceable src"); + let _val = unsafe { unaligned_volatile_load_model(src) }; + } + + // ---- unaligned_volatile_store ---- + // Volatile analogue of `ptr::write_unaligned`; calls the real intrinsic. + // Requires `can_write_unaligned(dst)`: dropping alignment is the whole + // difference from `volatile_store`. No ensures (write-only I/O memory); + // fidelity is pinned by the harness read-back. + #[requires(ub_checks::can_write_unaligned(dst))] + #[cfg_attr(kani, kani::modifies(dst))] + #[allow(dead_code)] + unsafe fn unaligned_volatile_store_model(dst: *mut T, val: T) { + // SAFETY: guaranteed by the precondition. + unsafe { unaligned_volatile_store(dst, val) } + } + + // As `check_volatile_store_for`, but misaligned pointers are NOT pruned; the + // cover witnesses a misaligned write, and the read-back assert pins fidelity. + macro_rules! check_unaligned_volatile_store_for { + ($harness:ident, $ty:ty) => { + #[kani::proof_for_contract(unaligned_volatile_store_model)] + fn $harness() { + const N: usize = 100; + let mut buffer = [MaybeUninit::<$ty>::uninit(); N]; + let base = buffer.as_mut_ptr() as *mut u8; + let dst = base + .wrapping_add(kani::any_where(|o: &usize| *o < N * core::mem::size_of::<$ty>())) + as *mut $ty; + let val: $ty = kani::any(); + kani::cover( + dst.addr() % core::mem::align_of::<$ty>() != 0, + "unaligned_volatile_store reaches a misaligned dst", + ); + unsafe { unaligned_volatile_store_model(dst, val) }; + // Fidelity: the model actually stored `val` at `dst`. + let read_back = unsafe { crate::ptr::read_unaligned(dst) }; + assert!(read_back == val); + } + }; + } + + // `char`/`u32` have alignment > 1, so the misaligned cover is satisfiable; + // `u8` is handled separately as for the load case. + check_unaligned_volatile_store_for!(check_unaligned_volatile_store_char, char); + check_unaligned_volatile_store_for!(check_unaligned_volatile_store_u32, u32); + + #[kani::proof_for_contract(unaligned_volatile_store_model)] + fn check_unaligned_volatile_store_u8() { + const N: usize = 100; + let mut buffer = [MaybeUninit::::uninit(); N]; + let base = buffer.as_mut_ptr(); + let dst = base.wrapping_add(kani::any_where(|o: &usize| *o < N)) as *mut u8; + let val: u8 = kani::any(); + // `u8` is always aligned; just witness a writeable dst (non-vacuity). + kani::cover(true, "unaligned_volatile_store reaches a writeable dst"); + unsafe { unaligned_volatile_store_model(dst, val) }; + let read_back = unsafe { crate::ptr::read_unaligned(dst) }; + assert!(read_back == val); + } + + // ---- ptr_offset_from ---- + // Kani models this as the CBMC pointer difference scaled to units of `T` + // (primitive behind `<*const T>::offset_from`). The four `requires` encode + // the `# Safety` of `offset_from`, matching the already-verified contract in + // `ptr/const_ptr.rs`. Ensures: the exact signed element distance. + #[requires(crate::mem::size_of::() != 0)] + // Subtracting `base` from `ptr` (as addresses) does not overflow `isize`. + #[requires((ptr as isize).checked_sub(base as isize).is_some())] + // The byte distance is an exact multiple of the pointee size. + #[requires((ptr as isize - base as isize) % (crate::mem::size_of::() as isize) == 0)] + // The pointers share an allocation (or are literally the same address). + #[requires(ptr as isize == base as isize || ub_checks::same_allocation(ptr, base))] + #[ensures(|result: &isize| + *result == (ptr as isize - base as isize) / (crate::mem::size_of::() as isize))] + #[allow(dead_code)] + unsafe fn ptr_offset_from_wrapper(ptr: *const T, base: *const T) -> isize { + // SAFETY: guaranteed by the preconditions. + unsafe { ptr_offset_from(ptr, base) } + } + + // Same-generator pairs satisfy `same_allocation`; cross-generator pairs are + // pruned. For these primitive `T`, size == align, so in-bounds pairs satisfy + // the exact-multiple clause; covers witness zero/forward/backward distances. + macro_rules! check_ptr_offset_from_for { + ($harness:ident, $ty:ty) => { + #[kani::proof_for_contract(ptr_offset_from_wrapper)] + fn $harness() { + const GEN_SIZE: usize = mem::size_of::<$ty>(); + let mut generator1 = PointerGenerator::<{ GEN_SIZE * 4 }>::new(); + let mut generator2 = PointerGenerator::<{ GEN_SIZE * 4 }>::new(); + let ptr: *const $ty = generator1.any_in_bounds().ptr; + let base: *const $ty = if kani::any() { + generator1.any_in_bounds().ptr + } else { + generator2.any_in_bounds().ptr + }; + kani::cover(ptr.addr() == base.addr(), "offset_from: zero distance"); + kani::cover(ptr.addr() > base.addr(), "offset_from: forward distance"); + kani::cover(ptr.addr() < base.addr(), "offset_from: backward distance"); + let _ = unsafe { ptr_offset_from_wrapper::<$ty>(ptr, base) }; + } + }; + } + + check_ptr_offset_from_for!(check_ptr_offset_from_u8, u8); + check_ptr_offset_from_for!(check_ptr_offset_from_u32, u32); + check_ptr_offset_from_for!(check_ptr_offset_from_u64, u64); + check_ptr_offset_from_for!(check_ptr_offset_from_i32, i32); + check_ptr_offset_from_for!(check_ptr_offset_from_i128, i128); + + // ---- ptr_offset_from_unsigned ---- + // Unsigned variant of `ptr_offset_from`, same model. The first four + // `requires` are shared verbatim with `ptr_offset_from_wrapper`; the fifth + // adds the variant-specific `ptr >= base`. Ensures: the exact unsigned + // element distance (loss-free cast, since the distance is non-negative). + #[requires(crate::mem::size_of::() != 0)] + #[requires((ptr as isize).checked_sub(base as isize).is_some())] + #[requires((ptr as isize - base as isize) % (crate::mem::size_of::() as isize) == 0)] + #[requires(ptr as isize == base as isize || ub_checks::same_allocation(ptr, base))] + #[requires(ptr as isize >= base as isize)] + #[ensures(|result: &usize| + *result == ((ptr as isize - base as isize) / (crate::mem::size_of::() as isize)) as usize)] + #[allow(dead_code)] + unsafe fn ptr_offset_from_unsigned_wrapper(ptr: *const T, base: *const T) -> usize { + // SAFETY: guaranteed by the preconditions. + unsafe { ptr_offset_from_unsigned(ptr, base) } + } + + // As `check_ptr_offset_from_for`; `ptr >= base` prunes backward distances, + // so only the zero and forward covers remain. + macro_rules! check_ptr_offset_from_unsigned_for { + ($harness:ident, $ty:ty) => { + #[kani::proof_for_contract(ptr_offset_from_unsigned_wrapper)] + fn $harness() { + const GEN_SIZE: usize = mem::size_of::<$ty>(); + let mut generator1 = PointerGenerator::<{ GEN_SIZE * 4 }>::new(); + let mut generator2 = PointerGenerator::<{ GEN_SIZE * 4 }>::new(); + let ptr: *const $ty = generator1.any_in_bounds().ptr; + let base: *const $ty = if kani::any() { + generator1.any_in_bounds().ptr + } else { + generator2.any_in_bounds().ptr + }; + kani::cover(ptr.addr() == base.addr(), "offset_from_unsigned: zero distance"); + kani::cover(ptr.addr() > base.addr(), "offset_from_unsigned: forward distance"); + let _ = unsafe { ptr_offset_from_unsigned_wrapper::<$ty>(ptr, base) }; + } + }; + } + + check_ptr_offset_from_unsigned_for!(check_ptr_offset_from_unsigned_u8, u8); + check_ptr_offset_from_unsigned_for!(check_ptr_offset_from_unsigned_u32, u32); + check_ptr_offset_from_unsigned_for!(check_ptr_offset_from_unsigned_u64, u64); + check_ptr_offset_from_unsigned_for!(check_ptr_offset_from_unsigned_i32, i32); + check_ptr_offset_from_unsigned_for!(check_ptr_offset_from_unsigned_i128, i128); + + // ---- read_via_copy ---- + // Backs `ptr::read`; Kani models it as the plain typed load. Requires + // `can_dereference(ptr)`, the `# Safety` of `ptr::read`; a read has no + // `modifies` and no ensures. + #[requires(ub_checks::can_dereference(ptr))] + #[allow(dead_code)] + unsafe fn read_via_copy_model(ptr: *const T) -> T { + // SAFETY: guaranteed by the precondition. + unsafe { read_via_copy(ptr) } + } + + // Same setup rationale as `check_volatile_load_for`. + macro_rules! check_read_via_copy_for { + ($harness:ident, $ty:ty) => { + #[kani::proof_for_contract(read_via_copy_model)] + fn $harness() { + const N: usize = 100; + let mut buffer = [MaybeUninit::<$ty>::uninit(); N]; + for i in 0..N { + buffer[i] = MaybeUninit::new(kani::any()); + } + let base = buffer.as_ptr() as *const u8; + let ptr = base + .wrapping_add(kani::any_where(|o: &usize| *o < N * core::mem::size_of::<$ty>())) + as *const $ty; + kani::cover(true, "read_via_copy reaches a dereferenceable ptr"); + let _val = unsafe { read_via_copy_model(ptr) }; + } + }; + } + + check_read_via_copy_for!(check_read_via_copy_u8, u8); + check_read_via_copy_for!(check_read_via_copy_char, char); + check_read_via_copy_for!(check_read_via_copy_u32, u32); + + // ---- write_via_move ---- + // Backs `ptr::write`; Kani models it as the plain typed store. Requires only + // `can_write(ptr)`: the write overwrites without reading. Ensures the + // destination holds a fully-formed `T`; `*ptr == value` is not expressible + // because `value` is moved and generic `T: !Copy` cannot be re-read. + #[requires(ub_checks::can_write(ptr))] + #[ensures(|_| ub_checks::can_dereference(ptr as *const T))] + #[cfg_attr(kani, kani::modifies(ptr))] + #[allow(dead_code)] + unsafe fn write_via_move_model(ptr: *mut T, value: T) { + // SAFETY: guaranteed by the precondition. + unsafe { write_via_move(ptr, value) } + } + + // Destination deliberately left `MaybeUninit`: overwriting uninit memory is + // legal and exercised here; misaligned pointers from the byte-granular + // offset must be pruned by the alignment clause. + macro_rules! check_write_via_move_for { + ($harness:ident, $ty:ty) => { + #[kani::proof_for_contract(write_via_move_model)] + fn $harness() { + const N: usize = 100; + let mut buffer = [MaybeUninit::<$ty>::uninit(); N]; + let base = buffer.as_mut_ptr() as *mut u8; + let ptr = base + .wrapping_add(kani::any_where(|o: &usize| *o < N * core::mem::size_of::<$ty>())) + as *mut $ty; + let value: $ty = kani::any(); + kani::cover(true, "write_via_move reaches a writeable ptr"); + unsafe { write_via_move_model(ptr, value) }; + } + }; + } + + check_write_via_move_for!(check_write_via_move_u8, u8); + check_write_via_move_for!(check_write_via_move_char, char); + check_write_via_move_for!(check_write_via_move_u32, u32); + + // ---- compare_bytes ---- + // Backs slice comparison; Kani models it as a memcmp. Requires each pointer + // readable and initialized for the WHOLE `bytes` range, not merely up to the + // first differing byte (the docs stress chunked reads); Kani checks the + // initialization part only with `-Z uninit-checks`. No ensures: relating + // the returned sign to the first differing byte is functional, not safety. + #[requires(ub_checks::can_dereference(core::ptr::slice_from_raw_parts(left, bytes)) + && ub_checks::can_dereference(core::ptr::slice_from_raw_parts(right, bytes)))] + #[allow(dead_code)] + unsafe fn compare_bytes_model(left: *const u8, right: *const u8, bytes: usize) -> i32 { + // SAFETY: guaranteed by the precondition. + unsafe { compare_bytes(left, right, bytes) } + } + + // Both buffers fully initialized; `right` may alias `buffer1`. BOUNDED DOMAIN: Kani lowers + // the intrinsic to CBMC's built-in `memcmp` loop, which cannot take a loop + // invariant, so the range is capped at `MAX_BYTES = 64` with matching + // `kani::unwind`; the bound limits the checked instances, not the contract. + const MAX_BYTES: usize = 64; + + #[kani::proof_for_contract(compare_bytes_model)] + #[kani::unwind(65)] // MAX_BYTES + 1 + fn check_compare_bytes() { + const N: usize = MAX_BYTES; + let mut buffer1 = [MaybeUninit::::uninit(); N]; + let mut buffer2 = [MaybeUninit::::uninit(); N]; + for i in 0..N { + buffer1[i] = MaybeUninit::new(kani::any()); + buffer2[i] = MaybeUninit::new(kani::any()); + } + let gen_any_ptr = |buf: &[MaybeUninit; N]| -> *const u8 { + (buf.as_ptr() as *const u8).wrapping_add(kani::any_where(|o: &usize| *o < N)) + }; + let left = gen_any_ptr(&buffer1); + // `right` may alias `buffer1` or point into a separate allocation. + let right = if kani::any() { gen_any_ptr(&buffer2) } else { gen_any_ptr(&buffer1) }; + // Unconstrained `bytes` is pruned to `<= MAX_BYTES` by `can_dereference`. + let bytes: usize = kani::any(); + kani::cover(bytes > 0, "compare_bytes compares a non-empty range"); + let _ = unsafe { compare_bytes_model(left, right, bytes) }; + } + + // FIXME: Enable this harness once is fixed. + // Harness triggers a spurious failure when writing 0 bytes to an invalid memory location, + // which is a safe operation. + // + // Superseded by `write_bytes_wrapper` + `check_write_bytes_*` above, which + // carry a contract and keep `dst` in a live allocation (sidestepping #90). + + fn run_with_arbitrary_ptrs(harness: impl Fn(*mut T, *mut T)) { + let mut generator1 = PointerGenerator::<100>::new(); + let mut generator2 = PointerGenerator::<100>::new(); + let ArbitraryPointer { ptr: src, status: src_status, .. } = + generator1.any_alloc_status::(); + let ArbitraryPointer { ptr: dst, status: dst_status, .. } = if kani::any() { + generator1.any_alloc_status::() + } else { + generator2.any_alloc_status::() + }; + kani::assume(supported_status(src_status)); + kani::assume(supported_status(dst_status)); + harness(src, dst); + } + + /// Return whether the current status is supported by Kani's contract. + /// + /// Kani memory predicates currently doesn't support pointers to dangling or dead allocations. + /// Thus, we have to explicitly exclude those cases. + fn supported_status(status: AllocationStatus) -> bool { + status != AllocationStatus::Dangling && status != AllocationStatus::DeadObject + } + + // Challenge 7, Part 3: atomic intrinsic contracts. + // + // Kani cannot currently attach contracts directly to bodyless + // `rustc_intrinsic` declarations (model-checking/kani#3345). These wrappers + // are the Kani-facing specifications for the const-generic intrinsics above. + // The harness instantiations follow the integer and pointer restrictions in + // the intrinsic documentation, while the contracts encode the local memory + // obligations and valid `AtomicOrdering` constraints required by the + // intrinsic calls. + // + // `can_dereference` and `can_write` express local memory requirements for `T`. + // Checking initialization through `can_dereference` requires `-Z uninit-checks`. + // These single-threaded proofs do not establish the absence of data races or + // unsynchronized mixed-size overlapping atomic accesses. The load and store + // wrappers cover non-volatile accesses only; volatile accesses have separate + // safety requirements. + + #[allow(dead_code)] + #[kani::modifies(dst)] + #[requires( + ORD == AtomicOrdering::Relaxed + || ORD == AtomicOrdering::Release + || ORD == AtomicOrdering::SeqCst + )] + #[requires(crate::ub_checks::can_write(dst))] + unsafe fn atomic_store_wrapper(dst: *mut T, val: T) { + unsafe { atomic_store::(dst, val) } + } + + #[allow(dead_code)] + #[requires( + ORD == AtomicOrdering::Relaxed + || ORD == AtomicOrdering::Acquire + || ORD == AtomicOrdering::SeqCst + )] + #[requires((ORD == AtomicOrdering::Relaxed && crate::sync::atomic::small_read_only_atomic_load::()) + || crate::ub_checks::can_write(src as *mut T))] + #[requires(crate::ub_checks::can_dereference(src))] + unsafe fn atomic_load_wrapper(src: *const T) -> T { + unsafe { atomic_load::(src) } + } + + #[allow(dead_code)] + #[kani::modifies(dst)] + #[requires(crate::ub_checks::can_dereference(dst as *const T))] + #[requires(crate::ub_checks::can_write(dst))] + unsafe fn atomic_xchg_wrapper(dst: *mut T, val: T) -> T { + unsafe { atomic_xchg::(dst, val) } + } + + macro_rules! define_atomic_binary_rmw_wrapper { + ($wrapper:ident, $intrinsic:ident) => { + #[allow(dead_code)] + #[kani::modifies(dst)] + #[requires(crate::ub_checks::can_dereference(dst as *const T))] + #[requires(crate::ub_checks::can_write(dst))] + unsafe fn $wrapper( + dst: *mut T, + val: U, + ) -> T { + unsafe { $intrinsic::(dst, val) } + } + }; + } + + define_atomic_binary_rmw_wrapper!(atomic_xadd_wrapper, atomic_xadd); + define_atomic_binary_rmw_wrapper!(atomic_xsub_wrapper, atomic_xsub); + define_atomic_binary_rmw_wrapper!(atomic_and_wrapper, atomic_and); + define_atomic_binary_rmw_wrapper!(atomic_nand_wrapper, atomic_nand); + define_atomic_binary_rmw_wrapper!(atomic_or_wrapper, atomic_or); + define_atomic_binary_rmw_wrapper!(atomic_xor_wrapper, atomic_xor); + + macro_rules! define_atomic_extremum_wrapper { + ($wrapper:ident, $intrinsic:ident) => { + #[allow(dead_code)] + #[kani::modifies(dst)] + #[requires(crate::ub_checks::can_dereference(dst as *const T))] + #[requires(crate::ub_checks::can_write(dst))] + unsafe fn $wrapper(dst: *mut T, val: T) -> T { + unsafe { $intrinsic::(dst, val) } + } + }; + } + + define_atomic_extremum_wrapper!(atomic_max_wrapper, atomic_max); + define_atomic_extremum_wrapper!(atomic_min_wrapper, atomic_min); + define_atomic_extremum_wrapper!(atomic_umax_wrapper, atomic_umax); + define_atomic_extremum_wrapper!(atomic_umin_wrapper, atomic_umin); + + macro_rules! define_atomic_compare_exchange_wrapper { + ($wrapper:ident, $intrinsic:ident) => { + #[allow(dead_code)] + #[kani::modifies(dst)] + #[requires( + ORD_FAIL == AtomicOrdering::Relaxed + || ORD_FAIL == AtomicOrdering::Acquire + || ORD_FAIL == AtomicOrdering::SeqCst + )] + #[requires(crate::ub_checks::can_dereference(dst as *const T))] + #[requires(crate::ub_checks::can_write(dst))] + unsafe fn $wrapper< + T: Copy, + const ORD_SUCC: AtomicOrdering, + const ORD_FAIL: AtomicOrdering, + >( + dst: *mut T, + old: T, + new: T, + ) -> (T, bool) { + unsafe { $intrinsic::(dst, old, new) } + } + }; + } + + define_atomic_compare_exchange_wrapper!(atomic_cxchg_wrapper, atomic_cxchg); + define_atomic_compare_exchange_wrapper!(atomic_cxchgweak_wrapper, atomic_cxchgweak); + + // Every ordering-specific harness below expands to every legal integer + // width and to the pointer form. Storage is a local object, so the raw + // pointer passed to the intrinsic has concrete provenance without a + // separate wrapper type. Pointer *values* remain arbitrary addresses. + macro_rules! atomic_integer_load_store_types { + ($call:ident, $($args:tt)*) => { + #[cfg(target_has_atomic_load_store = "8")] { $call!(i8, $($args)*); $call!(u8, $($args)*); } + #[cfg(target_has_atomic_load_store = "16")] { $call!(i16, $($args)*); $call!(u16, $($args)*); } + #[cfg(target_has_atomic_load_store = "32")] { $call!(i32, $($args)*); $call!(u32, $($args)*); } + #[cfg(target_has_atomic_load_store = "64")] { $call!(i64, $($args)*); $call!(u64, $($args)*); } + #[cfg(target_has_atomic_load_store = "128")] { $call!(i128, $($args)*); $call!(u128, $($args)*); } + #[cfg(target_has_atomic_load_store = "ptr")] { $call!(isize, $($args)*); $call!(usize, $($args)*); } + }; + } + + macro_rules! atomic_integer_types { + ($call:ident, $($args:tt)*) => { + #[cfg(target_has_atomic = "8")] { $call!(i8, $($args)*); $call!(u8, $($args)*); } + #[cfg(target_has_atomic = "16")] { $call!(i16, $($args)*); $call!(u16, $($args)*); } + #[cfg(target_has_atomic = "32")] { $call!(i32, $($args)*); $call!(u32, $($args)*); } + #[cfg(target_has_atomic = "64")] { $call!(i64, $($args)*); $call!(u64, $($args)*); } + #[cfg(target_has_atomic = "128")] { $call!(i128, $($args)*); $call!(u128, $($args)*); } + #[cfg(target_has_atomic = "ptr")] { $call!(isize, $($args)*); $call!(usize, $($args)*); } + }; + } + + macro_rules! atomic_signed_types { + ($call:ident, $($args:tt)*) => { + #[cfg(target_has_atomic = "8")] { $call!(i8, $($args)*); } + #[cfg(target_has_atomic = "16")] { $call!(i16, $($args)*); } + #[cfg(target_has_atomic = "32")] { $call!(i32, $($args)*); } + #[cfg(target_has_atomic = "64")] { $call!(i64, $($args)*); } + #[cfg(target_has_atomic = "128")] { $call!(i128, $($args)*); } + #[cfg(target_has_atomic = "ptr")] { $call!(isize, $($args)*); } + }; + } + + macro_rules! atomic_unsigned_types { + ($call:ident, $($args:tt)*) => { + #[cfg(target_has_atomic = "8")] { $call!(u8, $($args)*); } + #[cfg(target_has_atomic = "16")] { $call!(u16, $($args)*); } + #[cfg(target_has_atomic = "32")] { $call!(u32, $($args)*); } + #[cfg(target_has_atomic = "64")] { $call!(u64, $($args)*); } + #[cfg(target_has_atomic = "128")] { $call!(u128, $($args)*); } + #[cfg(target_has_atomic = "ptr")] { $call!(usize, $($args)*); } + }; + } + + // Store: integer and pointer T, with the three orderings accepted by the + // intrinsic's stabilized atomic counterpart. + macro_rules! atomic_store_call { + ($ty:ty, $ord:path) => {{ + let mut dst: $ty = kani::any(); + let val: $ty = kani::any(); + unsafe { atomic_store_wrapper::<$ty, { $ord }>(&mut dst, val) }; + }}; + } + macro_rules! atomic_store_harness { + ($name:ident, $ord:path) => { + #[kani::proof_for_contract(atomic_store_wrapper)] + fn $name() { + atomic_integer_load_store_types!(atomic_store_call, $ord); + #[cfg(target_has_atomic_load_store = "ptr")] + { + let mut dst: *mut u8 = kani::any::() as *mut u8; + let val: *mut u8 = kani::any::() as *mut u8; + unsafe { atomic_store_wrapper::<*mut u8, { $ord }>(&mut dst, val) }; + } + kani::cover(true, "atomic intrinsic store: reached after call"); + } + }; + } + atomic_store_harness!(harness_intrinsic_atomic_store_relaxed, AtomicOrdering::Relaxed); + atomic_store_harness!(harness_intrinsic_atomic_store_release, AtomicOrdering::Release); + atomic_store_harness!(harness_intrinsic_atomic_store_seqcst, AtomicOrdering::SeqCst); + + // Load: the same complete T matrix as store. + macro_rules! atomic_load_call { + ($ty:ty, $ord:path) => {{ + let src: $ty = kani::any(); + let _ = unsafe { atomic_load_wrapper::<$ty, { $ord }>(&src) }; + }}; + } + macro_rules! atomic_load_harness { + ($name:ident, $ord:path) => { + #[kani::proof_for_contract(atomic_load_wrapper)] + fn $name() { + atomic_integer_load_store_types!(atomic_load_call, $ord); + #[cfg(target_has_atomic_load_store = "ptr")] + { + let src: *mut u8 = kani::any::() as *mut u8; + let _ = unsafe { atomic_load_wrapper::<*mut u8, { $ord }>(&src) }; + } + kani::cover(true, "atomic intrinsic load: reached after call"); + } + }; + } + atomic_load_harness!(harness_intrinsic_atomic_load_relaxed, AtomicOrdering::Relaxed); + atomic_load_harness!(harness_intrinsic_atomic_load_acquire, AtomicOrdering::Acquire); + atomic_load_harness!(harness_intrinsic_atomic_load_seqcst, AtomicOrdering::SeqCst); + + // Unary RMW operations (swap, xchg): integer and pointer T. + macro_rules! atomic_rmw_call { + ($ty:ty, $wrapper:ident, $ord:path) => {{ + let mut dst: $ty = kani::any(); + let val: $ty = kani::any(); + let _ = unsafe { $wrapper::<$ty, { $ord }>(&mut dst, val) }; + }}; + } + macro_rules! atomic_rmw_harness { + ($name:ident, $wrapper:ident, $ord:path) => { + #[kani::proof_for_contract($wrapper)] + fn $name() { + atomic_integer_types!(atomic_rmw_call, $wrapper, $ord); + #[cfg(target_has_atomic = "ptr")] + { + let mut dst: *mut u8 = kani::any::() as *mut u8; + let val: *mut u8 = kani::any::() as *mut u8; + let _ = unsafe { $wrapper::<*mut u8, { $ord }>(&mut dst, val) }; + } + kani::cover(true, "atomic intrinsic exchange: reached after call"); + } + }; + } + macro_rules! atomic_rmw_orders { + ($wrapper:ident, $relaxed:ident, $acquire:ident, $release:ident, $acqrel:ident, $seqcst:ident) => { + atomic_rmw_harness!($relaxed, $wrapper, AtomicOrdering::Relaxed); + atomic_rmw_harness!($acquire, $wrapper, AtomicOrdering::Acquire); + atomic_rmw_harness!($release, $wrapper, AtomicOrdering::Release); + atomic_rmw_harness!($acqrel, $wrapper, AtomicOrdering::AcqRel); + atomic_rmw_harness!($seqcst, $wrapper, AtomicOrdering::SeqCst); + }; + } + atomic_rmw_orders!( + atomic_xchg_wrapper, + harness_intrinsic_atomic_xchg_relaxed, + harness_intrinsic_atomic_xchg_acquire, + harness_intrinsic_atomic_xchg_release, + harness_intrinsic_atomic_xchg_acqrel, + harness_intrinsic_atomic_xchg_seqcst + ); + + // Binary RMW operations: U == T for integer T, and U == usize for pointer T. + macro_rules! atomic_binary_call { + ($ty:ty, $wrapper:ident, $ord:path) => {{ + let mut dst: $ty = kani::any(); + let val: $ty = kani::any(); + let _ = unsafe { $wrapper::<$ty, $ty, { $ord }>(&mut dst, val) }; + }}; + } + macro_rules! atomic_binary_harness { + ($name:ident, $wrapper:ident, $ord:path) => { + #[kani::proof_for_contract($wrapper)] + fn $name() { + atomic_integer_types!(atomic_binary_call, $wrapper, $ord); + #[cfg(target_has_atomic = "ptr")] + { + let mut dst: *mut u8 = kani::any::() as *mut u8; + let val: usize = kani::any(); + let _ = unsafe { $wrapper::<*mut u8, usize, { $ord }>(&mut dst, val) }; + } + kani::cover(true, "atomic intrinsic binary RMW: reached after call"); + } + }; + } + macro_rules! atomic_binary_orders { + ($wrapper:ident, $relaxed:ident, $acquire:ident, $release:ident, $acqrel:ident, $seqcst:ident) => { + atomic_binary_harness!($relaxed, $wrapper, AtomicOrdering::Relaxed); + atomic_binary_harness!($acquire, $wrapper, AtomicOrdering::Acquire); + atomic_binary_harness!($release, $wrapper, AtomicOrdering::Release); + atomic_binary_harness!($acqrel, $wrapper, AtomicOrdering::AcqRel); + atomic_binary_harness!($seqcst, $wrapper, AtomicOrdering::SeqCst); + }; + } + atomic_binary_orders!( + atomic_xadd_wrapper, + harness_intrinsic_atomic_xadd_relaxed, + harness_intrinsic_atomic_xadd_acquire, + harness_intrinsic_atomic_xadd_release, + harness_intrinsic_atomic_xadd_acqrel, + harness_intrinsic_atomic_xadd_seqcst + ); + atomic_binary_orders!( + atomic_xsub_wrapper, + harness_intrinsic_atomic_xsub_relaxed, + harness_intrinsic_atomic_xsub_acquire, + harness_intrinsic_atomic_xsub_release, + harness_intrinsic_atomic_xsub_acqrel, + harness_intrinsic_atomic_xsub_seqcst + ); + atomic_binary_orders!( + atomic_and_wrapper, + harness_intrinsic_atomic_and_relaxed, + harness_intrinsic_atomic_and_acquire, + harness_intrinsic_atomic_and_release, + harness_intrinsic_atomic_and_acqrel, + harness_intrinsic_atomic_and_seqcst + ); + atomic_binary_orders!( + atomic_nand_wrapper, + harness_intrinsic_atomic_nand_relaxed, + harness_intrinsic_atomic_nand_acquire, + harness_intrinsic_atomic_nand_release, + harness_intrinsic_atomic_nand_acqrel, + harness_intrinsic_atomic_nand_seqcst + ); + atomic_binary_orders!( + atomic_or_wrapper, + harness_intrinsic_atomic_or_relaxed, + harness_intrinsic_atomic_or_acquire, + harness_intrinsic_atomic_or_release, + harness_intrinsic_atomic_or_acqrel, + harness_intrinsic_atomic_or_seqcst + ); + atomic_binary_orders!( + atomic_xor_wrapper, + harness_intrinsic_atomic_xor_relaxed, + harness_intrinsic_atomic_xor_acquire, + harness_intrinsic_atomic_xor_release, + harness_intrinsic_atomic_xor_acqrel, + harness_intrinsic_atomic_xor_seqcst + ); + + // Signed and unsigned extrema have the restricted T matrices documented by + // atomic_max/min and atomic_umax/umin respectively. + macro_rules! atomic_extremum_call { + ($ty:ty, $wrapper:ident, $ord:path) => {{ + let mut dst: $ty = kani::any(); + let val: $ty = kani::any(); + let _ = unsafe { $wrapper::<$ty, { $ord }>(&mut dst, val) }; + }}; + } + macro_rules! atomic_extremum_harness { + ($name:ident, $wrapper:ident, $types:ident, $ord:path) => { + #[kani::proof_for_contract($wrapper)] + fn $name() { + $types!(atomic_extremum_call, $wrapper, $ord); + kani::cover(true, "atomic intrinsic extremum: reached after call"); + } + }; + } + macro_rules! atomic_extremum_orders { + ($wrapper:ident, $types:ident, $relaxed:ident, $acquire:ident, $release:ident, $acqrel:ident, $seqcst:ident) => { + atomic_extremum_harness!($relaxed, $wrapper, $types, AtomicOrdering::Relaxed); + atomic_extremum_harness!($acquire, $wrapper, $types, AtomicOrdering::Acquire); + atomic_extremum_harness!($release, $wrapper, $types, AtomicOrdering::Release); + atomic_extremum_harness!($acqrel, $wrapper, $types, AtomicOrdering::AcqRel); + atomic_extremum_harness!($seqcst, $wrapper, $types, AtomicOrdering::SeqCst); + }; + } + atomic_extremum_orders!( + atomic_max_wrapper, + atomic_signed_types, + harness_intrinsic_atomic_max_relaxed, + harness_intrinsic_atomic_max_acquire, + harness_intrinsic_atomic_max_release, + harness_intrinsic_atomic_max_acqrel, + harness_intrinsic_atomic_max_seqcst + ); + atomic_extremum_orders!( + atomic_min_wrapper, + atomic_signed_types, + harness_intrinsic_atomic_min_relaxed, + harness_intrinsic_atomic_min_acquire, + harness_intrinsic_atomic_min_release, + harness_intrinsic_atomic_min_acqrel, + harness_intrinsic_atomic_min_seqcst + ); + atomic_extremum_orders!( + atomic_umax_wrapper, + atomic_unsigned_types, + harness_intrinsic_atomic_umax_relaxed, + harness_intrinsic_atomic_umax_acquire, + harness_intrinsic_atomic_umax_release, + harness_intrinsic_atomic_umax_acqrel, + harness_intrinsic_atomic_umax_seqcst + ); + atomic_extremum_orders!( + atomic_umin_wrapper, + atomic_unsigned_types, + harness_intrinsic_atomic_umin_relaxed, + harness_intrinsic_atomic_umin_acquire, + harness_intrinsic_atomic_umin_release, + harness_intrinsic_atomic_umin_acqrel, + harness_intrinsic_atomic_umin_seqcst + ); + + // Compare exchange uses all integer/pointer T types for every legal + // success/failure ordering pair. Failure orderings are exactly the three + // values listed in the intrinsic documentation. + macro_rules! atomic_cxchg_call { + ($ty:ty, $wrapper:ident, $succ:path, $fail:path) => {{ + let mut dst: $ty = kani::any(); + let old: $ty = kani::any(); + let new: $ty = kani::any(); + let _ = unsafe { $wrapper::<$ty, { $succ }, { $fail }>(&mut dst, old, new) }; + }}; + } + macro_rules! atomic_cxchg_harness { + ($name:ident, $wrapper:ident, $succ:path, $fail:path) => { + #[kani::proof_for_contract($wrapper)] + fn $name() { + atomic_integer_types!(atomic_cxchg_call, $wrapper, $succ, $fail); + #[cfg(target_has_atomic = "ptr")] + { + let mut dst: *mut u8 = kani::any::() as *mut u8; + let old: *mut u8 = kani::any::() as *mut u8; + let new: *mut u8 = kani::any::() as *mut u8; + let _ = + unsafe { $wrapper::<*mut u8, { $succ }, { $fail }>(&mut dst, old, new) }; + } + kani::cover(true, "atomic intrinsic compare-exchange: reached after call"); + } + }; + } + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchg_relaxed_relaxed, + atomic_cxchg_wrapper, + AtomicOrdering::Relaxed, + AtomicOrdering::Relaxed + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchg_relaxed_acquire, + atomic_cxchg_wrapper, + AtomicOrdering::Relaxed, + AtomicOrdering::Acquire + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchg_relaxed_seqcst, + atomic_cxchg_wrapper, + AtomicOrdering::Relaxed, + AtomicOrdering::SeqCst + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchg_acquire_relaxed, + atomic_cxchg_wrapper, + AtomicOrdering::Acquire, + AtomicOrdering::Relaxed + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchg_acquire_acquire, + atomic_cxchg_wrapper, + AtomicOrdering::Acquire, + AtomicOrdering::Acquire + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchg_acquire_seqcst, + atomic_cxchg_wrapper, + AtomicOrdering::Acquire, + AtomicOrdering::SeqCst + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchg_release_relaxed, + atomic_cxchg_wrapper, + AtomicOrdering::Release, + AtomicOrdering::Relaxed + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchg_release_acquire, + atomic_cxchg_wrapper, + AtomicOrdering::Release, + AtomicOrdering::Acquire + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchg_release_seqcst, + atomic_cxchg_wrapper, + AtomicOrdering::Release, + AtomicOrdering::SeqCst + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchg_acqrel_relaxed, + atomic_cxchg_wrapper, + AtomicOrdering::AcqRel, + AtomicOrdering::Relaxed + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchg_acqrel_acquire, + atomic_cxchg_wrapper, + AtomicOrdering::AcqRel, + AtomicOrdering::Acquire + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchg_acqrel_seqcst, + atomic_cxchg_wrapper, + AtomicOrdering::AcqRel, + AtomicOrdering::SeqCst + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchg_seqcst_relaxed, + atomic_cxchg_wrapper, + AtomicOrdering::SeqCst, + AtomicOrdering::Relaxed + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchg_seqcst_acquire, + atomic_cxchg_wrapper, + AtomicOrdering::SeqCst, + AtomicOrdering::Acquire + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchg_seqcst_seqcst, + atomic_cxchg_wrapper, + AtomicOrdering::SeqCst, + AtomicOrdering::SeqCst + ); + + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchgweak_relaxed_relaxed, + atomic_cxchgweak_wrapper, + AtomicOrdering::Relaxed, + AtomicOrdering::Relaxed + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchgweak_relaxed_acquire, + atomic_cxchgweak_wrapper, + AtomicOrdering::Relaxed, + AtomicOrdering::Acquire + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchgweak_relaxed_seqcst, + atomic_cxchgweak_wrapper, + AtomicOrdering::Relaxed, + AtomicOrdering::SeqCst + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchgweak_acquire_relaxed, + atomic_cxchgweak_wrapper, + AtomicOrdering::Acquire, + AtomicOrdering::Relaxed + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchgweak_acquire_acquire, + atomic_cxchgweak_wrapper, + AtomicOrdering::Acquire, + AtomicOrdering::Acquire + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchgweak_acquire_seqcst, + atomic_cxchgweak_wrapper, + AtomicOrdering::Acquire, + AtomicOrdering::SeqCst + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchgweak_release_relaxed, + atomic_cxchgweak_wrapper, + AtomicOrdering::Release, + AtomicOrdering::Relaxed + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchgweak_release_acquire, + atomic_cxchgweak_wrapper, + AtomicOrdering::Release, + AtomicOrdering::Acquire + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchgweak_release_seqcst, + atomic_cxchgweak_wrapper, + AtomicOrdering::Release, + AtomicOrdering::SeqCst + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchgweak_acqrel_relaxed, + atomic_cxchgweak_wrapper, + AtomicOrdering::AcqRel, + AtomicOrdering::Relaxed + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchgweak_acqrel_acquire, + atomic_cxchgweak_wrapper, + AtomicOrdering::AcqRel, + AtomicOrdering::Acquire + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchgweak_acqrel_seqcst, + atomic_cxchgweak_wrapper, + AtomicOrdering::AcqRel, + AtomicOrdering::SeqCst + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchgweak_seqcst_relaxed, + atomic_cxchgweak_wrapper, + AtomicOrdering::SeqCst, + AtomicOrdering::Relaxed + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchgweak_seqcst_acquire, + atomic_cxchgweak_wrapper, + AtomicOrdering::SeqCst, + AtomicOrdering::Acquire + ); + atomic_cxchg_harness!( + harness_intrinsic_atomic_cxchgweak_seqcst_seqcst, + atomic_cxchgweak_wrapper, + AtomicOrdering::SeqCst, + AtomicOrdering::SeqCst + ); +} + +/// Returns the return address of the caller function (after inlining) in a best-effort manner or a null pointer if it is not supported on the current backend. +/// Returning an accurate value is a quality-of-implementation concern, but no hard guarantees are +/// made about the return value: formally, the intrinsic non-deterministically returns +/// an arbitrary pointer without provenance. +/// +/// Note that unlike most intrinsics, this is safe to call. This is because it only finds the return address of the immediate caller, which is guaranteed to be possible. +/// Other forms of the corresponding gcc or llvm intrinsic (which can have wildly unpredictable results or even crash at runtime) are not exposed. +#[rustc_intrinsic] +#[rustc_nounwind] +pub fn return_address() -> *const () { + core::ptr::null() +} diff --git a/verifast-proofs/core/sync/atomic.rs/original/lib.rs b/verifast-proofs/core/sync/atomic.rs/original/lib.rs new file mode 100644 index 0000000000000..d568f465c26d8 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/original/lib.rs @@ -0,0 +1,430 @@ +//! # The Rust Core Library +//! +//! The Rust Core Library is the dependency-free[^free] foundation of [The +//! Rust Standard Library](../std/index.html). It is the portable glue +//! between the language and its libraries, defining the intrinsic and +//! primitive building blocks of all Rust code. It links to no +//! upstream libraries, no system libraries, and no libc. +//! +//! [^free]: Strictly speaking, there are some symbols which are needed but +//! they aren't always necessary. +//! +//! The core library is *minimal*: it isn't even aware of heap allocation, +//! nor does it provide concurrency or I/O. These things require +//! platform integration, and this library is platform-agnostic. +//! +//! # How to use the core library +//! +//! Please note that all of these details are currently not considered stable. +//! +// FIXME: Fill me in with more detail when the interface settles +//! This library is built on the assumption of a few existing symbols: +//! +//! * `memcpy`, `memmove`, `memset`, `memcmp`, `bcmp`, `strlen` - These are core memory routines +//! which are generated by Rust codegen backends. Additionally, this library can make explicit +//! calls to `strlen`. Their signatures are the same as found in C, but there are extra +//! assumptions about their semantics: For `memcpy`, `memmove`, `memset`, `memcmp`, and `bcmp`, if +//! the `n` parameter is 0, the function is assumed to not be UB, even if the pointers are NULL or +//! dangling. (Note that making extra assumptions about these functions is common among compilers: +//! [clang](https://reviews.llvm.org/D86993) and [GCC](https://gcc.gnu.org/onlinedocs/gcc/Standards.html#C-Language) do the same.) +//! These functions are often provided by the system libc, but can also be provided by the +//! [compiler-builtins crate](https://crates.io/crates/compiler_builtins). +//! Note that the library does not guarantee that it will always make these assumptions, so Rust +//! user code directly calling the C functions should follow the C specification! The advice for +//! Rust user code is to call the functions provided by this library instead (such as +//! `ptr::copy`). +//! +//! * Panic handler - This function takes one argument, a `&panic::PanicInfo`. It is up to consumers of this core +//! library to define this panic function; it is only required to never +//! return. You should mark your implementation using `#[panic_handler]`. +//! +//! * `rust_eh_personality` - is used by the failure mechanisms of the +//! compiler. This is often mapped to GCC's personality function, but crates +//! which do not trigger a panic can be assured that this function is never +//! called. The `lang` attribute is called `eh_personality`. + +#![stable(feature = "core", since = "1.6.0")] +#![doc( + html_playground_url = "https://play.rust-lang.org/", + issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/", + test(no_crate_inject, attr(deny(warnings))), + test(attr(allow(dead_code, deprecated, unused_variables, unused_mut, duplicate_features))) +)] +#![doc(rust_logo)] +#![doc(auto_cfg( + hide(no_fp_fmt_parse), + hide(target_pointer_width, values("16", "32", "64")), + hide( + target_has_atomic, + target_has_atomic_primitive_alignment, + target_has_atomic_load_store, + values("8", "16", "32", "64", "ptr"), + ), +))] +#![no_core] +#![rustc_coherence_is_core] +#![rustc_preserve_ub_checks] +// +// Lints: +#![deny(rust_2021_incompatible_or_patterns)] +#![deny(unsafe_op_in_unsafe_fn)] +#![deny(implicit_provenance_casts)] +#![warn(deprecated_in_future)] +#![warn(missing_debug_implementations)] +#![warn(missing_docs)] +#![allow(explicit_outlives_requirements)] +#![allow(incomplete_features)] +#![warn(multiple_supertrait_upcastable)] +#![allow(internal_features)] +#![allow(unused_features)] +#![deny(ffi_unwind_calls)] +#![warn(unreachable_pub)] +// Do not check link redundancy on bootstrapping phase +#![allow(rustdoc::redundant_explicit_links)] +#![warn(rustdoc::unescaped_backticks)] +// +// Library features: +// tidy-alphabetical-start +#![feature(asm_experimental_arch)] +#![feature(byte_str_internals)] +#![feature(cfg_target_has_reliable_f16_f128)] +#![feature(cfg_target_has_reliable_f16b)] +#![feature(const_cmp)] +#![feature(const_destruct)] +#![feature(const_eval_select)] +#![feature(const_select_unpredictable)] +#![feature(core_intrinsics)] +#![feature(coverage_attribute)] +#![feature(disjoint_bitor)] +#![feature(io_const_error)] +#![feature(offset_of_enum)] +#![feature(panic_internals)] +#![feature(pattern_types)] +#![feature(ub_checks)] +// tidy-alphabetical-end +// +// Language features: +// tidy-alphabetical-start +#![feature(adt_const_params)] +#![feature(allow_internal_unsafe)] +#![feature(allow_internal_unstable)] +#![feature(arbitrary_self_types_pointers)] +#![feature(auto_traits)] +#![feature(cfg_sanitize)] +#![feature(cfg_target_has_atomic)] +#![feature(cfg_ub_checks)] +#![feature(const_closures)] +#![feature(const_precise_live_drops)] +#![feature(const_trait_impl)] +#![feature(decl_macro)] +#![feature(deprecated_suggestion)] +#![feature(derive_const)] +#![feature(diagnostic_on_const)] +#![feature(diagnostic_on_unmatched_args)] +#![feature(diagnostic_opaque)] +#![feature(doc_cfg)] +#![feature(doc_notable_trait)] +#![feature(extern_types)] +#![feature(f16)] +#![feature(f128)] +#![feature(field_projections)] +#![feature(final_associated_functions)] +#![feature(forced_keywords)] +#![feature(freeze_impls)] +#![feature(fundamental)] +#![feature(impl_restriction)] +#![feature(intra_doc_pointers)] +#![feature(intrinsics)] +#![feature(lang_items)] +#![feature(link_cfg)] +#![feature(link_llvm_intrinsics)] +#![feature(macro_metavar_expr)] +#![feature(macro_metavar_expr_concat)] +#![feature(marker_trait_attr)] +#![feature(min_specialization)] +#![feature(move_trait)] +#![feature(multiple_supertrait_upcastable)] +#![feature(must_not_suspend)] +#![feature(negative_impls)] +#![feature(no_core)] +#![feature(pin_macro_internals)] +#![feature(prelude_import)] +#![feature(register_tool)] +// Flux injects `#![feature(register_tool)]` itself, which core now also enables (for +// `#![register_tool(lint)]`); allow the duplicate under Flux only. +#![cfg_attr(flux, allow(duplicate_features))] +#![feature(repr_simd)] +#![feature(rustc_attrs)] +#![feature(rustdoc_internals)] +#![feature(simd_ffi)] +#![feature(splat)] +#![feature(staged_api)] +#![feature(stmt_expr_attributes)] +#![feature(strict_provenance_lints)] +#![feature(trait_alias)] +#![feature(transparent_unions)] +#![feature(try_blocks)] +#![feature(uint_carryless_mul)] +#![feature(unboxed_closures)] +#![feature(unsized_fn_params)] +#![feature(with_negative_coherence)] +// Required for Kani loop contracts, which are annotated as custom stmt attributes. +#![feature(proc_macro_hygiene)] +// tidy-alphabetical-end +// +// Target features: +// tidy-alphabetical-start +#![feature(aarch64_unstable_target_feature)] +#![feature(arm_target_feature)] +#![feature(avx10_target_feature)] +#![feature(clflushopt_target_feature)] +#![feature(hexagon_target_feature)] +#![feature(loongarch_target_feature)] +#![feature(mips_target_feature)] +#![feature(movrs_target_feature)] +#![feature(nvptx_target_feature)] +#![feature(powerpc_target_feature)] +#![feature(riscv_target_feature)] +#![feature(rtm_target_feature)] +#![feature(s390x_target_feature)] +#![feature(wasm_target_feature)] +#![feature(x86_amx_intrinsics)] +// tidy-alphabetical-end + +// tidy-alphabetical-start +#![register_tool(lint)] +// tidy-alphabetical-end + +// tidy-alphabetical-start +#![expect(clippy::partialeq_ne_impl, reason = "we need to implement ne for a lot of core types")] +// tidy-alphabetical-end + +// allow using `core::` in intra-doc links +#[allow(unused_extern_crates)] +extern crate self as core; + +/* The core prelude, not as all-encompassing as the std prelude */ +// The compiler expects the prelude definition to be defined before it's use statement. +pub mod prelude; + +#[prelude_import] +#[allow(unused)] +use prelude::rust_2024::*; + +#[macro_use] +mod macros; + +#[stable(feature = "assert_matches", since = "1.96.0")] +pub use crate::macros::{assert_matches, debug_assert_matches}; + +#[unstable(feature = "derive_from", issue = "144889")] +/// Unstable module containing the unstable `From` derive macro. +pub mod from { + #[unstable(feature = "derive_from", issue = "144889")] + pub use crate::macros::builtin::From; +} + +// We don't export this through #[macro_export] for now, to avoid breakage. +#[unstable(feature = "autodiff", issue = "124509")] +#[doc = include_str!("../../core/src/autodiff.md")] +pub mod autodiff { + #[unstable(feature = "autodiff", issue = "124509")] + pub use crate::macros::builtin::{autodiff_forward, autodiff_reverse}; +} + +#[unstable(feature = "gpu_offload", issue = "131513")] +#[doc = include_str!("../../core/src/offload.md")] +pub mod offload; + +#[unstable(feature = "contracts", issue = "128044")] +pub mod contracts; + +#[allow(clippy::useless_attribute)] +#[expect( + ineffective_unstable_reexports, + reason = "accepted as stable after accidental stabilization in 1.96, see #154645" +)] +#[unstable(feature = "derive_macro_global_path", issue = "154645")] +pub use crate::macros::builtin::derive; +#[stable(feature = "cfg_select", since = "1.95.0")] +pub use crate::macros::cfg_select; + +#[macro_use] +mod internal_macros; + +#[path = "num/shells/legacy_int_modules.rs"] +mod legacy_int_modules; +#[stable(feature = "rust1", since = "1.0.0")] +#[allow(deprecated, clippy::legacy_numeric_constants)] +pub use legacy_int_modules::{i8, i16, i32, i64, isize, u8, u16, u32, u64, usize}; +#[stable(feature = "i128", since = "1.26.0")] +#[allow(deprecated, clippy::legacy_numeric_constants)] +pub use legacy_int_modules::{i128, u128}; + +#[macro_use] +pub mod num; + +#[path = "num/f128.rs"] +pub mod f128; +#[path = "num/f16.rs"] +pub mod f16; +#[path = "num/f32.rs"] +pub mod f32; +#[path = "num/f64.rs"] +pub mod f64; + +/* Core modules for ownership management */ + +pub mod hint; +pub mod intrinsics; +pub mod mem; +#[unstable(feature = "profiling_marker_api", issue = "148197")] +pub mod profiling; +pub mod ptr; +#[unstable(feature = "ub_checks", issue = "none")] +pub mod ub_checks; + +/* Core language traits */ + +pub mod borrow; +pub mod clone; +pub mod cmp; +pub mod convert; +pub mod default; +pub mod error; +#[unstable(feature = "field_projections", issue = "145383")] +pub mod field; +pub mod index; +pub mod marker; +pub mod ops; + +/* Core types and methods on primitives */ + +pub mod any; +pub mod array; +pub mod ascii; +pub mod asserting; +#[unstable(feature = "async_iterator", issue = "79024")] +pub mod async_iter; +#[unstable(feature = "byte_str", issue = "134915")] +pub mod byte_str; +pub mod cell; +pub mod char; +pub mod ffi; +#[unstable(feature = "core_io", issue = "154046")] +pub mod io; +pub mod iter; +pub mod net; +pub mod option; +pub mod os; +pub mod panic; +pub mod panicking; +#[unstable(feature = "pattern_types", issue = "123646")] +pub mod pat; +pub mod pin; +#[unstable(feature = "abort_immediate", issue = "154601")] +pub mod process; +#[unstable(feature = "random", issue = "130703")] +pub mod random; +#[stable(feature = "new_range_inclusive_api", since = "1.95.0")] +pub mod range; +pub mod result; +pub mod sync; +#[unstable(feature = "unsafe_binders", issue = "130516")] +pub mod unsafe_binder; + +pub mod fmt; +pub mod hash; +pub mod slice; +pub mod str; +pub mod time; + +pub mod wtf8; + +pub mod unicode; + +/* Async */ +pub mod future; +pub mod task; + +/* Heap memory allocator trait */ +pub mod alloc; + +// note: does not need to be public +mod bool; +mod escape; +mod tuple; +mod unit; +#[unstable(feature = "view_types", issue = "155938")] +pub mod view; + +#[stable(feature = "core_primitive", since = "1.43.0")] +pub mod primitive; + +#[cfg(kani)] +kani_core::kani_lib!(core); + +// Pull in the `core_arch` crate directly into core. The contents of +// `core_arch` are in a different repository: rust-lang/stdarch. +// +// `core_arch` depends on core, but the contents of this module are +// set up in such a way that directly pulling it here works such that the +// crate uses the this crate as its core. +#[path = "../../stdarch/crates/core_arch/src/mod.rs"] +#[allow( + missing_docs, + missing_debug_implementations, + dead_code, + unused_imports, + unsafe_op_in_unsafe_fn, + ambiguous_glob_reexports, + unreachable_pub, + // FIXME: stdach is a submodule so clippy lints should be fixed (and ideally enforced) there + clippy::all, +)] +#[allow(rustdoc::bare_urls)] +mod core_arch; + +#[stable(feature = "simd_arch", since = "1.27.0")] +pub mod arch; + +// Pull in the `core_simd` crate directly into core. The contents of +// `core_simd` are in a different repository: rust-lang/portable-simd. +// +// `core_simd` depends on core, but the contents of this module are +// set up in such a way that directly pulling it here works such that the +// crate uses this crate as its core. +#[path = "../../portable-simd/crates/core_simd/src/mod.rs"] +#[allow(missing_debug_implementations, dead_code, unsafe_op_in_unsafe_fn)] +#[allow(rustdoc::bare_urls)] +#[unstable(feature = "portable_simd", issue = "86656")] +mod core_simd; + +#[unstable(feature = "portable_simd", issue = "86656")] +pub mod simd { + #![doc = include_str!("../../portable-simd/crates/core_simd/src/core_simd_docs.md")] + + #[unstable(feature = "portable_simd", issue = "86656")] + pub use crate::core_simd::simd::*; +} + +// Include private modules that exist solely to provide rustdoc +// documentation for built-in attributes. Using `include!` because rustdoc +// only looks for these modules at the crate level. +include!("attribute_docs.rs"); + +// Include a number of private modules that exist solely to provide +// the rustdoc documentation for the existing keywords. Using `include!` +// because rustdoc only looks for these modules at the crate level. +include!("keyword_docs.rs"); + +// Include a number of private modules that exist solely to provide +// the rustdoc documentation for primitive types. Using `include!` +// because rustdoc only looks for these modules at the crate level. +include!("primitive_docs.rs"); + +#[cfg(flux)] +mod flux_info; + +#[cfg(rapx)] +mod rapx_macro {} diff --git a/verifast-proofs/core/sync/atomic.rs/part1-manifest.tsv b/verifast-proofs/core/sync/atomic.rs/part1-manifest.tsv new file mode 100644 index 0000000000000..93bf70abc0313 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/part1-manifest.tsv @@ -0,0 +1,13 @@ +required_type target production_mir_root client +AtomicBool x86_64-unknown-linux-gnu sync::atomic::{impl#4}::from_ptr ch7_bool::bool_round_trip +AtomicPtr x86_64-unknown-linux-gnu sync::atomic::{impl#5}::from_ptr ch7_pointer::exchange +AtomicI8 x86_64-unknown-linux-gnu sync::atomic::{impl#34}::from_ptr ch7_width::i8_view +AtomicU8 x86_64-unknown-linux-gnu sync::atomic::{impl#38}::from_ptr ch7_width::borrowed_view8 +AtomicI16 x86_64-unknown-linux-gnu sync::atomic::{impl#42}::from_ptr ch7_width::i16_view +AtomicU16 x86_64-unknown-linux-gnu sync::atomic::{impl#46}::from_ptr ch7_width::borrowed_view16 +AtomicI32 x86_64-unknown-linux-gnu sync::atomic::{impl#50}::from_ptr ch7_width::i32_view +AtomicU32 x86_64-unknown-linux-gnu sync::atomic::{impl#54}::from_ptr ch7_public::borrowed_from_ptr +AtomicI64 x86_64-unknown-linux-gnu sync::atomic::{impl#58}::from_ptr ch7_width::i64_view +AtomicU64 x86_64-unknown-linux-gnu sync::atomic::{impl#62}::from_ptr ch7_width::u64_view +AtomicI128 aarch64-unknown-linux-gnu sync::atomic::{impl#68}::from_ptr ch7_width::i128_view +AtomicU128 aarch64-unknown-linux-gnu sync::atomic::{impl#72}::from_ptr ch7_width::u128_view diff --git a/verifast-proofs/core/sync/atomic.rs/permission-inventory.tsv b/verifast-proofs/core/sync/atomic.rs/permission-inventory.tsv new file mode 100644 index 0000000000000..8b1babaec140b --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/permission-inventory.tsv @@ -0,0 +1,92 @@ +entry helper intrinsic ordering part2_required x86_64-unknown-linux-gnu aarch64-unknown-linux-gnu +atomic_store_relaxed atomic_store atomic_store Relaxed yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_store_release atomic_store atomic_store Release yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_store_seqcst atomic_store atomic_store SeqCst yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_load_relaxed atomic_load atomic_load Relaxed yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_load_acquire atomic_load atomic_load Acquire yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_load_seqcst atomic_load atomic_load SeqCst yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_xchg_relaxed atomic_swap atomic_xchg Relaxed yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_xchg_acquire atomic_swap atomic_xchg Acquire yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_xchg_release atomic_swap atomic_xchg Release yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_xchg_acqrel atomic_swap atomic_xchg AcqRel yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_xchg_seqcst atomic_swap atomic_xchg SeqCst yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_xadd_relaxed atomic_add atomic_xadd Relaxed yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_xadd_acquire atomic_add atomic_xadd Acquire yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_xadd_release atomic_add atomic_xadd Release yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_xadd_acqrel atomic_add atomic_xadd AcqRel yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_xadd_seqcst atomic_add atomic_xadd SeqCst yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_xsub_relaxed atomic_sub atomic_xsub Relaxed yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_xsub_acquire atomic_sub atomic_xsub Acquire yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_xsub_release atomic_sub atomic_xsub Release yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_xsub_acqrel atomic_sub atomic_xsub AcqRel yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_xsub_seqcst atomic_sub atomic_xsub SeqCst yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_cxchg_relaxed_relaxed atomic_compare_exchange atomic_cxchg Relaxed/Relaxed yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_cxchg_relaxed_acquire atomic_compare_exchange atomic_cxchg Relaxed/Acquire yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_cxchg_relaxed_seqcst atomic_compare_exchange atomic_cxchg Relaxed/SeqCst yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_cxchg_acquire_relaxed atomic_compare_exchange atomic_cxchg Acquire/Relaxed yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_cxchg_acquire_acquire atomic_compare_exchange atomic_cxchg Acquire/Acquire yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_cxchg_acquire_seqcst atomic_compare_exchange atomic_cxchg Acquire/SeqCst yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_cxchg_release_relaxed atomic_compare_exchange atomic_cxchg Release/Relaxed yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_cxchg_release_acquire atomic_compare_exchange atomic_cxchg Release/Acquire yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_cxchg_release_seqcst atomic_compare_exchange atomic_cxchg Release/SeqCst yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_cxchg_acqrel_relaxed atomic_compare_exchange atomic_cxchg AcqRel/Relaxed yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_cxchg_acqrel_acquire atomic_compare_exchange atomic_cxchg AcqRel/Acquire yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_cxchg_acqrel_seqcst atomic_compare_exchange atomic_cxchg AcqRel/SeqCst yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_cxchg_seqcst_relaxed atomic_compare_exchange atomic_cxchg SeqCst/Relaxed yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_cxchg_seqcst_acquire atomic_compare_exchange atomic_cxchg SeqCst/Acquire yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_cxchg_seqcst_seqcst atomic_compare_exchange atomic_cxchg SeqCst/SeqCst yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_cxchgweak_relaxed_relaxed atomic_compare_exchange_weak atomic_cxchgweak Relaxed/Relaxed yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_cxchgweak_relaxed_acquire atomic_compare_exchange_weak atomic_cxchgweak Relaxed/Acquire yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_cxchgweak_relaxed_seqcst atomic_compare_exchange_weak atomic_cxchgweak Relaxed/SeqCst yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_cxchgweak_acquire_relaxed atomic_compare_exchange_weak atomic_cxchgweak Acquire/Relaxed yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_cxchgweak_acquire_acquire atomic_compare_exchange_weak atomic_cxchgweak Acquire/Acquire yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_cxchgweak_acquire_seqcst atomic_compare_exchange_weak atomic_cxchgweak Acquire/SeqCst yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_cxchgweak_release_relaxed atomic_compare_exchange_weak atomic_cxchgweak Release/Relaxed yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_cxchgweak_release_acquire atomic_compare_exchange_weak atomic_cxchgweak Release/Acquire yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_cxchgweak_release_seqcst atomic_compare_exchange_weak atomic_cxchgweak Release/SeqCst yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_cxchgweak_acqrel_relaxed atomic_compare_exchange_weak atomic_cxchgweak AcqRel/Relaxed yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_cxchgweak_acqrel_acquire atomic_compare_exchange_weak atomic_cxchgweak AcqRel/Acquire yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_cxchgweak_acqrel_seqcst atomic_compare_exchange_weak atomic_cxchgweak AcqRel/SeqCst yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_cxchgweak_seqcst_relaxed atomic_compare_exchange_weak atomic_cxchgweak SeqCst/Relaxed yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_cxchgweak_seqcst_acquire atomic_compare_exchange_weak atomic_cxchgweak SeqCst/Acquire yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_cxchgweak_seqcst_seqcst atomic_compare_exchange_weak atomic_cxchgweak SeqCst/SeqCst yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_and_relaxed atomic_and atomic_and Relaxed yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_and_acquire atomic_and atomic_and Acquire yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_and_release atomic_and atomic_and Release yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_and_acqrel atomic_and atomic_and AcqRel yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_and_seqcst atomic_and atomic_and SeqCst yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_nand_relaxed atomic_nand atomic_nand Relaxed yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_nand_acquire atomic_nand atomic_nand Acquire yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_nand_release atomic_nand atomic_nand Release yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_nand_acqrel atomic_nand atomic_nand AcqRel yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_nand_seqcst atomic_nand atomic_nand SeqCst yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_or_seqcst atomic_or atomic_or SeqCst yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_or_acquire atomic_or atomic_or Acquire yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_or_release atomic_or atomic_or Release yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_or_acqrel atomic_or atomic_or AcqRel yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_or_relaxed atomic_or atomic_or Relaxed yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_xor_seqcst atomic_xor atomic_xor SeqCst yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_xor_acquire atomic_xor atomic_xor Acquire yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_xor_release atomic_xor atomic_xor Release yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_xor_acqrel atomic_xor atomic_xor AcqRel yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_xor_relaxed atomic_xor atomic_xor Relaxed yes i8,u8,i16,u16,i32,u32,i64,u64,isize,usize i8,u8,i16,u16,i32,u32,i64,u64,isize,usize,i128,u128 +atomic_max_relaxed atomic_max atomic_max Relaxed yes i8,i16,i32,i64,isize i8,i16,i32,i64,isize,i128 +atomic_max_acquire atomic_max atomic_max Acquire yes i8,i16,i32,i64,isize i8,i16,i32,i64,isize,i128 +atomic_max_release atomic_max atomic_max Release yes i8,i16,i32,i64,isize i8,i16,i32,i64,isize,i128 +atomic_max_acqrel atomic_max atomic_max AcqRel yes i8,i16,i32,i64,isize i8,i16,i32,i64,isize,i128 +atomic_max_seqcst atomic_max atomic_max SeqCst yes i8,i16,i32,i64,isize i8,i16,i32,i64,isize,i128 +atomic_min_relaxed atomic_min atomic_min Relaxed no i8,i16,i32,i64,isize i8,i16,i32,i64,isize,i128 +atomic_min_acquire atomic_min atomic_min Acquire no i8,i16,i32,i64,isize i8,i16,i32,i64,isize,i128 +atomic_min_release atomic_min atomic_min Release no i8,i16,i32,i64,isize i8,i16,i32,i64,isize,i128 +atomic_min_acqrel atomic_min atomic_min AcqRel no i8,i16,i32,i64,isize i8,i16,i32,i64,isize,i128 +atomic_min_seqcst atomic_min atomic_min SeqCst no i8,i16,i32,i64,isize i8,i16,i32,i64,isize,i128 +atomic_umax_relaxed atomic_umax atomic_umax Relaxed yes u8,u16,u32,u64,usize u8,u16,u32,u64,usize,u128 +atomic_umax_acquire atomic_umax atomic_umax Acquire yes u8,u16,u32,u64,usize u8,u16,u32,u64,usize,u128 +atomic_umax_release atomic_umax atomic_umax Release yes u8,u16,u32,u64,usize u8,u16,u32,u64,usize,u128 +atomic_umax_acqrel atomic_umax atomic_umax AcqRel yes u8,u16,u32,u64,usize u8,u16,u32,u64,usize,u128 +atomic_umax_seqcst atomic_umax atomic_umax SeqCst yes u8,u16,u32,u64,usize u8,u16,u32,u64,usize,u128 +atomic_umin_relaxed atomic_umin atomic_umin Relaxed yes u8,u16,u32,u64,usize u8,u16,u32,u64,usize,u128 +atomic_umin_acquire atomic_umin atomic_umin Acquire yes u8,u16,u32,u64,usize u8,u16,u32,u64,usize,u128 +atomic_umin_release atomic_umin atomic_umin Release yes u8,u16,u32,u64,usize u8,u16,u32,u64,usize,u128 +atomic_umin_acqrel atomic_umin atomic_umin AcqRel yes u8,u16,u32,u64,usize u8,u16,u32,u64,usize,u128 +atomic_umin_seqcst atomic_umin atomic_umin SeqCst yes u8,u16,u32,u64,usize u8,u16,u32,u64,usize,u128 diff --git a/verifast-proofs/core/sync/atomic.rs/platform.Cargo.lock b/verifast-proofs/core/sync/atomic.rs/platform.Cargo.lock new file mode 100644 index 0000000000000..f434f1f16f265 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/platform.Cargo.lock @@ -0,0 +1,16 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "libc" +version = "0.2.190" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" + +[[package]] +name = "platform" +version = "0.1.0" +dependencies = [ + "libc", +] diff --git a/verifast-proofs/core/sync/atomic.rs/specs/access.diff b/verifast-proofs/core/sync/atomic.rs/specs/access.diff new file mode 100644 index 0000000000000..211708c278b7a --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/specs/access.diff @@ -0,0 +1,342 @@ +--- a/sync/atomic.rs ++++ b/sync/atomic.rs +@@ -708,6 +708,52 @@ + SeqCst, + } + ++/*@ ++pred ordering_access(p: *T, needed: bool, f: real, af: real, inv_: fix(T, bool)) = ++ if needed { 0 < af &*& af <= 1 &*& [f]std::intrinsics::atomic_points_to::(p, af, inv_) } else { true }; ++fix bool_byte_slot(view: *Atomic) -> *u8 { ref_origin(view) as *u8 } ++lem begin_bool_access(view: *Atomic, k: lifetime_t, t: thread_id_t, q: real, needed: bool) ++ nonghost_callers_only ++ req [q]lifetime_token(k) &*& [_]Atomic_share::(k, t, view); ++ ens [_]frac_borrow(k, ref_initialized_(view)) &*& ordering_access(bool_byte_slot(view), needed, ?f, 1, valid_bool_byte) &*& ++ if needed { close_frac_borrow_token(f, bool_slot_content(ref_origin(view)), q, k) } else { [q]lifetime_token(k) }; ++{ ++ open Atomic_share::(k, t, view); ++ if needed { ++ let f = open_frac_borrow(k, bool_slot_content(ref_origin(view)), q); ++ open [f]bool_slot_content(ref_origin(view))(); ++ close ordering_access(bool_byte_slot(view), true, f, 1, valid_bool_byte); ++ } else { ++ close ordering_access(bool_byte_slot(view), false, 1, 1, valid_bool_byte); ++ } ++} ++lem end_bool_access(view: *Atomic) ++ nonghost_callers_only ++ req [?f]std::intrinsics::atomic_points_to::(bool_byte_slot(view), 1, valid_bool_byte) &*& ++ close_frac_borrow_token(f, bool_slot_content(ref_origin(view)), ?q, ?k); ++ ens [q]lifetime_token(k); ++{ ++ close [f]bool_slot_content(ref_origin(view))(); ++ close_frac_borrow(f, bool_slot_content(ref_origin(view))); ++} ++lem prepare_ordered_slot(view: *Atomic, p: *T, k: lifetime_t, t: thread_id_t, q: real, needed: bool) ++ nonghost_callers_only ++ req [q]lifetime_token(k) &*& [_]Atomic_share::(k, t, view) &*& ++ .atomic_content(ref_origin(view)) == unsigned_content::(p); ++ ens [_]frac_borrow(k, ref_initialized_(view)) &*& ordering_access(p, needed, ?f, 1, accepts_unsigned) &*& ++ if needed { close_frac_borrow_token(f, unsigned_content::(p), q, k) } else { [q]lifetime_token(k) }; ++{ ++ if needed { ++ open_rmw_slot(view, p, k, t, q); ++ assert [?f]std::intrinsics::atomic_points_to::(p, 1, accepts_unsigned); ++ close ordering_access(p, true, f, 1, accepts_unsigned); ++ } else { ++ open Atomic_share::(k, t, view); ++ close ordering_access(p, false, 1, 1, accepts_unsigned); ++ } ++} ++@*/ ++ + /// An [`AtomicBool`] initialized to `false`. + #[cfg(target_has_atomic_load_store = "8")] + #[stable(feature = "rust1", since = "1.0.0")] +@@ -987,7 +1049,14 @@ + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[requires(order == Relaxed || order == Acquire || order == SeqCst)] +- pub const fn load(&self, order: Ordering) -> bool { ++ pub const fn load(&self, order: Ordering) -> bool ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share::(k, currentThread, self) &*& Ordering_own(currentThread, order) &*& (if order == Ordering::Release || order == Ordering::AcqRel { thread_token(currentThread) } else { true }); ++ //@ ens [q]lifetime_token(k) &*& order != Ordering::Release &*& order != Ordering::AcqRel; ++ //@ on_unwind_ens [q]lifetime_token(k) &*& (order == Ordering::Release || order == Ordering::AcqRel) &*& thread_token(currentThread); ++ { ++ //@ open Ordering_own(currentThread, order); ++ //@ begin_bool_access(self, k, currentThread, q/2, order != Ordering::Release && order != Ordering::AcqRel); ++ //@ vf_on_normal_return(end_bool_access(self)); + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { +@@ -1035,12 +1088,20 @@ + #[lint::should_not_be_called_on_const_items] + #[requires(order == Relaxed || order == Release || order == SeqCst)] + #[cfg_attr(kani, kani::modifies(self))] +- pub const fn store(&self, val: bool, order: Ordering) { ++ pub const fn store(&self, val: bool, order: Ordering) ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share::(k, currentThread, self) &*& Ordering_own(currentThread, order) &*& (if order == Ordering::Acquire || order == Ordering::AcqRel { thread_token(currentThread) } else { true }); ++ //@ ens [q]lifetime_token(k) &*& order != Ordering::Acquire &*& order != Ordering::AcqRel; ++ //@ on_unwind_ens [q]lifetime_token(k) &*& (order == Ordering::Acquire || order == Ordering::AcqRel) &*& thread_token(currentThread); ++ { ++ //@ open Ordering_own(currentThread, order); ++ //@ begin_bool_access(self, k, currentThread, q/2, order != Ordering::Acquire && order != Ordering::AcqRel); ++ //@ if val {} else {} + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { + atomic_store::<_, /* VOLATILE */ false>(self.v.get().cast::(), val as u8, order); + } ++ //@ end_bool_access(self); + } + + /// Performs a volatile atomic store into the bool. +@@ -3397,7 +3458,14 @@ + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[requires(order == Relaxed || order == Acquire || order == SeqCst)] +- pub const fn load(&self, order: Ordering) -> $int_type { ++ pub const fn load(&self, order: Ordering) -> $int_type ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share(k, currentThread, self) &*& Ordering_own(currentThread, order) &*& (if order == Ordering::Release || order == Ordering::AcqRel { thread_token(currentThread) } else { true }); ++ //@ ens [q]lifetime_token(k) &*& order != Ordering::Release &*& order != Ordering::AcqRel; ++ //@ on_unwind_ens [q]lifetime_token(k) &*& (order == Ordering::Release || order == Ordering::AcqRel) &*& thread_token(currentThread); ++ { ++ //@ open Ordering_own(currentThread, order); ++ //@ prepare_ordered_slot(self, rmw_slot(self), k, currentThread, q/2, order != Ordering::Release && order != Ordering::AcqRel); ++ //@ vf_on_normal_return(close_rmw_slot(rmw_slot(self))); + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_load::<_, /* VOLATILE */ false>(self.as_ptr(), order) } + } +@@ -3478,9 +3546,16 @@ + #[lint::should_not_be_called_on_const_items] + #[requires(order == Relaxed || order == Release || order == SeqCst)] + #[cfg_attr(kani, kani::modifies(self))] +- pub const fn store(&self, val: $int_type, order: Ordering) { ++ pub const fn store(&self, val: $int_type, order: Ordering) ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share(k, currentThread, self) &*& Ordering_own(currentThread, order) &*& (if order == Ordering::Acquire || order == Ordering::AcqRel { thread_token(currentThread) } else { true }); ++ //@ ens [q]lifetime_token(k) &*& order != Ordering::Acquire &*& order != Ordering::AcqRel; ++ //@ on_unwind_ens [q]lifetime_token(k) &*& (order == Ordering::Acquire || order == Ordering::AcqRel) &*& thread_token(currentThread); ++ { ++ //@ open Ordering_own(currentThread, order); ++ //@ prepare_ordered_slot(self, rmw_slot(self), k, currentThread, q/2, order != Ordering::Acquire && order != Ordering::AcqRel); + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_store::<_, /* VOLATILE */ false>(self.as_ptr(), val, order); } ++ //@ close_rmw_slot(rmw_slot(self)); + } + + /// Performs a volatile store into the atomic integer. +@@ -3702,7 +3777,15 @@ + current: $int_type, + new: $int_type, + success: Ordering, +- failure: Ordering) -> Result<$int_type, $int_type> { ++ failure: Ordering) -> Result<$int_type, $int_type> ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share(k, currentThread, self) &*& Ordering_own(currentThread, success) &*& Ordering_own(currentThread, failure) &*& (if failure == Ordering::Release || failure == Ordering::AcqRel { thread_token(currentThread) } else { true }); ++ //@ ens [q]lifetime_token(k) &*& failure != Ordering::Release &*& failure != Ordering::AcqRel &*& result::Result_own(currentThread, result) &*& match result { Result::Ok(v) => v == current, Result::Err(v) => v != current }; ++ //@ on_unwind_ens [q]lifetime_token(k) &*& (failure == Ordering::Release || failure == Ordering::AcqRel) &*& thread_token(currentThread); ++ { ++ //@ open Ordering_own(currentThread, success); ++ //@ open Ordering_own(currentThread, failure); ++ //@ prepare_ordered_slot(self, rmw_slot(self), k, currentThread, q/2, failure != Ordering::Release && failure != Ordering::AcqRel); ++ //@ vf_on_normal_return(close_rmw_slot(rmw_slot(self))); + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_compare_exchange(self.as_ptr(), current, new, success, failure) } + } +@@ -3770,7 +3853,15 @@ + current: $int_type, + new: $int_type, + success: Ordering, +- failure: Ordering) -> Result<$int_type, $int_type> { ++ failure: Ordering) -> Result<$int_type, $int_type> ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share(k, currentThread, self) &*& Ordering_own(currentThread, success) &*& Ordering_own(currentThread, failure) &*& (if failure == Ordering::Release || failure == Ordering::AcqRel { thread_token(currentThread) } else { true }); ++ //@ ens [q]lifetime_token(k) &*& failure != Ordering::Release &*& failure != Ordering::AcqRel &*& result::Result_own(currentThread, result) &*& match result { Result::Ok(v) => v == current, Result::Err(v) => true }; ++ //@ on_unwind_ens [q]lifetime_token(k) &*& (failure == Ordering::Release || failure == Ordering::AcqRel) &*& thread_token(currentThread); ++ { ++ //@ open Ordering_own(currentThread, success); ++ //@ open Ordering_own(currentThread, failure); ++ //@ prepare_ordered_slot(self, rmw_slot(self), k, currentThread, q/2, failure != Ordering::Release && failure != Ordering::AcqRel); ++ //@ vf_on_normal_return(close_rmw_slot(rmw_slot(self))); + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { + atomic_compare_exchange_weak(self.as_ptr(), current, new, success, failure) +@@ -4580,8 +4671,19 @@ + #[requires(order == Relaxed || order == Release || order == SeqCst)] + #[ensures(|_| ub_checks::can_dereference(dst as *const T))] + #[ensures(|_| ub_checks::can_write(dst))] +-const unsafe fn atomic_store(dst: *mut T, val: T, order: Ordering) { ++const unsafe fn atomic_store(dst: *mut T, val: T, order: Ordering) /*@ ++ req rmw_integer_type(typeid(T)) == true &*& int_of_const(typeid(VOLATILE)) == 0 &*& ++ ordering_access(dst, order != Ordering::Acquire && order != Ordering::AcqRel, ?f, 1, ?inv_) &*& ++ (if order == Ordering::Acquire || order == Ordering::AcqRel { thread_token(currentThread) } else { inv_(val) == true }); ++@*/ ++/*@ ++ ens [f]std::intrinsics::atomic_points_to::(dst, 1, inv_) &*& order != Ordering::Acquire &*& order != Ordering::AcqRel; ++@*/ ++/*@ ++ on_unwind_ens (order == Ordering::Acquire || order == Ordering::AcqRel) &*& thread_token(currentThread); ++@*/{ + // SAFETY: the caller must uphold the safety contract for `atomic_store`. ++ //@ open ordering_access(dst, _, f, 1, inv_); + unsafe { + match order { + Relaxed => intrinsics::atomic_store::(dst, val), +@@ -4601,8 +4703,20 @@ + #[requires(ub_checks::can_dereference(dst))] + #[requires(order == Relaxed || order == Acquire || order == SeqCst)] + #[ensures(|_| ub_checks::can_dereference(dst))] +-const unsafe fn atomic_load(dst: *const T, order: Ordering) -> T { ++const unsafe fn atomic_load(dst: *const T, order: Ordering) -> T /*@ ++ req rmw_integer_type(typeid(T)) == true &*& int_of_const(typeid(VOLATILE)) == 0 &*& ++ ordering_access(dst, order != Ordering::Release && order != Ordering::AcqRel, ?f, ?af, ?inv_) &*& ++ (if order == Ordering::Release || order == Ordering::AcqRel { thread_token(currentThread) } else { true }); ++@*/ ++/*@ ++ ens [f]std::intrinsics::atomic_points_to::(dst, af, inv_) &*& 0 < af &*& af <= 1 &*& inv_(result) == true &*& ++ order != Ordering::Release &*& order != Ordering::AcqRel; ++@*/ ++/*@ ++ on_unwind_ens (order == Ordering::Release || order == Ordering::AcqRel) &*& thread_token(currentThread); ++@*/{ + // SAFETY: the caller must uphold the safety contract for `atomic_load`. ++ //@ open ordering_access(dst, _, f, af, inv_); + unsafe { + match order { + Relaxed => intrinsics::atomic_load::(dst), +@@ -4705,8 +4819,13 @@ + new: T, + success: Ordering, + failure: Ordering, +-) -> Result { ++) -> Result ++//@ req rmw_integer_type(typeid(T)) == true &*& ordering_access(dst, failure != Ordering::Release && failure != Ordering::AcqRel, ?f, ?af, ?inv_) &*& (if failure == Ordering::Release || failure == Ordering::AcqRel { thread_token(currentThread) } else { if af == 1 { inv_(new) == true || inv_(old) == false } else { inv_(old) == false } }); ++//@ ens [f]std::intrinsics::atomic_points_to::(dst, af, inv_) &*& 0 < af &*& af <= 1 &*& failure != Ordering::Release &*& failure != Ordering::AcqRel &*& result::Result_own::(currentThread, result) &*& match result { Result::Ok(v) => af == 1 &*& inv_(v) == true &*& v == old, Result::Err(v) => inv_(v) == true &*& v != old }; ++//@ on_unwind_ens (failure == Ordering::Release || failure == Ordering::AcqRel) &*& thread_token(currentThread); ++{ + // SAFETY: the caller must uphold the safety contract for `atomic_compare_exchange`. ++ //@ open ordering_access(dst, _, f, af, inv_); + let (val, ok) = unsafe { + match (success, failure) { + (Relaxed, Relaxed) => { +@@ -4758,6 +4877,11 @@ + (_, Release) => panic!("there is no such thing as a release failure ordering"), + } + }; ++ /*@ if ok { ++ close result::Result_own::(currentThread, result::Result::Ok(val)); ++ } else { ++ close result::Result_own::(currentThread, result::Result::Err(val)); ++ } @*/ + if ok { Ok(val) } else { Err(val) } + } + +@@ -4778,8 +4902,13 @@ + new: T, + success: Ordering, + failure: Ordering, +-) -> Result { ++) -> Result ++//@ req rmw_integer_type(typeid(T)) == true &*& ordering_access(dst, failure != Ordering::Release && failure != Ordering::AcqRel, ?f, ?af, ?inv_) &*& (if failure == Ordering::Release || failure == Ordering::AcqRel { thread_token(currentThread) } else { if af == 1 { inv_(new) == true || inv_(old) == false } else { inv_(old) == false } }); ++//@ ens [f]std::intrinsics::atomic_points_to::(dst, af, inv_) &*& 0 < af &*& af <= 1 &*& failure != Ordering::Release &*& failure != Ordering::AcqRel &*& result::Result_own::(currentThread, result) &*& match result { Result::Ok(v) => af == 1 &*& inv_(v) == true &*& v == old, Result::Err(v) => inv_(v) == true }; ++//@ on_unwind_ens (failure == Ordering::Release || failure == Ordering::AcqRel) &*& thread_token(currentThread); ++{ + // SAFETY: the caller must uphold the safety contract for `atomic_compare_exchange_weak`. ++ //@ open ordering_access(dst, _, f, af, inv_); + let (val, ok) = unsafe { + match (success, failure) { + (Relaxed, Relaxed) => { +@@ -4831,6 +4960,11 @@ + (_, Release) => panic!("there is no such thing as a release failure ordering"), + } + }; ++ /*@ if ok { ++ close result::Result_own::(currentThread, result::Result::Ok(val)); ++ } else { ++ close result::Result_own::(currentThread, result::Result::Err(val)); ++ } @*/ + if ok { Ok(val) } else { Err(val) } + } + +--- a/intrinsics/mod.rs ++++ b/intrinsics/mod.rs +@@ -160,7 +160,19 @@ + dst: *mut T, + old: T, + src: T, +-) -> (T, bool); ++) -> (T, bool)/*@ ++ req sync::atomic::rmw_integer_type(typeid(T)) == true &*& ++ 0 <= int_of_const(typeid(ORD_SUCC)) &*& int_of_const(typeid(ORD_SUCC)) <= 4 &*& ++ (int_of_const(typeid(ORD_FAIL)) == 0 || int_of_const(typeid(ORD_FAIL)) == 2 || int_of_const(typeid(ORD_FAIL)) == 4) &*& ++ [?f]std::intrinsics::atomic_points_to::(dst, ?af, ?inv_) &*& 0 < af &*& af <= 1 &*& (if af == 1 { inv_(src) == true || inv_(old) == false } else { inv_(old) == false }); ++@*/ ++/*@ ++ ens [f]std::intrinsics::atomic_points_to::(dst, af, inv_) &*& 0 < af &*& af <= 1 &*& inv_(result.0) == true &*& ++ .own(currentThread, result.0) &*& result.1 == (result.0 == old); ++@*/ ++/*@ ++ on_unwind_ens false; ++@*/; + + /// Stores a value if the current value is the same as the `old` value, + /// with the returned `T` being the previous value and the returned `bool` being +@@ -194,7 +206,19 @@ + _dst: *mut T, + _old: T, + _src: T, +-) -> (T, bool); ++) -> (T, bool)/*@ ++ req sync::atomic::rmw_integer_type(typeid(T)) == true &*& ++ 0 <= int_of_const(typeid(ORD_SUCC)) &*& int_of_const(typeid(ORD_SUCC)) <= 4 &*& ++ (int_of_const(typeid(ORD_FAIL)) == 0 || int_of_const(typeid(ORD_FAIL)) == 2 || int_of_const(typeid(ORD_FAIL)) == 4) &*& ++ [?f]std::intrinsics::atomic_points_to::(_dst, ?af, ?inv_) &*& 0 < af &*& af <= 1 &*& (if af == 1 { inv_(_src) == true || inv_(_old) == false } else { inv_(_old) == false }); ++@*/ ++/*@ ++ ens [f]std::intrinsics::atomic_points_to::(_dst, af, inv_) &*& 0 < af &*& af <= 1 &*& inv_(result.0) == true &*& ++ .own(currentThread, result.0) &*& (result.1 == false || result.0 == _old); ++@*/ ++/*@ ++ on_unwind_ens false; ++@*/; + + /// Loads the current value of the pointer. + /// `T` must be an integer or pointer type. +@@ -217,7 +241,18 @@ + #[rustc_nounwind] + pub const unsafe fn atomic_load( + src: *const T, +-) -> T; ++) -> T/*@ ++ req sync::atomic::rmw_integer_type(typeid(T)) == true &*& ++ (int_of_const(typeid(ORD)) == 0 || int_of_const(typeid(ORD)) == 2 || int_of_const(typeid(ORD)) == 4) &*& ++ int_of_const(typeid(VOLATILE)) == 0 &*& ++ [?f]std::intrinsics::atomic_points_to::(src, ?af, ?inv_) &*& 0 < af &*& af <= 1; ++@*/ ++/*@ ++ ens [f]std::intrinsics::atomic_points_to::(src, af, inv_) &*& 0 < af &*& af <= 1 &*& inv_(result) == true; ++@*/ ++/*@ ++ on_unwind_ens false; ++@*/; + + /// Stores the value at the specified memory location. + /// `T` must be an integer or pointer type. +@@ -241,7 +276,18 @@ + pub const unsafe fn atomic_store( + dst: *mut T, + val: T, +-); ++)/*@ ++ req sync::atomic::rmw_integer_type(typeid(T)) == true &*& ++ (int_of_const(typeid(ORD)) == 0 || int_of_const(typeid(ORD)) == 1 || int_of_const(typeid(ORD)) == 4) &*& ++ int_of_const(typeid(VOLATILE)) == 0 &*& ++ [?f]std::intrinsics::atomic_points_to::(dst, 1, ?inv_) &*& inv_(val) == true; ++@*/ ++/*@ ++ ens [f]std::intrinsics::atomic_points_to::(dst, 1, inv_); ++@*/ ++/*@ ++ on_unwind_ens false; ++@*/; + + /// Stores the value at the specified memory location, returning the old value. + /// `T` must be an integer or pointer type. diff --git a/verifast-proofs/core/sync/atomic.rs/specs/borrow.diff b/verifast-proofs/core/sync/atomic.rs/specs/borrow.diff new file mode 100644 index 0000000000000..7030439db9979 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/specs/borrow.diff @@ -0,0 +1,170 @@ +--- a/cell.rs ++++ b/cell.rs +@@ -2433,7 +2433,11 @@ + #[lint::as_ptr] + #[lint::never_returns_null_ptr] + #[lint::should_not_be_called_on_const_items] +- pub const fn get(&self) -> *mut T { ++ pub const fn get(&self) -> *mut T ++ //@ req true; ++ //@ ens result as pointer == ref_origin(self) as pointer; ++ //@ on_unwind_ens false; ++ { + // We can just cast the pointer from `UnsafeCell` to `T` because of + // #[repr(transparent)]. + self as *const UnsafeCell as *const T as *mut T +--- a/sync/atomic.rs ++++ b/sync/atomic.rs +@@ -255,6 +255,111 @@ + use crate::ub_checks; + use crate::{fmt, intrinsics}; + ++/*@ ++fix AtomicPrimitive::Storage_typeid(t: *_) -> *_; ++fix accepts_word(v: u32) -> bool { true } ++type_pred_decl .atomic_content : fix(*_, pred(;)); ++pred_ctor U32_atomic_content(p: *_)(;) = ++ std::intrinsics::atomic_points_to::(p as *u32, 1, accepts_word); ++fix rep_fn(owned: bool) -> fix(*_, pred(;)) { .atomic_content } ++fix representation(owned: bool, p: *_) -> pred(;) { (rep_fn::(owned))(p) } ++fix view_content(p: *T) -> pred(;) { .atomic_content(p) } ++pred >.share(k, t, p) = ++ exists::(?owned) &*& [_]frac_borrow(k, representation::(owned, ref_origin(p))) &*& [_]frac_borrow(k, ref_initialized_(p)); ++// The representation witnesses consume and return the actual slot at p. The ++// by-value predicate carries their linear permissions across the full borrow. ++lem_type atomic_pack(valid: fix(Atomic, bool), layout: bool, owned: bool, content: fix(*_, pred(;))) = lem(p: *Atomic); ++ req layout == true &*& atomic_mask(MaskTop) &*& *p |-> ?v &*& valid(v) == true; ++ ens atomic_mask(MaskTop) &*& (content(p))(); ++lem_type atomic_unpack(valid: fix(Atomic, bool), layout: bool, owned: bool, content: fix(*_, pred(;))) = lem(p: *Atomic); ++ req layout == true &*& (content(p))(); ++ ens *p |-> ?v &*& valid(v) == true; ++type_pred_decl .storage_owner : pred(thread_id_t, Self); ++pred >.storage_owner(t, v) = < ::Storage>.own(t, v.v); ++lem_type atomic_drop_rep(valid: fix(Atomic, bool), layout: bool, field: pred(thread_id_t, Atomic)) = lem(t: thread_id_t, v: Atomic); ++ req layout == true &*& valid(v) == true; ++ ens field(t, v); ++pred >.own(t, v) = ++ is_atomic_pack::(?pack, ?valid, ?layout, ?owned, rep_fn::(owned)) &*& is_atomic_unpack::(?unpack, valid, layout, owned, rep_fn::(owned)) &*& ++ is_atomic_drop_rep::(?drop_rep, valid, layout, >.storage_owner) &*& layout == true &*& valid(v) == true; ++lem Atomic_drop() ++ req Atomic_own::(?_t, ?_v); ++ ens < ::Storage>.own(_t, _v.v); ++{ ++ open Atomic_own::(_t, _v); ++ assert is_atomic_drop_rep::(?drop_rep, _, _, _); ++ drop_rep(_t, _v); ++ open Atomic_storage_owner::(_t, _v); ++ leak is_atomic_pack::(_, _, _, _, _); ++ leak is_atomic_unpack::(_, _, _, _, _); ++ leak is_atomic_drop_rep::(_, _, _, _); ++} ++lem Atomic_share_full(k: lifetime_t, t: thread_id_t, l: *Atomic) ++ req type_interp::() &*& atomic_mask(MaskTop) &*& full_borrow(k, Atomic_full_borrow_content::(t, l)) &*& [?q]lifetime_token(k) &*& ref_origin(l) == l; ++ ens type_interp::() &*& atomic_mask(MaskTop) &*& [_]Atomic_share::(k, t, l) &*& [q]lifetime_token(k); ++{ ++ let kl = open_full_borrow_strong_m(k, Atomic_full_borrow_content::(t, l), q); ++ open Atomic_full_borrow_content::(t, l)(); ++ open Atomic_own::(t, _); ++ assert is_atomic_pack::(?pack, ?valid, ?layout, ?owned, rep_fn::(owned)); ++ assert is_atomic_unpack::(?unpack, valid, layout, owned, rep_fn::(owned)); ++ assert is_atomic_drop_rep::(?drop_rep, valid, layout, >.storage_owner); ++ close_points_to(l); ++ pack(l); ++ { ++ pred Ctx() = is_atomic_pack::(pack, valid, layout, owned, rep_fn::(owned)) &*& is_atomic_unpack::(unpack, valid, layout, owned, rep_fn::(owned)) &*& is_atomic_drop_rep::(drop_rep, valid, layout, >.storage_owner) &*& layout == true; ++ produce_lem_ptr_chunk full_borrow_convert_strong(Ctx, representation::(owned, l), kl, Atomic_full_borrow_content::(t, l))() { ++ open Ctx(); ++ unpack(l); ++ close Atomic_own::(t, *l); ++ open_points_to(l); ++ close Atomic_full_borrow_content::(t, l)(); ++ } { ++ close Ctx(); ++ close_full_borrow_strong_m(kl, Atomic_full_borrow_content::(t, l), representation::(owned, l)); ++ full_borrow_mono(kl, k, representation::(owned, l)); ++ } ++ } ++ full_borrow_into_frac_m(k, representation::(owned, l)); ++ close_ref_initialized_Atomic::(l, 1); ++ close ref_initialized_::>(l)(); ++ borrow_m(k, ref_initialized_(l)); ++ full_borrow_into_frac_m(k, ref_initialized_(l)); ++ leak borrow_end_token(_, _); ++ close exists(owned); ++ close Atomic_share::(k, t, l); ++ leak Atomic_share::(k, t, l); ++} ++lem Atomic_share_mono(k: lifetime_t, sub: lifetime_t, t: thread_id_t, l: *Atomic) ++ req type_interp::() &*& lifetime_inclusion(sub, k) == true &*& [_]Atomic_share::(k, t, l); ++ ens type_interp::() &*& [_]Atomic_share::(sub, t, l); ++{ ++ open Atomic_share::(k, t, l); ++ assert [_]exists::(?owned); ++ frac_borrow_mono(k, sub, representation::(owned, ref_origin(l))); ++ frac_borrow_mono(k, sub, ref_initialized_(l)); ++ close exists(owned); ++ close Atomic_share::(sub, t, l); ++ leak Atomic_share::(sub, t, l); ++} ++lem init_ref_Atomic(p: *Atomic) ++ req type_interp::() &*& atomic_mask(Nlft) &*& ref_init_perm(p, ?x) &*& [_]Atomic_share::(?k, ?t, x) &*& [?q]lifetime_token(k); ++ ens type_interp::() &*& atomic_mask(Nlft) &*& [q]lifetime_token(k) &*& [_]Atomic_share::(k, t, p) &*& [_]frac_borrow(k, ref_initialized_(p)); ++{ ++ open Atomic_share::(k, t, x); ++ assert [_]exists::(?owned); ++ open_ref_init_perm_Atomic::(p); ++ close_ref_initialized_Atomic::(p, 1); ++ close ref_initialized_::>(p)(); ++ borrow_m(k, ref_initialized_(p)); ++ full_borrow_into_frac_m(k, ref_initialized_(p)); ++ leak borrow_end_token(_, _); ++ close exists(owned); ++ close Atomic_share::(k, t, p); ++ leak Atomic_share::(k, t, p); ++} ++@*/ ++ + #[unstable( + feature = "atomic_internals", + reason = "implementation detail which may disappear or be replaced at any time", +@@ -2997,7 +3102,11 @@ + #[ensures(|result: &&$atomic_type| { + ub_checks::can_write((*result).as_ptr()) + })] +- pub const unsafe fn from_ptr<'a>(ptr: *mut $int_type) -> &'a $atomic_type { ++ pub const unsafe fn from_ptr<'a>(ptr: *mut $int_type) -> &'a $atomic_type ++ //@ req [?q]lifetime_token('a) &*& [_]frac_borrow('a, view_content(ptr)) &*& ref_origin(ptr) == ptr; ++ //@ ens [q]lifetime_token('a) &*& [_]Atomic_share('a, currentThread, result) &*& [_]frac_borrow('a, ref_initialized_(result)) &*& ref_origin(result) as *_ == ptr as *_; ++ //@ on_unwind_ens false; ++ { + // SAFETY: guaranteed by the caller + unsafe { &*ptr.cast() } + } +@@ -4084,7 +4193,11 @@ + #[stable(feature = "atomic_as_ptr", since = "1.70.0")] + #[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")] + #[lint::never_returns_null_ptr] +- pub const fn as_ptr(&self) -> *mut $int_type { ++ pub const fn as_ptr(&self) -> *mut $int_type ++ //@ req true; ++ //@ ens result as pointer == ref_origin(self) as pointer; ++ //@ on_unwind_ens false; ++ { + self.v.get().cast() + } + } +--- a/ptr/mut_ptr.rs ++++ b/ptr/mut_ptr.rs +@@ -32,7 +32,11 @@ + #[rustc_const_stable(feature = "const_ptr_cast", since = "1.38.0")] + #[rustc_diagnostic_item = "ptr_cast"] + #[inline(always)] +- pub const fn cast(self) -> *mut U { ++ pub const fn cast(self) -> *mut U ++ //@ req true; ++ //@ ens result == self as *U; ++ //@ on_unwind_ens false; ++ { + self as _ + } + diff --git a/verifast-proofs/core/sync/atomic.rs/specs/i128.diff b/verifast-proofs/core/sync/atomic.rs/specs/i128.diff new file mode 100644 index 0000000000000..a3aeb27df5b09 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/specs/i128.diff @@ -0,0 +1,15 @@ +--- a/sync/atomic.rs ++++ b/sync/atomic.rs +@@ -289,10 +289,10 @@ + type_pred_def .atomic_content = rmw_usize_content; + type_pred_def .atomic_content = rmw_isize_content; + fix rmw_signed_type(t: *_) -> bool { +- t == typeid(i8) || t == typeid(i16) || t == typeid(i32) || t == typeid(i64) || t == typeid(isize) ++ t == typeid(i8) || t == typeid(i16) || t == typeid(i32) || t == typeid(i64) || t == typeid(isize) || t == typeid(i128) + } + fix rmw_unsigned_type(t: *_) -> bool { +- t == typeid(u8) || t == typeid(u16) || t == typeid(u32) || t == typeid(u64) || t == typeid(usize) ++ t == typeid(u8) || t == typeid(u16) || t == typeid(u32) || t == typeid(u64) || t == typeid(usize) || t == typeid(u128) + } + fix rmw_integer_type(t: *_) -> bool { rmw_signed_type(t) || rmw_unsigned_type(t) } + fix rmw_slot(a: *Atomic) -> *T { ref_origin(a) as *T } diff --git a/verifast-proofs/core/sync/atomic.rs/specs/integer-storage.diff b/verifast-proofs/core/sync/atomic.rs/specs/integer-storage.diff new file mode 100644 index 0000000000000..b48b297cfe6d9 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/specs/integer-storage.diff @@ -0,0 +1,94 @@ +--- a/sync/atomic.rs ++++ b/sync/atomic.rs +@@ -268,9 +268,59 @@ + fix halfword_content(p: *_) -> pred(;) { unsigned_content::(p) } + type_pred_def .atomic_content = byte_content; + type_pred_def .atomic_content = halfword_content; ++fix i8_content(p: *_) -> pred(;) { unsigned_content::(p) } ++fix i16_content(p: *_) -> pred(;) { unsigned_content::(p) } ++fix i32_content(p: *_) -> pred(;) { unsigned_content::(p) } ++fix i64_content(p: *_) -> pred(;) { unsigned_content::(p) } ++fix u64_content(p: *_) -> pred(;) { unsigned_content::(p) } ++fix i128_content(p: *_) -> pred(;) { unsigned_content::(p) } ++fix u128_content(p: *_) -> pred(;) { unsigned_content::(p) } ++type_pred_def .atomic_content = i8_content; ++type_pred_def .atomic_content = i16_content; ++type_pred_def .atomic_content = i32_content; ++type_pred_def .atomic_content = i64_content; ++type_pred_def .atomic_content = u64_content; ++type_pred_def .atomic_content = i128_content; ++type_pred_def .atomic_content = u128_content; ++fix rmw_u32_content(p: *_) -> pred(;) { unsigned_content::(p) } ++fix rmw_usize_content(p: *_) -> pred(;) { unsigned_content::(p) } ++fix rmw_isize_content(p: *_) -> pred(;) { unsigned_content::(p) } ++type_pred_def .atomic_content = rmw_u32_content; ++type_pred_def .atomic_content = rmw_usize_content; ++type_pred_def .atomic_content = rmw_isize_content; ++fix rmw_signed_type(t: *_) -> bool { ++ t == typeid(i8) || t == typeid(i16) || t == typeid(i32) || t == typeid(i64) || t == typeid(isize) ++} ++fix rmw_unsigned_type(t: *_) -> bool { ++ t == typeid(u8) || t == typeid(u16) || t == typeid(u32) || t == typeid(u64) || t == typeid(usize) ++} ++fix rmw_integer_type(t: *_) -> bool { rmw_signed_type(t) || rmw_unsigned_type(t) } ++fix rmw_slot(a: *Atomic) -> *T { ref_origin(a) as *T } ++lem open_rmw_slot(view: *Atomic, p: *T, k: lifetime_t, t: thread_id_t, q: real) ++ nonghost_callers_only ++ req [q]lifetime_token(k) &*& [_]Atomic_share::(k, t, view) &*& ++ .atomic_content(ref_origin(view)) == unsigned_content::(p); ++ ens [_]frac_borrow(k, ref_initialized_(view)) &*& [?f]std::intrinsics::atomic_points_to::(p, 1, accepts_unsigned) &*& close_frac_borrow_token(f, unsigned_content::(p), q, k); ++{ ++ open Atomic_share::(k, t, view); ++ let f = open_frac_borrow(k, unsigned_content::(p), q); ++ open [f]unsigned_content::(p)(); ++} ++lem close_rmw_slot(p: *T) ++ nonghost_callers_only ++ req [?f]std::intrinsics::atomic_points_to::(p, 1, accepts_unsigned) &*& close_frac_borrow_token(f, unsigned_content::(p), ?q, ?k); ++ ens [q]lifetime_token(k); ++{ ++ close [f]unsigned_content::(p)(); ++ close_frac_borrow(f, unsigned_content::(p)); ++} + fix unsigned_view_address(p: *T) -> *Atomic { + p as *Atomic + } ++fix valid_bool_byte(v: u8) -> bool { v == 0 || v == 1 } ++pred_ctor bool_slot_content(p: *_)(;) = ++ std::intrinsics::atomic_points_to::(p as *u8, 1, valid_bool_byte); ++type_pred_def .atomic_content = bool_slot_content; + lem finish_unsigned_ref(k: lifetime_t, t: thread_id_t, p: *Atomic) + nonghost_callers_only + req [1/2]ref_initialized(p) &*& [_]frac_borrow(k, .atomic_content(ref_origin(p))); +@@ -741,8 +791,17 @@ + #[ensures(|result: &&AtomicBool| { + core::ptr::eq(*result, ptr.cast::()) + })] +- pub const unsafe fn from_ptr<'a>(ptr: *mut bool) -> &'a AtomicBool { ++ pub const unsafe fn from_ptr<'a>(ptr: *mut bool) -> &'a AtomicBool ++ //@ req [?q]lifetime_token('a) &*& [_]frac_borrow('a, bool_slot_content(ptr)) &*& ref_origin(ptr) == ptr; ++ //@ ens [q]lifetime_token('a) &*& [_]Atomic_share::('a, currentThread, result) &*& [_]frac_borrow('a, ref_initialized_(result)) &*& ref_origin(result) as pointer == ptr as pointer; ++ //@ on_unwind_ens false; ++ { + // SAFETY: guaranteed by the caller ++ //@ let view = precreate_ref(ptr as *Atomic); ++ //@ open_ref_init_perm_Atomic::(view); ++ //@ close_ref_initialized_Atomic::(view, 1); ++ //@ leak [1/2]ref_initialized(view); ++ //@ finish_unsigned_ref('a, currentThread, view); + unsafe { &*ptr.cast() } + } + +@@ -1572,7 +1631,11 @@ + #[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")] + #[lint::never_returns_null_ptr] + #[lint::should_not_be_called_on_const_items] +- pub const fn as_ptr(&self) -> *mut bool { ++ pub const fn as_ptr(&self) -> *mut bool ++ //@ req true; ++ //@ ens result as pointer == ref_origin(self) as pointer; ++ //@ on_unwind_ens false; ++ { + self.v.get().cast() + } + diff --git a/verifast-proofs/core/sync/atomic.rs/specs/panic.diff b/verifast-proofs/core/sync/atomic.rs/specs/panic.diff new file mode 100644 index 0000000000000..f6cc254136d64 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/specs/panic.diff @@ -0,0 +1,24 @@ +--- a/intrinsics/mod.rs ++++ b/intrinsics/mod.rs +@@ -641,7 +641,7 @@ + /// The stabilized version of this intrinsic is [`core::process::crash`]. + #[rustc_nounwind] + #[rustc_intrinsic] +-pub const fn abort_immediate() -> !; ++pub const fn abort_immediate() -> !/*@ req true; @*/ /*@ ens false; @*/ /*@ on_unwind_ens false; @*/; + + /// Informs the optimizer that this point in the code is not reachable, + /// enabling further optimizations. +@@ -804,7 +804,11 @@ + #[rustc_intrinsic_const_stable_indirect] + #[rustc_nounwind] + #[rustc_intrinsic] +-pub const fn caller_location() -> &'static crate::panic::Location<'static>; ++pub const fn caller_location() -> &'static crate::panic::Location<'static>/*@ req true; @*/ /*@ ++ ens (result as pointer).address != 0 &*& [_](*result |-> ?location) &*& ++ [_]panic::location::Location_share::<'static>('static, currentThread, result) &*& ++ [_]frac_borrow('static, ref_initialized_(result)); ++@*/ /*@ on_unwind_ens false; @*/; + + /// Moves a value out of scope without running drop glue. + /// diff --git a/verifast-proofs/core/sync/atomic.rs/specs/pointer-access.diff b/verifast-proofs/core/sync/atomic.rs/specs/pointer-access.diff new file mode 100644 index 0000000000000..5304e1330f40b --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/specs/pointer-access.diff @@ -0,0 +1,314 @@ +--- a/sync/atomic.rs ++++ b/sync/atomic.rs +@@ -270,6 +270,11 @@ + type_pred_def .atomic_content = byte_content; + type_pred_def .atomic_content = halfword_content; + fix accepts_pointer(payload: *T) -> bool { true } ++type_pred_decl .cas_address_model : pred(fix(Self, usize)); ++fix raw_cas_address

(value: *P) -> usize { value as usize } ++pred_ctor raw_cas_address_model

()(key: fix(*P, usize)) = key == raw_cas_address; ++type_pred_def for

<*P>.cas_address_model = raw_cas_address_model::

; ++pred pointer_cas_returned(slot: *S, value: result::Result) = true; + fix thin_raw_slot_type() -> bool { + typeid(S) == typeid(*::Pointee) && + ptr::metadata::Pointee::Metadata_typeid(intrinsics::bounds::BuiltinDeref::Pointee_typeid(typeid(S))) == typeid(()) +@@ -287,6 +292,20 @@ + { + close [f]pointer_slot_content::

(slot)(); + close_frac_borrow(f, pointer_slot_content::

(slot)); ++} ++lem finish_pointer_cas(slot: **P, t: thread_id_t) ++ nonghost_callers_only ++ req [?f]std::intrinsics::atomic_points_to::<*P>(slot, 1, accepts_pointer) &*& thin_raw_slot_type::<*P>() == true &*& ++ close_frac_borrow_token(f, pointer_slot_content::

(slot), ?q, ?k) &*& pointer_cas_returned(slot, ?value); ++ ens [q]lifetime_token(k) &*& result::Result_own::<*P, *P>(t, value); ++{ ++ open pointer_cas_returned(slot, value); ++ match value { ++ Result::Ok(v) => { close raw_ptr_own::

()(t, v); } ++ Result::Err(v) => { close raw_ptr_own::

()(t, v); } ++ } ++ close result::Result_own::<*P, *P>(t, value); ++ close_pointer_exchange::

(slot); + } + fix unsigned_view_address(p: *T) -> *Atomic { + p as *Atomic +@@ -679,6 +698,29 @@ + #[stable(feature = "rust1", since = "1.0.0")] + SeqCst, + } ++ ++/*@ ++pred ordering_access(p: *T, needed: bool, f: real, inv_: fix(T, bool)) = ++ if needed { [f]std::intrinsics::atomic_points_to::(p, 1, inv_) } else { true }; ++lem prepare_pointer_access(view: *Atomic<*P>, k: lifetime_t, t: thread_id_t, q: real, needed: bool) ++ nonghost_callers_only ++ req [q]lifetime_token(k) &*& [_]Atomic_share::<*P>(k, t, view); ++ ens [_]frac_borrow(k, ref_initialized_(view)) &*& ++ ordering_access(ref_origin(view) as **P, needed, ?f, accepts_pointer) &*& ++ if needed { thin_raw_slot_type::<*P>() == true &*& close_frac_borrow_token(f, pointer_slot_content::

(ref_origin(view)), q, k) } ++ else { [q]lifetime_token(k) }; ++{ ++ open Atomic_share::<*P>(k, t, view); ++ let slot = ref_origin(view) as **P; ++ if needed { ++ let f = open_frac_borrow(k, pointer_slot_content::

(slot), q); ++ open [f]pointer_slot_content::

(slot)(); ++ close ordering_access(slot, true, f, accepts_pointer); ++ } else { ++ close ordering_access(slot, false, 1, accepts_pointer); ++ } ++} ++@*/ + + /// An [`AtomicBool`] initialized to `false`. + #[cfg(target_has_atomic_load_store = "8")] +@@ -2040,7 +2082,14 @@ + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[requires(order == Relaxed || order == Acquire || order == SeqCst)] +- pub const fn load(&self, order: Ordering) -> *mut T { ++ pub const fn load(&self, order: Ordering) -> *mut T ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share::<*T>(k, currentThread, self) &*& Ordering_own(currentThread, order) &*& (if order == Ordering::Release || order == Ordering::AcqRel { thread_token(currentThread) } else { true }); ++ //@ ens [q]lifetime_token(k) &*& order != Ordering::Release &*& order != Ordering::AcqRel; ++ //@ on_unwind_ens [q]lifetime_token(k) &*& (order == Ordering::Release || order == Ordering::AcqRel) &*& thread_token(currentThread); ++ { ++ //@ open Ordering_own(currentThread, order); ++ //@ prepare_pointer_access(self, k, currentThread, q/2, order != Ordering::Release && order != Ordering::AcqRel); ++ //@ vf_on_normal_return(close_pointer_exchange::(ref_origin(self) as **T)); + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { + atomic_load::<_, /* VOLATILE */ false>(self.as_ptr(), order) +@@ -2140,11 +2189,18 @@ + #[lint::should_not_be_called_on_const_items] + #[requires(order == Relaxed || order == Release || order == SeqCst)] + #[cfg_attr(kani, kani::modifies(self))] +- pub const fn store(&self, ptr: *mut T, order: Ordering) { ++ pub const fn store(&self, ptr: *mut T, order: Ordering) ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share::<*T>(k, currentThread, self) &*& Ordering_own(currentThread, order) &*& (if order == Ordering::Acquire || order == Ordering::AcqRel { thread_token(currentThread) } else { true }); ++ //@ ens [q]lifetime_token(k) &*& order != Ordering::Acquire &*& order != Ordering::AcqRel; ++ //@ on_unwind_ens [q]lifetime_token(k) &*& (order == Ordering::Acquire || order == Ordering::AcqRel) &*& thread_token(currentThread); ++ { ++ //@ open Ordering_own(currentThread, order); ++ //@ prepare_pointer_access(self, k, currentThread, q/2, order != Ordering::Acquire && order != Ordering::AcqRel); + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { + atomic_store::<_, /* VOLATILE */ false>(self.as_ptr(), ptr, order); + } ++ //@ close_pointer_exchange::(ref_origin(self) as **T); + } + + /// Performs a volatile atomic store into the pointer. +@@ -2374,7 +2430,17 @@ + new: *mut T, + success: Ordering, + failure: Ordering, +- ) -> Result<*mut T, *mut T> { ++ ) -> Result<*mut T, *mut T> ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share::<*T>(k, currentThread, self) &*& Ordering_own(currentThread, success) &*& Ordering_own(currentThread, failure) &*& (if failure == Ordering::Release || failure == Ordering::AcqRel { thread_token(currentThread) } else { true }); ++ //@ ens [q]lifetime_token(k) &*& failure != Ordering::Release &*& failure != Ordering::AcqRel &*& result::Result_own::<*T, *T>(currentThread, result) &*& match result { Result::Ok(v) => v as usize == current as usize, Result::Err(v) => v as usize != current as usize }; ++ //@ on_unwind_ens [q]lifetime_token(k) &*& (failure == Ordering::Release || failure == Ordering::AcqRel) &*& thread_token(currentThread); ++ { ++ //@ open Ordering_own(currentThread, success); ++ //@ open Ordering_own(currentThread, failure); ++ //@ close raw_cas_address_model::()(raw_cas_address); ++ //@ leak raw_cas_address_model::()(raw_cas_address); ++ //@ prepare_pointer_access(self, k, currentThread, q/2, failure != Ordering::Release && failure != Ordering::AcqRel); ++ //@ vf_on_normal_return(finish_pointer_cas::(ref_origin(self) as **T, currentThread)); + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_compare_exchange(self.as_ptr(), current, new, success, failure) } + } +@@ -2440,7 +2506,17 @@ + new: *mut T, + success: Ordering, + failure: Ordering, +- ) -> Result<*mut T, *mut T> { ++ ) -> Result<*mut T, *mut T> ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share::<*T>(k, currentThread, self) &*& Ordering_own(currentThread, success) &*& Ordering_own(currentThread, failure) &*& (if failure == Ordering::Release || failure == Ordering::AcqRel { thread_token(currentThread) } else { true }); ++ //@ ens [q]lifetime_token(k) &*& failure != Ordering::Release &*& failure != Ordering::AcqRel &*& result::Result_own::<*T, *T>(currentThread, result) &*& match result { Result::Ok(v) => v as usize == current as usize, Result::Err(v) => true }; ++ //@ on_unwind_ens [q]lifetime_token(k) &*& (failure == Ordering::Release || failure == Ordering::AcqRel) &*& thread_token(currentThread); ++ { ++ //@ open Ordering_own(currentThread, success); ++ //@ open Ordering_own(currentThread, failure); ++ //@ close raw_cas_address_model::()(raw_cas_address); ++ //@ leak raw_cas_address_model::()(raw_cas_address); ++ //@ prepare_pointer_access(self, k, currentThread, q/2, failure != Ordering::Release && failure != Ordering::AcqRel); ++ //@ vf_on_normal_return(finish_pointer_cas::(ref_origin(self) as **T, currentThread)); + // SAFETY: This intrinsic is unsafe because it operates on a raw pointer + // but we know for sure that the pointer is valid (we just got it from + // an `UnsafeCell` that we have by reference) and the atomic operation +@@ -4560,8 +4636,19 @@ + #[requires(order == Relaxed || order == Release || order == SeqCst)] + #[ensures(|_| ub_checks::can_dereference(dst as *const T))] + #[ensures(|_| ub_checks::can_write(dst))] +-const unsafe fn atomic_store(dst: *mut T, val: T, order: Ordering) { ++const unsafe fn atomic_store(dst: *mut T, val: T, order: Ordering) /*@ ++ req (order == Ordering::Acquire || order == Ordering::AcqRel || typeid(T) == typeid(u32) || thin_raw_slot_type::()) &*& int_of_const(typeid(VOLATILE)) == 0 &*& ++ ordering_access(dst, order != Ordering::Acquire && order != Ordering::AcqRel, ?f, ?inv_) &*& ++ (if order == Ordering::Acquire || order == Ordering::AcqRel { thread_token(currentThread) } else { inv_(val) == true }); ++@*/ ++/*@ ++ ens [f]std::intrinsics::atomic_points_to::(dst, 1, inv_) &*& order != Ordering::Acquire &*& order != Ordering::AcqRel; ++@*/ ++/*@ ++ on_unwind_ens (order == Ordering::Acquire || order == Ordering::AcqRel) &*& thread_token(currentThread); ++@*/{ + // SAFETY: the caller must uphold the safety contract for `atomic_store`. ++ //@ open ordering_access(dst, _, f, inv_); + unsafe { + match order { + Relaxed => intrinsics::atomic_store::(dst, val), +@@ -4581,8 +4668,20 @@ + #[requires(ub_checks::can_dereference(dst))] + #[requires(order == Relaxed || order == Acquire || order == SeqCst)] + #[ensures(|_| ub_checks::can_dereference(dst))] +-const unsafe fn atomic_load(dst: *const T, order: Ordering) -> T { ++const unsafe fn atomic_load(dst: *const T, order: Ordering) -> T /*@ ++ req (order == Ordering::Release || order == Ordering::AcqRel || typeid(T) == typeid(u32) || thin_raw_slot_type::()) &*& int_of_const(typeid(VOLATILE)) == 0 &*& ++ ordering_access(dst, order != Ordering::Release && order != Ordering::AcqRel, ?f, ?inv_) &*& ++ (if order == Ordering::Release || order == Ordering::AcqRel { thread_token(currentThread) } else { true }); ++@*/ ++/*@ ++ ens [f]std::intrinsics::atomic_points_to::(dst, 1, inv_) &*& inv_(result) == true &*& ++ order != Ordering::Release &*& order != Ordering::AcqRel; ++@*/ ++/*@ ++ on_unwind_ens (order == Ordering::Release || order == Ordering::AcqRel) &*& thread_token(currentThread); ++@*/{ + // SAFETY: the caller must uphold the safety contract for `atomic_load`. ++ //@ open ordering_access(dst, _, f, inv_); + unsafe { + match order { + Relaxed => intrinsics::atomic_load::(dst), +@@ -4689,8 +4788,13 @@ + new: T, + success: Ordering, + failure: Ordering, +-) -> Result { ++) -> Result ++//@ req [_](.cas_address_model)(?key) &*& (failure == Ordering::Release || failure == Ordering::AcqRel || thin_raw_slot_type::()) &*& ordering_access(dst, failure != Ordering::Release && failure != Ordering::AcqRel, ?f, ?inv_) &*& (if failure == Ordering::Release || failure == Ordering::AcqRel { thread_token(currentThread) } else { inv_(new) == true }); ++//@ ens [f]std::intrinsics::atomic_points_to::(dst, 1, inv_) &*& failure != Ordering::Release &*& failure != Ordering::AcqRel &*& pointer_cas_returned(dst, result) &*& match result { Result::Ok(v) => inv_(v) == true &*& key(v) == key(old), Result::Err(v) => inv_(v) == true &*& key(v) != key(old) }; ++//@ on_unwind_ens (failure == Ordering::Release || failure == Ordering::AcqRel) &*& thread_token(currentThread); ++{ + // SAFETY: the caller must uphold the safety contract for `atomic_compare_exchange`. ++ //@ open ordering_access(dst, _, f, inv_); + let (val, ok) = unsafe { + match (success, failure) { + (Relaxed, Relaxed) => { +@@ -4742,6 +4846,8 @@ + (_, Release) => panic!("there is no such thing as a release failure ordering"), + } + }; ++ /*@ if ok { close pointer_cas_returned(dst, result::Result::Ok(val)); } ++ else { close pointer_cas_returned(dst, result::Result::Err(val)); } @*/ + if ok { Ok(val) } else { Err(val) } + } + +@@ -4762,8 +4868,13 @@ + new: T, + success: Ordering, + failure: Ordering, +-) -> Result { ++) -> Result ++//@ req [_](.cas_address_model)(?key) &*& (failure == Ordering::Release || failure == Ordering::AcqRel || thin_raw_slot_type::()) &*& ordering_access(dst, failure != Ordering::Release && failure != Ordering::AcqRel, ?f, ?inv_) &*& (if failure == Ordering::Release || failure == Ordering::AcqRel { thread_token(currentThread) } else { inv_(new) == true }); ++//@ ens [f]std::intrinsics::atomic_points_to::(dst, 1, inv_) &*& failure != Ordering::Release &*& failure != Ordering::AcqRel &*& pointer_cas_returned(dst, result) &*& match result { Result::Ok(v) => inv_(v) == true &*& key(v) == key(old), Result::Err(v) => inv_(v) == true }; ++//@ on_unwind_ens (failure == Ordering::Release || failure == Ordering::AcqRel) &*& thread_token(currentThread); ++{ + // SAFETY: the caller must uphold the safety contract for `atomic_compare_exchange_weak`. ++ //@ open ordering_access(dst, _, f, inv_); + let (val, ok) = unsafe { + match (success, failure) { + (Relaxed, Relaxed) => { +@@ -4815,6 +4926,8 @@ + (_, Release) => panic!("there is no such thing as a release failure ordering"), + } + }; ++ /*@ if ok { close pointer_cas_returned(dst, result::Result::Ok(val)); } ++ else { close pointer_cas_returned(dst, result::Result::Err(val)); } @*/ + if ok { Ok(val) } else { Err(val) } + } + +--- a/intrinsics/mod.rs ++++ b/intrinsics/mod.rs +@@ -160,7 +160,19 @@ + dst: *mut T, + old: T, + src: T, +-) -> (T, bool); ++) -> (T, bool)/*@ ++ req sync::atomic::thin_raw_slot_type::() == true &*& [_](.cas_address_model)(?key) &*& ++ 0 <= int_of_const(typeid(ORD_SUCC)) &*& int_of_const(typeid(ORD_SUCC)) <= 4 &*& ++ (int_of_const(typeid(ORD_FAIL)) == 0 || int_of_const(typeid(ORD_FAIL)) == 2 || int_of_const(typeid(ORD_FAIL)) == 4) &*& ++ [?f]std::intrinsics::atomic_points_to::(dst, 1, ?inv_) &*& inv_(src) == true; ++@*/ ++/*@ ++ ens [f]std::intrinsics::atomic_points_to::(dst, 1, inv_) &*& inv_(result.0) == true &*& ++ result.1 == (key(result.0) == key(old)); ++@*/ ++/*@ ++ on_unwind_ens false; ++@*/; + + /// Stores a value if the current value is the same as the `old` value, + /// with the returned `T` being the previous value and the returned `bool` being +@@ -194,7 +206,19 @@ + _dst: *mut T, + _old: T, + _src: T, +-) -> (T, bool); ++) -> (T, bool)/*@ ++ req sync::atomic::thin_raw_slot_type::() == true &*& [_](.cas_address_model)(?key) &*& ++ 0 <= int_of_const(typeid(ORD_SUCC)) &*& int_of_const(typeid(ORD_SUCC)) <= 4 &*& ++ (int_of_const(typeid(ORD_FAIL)) == 0 || int_of_const(typeid(ORD_FAIL)) == 2 || int_of_const(typeid(ORD_FAIL)) == 4) &*& ++ [?f]std::intrinsics::atomic_points_to::(_dst, 1, ?inv_) &*& inv_(_src) == true; ++@*/ ++/*@ ++ ens [f]std::intrinsics::atomic_points_to::(_dst, 1, inv_) &*& inv_(result.0) == true &*& ++ (result.1 == false || key(result.0) == key(_old)); ++@*/ ++/*@ ++ on_unwind_ens false; ++@*/; + + /// Loads the current value of the pointer. + /// `T` must be an integer or pointer type. +@@ -217,7 +241,18 @@ + #[rustc_nounwind] + pub const unsafe fn atomic_load( + src: *const T, +-) -> T; ++) -> T/*@ ++ req (typeid(T) == typeid(u32) || sync::atomic::thin_raw_slot_type::()) &*& ++ (int_of_const(typeid(ORD)) == 0 || int_of_const(typeid(ORD)) == 2 || int_of_const(typeid(ORD)) == 4) &*& ++ int_of_const(typeid(VOLATILE)) == 0 &*& ++ [?f]std::intrinsics::atomic_points_to::(src, 1, ?inv_); ++@*/ ++/*@ ++ ens [f]std::intrinsics::atomic_points_to::(src, 1, inv_) &*& inv_(result) == true; ++@*/ ++/*@ ++ on_unwind_ens false; ++@*/; + + /// Stores the value at the specified memory location. + /// `T` must be an integer or pointer type. +@@ -241,7 +276,18 @@ + pub const unsafe fn atomic_store( + dst: *mut T, + val: T, +-); ++)/*@ ++ req (typeid(T) == typeid(u32) || sync::atomic::thin_raw_slot_type::()) &*& ++ (int_of_const(typeid(ORD)) == 0 || int_of_const(typeid(ORD)) == 1 || int_of_const(typeid(ORD)) == 4) &*& ++ int_of_const(typeid(VOLATILE)) == 0 &*& ++ [?f]std::intrinsics::atomic_points_to::(dst, 1, ?inv_) &*& inv_(val) == true; ++@*/ ++/*@ ++ ens [f]std::intrinsics::atomic_points_to::(dst, 1, inv_); ++@*/ ++/*@ ++ on_unwind_ens false; ++@*/; + + /// Stores the value at the specified memory location, returning the old value. + /// `T` must be an integer or pointer type. diff --git a/verifast-proofs/core/sync/atomic.rs/specs/pointer-rmw.diff b/verifast-proofs/core/sync/atomic.rs/specs/pointer-rmw.diff new file mode 100644 index 0000000000000..8aff3232bfb3d --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/specs/pointer-rmw.diff @@ -0,0 +1,269 @@ +--- a/sync/atomic.rs ++++ b/sync/atomic.rs +@@ -270,6 +270,9 @@ + type_pred_def .atomic_content = byte_content; + type_pred_def .atomic_content = halfword_content; + fix accepts_pointer(payload: *T) -> bool { true } ++type_pred_decl .rmw_pointer_invariant : pred(fix(Self, bool)); ++pred_ctor raw_rmw_pointer_invariant

()(inv_: fix(*P, bool)) = inv_ == accepts_pointer; ++type_pred_def for

<*P>.rmw_pointer_invariant = raw_rmw_pointer_invariant::

; + fix thin_raw_slot_type() -> bool { + typeid(S) == typeid(*::Pointee) && + ptr::metadata::Pointee::Metadata_typeid(intrinsics::bounds::BuiltinDeref::Pointee_typeid(typeid(S))) == typeid(()) +@@ -277,6 +280,9 @@ + pred_ctor pointer_slot_content(slot: *_)(;) = + thin_raw_slot_type::<*T>() == true &*& + std::intrinsics::atomic_points_to::<*T>(slot as **T, 1, accepts_pointer); ++pred pointer_usize_domain(inv_: fix(S, bool)) = ++ thin_raw_slot_type::() == true &*& typeid(U) == typeid(usize) &*& ++ [_](.rmw_pointer_invariant)(inv_); + fix pointer_view_content(slot: *_) -> pred(;) { pointer_slot_content::(slot) } + type_pred_def for <*T>.atomic_content = pointer_view_content::; + lem close_pointer_exchange(slot: **P) +@@ -384,7 +390,24 @@ + frac_borrow_mono(k, sub, ref_initialized_(l)); + close exists(owned); + close Atomic_share::(sub, t, l); + leak Atomic_share::(sub, t, l); ++} ++lem open_pointer_usize_rmw(a: *Atomic<*P>, k: lifetime_t, t: thread_id_t, q: real) ++ nonghost_callers_only ++ req [_]Atomic_share::<*P>(k, t, a) &*& [q]lifetime_token(k); ++ ens [?f]std::intrinsics::atomic_points_to::<*P>(ref_origin(a) as **P, 1, accepts_pointer) &*& ++ thin_raw_slot_type::<*P>() == true &*& [_]pointer_usize_domain::<*P, usize>(accepts_pointer) &*& ++ [_]frac_borrow(k, ref_initialized_(a)) &*& ++ close_frac_borrow_token(f, pointer_slot_content::

(ref_origin(a) as **P), q, k); ++{ ++ let slot = ref_origin(a) as **P; ++ open Atomic_share::<*P>(k, t, a); ++ let f = open_frac_borrow(k, pointer_slot_content::

(slot), q); ++ open [f]pointer_slot_content::

(slot)(); ++ close raw_rmw_pointer_invariant::

()(accepts_pointer); ++ leak raw_rmw_pointer_invariant::

()(accepts_pointer); ++ close pointer_usize_domain::<*P, usize>(accepts_pointer); ++ leak pointer_usize_domain::<*P, usize>(accepts_pointer); + } + lem init_ref_Atomic(p: *Atomic) + req type_interp::() &*& atomic_mask(Nlft) &*& ref_init_perm(p, ?x) &*& [_]Atomic_share::(?k, ?t, x) &*& [?q]lifetime_token(k); +@@ -2732,7 +2755,14 @@ + #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] +- pub fn fetch_byte_add(&self, val: usize, order: Ordering) -> *mut T { ++ pub fn fetch_byte_add(&self, val: usize, order: Ordering) -> *mut T ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share::<*T>(k, currentThread, self) &*& Ordering_own(currentThread, order); ++ //@ ens [q]lifetime_token(k); ++ //@ on_unwind_ens false; ++ { ++ //@ open Ordering_own(currentThread, order); ++ //@ open_pointer_usize_rmw::(self, k, currentThread, q/2); ++ //@ vf_on_normal_return(close_pointer_exchange::(ref_origin(self) as **T)); + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_add(self.as_ptr(), val, order).cast() } + } +@@ -2768,7 +2798,14 @@ + #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] +- pub fn fetch_byte_sub(&self, val: usize, order: Ordering) -> *mut T { ++ pub fn fetch_byte_sub(&self, val: usize, order: Ordering) -> *mut T ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share::<*T>(k, currentThread, self) &*& Ordering_own(currentThread, order); ++ //@ ens [q]lifetime_token(k); ++ //@ on_unwind_ens false; ++ { ++ //@ open Ordering_own(currentThread, order); ++ //@ open_pointer_usize_rmw::(self, k, currentThread, q/2); ++ //@ vf_on_normal_return(close_pointer_exchange::(ref_origin(self) as **T)); + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_sub(self.as_ptr(), val, order).cast() } + } +@@ -2820,7 +2857,14 @@ + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] +- pub fn fetch_or(&self, val: usize, order: Ordering) -> *mut T { ++ pub fn fetch_or(&self, val: usize, order: Ordering) -> *mut T ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share::<*T>(k, currentThread, self) &*& Ordering_own(currentThread, order); ++ //@ ens [q]lifetime_token(k); ++ //@ on_unwind_ens false; ++ { ++ //@ open Ordering_own(currentThread, order); ++ //@ open_pointer_usize_rmw::(self, k, currentThread, q/2); ++ //@ vf_on_normal_return(close_pointer_exchange::(ref_origin(self) as **T)); + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_or(self.as_ptr(), val, order).cast() } + } +@@ -2871,7 +2915,14 @@ + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] +- pub fn fetch_and(&self, val: usize, order: Ordering) -> *mut T { ++ pub fn fetch_and(&self, val: usize, order: Ordering) -> *mut T ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share::<*T>(k, currentThread, self) &*& Ordering_own(currentThread, order); ++ //@ ens [q]lifetime_token(k); ++ //@ on_unwind_ens false; ++ { ++ //@ open Ordering_own(currentThread, order); ++ //@ open_pointer_usize_rmw::(self, k, currentThread, q/2); ++ //@ vf_on_normal_return(close_pointer_exchange::(ref_origin(self) as **T)); + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_and(self.as_ptr(), val, order).cast() } + } +@@ -2920,7 +2971,14 @@ + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] +- pub fn fetch_xor(&self, val: usize, order: Ordering) -> *mut T { ++ pub fn fetch_xor(&self, val: usize, order: Ordering) -> *mut T ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share::<*T>(k, currentThread, self) &*& Ordering_own(currentThread, order); ++ //@ ens [q]lifetime_token(k); ++ //@ on_unwind_ens false; ++ { ++ //@ open Ordering_own(currentThread, order); ++ //@ open_pointer_usize_rmw::(self, k, currentThread, q/2); ++ //@ vf_on_normal_return(close_pointer_exchange::(ref_origin(self) as **T)); + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_xor(self.as_ptr(), val, order).cast() } + } +@@ -4632,7 +4690,11 @@ + #[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) + })] +-const unsafe fn atomic_add(dst: *mut T, val: U, order: Ordering) -> T { ++const unsafe fn atomic_add(dst: *mut T, val: U, order: Ordering) -> T ++//@ req [?f]std::intrinsics::atomic_points_to::(dst, 1, ?inv_) &*& [_]pointer_usize_domain::(inv_); ++//@ ens [f]std::intrinsics::atomic_points_to::(dst, 1, inv_) &*& inv_(result) == true; ++//@ on_unwind_ens false; ++{ + // SAFETY: the caller must uphold the safety contract for `atomic_add`. + unsafe { + match order { +@@ -4656,7 +4718,11 @@ + #[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) + })] +-const unsafe fn atomic_sub(dst: *mut T, val: U, order: Ordering) -> T { ++const unsafe fn atomic_sub(dst: *mut T, val: U, order: Ordering) -> T ++//@ req [?f]std::intrinsics::atomic_points_to::(dst, 1, ?inv_) &*& [_]pointer_usize_domain::(inv_); ++//@ ens [f]std::intrinsics::atomic_points_to::(dst, 1, inv_) &*& inv_(result) == true; ++//@ on_unwind_ens false; ++{ + // SAFETY: the caller must uphold the safety contract for `atomic_sub`. + unsafe { + match order { +@@ -4828,7 +4894,11 @@ + #[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) + })] +-const unsafe fn atomic_and(dst: *mut T, val: U, order: Ordering) -> T { ++const unsafe fn atomic_and(dst: *mut T, val: U, order: Ordering) -> T ++//@ req [?f]std::intrinsics::atomic_points_to::(dst, 1, ?inv_) &*& [_]pointer_usize_domain::(inv_); ++//@ ens [f]std::intrinsics::atomic_points_to::(dst, 1, inv_) &*& inv_(result) == true; ++//@ on_unwind_ens false; ++{ + // SAFETY: the caller must uphold the safety contract for `atomic_and` + unsafe { + match order { +@@ -4874,7 +4944,11 @@ + #[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) + })] +-const unsafe fn atomic_or(dst: *mut T, val: U, order: Ordering) -> T { ++const unsafe fn atomic_or(dst: *mut T, val: U, order: Ordering) -> T ++//@ req [?f]std::intrinsics::atomic_points_to::(dst, 1, ?inv_) &*& [_]pointer_usize_domain::(inv_); ++//@ ens [f]std::intrinsics::atomic_points_to::(dst, 1, inv_) &*& inv_(result) == true; ++//@ on_unwind_ens false; ++{ + // SAFETY: the caller must uphold the safety contract for `atomic_or` + unsafe { + match order { +@@ -4897,7 +4971,11 @@ + #[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) + })] +-const unsafe fn atomic_xor(dst: *mut T, val: U, order: Ordering) -> T { ++const unsafe fn atomic_xor(dst: *mut T, val: U, order: Ordering) -> T ++//@ req [?f]std::intrinsics::atomic_points_to::(dst, 1, ?inv_) &*& [_]pointer_usize_domain::(inv_); ++//@ ens [f]std::intrinsics::atomic_points_to::(dst, 1, inv_) &*& inv_(result) == true; ++//@ on_unwind_ens false; ++{ + // SAFETY: the caller must uphold the safety contract for `atomic_xor` + unsafe { + match order { +--- a/intrinsics/mod.rs ++++ b/intrinsics/mod.rs +@@ -300,7 +300,13 @@ + pub const unsafe fn atomic_xadd( + dst: *mut T, + src: U, +-) -> T; ++) -> T/*@ ++ req 0 <= int_of_const(typeid(ORD)) &*& int_of_const(typeid(ORD)) <= 4 &*& ++ [?f]std::intrinsics::atomic_points_to::(dst, 1, ?inv_) &*& ++ [_]sync::atomic::pointer_usize_domain::(inv_); ++@*/ ++/*@ ens [f]std::intrinsics::atomic_points_to::(dst, 1, inv_) &*& inv_(result) == true; @*/ ++/*@ on_unwind_ens false; @*/; + + /// Subtract from the current value, returning the previous value. + /// `T` must be an integer or pointer type. +@@ -327,7 +333,13 @@ + pub const unsafe fn atomic_xsub( + dst: *mut T, + src: U, +-) -> T; ++) -> T/*@ ++ req 0 <= int_of_const(typeid(ORD)) &*& int_of_const(typeid(ORD)) <= 4 &*& ++ [?f]std::intrinsics::atomic_points_to::(dst, 1, ?inv_) &*& ++ [_]sync::atomic::pointer_usize_domain::(inv_); ++@*/ ++/*@ ens [f]std::intrinsics::atomic_points_to::(dst, 1, inv_) &*& inv_(result) == true; @*/ ++/*@ on_unwind_ens false; @*/; + + /// Bitwise and with the current value, returning the previous value. + /// `T` must be an integer or pointer type. +@@ -354,7 +366,13 @@ + pub const unsafe fn atomic_and( + dst: *mut T, + src: U, +-) -> T; ++) -> T/*@ ++ req 0 <= int_of_const(typeid(ORD)) &*& int_of_const(typeid(ORD)) <= 4 &*& ++ [?f]std::intrinsics::atomic_points_to::(dst, 1, ?inv_) &*& ++ [_]sync::atomic::pointer_usize_domain::(inv_); ++@*/ ++/*@ ens [f]std::intrinsics::atomic_points_to::(dst, 1, inv_) &*& inv_(result) == true; @*/ ++/*@ on_unwind_ens false; @*/; + + /// Bitwise nand with the current value, returning the previous value. + /// `T` must be an integer or pointer type. +@@ -402,7 +420,13 @@ + pub const unsafe fn atomic_or( + dst: *mut T, + src: U, +-) -> T; ++) -> T/*@ ++ req 0 <= int_of_const(typeid(ORD)) &*& int_of_const(typeid(ORD)) <= 4 &*& ++ [?f]std::intrinsics::atomic_points_to::(dst, 1, ?inv_) &*& ++ [_]sync::atomic::pointer_usize_domain::(inv_); ++@*/ ++/*@ ens [f]std::intrinsics::atomic_points_to::(dst, 1, inv_) &*& inv_(result) == true; @*/ ++/*@ on_unwind_ens false; @*/; + + /// Bitwise xor with the current value, returning the previous value. + /// `T` must be an integer or pointer type. +@@ -429,7 +453,13 @@ + pub const unsafe fn atomic_xor( + dst: *mut T, + src: U, +-) -> T; ++) -> T/*@ ++ req 0 <= int_of_const(typeid(ORD)) &*& int_of_const(typeid(ORD)) <= 4 &*& ++ [?f]std::intrinsics::atomic_points_to::(dst, 1, ?inv_) &*& ++ [_]sync::atomic::pointer_usize_domain::(inv_); ++@*/ ++/*@ ens [f]std::intrinsics::atomic_points_to::(dst, 1, inv_) &*& inv_(result) == true; @*/ ++/*@ on_unwind_ens false; @*/; + + /// Maximum with the current value using a signed comparison. + /// `T` must be a signed integer type. diff --git a/verifast-proofs/core/sync/atomic.rs/specs/pointer-slot.diff b/verifast-proofs/core/sync/atomic.rs/specs/pointer-slot.diff new file mode 100644 index 0000000000000..064305c9f1571 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/specs/pointer-slot.diff @@ -0,0 +1,135 @@ +--- a/sync/atomic.rs ++++ b/sync/atomic.rs +@@ -261,6 +261,7 @@ + type_pred_decl .atomic_content : fix(*_, pred(;)); + pred_ctor U32_atomic_content(p: *_)(;) = + std::intrinsics::atomic_points_to::(p as *u32, 1, accepts_word); ++type_pred_def .atomic_content = U32_atomic_content; + fix accepts_unsigned(v: T) -> bool { true } + pred_ctor unsigned_content(p: *_)(;) = + std::intrinsics::atomic_points_to::(p as *T, 1, accepts_unsigned); +@@ -268,6 +269,25 @@ + fix halfword_content(p: *_) -> pred(;) { unsigned_content::(p) } + type_pred_def .atomic_content = byte_content; + type_pred_def .atomic_content = halfword_content; ++fix accepts_pointer(payload: *T) -> bool { true } ++fix thin_raw_slot_type() -> bool { ++ typeid(S) == typeid(*::Pointee) && ++ ptr::metadata::Pointee::Metadata_typeid(intrinsics::bounds::BuiltinDeref::Pointee_typeid(typeid(S))) == typeid(()) ++} ++pred_ctor pointer_slot_content(slot: *_)(;) = ++ thin_raw_slot_type::<*T>() == true &*& ++ std::intrinsics::atomic_points_to::<*T>(slot as **T, 1, accepts_pointer); ++fix pointer_view_content(slot: *_) -> pred(;) { pointer_slot_content::(slot) } ++type_pred_def for <*T>.atomic_content = pointer_view_content::; ++lem close_pointer_exchange(slot: **P) ++ nonghost_callers_only ++ req [?f]std::intrinsics::atomic_points_to::<*P>(slot, 1, accepts_pointer) &*& thin_raw_slot_type::<*P>() == true &*& ++ close_frac_borrow_token(f, pointer_slot_content::

(slot), ?q, ?k); ++ ens [q]lifetime_token(k); ++{ ++ close [f]pointer_slot_content::

(slot)(); ++ close_frac_borrow(f, pointer_slot_content::

(slot)); ++} + fix unsigned_view_address(p: *T) -> *Atomic { + p as *Atomic + } +@@ -1799,8 +1819,17 @@ + #[ensures(|result: &&AtomicPtr| { + core::ptr::eq(*result, ptr.cast::>()) + })] +- pub const unsafe fn from_ptr<'a>(ptr: *mut *mut T) -> &'a AtomicPtr { ++ pub const unsafe fn from_ptr<'a>(ptr: *mut *mut T) -> &'a AtomicPtr ++ //@ req [?q]lifetime_token('a) &*& [_]frac_borrow('a, pointer_slot_content::(ptr)) &*& ref_origin(ptr) == ptr; ++ //@ ens [q]lifetime_token('a) &*& [_]Atomic_share::<*T>('a, currentThread, result) &*& [_]frac_borrow('a, ref_initialized_(result)) &*& ref_origin(result) as pointer == ptr as pointer; ++ //@ on_unwind_ens false; ++ { + // SAFETY: guaranteed by the caller ++ //@ let view = precreate_ref(ptr as *Atomic<*T>); ++ //@ open_ref_init_perm_Atomic::<*T>(view); ++ //@ close_ref_initialized_Atomic::<*T>(view, 1); ++ //@ leak [1/2]ref_initialized(view); ++ //@ finish_unsigned_ref('a, currentThread, view); + unsafe { &*ptr.cast() } + } + +@@ -2208,8 +2237,18 @@ + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] +- pub const fn swap(&self, ptr: *mut T, order: Ordering) -> *mut T { ++ pub const fn swap(&self, ptr: *mut T, order: Ordering) -> *mut T ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share::<*T>(k, currentThread, self) &*& Ordering_own(currentThread, order); ++ //@ ens [q]lifetime_token(k); ++ //@ on_unwind_ens false; ++ { + // SAFETY: data races are prevented by atomic intrinsics. ++ //@ open Ordering_own(currentThread, order); ++ //@ let slot = ref_origin(self) as **T; ++ //@ open Atomic_share::<*T>(k, currentThread, self); ++ //@ let f = open_frac_borrow(k, pointer_slot_content::(slot), q/2); ++ //@ open [f]pointer_slot_content::(slot)(); ++ //@ vf_on_normal_return(close_pointer_exchange::(ref_origin(self) as **T)); + unsafe { atomic_swap(self.as_ptr(), ptr, order) } + } + +@@ -2921,7 +2960,11 @@ + #[stable(feature = "atomic_as_ptr", since = "1.70.0")] + #[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")] + #[lint::never_returns_null_ptr] +- pub const fn as_ptr(&self) -> *mut *mut T { ++ pub const fn as_ptr(&self) -> *mut *mut T ++ //@ req true; ++ //@ ens result as pointer == ref_origin(self) as pointer; ++ //@ on_unwind_ens false; ++ { + self.v.get().cast() + } + } +@@ -4561,7 +4604,11 @@ + #[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) + })] +-const unsafe fn atomic_swap(dst: *mut T, val: T, order: Ordering) -> T { ++const unsafe fn atomic_swap(dst: *mut T, val: T, order: Ordering) -> T ++//@ req thin_raw_slot_type::() == true &*& [?f]std::intrinsics::atomic_points_to::(dst, 1, ?inv_) &*& inv_(val) == true; ++//@ ens [f]std::intrinsics::atomic_points_to::(dst, 1, inv_) &*& inv_(result) == true; ++//@ on_unwind_ens false; ++{ + // SAFETY: the caller must uphold the safety contract for `atomic_swap`. + unsafe { + match order { +--- a/lib.rs ++++ b/lib.rs +@@ -62,6 +62,11 @@ + ), + ))] + #![no_core] ++ ++/*@ ++fix intrinsics::bounds::BuiltinDeref::Pointee_typeid(t: *_) -> *_; ++fix ptr::metadata::Pointee::Metadata_typeid(t: *_) -> *_; ++@*/ + #![rustc_coherence_is_core] + #![rustc_preserve_ub_checks] + // +--- a/intrinsics/mod.rs ++++ b/intrinsics/mod.rs +@@ -264,7 +264,16 @@ + /// [`AtomicPtr

::swap`]: AtomicPtr::swap + #[rustc_intrinsic] + #[rustc_nounwind] +-pub const unsafe fn atomic_xchg(dst: *mut T, src: T) -> T; ++pub const unsafe fn atomic_xchg(dst: *mut T, src: T) -> T/*@ ++ req sync::atomic::thin_raw_slot_type::() == true &*& 0 <= int_of_const(typeid(ORD)) &*& int_of_const(typeid(ORD)) <= 4 &*& ++ [?f]std::intrinsics::atomic_points_to::(dst, 1, ?inv_) &*& inv_(src) == true; ++@*/ ++/*@ ++ ens [f]std::intrinsics::atomic_points_to::(dst, 1, inv_) &*& inv_(result) == true; ++@*/ ++/*@ ++ on_unwind_ens false; ++@*/; + + /// Adds to the current value, returning the previous value. + /// `T` must be an integer or pointer type. diff --git a/verifast-proofs/core/sync/atomic.rs/specs/readonly.diff b/verifast-proofs/core/sync/atomic.rs/specs/readonly.diff new file mode 100644 index 0000000000000..eda430ffa0781 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/specs/readonly.diff @@ -0,0 +1,508 @@ +--- a/sync/atomic.rs ++++ b/sync/atomic.rs +@@ -261,32 +261,59 @@ + type_pred_decl .atomic_content : fix(*_, pred(;)); + pred_ctor U32_atomic_content(p: *_)(;) = + std::intrinsics::atomic_points_to::(p as *u32, 1, accepts_word); ++fix ro_scalar_type(t: *_) -> bool { t == typeid(u8) || t == typeid(u32) } ++fix valid_bool_byte(v: u8) -> bool { v == 0 || v == 1 } ++fix is_bool_byte(target: u8, v: u8) -> bool { valid_bool_byte(v) && v == target } ++fix is_u32_val(target: u32, v: u32) -> bool { v == target } ++pred_ctor ro_bool_content(p: *_, af: real, val: bool)(;) = ++ 0 < af &*& af <= 1 &*& std::intrinsics::atomic_points_to::(p as *u8, af, (is_bool_byte)(if val { 1 } else { 0 })) &*& (if af < 1 { [1 - af](*(p as *u8) |-> if val { 1 } else { 0 }) } else { true }); ++pred_ctor ro_u32_content(p: *_, af: real, val: u32)(;) = ++ 0 < af &*& af <= 1 &*& std::intrinsics::atomic_points_to::(p as *u32, af, (is_u32_val)(val)) &*& (if af < 1 { [1 - af](*(p as *u32) |-> val) } else { true }); ++pred ro_bool_borrow(k: lifetime_t, p: *_, af: real, val: bool) = [_]frac_borrow(k, ro_bool_content(p, af, val)); ++pred ro_u32_borrow(k: lifetime_t, p: *_, af: real, val: u32) = [_]frac_borrow(k, ro_u32_content(p, af, val)); ++pred_ctor rw_bool_content(p: *_)(;) = ++ std::intrinsics::atomic_points_to::(p as *u8, 1, valid_bool_byte); ++pred_ctor rw_u32_content(p: *_)(;) = ++ std::intrinsics::atomic_points_to::(p as *u32, 1, accepts_word); ++fix ro_bool_full(val: bool, p: *_) -> pred(;) { ro_bool_content(p, 1, val) } ++fix ro_u32_full(val: u32, p: *_) -> pred(;) { ro_u32_content(p, 1, val) } ++fix ro_rep_fn(bval: bool, uval: u32) -> fix(*_, pred(;)) { ++ if typeid(T) == typeid(bool) { (ro_bool_full)(bval) } else { (ro_u32_full)(uval) } ++} ++fix ro_representation(bval: bool, uval: u32, p: *_) -> pred(;) { (ro_rep_fn::(bval, uval))(p) } + fix rep_fn(owned: bool) -> fix(*_, pred(;)) { .atomic_content } + fix representation(owned: bool, p: *_) -> pred(;) { (rep_fn::(owned))(p) } + fix view_content(p: *T) -> pred(;) { .atomic_content(p) } + pred >.share(k, t, p) = +- exists::(?owned) &*& [_]frac_borrow(k, representation::(owned, ref_origin(p))) &*& [_]frac_borrow(k, ref_initialized_(p)); ++ if typeid(T) == typeid(bool) { ++ [_]ro_bool_borrow(k, ref_origin(p), ?af, ?val) &*& [_]frac_borrow(k, ref_initialized_(p)) ++ } else { ++ [_]ro_u32_borrow(k, ref_origin(p), ?af, ?val) &*& [_]frac_borrow(k, ref_initialized_(p)) ++ }; + // The representation witnesses consume and return the actual slot at p. The + // by-value predicate carries their linear permissions across the full borrow. + lem_type atomic_pack(valid: fix(Atomic, bool), layout: bool, owned: bool, content: fix(*_, pred(;))) = lem(p: *Atomic); + req layout == true &*& atomic_mask(MaskTop) &*& *p |-> ?v &*& valid(v) == true; + ens atomic_mask(MaskTop) &*& (content(p))(); + lem_type atomic_unpack(valid: fix(Atomic, bool), layout: bool, owned: bool, content: fix(*_, pred(;))) = lem(p: *Atomic); + req layout == true &*& (content(p))(); + ens *p |-> ?v &*& valid(v) == true; + type_pred_decl .storage_owner : pred(thread_id_t, Self); + pred >.storage_owner(t, v) = < ::Storage>.own(t, v.v); + lem_type atomic_drop_rep(valid: fix(Atomic, bool), layout: bool, field: pred(thread_id_t, Atomic)) = lem(t: thread_id_t, v: Atomic); + req layout == true &*& valid(v) == true; + ens field(t, v); + pred >.own(t, v) = +- is_atomic_pack::(?pack, ?valid, ?layout, ?owned, rep_fn::(owned)) &*& is_atomic_unpack::(?unpack, valid, layout, owned, rep_fn::(owned)) &*& ++ exists::(?bval) &*& exists::(?uval) &*& ++ is_atomic_pack::(?pack, ?valid, ?layout, ?owned, ro_rep_fn::(bval, uval)) &*& is_atomic_unpack::(?unpack, valid, layout, owned, ro_rep_fn::(bval, uval)) &*& + is_atomic_drop_rep::(?drop_rep, valid, layout, >.storage_owner) &*& layout == true &*& valid(v) == true; + lem Atomic_drop() + req Atomic_own::(?_t, ?_v); + ens < ::Storage>.own(_t, _v.v); + { + open Atomic_own::(_t, _v); ++ open exists::(?bval); ++ open exists::(?uval); + assert is_atomic_drop_rep::(?drop_rep, _, _, _); + drop_rep(_t, _v); + open Atomic_storage_owner::(_t, _v); +@@ -295,63 +322,91 @@ + let kl = open_full_borrow_strong_m(k, Atomic_full_borrow_content::(t, l), q); + open Atomic_full_borrow_content::(t, l)(); + open Atomic_own::(t, _); +- assert is_atomic_pack::(?pack, ?valid, ?layout, ?owned, rep_fn::(owned)); +- assert is_atomic_unpack::(?unpack, valid, layout, owned, rep_fn::(owned)); ++ open exists::(?bval); ++ open exists::(?uval); ++ assert is_atomic_pack::(?pack, ?valid, ?layout, ?owned, ro_rep_fn::(bval, uval)); ++ assert is_atomic_unpack::(?unpack, valid, layout, owned, ro_rep_fn::(bval, uval)); + assert is_atomic_drop_rep::(?drop_rep, valid, layout, >.storage_owner); + close_points_to(l); + pack(l); + { +- pred Ctx() = is_atomic_pack::(pack, valid, layout, owned, rep_fn::(owned)) &*& is_atomic_unpack::(unpack, valid, layout, owned, rep_fn::(owned)) &*& is_atomic_drop_rep::(drop_rep, valid, layout, >.storage_owner) &*& layout == true; +- produce_lem_ptr_chunk full_borrow_convert_strong(Ctx, representation::(owned, l), kl, Atomic_full_borrow_content::(t, l))() { ++ pred Ctx() = is_atomic_pack::(pack, valid, layout, owned, ro_rep_fn::(bval, uval)) &*& is_atomic_unpack::(unpack, valid, layout, owned, ro_rep_fn::(bval, uval)) &*& is_atomic_drop_rep::(drop_rep, valid, layout, >.storage_owner) &*& layout == true; ++ produce_lem_ptr_chunk full_borrow_convert_strong(Ctx, ro_representation::(bval, uval, l), kl, Atomic_full_borrow_content::(t, l))() { + open Ctx(); + unpack(l); ++ close exists(bval); ++ close exists(uval); + close Atomic_own::(t, *l); + open_points_to(l); + close Atomic_full_borrow_content::(t, l)(); + } { + close Ctx(); +- close_full_borrow_strong_m(kl, Atomic_full_borrow_content::(t, l), representation::(owned, l)); +- full_borrow_mono(kl, k, representation::(owned, l)); ++ close_full_borrow_strong_m(kl, Atomic_full_borrow_content::(t, l), ro_representation::(bval, uval, l)); ++ full_borrow_mono(kl, k, ro_representation::(bval, uval, l)); + } + } +- full_borrow_into_frac_m(k, representation::(owned, l)); ++ full_borrow_into_frac_m(k, ro_representation::(bval, uval, l)); ++ if typeid(T) == typeid(bool) { ++ close ro_bool_borrow(k, l, 1, bval); ++ leak ro_bool_borrow(k, l, 1, bval); ++ } else { ++ close ro_u32_borrow(k, l, 1, uval); ++ leak ro_u32_borrow(k, l, 1, uval); ++ } + close_ref_initialized_Atomic::(l, 1); + close ref_initialized_::>(l)(); + borrow_m(k, ref_initialized_(l)); + full_borrow_into_frac_m(k, ref_initialized_(l)); + leak borrow_end_token(_, _); +- close exists(owned); + close Atomic_share::(k, t, l); + leak Atomic_share::(k, t, l); + } + lem Atomic_share_mono(k: lifetime_t, sub: lifetime_t, t: thread_id_t, l: *Atomic) + req type_interp::() &*& lifetime_inclusion(sub, k) == true &*& [_]Atomic_share::(k, t, l); + ens type_interp::() &*& [_]Atomic_share::(sub, t, l); + { + open Atomic_share::(k, t, l); +- assert [_]exists::(?owned); +- frac_borrow_mono(k, sub, representation::(owned, ref_origin(l))); ++ if typeid(T) == typeid(bool) { ++ open ro_bool_borrow(k, ref_origin(l), ?af, ?val); ++ frac_borrow_mono(k, sub, ro_bool_content(ref_origin(l), af, val)); ++ close ro_bool_borrow(sub, ref_origin(l), af, val); ++ leak ro_bool_borrow(sub, ref_origin(l), af, val); ++ } else { ++ open ro_u32_borrow(k, ref_origin(l), ?af, ?val); ++ frac_borrow_mono(k, sub, ro_u32_content(ref_origin(l), af, val)); ++ close ro_u32_borrow(sub, ref_origin(l), af, val); ++ leak ro_u32_borrow(sub, ref_origin(l), af, val); ++ } + frac_borrow_mono(k, sub, ref_initialized_(l)); +- close exists(owned); + close Atomic_share::(sub, t, l); + leak Atomic_share::(sub, t, l); + } + lem init_ref_Atomic(p: *Atomic) + req type_interp::() &*& atomic_mask(Nlft) &*& ref_init_perm(p, ?x) &*& [_]Atomic_share::(?k, ?t, x) &*& [?q]lifetime_token(k); + ens type_interp::() &*& atomic_mask(Nlft) &*& [q]lifetime_token(k) &*& [_]Atomic_share::(k, t, p) &*& [_]frac_borrow(k, ref_initialized_(p)); + { + open Atomic_share::(k, t, x); +- assert [_]exists::(?owned); + open_ref_init_perm_Atomic::(p); + close_ref_initialized_Atomic::(p, 1); + close ref_initialized_::>(p)(); + borrow_m(k, ref_initialized_(p)); + full_borrow_into_frac_m(k, ref_initialized_(p)); + leak borrow_end_token(_, _); +- close exists(owned); + close Atomic_share::(k, t, p); + leak Atomic_share::(k, t, p); + } ++lem finish_ro_ref(k: lifetime_t, p: *Atomic) ++ nonghost_callers_only ++ req [1/2]ref_initialized(p); ++ ens [_]frac_borrow(k, ref_initialized_(p)); ++{ ++ close [1/2]ref_initialized_::>(p)(); ++ close scaledp(1/2, ref_initialized_(p))(); ++ borrow(k, scaledp(1/2, ref_initialized_(p))); ++ full_borrow_into_frac(k, scaledp(1/2, ref_initialized_(p))); ++ frac_borrow_implies_scaled(k, 1/2, ref_initialized_(p)); ++ leak borrow_end_token(k, scaledp(1/2, ref_initialized_(p))); ++} + @*/ + + #[unstable( +@@ -635,6 +690,69 @@ + #[stable(feature = "rust1", since = "1.0.0")] + SeqCst, + } ++ ++/*@ ++pred ordering_access(p: *T, needed: bool, f: real, af: real, inv_: fix(T, bool)) = ++ if needed { 0 < af &*& af <= 1 &*& [f]std::intrinsics::atomic_points_to::(p, af, inv_) } else { true }; ++pred ro_bool_close_tok(view: *Atomic, f: real, af: real, val: bool, q: real, k: lifetime_t) = ++ close_frac_borrow_token(f, ro_bool_content(ref_origin(view), af, val), q, k) &*& (if af < 1 { [f * (1 - af)](*(ref_origin(view) as *u8) |-> if val { 1 } else { 0 }) } else { true }); ++lem begin_ro_bool_load(view: *Atomic, k: lifetime_t, t: thread_id_t, q: real, needed: bool) ++ nonghost_callers_only ++ req [q]lifetime_token(k) &*& [_]Atomic_share::(k, t, view); ++ ens [_]frac_borrow(k, ref_initialized_(view)) &*& ordering_access(ref_origin(view) as *u8, needed, ?f, ?af, ?inv_) &*& ++ if needed { ro_bool_close_tok(view, f, af, ?val, q, k) &*& inv_ == (is_bool_byte)(if val { 1 } else { 0 }) } else { [q]lifetime_token(k) }; ++{ ++ open Atomic_share::(k, t, view); ++ open ro_bool_borrow(k, ref_origin(view), ?af, ?val); ++ if needed { ++ let f = open_frac_borrow(k, ro_bool_content(ref_origin(view), af, val), q); ++ open [f]ro_bool_content(ref_origin(view), af, val)(); ++ close ro_bool_close_tok(view, f, af, val, q, k); ++ close ordering_access(ref_origin(view) as *u8, true, f, af, (is_bool_byte)(if val { 1 } else { 0 })); ++ } else { ++ close ordering_access(ref_origin(view) as *u8, false, 1, af, (is_bool_byte)(if val { 1 } else { 0 })); ++ } ++} ++lem end_ro_bool_load(view: *Atomic) ++ nonghost_callers_only ++ req ro_bool_close_tok(view, ?f, ?af, ?val, ?q, ?k) &*& 0 < af &*& af <= 1 &*& ++ [f]std::intrinsics::atomic_points_to::(ref_origin(view) as *u8, af, (is_bool_byte)(if val { 1 } else { 0 })); ++ ens [q]lifetime_token(k); ++{ ++ open ro_bool_close_tok(view, f, af, val, q, k); ++ close [f]ro_bool_content(ref_origin(view), af, val)(); ++ close_frac_borrow(f, ro_bool_content(ref_origin(view), af, val)); ++} ++pred ro_u32_close_tok(view: *Atomic, f: real, af: real, val: u32, q: real, k: lifetime_t) = ++ close_frac_borrow_token(f, ro_u32_content(ref_origin(view), af, val), q, k) &*& (if af < 1 { [f * (1 - af)](*(ref_origin(view) as *u32) |-> val) } else { true }); ++lem begin_ro_u32_load(view: *Atomic, k: lifetime_t, t: thread_id_t, q: real, needed: bool) ++ nonghost_callers_only ++ req [q]lifetime_token(k) &*& [_]Atomic_share::(k, t, view); ++ ens [_]frac_borrow(k, ref_initialized_(view)) &*& ordering_access(ref_origin(view) as *u32, needed, ?f, ?af, ?inv_) &*& ++ if needed { ro_u32_close_tok(view, f, af, ?val, q, k) &*& inv_ == (is_u32_val)(val) } else { [q]lifetime_token(k) }; ++{ ++ open Atomic_share::(k, t, view); ++ open ro_u32_borrow(k, ref_origin(view), ?af, ?val); ++ if needed { ++ let f = open_frac_borrow(k, ro_u32_content(ref_origin(view), af, val), q); ++ open [f]ro_u32_content(ref_origin(view), af, val)(); ++ close ro_u32_close_tok(view, f, af, val, q, k); ++ close ordering_access(ref_origin(view) as *u32, true, f, af, (is_u32_val)(val)); ++ } else { ++ close ordering_access(ref_origin(view) as *u32, false, 1, af, (is_u32_val)(val)); ++ } ++} ++lem end_ro_u32_load(view: *Atomic) ++ nonghost_callers_only ++ req ro_u32_close_tok(view, ?f, ?af, ?val, ?q, ?k) &*& 0 < af &*& af <= 1 &*& ++ [f]std::intrinsics::atomic_points_to::(ref_origin(view) as *u32, af, (is_u32_val)(val)); ++ ens [q]lifetime_token(k); ++{ ++ open ro_u32_close_tok(view, f, af, val, q, k); ++ close [f]ro_u32_content(ref_origin(view), af, val)(); ++ close_frac_borrow(f, ro_u32_content(ref_origin(view), af, val)); ++} ++@*/ + + /// An [`AtomicBool`] initialized to `false`. + #[cfg(target_has_atomic_load_store = "8")] +@@ -717,8 +827,19 @@ + #[ensures(|result: &&AtomicBool| { + core::ptr::eq(*result, ptr.cast::()) + })] +- pub const unsafe fn from_ptr<'a>(ptr: *mut bool) -> &'a AtomicBool { ++ pub const unsafe fn from_ptr<'a>(ptr: *mut bool) -> &'a AtomicBool ++ //@ req [?q]lifetime_token('a) &*& [_]ro_bool_borrow('a, ptr, ?af, ?val) &*& ref_origin(ptr) == ptr; ++ //@ ens [q]lifetime_token('a) &*& [_]ro_bool_borrow('a, ref_origin(result), af, val) &*& [_]Atomic_share::('a, currentThread, result) &*& [_]frac_borrow('a, ref_initialized_(result)) &*& ref_origin(result) as pointer == ptr as pointer; ++ //@ on_unwind_ens false; ++ { + // SAFETY: guaranteed by the caller ++ //@ let view = precreate_ref(ptr as *Atomic); ++ //@ open_ref_init_perm_Atomic::(view); ++ //@ close_ref_initialized_Atomic::(view, 1); ++ //@ leak [1/2]ref_initialized(view); ++ //@ finish_ro_ref::('a, view); ++ //@ close Atomic_share::('a, currentThread, view); ++ //@ leak Atomic_share::('a, currentThread, view); + unsafe { &*ptr.cast() } + } + +@@ -884,7 +1005,14 @@ + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[requires(order == Relaxed || order == Acquire || order == SeqCst)] +- pub const fn load(&self, order: Ordering) -> bool { ++ pub const fn load(&self, order: Ordering) -> bool ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share::(k, currentThread, self) &*& Ordering_own(currentThread, order) &*& (if order == Ordering::Release || order == Ordering::AcqRel { thread_token(currentThread) } else { true }); ++ //@ ens [q]lifetime_token(k) &*& order != Ordering::Release &*& order != Ordering::AcqRel; ++ //@ on_unwind_ens [q]lifetime_token(k) &*& (order == Ordering::Release || order == Ordering::AcqRel) &*& thread_token(currentThread); ++ { ++ //@ open Ordering_own(currentThread, order); ++ //@ begin_ro_bool_load(self, k, currentThread, q/2, order != Ordering::Release && order != Ordering::AcqRel); ++ //@ vf_on_normal_return(end_ro_bool_load(self)); + // SAFETY: any data races are prevented by atomic intrinsics and the raw + // pointer passed in is valid because we got it from a reference. + unsafe { +@@ -1548,7 +1676,11 @@ + #[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")] + #[lint::never_returns_null_ptr] + #[lint::should_not_be_called_on_const_items] +- pub const fn as_ptr(&self) -> *mut bool { ++ pub const fn as_ptr(&self) -> *mut bool ++ //@ req true; ++ //@ ens result as pointer == ref_origin(self) as pointer; ++ //@ on_unwind_ens false; ++ { + self.v.get().cast() + } + +@@ -3102,12 +3234,19 @@ + #[ensures(|result: &&$atomic_type| { + ub_checks::can_write((*result).as_ptr()) + })] + pub const unsafe fn from_ptr<'a>(ptr: *mut $int_type) -> &'a $atomic_type +- //@ req [?q]lifetime_token('a) &*& [_]frac_borrow('a, view_content(ptr)) &*& ref_origin(ptr) == ptr; +- //@ ens [q]lifetime_token('a) &*& [_]Atomic_share('a, currentThread, result) &*& [_]frac_borrow('a, ref_initialized_(result)) &*& ref_origin(result) as *_ == ptr as *_; ++ //@ req [?q]lifetime_token('a) &*& [_]ro_u32_borrow('a, ptr, ?af, ?val) &*& ref_origin(ptr) == ptr; ++ //@ ens [q]lifetime_token('a) &*& [_]ro_u32_borrow('a, ref_origin(result), af, val) &*& [_]Atomic_share::('a, currentThread, result) &*& [_]frac_borrow('a, ref_initialized_(result)) &*& ref_origin(result) as *_ == ptr as *_; + //@ on_unwind_ens false; + { + // SAFETY: guaranteed by the caller ++ //@ let view = precreate_ref(ptr as *Atomic); ++ //@ open_ref_init_perm_Atomic::(view); ++ //@ close_ref_initialized_Atomic::(view, 1); ++ //@ leak [1/2]ref_initialized(view); ++ //@ finish_ro_ref::('a, view); ++ //@ close Atomic_share::('a, currentThread, view); ++ //@ leak Atomic_share::('a, currentThread, view); + unsafe { &*ptr.cast() } + } + +@@ -3305,7 +3444,14 @@ + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[requires(order == Relaxed || order == Acquire || order == SeqCst)] +- pub const fn load(&self, order: Ordering) -> $int_type { ++ pub const fn load(&self, order: Ordering) -> $int_type ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share(k, currentThread, self) &*& Ordering_own(currentThread, order) &*& (if order == Ordering::Release || order == Ordering::AcqRel { thread_token(currentThread) } else { true }); ++ //@ ens [q]lifetime_token(k) &*& order != Ordering::Release &*& order != Ordering::AcqRel; ++ //@ on_unwind_ens [q]lifetime_token(k) &*& (order == Ordering::Release || order == Ordering::AcqRel) &*& thread_token(currentThread); ++ { ++ //@ open Ordering_own(currentThread, order); ++ //@ begin_ro_u32_load(self, k, currentThread, q/2, order != Ordering::Release && order != Ordering::AcqRel); ++ //@ vf_on_normal_return(end_ro_u32_load(self)); + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_load::<_, /* VOLATILE */ false>(self.as_ptr(), order) } + } +@@ -4488,8 +4634,19 @@ + #[requires(order == Relaxed || order == Release || order == SeqCst)] + #[ensures(|_| ub_checks::can_dereference(dst as *const T))] + #[ensures(|_| ub_checks::can_write(dst))] +-const unsafe fn atomic_store(dst: *mut T, val: T, order: Ordering) { ++const unsafe fn atomic_store(dst: *mut T, val: T, order: Ordering) /*@ ++ req ro_scalar_type(typeid(T)) == true &*& int_of_const(typeid(VOLATILE)) == 0 &*& ++ ordering_access(dst, order != Ordering::Acquire && order != Ordering::AcqRel, ?f, 1, ?inv_) &*& ++ (if order == Ordering::Acquire || order == Ordering::AcqRel { thread_token(currentThread) } else { inv_(val) == true }); ++@*/ ++/*@ ++ ens [f]std::intrinsics::atomic_points_to::(dst, 1, inv_) &*& order != Ordering::Acquire &*& order != Ordering::AcqRel; ++@*/ ++/*@ ++ on_unwind_ens (order == Ordering::Acquire || order == Ordering::AcqRel) &*& thread_token(currentThread); ++@*/{ + // SAFETY: the caller must uphold the safety contract for `atomic_store`. ++ //@ open ordering_access(dst, _, f, 1, inv_); + unsafe { + match order { + Relaxed => intrinsics::atomic_store::(dst, val), +@@ -4509,8 +4666,20 @@ + #[requires(ub_checks::can_dereference(dst))] + #[requires(order == Relaxed || order == Acquire || order == SeqCst)] + #[ensures(|_| ub_checks::can_dereference(dst))] +-const unsafe fn atomic_load(dst: *const T, order: Ordering) -> T { ++const unsafe fn atomic_load(dst: *const T, order: Ordering) -> T /*@ ++ req ro_scalar_type(typeid(T)) == true &*& int_of_const(typeid(VOLATILE)) == 0 &*& ++ ordering_access(dst, order != Ordering::Release && order != Ordering::AcqRel, ?f, ?af, ?inv_) &*& ++ (if order == Ordering::Release || order == Ordering::AcqRel { thread_token(currentThread) } else { true }); ++@*/ ++/*@ ++ ens [f]std::intrinsics::atomic_points_to::(dst, af, inv_) &*& 0 < af &*& af <= 1 &*& inv_(result) == true &*& ++ order != Ordering::Release &*& order != Ordering::AcqRel; ++@*/ ++/*@ ++ on_unwind_ens (order == Ordering::Release || order == Ordering::AcqRel) &*& thread_token(currentThread); ++@*/{ + // SAFETY: the caller must uphold the safety contract for `atomic_load`. ++ //@ open ordering_access(dst, _, f, af, inv_); + unsafe { + match order { + Relaxed => intrinsics::atomic_load::(dst), +@@ -4613,8 +4782,13 @@ + new: T, + success: Ordering, + failure: Ordering, +-) -> Result { ++) -> Result ++//@ req ro_scalar_type(typeid(T)) == true &*& ordering_access(dst, failure != Ordering::Release && failure != Ordering::AcqRel, ?f, ?af, ?inv_) &*& (if failure == Ordering::Release || failure == Ordering::AcqRel { thread_token(currentThread) } else { if af == 1 { inv_(new) == true || inv_(old) == false } else { inv_(old) == false } }); ++//@ ens [f]std::intrinsics::atomic_points_to::(dst, af, inv_) &*& 0 < af &*& af <= 1 &*& failure != Ordering::Release &*& failure != Ordering::AcqRel &*& result::Result_own::(currentThread, result) &*& match result { Result::Ok(v) => af == 1 &*& inv_(v) == true &*& v == old, Result::Err(v) => inv_(v) == true &*& v != old }; ++//@ on_unwind_ens (failure == Ordering::Release || failure == Ordering::AcqRel) &*& thread_token(currentThread); ++{ + // SAFETY: the caller must uphold the safety contract for `atomic_compare_exchange`. ++ //@ open ordering_access(dst, _, f, af, inv_); + let (val, ok) = unsafe { + match (success, failure) { + (Relaxed, Relaxed) => { +@@ -4666,6 +4840,11 @@ + (_, Release) => panic!("there is no such thing as a release failure ordering"), + } + }; ++ /*@ if ok { ++ close result::Result_own::(currentThread, result::Result::Ok(val)); ++ } else { ++ close result::Result_own::(currentThread, result::Result::Err(val)); ++ } @*/ + if ok { Ok(val) } else { Err(val) } + } + +@@ -4686,8 +4865,13 @@ + new: T, + success: Ordering, + failure: Ordering, +-) -> Result { ++) -> Result ++//@ req ro_scalar_type(typeid(T)) == true &*& ordering_access(dst, failure != Ordering::Release && failure != Ordering::AcqRel, ?f, ?af, ?inv_) &*& (if failure == Ordering::Release || failure == Ordering::AcqRel { thread_token(currentThread) } else { if af == 1 { inv_(new) == true || inv_(old) == false } else { inv_(old) == false } }); ++//@ ens [f]std::intrinsics::atomic_points_to::(dst, af, inv_) &*& 0 < af &*& af <= 1 &*& failure != Ordering::Release &*& failure != Ordering::AcqRel &*& result::Result_own::(currentThread, result) &*& match result { Result::Ok(v) => af == 1 &*& inv_(v) == true &*& v == old, Result::Err(v) => inv_(v) == true }; ++//@ on_unwind_ens (failure == Ordering::Release || failure == Ordering::AcqRel) &*& thread_token(currentThread); ++{ + // SAFETY: the caller must uphold the safety contract for `atomic_compare_exchange_weak`. ++ //@ open ordering_access(dst, _, f, af, inv_); + let (val, ok) = unsafe { + match (success, failure) { + (Relaxed, Relaxed) => { +@@ -4739,6 +4923,11 @@ + (_, Release) => panic!("there is no such thing as a release failure ordering"), + } + }; ++ /*@ if ok { ++ close result::Result_own::(currentThread, result::Result::Ok(val)); ++ } else { ++ close result::Result_own::(currentThread, result::Result::Err(val)); ++ } @*/ + if ok { Ok(val) } else { Err(val) } + } + +--- a/intrinsics/mod.rs ++++ b/intrinsics/mod.rs +@@ -160,7 +160,19 @@ + dst: *mut T, + old: T, + src: T, +-) -> (T, bool); ++) -> (T, bool)/*@ ++ req sync::atomic::ro_scalar_type(typeid(T)) == true &*& ++ 0 <= int_of_const(typeid(ORD_SUCC)) &*& int_of_const(typeid(ORD_SUCC)) <= 4 &*& ++ (int_of_const(typeid(ORD_FAIL)) == 0 || int_of_const(typeid(ORD_FAIL)) == 2 || int_of_const(typeid(ORD_FAIL)) == 4) &*& ++ [?f]std::intrinsics::atomic_points_to::(dst, ?af, ?inv_) &*& 0 < af &*& af <= 1 &*& (if af == 1 { inv_(src) == true || inv_(old) == false } else { inv_(old) == false }); ++@*/ ++/*@ ++ ens [f]std::intrinsics::atomic_points_to::(dst, af, inv_) &*& 0 < af &*& af <= 1 &*& inv_(result.0) == true &*& ++ .own(currentThread, result.0) &*& result.1 == (result.0 == old); ++@*/ ++/*@ ++ on_unwind_ens false; ++@*/; + + /// Stores a value if the current value is the same as the `old` value, + /// with the returned `T` being the previous value and the returned `bool` being +@@ -194,7 +206,19 @@ + _dst: *mut T, + _old: T, + _src: T, +-) -> (T, bool); ++) -> (T, bool)/*@ ++ req sync::atomic::ro_scalar_type(typeid(T)) == true &*& ++ 0 <= int_of_const(typeid(ORD_SUCC)) &*& int_of_const(typeid(ORD_SUCC)) <= 4 &*& ++ (int_of_const(typeid(ORD_FAIL)) == 0 || int_of_const(typeid(ORD_FAIL)) == 2 || int_of_const(typeid(ORD_FAIL)) == 4) &*& ++ [?f]std::intrinsics::atomic_points_to::(_dst, ?af, ?inv_) &*& 0 < af &*& af <= 1 &*& (if af == 1 { inv_(_src) == true || inv_(_old) == false } else { inv_(_old) == false }); ++@*/ ++/*@ ++ ens [f]std::intrinsics::atomic_points_to::(_dst, af, inv_) &*& 0 < af &*& af <= 1 &*& inv_(result.0) == true &*& ++ .own(currentThread, result.0) &*& (result.1 == false || result.0 == _old); ++@*/ ++/*@ ++ on_unwind_ens false; ++@*/; + + /// Loads the current value of the pointer. + /// `T` must be an integer or pointer type. +@@ -217,7 +241,18 @@ + #[rustc_nounwind] + pub const unsafe fn atomic_load( + src: *const T, +-) -> T; ++) -> T/*@ ++ req sync::atomic::ro_scalar_type(typeid(T)) == true &*& ++ (int_of_const(typeid(ORD)) == 0 || int_of_const(typeid(ORD)) == 2 || int_of_const(typeid(ORD)) == 4) &*& ++ int_of_const(typeid(VOLATILE)) == 0 &*& ++ [?f]std::intrinsics::atomic_points_to::(src, ?af, ?inv_) &*& 0 < af &*& af <= 1; ++@*/ ++/*@ ++ ens [f]std::intrinsics::atomic_points_to::(src, af, inv_) &*& 0 < af &*& af <= 1 &*& inv_(result) == true; ++@*/ ++/*@ ++ on_unwind_ens false; ++@*/; + + /// Stores the value at the specified memory location. + /// `T` must be an integer or pointer type. +@@ -241,7 +276,18 @@ + pub const unsafe fn atomic_store( + dst: *mut T, + val: T, +-); ++)/*@ ++ req sync::atomic::ro_scalar_type(typeid(T)) == true &*& ++ (int_of_const(typeid(ORD)) == 0 || int_of_const(typeid(ORD)) == 1 || int_of_const(typeid(ORD)) == 4) &*& ++ int_of_const(typeid(VOLATILE)) == 0 &*& ++ [?f]std::intrinsics::atomic_points_to::(dst, 1, ?inv_) &*& inv_(val) == true; ++@*/ ++/*@ ++ ens [f]std::intrinsics::atomic_points_to::(dst, 1, inv_); ++@*/ ++/*@ ++ on_unwind_ens false; ++@*/; + + /// Stores the value at the specified memory location, returning the old value. + /// `T` must be an integer or pointer type. diff --git a/verifast-proofs/core/sync/atomic.rs/specs/rmw.diff b/verifast-proofs/core/sync/atomic.rs/specs/rmw.diff new file mode 100644 index 0000000000000..aa6a5b36847ad --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/specs/rmw.diff @@ -0,0 +1,759 @@ +--- a/sync/atomic.rs ++++ b/sync/atomic.rs +@@ -318,9 +318,142 @@ + p as *Atomic + } + fix valid_bool_byte(v: u8) -> bool { v == 0 || v == 1 } ++// This association has one concrete interpretation, used behind exact u8 ++// type checks. It relates the generic Rust argument to its actual byte. ++type_pred_decl .rmw_byte_repr : pred(Self; u8); ++pred byte_repr(value: u8; byte: u8) = byte == value; ++type_pred_def .rmw_byte_repr = byte_repr; ++ ++inductive byte_operation = byte_and | byte_or | byte_xor | byte_nand; ++ ++// Exact byte results on the two initialized bool representations only. ++// In particular, a raw u8 NAND also flips the high seven bits. ++fix bool_byte_after(op: byte_operation, old: u8, arg: u8) -> u8 { ++ match op { ++ byte_and => if old == 1 && arg == 1 { 1 } else { 0 }, ++ byte_or => if old == 1 || arg == 1 { 1 } else { 0 }, ++ byte_xor => if old != arg { 1 } else { 0 }, ++ byte_nand => if old == 1 && arg == 1 { 254 } else { 255 } ++ } ++} ++ ++fix bool_byte_closed(op: byte_operation, arg: u8) -> bool { ++ valid_bool_byte(arg) && valid_bool_byte(bool_byte_after(op, 0, arg)) && valid_bool_byte(bool_byte_after(op, 1, arg)) ++} ++ ++lem bool_byte_transition(op: byte_operation, old: u8, arg: u8) ++ req valid_bool_byte(old) == true &*& bool_byte_closed(op, arg) == true; ++ ens valid_bool_byte(bool_byte_after(op, old, arg)) == true; ++{ if old == 0 {} else { assert old == 1; } } ++ ++lem bool_bitwise_domain(arg: u8) ++ req valid_bool_byte(arg) == true; ++ ens bool_byte_closed(byte_and, arg) == true &*& bool_byte_closed(byte_or, arg) == true &*& ++ bool_byte_closed(byte_xor, arg) == true &*& bool_byte_closed(byte_nand, arg) == false; ++{ if arg == 0 {} else { assert arg == 1; } } ++ ++pred bitwise_access(slot: *T, op: byte_operation, arg: U, f: real, boolean: bool) = ++ if boolean { ++ typeid(T) == typeid(u8) &*& typeid(U) == typeid(u8) &*& ++ [_](.rmw_byte_repr)(arg, ?byte) &*& bool_byte_closed(op, byte) == true &*& ++ [f]std::intrinsics::atomic_points_to::(slot as *u8, 1, valid_bool_byte) ++ } else { ++ rmw_integer_type(typeid(T)) == true &*& typeid(T) == typeid(U) &*& ++ [f]std::intrinsics::atomic_points_to::(slot, 1, accepts_unsigned) ++ }; ++ ++pred bitwise_previous(boolean: bool, old: T) = ++ if boolean { [_](.rmw_byte_repr)(old, ?byte) &*& valid_bool_byte(byte) == true } else { true }; + pred_ctor bool_slot_content(p: *_)(;) = + std::intrinsics::atomic_points_to::(p as *u8, 1, valid_bool_byte); + type_pred_def .atomic_content = bool_slot_content; ++fix encode_bool(value: bool) -> u8 { if value { 1 } else { 0 } } ++ ++fix bool_rmw_slot(view: *Atomic) -> *u8 { ref_origin(view) as *u8 } ++ ++lem open_bool_rmw_slot(view: *Atomic, k: lifetime_t, t: thread_id_t, q: real) ++ nonghost_callers_only ++ req [q]lifetime_token(k) &*& [_]Atomic_share::(k, t, view); ++ ens [_]frac_borrow(k, ref_initialized_(view)) &*& [?f]std::intrinsics::atomic_points_to::(bool_rmw_slot(view), 1, valid_bool_byte) &*& ++ close_frac_borrow_token(f, bool_slot_content(ref_origin(view)), q, k); ++{ ++ open Atomic_share::(k, t, view); ++ let f = open_frac_borrow(k, bool_slot_content(ref_origin(view)), q); ++ open [f]bool_slot_content(ref_origin(view))(); ++} ++ ++lem close_bool_rmw_slot(view: *Atomic) ++ nonghost_callers_only ++ req [?f]std::intrinsics::atomic_points_to::(bool_rmw_slot(view), 1, valid_bool_byte) &*& ++ close_frac_borrow_token(f, bool_slot_content(ref_origin(view)), ?q, ?k); ++ ens [q]lifetime_token(k); ++{ ++ close [f]bool_slot_content(ref_origin(view))(); ++ close_frac_borrow(f, bool_slot_content(ref_origin(view))); ++} ++ ++// The return hook covers both paths. A forwarded call already returns its ++// lifetime fraction. The direct exchange returns the open atomic resource. ++pred bool_swap_branch(view: *Atomic, direct: bool) = true; ++lem finish_bool_swap(view: *Atomic, k: lifetime_t, q: real) ++ nonghost_callers_only ++ req bool_swap_branch(view, ?direct) &*& (if direct { ++ [?f]std::intrinsics::atomic_points_to::(bool_rmw_slot(view), 1, valid_bool_byte) &*& ++ close_frac_borrow_token(f, bool_slot_content(ref_origin(view)), q, k) ++ } else { [q]lifetime_token(k) }); ++ ens [q]lifetime_token(k); ++{ ++ open bool_swap_branch(view, direct); ++ if direct { close_bool_rmw_slot(view); } ++} ++ ++lem begin_bool_bitwise(view: *Atomic, k: lifetime_t, t: thread_id_t, q: real, op: byte_operation, arg: u8) ++ nonghost_callers_only ++ req [q]lifetime_token(k) &*& [_]Atomic_share::(k, t, view) &*& valid_bool_byte(arg) == true &*& op != byte_nand; ++ ens [_]frac_borrow(k, ref_initialized_(view)) &*& bitwise_access::(bool_rmw_slot(view), op, arg, ?f, true) &*& ++ close_frac_borrow_token(f, bool_slot_content(ref_origin(view)), q, k); ++{ ++ open_bool_rmw_slot(view, k, t, q); ++ assert [?f]std::intrinsics::atomic_points_to::(bool_rmw_slot(view), 1, valid_bool_byte); ++ bool_bitwise_domain(arg); ++ match op { byte_and => {} byte_or => {} byte_xor => {} byte_nand => {} } ++ close byte_repr(arg, arg); ++ leak byte_repr(arg, arg); ++ close bitwise_access::(bool_rmw_slot(view), op, arg, f, true); ++} ++ ++lem end_bool_bitwise(view: *Atomic, op: byte_operation, arg: u8) ++ nonghost_callers_only ++ req bitwise_access::(bool_rmw_slot(view), op, arg, ?f, true) &*& ++ close_frac_borrow_token(f, bool_slot_content(ref_origin(view)), ?q, ?k); ++ ens [q]lifetime_token(k); ++{ ++ open bitwise_access::(bool_rmw_slot(view), op, arg, f, true); ++ close_bool_rmw_slot(view); ++} ++ ++lem begin_int_bitwise(view: *Atomic, k: lifetime_t, t: thread_id_t, q: real, op: byte_operation, arg: T) ++ nonghost_callers_only ++ req [q]lifetime_token(k) &*& [_]Atomic_share::(k, t, view) &*& rmw_integer_type(typeid(T)) == true &*& ++ .atomic_content(ref_origin(view)) == unsigned_content::(rmw_slot(view)); ++ ens [_]frac_borrow(k, ref_initialized_(view)) &*& bitwise_access::(rmw_slot(view), op, arg, ?f, false) &*& ++ close_frac_borrow_token(f, unsigned_content::(rmw_slot(view)), q, k); ++{ ++ open_rmw_slot(view, rmw_slot(view), k, t, q); ++ assert [?f]std::intrinsics::atomic_points_to::(rmw_slot(view), 1, accepts_unsigned); ++ close bitwise_access::(rmw_slot(view), op, arg, f, false); ++} ++ ++lem end_int_bitwise(view: *Atomic, op: byte_operation, arg: T) ++ nonghost_callers_only ++ req bitwise_access::(rmw_slot(view), op, arg, ?f, false) &*& ++ close_frac_borrow_token(f, unsigned_content::(rmw_slot(view)), ?q, ?k); ++ ens [q]lifetime_token(k); ++{ ++ open bitwise_access::(rmw_slot(view), op, arg, f, false); ++ close_rmw_slot(rmw_slot(view)); ++} ++ + lem finish_unsigned_ref(k: lifetime_t, t: thread_id_t, p: *Atomic) + nonghost_callers_only + req [1/2]ref_initialized(p) &*& [_]frac_borrow(k, .atomic_content(ref_origin(p))); +@@ -1103,11 +1236,25 @@ + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] +- pub const fn swap(&self, val: bool, order: Ordering) -> bool { ++ pub const fn swap(&self, val: bool, order: Ordering) -> bool ++ //@ req [_]Atomic_share::(?k, currentThread, self) &*& [?q]lifetime_token(k) &*& Ordering_own(currentThread, order); ++ //@ ens [q]lifetime_token(k); ++ //@ on_unwind_ens false; ++ { ++ //@ vf_on_normal_return(finish_bool_swap(self, k, q/2)); + if EMULATE_ATOMIC_BOOL { ++ //@ close bool_swap_branch(self, false); ++ //@ open Atomic_share::(k, currentThread, self); ++ //@ close exists(false); ++ //@ close Atomic_share::(k, currentThread, self); ++ //@ leak Atomic_share::(k, currentThread, self); + if val { self.fetch_or(true, order) } else { self.fetch_and(false, order) } + } else { + // SAFETY: data races are prevented by atomic intrinsics. ++ //@ open Ordering_own(currentThread, order); ++ //@ open_bool_rmw_slot(self, k, currentThread, q/2); ++ //@ close bool_swap_branch(self, true); ++ //@ if val {} else {} + unsafe { atomic_swap(self.v.get().cast::(), val as u8, order) != 0 } + } + } +@@ -1408,7 +1555,15 @@ + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] +- pub const fn fetch_and(&self, val: bool, order: Ordering) -> bool { ++ pub const fn fetch_and(&self, val: bool, order: Ordering) -> bool ++ //@ req [_]Atomic_share::(?k, currentThread, self) &*& [?q]lifetime_token(k) &*& Ordering_own(currentThread, order); ++ //@ ens [q]lifetime_token(k); ++ //@ on_unwind_ens false; ++ { ++ //@ open Ordering_own(currentThread, order); ++ //@ if val {} else {} ++ //@ begin_bool_bitwise(self, k, currentThread, q/2, byte_and, encode_bool(val)); ++ //@ vf_on_normal_return(end_bool_bitwise(self, byte_and, encode_bool(val))); + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_and(self.v.get().cast::(), val as u8, order) != 0 } + } +@@ -1453,7 +1608,15 @@ + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] +- pub const fn fetch_nand(&self, val: bool, order: Ordering) -> bool { ++ pub const fn fetch_nand(&self, val: bool, order: Ordering) -> bool ++ //@ req [_]Atomic_share::(?k, currentThread, self) &*& [?q]lifetime_token(k) &*& Ordering_own(currentThread, order); ++ //@ ens [q]lifetime_token(k); ++ //@ on_unwind_ens false; ++ { ++ //@ open Atomic_share::(k, currentThread, self); ++ //@ close exists(false); ++ //@ close Atomic_share::(k, currentThread, self); ++ //@ leak Atomic_share::(k, currentThread, self); + // We can't use atomic_nand here because it can result in a bool with + // an invalid value. This happens because the atomic operation is done + // with an 8-bit integer internally, which would set the upper 7 bits. +@@ -1508,7 +1671,15 @@ + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] +- pub const fn fetch_or(&self, val: bool, order: Ordering) -> bool { ++ pub const fn fetch_or(&self, val: bool, order: Ordering) -> bool ++ //@ req [_]Atomic_share::(?k, currentThread, self) &*& [?q]lifetime_token(k) &*& Ordering_own(currentThread, order); ++ //@ ens [q]lifetime_token(k); ++ //@ on_unwind_ens false; ++ { ++ //@ open Ordering_own(currentThread, order); ++ //@ if val {} else {} ++ //@ begin_bool_bitwise(self, k, currentThread, q/2, byte_or, encode_bool(val)); ++ //@ vf_on_normal_return(end_bool_bitwise(self, byte_or, encode_bool(val))); + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_or(self.v.get().cast::(), val as u8, order) != 0 } + } +@@ -1552,7 +1723,15 @@ + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] +- pub const fn fetch_xor(&self, val: bool, order: Ordering) -> bool { ++ pub const fn fetch_xor(&self, val: bool, order: Ordering) -> bool ++ //@ req [_]Atomic_share::(?k, currentThread, self) &*& [?q]lifetime_token(k) &*& Ordering_own(currentThread, order); ++ //@ ens [q]lifetime_token(k); ++ //@ on_unwind_ens false; ++ { ++ //@ open Ordering_own(currentThread, order); ++ //@ if val {} else {} ++ //@ begin_bool_bitwise(self, k, currentThread, q/2, byte_xor, encode_bool(val)); ++ //@ vf_on_normal_return(end_bool_bitwise(self, byte_xor, encode_bool(val))); + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_xor(self.v.get().cast::(), val as u8, order) != 0 } + } +@@ -1592,7 +1771,15 @@ + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] +- pub const fn fetch_not(&self, order: Ordering) -> bool { ++ pub const fn fetch_not(&self, order: Ordering) -> bool ++ //@ req [_]Atomic_share::(?k, currentThread, self) &*& [?q]lifetime_token(k) &*& Ordering_own(currentThread, order); ++ //@ ens [q]lifetime_token(k); ++ //@ on_unwind_ens false; ++ { ++ //@ open Atomic_share::(k, currentThread, self); ++ //@ close exists(false); ++ //@ close Atomic_share::(k, currentThread, self); ++ //@ leak Atomic_share::(k, currentThread, self); + self.fetch_xor(true, order) + } + +@@ -3557,7 +3744,15 @@ + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] +- pub const fn swap(&self, val: $int_type, order: Ordering) -> $int_type { ++ pub const fn swap(&self, val: $int_type, order: Ordering) -> $int_type ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share(k, currentThread, self) &*& Ordering_own(currentThread, order); ++ //@ ens [q]lifetime_token(k); ++ //@ on_unwind_ens false; ++ { ++ //@ open Ordering_own(currentThread, order); ++ //@ let p = rmw_slot(self); ++ //@ open_rmw_slot(self, p, k, currentThread, q/2); ++ //@ vf_on_normal_return(close_rmw_slot(rmw_slot(self))); + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_swap(self.as_ptr(), val, order) } + } +@@ -3806,7 +4001,15 @@ + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] +- pub const fn fetch_add(&self, val: $int_type, order: Ordering) -> $int_type { ++ pub const fn fetch_add(&self, val: $int_type, order: Ordering) -> $int_type ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share(k, currentThread, self) &*& Ordering_own(currentThread, order); ++ //@ ens [q]lifetime_token(k); ++ //@ on_unwind_ens false; ++ { ++ //@ open Ordering_own(currentThread, order); ++ //@ let p = rmw_slot(self); ++ //@ open_rmw_slot(self, p, k, currentThread, q/2); ++ //@ vf_on_normal_return(close_rmw_slot(rmw_slot(self))); + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_add(self.as_ptr(), val, order) } + } +@@ -3840,7 +4043,15 @@ + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] +- pub const fn fetch_sub(&self, val: $int_type, order: Ordering) -> $int_type { ++ pub const fn fetch_sub(&self, val: $int_type, order: Ordering) -> $int_type ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share(k, currentThread, self) &*& Ordering_own(currentThread, order); ++ //@ ens [q]lifetime_token(k); ++ //@ on_unwind_ens false; ++ { ++ //@ open Ordering_own(currentThread, order); ++ //@ let p = rmw_slot(self); ++ //@ open_rmw_slot(self, p, k, currentThread, q/2); ++ //@ vf_on_normal_return(close_rmw_slot(rmw_slot(self))); + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_sub(self.as_ptr(), val, order) } + } +@@ -3877,7 +4088,14 @@ + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] +- pub const fn fetch_and(&self, val: $int_type, order: Ordering) -> $int_type { ++ pub const fn fetch_and(&self, val: $int_type, order: Ordering) -> $int_type ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share(k, currentThread, self) &*& Ordering_own(currentThread, order); ++ //@ ens [q]lifetime_token(k); ++ //@ on_unwind_ens false; ++ { ++ //@ open Ordering_own(currentThread, order); ++ //@ begin_int_bitwise(self, k, currentThread, q/2, byte_and, val); ++ //@ vf_on_normal_return(end_int_bitwise(self, byte_and, val)); + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_and(self.as_ptr(), val, order) } + } +@@ -3914,7 +4132,14 @@ + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] +- pub const fn fetch_nand(&self, val: $int_type, order: Ordering) -> $int_type { ++ pub const fn fetch_nand(&self, val: $int_type, order: Ordering) -> $int_type ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share(k, currentThread, self) &*& Ordering_own(currentThread, order); ++ //@ ens [q]lifetime_token(k); ++ //@ on_unwind_ens false; ++ { ++ //@ open Ordering_own(currentThread, order); ++ //@ begin_int_bitwise(self, k, currentThread, q/2, byte_nand, val); ++ //@ vf_on_normal_return(end_int_bitwise(self, byte_nand, val)); + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_nand(self.as_ptr(), val, order) } + } +@@ -3951,7 +4176,14 @@ + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] +- pub const fn fetch_or(&self, val: $int_type, order: Ordering) -> $int_type { ++ pub const fn fetch_or(&self, val: $int_type, order: Ordering) -> $int_type ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share(k, currentThread, self) &*& Ordering_own(currentThread, order); ++ //@ ens [q]lifetime_token(k); ++ //@ on_unwind_ens false; ++ { ++ //@ open Ordering_own(currentThread, order); ++ //@ begin_int_bitwise(self, k, currentThread, q/2, byte_or, val); ++ //@ vf_on_normal_return(end_int_bitwise(self, byte_or, val)); + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_or(self.as_ptr(), val, order) } + } +@@ -3988,7 +4220,14 @@ + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] +- pub const fn fetch_xor(&self, val: $int_type, order: Ordering) -> $int_type { ++ pub const fn fetch_xor(&self, val: $int_type, order: Ordering) -> $int_type ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share(k, currentThread, self) &*& Ordering_own(currentThread, order); ++ //@ ens [q]lifetime_token(k); ++ //@ on_unwind_ens false; ++ { ++ //@ open Ordering_own(currentThread, order); ++ //@ begin_int_bitwise(self, k, currentThread, q/2, byte_xor, val); ++ //@ vf_on_normal_return(end_int_bitwise(self, byte_xor, val)); + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_xor(self.as_ptr(), val, order) } + } +@@ -4193,7 +4432,15 @@ + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] +- pub const fn fetch_max(&self, val: $int_type, order: Ordering) -> $int_type { ++ pub const fn fetch_max(&self, val: $int_type, order: Ordering) -> $int_type ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share(k, currentThread, self) &*& Ordering_own(currentThread, order); ++ //@ ens [q]lifetime_token(k); ++ //@ on_unwind_ens false; ++ { ++ //@ open Ordering_own(currentThread, order); ++ //@ let p = rmw_slot(self); ++ //@ open_rmw_slot(self, p, k, currentThread, q/2); ++ //@ vf_on_normal_return(close_rmw_slot(rmw_slot(self))); + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { $max_fn(self.as_ptr(), val, order) } + } +@@ -4244,7 +4491,15 @@ + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] +- pub const fn fetch_min(&self, val: $int_type, order: Ordering) -> $int_type { ++ pub const fn fetch_min(&self, val: $int_type, order: Ordering) -> $int_type ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share(k, currentThread, self) &*& Ordering_own(currentThread, order); ++ //@ ens [q]lifetime_token(k); ++ //@ on_unwind_ens false; ++ { ++ //@ open Ordering_own(currentThread, order); ++ //@ let p = rmw_slot(self); ++ //@ open_rmw_slot(self, p, k, currentThread, q/2); ++ //@ vf_on_normal_return(close_rmw_slot(rmw_slot(self))); + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { $min_fn(self.as_ptr(), val, order) } + } +@@ -4624,7 +4879,11 @@ + #[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) + })] +-const unsafe fn atomic_swap(dst: *mut T, val: T, order: Ordering) -> T { ++const unsafe fn atomic_swap(dst: *mut T, val: T, order: Ordering) -> T ++//@ req rmw_integer_type(typeid(T)) == true &*& [?f]std::intrinsics::atomic_points_to::(dst, 1, ?inv_) &*& inv_(val) == true; ++//@ ens [f]std::intrinsics::atomic_points_to::(dst, 1, inv_) &*& inv_(result) == true; ++//@ on_unwind_ens false; ++{ + // SAFETY: the caller must uphold the safety contract for `atomic_swap`. + unsafe { + match order { +@@ -4648,7 +4907,11 @@ + #[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) + })] +-const unsafe fn atomic_add(dst: *mut T, val: U, order: Ordering) -> T { ++const unsafe fn atomic_add(dst: *mut T, val: U, order: Ordering) -> T ++//@ req rmw_integer_type(typeid(T)) == true &*& typeid(T) == typeid(U) &*& [?f]std::intrinsics::atomic_points_to::(dst, 1, accepts_unsigned); ++//@ ens [f]std::intrinsics::atomic_points_to::(dst, 1, accepts_unsigned); ++//@ on_unwind_ens false; ++{ + // SAFETY: the caller must uphold the safety contract for `atomic_add`. + unsafe { + match order { +@@ -4672,7 +4935,11 @@ + #[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) + })] +-const unsafe fn atomic_sub(dst: *mut T, val: U, order: Ordering) -> T { ++const unsafe fn atomic_sub(dst: *mut T, val: U, order: Ordering) -> T ++//@ req rmw_integer_type(typeid(T)) == true &*& typeid(T) == typeid(U) &*& [?f]std::intrinsics::atomic_points_to::(dst, 1, accepts_unsigned); ++//@ ens [f]std::intrinsics::atomic_points_to::(dst, 1, accepts_unsigned); ++//@ on_unwind_ens false; ++{ + // SAFETY: the caller must uphold the safety contract for `atomic_sub`. + unsafe { + match order { +@@ -4844,7 +5111,11 @@ + #[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) + })] +-const unsafe fn atomic_and(dst: *mut T, val: U, order: Ordering) -> T { ++const unsafe fn atomic_and(dst: *mut T, val: U, order: Ordering) -> T ++//@ req bitwise_access::(dst, byte_and, val, ?f, ?boolean); ++//@ ens bitwise_access::(dst, byte_and, val, f, boolean) &*& [_]bitwise_previous::(boolean, result); ++//@ on_unwind_ens false; ++{ + // SAFETY: the caller must uphold the safety contract for `atomic_and` + unsafe { + match order { +@@ -4867,7 +5138,11 @@ + #[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) + })] +-const unsafe fn atomic_nand(dst: *mut T, val: U, order: Ordering) -> T { ++const unsafe fn atomic_nand(dst: *mut T, val: U, order: Ordering) -> T ++//@ req bitwise_access::(dst, byte_nand, val, ?f, ?boolean); ++//@ ens bitwise_access::(dst, byte_nand, val, f, boolean) &*& [_]bitwise_previous::(boolean, result); ++//@ on_unwind_ens false; ++{ + // SAFETY: the caller must uphold the safety contract for `atomic_nand` + unsafe { + match order { +@@ -4890,7 +5165,11 @@ + #[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) + })] +-const unsafe fn atomic_or(dst: *mut T, val: U, order: Ordering) -> T { ++const unsafe fn atomic_or(dst: *mut T, val: U, order: Ordering) -> T ++//@ req bitwise_access::(dst, byte_or, val, ?f, ?boolean); ++//@ ens bitwise_access::(dst, byte_or, val, f, boolean) &*& [_]bitwise_previous::(boolean, result); ++//@ on_unwind_ens false; ++{ + // SAFETY: the caller must uphold the safety contract for `atomic_or` + unsafe { + match order { +@@ -4913,7 +5192,11 @@ + #[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) + })] +-const unsafe fn atomic_xor(dst: *mut T, val: U, order: Ordering) -> T { ++const unsafe fn atomic_xor(dst: *mut T, val: U, order: Ordering) -> T ++//@ req bitwise_access::(dst, byte_xor, val, ?f, ?boolean); ++//@ ens bitwise_access::(dst, byte_xor, val, f, boolean) &*& [_]bitwise_previous::(boolean, result); ++//@ on_unwind_ens false; ++{ + // SAFETY: the caller must uphold the safety contract for `atomic_xor` + unsafe { + match order { +@@ -4937,7 +5220,11 @@ + #[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) + })] +-const unsafe fn atomic_max(dst: *mut T, val: T, order: Ordering) -> T { ++const unsafe fn atomic_max(dst: *mut T, val: T, order: Ordering) -> T ++//@ req rmw_signed_type(typeid(T)) == true &*& [?f]std::intrinsics::atomic_points_to::(dst, 1, accepts_unsigned); ++//@ ens [f]std::intrinsics::atomic_points_to::(dst, 1, accepts_unsigned); ++//@ on_unwind_ens false; ++{ + // SAFETY: the caller must uphold the safety contract for `atomic_max` + unsafe { + match order { +@@ -4955,7 +5242,11 @@ + #[cfg(target_has_atomic)] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] +-const unsafe fn atomic_min(dst: *mut T, val: T, order: Ordering) -> T { ++const unsafe fn atomic_min(dst: *mut T, val: T, order: Ordering) -> T ++//@ req rmw_signed_type(typeid(T)) == true &*& [?f]std::intrinsics::atomic_points_to::(dst, 1, accepts_unsigned); ++//@ ens [f]std::intrinsics::atomic_points_to::(dst, 1, accepts_unsigned); ++//@ on_unwind_ens false; ++{ + // SAFETY: the caller must uphold the safety contract for `atomic_min` + unsafe { + match order { +@@ -4979,7 +5270,11 @@ + #[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) + })] +-const unsafe fn atomic_umax(dst: *mut T, val: T, order: Ordering) -> T { ++const unsafe fn atomic_umax(dst: *mut T, val: T, order: Ordering) -> T ++//@ req rmw_unsigned_type(typeid(T)) == true &*& [?f]std::intrinsics::atomic_points_to::(dst, 1, accepts_unsigned); ++//@ ens [f]std::intrinsics::atomic_points_to::(dst, 1, accepts_unsigned); ++//@ on_unwind_ens false; ++{ + // SAFETY: the caller must uphold the safety contract for `atomic_umax` + unsafe { + match order { +@@ -5003,7 +5298,11 @@ + #[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) + })] +-const unsafe fn atomic_umin(dst: *mut T, val: T, order: Ordering) -> T { ++const unsafe fn atomic_umin(dst: *mut T, val: T, order: Ordering) -> T ++//@ req rmw_unsigned_type(typeid(T)) == true &*& [?f]std::intrinsics::atomic_points_to::(dst, 1, accepts_unsigned); ++//@ ens [f]std::intrinsics::atomic_points_to::(dst, 1, accepts_unsigned); ++//@ on_unwind_ens false; ++{ + // SAFETY: the caller must uphold the safety contract for `atomic_umin` + unsafe { + match order { +--- a/intrinsics/mod.rs ++++ b/intrinsics/mod.rs +@@ -264,7 +264,16 @@ + /// [`AtomicPtr

::swap`]: AtomicPtr::swap + #[rustc_intrinsic] + #[rustc_nounwind] +-pub const unsafe fn atomic_xchg(dst: *mut T, src: T) -> T; ++pub const unsafe fn atomic_xchg(dst: *mut T, src: T) -> T/*@ ++ req sync::atomic::rmw_integer_type(typeid(T)) == true &*& 0 <= int_of_const(typeid(ORD)) &*& int_of_const(typeid(ORD)) <= 4 &*& ++ [?f]std::intrinsics::atomic_points_to::(dst, 1, ?inv_) &*& inv_(src) == true; ++@*/ ++/*@ ++ ens [f]std::intrinsics::atomic_points_to::(dst, 1, inv_) &*& inv_(result) == true; ++@*/ ++/*@ ++ on_unwind_ens false; ++@*/; + + /// Adds to the current value, returning the previous value. + /// `T` must be an integer or pointer type. +@@ -291,7 +300,17 @@ + pub const unsafe fn atomic_xadd( + dst: *mut T, + src: U, +-) -> T; ++) -> T/*@ ++ req sync::atomic::rmw_integer_type(typeid(T)) == true &*& typeid(T) == typeid(U) &*& ++ 0 <= int_of_const(typeid(ORD)) &*& int_of_const(typeid(ORD)) <= 4 &*& ++ [?f]std::intrinsics::atomic_points_to::(dst, 1, sync::atomic::accepts_unsigned); ++@*/ ++/*@ ++ ens [f]std::intrinsics::atomic_points_to::(dst, 1, sync::atomic::accepts_unsigned); ++@*/ ++/*@ ++ on_unwind_ens false; ++@*/; + + /// Subtract from the current value, returning the previous value. + /// `T` must be an integer or pointer type. +@@ -318,7 +337,17 @@ + pub const unsafe fn atomic_xsub( + dst: *mut T, + src: U, +-) -> T; ++) -> T/*@ ++ req sync::atomic::rmw_integer_type(typeid(T)) == true &*& typeid(T) == typeid(U) &*& ++ 0 <= int_of_const(typeid(ORD)) &*& int_of_const(typeid(ORD)) <= 4 &*& ++ [?f]std::intrinsics::atomic_points_to::(dst, 1, sync::atomic::accepts_unsigned); ++@*/ ++/*@ ++ ens [f]std::intrinsics::atomic_points_to::(dst, 1, sync::atomic::accepts_unsigned); ++@*/ ++/*@ ++ on_unwind_ens false; ++@*/; + + /// Bitwise and with the current value, returning the previous value. + /// `T` must be an integer or pointer type. +@@ -345,7 +374,17 @@ + pub const unsafe fn atomic_and( + dst: *mut T, + src: U, +-) -> T; ++) -> T/*@ ++ req 0 <= int_of_const(typeid(ORD)) &*& int_of_const(typeid(ORD)) <= 4 &*& ++ sync::atomic::bitwise_access::(dst, sync::atomic::byte_and, src, ?f, ?boolean); ++@*/ ++/*@ ++ ens sync::atomic::bitwise_access::(dst, sync::atomic::byte_and, src, f, boolean) &*& ++ [_]sync::atomic::bitwise_previous::(boolean, result); ++@*/ ++/*@ ++ on_unwind_ens false; ++@*/; + + /// Bitwise nand with the current value, returning the previous value. + /// `T` must be an integer or pointer type. +@@ -366,7 +405,17 @@ + pub const unsafe fn atomic_nand( + dst: *mut T, + src: U, +-) -> T; ++) -> T/*@ ++ req 0 <= int_of_const(typeid(ORD)) &*& int_of_const(typeid(ORD)) <= 4 &*& ++ sync::atomic::bitwise_access::(dst, sync::atomic::byte_nand, src, ?f, ?boolean); ++@*/ ++/*@ ++ ens sync::atomic::bitwise_access::(dst, sync::atomic::byte_nand, src, f, boolean) &*& ++ [_]sync::atomic::bitwise_previous::(boolean, result); ++@*/ ++/*@ ++ on_unwind_ens false; ++@*/; + + /// Bitwise or with the current value, returning the previous value. + /// `T` must be an integer or pointer type. +@@ -393,7 +442,17 @@ + pub const unsafe fn atomic_or( + dst: *mut T, + src: U, +-) -> T; ++) -> T/*@ ++ req 0 <= int_of_const(typeid(ORD)) &*& int_of_const(typeid(ORD)) <= 4 &*& ++ sync::atomic::bitwise_access::(dst, sync::atomic::byte_or, src, ?f, ?boolean); ++@*/ ++/*@ ++ ens sync::atomic::bitwise_access::(dst, sync::atomic::byte_or, src, f, boolean) &*& ++ [_]sync::atomic::bitwise_previous::(boolean, result); ++@*/ ++/*@ ++ on_unwind_ens false; ++@*/; + + /// Bitwise xor with the current value, returning the previous value. + /// `T` must be an integer or pointer type. +@@ -420,7 +479,17 @@ + pub const unsafe fn atomic_xor( + dst: *mut T, + src: U, +-) -> T; ++) -> T/*@ ++ req 0 <= int_of_const(typeid(ORD)) &*& int_of_const(typeid(ORD)) <= 4 &*& ++ sync::atomic::bitwise_access::(dst, sync::atomic::byte_xor, src, ?f, ?boolean); ++@*/ ++/*@ ++ ens sync::atomic::bitwise_access::(dst, sync::atomic::byte_xor, src, f, boolean) &*& ++ [_]sync::atomic::bitwise_previous::(boolean, result); ++@*/ ++/*@ ++ on_unwind_ens false; ++@*/; + + /// Maximum with the current value using a signed comparison. + /// `T` must be a signed integer type. +@@ -437,7 +506,17 @@ + /// [`Atomic::fetch_max`]: AtomicI32::fetch_max + #[rustc_intrinsic] + #[rustc_nounwind] +-pub const unsafe fn atomic_max(dst: *mut T, src: T) -> T; ++pub const unsafe fn atomic_max(dst: *mut T, src: T) -> T/*@ ++ req sync::atomic::rmw_signed_type(typeid(T)) == true &*& ++ 0 <= int_of_const(typeid(ORD)) &*& int_of_const(typeid(ORD)) <= 4 &*& ++ [?f]std::intrinsics::atomic_points_to::(dst, 1, sync::atomic::accepts_unsigned); ++@*/ ++/*@ ++ ens [f]std::intrinsics::atomic_points_to::(dst, 1, sync::atomic::accepts_unsigned); ++@*/ ++/*@ ++ on_unwind_ens false; ++@*/; + + /// Minimum with the current value using a signed comparison. + /// `T` must be a signed integer type. +@@ -454,7 +533,17 @@ + /// [`Atomic::fetch_min`]: AtomicI32::fetch_min + #[rustc_intrinsic] + #[rustc_nounwind] +-pub const unsafe fn atomic_min(dst: *mut T, src: T) -> T; ++pub const unsafe fn atomic_min(dst: *mut T, src: T) -> T/*@ ++ req sync::atomic::rmw_signed_type(typeid(T)) == true &*& ++ 0 <= int_of_const(typeid(ORD)) &*& int_of_const(typeid(ORD)) <= 4 &*& ++ [?f]std::intrinsics::atomic_points_to::(dst, 1, sync::atomic::accepts_unsigned); ++@*/ ++/*@ ++ ens [f]std::intrinsics::atomic_points_to::(dst, 1, sync::atomic::accepts_unsigned); ++@*/ ++/*@ ++ on_unwind_ens false; ++@*/; + + /// Minimum with the current value using an unsigned comparison. + /// `T` must be an unsigned integer type. +@@ -471,7 +560,17 @@ + /// [`Atomic::fetch_min`]: AtomicU32::fetch_min + #[rustc_intrinsic] + #[rustc_nounwind] +-pub const unsafe fn atomic_umin(dst: *mut T, src: T) -> T; ++pub const unsafe fn atomic_umin(dst: *mut T, src: T) -> T/*@ ++ req sync::atomic::rmw_unsigned_type(typeid(T)) == true &*& ++ 0 <= int_of_const(typeid(ORD)) &*& int_of_const(typeid(ORD)) <= 4 &*& ++ [?f]std::intrinsics::atomic_points_to::(dst, 1, sync::atomic::accepts_unsigned); ++@*/ ++/*@ ++ ens [f]std::intrinsics::atomic_points_to::(dst, 1, sync::atomic::accepts_unsigned); ++@*/ ++/*@ ++ on_unwind_ens false; ++@*/; + + /// Maximum with the current value using an unsigned comparison. + /// `T` must be an unsigned integer type. +@@ -488,7 +587,17 @@ + /// [`Atomic::fetch_max`]: AtomicU32::fetch_max + #[rustc_intrinsic] + #[rustc_nounwind] +-pub const unsafe fn atomic_umax(dst: *mut T, src: T) -> T; ++pub const unsafe fn atomic_umax(dst: *mut T, src: T) -> T/*@ ++ req sync::atomic::rmw_unsigned_type(typeid(T)) == true &*& ++ 0 <= int_of_const(typeid(ORD)) &*& int_of_const(typeid(ORD)) <= 4 &*& ++ [?f]std::intrinsics::atomic_points_to::(dst, 1, sync::atomic::accepts_unsigned); ++@*/ ++/*@ ++ ens [f]std::intrinsics::atomic_points_to::(dst, 1, sync::atomic::accepts_unsigned); ++@*/ ++/*@ ++ on_unwind_ens false; ++@*/; + + /// An atomic fence. + /// diff --git a/verifast-proofs/core/sync/atomic.rs/specs/u32.diff b/verifast-proofs/core/sync/atomic.rs/specs/u32.diff new file mode 100644 index 0000000000000..e10bcb2d29cd1 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/specs/u32.diff @@ -0,0 +1,581 @@ +--- a/sync/atomic.rs ++++ b/sync/atomic.rs +@@ -261,8 +261,41 @@ + type_pred_decl .atomic_content : fix(*_, pred(;)); + pred_ctor U32_atomic_content(p: *_)(;) = + std::intrinsics::atomic_points_to::(p as *u32, 1, accepts_word); ++fix valid_word_value(v: Atomic) -> bool { true } ++pred_ctor owned_word_content(p: *_)(;) = ++ std::intrinsics::atomic_points_to::>(p as *Atomic, 1, valid_word_value); ++fix word_content(owned: bool, p: *_) -> pred(;) { if owned { owned_word_content(p) } else { U32_atomic_content(p) } } ++pred word_access(p: *_, owned: bool;) = if owned { owned_word_content(p)() } else { U32_atomic_content(p)() }; ++lem finish_u32_load(p: *u32) ++ nonghost_callers_only ++ req [?f]word_access(p, ?owned) &*& ++ close_frac_borrow_token(f, word_content(owned, p), ?q, ?k); ++ ens [q]lifetime_token(k); ++{ ++ open [f]word_access(p, owned); ++ close_frac_borrow(f, word_content(owned, p)); ++} ++type_pred_def .atomic_content = U32_atomic_content; ++pred cas_returned(p: *T, v: result::Result) = true; ++lem finish_u32_cas(p: *u32, t: thread_id_t) ++ nonghost_callers_only ++ req [?f]word_access(p, ?owned) &*& ++ close_frac_borrow_token(f, word_content(owned, p), ?q, ?k) &*& ++ cas_returned(p, ?value); ++ ens [q]lifetime_token(k) &*& result::Result_own::(t, value); ++{ ++ open cas_returned(p, value); ++ match value { ++ Result::Ok(x) => { close u32_own(t, x); } ++ Result::Err(x) => { close u32_own(t, x); } ++ } ++ close result::Result_own::(t, value); ++ finish_u32_load(p); ++} +-fix rep_fn(owned: bool) -> fix(*_, pred(;)) { .atomic_content } ++fix rep_fn(owned: bool) -> fix(*_, pred(;)) { ++ if owned && typeid(T) == typeid(u32) { owned_word_content } else { .atomic_content } ++} + fix representation(owned: bool, p: *_) -> pred(;) { (rep_fn::(owned))(p) } + fix view_content(p: *T) -> pred(;) { .atomic_content(p) } + pred >.share(k, t, p) = + exists::(?owned) &*& [_]frac_borrow(k, representation::(owned, ref_origin(p))) &*& [_]frac_borrow(k, ref_initialized_(p)); +@@ -377,3 +408,29 @@ + #[repr(C, align(4))] + pub struct Align4(T); ++ /*@ ++ pred >.own(t, v) = .own(t, v.0); ++ ++ lem Align4_drop() ++ req Align4_own::(?t, ?v); ++ ens .own(t, v.0); ++ { open Align4_own::(t, v); } ++ ++ lem Align4_own_mono() ++ req type_interp::() &*& type_interp::() &*& Align4_own::(?t, ?v) &*& is_subtype_of::() == true; ++ ens type_interp::() &*& type_interp::() &*& Align4_own::(t, Align4:: { 0: upcast(v.0) }); ++ { ++ open Align4_own::(t, v); ++ own_mono::(t, v.0); ++ close Align4_own::(t, Align4:: { 0: upcast(v.0) }); ++ } ++ ++ lem Align4_send(t1: thread_id_t) ++ req type_interp::() &*& Align4_own::(?t, ?v) &*& is_Send(typeid(T)) == true; ++ ens type_interp::() &*& Align4_own::(t1, v); ++ { ++ open Align4_own::(t, v); ++ Send::send::(t, t1, v.0); ++ close Align4_own::(t1, v); ++ } ++ @*/ + #[cfg(target_has_atomic_load_store = "64")] +@@ -635,6 +692,11 @@ + #[stable(feature = "rust1", since = "1.0.0")] + SeqCst, + } ++ ++/*@ ++pred ordering_access(p: *T, needed: bool, f: real, owned: bool) = ++ if needed { [f]sync::atomic::word_access(p, owned) } else { true }; ++@*/ + + /// An [`AtomicBool`] initialized to `false`. + #[cfg(target_has_atomic_load_store = "8")] +@@ -3105,9 +3167,22 @@ + pub const unsafe fn from_ptr<'a>(ptr: *mut $int_type) -> &'a $atomic_type + //@ req [?q]lifetime_token('a) &*& [_]frac_borrow('a, view_content(ptr)) &*& ref_origin(ptr) == ptr; + //@ ens [q]lifetime_token('a) &*& [_]Atomic_share('a, currentThread, result) &*& [_]frac_borrow('a, ref_initialized_(result)) &*& ref_origin(result) as *_ == ptr as *_; + //@ on_unwind_ens false; + { + // SAFETY: guaranteed by the caller ++ //@ let view = precreate_ref(ptr as *Atomic); ++ //@ open_ref_init_perm_Atomic::(view); ++ //@ close_ref_initialized_Atomic::(view, 1); ++ //@ leak [1/2]ref_initialized(view); ++ //@ close [1/2]ref_initialized_::>(view)(); ++ //@ close scaledp(1/2, ref_initialized_(view))(); ++ //@ borrow('a, scaledp(1/2, ref_initialized_(view))); ++ //@ full_borrow_into_frac('a, scaledp(1/2, ref_initialized_(view))); ++ //@ frac_borrow_implies_scaled('a, 1/2, ref_initialized_(view)); ++ //@ leak borrow_end_token('a, scaledp(1/2, ref_initialized_(view))); ++ //@ close exists(false); ++ //@ close Atomic_share::('a, currentThread, view); ++ //@ leak Atomic_share::('a, currentThread, view); + unsafe { &*ptr.cast() } + } + +@@ -3305,8 +3380,24 @@ + #[rustc_const_unstable(feature = "const_atomic", issue = "160078")] + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[requires(order == Relaxed || order == Acquire || order == SeqCst)] +- pub const fn load(&self, order: Ordering) -> $int_type { ++ pub const fn load(&self, order: Ordering) -> $int_type ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share(k, currentThread, self) &*& Ordering_own(currentThread, order) &*& (if order == Ordering::Release || order == Ordering::AcqRel { thread_token(currentThread) } else { true }); ++ //@ ens [q]lifetime_token(k) &*& order != Ordering::Release &*& order != Ordering::AcqRel; ++ //@ on_unwind_ens [q]lifetime_token(k) &*& (order == Ordering::Release || order == Ordering::AcqRel) &*& thread_token(currentThread); ++ { + // SAFETY: data races are prevented by atomic intrinsics. ++ //@ let p = ref_origin(self) as *u32; ++ //@ open Ordering_own(currentThread, order); ++ //@ open Atomic_share::(k, currentThread, self); ++ //@ assert [_]exists::(?owned); ++ /*@ if order == Ordering::Release || order == Ordering::AcqRel { ++ close ordering_access::(p, false, 1, owned); ++ } else { ++ let f = open_frac_borrow(k, word_content(owned, p), q/2); ++ close [f]word_access(p, owned); ++ close ordering_access::(p, true, f, owned); ++ } @*/ ++ //@ vf_on_normal_return(finish_u32_load(ref_origin(self) as *u32)); + unsafe { atomic_load::<_, /* VOLATILE */ false>(self.as_ptr(), order) } + } + +@@ -3386,9 +3477,27 @@ + #[lint::should_not_be_called_on_const_items] + #[requires(order == Relaxed || order == Release || order == SeqCst)] + #[cfg_attr(kani, kani::modifies(self))] +- pub const fn store(&self, val: $int_type, order: Ordering) { ++ pub const fn store(&self, val: $int_type, order: Ordering) ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share(k, currentThread, self) &*& Ordering_own(currentThread, order) &*& (if order == Ordering::Acquire || order == Ordering::AcqRel { thread_token(currentThread) } else { true }); ++ //@ ens [q]lifetime_token(k) &*& order != Ordering::Acquire &*& order != Ordering::AcqRel; ++ //@ on_unwind_ens [q]lifetime_token(k) &*& (order == Ordering::Acquire || order == Ordering::AcqRel) &*& thread_token(currentThread); ++ { + // SAFETY: data races are prevented by atomic intrinsics. ++ //@ let p = ref_origin(self) as *u32; ++ //@ open Ordering_own(currentThread, order); ++ //@ open Atomic_share::(k, currentThread, self); ++ //@ assert [_]exists::(?owned); ++ /*@ if order == Ordering::Acquire || order == Ordering::AcqRel { ++ close ordering_access::(p, false, 1, owned); ++ } else { ++ let f = open_frac_borrow(k, word_content(owned, p), q/2); ++ close [f]word_access(p, owned); ++ close ordering_access::(p, true, f, owned); ++ } @*/ + unsafe { atomic_store::<_, /* VOLATILE */ false>(self.as_ptr(), val, order); } ++ //@ assert [?f]word_access(p, owned); ++ //@ open [f]word_access(p, owned); ++ //@ close_frac_borrow(f, word_content(owned, p)); + } + + /// Performs a volatile store into the atomic integer. +@@ -3465,8 +3574,19 @@ + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] +- pub const fn swap(&self, val: $int_type, order: Ordering) -> $int_type { ++ pub const fn swap(&self, val: $int_type, order: Ordering) -> $int_type ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share(k, currentThread, self) &*& Ordering_own(currentThread, order); ++ //@ ens [q]lifetime_token(k); ++ //@ on_unwind_ens false; ++ { + // SAFETY: data races are prevented by atomic intrinsics. ++ //@ let p = ref_origin(self) as *u32; ++ //@ open Ordering_own(currentThread, order); ++ //@ open Atomic_share::(k, currentThread, self); ++ //@ assert [_]exists::(?owned); ++ //@ let f = open_frac_borrow(k, word_content(owned, p), q/2); ++ //@ close [f]word_access(p, owned); ++ //@ vf_on_normal_return(finish_u32_load(ref_origin(self) as *u32)); + unsafe { atomic_swap(self.as_ptr(), val, order) } + } + +@@ -3610,8 +3730,25 @@ + current: $int_type, + new: $int_type, + success: Ordering, +- failure: Ordering) -> Result<$int_type, $int_type> { ++ failure: Ordering) -> Result<$int_type, $int_type> ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share(k, currentThread, self) &*& Ordering_own(currentThread, success) &*& Ordering_own(currentThread, failure) &*& (if failure == Ordering::Release || failure == Ordering::AcqRel { thread_token(currentThread) } else { true }); ++ //@ ens [q]lifetime_token(k) &*& failure != Ordering::Release &*& failure != Ordering::AcqRel &*& result::Result_own::(currentThread, result) &*& match result { Result::Ok(v) => v == current, Result::Err(v) => v != current }; ++ //@ on_unwind_ens [q]lifetime_token(k) &*& (failure == Ordering::Release || failure == Ordering::AcqRel) &*& thread_token(currentThread); ++ { + // SAFETY: data races are prevented by atomic intrinsics. ++ //@ let p = ref_origin(self) as *u32; ++ //@ open Ordering_own(currentThread, success); ++ //@ open Ordering_own(currentThread, failure); ++ //@ open Atomic_share::(k, currentThread, self); ++ //@ assert [_]exists::(?owned); ++ /*@ if failure == Ordering::Release || failure == Ordering::AcqRel { ++ close ordering_access::(p, false, 1, owned); ++ } else { ++ let f = open_frac_borrow(k, word_content(owned, p), q/2); ++ close [f]word_access(p, owned); ++ close ordering_access::(p, true, f, owned); ++ } @*/ ++ //@ vf_on_normal_return(finish_u32_cas(ref_origin(self) as *u32, currentThread)); + unsafe { atomic_compare_exchange(self.as_ptr(), current, new, success, failure) } + } + +@@ -3678,8 +3815,25 @@ + current: $int_type, + new: $int_type, + success: Ordering, +- failure: Ordering) -> Result<$int_type, $int_type> { ++ failure: Ordering) -> Result<$int_type, $int_type> ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share(k, currentThread, self) &*& Ordering_own(currentThread, success) &*& Ordering_own(currentThread, failure) &*& (if failure == Ordering::Release || failure == Ordering::AcqRel { thread_token(currentThread) } else { true }); ++ //@ ens [q]lifetime_token(k) &*& failure != Ordering::Release &*& failure != Ordering::AcqRel &*& result::Result_own::(currentThread, result) &*& match result { Result::Ok(v) => v == current, Result::Err(v) => true }; ++ //@ on_unwind_ens [q]lifetime_token(k) &*& (failure == Ordering::Release || failure == Ordering::AcqRel) &*& thread_token(currentThread); ++ { + // SAFETY: data races are prevented by atomic intrinsics. ++ //@ let p = ref_origin(self) as *u32; ++ //@ open Ordering_own(currentThread, success); ++ //@ open Ordering_own(currentThread, failure); ++ //@ open Atomic_share::(k, currentThread, self); ++ //@ assert [_]exists::(?owned); ++ /*@ if failure == Ordering::Release || failure == Ordering::AcqRel { ++ close ordering_access::(p, false, 1, owned); ++ } else { ++ let f = open_frac_borrow(k, word_content(owned, p), q/2); ++ close [f]word_access(p, owned); ++ close ordering_access::(p, true, f, owned); ++ } @*/ ++ //@ vf_on_normal_return(finish_u32_cas(ref_origin(self) as *u32, currentThread)); + unsafe { + atomic_compare_exchange_weak(self.as_ptr(), current, new, success, failure) + } +@@ -3714,7 +3868,18 @@ + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] +- pub const fn fetch_add(&self, val: $int_type, order: Ordering) -> $int_type { ++ pub const fn fetch_add(&self, val: $int_type, order: Ordering) -> $int_type ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share(k, currentThread, self) &*& Ordering_own(currentThread, order); ++ //@ ens [q]lifetime_token(k); ++ //@ on_unwind_ens false; ++ { ++ //@ let p = ref_origin(self) as *u32; ++ //@ open Ordering_own(currentThread, order); ++ //@ open Atomic_share::(k, currentThread, self); ++ //@ assert [_]exists::(?owned); ++ //@ let f = open_frac_borrow(k, word_content(owned, p), q/2); ++ //@ close [f]word_access(p, owned); ++ //@ vf_on_normal_return(finish_u32_load(ref_origin(self) as *u32)); + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_add(self.as_ptr(), val, order) } + } +@@ -3748,7 +3913,18 @@ + #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces + #[lint::should_not_be_called_on_const_items] + #[cfg_attr(kani, kani::modifies(self))] +- pub const fn fetch_sub(&self, val: $int_type, order: Ordering) -> $int_type { ++ pub const fn fetch_sub(&self, val: $int_type, order: Ordering) -> $int_type ++ //@ req [?q]lifetime_token(?k) &*& [_]Atomic_share(k, currentThread, self) &*& Ordering_own(currentThread, order); ++ //@ ens [q]lifetime_token(k); ++ //@ on_unwind_ens false; ++ { ++ //@ let p = ref_origin(self) as *u32; ++ //@ open Ordering_own(currentThread, order); ++ //@ open Atomic_share::(k, currentThread, self); ++ //@ assert [_]exists::(?owned); ++ //@ let f = open_frac_borrow(k, word_content(owned, p), q/2); ++ //@ close [f]word_access(p, owned); ++ //@ vf_on_normal_return(finish_u32_load(ref_origin(self) as *u32)); + // SAFETY: data races are prevented by atomic intrinsics. + unsafe { atomic_sub(self.as_ptr(), val, order) } + } +@@ -4488,8 +4664,19 @@ + #[requires(order == Relaxed || order == Release || order == SeqCst)] + #[ensures(|_| ub_checks::can_dereference(dst as *const T))] + #[ensures(|_| ub_checks::can_write(dst))] +-const unsafe fn atomic_store(dst: *mut T, val: T, order: Ordering) { ++const unsafe fn atomic_store(dst: *mut T, val: T, order: Ordering) /*@ ++ req typeid(T) == typeid(u32) &*& int_of_const(typeid(VOLATILE)) == 0 &*& ++ ordering_access(dst, order != Ordering::Acquire && order != Ordering::AcqRel, ?f, ?owned) &*& ++ (if order == Ordering::Acquire || order == Ordering::AcqRel { thread_token(currentThread) } else { true }); ++@*/ ++/*@ ++ ens [f]sync::atomic::word_access(dst, owned) &*& order != Ordering::Acquire &*& order != Ordering::AcqRel; ++@*/ ++/*@ ++ on_unwind_ens (order == Ordering::Acquire || order == Ordering::AcqRel) &*& thread_token(currentThread); ++@*/{ + // SAFETY: the caller must uphold the safety contract for `atomic_store`. ++ //@ open ordering_access(dst, _, f, owned); + unsafe { + match order { + Relaxed => intrinsics::atomic_store::(dst, val), +@@ -4509,8 +4696,20 @@ + #[requires(ub_checks::can_dereference(dst))] + #[requires(order == Relaxed || order == Acquire || order == SeqCst)] + #[ensures(|_| ub_checks::can_dereference(dst))] +-const unsafe fn atomic_load(dst: *const T, order: Ordering) -> T { ++const unsafe fn atomic_load(dst: *const T, order: Ordering) -> T /*@ ++ req typeid(T) == typeid(u32) &*& int_of_const(typeid(VOLATILE)) == 0 &*& ++ ordering_access(dst, order != Ordering::Release && order != Ordering::AcqRel, ?f, ?owned) &*& ++ (if order == Ordering::Release || order == Ordering::AcqRel { thread_token(currentThread) } else { true }); ++@*/ ++/*@ ++ ens [f]sync::atomic::word_access(dst, owned) &*& ++ order != Ordering::Release &*& order != Ordering::AcqRel; ++@*/ ++/*@ ++ on_unwind_ens (order == Ordering::Release || order == Ordering::AcqRel) &*& thread_token(currentThread); ++@*/{ + // SAFETY: the caller must uphold the safety contract for `atomic_load`. ++ //@ open ordering_access(dst, _, f, owned); + unsafe { + match order { + Relaxed => intrinsics::atomic_load::(dst), +@@ -4532,7 +4731,11 @@ + #[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) + })] +-const unsafe fn atomic_swap(dst: *mut T, val: T, order: Ordering) -> T { ++const unsafe fn atomic_swap(dst: *mut T, val: T, order: Ordering) -> T ++//@ req typeid(T) == typeid(u32) &*& [?f]sync::atomic::word_access(dst, ?owned); ++//@ ens [f]sync::atomic::word_access(dst, owned); ++//@ on_unwind_ens false; ++{ + // SAFETY: the caller must uphold the safety contract for `atomic_swap`. + unsafe { + match order { +@@ -4556,7 +4759,11 @@ + #[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) + })] +-const unsafe fn atomic_add(dst: *mut T, val: U, order: Ordering) -> T { ++const unsafe fn atomic_add(dst: *mut T, val: U, order: Ordering) -> T ++//@ req typeid(T) == typeid(u32) &*& typeid(U) == typeid(u32) &*& [?f]word_access(dst, ?owned); ++//@ ens [f]word_access(dst, owned); ++//@ on_unwind_ens false; ++{ + // SAFETY: the caller must uphold the safety contract for `atomic_add`. + unsafe { + match order { +@@ -4580,7 +4787,11 @@ + #[ensures(|_| { + ub_checks::can_dereference(dst as *const T) && ub_checks::can_write(dst) + })] +-const unsafe fn atomic_sub(dst: *mut T, val: U, order: Ordering) -> T { ++const unsafe fn atomic_sub(dst: *mut T, val: U, order: Ordering) -> T ++//@ req typeid(T) == typeid(u32) &*& typeid(U) == typeid(u32) &*& [?f]word_access(dst, ?owned); ++//@ ens [f]word_access(dst, owned); ++//@ on_unwind_ens false; ++{ + // SAFETY: the caller must uphold the safety contract for `atomic_sub`. + unsafe { + match order { +@@ -4613,8 +4824,13 @@ + new: T, + success: Ordering, + failure: Ordering, +-) -> Result { ++) -> Result ++//@ req typeid(T) == typeid(u32) &*& ordering_access(dst, failure != Ordering::Release && failure != Ordering::AcqRel, ?f, ?owned) &*& (if failure == Ordering::Release || failure == Ordering::AcqRel { thread_token(currentThread) } else { true }); ++//@ ens [f]sync::atomic::word_access(dst, owned) &*& failure != Ordering::Release &*& failure != Ordering::AcqRel &*& cas_returned(dst, result) &*& match result { Result::Ok(v) => v == old, Result::Err(v) => v != old }; ++//@ on_unwind_ens (failure == Ordering::Release || failure == Ordering::AcqRel) &*& thread_token(currentThread); ++{ + // SAFETY: the caller must uphold the safety contract for `atomic_compare_exchange`. ++ //@ open ordering_access(dst, _, f, owned); + let (val, ok) = unsafe { + match (success, failure) { + (Relaxed, Relaxed) => { +@@ -4666,6 +4882,11 @@ + (_, Release) => panic!("there is no such thing as a release failure ordering"), + } + }; ++ /*@ if ok { ++ close cas_returned(dst, result::Result::Ok(val)); ++ } else { ++ close cas_returned(dst, result::Result::Err(val)); ++ } @*/ + if ok { Ok(val) } else { Err(val) } + } + +@@ -4686,8 +4907,13 @@ + new: T, + success: Ordering, + failure: Ordering, +-) -> Result { ++) -> Result ++//@ req typeid(T) == typeid(u32) &*& ordering_access(dst, failure != Ordering::Release && failure != Ordering::AcqRel, ?f, ?owned) &*& (if failure == Ordering::Release || failure == Ordering::AcqRel { thread_token(currentThread) } else { true }); ++//@ ens [f]sync::atomic::word_access(dst, owned) &*& failure != Ordering::Release &*& failure != Ordering::AcqRel &*& cas_returned(dst, result) &*& match result { Result::Ok(v) => v == old, Result::Err(v) => true }; ++//@ on_unwind_ens (failure == Ordering::Release || failure == Ordering::AcqRel) &*& thread_token(currentThread); ++{ + // SAFETY: the caller must uphold the safety contract for `atomic_compare_exchange_weak`. ++ //@ open ordering_access(dst, _, f, owned); + let (val, ok) = unsafe { + match (success, failure) { + (Relaxed, Relaxed) => { +@@ -4739,6 +4965,11 @@ + (_, Release) => panic!("there is no such thing as a release failure ordering"), + } + }; ++ /*@ if ok { ++ close cas_returned(dst, result::Result::Ok(val)); ++ } else { ++ close cas_returned(dst, result::Result::Err(val)); ++ } @*/ + if ok { Ok(val) } else { Err(val) } + } + +--- a/ptr/mod.rs ++++ b/ptr/mod.rs +@@ -1983,7 +1983,11 @@ + #[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")] + #[rustc_diagnostic_item = "ptr_write"] + #[track_caller] +-pub const unsafe fn write(dst: *mut T, src: T) { ++pub const unsafe fn write(dst: *mut T, src: T) ++//@ req points_to_(dst, ?old); ++//@ ens *dst |-> src; ++//@ on_unwind_ens points_to_(dst, old); ++{ + // Semantically, it would be fine for this to be implemented as a + // `copy_nonoverlapping` and appropriate drop suppression of `src`. + +--- a/ptr/mut_ptr.rs ++++ b/ptr/mut_ptr.rs +@@ -1562,6 +1562,9 @@ + pub const unsafe fn write(self, val: T) + where + T: Sized, ++ //@ req points_to_(self, ?old); ++ //@ ens *self |-> val; ++ //@ on_unwind_ens points_to_(self, old); + { + // SAFETY: the caller must uphold the safety contract for `write`. + unsafe { write(self, val) } +--- a/intrinsics/mod.rs ++++ b/intrinsics/mod.rs +@@ -160,7 +160,18 @@ + dst: *mut T, + old: T, + src: T, +-) -> (T, bool); ++) -> (T, bool)/*@ ++ req typeid(T) == typeid(u32) &*& 0 <= int_of_const(typeid(ORD_SUCC)) &*& int_of_const(typeid(ORD_SUCC)) <= 4 &*& ++ (int_of_const(typeid(ORD_FAIL)) == 0 || int_of_const(typeid(ORD_FAIL)) == 2 || int_of_const(typeid(ORD_FAIL)) == 4) &*& ++ [?f]sync::atomic::word_access(dst, ?owned); ++@*/ ++/*@ ++ ens [f]sync::atomic::word_access(dst, owned) &*& ++ result.1 == (result.0 == old); ++@*/ ++/*@ ++ on_unwind_ens false; ++@*/; + + /// Stores a value if the current value is the same as the `old` value, + /// with the returned `T` being the previous value and the returned `bool` being +@@ -194,7 +205,18 @@ + _dst: *mut T, + _old: T, + _src: T, +-) -> (T, bool); ++) -> (T, bool)/*@ ++ req typeid(T) == typeid(u32) &*& 0 <= int_of_const(typeid(ORD_SUCC)) &*& int_of_const(typeid(ORD_SUCC)) <= 4 &*& ++ (int_of_const(typeid(ORD_FAIL)) == 0 || int_of_const(typeid(ORD_FAIL)) == 2 || int_of_const(typeid(ORD_FAIL)) == 4) &*& ++ [?f]sync::atomic::word_access(_dst, ?owned); ++@*/ ++/*@ ++ ens [f]sync::atomic::word_access(_dst, owned) &*& ++ (result.1 == false || result.0 == _old); ++@*/ ++/*@ ++ on_unwind_ens false; ++@*/; + + /// Loads the current value of the pointer. + /// `T` must be an integer or pointer type. +@@ -217,7 +239,18 @@ + #[rustc_nounwind] + pub const unsafe fn atomic_load( + src: *const T, +-) -> T; ++) -> T/*@ ++ req typeid(T) == typeid(u32) &*& ++ (int_of_const(typeid(ORD)) == 0 || int_of_const(typeid(ORD)) == 2 || int_of_const(typeid(ORD)) == 4) &*& ++ int_of_const(typeid(VOLATILE)) == 0 &*& ++ [?f]sync::atomic::word_access(src, ?owned); ++@*/ ++/*@ ++ ens [f]sync::atomic::word_access(src, owned); ++@*/ ++/*@ ++ on_unwind_ens false; ++@*/; + + /// Stores the value at the specified memory location. + /// `T` must be an integer or pointer type. +@@ -241,7 +274,18 @@ + pub const unsafe fn atomic_store( + dst: *mut T, + val: T, +-); ++)/*@ ++ req typeid(T) == typeid(u32) &*& ++ (int_of_const(typeid(ORD)) == 0 || int_of_const(typeid(ORD)) == 1 || int_of_const(typeid(ORD)) == 4) &*& ++ int_of_const(typeid(VOLATILE)) == 0 &*& ++ [?f]sync::atomic::word_access(dst, ?owned); ++@*/ ++/*@ ++ ens [f]sync::atomic::word_access(dst, owned); ++@*/ ++/*@ ++ on_unwind_ens false; ++@*/; + + /// Stores the value at the specified memory location, returning the old value. + /// `T` must be an integer or pointer type. +@@ -264,7 +308,16 @@ + /// [`AtomicPtr

::swap`]: AtomicPtr::swap + #[rustc_intrinsic] + #[rustc_nounwind] +-pub const unsafe fn atomic_xchg(dst: *mut T, src: T) -> T; ++pub const unsafe fn atomic_xchg(dst: *mut T, src: T) -> T/*@ ++ req typeid(T) == typeid(u32) &*& 0 <= int_of_const(typeid(ORD)) &*& int_of_const(typeid(ORD)) <= 4 &*& ++ [?f]sync::atomic::word_access(dst, ?owned); ++@*/ ++/*@ ++ ens [f]sync::atomic::word_access(dst, owned); ++@*/ ++/*@ ++ on_unwind_ens false; ++@*/; + + /// Adds to the current value, returning the previous value. + /// `T` must be an integer or pointer type. +@@ -291,7 +344,17 @@ + pub const unsafe fn atomic_xadd( + dst: *mut T, + src: U, +-) -> T; ++) -> T/*@ ++ req typeid(T) == typeid(u32) &*& typeid(U) == typeid(u32) &*& ++ 0 <= int_of_const(typeid(ORD)) &*& int_of_const(typeid(ORD)) <= 4 &*& ++ [?f]sync::atomic::word_access(dst, ?owned); ++@*/ ++/*@ ++ ens [f]sync::atomic::word_access(dst, owned); ++@*/ ++/*@ ++ on_unwind_ens false; ++@*/; + + /// Subtract from the current value, returning the previous value. + /// `T` must be an integer or pointer type. +@@ -318,7 +381,17 @@ + pub const unsafe fn atomic_xsub( + dst: *mut T, + src: U, +-) -> T; ++) -> T/*@ ++ req typeid(T) == typeid(u32) &*& typeid(U) == typeid(u32) &*& ++ 0 <= int_of_const(typeid(ORD)) &*& int_of_const(typeid(ORD)) <= 4 &*& ++ [?f]sync::atomic::word_access(dst, ?owned); ++@*/ ++/*@ ++ ens [f]sync::atomic::word_access(dst, owned); ++@*/ ++/*@ ++ on_unwind_ens false; ++@*/; + + /// Bitwise and with the current value, returning the previous value. + /// `T` must be an integer or pointer type. diff --git a/verifast-proofs/core/sync/atomic.rs/specs/widths.diff b/verifast-proofs/core/sync/atomic.rs/specs/widths.diff new file mode 100644 index 0000000000000..64be601316e94 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/specs/widths.diff @@ -0,0 +1,47 @@ +--- a/sync/atomic.rs ++++ b/sync/atomic.rs +@@ -261,8 +261,32 @@ + type_pred_decl .atomic_content : fix(*_, pred(;)); + pred_ctor U32_atomic_content(p: *_)(;) = + std::intrinsics::atomic_points_to::(p as *u32, 1, accepts_word); ++fix accepts_unsigned(v: T) -> bool { true } ++pred_ctor unsigned_content(p: *_)(;) = ++ std::intrinsics::atomic_points_to::(p as *T, 1, accepts_unsigned); ++fix byte_content(p: *_) -> pred(;) { unsigned_content::(p) } ++fix halfword_content(p: *_) -> pred(;) { unsigned_content::(p) } ++type_pred_def .atomic_content = byte_content; ++type_pred_def .atomic_content = halfword_content; ++fix unsigned_view_address(p: *T) -> *Atomic { ++ p as *Atomic ++} ++lem finish_unsigned_ref(k: lifetime_t, t: thread_id_t, p: *Atomic) ++ nonghost_callers_only ++ req [1/2]ref_initialized(p) &*& [_]frac_borrow(k, .atomic_content(ref_origin(p))); ++ ens [_]Atomic_share::(k, t, p) &*& [_]frac_borrow(k, ref_initialized_(p)); ++{ ++ close [1/2]ref_initialized_::>(p)(); ++ close scaledp(1/2, ref_initialized_(p))(); ++ borrow(k, scaledp(1/2, ref_initialized_(p))); ++ full_borrow_into_frac(k, scaledp(1/2, ref_initialized_(p))); ++ frac_borrow_implies_scaled(k, 1/2, ref_initialized_(p)); ++ leak borrow_end_token(k, scaledp(1/2, ref_initialized_(p))); ++ close exists(false); ++ close Atomic_share::(k, t, p); leak Atomic_share::(k, t, p); ++} + fix rep_fn(owned: bool) -> fix(*_, pred(;)) { .atomic_content } + fix representation(owned: bool, p: *_) -> pred(;) { (rep_fn::(owned))(p) } + fix view_content(p: *T) -> pred(;) { .atomic_content(p) } + pred >.share(k, t, p) = + exists::(?owned) &*& [_]frac_borrow(k, representation::(owned, ref_origin(p))) &*& [_]frac_borrow(k, ref_initialized_(p)); +@@ -3108,6 +3132,11 @@ + //@ on_unwind_ens false; + { + // SAFETY: guaranteed by the caller ++ //@ let view = precreate_ref(unsigned_view_address(ptr)); ++ //@ open_ref_init_perm_Atomic(view); ++ //@ close_ref_initialized_Atomic(view, 1); ++ //@ leak [1/2]ref_initialized(view); ++ //@ finish_unsigned_ref('a, currentThread, view); + unsafe { &*ptr.cast() } + } + diff --git a/verifast-proofs/core/sync/atomic.rs/tool-tests/auto_traits.rs b/verifast-proofs/core/sync/atomic.rs/tool-tests/auto_traits.rs new file mode 100644 index 0000000000000..8bce722a839c2 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/tool-tests/auto_traits.rs @@ -0,0 +1,84 @@ +#![no_std] +#![feature(negative_impls)] + +use core::cell::UnsafeCell; + +struct Local; +impl !Send for Local {} + +struct SyncLocal; +impl !Sync for SyncLocal {} + +struct Plain([u8; 1]); +struct Direct(UnsafeCell); +struct Wrapped([UnsafeCell; 1]); +struct Nested(Wrapped); +struct ConstPtr(*const u8); +struct MutPtr(*mut u8); +struct Explicit(UnsafeCell); +unsafe impl Sync for Explicit {} +unsafe impl Send for Explicit {} + +unsafe fn visit() +//@ req true; +//@ ens true; +//@ on_unwind_ens false; +{} + +pub unsafe fn send_client() +//@ req true; +//@ ens is_Sync(typeid(Local)) == true; +//@ on_unwind_ens false; +{ + unsafe { visit::() } +} + +pub unsafe fn sync_client() +//@ req true; +//@ ens is_Send(typeid(SyncLocal)) == true; +//@ on_unwind_ens false; +{ + unsafe { visit::() } +} + +pub unsafe fn field_traits() +//@ req true; +//@ ens true; +//@ on_unwind_ens false; +{ + unsafe { + visit::(); + visit::(); + visit::(); + visit::(); + visit::(); + visit::(); + visit::(); + } + //@ assert is_Sync(typeid(Plain)) == true; + //@ assert is_Send(typeid(Plain)) == true; + //@ assert is_Sync(typeid(Direct)) == false; + //@ assert is_Send(typeid(Direct)) == true; + //@ assert is_Sync(typeid(Wrapped)) == false; + //@ assert is_Send(typeid(Wrapped)) == true; + //@ assert is_Sync(typeid(Nested)) == false; + //@ assert is_Send(typeid(Nested)) == true; + //@ assert is_Sync(typeid(ConstPtr)) == false; + //@ assert is_Send(typeid(ConstPtr)) == false; + //@ assert is_Sync(typeid(MutPtr)) == false; + //@ assert is_Send(typeid(MutPtr)) == false; +} + +#[cfg(test)] +#[test] +fn rust_field_traits() { + fn send() {} + fn sync() {} + sync::(); + send::(); + send::(); + send::(); + send::(); + send::(); + sync::(); +} diff --git a/verifast-proofs/core/sync/atomic.rs/tool-tests/drop.rs b/verifast-proofs/core/sync/atomic.rs/tool-tests/drop.rs new file mode 100644 index 0000000000000..d24d94d6bc04c --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/tool-tests/drop.rs @@ -0,0 +1,33 @@ +#![no_std] + +pub unsafe fn finish(_value: T) +//@ req thread_token(currentThread) &*& .own(currentThread, _value); +//@ ens thread_token(currentThread); +//@ on_unwind_ens thread_token(currentThread); +{ +} + +#[cfg(test)] +mod tests { + extern crate std; + + use core::cell::Cell; + use std::panic::{catch_unwind, AssertUnwindSafe}; + + struct PanickingDrop<'a>(&'a Cell); + + impl Drop for PanickingDrop<'_> { + fn drop(&mut self) { + self.0.set(1); + panic!("destructor"); + } + } + + #[test] + fn destructor_can_unwind_through_finish() { + let count = Cell::new(0); + let result = catch_unwind(AssertUnwindSafe(|| unsafe { super::finish(PanickingDrop(&count)) })); + assert!(result.is_err()); + assert_eq!(count.get(), 1); + } +} diff --git a/verifast-proofs/core/sync/atomic.rs/tool-tests/external_array_client.rs b/verifast-proofs/core/sync/atomic.rs/tool-tests/external_array_client.rs new file mode 100644 index 0000000000000..10e7c51ea8eaf --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/tool-tests/external_array_client.rs @@ -0,0 +1,13 @@ +#![no_std] + +use layout_provider::Bytes; + +pub unsafe fn client(p: *const Bytes) -> *const Bytes +//@ req true; +//@ ens result == p; +//@ on_unwind_ens false; +{ + #[cfg(opaque_result)] + let _factory = layout_provider::opaque_value::<*mut u8>; + p +} diff --git a/verifast-proofs/core/sync/atomic.rs/tool-tests/external_assoc_const.rs b/verifast-proofs/core/sync/atomic.rs/tool-tests/external_assoc_const.rs new file mode 100644 index 0000000000000..332198ea27224 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/tool-tests/external_assoc_const.rs @@ -0,0 +1,14 @@ +#![no_std] +#![feature(gca_min_const_items, rustc_attrs)] +#![allow(incomplete_features, internal_features)] + +// Request a direct associated const in metadata. The generic_const_exprs +// fixture lowers T::N through a separate anonymous constant. +pub trait Kind { + #[rustc_always_gca] + const N: usize; +} +impl Kind for *mut u8 { const N: usize = core::gca!(1); } +impl Kind for *const u8 { const N: usize = core::gca!(4); } + +pub struct Associated([u8; core::gca!(T::N)], core::marker::PhantomData); diff --git a/verifast-proofs/core/sync/atomic.rs/tool-tests/external_layout.rs b/verifast-proofs/core/sync/atomic.rs/tool-tests/external_layout.rs new file mode 100644 index 0000000000000..3c12cff60248e --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/tool-tests/external_layout.rs @@ -0,0 +1,55 @@ +#![no_std] +#![feature(inherent_associated_types, type_alias_impl_trait, generic_const_exprs)] +#![allow(incomplete_features)] + +use core::marker::PhantomData; + +pub trait Kind { + type Storage: Copy + Default; + const N: usize; +} +impl Kind for *mut u8 { + type Storage = u8; + const N: usize = 1; +} +impl Kind for *const u8 { + type Storage = u32; + const N: usize = 4; +} + +pub struct Bridge(PhantomData); +impl Bridge { pub type Repr = T::Storage; } +pub struct Inherent(Bridge::Repr); + +pub type Hidden = impl Copy; +#[define_opaque(Hidden)] +pub fn hide(storage: T::Storage) -> Hidden { storage } +pub struct Opaque(Hidden); +pub fn opaque_value() -> impl Copy { T::Storage::default() } + +pub const fn width() -> usize { core::mem::size_of::() } +pub struct Width([u8; width::()], PhantomData) where [(); width::()]:; +pub struct Associated([u8; T::N], PhantomData) where [(); T::N]:; +pub struct Fixed([u8; width::<*mut u8>()], PhantomData); +pub struct Bytes([u8; N]); + +// A foreign trait with the same relative path as core::ptr::metadata::Pointee. +pub mod ptr { + pub mod metadata { + pub trait Pointee { type Metadata; } + } +} +use ptr::metadata::Pointee; + +pub struct Marker; +impl Pointee for Marker { type Metadata = u8; } + +pub struct Inner(T::Metadata); +pub struct Field(Inner); +pub struct Bound>(T); +pub trait Byte: Pointee {} +impl Byte for Marker {} +pub struct Inherited(T); + +pub struct Argument(T); +pub struct Erased(Argument>); diff --git a/verifast-proofs/core/sync/atomic.rs/tool-tests/external_layout.rsspec b/verifast-proofs/core/sync/atomic.rs/tool-tests/external_layout.rsspec new file mode 100644 index 0000000000000..8d017193c3fa0 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/tool-tests/external_layout.rsspec @@ -0,0 +1,6 @@ +struct Inherent; +struct Opaque; +struct Width; +struct Associated; +struct Fixed; +struct Bytes; diff --git a/verifast-proofs/core/sync/atomic.rs/tool-tests/external_layout_client.rs b/verifast-proofs/core/sync/atomic.rs/tool-tests/external_layout_client.rs new file mode 100644 index 0000000000000..5bd3456e68b27 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/tool-tests/external_layout_client.rs @@ -0,0 +1,69 @@ +#![no_std] +#![cfg_attr( + any(inherent, opaque, width, associated, fixed), + feature(generic_const_exprs) +)] +#![allow(incomplete_features)] + +#[cfg(any(ext_field, ext_bound, ext_inherited, ext_erased))] +mod foreign { + #[cfg(ext_field)] + use layout_provider::Field as Carrier; + #[cfg(ext_bound)] + use layout_provider::Bound as Carrier; + #[cfg(ext_inherited)] + use layout_provider::Inherited as Carrier; + #[cfg(ext_erased)] + use layout_provider::Erased as Carrier; + + pub unsafe fn client(_: *const Carrier) + //@ req true; + //@ ens true; + //@ on_unwind_ens false; + {} +} + +#[cfg(any(inherent, opaque, width, associated, direct, fixed))] +mod layout_case { + #[cfg(inherent)] + use layout_provider::Inherent as Field; + #[cfg(opaque)] + use layout_provider::Opaque as Field; + #[cfg(width)] + use layout_provider::Width as Field; + #[cfg(any(associated, direct))] + use layout_provider::Associated as Field; + #[cfg(fixed)] + use layout_provider::Fixed as Field; + + #[repr(C)] + pub struct Slot { data: F, tail: u8 } + + pub unsafe fn client(a: *const Slot>, b: *const Slot>) -> bool + //@ req a == b &*& pointer_within_limits(&(*a).tail) == true &*& pointer_within_limits(&(*b).tail) == true; + //@ ens result == true; + //@ on_unwind_ens false; + { + unsafe { (&raw const (*a).tail) == (&raw const (*b).tail) } + } + + #[cfg(test)] + const _: () = { + assert!(core::mem::offset_of!(Slot>, tail) == 1); + assert!(core::mem::offset_of!(Slot>, tail) == if cfg!(fixed) { 1 } else { 4 }); + }; + + #[cfg(test)] + #[test] + fn compare_tails() { + let storage = [0u32; 2]; + let base = storage.as_ptr(); + assert_eq!(unsafe { client(base.cast(), base.cast()) }, cfg!(fixed)); + #[cfg(opaque)] + { + fn tail(_: F) -> usize { core::mem::offset_of!(Slot, tail) } + assert_eq!(tail(layout_provider::opaque_value::<*mut u8>()), 1); + assert_eq!(tail(layout_provider::opaque_value::<*const u8>()), 4); + } + } +} diff --git a/verifast-proofs/core/sync/atomic.rs/tool-tests/generic_projection.rs b/verifast-proofs/core/sync/atomic.rs/tool-tests/generic_projection.rs new file mode 100644 index 0000000000000..496400129b449 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/tool-tests/generic_projection.rs @@ -0,0 +1,34 @@ +#![no_std] + +unsafe fn inspect(_: T) +//@ req typeid(T) == typeid(u8); +//@ ens true; +//@ on_unwind_ens false; +{} + +unsafe fn count(value: usize) -> usize +//@ req value == int_of_const(typeid(N)); +//@ ens result == int_of_const(typeid(N)); +//@ on_unwind_ens false; +{ value } + +pub unsafe fn projection_client() -> usize +//@ req true; +//@ ens result == 1; +//@ on_unwind_ens false; +{ + unsafe { inspect::(0) }; + unsafe { count::<1>(1) } +} + +pub unsafe fn borrow_bytes(buffer: *const u8, length: usize) +//@ req [?f]buffer[..length] |-> ?bytes; +//@ ens [f]buffer[..length] |-> bytes; +//@ on_unwind_ens false; +{} + +#[cfg(test)] +#[test] +fn rust_value() { + assert_eq!(unsafe { projection_client() }, 1); +} diff --git a/verifast-proofs/core/sync/atomic.rs/tool-tests/macro_expansion.rs b/verifast-proofs/core/sync/atomic.rs/tool-tests/macro_expansion.rs new file mode 100644 index 0000000000000..5dda1190becc7 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/tool-tests/macro_expansion.rs @@ -0,0 +1,22 @@ +#![allow(dead_code)] + +// Coverage test for a contract in a macro that emits inherent impls, +// as used by core's atomic_int!. The runner changes only the second argument. +struct Atomic(T); + +macro_rules! atomic_int_probe { + ($ty:ty, $returned:expr) => { + impl Atomic<$ty> { + unsafe fn expansion() -> u32 + //@ req true; + //@ ens result == 0; + //@ on_unwind_ens false; + { + $returned + } + } + } +} + +atomic_int_probe!(u8, 0); +atomic_int_probe!(u32, 0); diff --git a/verifast-proofs/core/sync/atomic.rs/tool-tests/ordering.rs b/verifast-proofs/core/sync/atomic.rs/tool-tests/ordering.rs new file mode 100644 index 0000000000000..67e65de66081c --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/tool-tests/ordering.rs @@ -0,0 +1,25 @@ +#![allow(dead_code, incomplete_features, internal_features)] +#![feature(adt_const_params, core_intrinsics, intrinsics, rustc_attrs)] + +mod intrinsics { + use core::intrinsics::AtomicOrdering; + + #[rustc_intrinsic] + #[rustc_nounwind] + pub const unsafe fn atomic_store( + dst: *mut T, + val: T, + ) + //@ req typeid(T) == typeid(u32) &*& int_of_const(typeid(ORD)) == 0 &*& int_of_const(typeid(VOLATILE)) == 0 &*& [?f]std::intrinsics::atomic_points_to::(dst, 1, ?inv_) &*& inv_(val) == true; + //@ ens [f]std::intrinsics::atomic_points_to::(dst, 1, inv_); + //@ on_unwind_ens false; + ; +} + +pub unsafe fn store_relaxed(p: *mut u32, val: u32) +//@ req [?f]std::intrinsics::atomic_points_to::(p, 1, ?inv_) &*& inv_(val) == true; +//@ ens [f]std::intrinsics::atomic_points_to::(p, 1, inv_); +//@ on_unwind_ens false; +{ + unsafe { crate::intrinsics::atomic_store::(p, val) } +} diff --git a/verifast-proofs/core/sync/atomic.rs/tool-tests/pointer_client.rs b/verifast-proofs/core/sync/atomic.rs/tool-tests/pointer_client.rs new file mode 100644 index 0000000000000..afe48154186e5 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/tool-tests/pointer_client.rs @@ -0,0 +1,12 @@ +#![no_std] +extern crate slot_flags; +pub unsafe fn mut_client() -> u8 +//@ req true; +//@ ens result == 17; +//@ on_unwind_ens false; +{ unsafe { slot_flags::Slot::<*mut u8>::tag() } } +pub unsafe fn const_client() -> u8 +//@ req true; +//@ ens result == 29; +//@ on_unwind_ens false; +{ unsafe { slot_flags::Slot::<*const u8>::tag() } } diff --git a/verifast-proofs/core/sync/atomic.rs/tool-tests/pointer_lib.rs b/verifast-proofs/core/sync/atomic.rs/tool-tests/pointer_lib.rs new file mode 100644 index 0000000000000..d53de149cde8b --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/tool-tests/pointer_lib.rs @@ -0,0 +1,16 @@ +#![no_std] +pub struct Slot(T); +impl Slot<*mut T> { + pub unsafe fn tag() -> u8 + //@ req true; + //@ ens result == 17; + //@ on_unwind_ens false; + { 17 } +} +impl Slot<*const T> { + pub unsafe fn tag() -> u8 + //@ req true; + //@ ens result == 29; + //@ on_unwind_ens false; + { 29 } +} diff --git a/verifast-proofs/core/sync/atomic.rs/tool-tests/projection_recursion.rs b/verifast-proofs/core/sync/atomic.rs/tool-tests/projection_recursion.rs new file mode 100644 index 0000000000000..693137fca914b --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/tool-tests/projection_recursion.rs @@ -0,0 +1,23 @@ +#![no_std] +#![feature(generic_atomic)] + +use core::sync::atomic::Atomic; + +struct Node { value: T, next: *const Node } + +unsafe fn visit(p: *const Node, again: bool) -> *const Node +//@ req true; +//@ ens result == p; +//@ on_unwind_ens false; +{ + if again { unsafe { visit::(p, false) } } else { p } +} + +unsafe fn round_trip(p: *const Node<*mut T>, slot: *const Atomic<*mut T>) -> *const Atomic<*mut T> +//@ req true; +//@ ens result == slot; +//@ on_unwind_ens false; +{ + unsafe { visit::<*mut T>(p, true) }; + slot +} diff --git a/verifast-proofs/core/sync/atomic.rs/tool-tests/projections.rs b/verifast-proofs/core/sync/atomic.rs/tool-tests/projections.rs new file mode 100644 index 0000000000000..900e42ee6c851 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/tool-tests/projections.rs @@ -0,0 +1,319 @@ +#![no_std] + +#[cfg(any(case_slot, case_field, case_field_sync, case_body, case_param, case_mapped))] +trait Kind { + type Storage; +} +//@ fix Kind::Storage_typeid(t: *_) -> *_; + +#[cfg(case_slot)] +mod case { + use super::Kind; + struct Slot(core::marker::PhantomData); + impl Kind for Slot<*mut u8> { type Storage = u8; } + impl Kind for Slot<*const u8> { type Storage = u32; } + const _: () = assert!(core::mem::size_of::< as Kind>::Storage>() == 1); + + unsafe fn storage_type, S>() + //@ req true; + //@ ens typeid(::Storage) == typeid(S); + //@ on_unwind_ens false; + {} + + unsafe fn value() -> u8 + //@ req true; + //@ ens result == if typeid( as Kind>::Storage) == typeid(u32) { 4 } else { 1 }; + //@ on_unwind_ens false; + { + unsafe { storage_type::, u8>() }; + 1 + } + + pub unsafe fn client() -> u8 + //@ req true; + //@ ens result == 4; + //@ on_unwind_ens false; + { + unsafe { storage_type::, u32>() }; + unsafe { value() } + } + + #[cfg(test)] + #[test] + fn rust_value() { + assert_eq!(unsafe { client() }, 1); + } +} + +#[cfg(case_nested_trait)] +mod case { + struct Slot; + trait NestedKind

{ type Storage; } + //@ fix NestedKind::Storage_typeid(p: *_, t: *_) -> *_; + impl NestedKind<*const *mut u8> for Slot { type Storage = u8; } + impl NestedKind<*const *const u8> for Slot { type Storage = u32; } + + unsafe fn storage_type, P, S>() + //@ req true; + //@ ens typeid(>::Storage) == typeid(S); + //@ on_unwind_ens false; + {} + + unsafe fn value() -> u8 + //@ req true; + //@ ens result == if typeid(>::Storage) == typeid(u32) { 4 } else { 1 }; + //@ on_unwind_ens false; + { + unsafe { storage_type::() }; + 1 + } + + pub unsafe fn client() -> u8 + //@ req true; + //@ ens result == 4; + //@ on_unwind_ens false; + { + unsafe { storage_type::() }; + unsafe { value() } + } + + #[cfg(test)] + #[test] + fn rust_value() { + assert_eq!(unsafe { client() }, 1); + } +} + +#[cfg(case_field)] +mod case { + use super::Kind; + impl Kind for *mut u8 { type Storage = u8; } + impl Kind for *const u8 { type Storage = u32; } + + #[repr(C)] + struct Slot { data: T::Storage, tail: u8 } + + pub unsafe fn client(p: *const u8) -> bool + //@ req pointer_within_limits(&(*(p as *Slot<*mut u8>)).tail) == true &*& pointer_within_limits(&(*(p as *Slot<*const u8>)).tail) == true; + //@ ens result == true; + //@ on_unwind_ens false; + { + let a = p as *const Slot<*mut u8>; + let b = p as *const Slot<*const u8>; + unsafe { (&raw const (*a).tail) == (&raw const (*b).tail) } + } + + #[cfg(test)] + const _: () = { + assert!(core::mem::offset_of!(Slot<*mut u8>, tail) == 1); + assert!(core::mem::offset_of!(Slot<*const u8>, tail) == 4); + }; + + #[cfg(test)] + #[test] + fn different_offsets() { + let storage = [0u32; 2]; + assert!(!unsafe { client(storage.as_ptr().cast()) }); + } +} + +#[cfg(case_field_sync)] +mod case { + use super::Kind; + impl Kind for *mut u8 { type Storage = u8; } + impl Kind for *const u8 { type Storage = core::cell::UnsafeCell; } + + #[repr(C)] + struct Slot { data: T::Storage, tail: u8 } + struct Outer(Slot); + + #[cfg(nested)] + type Carrier = Outer; + #[cfg(not(nested))] + type Carrier = Slot; + + pub unsafe fn client(_a: *const Carrier<*mut u8>, _b: *const Carrier<*const u8>) + //@ req true; + //@ ens is_Sync(typeid(Slot<*mut u8>)) == is_Sync(typeid(Slot<*const u8>)); + //@ on_unwind_ens false; + {} + + #[cfg(test)] + #[test] + fn sync_bounds() { + fn require_sync() {} + require_sync::>(); + #[cfg(bad_sync)] + require_sync::>(); + } +} + +#[cfg(case_body)] +mod case { + use super::Kind; + impl Kind for *mut u8 { type Storage = u8; } + impl Kind for *const u8 { type Storage = u32; } + + #[repr(C)] + struct Pair { data: U, tail: u8 } + + unsafe fn tail(p: *const u8) -> *const u8 + //@ req pointer_within_limits(&(*(p as *Pair< ::Storage>)).tail) == true; + //@ ens result == &(*(p as *Pair< ::Storage>)).tail; + //@ on_unwind_ens false; + { + let pair = p as *const Pair; + unsafe { &raw const (*pair).tail } + } + + pub unsafe fn outer(p: *const u8) -> *const u8 + //@ req pointer_within_limits(&(*(p as *Pair< ::Storage>)).tail) == true; + //@ ens result == &(*(p as *Pair< ::Storage>)).tail; + //@ on_unwind_ens false; + { unsafe { tail::(p) } } + + #[cfg(two_hop)] + use outer as project; + #[cfg(not(two_hop))] + use tail as project; + + pub unsafe fn client(p: *const u8) -> bool + //@ req pointer_within_limits(&(*(p as *Pair< <*mut u8 as Kind>::Storage>)).tail) == true &*& pointer_within_limits(&(*(p as *Pair< <*const u8 as Kind>::Storage>)).tail) == true; + //@ ens result == true; + //@ on_unwind_ens false; + { unsafe { project::<*mut u8>(p) == project::<*const u8>(p) } } + + #[cfg(test)] + const _: () = { + assert!(core::mem::offset_of!(Pair<<*mut u8 as Kind>::Storage>, tail) == 1); + assert!(core::mem::offset_of!(Pair<<*const u8 as Kind>::Storage>, tail) == 4); + }; + + #[cfg(test)] + #[test] + fn different_addresses() { + let storage = [0u32; 2]; + let p: *const u8 = storage.as_ptr().cast(); + assert_eq!(unsafe { project::<*mut u8>(p) }, p.wrapping_add(1)); + assert_eq!(unsafe { project::<*const u8>(p) }, p.wrapping_add(4)); + assert!(!unsafe { client(p) }); + } +} + +#[cfg(case_param)] +mod case { + use super::Kind; + impl Kind for *mut u8 { type Storage = u8; } + impl Kind for *const u8 { type Storage = u32; } + + #[repr(C)] + struct Slot { data: T::Storage, tail: u8 } + + pub unsafe fn client(p: *const u8) -> bool + //@ req typeid(A) == typeid(*mut u8) &*& typeid(B) == typeid(*const u8) &*& pointer_within_limits(&(*(p as *Slot)).tail) == true &*& pointer_within_limits(&(*(p as *Slot)).tail) == true; + //@ ens result == (&(*(p as *Slot)).tail == &(*(p as *Slot)).tail); + //@ on_unwind_ens false; + { + let a = p as *const Slot; + let b = p as *const Slot; + unsafe { (&raw const (*a).tail) == (&raw const (*b).tail) } + } + + #[cfg(test)] + const _: () = { + assert!(core::mem::offset_of!(Slot<*mut u8>, tail) == 1); + assert!(core::mem::offset_of!(Slot<*const u8>, tail) == 4); + }; + + #[cfg(test)] + #[test] + fn different_tail_addresses() { + let storage = [0u32; 2]; + assert!(!unsafe { client::<*mut u8, *const u8>(storage.as_ptr().cast()) }); + } +} + +#[cfg(case_mapped)] +mod case { + use super::Kind; + impl Kind for *mut u8 { type Storage = u8; } + impl Kind for *const u8 { type Storage = u32; } + + trait Map { type P: Kind; } + //@ fix Map::P_typeid(t: *_) -> *_; + struct First; + struct Second; + impl Map for First { type P = *mut u8; } + impl Map for Second { type P = *const u8; } + + #[repr(C)] + struct Pair { data: U, tail: u8 } + + unsafe fn project(p: *const u8) -> *const u8 + //@ req pointer_within_limits(&(*(p as *Pair< < ::P as Kind>::Storage>)).tail) == true; + //@ ens result == &(*(p as *Pair< < ::P as Kind>::Storage>)).tail; + //@ on_unwind_ens false; + { + let pair = p as *const Pair<::Storage>; + unsafe { &raw const (*pair).tail } + } + + #[cfg(two_hop)] + unsafe fn outer(p: *const u8) -> *const u8 + //@ req pointer_within_limits(&(*(p as *Pair< < ::P as Kind>::Storage>)).tail) == true; + //@ ens result == &(*(p as *Pair< < ::P as Kind>::Storage>)).tail; + //@ on_unwind_ens false; + { unsafe { project::(p) } } + + pub unsafe fn client(p: *const u8) -> bool + //@ req pointer_within_limits(&(*(p as *Pair)).tail) == true &*& pointer_within_limits(&(*(p as *Pair)).tail) == true; + //@ ens result == (&(*(p as *Pair)).tail == &(*(p as *Pair)).tail); + //@ on_unwind_ens false; + { + #[cfg(not(two_hop))] + unsafe { project::(p) == project::(p) } + #[cfg(two_hop)] + unsafe { outer::(p) == outer::(p) } + } + + #[cfg(test)] + const _: () = { + assert!(core::mem::offset_of!(Pair<<::P as Kind>::Storage>, tail) == 1); + assert!(core::mem::offset_of!(Pair<<::P as Kind>::Storage>, tail) == 4); + }; + + #[cfg(test)] + #[test] + fn different_tail_addresses() { + let storage = [0u32; 2]; + let p = storage.as_ptr().cast(); + assert_eq!(unsafe { project::(p) }, p.wrapping_add(1)); + assert_eq!(unsafe { project::(p) }, p.wrapping_add(4)); + assert!(!unsafe { client(p) }); + } +} + +#[cfg(case_const)] +mod case { + trait ConstKind { type Output; } + //@ fix ConstKind::Output_typeid(n: *_, t: *_) -> *_; + + #[cfg(not(mir_operand))] + pub unsafe fn client>() + //@ req true; + //@ ens true; + //@ on_unwind_ens false; + {} + + #[cfg(mir_operand)] + struct Value(core::marker::PhantomData); + #[cfg(mir_operand)] + impl Value { const BYTE: u8 = 1; } + + #[cfg(mir_operand)] + pub unsafe fn client>() -> u8 + //@ req true; + //@ ens result == 1; + //@ on_unwind_ens false; + { Value::::BYTE } +} diff --git a/verifast-proofs/core/sync/atomic.rs/tool-tests/source_tokens.rs b/verifast-proofs/core/sync/atomic.rs/tool-tests/source_tokens.rs new file mode 100644 index 0000000000000..dc163300f9e1e --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/tool-tests/source_tokens.rs @@ -0,0 +1,47 @@ +#![feature(rustc_private)] +extern crate rustc_driver; +extern crate rustc_lexer; + +use rustc_lexer::{FrontmatterAllowed, TokenKind, tokenize}; +use std::{env, fs, process}; + +fn tokens(source: &str) -> Vec<(&str, bool)> { + let mut offset = 0; + let mut result = Vec::new(); + let mut previous_punctuation = None; + for token in tokenize(source, FrontmatterAllowed::No) { + let start = offset; + offset += token.len as usize; + let text = &source[start..offset]; + match token.kind { + TokenKind::Whitespace => continue, + TokenKind::LineComment { doc_style: None } if text.starts_with("//@") => continue, + TokenKind::BlockComment { doc_style: None, terminated: true } + if text.starts_with("/*@") && text.ends_with("@*/") => continue, + _ => {} + } + // Keep joint operators such as >>, ::, != and +=. A semicolon + // following a never type is still a separate token in both sources. + let punctuation = text.len() == 1 && "=<>!+-*/%^&|.:".contains(text); + let joint = punctuation && previous_punctuation == Some(start); + result.push((text, joint)); + previous_punctuation = punctuation.then_some(offset); + } + result +} + +fn main() { + let args: Vec<_> = env::args().collect(); + assert_eq!(args.len(), 3, "expected production and annotated source paths"); + let a = fs::read_to_string(&args[1]).unwrap(); + let b = fs::read_to_string(&args[2]).unwrap(); + let left = tokens(&a); + let right = tokens(&b); + if left != right { + let index = left.iter().zip(&right).position(|(a, b)| a != b) + .unwrap_or(left.len().min(right.len())); + eprintln!("{} token {index} differs: {:?} / {:?}", args[1], left.get(index), right.get(index)); + process::exit(1); + } + println!("{} tokens match in {}", left.len(), args[1]); +} diff --git a/verifast-proofs/core/sync/atomic.rs/tool-tests/trait_dispatch.rs b/verifast-proofs/core/sync/atomic.rs/tool-tests/trait_dispatch.rs new file mode 100644 index 0000000000000..cea7eba34a776 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/tool-tests/trait_dispatch.rs @@ -0,0 +1,21 @@ +#![no_std] + +trait Kind { + unsafe fn value() -> u8 { 1 } +} + +struct Item; + +impl Kind for Item { + unsafe fn value() -> u8 + //@ req true; + //@ ens result == 2; + //@ on_unwind_ens false; + { 2 } +} + +pub unsafe fn concrete_value() -> u8 +//@ req true; +//@ ens result == 2; +//@ on_unwind_ens false; +{ unsafe { ::value() } } diff --git a/verifast-proofs/core/sync/atomic.rs/tool-tests/wide_pointer_comparison.rs b/verifast-proofs/core/sync/atomic.rs/tool-tests/wide_pointer_comparison.rs new file mode 100644 index 0000000000000..a656c4927e0e6 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/tool-tests/wide_pointer_comparison.rs @@ -0,0 +1,29 @@ +#![no_std] +#![allow(ambiguous_wide_pointer_comparisons)] + +#[cfg(thin)] +type Pointee = u8; +#[cfg(not(thin))] +type Pointee = [u8]; +#[cfg(mutable)] +type Raw = *mut Pointee; +#[cfg(not(mutable))] +type Raw = *const Pointee; + +pub unsafe fn compare(a: Raw, b: Raw) -> bool +//@ req (a as pointer).address == (b as pointer).address; +//@ ens result == false; +//@ on_unwind_ens false; +{ a < b } + +#[cfg(all(test, not(thin)))] +#[test] +fn same_address_different_lengths() { + let mut bytes = [0u8; 2]; + let base = bytes.as_mut_ptr(); + let a: Raw = core::ptr::slice_from_raw_parts_mut(base, 1); + let b: Raw = core::ptr::slice_from_raw_parts_mut(base, 2); + assert!(core::ptr::addr_eq(a, b)); + assert!(unsafe { compare(a, b) }); + assert!(a != b && a <= b && b > a && b >= a); +} diff --git a/verifast-proofs/core/sync/atomic.rs/update.sh b/verifast-proofs/core/sync/atomic.rs/update.sh new file mode 100755 index 0000000000000..7a1a04a3d61ed --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/update.sh @@ -0,0 +1,241 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")" + +# Serialize concurrent snapshot updates. +exec 9<. +flock 9 + +src=../../../../library/core/src +paths=( + lib.rs + sync/atomic.rs + sync/atomic_load_volatile.md + sync/atomic_store_volatile.md + intrinsics/mod.rs +) + +# Refuse to overwrite uncommitted edits to tracked snapshot files. +if ! git diff --quiet HEAD -- original; then + echo "Preserve tracked local edits under original/ before updating." >&2 + exit 1 +fi + +# Refuse to overwrite unexpected or locally edited untracked files under original/. +preflight_tmp=$(mktemp -d "${TMPDIR:-/tmp}/atomic-update-pre.XXXXXXXX") +trap 'rm -rf -- "$preflight_tmp"' EXIT +git ls-files --others -z -- original > "$preflight_tmp/untracked.nul" +while IFS= read -r -d '' rel; do + mapped= + for path in "${paths[@]}"; do + if [[ $rel == "original/${path#sync/}" ]]; then + mapped=$path + break + fi + done + if [[ -z $mapped || ! -f $rel || -L $rel ]]; then + echo "Preserve local snapshot entry before updating: $rel" >&2 + exit 1 + fi + if cmp -s "$rel" "$src/$mapped"; then + continue + fi + if git cat-file -e "HEAD:library/core/src/$mapped" 2>/dev/null; then + git show "HEAD:library/core/src/$mapped" > "$preflight_tmp/head.file" + if cmp -s "$rel" "$preflight_tmp/head.file"; then + continue + fi + fi + echo "Preserve local snapshot edits before updating: $rel" >&2 + exit 1 +done < "$preflight_tmp/untracked.nul" +rm -rf -- "$preflight_tmp" +trap - EXIT + +git_dir=$(git rev-parse --path-format=absolute --git-common-dir) +backups="$git_dir/atomic-snapshot-backups" +mkdir -p "$backups" +chmod 700 "$backups" + +stage=$(mktemp -d "$backups/.stage.XXXXXXXX") +backup= +temps=() +dirs_to_create=() +declare -A existed_before=() +publishing=0 +committed=0 +cleaned_up=0 + +plan_mkdir_p() { + local d=$1 + local missing=() + while [[ ! -d $d ]]; do + missing+=("$d") + local parent + parent=$(dirname "$d") + if [[ $parent == "$d" ]]; then break; fi + d=$parent + done + local i existing already + for ((i = ${#missing[@]} - 1; i >= 0; i--)); do + already=0 + for existing in "${dirs_to_create[@]}"; do + if [[ $existing == "${missing[$i]}" ]]; then + already=1 + break + fi + done + if [[ $already -eq 0 ]]; then + dirs_to_create+=("${missing[$i]}") + fi + done +} + +verify_rollback_state() { + local path rel dst + for path in "${paths[@]}"; do + rel="${path#sync/}" + dst="original/$rel" + if [[ ${existed_before[$rel]:-0} -eq 1 ]]; then + if [[ ! -f $dst || -L $dst ]] || ! cmp -s "$backup/$rel" "$dst"; then + return 1 + fi + else + if [[ -e $dst || -L $dst ]]; then + return 1 + fi + fi + done + local d + for d in "${dirs_to_create[@]}"; do + if [[ -e $d || -L $d ]]; then + return 1 + fi + done + if [[ -d original && -n $(find original -maxdepth 2 \( -name ".update.$$.*" -o -name ".restore.$$.*" \) 2>/dev/null) ]]; then + return 1 + fi + return 0 +} + +cleanup() { + local rc=$? + if [[ $cleaned_up -eq 1 ]]; then + exit "$rc" + fi + cleaned_up=1 + set +e + trap '' INT TERM HUP + if [[ $committed -eq 0 ]]; then + local t + for t in "${temps[@]}"; do + rm -f -- "$t" + done + rm -f -- original/.update.$$.* original/*/.update.$$.* original/.restore.$$.* original/*/.restore.$$.* + local restore_failed=0 + if [[ -n $backup && $publishing -eq 1 ]]; then + local path rel dst rtmp + for path in "${paths[@]}"; do + rel="${path#sync/}" + dst="original/$rel" + if [[ ${existed_before[$rel]:-0} -eq 1 ]]; then + if mkdir -p "$(dirname "$dst")" \ + && rtmp=$(mktemp "$(dirname "$dst")/.restore.$$.XXXXXXXX") \ + && cp -p "$backup/$rel" "$rtmp" \ + && mv -f "$rtmp" "$dst"; then + : + else + restore_failed=1 + fi + else + if ! rm -f -- "$dst"; then + restore_failed=1 + fi + fi + done + fi + # Sweep again after restore attempts so a failed cp/mv never leaves stray .restore temp files. + rm -f -- original/.update.$$.* original/*/.update.$$.* original/.restore.$$.* original/*/.restore.$$.* + local i + for ((i = ${#dirs_to_create[@]} - 1; i >= 0; i--)); do + rmdir -- "${dirs_to_create[$i]}" 2>/dev/null || true + done + if [[ -n $backup ]]; then + if [[ $restore_failed -eq 0 ]] && verify_rollback_state; then + echo "Snapshot update aborted and rolled back. Recovery path: $backup" >&2 + else + echo "ERROR: Snapshot rollback verification failed. Manual recovery path: $backup" >&2 + if [[ $rc -eq 0 ]]; then rc=1; fi + fi + fi + fi + rm -rf -- "$stage" + exit "$rc" +} +on_signal() { + local sig=$1 + exit "$((128 + sig))" +} +trap cleanup EXIT +trap 'on_signal 1' HUP +trap 'on_signal 2' INT +trap 'on_signal 15' TERM + +# Stage and verify all five upstream inputs before modifying original/. +for path in "${paths[@]}"; do + rel="${path#sync/}" + dest="original/$rel" + if [[ -L $dest || ( -e $dest && ! -f $dest ) ]]; then + echo "Unexpected non-file entry in snapshot path: $dest" >&2 + exit 1 + fi + if [[ -e $dest ]]; then + existed_before[$rel]=1 + else + existed_before[$rel]=0 + fi + mkdir -p "$stage/$(dirname "$rel")" + cp -p "$src/$path" "$stage/$rel" + if ! cmp -s "$src/$path" "$stage/$rel"; then + echo "Upstream source changed while staging: $path" >&2 + exit 1 + fi +done + +# Retain a permanent backup outside the worktree and announce it before any live write. +backup=$(mktemp -d "$backups/original.XXXXXXXX") +if [[ -d original ]]; then + cp -a original/. "$backup/" +fi +echo "Previous snapshot retained. Recovery path: $backup" >&2 + +# Plan all missing directories BEFORE creating any of them so signals mid-mkdir still roll back cleanly. +for path in "${paths[@]}"; do + rel="${path#sync/}" + plan_mkdir_p "$(dirname "original/$rel")" +done +for d in "${dirs_to_create[@]}"; do + mkdir "$d" +done + +# Prepare all five per-file temp copies in original/ before replacing any live path. +declare -A staged_temps=() +for path in "${paths[@]}"; do + rel="${path#sync/}" + dest="original/$rel" + tmp=$(mktemp "$(dirname "$dest")/.update.$$.XXXXXXXX") + temps+=("$tmp") + cp -p "$stage/$rel" "$tmp" + staged_temps[$rel]=$tmp +done + +# Mark publish phase BEFORE the first rename so a signal or error at any point replays full rollback. +publishing=1 +for path in "${paths[@]}"; do + rel="${path#sync/}" + dest="original/$rel" + mv -f "${staged_temps[$rel]}" "$dest" +done + +bash check-sources.sh +committed=1 diff --git a/verifast-proofs/core/sync/atomic.rs/verifast-core.patch b/verifast-proofs/core/sync/atomic.rs/verifast-core.patch new file mode 100644 index 0000000000000..88e72f89af725 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/verifast-core.patch @@ -0,0 +1,1925 @@ +diff --git a/bin/rust/prelude_core.rsspec b/bin/rust/prelude_core.rsspec +index 34d3057d0325ef065b4e1933078e56894d2c70ce..d5bd28d3b79e2434424e35d70ce856451b5d026d 100644 +--- a/bin/rust/prelude_core.rsspec ++++ b/bin/rust/prelude_core.rsspec +@@ -298,4 +298,10 @@ lem_auto int_of_const_of_int(n: i32); + ens int_of_const(const_of_int(n)) == n; + ++// A fieldless Rust enum const is identified by its enum type and rustc discriminant. ++inductive rust_unit_enum_const = rust_unit_enum_const_tag; ++lem_auto rust_unit_enum_const_discriminant(); ++ req true; ++ ens int_of_const(typeid(rust_unit_enum_const)) == int_of_const(typeid(D)); ++ + fix Array_elems(array: [T; N]) -> list; + // If `length(elems)` is not `int_of_const(typeid(N))` then the result is unspecified. +diff --git a/bin/rust/std/lib.rsspec b/bin/rust/std/lib.rsspec +index a5d925d67c7934105a7a95c532c84edee8f3afd4..461a548e30b9c8be7b3375b80e78ee7f00d3bbe5 100644 +--- a/bin/rust/std/lib.rsspec ++++ b/bin/rust/std/lib.rsspec +@@ -297,4 +297,12 @@ mod marker { + mod intrinsics { + ++ enum AtomicOrdering { ++ Relaxed, ++ Release, ++ Acquire, ++ AcqRel, ++ SeqCst, ++ } ++ + fn ub_checks() -> bool; + //@ req true; +diff --git a/rust-toolchain.toml b/rust-toolchain.toml +index 65b6ce1bfcb0361ad5a47658263b4f458ec0691c..9532e8e99a66584618087c2c159c060d2fd06691 100644 +--- a/rust-toolchain.toml ++++ b/rust-toolchain.toml +@@ -1,3 +1,3 @@ + [toolchain] +-channel = "nightly-2026-09-25" ++channel = "nightly-2026-11-21" + components = ["rustc-dev", "llvm-tools-preview"] +diff --git a/src/refinement_checker/frontend.ml b/src/refinement_checker/frontend.ml +index 482353b1cb76b9ff8c9c3f9d750163dc12f0def9..f0ab604d07d37b1eade1fa443c10f015bf65c23b 100644 +--- a/src/refinement_checker/frontend.ml ++++ b/src/refinement_checker/frontend.ml +@@ -100,5 +100,5 @@ let run_vf_mir_exporter (rustc_args : string list) (rs_file_path : string) = + try + (*** TODO @Nima: Get these names from build system *) +- let tchain_name = "nightly-2026-09-25" in ++ let tchain_name = "nightly-2026-11-21" in + let tchain_root = RustTChain.find_tchain_root tchain_name in + let tchain_lib, rustc_driver_prefix = +diff --git a/src/refinement_checker/main.ml b/src/refinement_checker/main.ml +index 0001bd056e20cf00ecdb81bd23b1e36e09bb01ef..31143e198696809dd427e888a56cd11e4feb4de8 100644 +--- a/src/refinement_checker/main.ml ++++ b/src/refinement_checker/main.ml +@@ -64,4 +64,21 @@ let verified_vf_mir = + decode_vf_mir @@ VfMirRd.VfMir.of_message @@ Frontend.get_vf_mir !rustc_args verified_path + ++let local_enum_discriminants defs = ++ let rec collect acc = function ++ | Nil -> List.sort compare acc ++ | Cons {h = (adt: adt_def); t} -> ++ if adt.is_local && adt.kind = EnumKind then ++ let variants = List.map (fun (v: variant_def) -> ++ v.name, v.discriminant_ty, v.discriminant_bits) adt.variants in ++ collect ((adt.id.name, variants) :: acc) t ++ else collect acc t ++ in collect [] defs ++ ++let () = ++ if local_enum_discriminants original_vf_mir.adt_defs <> local_enum_discriminants verified_vf_mir.adt_defs then begin ++ prerr_endline "Refinement error: the crates have different enum discriminants"; ++ exit 1 ++ end ++ + let ensure_unique_keys kvs = + let keys_seen = Hashtbl.create (List.length kvs) in +diff --git a/src/refinement_checker/refinement_checker.ml b/src/refinement_checker/refinement_checker.ml +index 71fc1ad896e2a80fd873afcaf37cd8973280d917..f6f6bba649c1791d7ab915e7d5011b2da8191f07 100644 +--- a/src/refinement_checker/refinement_checker.ml ++++ b/src/refinement_checker/refinement_checker.ml +@@ -300,5 +300,5 @@ and decode_const_expr genv const_cpn = + match valtree with + Leaf scalar_int_cpn -> LiteralConstExpr (decode_scalar_int ty scalar_int_cpn) +- | Branch _ -> TreeConstExpr (ty, valtree) ++ | Branch _ | UnitVariant _ -> TreeConstExpr (ty, valtree) + + type call_path = basic_block_path option +@@ -329,4 +329,5 @@ type term = + | FieldTerm of term * int + | UnevaluatedConstTerm of string * gen_arg list ++| TypeConstTerm of ty * const_expr + | RepeatTerm of term * const_expr + +@@ -344,4 +345,5 @@ let rec string_of_term = function + | FieldTerm (term, i) -> Printf.sprintf "FieldTerm %s %d" (string_of_term term) i + | UnevaluatedConstTerm (def, args) -> Printf.sprintf "UnevaluatedConstTerm %s::<%s>" def (String.concat ", " (List.map string_of_gen_arg args)) ++| TypeConstTerm (ty, value) -> Printf.sprintf "TypeConstTerm %s %s" (string_of_ty ty) (string_of_const_expr value) + | RepeatTerm (term, count) -> Printf.sprintf "RepeatTerm %s %s" (string_of_term term) (string_of_const_expr count) + and string_of_terms ts = +@@ -365,5 +367,5 @@ let string_of_local_var_state = function + let eval_mir_const genv mir_const_cpn = + match mir_const_cpn with +- Ty mir_ty_const_cpn -> failwith "Using typesystem constant expressions as MIR constant operands is not yet supported" ++ Ty {ty; const} -> TypeConstTerm (decode_ty genv ty, decode_const_expr genv const) + | Val mir_val_const_cpn -> + let ty = decode_ty genv mir_val_const_cpn.ty in +@@ -621,4 +623,5 @@ let fns_to_be_inlined: (string * body) list = + clauses=[]; + is_trait_fn=false; ++ is_intrinsic_declaration=false; + is_drop_fn=false; + visibility=Public; +@@ -718,4 +721,5 @@ let fns_to_be_inlined: (string * body) list = + clauses=[]; + is_trait_fn=false; ++ is_intrinsic_declaration=false; + is_drop_fn=false; + visibility=Public; +@@ -746,5 +750,5 @@ let fns_to_be_inlined: (string * body) list = + id={index=Stdint.Uint32.of_int 0}; + statements=[ +- {kind=Assign {lhs_place=local "discr"; rhs_rvalue=Discriminant {place=local "self"; discriminant_ty=Signed ISize; discriminant_values=[]}}; source_info={span}} ++ {kind=Assign {lhs_place=local "discr"; rhs_rvalue=Discriminant {place=local "self"; discriminant_ty=Signed ISize; discriminant_values=[]; abstract_operand=Nothing}}; source_info={span}} + ]; + terminator={ +@@ -957,4 +961,5 @@ let fns_to_be_inlined: (string * body) list = + clauses=[]; + is_trait_fn=false; ++ is_intrinsic_declaration=false; + is_drop_fn=false; + visibility=Public; +@@ -984,5 +989,5 @@ let fns_to_be_inlined: (string * body) list = + id={index=Stdint.Uint32.of_int 0}; + statements=[ +- {kind=Assign {lhs_place=local "discr"; rhs_rvalue=Discriminant {place=local "self"; discriminant_ty=Signed ISize; discriminant_values=[]}}; source_info={span}} ++ {kind=Assign {lhs_place=local "discr"; rhs_rvalue=Discriminant {place=local "self"; discriminant_ty=Signed ISize; discriminant_values=[]; abstract_operand=Nothing}}; source_info={span}} + ]; + terminator={ +@@ -1195,4 +1200,5 @@ let fns_to_be_inlined: (string * body) list = + clauses=[]; + is_trait_fn=false; ++ is_intrinsic_declaration=false; + is_drop_fn=false; + visibility=Public; +@@ -1221,5 +1227,5 @@ let fns_to_be_inlined: (string * body) list = + id={index=Stdint.Uint32.of_int 0}; + statements=[ +- {kind=Assign {lhs_place=local "discr"; rhs_rvalue=Discriminant {place=local "self"; discriminant_ty=Signed ISize; discriminant_values=[]}}; source_info={span}} ++ {kind=Assign {lhs_place=local "discr"; rhs_rvalue=Discriminant {place=local "self"; discriminant_ty=Signed ISize; discriminant_values=[]; abstract_operand=Nothing}}; source_info={span}} + ]; + terminator={ +@@ -1411,4 +1417,5 @@ let fns_to_be_inlined: (string * body) list = + clauses=[]; + is_trait_fn=false; ++ is_intrinsic_declaration=false; + is_drop_fn=false; + visibility=Public; +@@ -1434,5 +1441,5 @@ let fns_to_be_inlined: (string * body) list = + id={index=Stdint.Uint32.of_int 0}; + statements=[ +- {kind=Assign {lhs_place=local "discr"; rhs_rvalue=Discriminant {place=local "self"; discriminant_ty=Signed ISize; discriminant_values=[]}}; source_info={span}} ++ {kind=Assign {lhs_place=local "discr"; rhs_rvalue=Discriminant {place=local "self"; discriminant_ty=Signed ISize; discriminant_values=[]; abstract_operand=Nothing}}; source_info={span}} + ]; + terminator={ +@@ -1591,4 +1598,5 @@ let fns_to_be_inlined: (string * body) list = + clauses=[]; + is_trait_fn=false; ++ is_intrinsic_declaration=false; + is_drop_fn=false; + visibility=Public; +@@ -1613,5 +1621,5 @@ type command = + | UnaryOp of rvalue_unary_op_data_un_op (* Pop a value from the top of the operand stack, apply the specified unary operator to it, and push the result *) + | Aggregate of aggregate_kind * int (* Pop the specified number of values from the top of the operand stack and push an aggregate value *) +-| Discriminant (* Pop a value from the top of the operand stack, which is an enum value, and push the discriminant of the enum value *) ++| Discriminant of rvalue_discriminant_data + | SourceInfo of source_info + | Assume (* Pop a Boolean value from the top of the operand stack. Produce UB if false. *) +@@ -1634,5 +1642,5 @@ let string_of_command c = + | RuntimeChecks checks -> Printf.sprintf "RuntimeChecks" + | Aggregate (aggregate_kind, n) -> Printf.sprintf "Aggregate %s %d" (string_of_aggregate_kind aggregate_kind) n +- | Discriminant -> "Discriminant" ++ | Discriminant _ -> "Discriminant" + | SourceInfo {span} -> Printf.sprintf "SourceInfo %s" (string_of_span span) + | Assume -> "Assume" +@@ -1663,5 +1671,5 @@ let commands_of_rvalue = function + | UnaryOp {operator; operand} -> commands_of_operand operand @ [UnaryOp operator] + | Aggregate {aggregate_kind; operands} -> List.concat_map commands_of_operand operands @ [Aggregate (aggregate_kind, List.length operands)] +-| Discriminant {place} -> commands_for_loading_place place @ [Discriminant] ++| Discriminant data -> commands_for_loading_place data.place @ [Discriminant data] + + let commands_of_statement_kind = function +@@ -2116,6 +2124,8 @@ let check_rvalue_refines_rvalue genv0 env0 span0 caller0 rhsRvalue0 genv1 env1 s + | Aggregate aggregate_data_cpn0, Aggregate aggregate_data_cpn1 -> + check_aggregate_refines_aggregate genv0 env0 span0 caller0 aggregate_data_cpn0 genv1 env1 span1 caller1 aggregate_data_cpn1 +-| Discriminant {place=place_cpn0}, Discriminant {place=place_cpn1} -> +- begin match check_place_refines_place env0 caller0 place_cpn0 env1 caller1 place_cpn1 with ++| Discriminant a, Discriminant b -> ++ if (a.abstract_operand, a.discriminant_ty, a.discriminant_values) <> ++ (b.abstract_operand, b.discriminant_ty, b.discriminant_values) then failwith "Discriminant layouts differ"; ++ begin match check_place_refines_place env0 caller0 a.place env1 caller1 b.place with + (Local x0, Local x1) | (LocalProjection x0, LocalProjection x1) -> if List.assoc x0 env0 <> List.assoc x1 env1 then failwith "The discriminees of the two rvalues are not equal" + | Nonlocal, Nonlocal -> () +@@ -2292,4 +2302,6 @@ let check_clause_refines_clause genv0 clause0 genv1 clause1 = + + let check_body_refines_body bodies0 bodies1 def_path body0 body1 = ++ if body0.is_intrinsic_declaration <> body1.is_intrinsic_declaration then ++ failwith (def_path ^ ": the compiler intrinsic declaration changed"); + let error msg = + Printf.printf "ERROR: %s\n" msg; +@@ -2698,5 +2710,7 @@ let check_body_refines_body bodies0 bodies1 def_path body0 body1 = + let v = fresh_symbol () in + cont env0 (v::opnds0) env1 (v::opnds1) +- | Discriminant, Discriminant -> ++ | Discriminant a, Discriminant b -> ++ if (a.abstract_operand, a.discriminant_ty, a.discriminant_values) <> ++ (b.abstract_operand, b.discriminant_ty, b.discriminant_values) then error "Discriminant layouts differ"; + let v, opnds0, opnds1 = consume_operand opnds0 opnds1 in + let v = fresh_symbol () in +diff --git a/src/refinement_checker/stringifier.ml b/src/refinement_checker/stringifier.ml +index 17b4917c17c6dae677f96bb82e92f1193d4db1a8..778585b22bb1e9ea0250af622c8c6a7b5d2bcb76 100644 +--- a/src/refinement_checker/stringifier.ml ++++ b/src/refinement_checker/stringifier.ml +@@ -85,4 +85,13 @@ let string_of_bin_op = function + | Ge -> ">=" + | Offset -> "offset" ++ | AddUnchecked -> "add_unchecked" ++ | SubUnchecked -> "sub_unchecked" ++ | MulUnchecked -> "mul_unchecked" ++ | ShlUnchecked -> "shl_unchecked" ++ | ShrUnchecked -> "shr_unchecked" ++ | AddWithOverflow -> "add_with_overflow" ++ | SubWithOverflow -> "sub_with_overflow" ++ | MulWithOverflow -> "mul_with_overflow" ++ | Cmp -> "cmp" + + let string_of_aggregate_kind = function +diff --git a/src/rust_frontend/rust_fe.ml b/src/rust_frontend/rust_fe.ml +index 6e60121fc904b6d9b018194409b411ca8bf38f10..ae5c989794cce4e77636b5ecd8e372818b359191 100644 +--- a/src/rust_frontend/rust_fe.ml ++++ b/src/rust_frontend/rust_fe.ml +@@ -103,5 +103,5 @@ module Make (Args : RUST_FE_ARGS) = struct + try + (*** TODO @Nima: Get these names from build system *) +- let tchain_name = "nightly-2026-09-25" in ++ let tchain_name = "nightly-2026-11-21" in + let* tchain_root = RustTChain.find_tchain_root tchain_name in + let tchain_lib, rustc_driver_prefix = +diff --git a/src/rust_frontend/vf_mir/vf_mir.capnp b/src/rust_frontend/vf_mir/vf_mir.capnp +index 902281e74fa70f00553ea28ce49c1a1b00e5ac00..e29425982352227a4fec3ec48b929b8201885bbf 100644 +--- a/src/rust_frontend/vf_mir/vf_mir.capnp ++++ b/src/rust_frontend/vf_mir/vf_mir.capnp +@@ -165,7 +165,13 @@ struct ParamConst { + + struct ValTree { ++ struct UnitVariant { ++ name @0: Text; ++ ordinal @1: UInt32; ++ discriminant @2: Int32; ++ } + union { + leaf @0: ScalarInt; + branch @1: List(TyConst); ++ unitVariant @2: UnitVariant; + } + } +@@ -263,5 +269,6 @@ struct VariantDef { + span @2: SpanData; + name @1: Text; +- #discr @1: UInt64; ++ discriminantBits @3: UInt128; ++ discriminantTy @4: IntegerType; + fields @0: List(FieldDef); + } +@@ -628,4 +635,5 @@ struct Rvalue { + mutability @0: Mutability; + place @1: Place; ++ unsafeCellGetReceiver @2: Bool; + } + +@@ -650,4 +658,13 @@ struct Rvalue { + gt @15: Void; + offset @16: Void; ++ addUnchecked @17: Void; ++ subUnchecked @18: Void; ++ mulUnchecked @19: Void; ++ shlUnchecked @20: Void; ++ shrUnchecked @21: Void; ++ addWithOverflow @22: Void; ++ subWithOverflow @23: Void; ++ mulWithOverflow @24: Void; ++ cmp @25: Void; + } + } +@@ -655,4 +672,5 @@ struct Rvalue { + operandl @1: Operand; + operandr @2: Operand; ++ comparisonOperandsThin @3: Bool; # rustc proves every raw pointee in this comparison is Sized + } + +@@ -699,4 +717,5 @@ struct Rvalue { + discriminantTy @1: IntegerType; + discriminantValues @2: List(UInt128); # The bit representations of the values of the discriminants for each variant of the ADT ++ abstractOperand @3: Option(Ty); # The concrete discriminant layout is unavailable before monomorphization. + } + +@@ -864,4 +883,5 @@ struct Body { + span @6: SpanData; + isFromExpansion @24: Bool; # True if the function body is from a macro expansion ++ isIntrinsicDeclaration @26: Bool; # rustc intrinsic with no Rust fallback body + impSpan @7: SpanData; + varDebugInfo @8: List(VarDebugInfo); +diff --git a/src/rust_frontend/vf_mir_exporter/src/atomic_literal_panic.rs b/src/rust_frontend/vf_mir_exporter/src/atomic_literal_panic.rs +new file mode 100644 +index 0000000000000000000000000000000000000000..a09808e333d878c2b1c0aa20b8edb607befbdbf5 +--- /dev/null ++++ b/src/rust_frontend/vf_mir_exporter/src/atomic_literal_panic.rs +@@ -0,0 +1,112 @@ ++//! Imports two upstream std contracts for the approved literal panics in the ++//! pinned core. Never enabled for ordinary exports or native refinement. ++use super::*; ++use rustc_hir::def_id::{DefId, LOCAL_CRATE}; ++use rustc_middle::mir::visit::{NonUseContext, PlaceContext, Visitor}; ++use std::collections::{BTreeSet, HashMap, HashSet}; ++ ++#[derive(Clone, Copy)] ++pub(crate) struct LiteralPanic { ++ pub args: DefId, ++ make: DefId, ++ panic: DefId, ++} ++ ++impl LiteralPanic { ++ pub fn new(tcx: TyCtxt<'_>, items: &HirVisitor<'_>) -> Self { ++ assert_eq!(tcx.crate_name(LOCAL_CRATE).as_str(), "core"); ++ let triple = tcx.sess.opts.target_triple.to_string(); ++ assert!(matches!(triple.as_str(), "aarch64-unknown-linux-gnu" | "x86_64-unknown-linux-gnu"), "unsupported literal panic target: {triple}"); ++ assert_eq!(tcx.sess.target.pointer_width, 64); ++ assert_eq!(tcx.sess.target.endian, rustc_abi::Endian::Little); ++ assert_eq!(tcx.sess.panic_strategy().desc(), "unwind"); ++ let args = tcx.lang_items().format_arguments().expect("missing format_arguments"); ++ let panic = tcx.lang_items().panic_fmt().expect("missing panic_fmt"); ++ let make = items.bodies.iter().map(|(id, _)| id.to_def_id()) ++ .find(|id| tcx.def_path(id.to_owned()).to_string_no_crate_verbose().trim_start_matches(':') == "fmt::{impl#6}::from_str") ++ .expect("missing pinned Arguments::from_str"); ++ assert!(args.is_local() && panic.is_local()); ++ let parent = tcx.parent(make); ++ assert!(matches!(tcx.type_of(parent).instantiate_identity().skip_normalization().kind(), ty::Adt(adt, _) if adt.did() == args)); ++ for (id, expected) in [ ++ (make, "ff4a32ba599cdf601b7cfd063774bb6c86f2892c79273671ae591e8f73bfe235"), ++ (panic, "2dd23856063ade34d1f300e7b62fb4aec2bb3013aedb4a4cfb26ca28a62d931e"), ++ ] { ++ let file = tcx.sess.source_map().lookup_source_file(tcx.def_span(id).lo()); ++ let source = file.src.as_ref().expect("missing local panic source"); ++ let hash = rustc_span::SourceFileHash::new_in_memory(rustc_span::SourceFileHashAlgorithm::Sha256, source.as_bytes()); ++ let actual: String = hash.hash_bytes().iter().map(|byte| format!("{byte:02x}")).collect(); ++ assert_eq!(actual, expected, "literal panic source changed at {}", tcx.def_path_str(id)); ++ } ++ Self { args, make, panic } ++ } ++ ++ pub fn external_name(self, id: DefId) -> Option<&'static str> { ++ if id == self.make { Some("std::fmt::Arguments::<'a>::from_str") } ++ else if id == self.panic { Some("core::panicking::panic_fmt") } ++ else { None } ++ } ++ ++ // Only an immediately consumed literal temporary may cross the boundary. ++ // All other statements, terminators, normal and unwind successors are ++ // exported unchanged and retain their usual proof obligations. ++ pub fn check_body<'tcx>(self, tcx: TyCtxt<'tcx>, owner: &str, body: &mir::Body<'tcx>, evidence: &mut BTreeSet) { ++ let expected = match owner { ++ "sync::atomic::atomic_store" => &["there is no such thing as an acquire store", "there is no such thing as an acquire-release store"][..], ++ "sync::atomic::atomic_load" => &["there is no such thing as a release load", "there is no such thing as an acquire-release load"][..], ++ "sync::atomic::atomic_compare_exchange" | "sync::atomic::atomic_compare_exchange_weak" => ++ &["there is no such thing as a release failure ordering", "there is no such thing as an acquire-release failure ordering"][..], ++ _ => &[], ++ }; ++ let mut messages = HashSet::new(); ++ let mut consumers = HashSet::new(); ++ let mut uses = HashMap::new(); ++ let callee = |op: &mir::Operand<'tcx>| match op.ty(&body.local_decls, tcx).kind() { ++ ty::FnDef(id, _) => Some(*id), _ => None, ++ }; ++ for (bb, data) in body.basic_blocks.iter_enumerated() { ++ let mir::TerminatorKind::Call { func, args, destination, target, .. } = &data.terminator().kind else {continue}; ++ if callee(func) != Some(self.make) {continue} ++ let [arg] = &args[..] else {panic!("literal panic arity at {owner}")}; ++ let mir::Operand::Constant(c) = &arg.node else {panic!("nonliteral panic input at {owner}")}; ++ let mir::Const::Val(val @ mir::ConstValue::Slice {..}, ty) = c.const_ else {panic!("nonliteral panic input at {owner}")}; ++ assert!(matches!(ty.kind(), ty::Ref(_, inner, rustc_hir::Mutability::Not) if inner.is_str())); ++ let msg = std::str::from_utf8(val.try_get_slice_bytes_for_diagnostics(tcx).unwrap()).unwrap(); ++ assert!(expected.contains(&msg) && messages.insert(msg), "unapproved literal panic at {owner}: {msg}"); ++ let target = target.expect("literal constructor lacks a normal successor"); ++ let mir::TerminatorKind::Call { func: sink, args: operands, .. } = &body.basic_blocks[target].terminator().kind else {panic!("unpaired literal at {owner}")}; ++ assert_eq!(callee(sink), Some(self.panic), "wrong literal sink at {owner}"); ++ assert!(matches!(&operands[..], [arg] if matches!(arg.node, mir::Operand::Move(p) if p == *destination))); ++ let local = destination.as_local().expect("literal is not an isolated local"); ++ assert!(uses.insert(local, (body.terminator_loc(bb), body.terminator_loc(target))).is_none()); ++ consumers.insert(target); ++ evidence.insert(format!("literal-panic\t{owner}\t{bb:?}\t{target:?}\t{msg}")); ++ } ++ assert_eq!(messages.len(), expected.len(), "incomplete literal panic pairs at {owner}"); ++ for (bb, data) in body.basic_blocks.iter_enumerated() { ++ if let mir::TerminatorKind::Call {func, ..} | mir::TerminatorKind::TailCall {func, ..} = &data.terminator().kind { ++ if callee(func) == Some(self.panic) {assert!(consumers.contains(&bb), "unpaired panic_fmt at {owner}");} ++ if matches!(&data.terminator().kind, mir::TerminatorKind::TailCall {..}) { ++ assert!(callee(func).and_then(|id| self.external_name(id)).is_none()); ++ } ++ } ++ } ++ for (local, decl) in body.local_decls.iter_enumerated() { ++ let has_args = decl.ty.walk().filter_map(|arg| arg.as_type()).any(|t| matches!(t.kind(), ty::Adt(adt, _) if adt.did() == self.args)); ++ if has_args {assert!(uses.contains_key(&local), "unapproved Arguments value at {owner}");} ++ } ++ struct Uses(HashMap); ++ impl Visitor<'_> for Uses { ++ fn visit_local(&mut self, local: mir::Local, ctxt: PlaceContext, loc: mir::Location) { ++ use mir::visit::{MutatingUseContext as M, NonMutatingUseContext as N}; ++ if let Some(&(make, consume)) = self.0.get(&local) { ++ assert!(matches!(ctxt, PlaceContext::NonUse(NonUseContext::StorageLive | NonUseContext::StorageDead)) ++ || loc == make && ctxt == PlaceContext::MutatingUse(M::Call) ++ || loc == consume && ctxt == PlaceContext::NonMutatingUse(N::Move), ++ "literal Arguments escapes its approved calls: {loc:?} {ctxt:?}"); ++ } ++ } ++ } ++ Uses(uses).visit_body(body); ++ } ++} +diff --git a/src/rust_frontend/vf_mir_exporter/src/lib.rs b/src/rust_frontend/vf_mir_exporter/src/lib.rs +index 56e7d9e868cd20765f6ac82774293724c9fedf9c..4e3c15868cdf988f6e7f7f1c14176964801aeeb5 100644 +--- a/src/rust_frontend/vf_mir_exporter/src/lib.rs ++++ b/src/rust_frontend/vf_mir_exporter/src/lib.rs +@@ -49,11 +49,14 @@ use rustc_interface::interface::Compiler; + use rustc_interface::Config; + use rustc_middle::mir; +-use rustc_middle::ty::{self, TyCtxt}; ++use rustc_middle::ty::{self, TyCtxt, TypeVisitable}; + use rustc_session::Session; + use rustc_span::Span; + use std::cell::RefCell; +-use std::collections::HashMap; ++use std::collections::{HashMap, HashSet}; + use std::thread_local; + use tracing::{debug, error, info, trace, Level}; ++mod atomic_literal_panic; ++use atomic_literal_panic::LiteralPanic; ++use rustc_hir::def_id::DefId; + + #[derive(PartialEq)] +@@ -73,4 +76,13 @@ pub fn run_compiler() -> std::process::ExitCode { + //rustc_args.push("-Zverbose_internals".to_owned()); + let mut preprocess_mode = PreprocessMode::Preprocess; ++ let take_scope_option = |args: &mut Vec, prefix: &str| { ++ args.iter().position(|s| s.starts_with(prefix)).map(|i| args.remove(i)[prefix.len()..].to_owned()) ++ }; ++ let scope_roots = take_scope_option(&mut rustc_args, "--vf-rust-mir-exporter:roots="); ++ let scope_report = take_scope_option(&mut rustc_args, "--vf-rust-mir-exporter:scope-report="); ++ let literal_panic = rustc_args.iter().position(|s| s == "--vf-rust-mir-exporter:atomic-literal-panic").is_some_and(|i| { ++ rustc_args.remove(i); ++ true ++ }); + if let Some(index) = rustc_args.iter().position(|arg| arg == "--vf-rust-mir-exporter:preprocess-readonly") { + preprocess_mode = PreprocessMode::PreprocessReadOnly; +@@ -100,4 +112,7 @@ pub fn run_compiler() -> std::process::ExitCode { + + let mut callbacks = CompilerCalls { ++ scope_roots, ++ scope_report, ++ literal_panic, + source_files: Box::leak(Box::new(std::sync::Mutex::new(SourceFiles::new()))), + preprocess_mode, +@@ -105,5 +120,5 @@ pub fn run_compiler() -> std::process::ExitCode { + // Call the Rust compiler with our callbacks. + trace!("Calling the Rust Compiler with args: {:?}", rustc_args); +- rustc_driver::run_compiler(&rustc_args, &mut callbacks) ++ rustc_driver::compiler_entrypoint(&rustc_args, &mut callbacks) + }) + } +@@ -155,4 +170,5 @@ impl SourceFiles { + struct FileLoader { + read_only: bool, ++ crate_root: Option, + source_files: &'static std::sync::Mutex, + } +@@ -177,6 +193,8 @@ impl rustc_span::source_map::FileLoader for FileLoader { + let mut directives = Vec::new(); + let mut ghost_ranges = Vec::new(); +- let preprocessed_contents = +- preprocessor::preprocess(contents.as_str(), self.read_only, &mut directives, &mut ghost_ranges); ++ let is_crate_root = self.crate_root.as_deref() == Some(path.canonicalize()?.as_path()); ++ let preprocessed_contents = preprocessor::preprocess( ++ &contents, self.read_only, is_crate_root, &mut directives, &mut ghost_ranges, ++ ); + if self.read_only { + assert_eq!(preprocessed_contents, contents); +@@ -199,4 +217,7 @@ impl rustc_span::source_map::FileLoader for FileLoader { + + struct CompilerCalls { ++ scope_roots: Option, ++ scope_report: Option, ++ literal_panic: bool, + source_files: &'static std::sync::Mutex, + preprocess_mode: PreprocessMode, +@@ -213,4 +234,5 @@ impl rustc_driver::Callbacks for CompilerCalls { + config.file_loader = Some(Box::from(FileLoader { + read_only: self.preprocess_mode == PreprocessMode::PreprocessReadOnly, ++ crate_root: config.input.opt_path().map(|path| path.canonicalize().expect("crate root")), + source_files: self.source_files, + })); +@@ -243,18 +265,57 @@ impl rustc_driver::Callbacks for CompilerCalls { + }; + tcx.hir_visit_all_item_likes_in_crate(&mut visitor); ++ let literal_panic = self.literal_panic.then(|| { ++ assert!(self.scope_roots.is_some() && self.scope_report.is_some() && self.preprocess_mode == PreprocessMode::Preprocess, ++ "literal panic import requires a scoped verification with a report"); ++ LiteralPanic::new(tcx, &visitor) ++ }); ++ let mut resolved_calls = HashMap::new(); ++ let scoped_items = self.scope_roots.as_deref().map(|path| ++ select_call_closure(tcx, &mut visitor, path, self.scope_report.as_deref(), literal_panic, &mut resolved_calls)); + ++ let mut projections = ProjectionCheck { tcx, seen: HashSet::new(), depth: 0 }; ++ for id in visitor.structs.iter().chain(&visitor.ty_aliases) { ++ projections.declaration(id.to_def_id()); ++ } ++ for imp in &visitor.trait_impls { ++ projections.declaration(imp.def_id.to_def_id()); ++ tcx.impl_trait_ref(imp.def_id).instantiate_identity().skip_normalization().visit_with(&mut projections); ++ } ++ for id in tcx.all_traits_including_private().take_while(|id| id.is_local()) { ++ if scoped_items.as_ref().is_some_and(|items| !items.contains(&id)) { continue; } ++ projections.declaration(id); ++ for item in tcx.associated_items(id).in_definition_order() { ++ if item.kind.as_def_kind() == rustc_hir::def::DefKind::AssocFn ++ && scoped_items.as_ref().is_none_or(|items| items.contains(&item.def_id)) { ++ projections.declaration(item.def_id); ++ } ++ } ++ } + let mut bodies = Vec::new(); ++ // Both the crate-wide and nested HIR walks may visit the same definition. ++ // Two impls expanded from one macro have distinct DefIds even when their spans coincide. ++ let mut visited = std::collections::HashSet::new(); + // Trigger borrow checking of all bodies. + for (def_id, span) in visitor.bodies { ++ if !visited.insert(def_id) { ++ continue; ++ } + //let _ = tcx.optimized_mir(def_id); + let body = tcx.mir_drops_elaborated_and_const_checked(def_id); +- if body.is_stolen() { +- trace!("Skipping body for {}; it's already been stolen", tcx.def_path_str(def_id)); +- } else { +- bodies.push(( +- body.steal(), +- span, +- )) +- } ++ assert!(!body.is_stolen(), "MIR unavailable for requested body {}", tcx.def_path_str(def_id)); ++ // Subsequent const evaluation (including enum discriminants) still needs rustc's body. ++ let mut body = body.borrow().clone(); ++ projections.declaration(def_id.to_def_id()); ++ body.visit_with(&mut projections); // Includes constants and the original operands before scoped dispatch. ++ // Encode the very same instance followed by scoped traversal. Ordinary ++ // exports keep rustc's original trait operand and dispatch semantics. ++ for (bb, fn_ty) in resolved_calls.remove(&def_id).unwrap_or_default() { ++ fn_ty.visit_with(&mut projections); ++ let term = &mut body.basic_blocks_mut()[bb].terminator_mut().kind; ++ let (mir::TerminatorKind::Call { func, .. } | mir::TerminatorKind::TailCall { func, .. }) = term else { unreachable!() }; ++ let mir::Operand::Constant(op) = func else { panic!("Expected a direct scoped trait call") }; ++ op.const_ = mir::Const::Val(mir::ConstValue::ZeroSized, fn_ty); ++ } ++ bodies.push((body, span)); + } + +@@ -272,4 +333,6 @@ impl rustc_driver::Callbacks for CompilerCalls { + + let mut vf_mir_capnp_builder = vf_mir_builder::VfMirCapnpBuilder::new(tcx); ++ vf_mir_capnp_builder.scoped_items = scoped_items; ++ vf_mir_capnp_builder.literal_panic = literal_panic; + let mut directives = Vec::new(); + let mut ghost_ranges = Vec::new(); +@@ -337,4 +400,323 @@ struct TraitImplItemInfo { + } + ++// Scope a full Rust compilation by real HIR definition identity. Every direct ++// MIR call in a selected body is followed, including panic and cleanup edges. ++// Unsupported dispatch cannot certify a closed graph. ++fn select_call_closure<'tcx>(tcx: TyCtxt<'tcx>, items: &mut HirVisitor<'tcx>, path: &str, report: Option<&str>, literal_panic: Option, ++ resolved_calls: &mut HashMap)>>) ++ -> std::collections::HashSet { ++ use std::collections::{BTreeSet, HashMap, HashSet, VecDeque}; ++ use rustc_middle::mir::TerminatorKind; ++ use ty::TypeVisitable; ++ let name = |id| tcx.def_path(id).to_string_no_crate_verbose().trim_start_matches(':').to_owned(); ++ let roots = std::fs::read_to_string(path).expect("Cannot read MIR root list"); ++ let roots: BTreeSet<_> = roots.lines().map(str::trim).filter(|line| !line.is_empty() && !line.starts_with('#')).collect(); ++ assert!(!roots.is_empty(), "Missing MIR roots"); ++ let available: HashMap<_, _> = items.bodies.iter().map(|(id, _)| (name(id.to_def_id()), *id)).collect(); ++ let mut queue = VecDeque::new(); ++ let mut evidence = BTreeSet::new(); ++ for root in roots { ++ let id = *available.get(root).unwrap_or_else(|| panic!("MIR root not found: {root}")); ++ evidence.insert(format!("root\t{root}\t{}", tcx.def_path_str(id))); ++ queue.push_back(id); ++ } ++ let mut seen = HashSet::new(); ++ let mut types = ParticipatingTypes { tcx, pending: VecDeque::new() }; ++ while let Some(id) = queue.pop_front() { ++ if !seen.insert(id) { continue; } ++ assert!(literal_panic.and_then(|b| b.external_name(id.to_def_id())).is_none(), "a trusted boundary cannot be a proof root"); ++ let owner = name(id.to_def_id()); ++ types.pending.push_back(id.to_def_id()); ++ if let Some(decl) = tcx.trait_item_of(id) { ++ types.pending.push_back(decl); ++ } ++ evidence.insert(format!("body\t{owner}\t{}", tcx.def_path_str(id))); ++ if tcx.intrinsic(id.to_def_id()).is_some() ++ && matches!(tcx.hir_node_by_def_id(id), rustc_hir::Node::Item(item) if matches!(item.kind, rustc_hir::ItemKind::Fn { has_body: false, .. })) { ++ evidence.insert(format!("compiler-intrinsic\t{owner}")); ++ continue; ++ } ++ let cell = tcx.mir_drops_elaborated_and_const_checked(id); ++ let body = cell.borrow(); ++ if let Some(boundary) = literal_panic { ++ boundary.check_body(tcx, &owner, &body, &mut evidence); ++ } ++ // rustc's TypeVisitable derivation covers declarations, all blocks, places, ++ // rvalues, constants and the original FnDef operands (including their args). ++ body.visit_with(&mut types); ++ for (bb, block) in body.basic_blocks.iter_enumerated() { ++ let func = match &block.terminator().kind { ++ TerminatorKind::Call {func, ..} | TerminatorKind::TailCall {func, ..} => func, ++ TerminatorKind::InlineAsm {..} | TerminatorKind::Yield {..} | TerminatorKind::Drop {..} => ++ panic!("Unresolved effectful MIR terminator in scope at {owner}: {:?}", block.terminator().kind), ++ _ => continue, ++ }; ++ let fn_ty = func.ty(&body.local_decls, tcx); ++ let ty::FnDef(callee, args) = fn_ty.kind() else { ++ panic!("Unresolved indirect call in scope at {owner}: {fn_ty}"); ++ }; ++ let (callee, fn_ty) = if tcx.trait_of_assoc(*callee).is_some() { ++ types.pending.push_back(*callee); ++ let typing_env = ty::TypingEnv::post_analysis(tcx, id.to_def_id()); ++ let args = args.no_bound_vars().unwrap_or_else(|| panic!("Bound variables in scoped trait call at {owner}/{bb:?}: {fn_ty}")); ++ let Ok(Some(instance)) = ty::Instance::try_resolve(tcx, typing_env, *callee, args) else { ++ panic!("Unresolved scoped trait call at {owner}/{bb:?}: {fn_ty}"); ++ }; ++ let ty::InstanceKind::Item(item) = instance.def else { ++ panic!("Unsupported scoped trait dispatch at {owner}/{bb:?}: {instance:?}"); ++ }; ++ assert!(available.get(&name(item)).is_some_and(|local| local.to_def_id() == item), ++ "Unavailable scoped trait implementation at {owner}/{bb:?}: {instance:?}"); ++ let concrete = ty::Ty::new_fn_def(tcx, item, ty::Binder::dummy(instance.args)); ++ concrete.visit_with(&mut types); ++ resolved_calls.entry(id).or_default().push((bb, concrete)); ++ (item, concrete) ++ } else { ++ (*callee, fn_ty) ++ }; ++ let target = name(callee); ++ evidence.insert(format!("edge\t{owner}\t{target}\t{fn_ty}\t{bb:?}")); ++ if let Some(spec) = literal_panic.and_then(|b| b.external_name(callee)) { ++ evidence.insert(format!("trusted-literal-interface\t{owner}\t{target}\t{spec}")); ++ } else if let Some(next) = available.get(&target).filter(|next| next.to_def_id() == callee) { ++ queue.push_back(*next); ++ } else if tcx.lang_items().panic_impl() == Some(callee) ++ || (target == "panicking::panic_fmt::{extern#0}::panic_impl" ++ && tcx.crate_name(callee.krate).as_str() == "core" ++ && tcx.is_foreign_item(callee)) { ++ evidence.insert(format!("panic-runtime\t{target}")); ++ } else if target == "VeriFast_ghost_command" || target == "VeriFast_ghost_decl" { ++ assert!(callee.is_local(), "Ghost markers must belong to the compiling crate"); ++ evidence.insert(format!("ghost-marker\t{target}")); ++ } else { ++ panic!("Unresolved function in scope at {owner}: {target} ({:?})", tcx.def_kind(callee)); ++ } ++ } ++ } ++ items.bodies.retain(|(id, _)| seen.contains(id)); ++ // Retain every impl (including negative Send/Sync) for participating ADTs. ++ // Include the trait interfaces required by their types and by method bounds, ++ // without adding interfaces from unrelated crate items as fresh roots. ++ let mut impls_by_adt = HashMap::<_, Vec<_>>::new(); ++ for imp in &items.trait_impls { ++ impls_by_adt.entry(imp.self_ty).or_default().push(imp.def_id.to_def_id()); ++ } ++ let mut type_items = HashSet::new(); ++ while let Some(id) = types.pending.pop_front() { ++ if literal_panic.is_some_and(|b| id == b.args) {continue;} ++ if !type_items.insert(id) { continue; } ++ if let Some(impls) = impls_by_adt.get(&id) { ++ for &imp in impls { ++ // The encoded impl header can name further ADTs, even on a foreign self type. ++ tcx.impl_trait_ref(imp).instantiate_identity().skip_normalization().visit_with(&mut types); ++ for (clause, _) in tcx.clauses_of(imp).clauses { ++ clause.visit_with(&mut types); ++ } ++ } ++ } ++ if !id.is_local() { continue; } ++ let predicates = tcx.clauses_of(id); ++ if let Some(parent) = predicates.parent { types.pending.push_back(parent); } ++ for (clause, _) in predicates.clauses { ++ clause.visit_with(&mut types); ++ match clause.kind().skip_binder() { ++ ty::ClauseKind::Trait(bound) => { ++ types.pending.push_back(bound.trait_ref.def_id); ++ } ++ ty::ClauseKind::Projection(proj) => { ++ if let Some(tr) = tcx.trait_of_assoc(proj.projection_term.expect_projection_def_id()) { types.pending.push_back(tr); } ++ } ++ _ => {} ++ } ++ } ++ match tcx.def_kind(id) { ++ rustc_hir::def::DefKind::Fn | rustc_hir::def::DefKind::AssocFn => { ++ tcx.fn_sig(id).instantiate_identity().visit_with(&mut types); ++ } ++ rustc_hir::def::DefKind::Trait => { ++ evidence.insert(format!("trait\t{}", name(id))); ++ } ++ rustc_hir::def::DefKind::Struct | rustc_hir::def::DefKind::Union | rustc_hir::def::DefKind::Enum => { ++ for field in tcx.adt_def(id).all_fields() { ++ tcx.type_of(field.did).instantiate_identity().skip_normalization().visit_with(&mut types); ++ } ++ } ++ _ => {} ++ } ++ } ++ items.trait_impls.retain(|imp| type_items.contains(&imp.self_ty)); ++ items.structs.clear(); ++ items.ty_aliases.retain(|id| { ++ if name(id.to_def_id()) != "sync::atomic::AtomicU32" { return false; } ++ let ty = tcx.type_of(*id).instantiate_identity().skip_normalization(); ++ matches!(ty.kind(), ty::Adt(adt, _) if type_items.contains(&adt.did())) ++ }); ++ if let Some(path) = report { ++ std::fs::write(path, evidence.into_iter().collect::>().join("\n") + "\n").expect("write MIR scope report"); ++ } ++ type_items ++} ++ ++struct ParticipatingTypes<'tcx> { ++ tcx: TyCtxt<'tcx>, ++ pending: std::collections::VecDeque, ++} ++ ++impl<'tcx> ty::TypeVisitor> for ParticipatingTypes<'tcx> { ++ fn visit_ty(&mut self, t: ty::Ty<'tcx>) { ++ use ty::TypeSuperVisitable; ++ match t.kind() { ++ ty::Adt(adt, _) => self.pending.push_back(adt.did()), ++ ty::Alias(_, alias) => { ++ if let ty::AliasTyKind::Projection { def_id } = alias.kind { ++ self.pending.push_back(self.tcx.trait_of_assoc(def_id).expect("projection trait")); ++ } ++ } ++ _ => {} ++ } ++ t.super_visit_with(self); ++ } ++} ++ ++// Check each exported MIR body in its generic form, before value translation or normalization. ++struct ProjectionCheck<'tcx> { ++ tcx: TyCtxt<'tcx>, ++ seen: HashSet<(DefId, ty::GenericArgs<'tcx>)>, ++ depth: usize, ++} ++ ++impl<'tcx> ProjectionCheck<'tcx> { ++ fn literal(v: mir::ConstValue) -> bool { ++ matches!(v, mir::ConstValue::ZeroSized) || v.try_to_scalar_int().is_some() ++ } ++ ++ fn identity(tcx: TyCtxt<'tcx>, arg: ty::GenericArg<'tcx>) { ++ for part in arg.walk().filter_map(|arg| arg.as_type()) { ++ if matches!(part.kind(), ty::FnDef(..) | ty::FnPtr(..) | ty::Closure(..)) ++ || matches!(part.kind(), ty::Adt(adt, _) if adt.is_unsafe_cell() || adt.is_manually_drop()) { ++ tcx.dcx().fatal(format!("Unsupported erased Rust type in projection or generic substitution: {part} in {arg}")); ++ } ++ } ++ } ++ ++ fn alias_projection(tcx: TyCtxt<'tcx>, ty: ty::Ty<'tcx>, alias: ty::AliasTy<'tcx>) -> DefId { ++ use ty::AliasTyKind as A; ++ let id = match alias.kind { ++ A::Projection { def_id } => def_id, ++ A::Inherent { .. } | A::Opaque { .. } | A::Free { .. } => ++ tcx.dcx().fatal(format!("Unsupported type alias in MIR export: {ty}")), ++ }; ++ Self::projection(tcx, id, alias.args); ++ id ++ } ++ ++ fn projection(tcx: TyCtxt<'tcx>, id: DefId, args: ty::GenericArgs<'tcx>) { ++ let path = tcx.def_path(id).to_string_no_crate_verbose(); ++ if !(tcx.lang_items().sized_trait().is_some_and(|sized| sized.krate == id.krate) ++ && match path.as_str() { ++ "::intrinsics::bounds::BuiltinDeref::Pointee" | "::ptr::metadata::Pointee::Metadata" => true, ++ "::sync::atomic::AtomicPrimitive::Storage" => !matches!(args.type_at(0).kind(), ty::RawPtr(_, mir::Mutability::Not)), ++ _ => false, ++ }) { ++ tcx.dcx().fatal(format!("Unsupported associated-type projection: {} {args:?}", tcx.def_path_str(id))); ++ } ++ for arg in args { Self::identity(tcx, arg); } ++ } ++ ++ fn declaration(&mut self, id: DefId) { ++ self.item(id, ty::GenericArgs::identity_for_item(self.tcx, id)); ++ } ++ ++ fn item(&mut self, id: DefId, args: ty::GenericArgs<'tcx>) { ++ use rustc_hir::def::DefKind; ++ if !self.seen.insert((id, args)) { return; } ++ let tcx = self.tcx; ++ if !tcx.recursion_limit().value_within_limit(self.depth) { ++ tcx.dcx().fatal("Recursion limit in projection check"); ++ } ++ self.depth += 1; ++ for (index, arg) in args.iter().enumerate() { ++ Self::identity(tcx, arg); ++ if arg.as_const().is_some() { ++ // ConstKind::Param stores an index and a name. Its type lives on the declaration. ++ let param = tcx.generics_of(id).param_at(index, tcx); ++ tcx.type_of(param.def_id).instantiate(tcx, args).skip_normalization().visit_with(self); ++ } ++ } ++ let clauses = tcx.clauses_of(id).instantiate(tcx, args).clauses; ++ for clause in ty::elaborate::elaborate(tcx, clauses.into_iter().map(|c| c.skip_normalization())) { ++ if let ty::ClauseKind::Projection(p) = clause.kind().skip_binder() { ++ Self::projection(tcx, p.projection_term.expect_projection_def_id(), p.projection_term.args); ++ Self::identity(tcx, p.term.into()); ++ } ++ clause.visit_with(self); ++ } ++ match tcx.def_kind(id) { ++ DefKind::Fn | DefKind::AssocFn => tcx.fn_sig(id).instantiate(tcx, args).skip_normalization().visit_with(self), ++ DefKind::Struct | DefKind::Enum | DefKind::Union => { ++ for field in tcx.adt_def(id).all_fields() { ++ tcx.type_of(field.did).instantiate(tcx, args).skip_normalization().visit_with(self); ++ } ++ } ++ DefKind::TyAlias => tcx.type_of(id).instantiate(tcx, args).skip_normalization().visit_with(self), ++ _ => {} ++ } ++ self.depth -= 1; ++ } ++} ++ ++impl<'tcx> ty::TypeVisitor> for ProjectionCheck<'tcx> { ++ fn visit_const(&mut self, c: ty::Const<'tcx>) { ++ use ty::{ConstKind as C, TypeSuperVisitable}; ++ let tcx = self.tcx; ++ match c.kind() { ++ C::Value(_) | C::Param(_) => {} ++ C::Alias(_, ty::AliasConst { kind: ty::AliasConstKind::Anon { def_id }, .. }) ++ if tcx.const_eval_poly(def_id).is_ok() => { ++ if let Some((value, ty)) = tcx.trivial_const(def_id) { ++ if !Self::literal(value) { tcx.dcx().fatal(format!("Unsupported constant in MIR export: {c}")); } ++ ty.visit_with(self); ++ } else { ++ let body = tcx.mir_for_ctfe(def_id); ++ use mir::TerminatorKind as T; ++ if !body.basic_blocks.iter().all(|bb| matches!(bb.terminator().kind, ++ T::Return | T::Goto { .. } | T::SwitchInt { .. } | T::Assert { .. } | T::Unreachable)) { ++ tcx.dcx().fatal(format!("Unsupported anonymous constant body in MIR export: {c}")); ++ } ++ mir::visit::Visitor::visit_body(self, body); ++ body.visit_with(self); ++ } ++ } ++ C::Alias(..) | C::Expr(..) | C::Placeholder(..) | C::Infer(..) | C::Bound(..) | C::Error(..) => ++ tcx.dcx().fatal(format!("Unsupported constant in MIR export: {c}")), ++ } ++ c.super_visit_with(self); ++ } ++ ++ fn visit_ty(&mut self, ty: ty::Ty<'tcx>) { ++ use ty::TypeSuperVisitable; ++ match *ty.kind() { ++ ty::Alias(_, alias) => { Self::alias_projection(self.tcx, ty, alias); } ++ ty::Adt(adt, args) => self.item(adt.did(), args), ++ ty::FnDef(id, args) => self.item(id, args.no_bound_vars().unwrap_or_else(|| ++ self.tcx.dcx().fatal("Bound FnDef arguments in projection check"))), ++ _ => {} ++ } ++ ty.super_visit_with(self); ++ } ++} ++ ++// CTFE can succeed through a call, a named MIR constant or a pointer to another allocation. ++// Check its MIR inputs separately from the types and substitutions visited by TypeVisitor. ++impl<'tcx> mir::visit::Visitor<'tcx> for ProjectionCheck<'tcx> { ++ fn visit_const_operand(&mut self, op: &mir::ConstOperand<'tcx>, _: mir::Location) { ++ match op.const_ { ++ mir::Const::Ty(..) => {} // Checked by body.visit_with(self). ++ mir::Const::Val(v, _) if Self::literal(v) => {} ++ _ => self.tcx.dcx().fatal(format!("Unsupported anonymous constant operand in MIR export: {}", op.const_)), ++ } ++ } ++} ++ + struct TraitImplInfo { + def_id: LocalDefId, +@@ -378,37 +760,28 @@ impl<'tcx> rustc_hir::intravisit::Visitor<'tcx> for HirVisitor<'tcx> { + if let Some(trait_impl_header) = &impl_.of_trait { + if let Some(of_trait) = trait_impl_header.trait_ref.trait_def_id() { +- if let rustc_hir::TyKind::Path(rustc_hir::QPath::Resolved( +- None, +- self_ty_path, +- )) = impl_.self_ty.kind +- { +- if let rustc_hir::def::Res::Def( +- rustc_hir::def::DefKind::Struct, +- self_ty, +- ) = self_ty_path.res +- { +- let mut items = Vec::::new(); +- for item_id in impl_.items { +- let item = self.tcx.hir_impl_item(*item_id); +- items.push( +- TraitImplItemInfo { +- name: item.ident.to_string(), +- def_id: self.tcx.def_path_str(item_id.owner_id.to_def_id()) +- } +- ); +- } +- self.trait_impls.push(TraitImplInfo { +- def_id: item.owner_id.def_id, +- span: item.span, +- is_unsafe: trait_impl_header.safety == rustc_hir::Safety::Unsafe, +- is_negative: match trait_impl_header.polarity { +- rustc_hir::ImplPolarity::Negative(_) => true, +- _ => false, +- }, +- of_trait, +- self_ty, +- items, +- }); ++ let self_ty = self.tcx.impl_trait_ref(item.owner_id.def_id).instantiate_identity().skip_normalization().self_ty(); ++ if let ty::Adt(adt, _) = self_ty.kind() { ++ let mut items = Vec::::new(); ++ for item_id in impl_.items { ++ let item = self.tcx.hir_impl_item(*item_id); ++ items.push( ++ TraitImplItemInfo { ++ name: item.ident.to_string(), ++ def_id: self.tcx.def_path_str(item_id.owner_id.to_def_id()) ++ } ++ ); + } ++ self.trait_impls.push(TraitImplInfo { ++ def_id: item.owner_id.def_id, ++ span: item.span, ++ is_unsafe: trait_impl_header.safety == rustc_hir::Safety::Unsafe, ++ is_negative: match trait_impl_header.polarity { ++ rustc_hir::ImplPolarity::Negative(_) => true, ++ _ => false, ++ }, ++ of_trait, ++ self_ty: adt.did(), ++ items, ++ }); + } + } +@@ -594,13 +967,11 @@ use rustc_span::RemapPathScopeComponents; + body_span = header_span.to(body_span); + } +- let mut mod_annots: LinkedList> = self ++ // A child declared with `mod atomic;` lives in a different source ++ // file. Let it claim its own globals before slicing the parent span. ++ let mod_submodules = collect_submodules(self.tcx, self.annots, n); ++ let mod_annots: LinkedList> = self + .annots + .extract_if(|annot| body_span.contains(annot.span().unwrap())) + .collect(); +- let mod_submodules = collect_submodules( +- self.tcx, +- &mut mod_annots, +- n, +- ); + self.submodules.push(Box::new(Module { + name, +@@ -630,4 +1001,5 @@ use rustc_span::RemapPathScopeComponents; + } + struct EncCtx<'tcx, 'a> { ++ literal_panic: Option, + req_adts: Vec>, + tcx: TyCtxt<'tcx>, +@@ -640,4 +1012,5 @@ use rustc_span::RemapPathScopeComponents; + pub fn new( + tcx: TyCtxt<'tcx>, ++ literal_panic: Option, + mode: EncKind<'tcx, 'a>, + annots: LinkedList>, +@@ -645,4 +1018,5 @@ use rustc_span::RemapPathScopeComponents; + ) -> Self { + Self { ++ literal_panic, + req_adts: Vec::new(), + tcx, +@@ -671,4 +1045,6 @@ use rustc_span::RemapPathScopeComponents; + pub struct VfMirCapnpBuilder<'tcx> { + tcx: TyCtxt<'tcx>, ++ pub(super) literal_panic: Option, ++ pub(super) scoped_items: Option>, + directives: Vec>, + structs: Vec, +@@ -683,4 +1059,6 @@ use rustc_span::RemapPathScopeComponents; + VfMirCapnpBuilder { + tcx, ++ literal_panic: None, ++ scoped_items: None, + directives: Vec::new(), + structs: Vec::new(), +@@ -734,5 +1112,5 @@ use rustc_span::RemapPathScopeComponents; + + fn encode_trait_impls(&mut self, vf_mir_cpn: &mut vf_mir_cpn::Builder<'_>) { +- let mut enc_ctx = EncCtx::new(self.tcx, EncKind::Other, LinkedList::new(), Vec::new()); ++ let mut enc_ctx = EncCtx::new(self.tcx, self.literal_panic, EncKind::Other, LinkedList::new(), Vec::new()); + vf_mir_cpn.fill_trait_impls(&self.trait_impls, |mut trait_impl_cpn, trait_impl| { + trace!("Encoding trait impl"); +@@ -777,5 +1155,5 @@ use rustc_span::RemapPathScopeComponents; + mut vf_mir_cpn: vf_mir_cpn::Builder<'_>, + ) { +- let mut enc_ctx = EncCtx::new(self.tcx, EncKind::Adt, LinkedList::new(), Vec::new()); ++ let mut enc_ctx = EncCtx::new(self.tcx, self.literal_panic, EncKind::Adt, LinkedList::new(), Vec::new()); + let mut traits_cpn = vf_mir_cpn.reborrow().init_traits(); + for trait_def_id in self.tcx.all_traits_including_private() { +@@ -783,4 +1161,5 @@ use rustc_span::RemapPathScopeComponents; + break; // We assume that the local crate's traits come first. + } ++ if self.scoped_items.as_ref().is_some_and(|set| !set.contains(&trait_def_id)) { continue; } + let mut traits_cons_cpn = traits_cpn.init_cons(); + let mut trait_cpn = traits_cons_cpn.reborrow().init_h(); +@@ -793,4 +1172,8 @@ use rustc_span::RemapPathScopeComponents; + .in_definition_order() + { ++ // Scoped calls use the resolved concrete body. Export the abstract ++ // contract for each selected trait method or implementation, even ++ // if the call's original and resolved generic arguments differ. ++ if self.scoped_items.as_ref().is_some_and(|set| !set.contains(&item.def_id)) { continue; } + if item.kind.as_def_kind() == rustc_hir::def::DefKind::AssocFn { + let hir_item = self.tcx.hir_expect_trait_item(item.def_id.expect_local()); +@@ -825,5 +1208,5 @@ use rustc_span::RemapPathScopeComponents; + ty::BoundRegionKind::Named( + def_id, +- ) => self.tcx.item_name(def_id).to_string(), ++ ) => Self::named_lifetime(self.tcx, def_id), + ty::BoundRegionKind::NamedForPrinting(name) => name.to_string(), + ty::BoundRegionKind::ClosureEnv => todo!(), +@@ -918,5 +1301,5 @@ use rustc_span::RemapPathScopeComponents; + ty_alias_cpn.reborrow().init_span(), + ); +- let mut enc_ctx = EncCtx::new(self.tcx, EncKind::Adt, LinkedList::new(), Vec::new()); ++ let mut enc_ctx = EncCtx::new(self.tcx, self.literal_panic, EncKind::Adt, LinkedList::new(), Vec::new()); + ty_alias_cpn.fill_generics( + &self.tcx.generics_of(ty_alias.to_def_id()).own_params, +@@ -961,5 +1344,5 @@ use rustc_span::RemapPathScopeComponents; + annot.span().unwrap().data().hi + }).collect::>(); +- let mut enc_ctx = EncCtx::new(self.tcx, EncKind::Body(body), annots, mut_annots); ++ let mut enc_ctx = EncCtx::new(self.tcx, self.literal_panic, EncKind::Body(body), annots, mut_annots); + Self::encode_body(&mut enc_ctx, body_cpn); + req_adt_defs.extend(enc_ctx.get_req_adts()); +@@ -1012,10 +1395,14 @@ use rustc_span::RemapPathScopeComponents; + req_adt_defs = Vec::new(); + for adt_def in it { +- if adt_def.is_unsafe_cell() ++ if self.literal_panic.is_some_and(|b| b.args == adt_def.did()) ++ || adt_def.is_unsafe_cell() + || adt_def.is_manually_drop() ++ || self.tcx.lang_items().non_null_trait() == Some(adt_def.did()) + || !adt_def.did().is_local() + { + continue; + } ++ assert!(self.scoped_items.as_ref().is_none_or(|items| items.contains(&adt_def.did())), ++ "Unaccounted ADT in scoped export: {}", self.tcx.def_path_str(adt_def.did())); + match encoded_adt_defs + .iter() +@@ -1026,5 +1413,5 @@ use rustc_span::RemapPathScopeComponents; + let adt_def_cpn = adt_defs_cons_cpn.reborrow().init_h(); + let mut enc_ctx = +- EncCtx::new(self.tcx, EncKind::Adt, LinkedList::new(), Vec::new()); ++ EncCtx::new(self.tcx, self.literal_panic, EncKind::Adt, LinkedList::new(), Vec::new()); + Self::encode_adt_def(self.tcx, &mut enc_ctx, &adt_def, adt_def_cpn); + req_adt_defs.extend(enc_ctx.get_req_adts()); +@@ -1044,5 +1431,17 @@ use rustc_span::RemapPathScopeComponents; + mut adt_did_cpn: adt_def_id_cpn::Builder<'_>, + ) { +- adt_did_cpn.set_name(&enc_ctx.tcx.def_path_str(adt_did)); ++ // The UnsafeCell lang item is interpreted by the frontend even when ++ // we are compiling core itself and rustc prints a crate-local path. ++ if enc_ctx.literal_panic.is_some_and(|b| b.args == adt_did) { ++ adt_did_cpn.set_name("std::fmt::Arguments"); ++ } else if enc_ctx.tcx.adt_def(adt_did).is_unsafe_cell() { ++ adt_did_cpn.set_name("std::cell::UnsafeCell"); ++ } else if enc_ctx.tcx.adt_def(adt_did).is_manually_drop() { ++ adt_did_cpn.set_name("std::mem::ManuallyDrop"); ++ } else if enc_ctx.tcx.lang_items().non_null_trait() == Some(adt_did) { ++ adt_did_cpn.set_name("std::ptr::NonNull"); ++ } else { ++ adt_did_cpn.set_name(&enc_ctx.tcx.def_path_str(adt_did)); ++ } + } + +@@ -1062,5 +1461,5 @@ use rustc_span::RemapPathScopeComponents; + let mut variant_index = 0; + adt_def_cpn.fill_variants(adt_def.variants(), |variant_cpn, variant| { +- Self::encode_variant_def(tcx, enc_ctx, variant_index, variant, variant_cpn); ++ Self::encode_variant_def(tcx, enc_ctx, *adt_def, variant_index, variant, variant_cpn); + variant_index += 1; + }); +@@ -1122,4 +1521,5 @@ use rustc_span::RemapPathScopeComponents; + tcx: TyCtxt<'tcx>, + enc_ctx: &mut EncCtx<'tcx, 'a>, ++ adt: ty::AdtDef<'tcx>, + variant_index: u32, + vdef: &ty::VariantDef, +@@ -1135,11 +1535,8 @@ use rustc_span::RemapPathScopeComponents; + Self::encode_field_def(tcx, enc_ctx, field, field_cpn); + }); +- match vdef.discr { +- ty::VariantDiscr::Explicit(_) => todo!(), +- ty::VariantDiscr::Relative(discr) => { +- if discr != variant_index { +- todo!() +- } +- } ++ if adt.is_enum() { ++ let discr = adt.discriminant_for_variant(tcx, rustc_abi::VariantIdx::from_u32(variant_index)); ++ Self::encode_integer_type(adt.repr().discr_type(), vdef_cpn.reborrow().init_discriminant_ty()); ++ capnp_utils::encode_u_int128(discr.val, vdef_cpn.reborrow().init_discriminant_bits()); + } + } +@@ -1253,4 +1650,13 @@ use rustc_span::RemapPathScopeComponents; + } + ++ fn named_lifetime(tcx: TyCtxt<'tcx>, id: rustc_hir::def_id::DefId) -> String { ++ let symbol = tcx.item_name(id); ++ if symbol.as_str() == "'_" { ++ Self::anonymous_late_bound_lifetime_name(id.index.as_usize()) ++ } else { ++ symbol.to_string() ++ } ++ } ++ + fn encode_generic_param_def( + generic_param: &GenericParamDef, +@@ -1282,4 +1688,8 @@ use rustc_span::RemapPathScopeComponents; + + let def_id = body.source.def_id(); ++ let is_intrinsic_declaration = tcx.intrinsic(def_id).is_some() ++ && matches!(tcx.hir_node_by_def_id(def_id.expect_local()), ++ hir::Node::Item(item) if matches!(item.kind, hir::ItemKind::Fn { has_body: false, .. })); ++ body_cpn.set_is_intrinsic_declaration(is_intrinsic_declaration); + + let kind = tcx.def_kind(def_id); +@@ -1840,5 +2250,5 @@ use rustc_span::RemapPathScopeComponents; + ty::TyKind::Adt(adt_def, substs) => { + let adt_ty_cpn = ty_kind_cpn.init_adt(); +- Self::encode_ty_adt(tcx, enc_ctx, *adt_def, substs, adt_ty_cpn); ++ Self::encode_ty_adt(tcx, enc_ctx, *adt_def, *substs, adt_ty_cpn); + } + ty::TyKind::Foreign(_) => ty_kind_cpn.set_foreign(()), +@@ -1899,11 +2309,6 @@ use rustc_span::RemapPathScopeComponents; + ty::TyKind::Alias(_is_rigid, alias_ty) => { + let mut alias_ty_cpn = ty_kind_cpn.init_alias(); +- let (kind_cpn, alias_def_id) = match alias_ty.kind { +- ty::AliasTyKind::Projection { def_id } => (crate::vf_mir_capnp::AliasTyKind::Projection, def_id), +- ty::AliasTyKind::Inherent { def_id } => (crate::vf_mir_capnp::AliasTyKind::Inherent, def_id), +- ty::AliasTyKind::Opaque { def_id } => (crate::vf_mir_capnp::AliasTyKind::Opaque, def_id), +- ty::AliasTyKind::Free { def_id } => (crate::vf_mir_capnp::AliasTyKind::Free, def_id), +- }; +- alias_ty_cpn.set_kind(kind_cpn); ++ let alias_def_id = super::ProjectionCheck::alias_projection(tcx, ty, *alias_ty); ++ alias_ty_cpn.set_kind(crate::vf_mir_capnp::AliasTyKind::Projection); + alias_ty_cpn.set_def_id(&tcx.def_path_str(alias_def_id)); + alias_ty_cpn.fill_args(alias_ty.args, |arg_cpn, arg| { +@@ -1911,4 +2316,7 @@ use rustc_span::RemapPathScopeComponents; + }); + } ++ ty::TyKind::View(..) => { ++ unimplemented!("exporting a Rust view type: {ty:?}") ++ } + ty::TyKind::Param(param_ty) => { + ty_kind_cpn.set_param(¶m_ty.to_string()); +@@ -1959,5 +2367,5 @@ use rustc_span::RemapPathScopeComponents; + enc_ctx: &mut EncCtx<'tcx, 'a>, + adt_def: ty::AdtDef<'tcx>, +- substs: &'tcx &'tcx ty::List>, ++ substs: ty::GenericArgs<'tcx>, + mut adt_ty_cpn: adt_ty_cpn::Builder<'_>, + ) { +@@ -2008,8 +2416,9 @@ use rustc_span::RemapPathScopeComponents; + enc_ctx: &mut EncCtx<'tcx, 'a>, + def_id: &hir::def_id::DefId, +- substs: ty::GenericArgsRef<'tcx>, ++ substs: ty::GenericArgs<'tcx>, + mut fn_def_ty_cpn: fn_def_ty_cpn::Builder<'_>, + ) { +- let def_path = tcx.def_path_str(*def_id); ++ let def_path = enc_ctx.literal_panic.and_then(|b| b.external_name(*def_id)) ++ .map(str::to_owned).unwrap_or_else(|| tcx.def_path_str(*def_id)); + let late_bound_generic_param_count = + tcx.fn_sig(*def_id).skip_binder().bound_vars().len(); +@@ -2046,11 +2455,5 @@ use rustc_span::RemapPathScopeComponents; + } + ty::BoundRegionKind::Named(def_id) => { +- let symbol = tcx.item_name(def_id); +- if symbol.as_str() == "'_" { +- let id = Self::anonymous_late_bound_lifetime_name(def_id.index.as_usize()); +- region_cpn.set_id(&id); +- } else { +- region_cpn.set_id(symbol.as_str()); +- } ++ region_cpn.set_id(&Self::named_lifetime(tcx, def_id)); + } + ty::BoundRegionKind::NamedForPrinting(name) => region_cpn.set_id(name.as_str()), +@@ -2074,4 +2477,9 @@ use rustc_span::RemapPathScopeComponents; + gen_arg_cpn: gen_arg_cpn::Builder<'_>, + ) { ++ // Value translation erases some identities in proof substitutions. ++ // Impl headers carry their nominal rustc self type and arguments. ++ if !matches!(enc_ctx.mode, EncKind::Other) { ++ super::ProjectionCheck::identity(tcx, gen_arg); ++ } + debug!("Encoding generic arg {:?}", gen_arg); + let kind_cpn = gen_arg_cpn.init_kind(); +@@ -2278,4 +2686,24 @@ use rustc_span::RemapPathScopeComponents; + mir::Rvalue::RawPtr(raw_ptr_kind, place) => { + let mut raw_ptr_data_cpn = rvalue_cpn.init_raw_ptr(); ++ // UnsafeCell::get is a provenance primitive in VeriFast's aliasing model. ++ // Mark only its raw address of the actual receiver, never a caller's cast. ++ let body = enc_ctx.body(); ++ let did = body.source.def_id(); ++ if *raw_ptr_kind == mir::RawPtrKind::Const ++ && place.local == mir::Local::from_usize(1) ++ && matches!(place.projection.as_slice(), [mir::ProjectionElem::Deref]) ++ && tcx.def_kind(did) == rustc_hir::def::DefKind::AssocFn ++ && tcx.item_name(did).as_str() == "get" ++ && tcx.impl_of_assoc(did).is_some_and(|imp| { ++ !tcx.impl_is_of_trait(imp) ++ && matches!(tcx.type_of(imp).instantiate_identity().skip_normalization().kind(), ++ ty::Adt(adt, _) if adt.is_unsafe_cell()) ++ }) ++ && matches!(body.local_decls[place.local].ty.kind(), ++ ty::Ref(_, inner, mir::Mutability::Not) ++ if matches!(inner.kind(), ty::Adt(adt, _) if adt.is_unsafe_cell())) ++ { ++ raw_ptr_data_cpn.set_unsafe_cell_get_receiver(true); ++ } + let mutability_cpn = raw_ptr_data_cpn.reborrow().init_mutability(); + Self::encode_mutability(match raw_ptr_kind { +@@ -2312,4 +2740,12 @@ use rustc_span::RemapPathScopeComponents; + mir::Rvalue::BinaryOp(bin_op, (operandl, operandr)) => { + let mut bin_op_data_cpn = rvalue_cpn.init_binary_op(); ++ if matches!(bin_op, mir::BinOp::Lt | mir::BinOp::Le | mir::BinOp::Gt | mir::BinOp::Ge | mir::BinOp::Eq | mir::BinOp::Ne) { ++ let body = enc_ctx.body(); ++ let thin = [operandl, operandr].iter().all(|op| match op.ty(&body.local_decls, tcx).kind() { ++ ty::RawPtr(pointee, _) => pointee.is_sized(tcx, body.typing_env(tcx)), ++ _ => true, ++ }); ++ bin_op_data_cpn.set_comparison_operands_thin(thin); ++ } + let bin_op_cpn = bin_op_data_cpn.reborrow().init_operator(); + Self::encode_bin_op(*bin_op, bin_op_cpn); +@@ -2332,5 +2768,9 @@ use rustc_span::RemapPathScopeComponents; + let body = enc_ctx.body(); + let ty = place.ty(body, tcx); +- let adt_def = ty.ty.ty_adt_def().unwrap(); ++ let Some(adt_def) = ty.ty.ty_adt_def() else { ++ Self::encode_ty(tcx, enc_ctx, ty.ty, discriminant_data_cpn.reborrow().init_abstract_operand().init_something()); ++ Self::encode_place(enc_ctx, place, discriminant_data_cpn.init_place()); ++ return; ++ }; + let variants_count = adt_def.variants().len(); + +@@ -2363,5 +2803,5 @@ use rustc_span::RemapPathScopeComponents; + fn encode_ty_args( + enc_ctx: &mut EncCtx<'tcx, 'a>, +- targs: &ty::List>, ++ targs: ty::GenericArgs<'tcx>, + mut targs_cpn: capnp::struct_list::Builder<'_, gen_arg_cpn::Owned>, + ) { +@@ -2415,5 +2855,5 @@ use rustc_span::RemapPathScopeComponents; + + let gen_args_cpn = adt_data_cpn.reborrow().init_gen_args(gen_args.len()); +- Self::encode_ty_args(enc_ctx, gen_args, gen_args_cpn); ++ Self::encode_ty_args(enc_ctx, *gen_args, gen_args_cpn); + } + mir::AggregateKind::Closure(def_id, gen_args) => { +@@ -2457,5 +2897,13 @@ use rustc_span::RemapPathScopeComponents; + mir::BinOp::Gt => bin_op_cpn.set_gt(()), + mir::BinOp::Offset => bin_op_cpn.set_offset(()), +- _ => todo!(), ++ mir::BinOp::AddUnchecked => bin_op_cpn.set_add_unchecked(()), ++ mir::BinOp::SubUnchecked => bin_op_cpn.set_sub_unchecked(()), ++ mir::BinOp::MulUnchecked => bin_op_cpn.set_mul_unchecked(()), ++ mir::BinOp::ShlUnchecked => bin_op_cpn.set_shl_unchecked(()), ++ mir::BinOp::ShrUnchecked => bin_op_cpn.set_shr_unchecked(()), ++ mir::BinOp::AddWithOverflow => bin_op_cpn.set_add_with_overflow(()), ++ mir::BinOp::SubWithOverflow => bin_op_cpn.set_sub_with_overflow(()), ++ mir::BinOp::MulWithOverflow => bin_op_cpn.set_mul_with_overflow(()), ++ mir::BinOp::Cmp => bin_op_cpn.set_cmp(()), + } + } +@@ -2488,5 +2936,5 @@ use rustc_span::RemapPathScopeComponents; + ) { + match terminator_kind { +- mir::TerminatorKind::Goto { target } => { ++ mir::TerminatorKind::Goto { target, .. } => { + let target_cpn = terminator_kind_cpn.init_goto(); + Self::encode_basic_block_id(*target, target_cpn); +@@ -2798,5 +3246,5 @@ use rustc_span::RemapPathScopeComponents; + let mut value_cpn = const_kind_cpn.init_value(); + Self::encode_ty(tcx, enc_ctx, value.ty, value_cpn.reborrow().init_ty()); +- Self::encode_val_tree(tcx, enc_ctx, &value.valtree, value_cpn.init_val_tree()); ++ Self::encode_val_tree(tcx, enc_ctx, *value, value_cpn.init_val_tree()); + } + // A placeholder for a const which could not be computed; this is +@@ -2807,12 +3255,39 @@ use rustc_span::RemapPathScopeComponents; + } + ++ fn unit_enum_variant( ++ tcx: TyCtxt<'tcx>, ++ value: ty::Value<'tcx>, ++ children: &[ty::Const<'tcx>], ++ ) -> Option<(rustc_span::Symbol, u32, i32)> { ++ let ty::Adt(def, args) = value.ty.kind() else { return None }; ++ let [index] = children else { return None }; ++ let index = index.try_to_value()?; ++ if !def.is_enum() || !args.is_empty() || index.ty != tcx.types.u32 { ++ return None; ++ } ++ let ordinal = index.try_to_leaf()?.to_u32(); ++ let variant = rustc_abi::VariantIdx::from_u32(ordinal); ++ let info = def.variant(variant); ++ if !info.fields.is_empty() { ++ return None; ++ } ++ let discr = def.discriminant_for_variant(tcx, variant); ++ let (size, signed) = discr.ty.int_size_and_signed(tcx); ++ let number = if signed { ++ i32::try_from(size.sign_extend(discr.val) as i128) ++ } else { ++ i32::try_from(discr.val) ++ }.ok()?; ++ Some((info.name, ordinal, number)) ++ } ++ + fn encode_val_tree( + tcx: TyCtxt<'tcx>, + enc_ctx: &mut EncCtx<'tcx, 'a>, +- val_tree: &ty::ValTree<'tcx>, ++ value: ty::Value<'tcx>, + mut val_tree_cpn: val_tree_cpn::Builder<'_>, + ) { + use ty::ValTreeKind as VT; +- match **val_tree { ++ match *value.valtree { + // Used only for types with `layout::abi::Scalar` ABI and ZSTs. + VT::Leaf(scalar_int) => { +@@ -2820,6 +3295,14 @@ use rustc_span::RemapPathScopeComponents; + Self::encode_scalar_int(tcx, scalar_int, scalar_int_cpn); + } +- // Used only for `&[u8]` and `&str` + VT::Branch(children) => { ++ // rustc prepends the variant *index*, even for enums with explicit discriminants. ++ // Leave data-carrying and out-of-range variants in their original structural form. ++ if let Some((name, ordinal, discr)) = Self::unit_enum_variant(tcx, value, children.as_slice()) { ++ let mut variant_cpn = val_tree_cpn.init_unit_variant(); ++ variant_cpn.set_name(name.as_str()); ++ variant_cpn.set_ordinal(ordinal); ++ variant_cpn.set_discriminant(discr); ++ return; ++ } + val_tree_cpn.fill_branch(children.iter(), |child_cpn, child| { + Self::encode_typesystem_constant(tcx, enc_ctx, &child, child_cpn); +diff --git a/src/rust_frontend/vf_mir_exporter/src/preprocessor.rs b/src/rust_frontend/vf_mir_exporter/src/preprocessor.rs +index 4c5ca4f2fad47e0341216b13e8b497bdfeafa440..e29c9299eecfeccb8632c7bdfa00763edf4128c2 100644 +--- a/src/rust_frontend/vf_mir_exporter/src/preprocessor.rs ++++ b/src/rust_frontend/vf_mir_exporter/src/preprocessor.rs +@@ -153,4 +153,5 @@ pub fn preprocess( + input: &str, + read_only: bool, ++ is_crate_root: bool, + directives: &mut Vec>, + ghost_ranges: &mut Vec>, +@@ -204,5 +205,5 @@ pub fn preprocess( + ); + } +- if !read_only { ++ if !read_only && is_crate_root { + output.push_str("\n\nconst fn VeriFast_ghost_command() {}\nfn VeriFast_alloc() -> *mut T { VeriFast_alloc() }\nfn VF_free(_ptr: *mut T) {}\n"); + } +@@ -736,8 +737,9 @@ pub fn preprocess( + } + cs.pos.byte_pos -= src_len as u32; +- output.push_str("VeriFast_alloc :: <"); ++ let prefix = "crate::VeriFast_alloc::<"; ++ output.push_str(prefix); + output.push_str(type_expr); + output.push_str(">("); +- let output_len = "VeriFast_alloc :: <".len() + type_expr.len() + ">()".len(); ++ let output_len = prefix.len() + type_expr.len() + ">()".len(); + cs.pos.byte_pos += output_len as u32; + for _ in 0..src_len as i32 - output_len as i32 { +@@ -770,9 +772,9 @@ pub fn preprocess( + cs.next(); + } +- output.push_str("VF_free("); ++ output.push_str("crate::VF_free("); + output.push_str(ptr_expr); + // " as *mut u8, Layout::new::<" +- // " as *mut u8 as *mut " +- output.push_str(" as *mut u8 as *mut "); ++ // The qualified helper adds seven bytes before ptr_expr. ++ output.push_str(" as *mut u8 as *mut "); + output.push_str(type_expr); + output.push_str(" )"); +diff --git a/src/rust_frontend/vf_mir_translator/rust_parser.ml b/src/rust_frontend/vf_mir_translator/rust_parser.ml +index c1a1530d595c298535e5000f58e2d9d79500f678..960e0a105f62f577ca3c4e9e82cfe7ee0b356f39 100644 +--- a/src/rust_frontend/vf_mir_translator/rust_parser.ml ++++ b/src/rust_frontend/vf_mir_translator/rust_parser.ml +@@ -1017,8 +1017,15 @@ let own_pred_decls_for_enum l en ctors tparams = + own_pred_decls @ [own_pred_def] + ++let parse_impl_receiver stream = ++ let qualifier = match Lexer.Stream.npeek 4 stream with ++ | [_, Ident _; _, Kwd "<"; _, Kwd "*"; _, Kwd ("mut" | "const" as q)] -> Some q ++ | _ -> None ++ in ++ parse_type stream, qualifier ++ + let parse_decls parse_rsspec_file = + let rec parse_impl_rest l tparams = function%parser + [ +- parse_type as tp; ++ [%let tp, qualifier = parse_impl_receiver]; + [%let forClause = function%parser + [ (_, Kwd "for"); parse_type as tp ] -> Some tp +@@ -1036,9 +1043,13 @@ let rec parse_impl_rest l tparams = function%parser + | _ -> static_error (type_expr_loc tp) "This form of type is not supported here" None + in ++ let arg_names = match qualifier, targs with ++ | Some q, [PtrTypeExpr (_, elem)] -> ["*" ^ q ^ " " ^ string_of_type_expr elem] ++ | _ -> List.map string_of_type_expr targs ++ in + let tpText = + if String.index_opt x ':' = None then +- x ^ (if targs = [] then "" else "::<" ^ String.concat ", " (List.map string_of_type_expr targs) ^ ">") ++ x ^ (if targs = [] then "" else "::<" ^ String.concat ", " arg_names ^ ">") + else +- Printf.sprintf ">" x (String.concat ", " (List.map string_of_type_expr targs)) ++ Printf.sprintf ">" x (String.concat ", " arg_names) + in + let prefix = match forClause with None -> tpText | Some tp -> Printf.sprintf "<%s as %s>" tpText (string_of_type_expr tp) in +diff --git a/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml b/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml +index 2cb793efc4fcbe91184f3cb500accfaf627868ce..3223d542c13c050c0a4e7cfd9c6c5fee2c8ebc3a 100644 +--- a/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml ++++ b/src/rust_frontend/vf_mir_translator/vf_mir_translator.ml +@@ -881,10 +881,5 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + targs + |> List.map @@ function +- | Mir.GenArgLifetime _ -> +- raise +- (Ast.StaticError +- ( loc, +- "Lifetime arguments are not yet supported here", +- None )) ++ | Mir.GenArgLifetime region -> vf_ty_arg_of_region loc region + | Mir.GenArgType arg_ty -> arg_ty.vf_ty + | Mir.GenArgConst ty_expr -> ty_expr +@@ -1074,17 +1069,8 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + let* self_ty = translate_ty self_ty loc in + let* gen_args = ListAux.try_map (fun arg -> translate_generic_arg arg loc) args in +- let targs = +- gen_args +- |> Util.flatmap @@ function +- | Mir.GenArgType arg_ty -> [ arg_ty.vf_ty ] +- | _ -> [] +- in +- let lft_args = +- gen_args +- |> Util.flatmap @@ function +- | Mir.GenArgLifetime name -> [ vf_ty_arg_of_region loc name ] +- | _ -> [] +- in +- let vf_targs = lft_args @ targs in ++ let vf_targs = List.map (function ++ | Mir.GenArgType ty -> ty.vf_ty ++ | Mir.GenArgLifetime region -> vf_ty_arg_of_region loc region ++ | Mir.GenArgConst te -> te) gen_args in + let def_id_separator = String.rindex def_id ':' in + let trait_name = String.sub def_id 0 (def_id_separator - 1) in +@@ -1093,6 +1079,6 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + let vf_ty = ProjectionTypeExpr (loc, self_ty.vf_ty, trait_name, vf_targs, alias_name) in + let size = SizeofExpr (loc, TypeExpr vf_ty) in +- let own tid vs = +- Error "Expressing ownership of alias types is not yet supported" ++ let own tid v = ++ Ok (ExprCallExpr (loc, TypePredExpr (loc, vf_ty, "own"), [ LitPat tid; LitPat v ])) + in + let shr lft tid l = +@@ -1191,6 +1177,8 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + in + let points_to tid l vid_op = +- Error +- (Printf.sprintf "Expressing a points-to assertion for a %s object is not yet supported" ref_ty_name) ++ (* This is the sized reference slot. Permissions for its str pointee ++ are still required separately by own and the borrow interpretation. *) ++ let* pat = RustBelt.Aux.vid_op_to_var_pat vid_op loc in ++ Ok (PointsTo (loc, l, RegularPointsTo, pat)) + in + { +@@ -1400,5 +1388,12 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + failwith "Unsupported constant type or size" + end +- | _ -> ++ | UnitVariant {discriminant; _} -> ++ let owner = match translate_ty ty loc with ++ | Ok ty -> ty.Mir.vf_ty ++ | Error _ -> Ast.static_error loc "Cannot translate the enum const's type" None ++ in ++ Ast.ConstructedTypeExpr (loc, "rust_unit_enum_const", ++ [owner; Ast.LiteralConstTypeExpr (loc, Z.of_int (Int32.to_int discriminant))]) ++ | Branch _ -> + failwith "Unsupported constant value tree" + end +@@ -1836,7 +1831,8 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + shr = + (fun k t l -> +- Error +- "Expressing the shared ownership of an array is not yet \ +- supported"); ++ let elems = Ast.CastExpr (loc, Ast.PtrTypeExpr (loc, elem_ty), l) in ++ let count = Ast.IntLit (loc, len, true, false, Ast.NoLSuffix) in ++ Ok (Ast.CallExpr (loc, "array_share", [elem_ty], [], ++ List.map (fun e -> Ast.LitPat e) [k; t; elems; count], Ast.Static))); + full_bor_content; + points_to; +@@ -1917,5 +1913,15 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + | Infer -> Ast.static_error loc "Infer types are not yet supported" None + | Error -> Ast.static_error loc "Error types are not yet supported" None +- | Str -> Ast.static_error loc "Str types are not yet supported" None ++ | Str -> ++ (* A type argument such as NonNull carries slice metadata. References ++ have their own UTF-8 interpretation; producing a bare value stays unsupported. *) ++ let vf_ty = Ast.ManifestTypeExpr (loc, Ast.Str) in ++ let by_value () = Error "An unsized str cannot be interpreted by value" in ++ Ok { Mir.vf_ty; interp = RustBelt.{ ++ size = Ast.SizeofExpr (loc, TypeExpr vf_ty); ++ own = (fun _ _ -> by_value ()); shr = (fun _ _ _ -> by_value ()); ++ full_bor_content = (fun _ _ -> by_value ()); ++ points_to = (fun _ _ _ -> by_value ()); pointee_fbc = None } ++ } + | Array array_ty_cpn -> translate_array_ty array_ty_cpn loc + | Pattern -> Ast.static_error loc "Pattern types are not yet supported" None +@@ -1938,4 +1944,13 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + module TranslatorArgs = Args + ++ (* A scalar tail expression cannot be followed by a Rust statement. A ++ normal-return proof runs the same checked, pure lemma call at each MIR ++ Return. It has no effect on the return value or unwind terminators. *) ++ let normal_return_lemma = function ++ | Ast.PureStmt (l, ExprStmt (CallExpr (_, "vf_on_normal_return", [], [], ++ [LitPat (CallExpr (_, _, _, [], _, Static) as call)], Static))) -> ++ Some (Ast.PureStmt (l, Ast.ExprStmt call)) ++ | _ -> None ++ + module TrBody (Args : sig + val var_id_trs_map_ref : var_id_trs_map ref +@@ -2352,25 +2367,23 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + in + let translate_regular_fn_call substs fn_name = +- let targs = +- substs +- |> Util.flatmap @@ function +- | Mir.GenArgType ty -> [ ty.vf_ty ] +- | Mir.GenArgLifetime region -> +- [ Ast.InferredTypeExpr call_loc ] +- | Mir.GenArgConst ty -> [ ty ] ++ let compiler_arg = function ++ | Mir.GenArgType ty -> ty.vf_ty ++ | Mir.GenArgConst ty -> ty ++ | Mir.GenArgLifetime _ -> Ast.InferredTypeExpr call_loc + in + let* targs = + match OptionRd.get ghost_generic_arg_list_opt_cpn with +- | Nothing -> Ok targs ++ | Nothing -> Ok (List.map compiler_arg substs) + | Something ptr_cpn -> +- let ghost_generic_arg_list_cpn = VfMirRd.of_pointer ptr_cpn in +- let* ghost_targs = translate_ghost_generic_arg_list ghost_generic_arg_list_cpn in +- if List.length ghost_targs <> List.length targs then +- Ast.static_error call_loc "Incorrect number of ghost type arguments." None; +- Ok (List.map2 +- (fun ghost_arg compiler_arg -> match ghost_arg with +- | Ast.InferredTypeExpr _ -> compiler_arg +- | _ -> ghost_arg) +- ghost_targs targs) ++ let* ghost_args = translate_ghost_generic_arg_list (VfMirRd.of_pointer ptr_cpn) in ++ if List.length ghost_args <> List.length substs then ++ Ast.static_error call_loc "Incorrect number of ghost generic arguments." None; ++ Ok (List.map2 (fun subst ghost -> match subst, ghost with ++ | _, Ast.InferredTypeExpr _ -> compiler_arg subst ++ | Mir.GenArgLifetime _, Ast.ManifestTypeExpr (_, Ast.StaticLifetime) -> ghost ++ | Mir.GenArgLifetime _, Ast.IdentTypeExpr (_, None, x) when String.starts_with ~prefix:"'" x -> ghost ++ | _ -> Ast.static_error (Ast.type_expr_loc ghost) ++ "Only lifetimes may be supplied at a Rust call. Use _ for MIR type and const arguments." None) ++ substs ghost_args) + in + let args = List.map (fun expr -> Ast.LitPat expr) args in +@@ -2789,5 +2802,5 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + !State.ghost_stmts + in +- ([ ghost_stmt ], targets) ++ ((if Option.is_some (normal_return_lemma ghost_stmt) then [] else [ghost_stmt]), targets) + | _ -> + ( (if ListAux.is_empty fn_call_tmp_rval_ctx then call_stmts +@@ -2916,5 +2929,6 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + Ast.CallExpr (loc, "returning", [], [], [ LitPat result ], Static) + in +- Ok ([ Ast.ReturnStmt (loc, Some result) ], EncodedTerminator, []) ++ let proofs = List.filter_map normal_return_lemma Args.ghost_stmts in ++ Ok (proofs @ [ Ast.ReturnStmt (loc, Some result) ], EncodedTerminator, []) + | Unreachable -> + Rocq_writer.rocq_print_ident TranslatorArgs.rocq_writer "Unreachable"; +@@ -2951,19 +2965,19 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + ] ) + in +- Ok +- ( unfreeze_stmts +- @ [ +- Ast.ExprStmt +- (CallExpr +- ( loc, +- "std::ptr::drop_in_place", +- [], +- [], +- [ LitPat (AddressOf (loc, place)) ], +- Static )); +- ] +- @ freeze_stmts, +- Mir.GotoTerminator (loc, target), +- [ target ] ) ++ let call = Ast.CallExpr (loc, "std::ptr::drop_in_place", [], [], ++ [LitPat (AddressOf (loc, place))], Static) in ++ let drop_stmt, unwind_targets = ++ if TranslatorArgs.ignore_unwind_paths then Ast.ExprStmt call, [] ++ else ++ let unwind, targets = translate_unwind_action (unwind_action_get drop_data_cpn) loc in ++ Ast.SwitchStmt (loc, call, [ ++ Ast.SwitchStmtClause (loc, CallExpr (loc, "returning", [], [], ++ [LitPat (Var (loc, "__drop_result"))], Static), []); ++ Ast.SwitchStmtClause (loc, CallExpr (loc, "unwinding", [], [], [], Static), ++ freeze_stmts @ unwind); ++ ]), targets ++ in ++ Ok (unfreeze_stmts @ [drop_stmt] @ freeze_stmts, ++ Mir.GotoTerminator (loc, target), target :: unwind_targets) + | Assert assert_data_cpn -> + (* `Assert { cond, expected, target, unwind }`: continue at `target` if `cond == expected`, +@@ -3041,4 +3055,7 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + | Gt -> Ok Ast.Gt + | Offset -> failwith "Todo: BinOp::Offset" ++ | AddUnchecked | SubUnchecked | MulUnchecked | ShlUnchecked | ShrUnchecked ++ | AddWithOverflow | SubWithOverflow | MulWithOverflow | Cmp -> ++ Error (`TrBinOp "The semantics of this rustc arithmetic operator are not implemented") + | Undefined _ -> Error (`TrBinOp "Unknown binary operator") + +@@ -3055,4 +3072,9 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + let operator_cpn = operator_get bin_op_data_cpn in + let* operator = translate_bin_op operator_cpn in ++ begin match operator with ++ | Ast.Lt | Ast.Le | Ast.Gt | Ast.Ge | Ast.Eq | Ast.Neq when not (comparison_operands_thin_get bin_op_data_cpn) -> ++ Ast.static_error loc "Raw pointer comparison requires a proven thin pointee." None ++ | _ -> () ++ end; + let operandl_cpn = operandl_get bin_op_data_cpn in + let* operandl = translate_operand operandl_cpn loc in +@@ -3338,4 +3360,9 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + in + let expr = Ast.AddressOf (loc, place_expr) in ++ let expr = ++ if unsafe_cell_get_receiver_get raw_ptr_data_cpn then ++ Ast.CallExpr (loc, "ref_origin", [], [], [ LitPat expr ], Static) ++ else expr ++ in + Ok (`TrRvalueExpr expr) + | Cast cast_data_cpn -> ( +@@ -3410,4 +3437,9 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + | Aggregate agg_data_cpn -> translate_aggregate agg_data_cpn loc + | Discriminant discriminant_data_cpn -> ++ begin match VfMirRd.Option.get (DiscriminantData.abstract_operand_get discriminant_data_cpn) with ++ | Something _ -> Ast.static_error loc "An abstract MIR discriminant requires a concrete operand layout" None ++ | Nothing -> () ++ | Undefined _ -> Ast.static_error loc "Unknown discriminant metadata" None ++ end; + let place_cpn = DiscriminantData.place_get discriminant_data_cpn in + let* place_expr, place_is_mutable = translate_place place_cpn loc in +@@ -4866,10 +4898,10 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + let* trait_args = + projection_term_cpn.args +- |> ListAux.try_map (fun genarg_cpn -> +- let* arg = translate_generic_arg genarg_cpn loc in +- match arg with +- | Mir.GenArgLifetime _ -> assert false +- | Mir.GenArgType ty -> Ok ty.vf_ty +- | Mir.GenArgConst _ -> assert false) ++ |> ListAux.try_map (fun (arg : D.generic_arg) -> match arg.kind with ++ | Type ty -> ++ let* ty = translate_decoded_ty ty loc in ++ Ok ty.vf_ty ++ | Const _ | Lifetime _ -> Ast.static_error loc ++ "Projection equality registration supports only type arguments." None) + in + Ok (projection_term_cpn.def_id, trait_args) +@@ -4887,5 +4919,5 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + let* ty = translate_decoded_ty ty_cpn loc in + Ok ty.vf_ty +- | Const const_cpn -> assert false ++ | Const _ -> Ast.static_error loc "Expected a type on the right of a projection equality." None + in + Ok +@@ -5192,5 +5224,10 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + let contract, assume_false = contract in + let* body = +- if assume_false then ++ if is_intrinsic_declaration_get body_cpn then ++ if contract_opt = None || assume_false then ++ Error (`TrBodyFailed (contract_loc, "A compiler intrinsic declaration requires an explicit contract")) ++ else ++ Ok (mk_fn_decl contract None) ++ else if assume_false then + Ok + (mk_fn_decl contract +@@ -5235,4 +5272,15 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + match contract_template_opt with + | None -> None ++ | Some contract_template when is_intrinsic_declaration_get body_cpn -> ++ if vf_tparams <> [] || vf_param_decls <> [] then ++ Ast.static_error loc "Safe compiler declaration compatibility is implemented only for nullary monomorphic declarations" None; ++ (* A safe intrinsic has no Rust body to mediate its two specifications. ++ Check its Rust interface by forwarding both outcomes of the real ++ declaration. Program calls always use its original DefId and contract. *) ++ let m, f = split_name in ++ let check_name = "#check_safe_intrinsic_" ^ f in ++ let invoke = Ast.CallExpr (loc, name, [], [], [], Ast.Static) in ++ let check_body = [Ast.ReturnStmt (loc, Some invoke)], closing_cbrace_loc in ++ Some ((m, check_name), mk_fn_decl contract_template (Some check_body)) + | Some contract_template -> + let body_sig = mk_fn_decl contract_template None in +@@ -6244,7 +6292,8 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + * The latter condition is exploited in gen_drop_contract. + *) +- let decoded_variants_no_zst = decoded_variants |> List.map @@ function ({span; name; fields}: D.variant_def) -> ++ let decoded_variants_no_zst = decoded_variants |> List.map @@ fun (variant: D.variant_def) -> ++ let fields = variant.fields in + let fields = fields |> List.filter (function ({ty={kind=Adt {id={name=("std::marker::PhantomData"|"core::marker::PhantomData")}}}}: D.variant_def_field_def) -> false | _ -> true) in +- ({span; name; fields}: D.variant_def) ++ { variant with fields } + in + let* variants = ListAux.try_map translate_variant_def decoded_variants in +@@ -6869,13 +6918,34 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + [mk_sync_lemma (List.fold_left (fun e e1 -> Ast.Operation (def_loc, And, [e; e1])) (mk_sync_expr def_loc structTypeExpr) rhs_conjuncts)] + in ++ (* Use the nominal MIR field before value translation erases wrappers. ++ An unsupported field leaves the structural equivalence unspecified. *) ++ let structural_auto_trait trait impls = ++ let rec condition trait (ty : D.ty) te = ++ match ty.kind, te with ++ | RawPtr _, _ -> Some (Ast.False def_loc) ++ | Array a, Ast.StaticArrayTypeExpr (_, elem, _) -> condition trait a.elem_ty elem ++ | Slice ty, Ast.SliceTypeExpr (_, elem) -> condition trait ty elem ++ | Ref r, Ast.RustRefTypeExpr (_, _, _, elem) -> ++ condition (if r.mutability = Not then `Sync else trait) r.ty elem ++ | Adt {id; substs = [{kind = Type inner}]}, _ when translate_adt_def_id id = "std::cell::UnsafeCell" -> ++ if trait = `Sync then Some (Ast.False def_loc) else condition trait inner te ++ | Adt {id; substs = [{kind = Type inner}]}, _ when translate_adt_def_id id = "std::mem::ManuallyDrop" -> ++ condition trait inner te ++ (* The exporter checks nominal ADT type arguments for erased identities. *) ++ | (Adt _ | Param _ | Bool | Int _ | UInt _ | Char | Str | Never), _ -> ++ Some ((if trait = `Send then mk_send_expr else mk_sync_expr) def_loc te) ++ | _ -> None ++ in ++ if impls <> [] then None else ++ let [variant] = decoded_variants in ++ List.fold_left2 (fun rhs (field : D.variant_def_field_def) (fd : Mir.field_def_tr) -> ++ Option.bind rhs (fun lhs -> Option.map (fun e -> Ast.Operation (def_loc, And, [lhs; e])) ++ (condition trait field.ty fd.ty.vf_ty))) ++ (Some (Ast.True def_loc)) variant.fields fds ++ in + let send_def_lemmas = +- if send_impls <> [] then [] else +- [ +- let rhs = +- let rhs_conjuncts = +- fds |> List.map (fun fd -> mk_send_expr def_loc fd.Mir.ty.Mir.vf_ty) +- in +- List.fold_left (fun e e1 -> Ast.Operation (def_loc, And, [e; e1])) (Ast.True def_loc) rhs_conjuncts +- in ++ match structural_auto_trait `Send send_impls with ++ | None -> [] ++ | Some rhs -> [ + let post = + Ast.Operation (def_loc, Eq, [ +@@ -6917,12 +6987,7 @@ module Make (Args : VF_MIR_TRANSLATOR_ARGS) = struct + in + let sync_def_lemmas = +- if sync_impls <> [] then [] else +- [ +- let rhs = +- let rhs_conjuncts = +- fds |> List.map (fun fd -> mk_sync_expr def_loc fd.Mir.ty.Mir.vf_ty) +- in +- List.fold_left (fun e e1 -> Ast.Operation (def_loc, And, [e; e1])) (Ast.True def_loc) rhs_conjuncts +- in ++ match structural_auto_trait `Sync sync_impls with ++ | None -> [] ++ | Some rhs -> [ + let post = + Ast.Operation (def_loc, Eq, [ +diff --git a/src/verifast.ml b/src/verifast.ml +index 2b64679edcfd3db233d2f35ec3fd14abf6e46006..ec489abde55f232850dd88e247355a5187214de8 100644 +--- a/src/verifast.ml ++++ b/src/verifast.ml +@@ -262,5 +262,10 @@ module VerifyProgram(VerifyProgramArgs: VERIFY_PROGRAM_ARGS) = struct + if stmt_ghostness = Ghost && not (is_lemma k) then static_error l "Not a lemma function." None; + if stmt_ghostness = Real && k <> Regular then static_error l "Regular function expected." None; +- if f_tparams <> [] then static_error l "Taking the address of a function with type parameters is not yet supported." None; ++ begin match f_tparams, ps, ftclause_opt, dialect, stmt_ghostness with ++ [], _, _, _, _ -> () ++ | [(lt, bounds)], [_, RustRefType (GhostTypeParam p, Shared, _)], Some _, Some Rust, Real ++ when bounds = Ast.no_bounds && String.starts_with ~prefix:"'" lt && p = lt -> () ++ | _ -> static_error l "Taking the address of a function with type parameters is not yet supported." None ++ end; + if body' = None then register_prototype_used lf fn (Some fterm); + if stmt_ghostness = Ghost then begin +@@ -271,5 +276,5 @@ module VerifyProgram(VerifyProgramArgs: VERIFY_PROGRAM_ARGS) = struct + if not (List.mem fn lems) then static_error l "Function pointer chunks can only be produced for preceding lemmas." None + end; +- (fterm, functype_opt, Some (funenv, rt, ps, pre, post, terminates)) ++ (fterm, functype_opt, Some (funenv, f_tparams, rt, ps, pre, post, terminates)) + in + if stmt_ghostness = Ghost && (match leminfo with LemInfo (_, _, _, nonghost_callers_only) -> not nonghost_callers_only | _ -> false) && scope_opt = None then +@@ -302,4 +307,21 @@ module VerifyProgram(VerifyProgramArgs: VERIFY_PROGRAM_ARGS) = struct + let rt = match rt with None -> None | Some rt -> Some (rt, instantiate_type tpenv rt) in + let xmap = List.map (fun (x, tp0) -> let tp = instantiate_type tpenv tp0 in (x, tp, tp0)) xmap in ++ (* Rust lifetimes are erased at the address, but remain part of ++ both proof contracts. Instantiate the callback at the exact ++ lifetime of the shared argument in this function-type chunk. *) ++ let funcinfo_opt = Option.map (fun (fenv, tps, frt, fps, fpre, fpost, ft) -> ++ let subst = match tps, xmap with ++ | [], _ -> [] ++ | [(lt, _)], [_, (RustRefType (actual_lt, Shared, _) as actual), _] -> ++ let binding = [lt, actual_lt] in ++ if instantiate_type binding (snd (List.hd fps)) <> actual then ++ static_error l "Rust callback shared-reference type mismatch." None; ++ binding ++ | _ -> static_error l "Expected a single shared reference for this Rust callback." None ++ in ++ let instantiate t = if subst = [] then t else instantiate_type subst t in ++ (typeid_env_of_tpenv l env subst @ fenv, subst, Option.map instantiate frt, ++ List.map (fun (x, t) -> x, instantiate t) fps, fpre, fpost, ft) ++ ) funcinfo_opt in + let args = + match zip ftxmap args with +@@ -335,5 +357,5 @@ module VerifyProgram(VerifyProgramArgs: VERIFY_PROGRAM_ARGS) = struct + if List.mem_assoc x tenv then static_error ld "Variable hides existing variable" None; + let t = option_map (check_pure_type (pn,ilist) tparams gh) tx in +- let Some (funenv1, rt1, xmap1, pre1, post1, terminates1) = funcinfo_opt in ++ let Some (funenv1, _, rt1, xmap1, pre1, post1, terminates1) = funcinfo_opt in + let t = match t, rt1 with + _, None -> static_error ld "Function does not return a value" None +@@ -393,5 +415,5 @@ module VerifyProgram(VerifyProgramArgs: VERIFY_PROGRAM_ARGS) = struct + ftcheck_cont h ft_env + | Some (callLoc, resultvar, ss_after) -> +- let Some (funenv1, rt1, xmap1, pre1, post1, terminates1) = funcinfo_opt in ++ let Some (funenv1, fsubst, rt1, xmap1, pre1, post1, terminates1) = funcinfo_opt in + begin match (rt, rt1) with + (None, _) -> () +@@ -415,5 +437,5 @@ module VerifyProgram(VerifyProgramArgs: VERIFY_PROGRAM_ARGS) = struct + with_context PushSubcontext $. fun () -> + let pre1_env = currentThreadEnv @ List.map (fun (x, x0, tp, t, t0, x1, tp1) -> (x1, t)) fparams @ funenv1 in +- consume_asn rules [] h env [] pre1_env pre1 true real_unit $. fun _ h _ f_env _ -> ++ consume_asn rules fsubst h env [] pre1_env pre1 true real_unit $. fun _ h _ f_env _ -> + let (result_var1, post1) = post1 in + let (f_env, ft_env, tenv, ghostenv, env) = +@@ -436,5 +458,5 @@ module VerifyProgram(VerifyProgramArgs: VERIFY_PROGRAM_ARGS) = struct + (f_env, ft_env, tenv, ghostenv, env) + in +- produce_asn typeid_env [] h [] f_env post1 real_unit None None $. fun h _ _ -> ++ produce_asn typeid_env fsubst h [] f_env post1 real_unit None None $. fun h _ _ -> + with_context PopSubcontext $. fun () -> + let tcont _ _ _ h _ = ftcheck_cont h ft_env in +@@ -1022,4 +1044,9 @@ module VerifyProgram(VerifyProgramArgs: VERIFY_PROGRAM_ARGS) = struct + iter h ((x, t)::tenv) ghostenv ((x, v)::env) xs + | Some t -> ++ (* A fresh Rust stack allocation owns its original provenance. Only ++ the allocation event establishes this fact, never a raw-pointer argument. *) ++ let with_stack_origin addr k = ++ if is_rust then assume_eq (mk_app !!ref_origin_symb [addr]) addr k else k () ++ in + let produce_object envTp = + if pure then static_error l "Cannot declare a variable of this type in a ghost context." None; +@@ -1028,4 +1055,5 @@ module VerifyProgram(VerifyProgramArgs: VERIFY_PROGRAM_ARGS) = struct + let addr_name = x ^ "_addr" in + let addr = get_unique_var_symb_non_ghost addr_name (PtrType Void) in ++ with_stack_origin addr @@ fun () -> + match e, dialect with + | Some (CallExpr _ as e), Some Cxx -> +@@ -1114,4 +1142,5 @@ module VerifyProgram(VerifyProgramArgs: VERIFY_PROGRAM_ARGS) = struct + if !address_taken then begin + let addr = get_unique_var_symb_non_ghost (x ^ "_addr") (PtrType t) in ++ with_stack_origin addr @@ fun () -> + if pure then static_error l "Taking the address of a ghost variable is not allowed." None; + let v = if e = None then None else Some v in diff --git a/verifast-proofs/core/sync/atomic.rs/verify.sh b/verifast-proofs/core/sync/atomic.rs/verify.sh new file mode 100755 index 0000000000000..cdbdbc52ed418 --- /dev/null +++ b/verifast-proofs/core/sync/atomic.rs/verify.sh @@ -0,0 +1,217 @@ +#!/usr/bin/env bash +set -euo pipefail + +here=$(cd "$(dirname "$0")" && pwd) +bash "$here/check-sources.sh" +tools=$(bash "$here/build-linux-tools.sh") +export LD_LIBRARY_PATH="$tools/bin${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" +work=$(mktemp -d) +trap 'rm -rf -- "$work"' EXIT +export CARGO_BUILD_JOBS=1 CARGO_INCREMENTAL=0 RAYON_NUM_THREADS=1 MALLOC_ARENA_MAX=2 +ulimit -S -v 8388608 + +# shellcheck source=checks/common.sh +source "$here/checks/common.sh" +init_env "$here" "$tools" "$work" + +"$CHECK_MIR" patch-audit "$PROOF/verifast-core.patch" "$PROOF/TRUSTED-BASE.md" + +run_positive_tool_tests() { + local folder="$PROOF/tool-tests" + local root_file="$WORK/diff-roots.txt" + local target export flags model + + for target in "$HOST" "$ARM"; do + model="(target: $target (LP64))" + local layout_rlib="$WORK/liblayout_provider-${target}.rlib" + run_expect "compile $target external layout provider" 0 0 -- \ + rustc "$TC" --edition=2024 "--target=$target" --crate-name=layout_provider \ + --crate-type=rlib "$folder/external_layout.rs" -o "$layout_rlib" + + for export in normal scoped; do + flags="--edition=2024 --target=$target" + if [[ $export == scoped ]]; then + flags+=" --vf-rust-mir-exporter:roots=$root_file" + fi + + printf 'client\n' > "$root_file" + run_expect "external_array_client $target $export plain [u8; N]" 0 3 \ + "0 errors found" "$model" "Verifying function 'client'" -- \ + "${VF_BASE[@]}" -rustc_args "$flags" \ + -extern_spec "layout_provider=$folder/external_layout.rsspec" \ + -rustc_arg "--extern=layout_provider=$layout_rlib" \ + "$folder/external_array_client.rs" + + printf 'round_trip\n' > "$root_file" + run_expect "projection_recursion $target $export" 0 3 \ + "0 errors found" "$model" "Verifying function 'round_trip'" -- \ + "${VF_BASE[@]}" -rustc_args "$flags" "$folder/projection_recursion.rs" + + printf 'projection_client\nborrow_bytes\n' > "$root_file" + run_expect "generic_projection $target $export" 0 4 \ + "0 errors found" "$model" "Verifying function 'projection_client'" "Verifying function 'borrow_bytes'" -- \ + "${VF_BASE[@]}" -rustc_args "$flags" "$folder/generic_projection.rs" + + printf 'send_client\nsync_client\nfield_traits\n' > "$root_file" + run_expect "auto_traits $target $export" 0 5 \ + "0 errors found" "$model" "Verifying function 'send_client'" "Verifying function 'sync_client'" "Verifying function 'field_traits'" -- \ + "${VF_BASE[@]}" -rustc_args "$flags" "$folder/auto_traits.rs" + + printf 'compare\n' > "$root_file" + run_expect "wide_pointer_comparison $target $export thin *const" 0 3 \ + "0 errors found" "$model" "Verifying function 'compare'" -- \ + "${VF_BASE[@]}" -rustc_args "$flags" -rustc_arg "--cfg=thin" "$folder/wide_pointer_comparison.rs" + run_expect "wide_pointer_comparison $target $export thin *mut" 0 3 \ + "0 errors found" "$model" "Verifying function 'compare'" -- \ + "${VF_BASE[@]}" -rustc_args "$flags" -rustc_arg "--cfg=thin" -rustc_arg "--cfg=mutable" "$folder/wide_pointer_comparison.rs" + done + done + + run_expect "ordering.rs" 0 2 "0 errors found" "Verifying function 'store_relaxed'" -- \ + "${VF_BASE[@]}" -rustc_arg "--edition=2021" "$folder/ordering.rs" + run_expect "macro_expansion.rs" 0 2 "0 errors found" "Verifying function 'Atomic::::expansion'" -- \ + "${VF_BASE[@]}" -skip_specless_fns -rustc_arg "--edition=2021" "$folder/macro_expansion.rs" + run_expect "drop.rs" 0 2 "0 errors found" "Verifying function 'finish'" -- \ + "${VF_BASE[@]}" -rustc_arg "--edition=2021" "$folder/drop.rs" + + printf 'concrete_value\n' > "$WORK/trait-roots.txt" + run_expect "concrete trait override" 0 2 "Verifying function 'concrete_value'" "0 errors found" -- \ + "${VF_BASE[@]}" -rustc_args "--edition=2024 --vf-rust-mir-exporter:roots=$WORK/trait-roots.txt --vf-rust-mir-exporter:scope-report=$WORK/trait-scope.tsv" \ + "$folder/trait_dispatch.rs" + "$CHECK_MIR" edge-check "$WORK/trait-scope.tsv" "concrete_value" "{impl#0}::value" "-" 1 + + run_expect "panicking destructor" 0 0 -- \ + rustc "$TC" --test --edition=2021 "$folder/drop.rs" -o "$WORK/destructor" + run_expect "destructor unwind observed" 0 1 "1 passed" -- "$WORK/destructor" + + build_pointer_spec + local rlib="$WORK/libslot_flags.rlib" + for target in "$HOST" "$ARM"; do + model="(target: $target (LP64))" + flags="--edition=2024 --target=$target" + run_expect "$target pointer qualifier provider" 0 4 \ + "$model" "0 errors found" "Slot::<*mut T>::tag" "Slot::<*const T>::tag" -- \ + "${VF_BASE[@]}" -rustc_args "$flags --crate-name slot_flags" "$folder/pointer_lib.rs" + run_expect "$target compile pointer qualifier provider" 0 0 -- \ + rustc "$TC" "--target=$target" --crate-type=rlib --crate-name=slot_flags "$folder/pointer_lib.rs" -o "$rlib" + run_expect "$target qualified external calls" 0 4 \ + "$model" "0 errors found" "mut_client" "const_client" -- \ + "${VF_BASE[@]}" -rustc_args "$flags --extern slot_flags=$rlib" \ + -extern_spec "slot_flags=$POINTER_SPEC" "$folder/pointer_client.rs" + done + + run_expect "byte range and CAS effects" 0 7 \ + "0 errors found" \ + "Verifying function 'aligned_gap'" \ + "Verifying function 'same_width'" \ + "Verifying function 'nested_on_grid'" \ + "Verifying function 'ordinary_byte'" \ + "Verifying function 'different_widths'" \ + "Verifying function 'integer_pair'" -- \ + "${VF_BASE[@]}" -rustc_arg "--edition=2024" "$CHECKS/ranges.rs" + + run_expect "overlapping byte separation" 0 12 \ + "0 errors found" \ + "Verifying function 'atomic_storage_excludes_byte'" \ + "Verifying function 'sealed_word_excludes_byte'" \ + "Verifying function 'outstanding_client_excludes_byte'" \ + "Verifying function 'two_open_clients_exclude_byte'" \ + "Verifying function 'word_excludes_overlapping_access'" \ + "Verifying function 'disjoint_word'" \ + "Verifying function 'storage_round_trip'" \ + "Verifying function 'recovered_byte_write_read'" \ + "Verifying function 'readonly_atomic_excludes_ordinary_write'" \ + "Verifying function 'ordinary_read_excludes_writable_atomic'" \ + "Verifying function 'readonly_coexists_with_ordinary_read'" -- \ + "${VF_BASE[@]}" "$CHECKS/storage.rs" +} + +run_positive_tool_tests +build_safety_macro +: > "$WORK/interfaces.rsspec" + +for target in "$HOST" "$ARM"; do + dump_original_mir "$target" + records="$WORK/records-${target}" + mkdir -p "$records" + + for family in "${FAMILIES[@]}"; do + setup_crate "$target" "$family" + run_crate_refine "$target $family refinement" 0 1 "No refinement errors found" + attach_clients + check_dead_swap + allow_dead=0 + if [[ $family == rmw ]]; then allow_dead=1; fi + run_crate_verifast "$allow_dead" "$target $family proofs" 0 2 \ + "0 errors found" "(target: $target (LP64))" + + sed -n "s/.*Verifying function '\([^']*\)'.*/\1/p" "$LAST_LOG" | sort -u > "$records/${family}.fns" + cp "$CRATE_REPORT" "$records/${family}.tsv" + + { + printf '%s\n' "${CRATE_WANTED[@]}" "${CRATE_CLIENT_ROOTS[@]}" + if [[ $family == u32 ]]; then + printf '%s\n' "${ATOMIC}Atomic_share_full" "${ATOMIC}Atomic_drop" + fi + } | sort -u > "$WORK/wanted.txt" + missing=$(comm -23 "$WORK/wanted.txt" "$records/${family}.fns") + if [[ -n $missing ]]; then + echo "Missing checked functions in $target $family:" >&2 + printf '%s\n' "$missing" >&2 + exit 1 + fi + + if [[ $family == readonly ]]; then + dump_witness_mir + ro_out="$WORK/readonly-${target}.rsspec" + if [[ $target == "$HOST" ]]; then ro_out="$WORK/readonly.rsspec"; fi + "$CHECK_MIR" thread-spec "$family" "$CRATE_SRC" "$WORK/owners-${target}.tsv" \ + "$CRATE_REPORT" "$CHECKS/pointer-shape.rs" "$CRATE_WITNESS_MIR" "$WORK/${target}-mir" > "$ro_out" + elif [[ $target == "$HOST" && $family != pointer-rmw ]]; then + dump_witness_mir + "$CHECK_MIR" thread-spec "$family" "$CRATE_SRC" "$WORK/owners-${target}.tsv" \ + "$CRATE_REPORT" "$CHECKS/pointer-shape.rs" "$CRATE_WITNESS_MIR" >> "$WORK/interfaces.rsspec" + fi + done + + "$CHECK_MIR" inventory "$target" "$WORK/${target}-mir" "$WORK/owners-${target}.tsv" \ + "$records" "$PROOF" "$BOOK" +done + +build_platform_runtime +mkdir -p "$PLAT/examples" + +verify_thread_client() { + local name=$1 parents=$2; shift 2 + local fixture="$CHECKS/threads/${name}.rs" + local markers=("0 errors found") + local p + IFS=',' read -r -a parent_list <<< "$parents" + for p in "${parent_list[@]}"; do + markers+=("Verifying function '$p'") + done + local vf_cmd=("${THREAD_VF[@]}") + if [[ $name == readonly ]]; then + vf_cmd=("${RO_THREAD_VF[@]}") + fi + run_expect "$name two-worker proof" 0 "${#markers[@]}" "${markers[@]}" -- \ + "${vf_cmd[@]}" "$fixture" + local ir="$WORK/${name}.ll" + run_expect "$name platform boundary MIR lowering" 0 0 -- \ + rustc "$TC" "@$THREAD_FLAGS" --edition=2024 -Cpanic=unwind -Cdebug-assertions=no \ + -Csymbol-mangling-version=v0 --crate-type=rlib --emit=llvm-ir -o "$ir" "$fixture" + "$CHECK_MIR" check-ir "$ir" "$@" + cp "$fixture" "$PLAT/examples/${name}.rs" +} + +verify_thread_client u32 borrowed_pair fork_boundary:fork_joinable join_boundary:join +verify_thread_client boolean bool_pair fork_bool:fork_joinable join_bool:join +verify_thread_client pointer pointer_pair fork_pointer:fork_joinable join_pointer:join +verify_thread_client width width_pair fork16:fork_joinable fork8:fork_joinable join_width:join +verify_thread_client readonly bool_readonly_pair,u32_readonly_pair \ + fork_ro_bool:fork_joinable fork_plain_u8:fork_joinable fork_ro_u32:fork_joinable fork_plain_u32:fork_joinable join_ro:join + +cp "$CHECKS/threads/runtime.rs" "$PLAT/examples/atomic_clients.rs" +run_expect "link POSIX clients" 0 0 -- "${PLATFORM_CARGO[@]}" --example atomic_clients +run_expect "execute POSIX clients" 0 1 "worker pairs passed" -- \ + "$WORK/platform-target/$HOST/debug/examples/atomic_clients" From bda62b7fe6fd460ae24cd506c0e2b838ce770a8c Mon Sep 17 00:00:00 2001 From: v3risec Date: Fri, 4 Dec 2026 23:20:06 +0800 Subject: [PATCH 5/5] Fix CI backtrace tar mode normalization and rustfmt formatting --- library/core/src/intrinsics/mod.rs | 64 +++++++++++-------- library/core/src/sync/atomic.rs | 33 +++++++--- .../core/sync/atomic.rs/checks/common.sh | 4 +- .../core/sync/atomic.rs/original/atomic.rs | 33 +++++++--- .../sync/atomic.rs/original/intrinsics/mod.rs | 64 +++++++++++-------- 5 files changed, 128 insertions(+), 70 deletions(-) diff --git a/library/core/src/intrinsics/mod.rs b/library/core/src/intrinsics/mod.rs index f74fd9e2c1fec..710c73310c7a3 100644 --- a/library/core/src/intrinsics/mod.rs +++ b/library/core/src/intrinsics/mod.rs @@ -5172,33 +5172,47 @@ mod verify { define_atomic_extremum_wrapper!(atomic_umax_wrapper, atomic_umax); define_atomic_extremum_wrapper!(atomic_umin_wrapper, atomic_umin); - macro_rules! define_atomic_compare_exchange_wrapper { - ($wrapper:ident, $intrinsic:ident) => { - #[allow(dead_code)] - #[kani::modifies(dst)] - #[requires( - ORD_FAIL == AtomicOrdering::Relaxed - || ORD_FAIL == AtomicOrdering::Acquire - || ORD_FAIL == AtomicOrdering::SeqCst - )] - #[requires(crate::ub_checks::can_dereference(dst as *const T))] - #[requires(crate::ub_checks::can_write(dst))] - unsafe fn $wrapper< - T: Copy, - const ORD_SUCC: AtomicOrdering, - const ORD_FAIL: AtomicOrdering, - >( - dst: *mut T, - old: T, - new: T, - ) -> (T, bool) { - unsafe { $intrinsic::(dst, old, new) } - } - }; + #[allow(dead_code)] + #[kani::modifies(dst)] + #[requires( + ORD_FAIL == AtomicOrdering::Relaxed + || ORD_FAIL == AtomicOrdering::Acquire + || ORD_FAIL == AtomicOrdering::SeqCst + )] + #[requires(crate::ub_checks::can_dereference(dst as *const T))] + #[requires(crate::ub_checks::can_write(dst))] + unsafe fn atomic_cxchg_wrapper< + T: Copy, + const ORD_SUCC: AtomicOrdering, + const ORD_FAIL: AtomicOrdering, + >( + dst: *mut T, + old: T, + new: T, + ) -> (T, bool) { + unsafe { atomic_cxchg::(dst, old, new) } } - define_atomic_compare_exchange_wrapper!(atomic_cxchg_wrapper, atomic_cxchg); - define_atomic_compare_exchange_wrapper!(atomic_cxchgweak_wrapper, atomic_cxchgweak); + #[allow(dead_code)] + #[kani::modifies(dst)] + #[requires( + ORD_FAIL == AtomicOrdering::Relaxed + || ORD_FAIL == AtomicOrdering::Acquire + || ORD_FAIL == AtomicOrdering::SeqCst + )] + #[requires(crate::ub_checks::can_dereference(dst as *const T))] + #[requires(crate::ub_checks::can_write(dst))] + unsafe fn atomic_cxchgweak_wrapper< + T: Copy, + const ORD_SUCC: AtomicOrdering, + const ORD_FAIL: AtomicOrdering, + >( + dst: *mut T, + old: T, + new: T, + ) -> (T, bool) { + unsafe { atomic_cxchgweak::(dst, old, new) } + } // Every ordering-specific harness below expands to every legal integer // width and to the pointer form. Storage is a local object, so the raw diff --git a/library/core/src/sync/atomic.rs b/library/core/src/sync/atomic.rs index 83042919c1aac..ed37510fe3dcc 100644 --- a/library/core/src/sync/atomic.rs +++ b/library/core/src/sync/atomic.rs @@ -5106,15 +5106,30 @@ pub fn spin_loop_hint() { // The module's read-only memory guarantee applies only to these small Relaxed loads. #[cfg(kani)] pub(crate) const fn small_read_only_atomic_load() -> bool { - (crate::mem::size_of::() <= 8 && cfg!(any( - target_arch = "x86_64", target_arch = "aarch64", target_arch = "loongarch64", - target_arch = "mips64", target_arch = "mips64r6", target_arch = "powerpc64", - target_arch = "riscv64", target_arch = "sparc64", target_arch = "s390x", - ))) || (crate::mem::size_of::() <= 4 && cfg!(any( - target_arch = "x86", target_arch = "arm", target_arch = "loongarch32", - target_arch = "mips", target_arch = "mips32r6", target_arch = "powerpc", - target_arch = "riscv32", target_arch = "sparc", target_arch = "hexagon", - ))) + (crate::mem::size_of::() <= 8 + && cfg!(any( + target_arch = "x86_64", + target_arch = "aarch64", + target_arch = "loongarch64", + target_arch = "mips64", + target_arch = "mips64r6", + target_arch = "powerpc64", + target_arch = "riscv64", + target_arch = "sparc64", + target_arch = "s390x", + ))) + || (crate::mem::size_of::() <= 4 + && cfg!(any( + target_arch = "x86", + target_arch = "arm", + target_arch = "loongarch32", + target_arch = "mips", + target_arch = "mips32r6", + target_arch = "powerpc", + target_arch = "riscv32", + target_arch = "sparc", + target_arch = "hexagon", + ))) } #[cfg(kani)] diff --git a/verifast-proofs/core/sync/atomic.rs/checks/common.sh b/verifast-proofs/core/sync/atomic.rs/checks/common.sh index fe157e7f3aaa6..c115c34d3a3ca 100644 --- a/verifast-proofs/core/sync/atomic.rs/checks/common.sh +++ b/verifast-proofs/core/sync/atomic.rs/checks/common.sh @@ -11,7 +11,7 @@ ACCESS_METHODS=(load store compare_exchange compare_exchange_weak) RMW_METHODS=(swap fetch_add fetch_sub fetch_and fetch_nand fetch_or fetch_xor fetch_max fetch_min) PTR_RMW_METHODS=(fetch_byte_add fetch_byte_sub fetch_and fetch_or fetch_xor) BOOL_RMW_METHODS=(swap fetch_and fetch_or fetch_xor fetch_nand fetch_not) -BACKTRACE_TAR_SHA="66f3d6097f3ef1ced7ee5f05ca1f3797cc4ee6ba3212af303c13ea8eb540d8d0" +BACKTRACE_TAR_SHA="c35fcaad87894021e190dba3da7ce47ec5fbad7d59f0d3df457bb36f4f8a0901" BACKTRACE_GITLINK="160000 d902726a1dcdc1e1c66f73d1162181b5423c645b" init_env() { @@ -401,7 +401,7 @@ build_platform_runtime() { local bt="$SYSROOT/lib/rustlib/src/rust/library/backtrace" local bt_sha bt_sha=$(LC_ALL=C tar --sort=name --mtime=@0 --owner=0 --group=0 --numeric-owner \ - --format=gnu -cf - -C "$bt/src" . | sha256sum | cut -d' ' -f1) + --mode='u=rwX,go=rX,a-s' --format=gnu -cf - -C "$bt/src" . | sha256sum | cut -d' ' -f1) if [[ $bt_sha != "$BACKTRACE_TAR_SHA" ]]; then echo "Unexpected pinned backtrace source digest: $bt_sha" >&2 exit 1 diff --git a/verifast-proofs/core/sync/atomic.rs/original/atomic.rs b/verifast-proofs/core/sync/atomic.rs/original/atomic.rs index 83042919c1aac..ed37510fe3dcc 100644 --- a/verifast-proofs/core/sync/atomic.rs/original/atomic.rs +++ b/verifast-proofs/core/sync/atomic.rs/original/atomic.rs @@ -5106,15 +5106,30 @@ pub fn spin_loop_hint() { // The module's read-only memory guarantee applies only to these small Relaxed loads. #[cfg(kani)] pub(crate) const fn small_read_only_atomic_load() -> bool { - (crate::mem::size_of::() <= 8 && cfg!(any( - target_arch = "x86_64", target_arch = "aarch64", target_arch = "loongarch64", - target_arch = "mips64", target_arch = "mips64r6", target_arch = "powerpc64", - target_arch = "riscv64", target_arch = "sparc64", target_arch = "s390x", - ))) || (crate::mem::size_of::() <= 4 && cfg!(any( - target_arch = "x86", target_arch = "arm", target_arch = "loongarch32", - target_arch = "mips", target_arch = "mips32r6", target_arch = "powerpc", - target_arch = "riscv32", target_arch = "sparc", target_arch = "hexagon", - ))) + (crate::mem::size_of::() <= 8 + && cfg!(any( + target_arch = "x86_64", + target_arch = "aarch64", + target_arch = "loongarch64", + target_arch = "mips64", + target_arch = "mips64r6", + target_arch = "powerpc64", + target_arch = "riscv64", + target_arch = "sparc64", + target_arch = "s390x", + ))) + || (crate::mem::size_of::() <= 4 + && cfg!(any( + target_arch = "x86", + target_arch = "arm", + target_arch = "loongarch32", + target_arch = "mips", + target_arch = "mips32r6", + target_arch = "powerpc", + target_arch = "riscv32", + target_arch = "sparc", + target_arch = "hexagon", + ))) } #[cfg(kani)] diff --git a/verifast-proofs/core/sync/atomic.rs/original/intrinsics/mod.rs b/verifast-proofs/core/sync/atomic.rs/original/intrinsics/mod.rs index f74fd9e2c1fec..710c73310c7a3 100644 --- a/verifast-proofs/core/sync/atomic.rs/original/intrinsics/mod.rs +++ b/verifast-proofs/core/sync/atomic.rs/original/intrinsics/mod.rs @@ -5172,33 +5172,47 @@ mod verify { define_atomic_extremum_wrapper!(atomic_umax_wrapper, atomic_umax); define_atomic_extremum_wrapper!(atomic_umin_wrapper, atomic_umin); - macro_rules! define_atomic_compare_exchange_wrapper { - ($wrapper:ident, $intrinsic:ident) => { - #[allow(dead_code)] - #[kani::modifies(dst)] - #[requires( - ORD_FAIL == AtomicOrdering::Relaxed - || ORD_FAIL == AtomicOrdering::Acquire - || ORD_FAIL == AtomicOrdering::SeqCst - )] - #[requires(crate::ub_checks::can_dereference(dst as *const T))] - #[requires(crate::ub_checks::can_write(dst))] - unsafe fn $wrapper< - T: Copy, - const ORD_SUCC: AtomicOrdering, - const ORD_FAIL: AtomicOrdering, - >( - dst: *mut T, - old: T, - new: T, - ) -> (T, bool) { - unsafe { $intrinsic::(dst, old, new) } - } - }; + #[allow(dead_code)] + #[kani::modifies(dst)] + #[requires( + ORD_FAIL == AtomicOrdering::Relaxed + || ORD_FAIL == AtomicOrdering::Acquire + || ORD_FAIL == AtomicOrdering::SeqCst + )] + #[requires(crate::ub_checks::can_dereference(dst as *const T))] + #[requires(crate::ub_checks::can_write(dst))] + unsafe fn atomic_cxchg_wrapper< + T: Copy, + const ORD_SUCC: AtomicOrdering, + const ORD_FAIL: AtomicOrdering, + >( + dst: *mut T, + old: T, + new: T, + ) -> (T, bool) { + unsafe { atomic_cxchg::(dst, old, new) } } - define_atomic_compare_exchange_wrapper!(atomic_cxchg_wrapper, atomic_cxchg); - define_atomic_compare_exchange_wrapper!(atomic_cxchgweak_wrapper, atomic_cxchgweak); + #[allow(dead_code)] + #[kani::modifies(dst)] + #[requires( + ORD_FAIL == AtomicOrdering::Relaxed + || ORD_FAIL == AtomicOrdering::Acquire + || ORD_FAIL == AtomicOrdering::SeqCst + )] + #[requires(crate::ub_checks::can_dereference(dst as *const T))] + #[requires(crate::ub_checks::can_write(dst))] + unsafe fn atomic_cxchgweak_wrapper< + T: Copy, + const ORD_SUCC: AtomicOrdering, + const ORD_FAIL: AtomicOrdering, + >( + dst: *mut T, + old: T, + new: T, + ) -> (T, bool) { + unsafe { atomic_cxchgweak::(dst, old, new) } + } // Every ordering-specific harness below expands to every legal integer // width and to the pointer form. Storage is a local object, so the raw