blob: e12e91a399f65d88422f215a6349960ad2cbc068 [file]
-- Copyright 2026 The Fuchsia Authors
--
-- Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
-- <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
-- license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
-- This file may not be copied, modified, or distributed except according to
-- those terms.
prelude
import Init.NotationExtra
import GuardRefuteWf
/-!
# Negative Refutations for `Trusted.MirSemantics.Step` Guards
Covers every `.undefined` branch, move-deinitialization guard, projection
guard, static type-check guard, storage-lifecycle guard, switch-case guard,
`TerminatorKind.assert` guard, cleanup-return guard, and fail-closed unmodeled
statement/terminator guard in `Trusted/MirSemantics/Step.lean`.
-/
namespace GuardMutation
open Trusted.MirAst Trusted.MirSemantics
/-- Refutation-local `Except` projection over `CoreCallOutcome`, mapping
`.panicked` to `corePanicTrap`. -/
private noncomputable def coreOutcomeToExcept :
CoreCallOutcome → Except FaultKind (Val × MemoryState)
| .ok v m => .ok (v, m)
| .panicked => .error corePanicTrap
| .fault k => .error k
/-- Refutation-local `Except` projection over `execCoreContractOpOutcome`. -/
private noncomputable def execCoreContractOp (m : MemoryState)
(op : CoreCallOp) (args : List (MirTy × Val)) (dstTy : MirTy) :
Except FaultKind (Val × MemoryState) :=
coreOutcomeToExcept (execCoreContractOpOutcome m op args dstTy)
/-- Program reading a dead `.unit` local via `Operand.copy`. Using `.unit`
ensures the weakened mutant returns a type-compatible `Val.unit` rather than
failing a downstream type check. -/
noncomputable def progCopyDeadLocal : Program :=
mkSingleBlockProg 0 [.unit, .unit]
[.storageLive 1, .storageDead 1, .assign ⟨0, []⟩ (.use (.copy ⟨1, []⟩))]
/-- Guard `step_copy_dead_local`: `Operand.copy` on a `.dead` local faults
with `.undefined`. -/
theorem refute_step_copy_dead_local :
ReachesResult progCopyDeadLocal queryEmpty (.fault .undefined) ∧
¬ WellFormed progCopyDeadLocal queryEmpty :=
refutes_wf_of_execFault (fuel := 3) rfl
/-- Program reading a dead `.unit` local via `Operand.move`. -/
noncomputable def progMoveDeadLocal : Program :=
mkSingleBlockProg 0 [.unit, .unit]
[.storageLive 1, .storageDead 1, .assign ⟨0, []⟩ (.use (.move ⟨1, []⟩))]
/-- Guard `step_move_dead_local`: `Operand.move` on a `.dead` local faults
with `.undefined`. -/
theorem refute_step_move_dead_local :
ReachesResult progMoveDeadLocal queryEmpty (.fault .undefined) ∧
¬ WellFormed progMoveDeadLocal queryEmpty :=
refutes_wf_of_execFault (fuel := 3) rfl
/-- Program moving out of `_1 : u32` and then reading `_1` again without
re-initialization. -/
noncomputable def progUseAfterMove : Program :=
mkSingleBlockProg 1 [u32Ty, u32Ty]
[.assign ⟨0, []⟩ (.use (.move ⟨1, []⟩)),
.assign ⟨0, []⟩ (.use (.copy ⟨1, []⟩))]
/-- Guard `step_move_deinit_immediate`: moving out of an immediate non-ZST
local deinitializes it so a second read faults with `.undefined`. -/
theorem refute_step_move_deinit_immediate :
ReachesResult progUseAfterMove { args := [u32Val 7] } (.fault .undefined) ∧
¬ WellFormed progUseAfterMove { args := [u32Val 7] } :=
refutes_wf_of_execFault (fuel := 2) rfl
/-- Guard `step_move_deinit_indirect`: moving out of an `.indirect` non-ZST
local marks its memory bytes uninitialized so a subsequent read faults with
`.undefined`. -/
theorem refute_step_move_deinit_indirect :
(match initState progUseAfterMove { args := [u32Val 7] } with
| .ok s₀ =>
match forceAllocation progUseAfterMove s₀ 1 with
| .ok (s₁, _) =>
match evalStep progUseAfterMove 0 s₁ with
| .step s₂ =>
evalStep progUseAfterMove 0 s₂ = .fault .undefined
| _ => False
| .error _ => False
| .error _ => False) :=
rfl
/-- Program applying `UnOp.not` to an uninitialized `bool` local. -/
noncomputable def progPrimUninitRead : Program :=
mkSingleBlockProg 0 [.bool, .bool]
[.storageLive 1, .assign ⟨0, []⟩ (.unaryOp .not (.copy ⟨1, []⟩))]
/-- Guard `step_prim_uninit_read`: `evalPrimitiveOperand` on an uninitialized
local faults with `.undefined`. -/
theorem refute_step_prim_uninit_read :
ReachesResult progPrimUninitRead queryEmpty (.fault .undefined) ∧
¬ WellFormed progPrimUninitRead queryEmpty :=
refutes_wf_of_execFault (fuel := 2) rfl
/-- Program reading `Rvalue.discriminant` of an uninitialized scalar-tagged
enum local. -/
noncomputable def progDiscrUninitEnum : Program :=
mkSingleBlockProg 0 [u8Ty, .enum reprU8EnumTy]
[.storageLive 1, .assign ⟨0, []⟩ (.discriminant ⟨1, []⟩)]
/-- Guard `step_discriminant_uninit_enum`: `evalDiscriminantOfVal` on an
uninitialized scalar-tagged enum faults with `.undefined`. -/
theorem refute_step_discriminant_uninit_enum :
ReachesResult progDiscrUninitEnum queryEmpty (.fault .undefined) ∧
¬ WellFormed progDiscrUninitEnum queryEmpty :=
refutes_wf_of_execFault (fuel := 2) rfl
/-- Program reading `Rvalue.discriminant` of an uninitialized `Ordering`
local. -/
noncomputable def progDiscrUninitOrdering : Program :=
mkSingleBlockProg 0 [i8Ty, .ordering]
[.storageLive 1, .assign ⟨0, []⟩ (.discriminant ⟨1, []⟩)]
/-- Guard `step_discriminant_uninit_ordering`: `evalOrderingDiscriminantOfVal`
on an uninitialized `Ordering` faults with `.undefined`. -/
theorem refute_step_discriminant_uninit_ordering :
ReachesResult progDiscrUninitOrdering queryEmpty (.fault .undefined) ∧
¬ WellFormed progDiscrUninitOrdering queryEmpty :=
refutes_wf_of_execFault (fuel := 2) rfl
/-- Program copying an uninitialized `bool` local into `_0 : bool`. -/
noncomputable def progUseUninitRead : Program :=
mkSingleBlockProg 0 [.bool, .bool]
[.storageLive 1, .assign ⟨0, []⟩ (.use (.copy ⟨1, []⟩))]
/-- Guard `step_use_uninit_read`: `evalRvalue .use` on an uninitialized local
faults with `.undefined`. -/
theorem refute_step_use_uninit_read :
ReachesResult progUseUninitRead queryEmpty (.fault .undefined) ∧
¬ WellFormed progUseUninitRead queryEmpty :=
refutes_wf_of_execFault (fuel := 2) rfl
/-- Program casting an uninitialized `u8` local to `u32`. -/
noncomputable def progCastUninitRead : Program :=
mkSingleBlockProg 0 [u32Ty, u8Ty]
[.storageLive 1, .assign ⟨0, []⟩ (.cast .intToInt (.copy ⟨1, []⟩) u32Ty)]
/-- Guard `step_cast_uninit_read`: `evalRvalue (.cast .intToInt)` on an
uninitialized source local faults with `.undefined`. -/
theorem refute_step_cast_uninit_read :
ReachesResult progCastUninitRead queryEmpty (.fault .undefined) ∧
¬ WellFormed progCastUninitRead queryEmpty :=
refutes_wf_of_execFault (fuel := 2) rfl
/-- Program reading `Rvalue.discriminant` from a `.dead` `Ordering` local. -/
noncomputable def progDiscrDeadLocal : Program :=
mkSingleBlockProg 0 [i8Ty, .ordering]
[.storageLive 1, .storageDead 1, .assign ⟨0, []⟩ (.discriminant ⟨1, []⟩)]
/-- Guard `step_discriminant_dead_local`: `evalRvalue .discriminant` on a
`.dead` local faults with `.undefined`. -/
theorem refute_step_discriminant_dead_local :
ReachesResult progDiscrDeadLocal queryEmpty (.fault .undefined) ∧
¬ WellFormed progDiscrDeadLocal queryEmpty :=
refutes_wf_of_execFault (fuel := 3) rfl
/-- Program writing a constant into a `.dead` local. -/
noncomputable def progWriteDeadLocal : Program :=
mkSingleBlockProg 0 [.unit, u32Ty]
[.storageLive 1, .storageDead 1,
.assign ⟨1, []⟩ (.use (.constant ⟨u32Ty, .scalar (BitVec.ofNat 128 1)⟩))]
/-- Guard `step_write_dead_local`: `writePlace` on a `.dead` destination local
faults with `.undefined`. -/
theorem refute_step_write_dead_local :
ReachesResult progWriteDeadLocal queryEmpty (.fault .undefined) ∧
¬ WellFormed progWriteDeadLocal queryEmpty :=
refutes_wf_of_execFault (fuel := 3) rfl
/-- Program returning immediately with an uninitialized `_0 : u32`. -/
noncomputable def progReturnUninit : Program :=
mkSingleBlockProg 0 [u32Ty] [] .return_
/-- Guard `step_return_uninit_or_dead`: `TerminatorKind.return_` with an
uninitialized immediate `_0` faults with `.undefined`. -/
theorem refute_step_return_uninit_or_dead :
ReachesResult progReturnUninit queryEmpty (.fault .undefined) ∧
¬ WellFormed progReturnUninit queryEmpty :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Guard `step_return_indirect_uninit`: `TerminatorKind.return_` with an
uninitialized `.indirect` `_0` faults with `.undefined`. -/
theorem refute_step_return_indirect_uninit :
(match initState progReturnUninit queryEmpty with
| .ok s₀ =>
match forceAllocation progReturnUninit s₀ 0 with
| .ok (s₁, _) =>
evalStep progReturnUninit 0 s₁ = .fault .undefined
| .error _ => False
| .error _ => False) :=
rfl
/-- Program executing `TerminatorKind.unreachable`. -/
noncomputable def progUnreachable : Program :=
mkSingleBlockProg 0 [.unit] [] .unreachable
/-- Guard `step_unreachable_terminator`: `TerminatorKind.unreachable` faults
with `.undefined`. -/
theorem refute_step_unreachable_terminator :
ReachesResult progUnreachable queryEmpty (.fault .undefined) ∧
¬ WellFormed progUnreachable queryEmpty :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Program whose local `_1` starts `.dead` because it has a `StorageLive`
annotation in the body. -/
noncomputable def progDeadLocalForForceAlloc : Program :=
mkSingleBlockProg 0 [.unit, u32Ty] [.storageLive 1] .return_
/-- Guard `step_force_alloc_dead_local`: `forceAllocation` on a `.dead` local
faults with `.undefined`. -/
theorem refute_step_force_alloc_dead_local :
(match initState progDeadLocalForForceAlloc queryEmpty with
| .ok s₀ =>
match forceAllocation progDeadLocalForForceAlloc s₀ 1 with
| .error .undefined => True
| _ => False
| .error _ => False) :=
trivial
/-- Guard `step_v2_write_readonly`: storing through `*const u8`
(`ptrMut = .shared`) into a live `.mut` allocation faults with `.undefined`. -/
theorem refute_step_v2_write_readonly :
(match writePlaceV2
[.unit, .rawPtr .shared (.int .i8 false)]
[.immediate (some .unit), .immediate (some (.ptr ⟨some 1, 0, .isize⟩))]
{ allocations := [{
allocId := 1
alignLog2 := 0
mutability := .mut
bytes := [.init 0 none]
live := true
}], nextAllocId := 2 }
{ localId := 1, projection := [.deref] }
(.int .i8 false)
(.scalar ⟨.i8, false, BitVec.ofNat 128 7⟩) with
| .error .undefined => True
| _ => False) :=
trivial
/-- Profile v2 program taking a shared reference to stack parameter `_1 : u8`
and attempting to return it. -/
noncomputable def progDanglingStackRefV2 : Program := {
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 2
bodies := [{
argumentCount := 1
locals := [.ref .shared (.int .i8 false), .int .i8 false]
basicBlocks := [{
statements := [
.assign { localId := 0, projection := [] }
(.ref .shared { localId := 1, projection := [] })
]
terminator := .return_
}]
isUnsafe := false
identity := "guard_mutation::dangling_stack_ref_v2"
}]
}
/-- Guard `step_v2_return_dangling_stack_ref`: returning a reference to a
callee-allocated stack local faults with `.undefined`. -/
theorem refute_step_v2_return_dangling_stack_ref :
(match initStateV2 progDanglingStackRefV2
{ args := [.scalar ⟨.i8, false, BitVec.ofNat 128 42⟩] } with
| .ok s₀ =>
match evalStepV2 progDanglingStackRefV2 s₀ with
| .step s₁ =>
match evalStepV2 progDanglingStackRefV2 s₁ with
| .fault .undefined => True
| _ => False
| _ => False
| .error _ => False) :=
trivial
/-- Anti-overreach canary for zero-size raw-pointer dereference stores and
reads (`writePlaceV2` / `readPlaceV2`): `*mut ()` into a dead `.shared`
allocation succeeds consistently with `Memory.lean`. -/
theorem positive_step_v2_zst_raw_ptr_write_and_read :
(match writePlaceV2
[.unit, .rawPtr .mut .unit]
[.immediate (some .unit), .immediate (some (.ptr ⟨some 1, 0, .isize⟩))]
{ allocations := [{
allocId := 1
alignLog2 := 0
mutability := .shared
bytes := [.init 0 none]
live := false
}], nextAllocId := 2 }
{ localId := 1, projection := [.deref] }
.unit
.unit with
| .ok _ => True
| .error _ => False) ∧
(match readPlaceV2
[.unit, .rawPtr .mut .unit]
[.immediate (some .unit), .immediate (some (.ptr ⟨some 1, 0, .isize⟩))]
{ allocations := [{
allocId := 1
alignLog2 := 0
mutability := .shared
bytes := [.init 0 none]
live := false
}], nextAllocId := 2 }
false
{ localId := 1, projection := [.deref] } with
| .ok (.unit, some .unit, _, _) => True
| _ => False) :=
⟨trivial, trivial⟩
/-- Guard `step_v2_offset_dst_type`: `Offset` on a `*const u8` operand fails
closed when the destination local has a different raw-pointer type
(`*mut u64`). -/
theorem refute_step_v2_offset_dst_type :
(match evalRvalueV2
[.unit, .rawPtr .shared (.int .i8 false), .rawPtr .mut (.int .i64 false)]
[.immediate (some .unit), .immediate (some (.ptr ⟨some 1, 0, .isize⟩)),
.immediate none]
{ allocations := [{
allocId := 1
alignLog2 := 0
mutability := .mut
bytes := [.init 0 none, .init 0 none]
live := true
}], nextAllocId := 2 }
(.rawPtr .mut (.int .i64 false))
(.binaryOp .offset (.copy { localId := 1, projection := [] })
(.constant ⟨.int .isize true, .scalar (BitVec.ofNat 128 1)⟩)) with
| .error .unsupported => True
| _ => False) :=
trivial
/-- Guard `step_v2_ptr_cast_const_to_mut`: `PtrToPtr` casts from `*const u32`
to `*mut u32` and from `*const [u8]` to `*mut [u8]` fail closed, so
`&raw const x as *mut u32` cannot write to an immutable binding `x`. -/
theorem refute_step_v2_ptr_cast_const_to_mut :
(match evalRvalueV2
[.unit, .rawPtr .shared (.int .i32 false), .rawPtr .mut (.int .i32 false)]
[.immediate (some .unit), .immediate (some (.ptr ⟨some 1, 0, .isize⟩)),
.immediate none]
{ allocations := [{
allocId := 1
alignLog2 := 2
mutability := .mut
bytes := List.replicate 4 (.init 0 none)
live := true
}], nextAllocId := 2 }
(.rawPtr .mut (.int .i32 false))
(.cast .ptrToPtr (.copy { localId := 1, projection := [] })
(.rawPtr .mut (.int .i32 false))) with
| .error .unsupported => True
| _ => False) ∧
(match evalPtrToPtrCastV2 (.rawPtr .shared (.slice (.int .i8 false)))
(.slicePtr ⟨some 1, 0, .isize⟩ 4) (.rawPtr .mut (.slice (.int .i8 false))) with
| .error .unsupported => True
| _ => False) :=
⟨trivial, trivial⟩
/-- Anti-overreach canary for `step_v2_ptr_cast_const_to_mut`: `PtrToPtr`
casts that do not add mutability (`*mut u32` to `*const u32`, `*mut u32` to
`*mut u8`, `*const u32` to `*const u8`, and `*mut [u8]` to `*const [u8]`)
still succeed. -/
theorem positive_step_v2_ptr_cast_keeps_or_drops_mut :
(match evalPtrToPtrCastV2 (.rawPtr .mut (.int .i32 false))
(.ptr ⟨some 1, 0, .isize⟩) (.rawPtr .shared (.int .i32 false)) with
| .ok (.ptr ⟨some 1, 0, .isize⟩) => True
| _ => False) ∧
(match evalPtrToPtrCastV2 (.rawPtr .mut (.int .i32 false))
(.ptr ⟨some 1, 0, .isize⟩) (.rawPtr .mut (.int .i8 false)) with
| .ok (.ptr ⟨some 1, 0, .isize⟩) => True
| _ => False) ∧
(match evalPtrToPtrCastV2 (.rawPtr .shared (.int .i32 false))
(.ptr ⟨some 1, 0, .isize⟩) (.rawPtr .shared (.int .i8 false)) with
| .ok (.ptr ⟨some 1, 0, .isize⟩) => True
| _ => False) ∧
(match evalPtrToPtrCastV2 (.rawPtr .mut (.slice (.int .i8 false)))
(.slicePtr ⟨some 1, 0, .isize⟩ 4) (.rawPtr .shared (.slice (.int .i8 false))) with
| .ok (.slicePtr ⟨some 1, 0, .isize⟩ 4) => True
| _ => False) :=
⟨trivial, trivial, trivial, trivial⟩
/-- Admitted zero-sized single-variant fieldless enum (`enum One { A }`). -/
noncomputable def zstOneEnumTy : EnumTy := {
id := 7
discrWidth := .isize
discrSigned := true
tagRepr := .zeroSized
discriminants := [0]
}
/-- Anti-overreach canary for provenance-free zero-size reference
dereferences: reading and writing `*r` for `r : &mut One` holding an aligned,
non-null address without provenance succeeds, consistently with
`refValidInMem` admitting such references at entry. -/
theorem positive_step_v2_zst_enum_no_provenance_deref :
(match readPlaceV2
[.unit, .ref .mut (.enum zstOneEnumTy)]
[.immediate (some .unit), .immediate (some (.ptr ⟨none, 1, .isize⟩))]
MemoryState.empty
false
{ localId := 1, projection := [.deref] } with
| .ok (_, some (.enumVal _ 0), _, _) => True
| _ => False) ∧
(match writePlaceV2
[.unit, .ref .mut (.enum zstOneEnumTy)]
[.immediate (some .unit), .immediate (some (.ptr ⟨none, 1, .isize⟩))]
MemoryState.empty
{ localId := 1, projection := [.deref] }
(.enum zstOneEnumTy)
(.enumVal zstOneEnumTy 0) with
| .ok _ => True
| .error _ => False) :=
⟨trivial, trivial⟩
/-- Read-only 2-byte allocation with id `1` holding initialized bytes, for
the `get_unchecked` input-mutability refutations. -/
noncomputable def sharedInit2Mem : MemoryState :=
{ allocations := [{
allocId := 1
alignLog2 := 0
mutability := .shared
bytes := [.init 0 none, .init 0 none]
live := true
}], nextAllocId := 2 }
/-- Guard `step_v2_get_unchecked_range_to_in_mut`: `get_unchecked(..1)` on a
`&mut [u8]` input over a `.shared` allocation faults with `.undefined` even
though the result is `&[u8]`, because the input is validated at its own
mutability. -/
theorem refute_step_v2_get_unchecked_range_to_in_mut :
(match execCoreCallOp sharedInit2Mem .sliceGetUncheckedRangeTo
[(.ref .mut (.slice (.int .i8 false)), .slicePtr ⟨some 1, 0, .isize⟩ 2),
(.rangeTo (.int .isize false), .rangeTo 1)]
(.ref .shared (.slice (.int .i8 false))) with
| .error .undefined => True
| _ => False) :=
trivial
/-- Guard `step_v2_get_unchecked_range_from_in_mut`: `get_unchecked(1..)` on a
`&mut [u8]` input over a `.shared` allocation faults with `.undefined` even
though the result is `&[u8]`. -/
theorem refute_step_v2_get_unchecked_range_from_in_mut :
(match execCoreCallOp sharedInit2Mem .sliceGetUncheckedRangeFrom
[(.ref .mut (.slice (.int .i8 false)), .slicePtr ⟨some 1, 0, .isize⟩ 2),
(.rangeFrom (.int .isize false), .rangeFrom 1)]
(.ref .shared (.slice (.int .i8 false))) with
| .error .undefined => True
| _ => False) :=
trivial
/-- Guard `step_v2_get_unchecked_range_in_mut`: `get_unchecked(0..1)` on a
`&mut [u8]` input over a `.shared` allocation faults with `.undefined` even
though the result is `&[u8]`. -/
theorem refute_step_v2_get_unchecked_range_in_mut :
(match execCoreCallOp sharedInit2Mem .sliceGetUncheckedRange
[(.ref .mut (.slice (.int .i8 false)), .slicePtr ⟨some 1, 0, .isize⟩ 2),
(.range (.int .isize false), .range 0 1)]
(.ref .shared (.slice (.int .i8 false))) with
| .error .undefined => True
| _ => False) :=
trivial
/-- Read-only 4-byte allocation holding 2 initialized `u16` elements for the
`get_unchecked` element-stride refutations. -/
noncomputable def sharedInitU16x2Mem : MemoryState :=
{ allocations := [{
allocId := 1
alignLog2 := 1
mutability := .shared
bytes := [.init 1 none, .init 0 none, .init 2 none, .init 0 none]
live := true
}], nextAllocId := 2 }
/-- Guard `step_v2_get_unchecked_range_from_elem_stride`: `get_unchecked(1..)`
on `&[u16]` advances the slice pointer by `w.byteSize = 2` bytes per element. -/
theorem refute_step_v2_get_unchecked_range_from_elem_stride :
execCoreCallOp sharedInitU16x2Mem .sliceGetUncheckedRangeFrom
[(.ref .shared (.slice (.int .i16 false)),
.slicePtr ⟨some 1, 0, .isize⟩ 2),
(.rangeFrom (.int .isize false), .rangeFrom 1)]
(.ref .shared (.slice (.int .i16 false))) =
.ok (.slicePtr ⟨some 1, 2, .isize⟩ 1) :=
rfl
/-- Guard `step_v2_get_unchecked_range_elem_stride`: `get_unchecked(1..2)`
on `&[u16]` advances the slice pointer by `w.byteSize = 2` bytes per element. -/
theorem refute_step_v2_get_unchecked_range_elem_stride :
execCoreCallOp sharedInitU16x2Mem .sliceGetUncheckedRange
[(.ref .shared (.slice (.int .i16 false)),
.slicePtr ⟨some 1, 0, .isize⟩ 2),
(.range (.int .isize false), .range 1 2)]
(.ref .shared (.slice (.int .i16 false))) =
.ok (.slicePtr ⟨some 1, 2, .isize⟩ 1) :=
rfl
/-- Guard `step_v2_mem_size_of_unsupported_local_ty`: `core::mem::size_of`
rejects `[&u8; 2]` (not `isSupportedV2LocalTy`) as `.unsupported` even though
`layoutOfArrayV2` has pointer layout support. -/
theorem refute_step_v2_mem_size_of_unsupported_local_ty :
execCoreCallOp MemoryState.empty
(.memSizeOf (.array (.ref .shared (.int .i8 false)) 2)) []
(.int .isize false) = .error .unsupported :=
rfl
/-- Guard `step_v2_mem_size_of_isize_max`: `core::mem::size_of` on
`[u8; 2^63]` (whose `layoutOfTyV2` size is `isize::MAX + 1`) fails closed with
`.unsupported` instead of truncating to an `isize`-wide `usize`, while
`[u8; 4]` still reports `4`. -/
theorem refute_step_v2_mem_size_of_isize_max :
execCoreCallOp MemoryState.empty
(.memSizeOf (.array (.int .i8 false) (Nat.pow 2 63))) []
(.int .isize false) = .error .unsupported ∧
execCoreCallOp MemoryState.empty
(.memSizeOf (.array (.int .i8 false) 4)) []
(.int .isize false) = .ok (.scalar ⟨.isize, false, 4⟩) :=
⟨rfl, rfl⟩
/-- Guard `step_v2_int_from_le_bytes_array_len`: `intFromLeBytes` rejects a
byte array whose length disagrees with `w.byteSize` as `.unsupported`. -/
theorem refute_step_v2_int_from_le_bytes_array_len :
execCoreCallOp MemoryState.empty (.intFromLeBytes .i16 false)
[(.array (.int .i8 false) 1, .array [.scalar ⟨.i8, false, 0x34⟩])]
(.int .i16 false) = .error .unsupported :=
rfl
/-- Anti-overreach canary: the same `get_unchecked` calls (`RangeTo`,
`RangeFrom`, and `Range`) on a `&[u8]` input over `.shared` succeed. -/
theorem positive_step_v2_get_unchecked_shared_input :
(match execCoreCallOp sharedInit2Mem .sliceGetUncheckedRangeTo
[(.ref .shared (.slice (.int .i8 false)),
.slicePtr ⟨some 1, 0, .isize⟩ 2),
(.rangeTo (.int .isize false), .rangeTo 1)]
(.ref .shared (.slice (.int .i8 false))) with
| .ok _ => True
| .error _ => False) ∧
(match execCoreCallOp sharedInit2Mem .sliceGetUncheckedRangeFrom
[(.ref .shared (.slice (.int .i8 false)),
.slicePtr ⟨some 1, 0, .isize⟩ 2),
(.rangeFrom (.int .isize false), .rangeFrom 1)]
(.ref .shared (.slice (.int .i8 false))) with
| .ok _ => True
| .error _ => False) ∧
(match execCoreCallOp sharedInit2Mem .sliceGetUncheckedRange
[(.ref .shared (.slice (.int .i8 false)),
.slicePtr ⟨some 1, 0, .isize⟩ 2),
(.range (.int .isize false), .range 0 1)]
(.ref .shared (.slice (.int .i8 false))) with
| .ok _ => True
| .error _ => False) :=
⟨trivial, trivial, trivial⟩
/-- Body with locals `_0 : ()` and `_1 : *mut ()`, whose only statement
`*_1 = PtrMetadata(move _1)` moves out of the pointer it stores through. -/
noncomputable def bodyStoreThroughMovedPtr : Body := {
argumentCount := 1
locals := [.unit, .rawPtr .mut .unit]
basicBlocks := [{
statements := [.assign ⟨1, [.deref]⟩
(.unaryOp .ptrMetadata (.move ⟨1, []⟩))]
terminator := .return_
}]
}
/-- Guard `step_v2_assign_resolves_destination_first`: an assignment resolves
its destination before its rvalue runs, so `*_1 = PtrMetadata(move _1)` stores
through the pointer `_1` held before the move instead of faulting on the
moved-out slot. -/
theorem refute_step_v2_assign_resolves_destination_first :
(match evalStatementV2 bodyStoreThroughMovedPtr
{ defId := 0, blockIdx := 0, stmtIdx := 0,
locals := [.immediate (some .unit),
.immediate (some (.ptr ⟨some 1, 0, .isize⟩))] }
{ allocations := [{
allocId := 1
alignLog2 := 0
mutability := .mut
bytes := []
live := true
}], nextAllocId := 2 }
{}
(.assign ⟨1, [.deref]⟩ (.unaryOp .ptrMetadata (.move ⟨1, []⟩))) with
| .step _ => True
| _ => False) :=
trivial
/-- Guard `step_v2_raw_borrow_mut_through_const`: `&raw mut *p` through a
`*const u8` faults with `.undefined` instead of yielding a `*mut u8`. -/
theorem refute_step_v2_raw_borrow_mut_through_const :
(match evalAddressOfRvalueV2
[.unit, .rawPtr .shared (.int .i8 false), .rawPtr .mut (.int .i8 false)]
[.immediate (some .unit), .immediate (some (.ptr ⟨some 1, 0, .isize⟩)),
.immediate none]
{ allocations := [{
allocId := 1
alignLog2 := 0
mutability := .mut
bytes := [.init 0 none]
live := true
}], nextAllocId := 2 }
(.rawPtr .mut (.int .i8 false)) .mut
{ localId := 1, projection := [.deref] } with
| .error .undefined => True
| _ => False) :=
trivial
/-- Anti-overreach canary: `&raw const *p` through the same `*const u8`
still succeeds. -/
theorem positive_step_v2_raw_borrow_const_through_const :
(match evalAddressOfRvalueV2
[.unit, .rawPtr .shared (.int .i8 false), .rawPtr .shared (.int .i8 false)]
[.immediate (some .unit), .immediate (some (.ptr ⟨some 1, 0, .isize⟩)),
.immediate none]
{ allocations := [{
allocId := 1
alignLog2 := 0
mutability := .mut
bytes := [.init 0 none]
live := true
}], nextAllocId := 2 }
(.rawPtr .shared (.int .i8 false)) .shared
{ localId := 1, projection := [.deref] } with
| .ok _ => True
| .error _ => False) :=
trivial
/-! ## Partially moved overflow pairs (`LocalSlot.partialTuple`)
Under `-Coverflow-checks=yes`, rustc lowers `x + 1` to
`_t = AddWithOverflow(x, 1)`, `assert(!move (_t.1))`, and
`_r = move (_t.0)`. Moving one field leaves the other readable; the
moved field, and the tuple as a whole, must not be read again. -/
/-- Overflow pair type `(u8, bool)`. -/
noncomputable def overflowPairU8 : MirTy := .tuple [.int .i8 false, .bool]
/-- Local slots after `move (_1.1)`: field 0 still holds `7_u8`. -/
noncomputable def partialPairLocals : List LocalSlot :=
[.immediate (some .unit),
.partialTuple [some (.scalar ⟨.i8, false, BitVec.ofNat 128 7⟩), none]]
/-- Guard `step_v2_partial_tuple_move_moved_field`: moving an already moved
tuple field faults with `.undefined`. -/
theorem refute_step_v2_partial_tuple_move_moved_field :
(match readPlaceV2 [.unit, overflowPairU8] partialPairLocals
MemoryState.empty true
{ localId := 1, projection := [.field 1 .bool] } with
| .error .undefined => True
| _ => False) :=
trivial
/-- Guard `step_v2_partial_tuple_copy_moved_field`: copying an already moved
tuple field faults with `.undefined`. -/
theorem refute_step_v2_partial_tuple_copy_moved_field :
(match readPlaceV2 [.unit, overflowPairU8] partialPairLocals
MemoryState.empty false
{ localId := 1, projection := [.field 1 .bool] } with
| .error .undefined => True
| _ => False) :=
trivial
/-- Guard `step_v2_partial_tuple_whole_read`: reading a partially moved tuple
as a whole faults with `.undefined`, for both copies and moves. -/
theorem refute_step_v2_partial_tuple_whole_read :
(match readPlaceV2 [.unit, overflowPairU8] partialPairLocals
MemoryState.empty false { localId := 1, projection := [] } with
| .error .undefined => True
| _ => False) ∧
(match readPlaceV2 [.unit, overflowPairU8] partialPairLocals
MemoryState.empty true { localId := 1, projection := [] } with
| .error .undefined => True
| _ => False) :=
⟨trivial, trivial⟩
/-- Anti-overreach canary: moving field 1 and then field 0 out of an
initialized overflow pair returns both values, leaves field 0 readable in
between, and restores the uninitialized `.immediate none` slot once both
fields are moved. -/
theorem positive_step_v2_partial_tuple_moves :
readPlaceV2 [.unit, overflowPairU8]
[.immediate (some .unit),
.immediate (some (.tuple
[.scalar ⟨.i8, false, BitVec.ofNat 128 7⟩, .bool false]))]
MemoryState.empty true
{ localId := 1, projection := [.field 1 .bool] } =
.ok (.bool, some (.bool false), partialPairLocals, MemoryState.empty) ∧
readPlaceV2 [.unit, overflowPairU8] partialPairLocals
MemoryState.empty false
{ localId := 1, projection := [.field 0 (.int .i8 false)] } =
.ok (.int .i8 false, some (.scalar ⟨.i8, false, BitVec.ofNat 128 7⟩),
partialPairLocals, MemoryState.empty) ∧
readPlaceV2 [.unit, overflowPairU8] partialPairLocals
MemoryState.empty true
{ localId := 1, projection := [.field 0 (.int .i8 false)] } =
.ok (.int .i8 false, some (.scalar ⟨.i8, false, BitVec.ofNat 128 7⟩),
[.immediate (some .unit), .immediate none], MemoryState.empty) :=
⟨rfl, rfl, rfl⟩
/-- `buggy_add_u8(x: u8) -> u8 { x + 1 }` as captured under
`-Coverflow-checks=yes --panic abort` (hence the `.unreachable` unwind
action). -/
noncomputable def bodyOverflowAddV2 : Body := {
argumentCount := 1
locals := [.int .i8 false, .int .i8 false, .int .i8 false, overflowPairU8]
basicBlocks := [
{ statements := [
.storageLive 2,
.assign ⟨2, []⟩ (.use (.copy ⟨1, []⟩)),
.assign ⟨3, []⟩ (.binaryOp .addWithOverflow (.copy ⟨2, []⟩)
(.constant ⟨.int .i8 false, .scalar (BitVec.ofNat 128 1)⟩))
]
terminator := .assert (.move ⟨3, [.field 1 .bool]⟩) false
(.overflow .add) 1 .unreachable },
{ statements := [
.assign ⟨0, []⟩ (.use (.move ⟨3, [.field 0 (.int .i8 false)]⟩)),
.storageDead 2
]
terminator := .return_ }
]
isUnsafe := false
identity := "guard_mutation::overflow_add_v2"
}
/-- Profile v2 program wrapping `bodyOverflowAddV2`, with overflow checks and
the default `.unwind` panic strategy, under which a failed overflow assert
faults rather than aborting. -/
noncomputable def progOverflowAddV2 : Program := {
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 2
bodies := [bodyOverflowAddV2]
overflowChecks := true
}
/-- `progOverflowAddV2` called with `x = 255`. -/
noncomputable def queryOverflowAdd255 : Query :=
{ args := [.scalar ⟨.i8, false, BitVec.ofNat 128 255⟩] }
/-- Guard `step_v2_assert_failure_faults`: the failed overflow assert of
`255 + 1` faults instead of continuing with the wrapped sum, so
`WellFormedV2` (and hence any Profile v2 verification theorem) is refuted. -/
theorem refute_step_v2_assert_failure_faults :
ReachesResultV2 progOverflowAddV2 queryOverflowAdd255
(.fault .unsupported) ∧
¬ WellFormedV2 progOverflowAddV2 queryOverflowAdd255 := by
have hReach : ReachesResultV2 progOverflowAddV2 queryOverflowAdd255
(.fault .unsupported) := by
unfold ReachesResultV2
change ∃ s : State, ReachesV2 progOverflowAddV2 _ s ∧
StepV2 progOverflowAddV2 s (.fault .unsupported)
exact ⟨_,
ReachesV2.tail (ReachesV2.tail (ReachesV2.tail (ReachesV2.refl _)
⟨0, rfl, rfl⟩) ⟨0, rfl, rfl⟩) ⟨0, rfl, rfl⟩,
⟨0, rfl, rfl⟩⟩
exact ⟨hReach, fun hWf => hWf.2 .unsupported hReach⟩
/-! The run below is split into one declaration per state so that no single
proof has to evaluate all seven steps of `progOverflowAddV2`. -/
/-- `progOverflowAddV2` called with `x = 254`. -/
noncomputable def queryOverflowAdd254 : Query :=
{ args := [.scalar ⟨.i8, false, BitVec.ofNat 128 254⟩] }
/-- Entry state of `progOverflowAddV2` on `queryOverflowAdd254`. -/
noncomputable def overflowAdd254S0 : State :=
match initStateV2 progOverflowAddV2 queryOverflowAdd254 with
| .ok s => s
| .error _ => { frames := [], mem := MemoryState.empty }
/-- Successor of `s` under `progOverflowAddV2` (or `s` itself when the step
does not continue). -/
noncomputable def overflowAdd254Next (s : State) : State :=
match evalStepV2 progOverflowAddV2 s with
| .step s' => s'
| _ => s
noncomputable def overflowAdd254S1 : State :=
overflowAdd254Next overflowAdd254S0
noncomputable def overflowAdd254S2 : State :=
overflowAdd254Next overflowAdd254S1
noncomputable def overflowAdd254S3 : State :=
overflowAdd254Next overflowAdd254S2
noncomputable def overflowAdd254S4 : State :=
overflowAdd254Next overflowAdd254S3
noncomputable def overflowAdd254S5 : State :=
overflowAdd254Next overflowAdd254S4
noncomputable def overflowAdd254S6 : State :=
overflowAdd254Next overflowAdd254S5
/-- Terminal output of the final step from `overflowAdd254S6`. -/
noncomputable def overflowAdd254Out : Out :=
match evalStepV2 progOverflowAddV2 overflowAdd254S6 with
| .done (.returned out) => out
| _ => ⟨.unit, ⟨[]⟩⟩
theorem overflowAdd254_init :
initStateV2 progOverflowAddV2 queryOverflowAdd254 = .ok overflowAdd254S0 :=
rfl
theorem overflowAdd254_step1 :
StepV2 progOverflowAddV2 overflowAdd254S0 (.step overflowAdd254S1) :=
⟨0, rfl, rfl⟩
theorem overflowAdd254_step2 :
StepV2 progOverflowAddV2 overflowAdd254S1 (.step overflowAdd254S2) :=
⟨0, rfl, rfl⟩
theorem overflowAdd254_step3 :
StepV2 progOverflowAddV2 overflowAdd254S2 (.step overflowAdd254S3) :=
⟨0, rfl, rfl⟩
theorem overflowAdd254_step4 :
StepV2 progOverflowAddV2 overflowAdd254S3 (.step overflowAdd254S4) :=
⟨0, rfl, rfl⟩
theorem overflowAdd254_step5 :
StepV2 progOverflowAddV2 overflowAdd254S4 (.step overflowAdd254S5) :=
⟨0, rfl, rfl⟩
theorem overflowAdd254_step6 :
StepV2 progOverflowAddV2 overflowAdd254S5 (.step overflowAdd254S6) :=
⟨0, rfl, rfl⟩
theorem overflowAdd254_done :
StepV2 progOverflowAddV2 overflowAdd254S6
(.done (.returned overflowAdd254Out)) :=
⟨0, rfl, rfl⟩
theorem overflowAdd254_ret :
overflowAdd254Out.ret = .scalar ⟨.i8, false, BitVec.ofNat 128 255⟩ :=
rfl
/-- Anti-overreach canary: `progOverflowAddV2` with `x = 254` passes its
overflow assert and returns `255`. -/
theorem positive_step_v2_overflow_assert_passes :
∃ out : Out,
ReachesResultV2 progOverflowAddV2
{ args := [.scalar ⟨.i8, false, BitVec.ofNat 128 254⟩] }
(.done (.returned out)) ∧
out.ret = .scalar ⟨.i8, false, BitVec.ofNat 128 255⟩ := by
refine ⟨overflowAdd254Out, ?_, overflowAdd254_ret⟩
change ReachesResultV2 progOverflowAddV2 queryOverflowAdd254 _
unfold ReachesResultV2
rw [overflowAdd254_init]
exact ⟨_,
ReachesV2.tail (ReachesV2.tail (ReachesV2.tail (ReachesV2.tail
(ReachesV2.tail (ReachesV2.tail (ReachesV2.refl _)
overflowAdd254_step1) overflowAdd254_step2) overflowAdd254_step3)
overflowAdd254_step4) overflowAdd254_step5) overflowAdd254_step6,
overflowAdd254_done⟩
/-- Two-frame program calling a `u32`-returning helper whose `_0` remains
uninitialized on `.return_`. -/
noncomputable def progNonRootRetUninit : Program where
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 1
bodies := [
{
identity := "entry"
argumentCount := 0
locals := [u32Ty]
basicBlocks := [
{
statements := []
terminator := .call 1 [] ⟨0, []⟩ (some 1) .continue_
},
{
statements := []
terminator := .return_
}
]
},
{
identity := "callee"
argumentCount := 0
locals := [u32Ty]
basicBlocks := [{ statements := [], terminator := .return_ }]
}
]
/-- Guard `step_nonroot_return_uninit_or_dead`: `evalNonRootReturn` faults
with `.undefined` when a callee executes `.return_` with an uninitialized or
dead `_0`. -/
theorem refute_step_nonroot_return_uninit_or_dead :
ReachesResult progNonRootRetUninit queryEmpty (.fault .undefined) ∧
¬ WellFormed progNonRootRetUninit queryEmpty :=
refutes_wf_of_execFault (fuel := 3) rfl
/-- Two-frame program executing a diverging `.call` (`target := none`) whose
callee returns normally. -/
noncomputable def progNonRootRetNoneTarget : Program where
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 1
bodies := [
{
identity := "entry"
argumentCount := 0
locals := [u32Ty]
basicBlocks := [
{
statements := []
terminator := .call 1 [] ⟨0, []⟩ none .continue_
}
]
},
{
identity := "callee"
argumentCount := 0
locals := [u32Ty]
basicBlocks := [
{
statements := [
.assign ⟨0, []⟩
(.use (.constant ⟨u32Ty, .scalar (BitVec.ofNat 128 42)⟩))
]
terminator := .return_
}
]
}
]
/-- Guard `step_nonroot_return_none_target`: `evalNonRootReturn` faults with
`.undefined` when a callee returns from a call whose caller supplied
`target := none`. -/
theorem refute_step_nonroot_return_none_target :
ReachesResult progNonRootRetNoneTarget queryEmpty (.fault .undefined) ∧
¬ WellFormed progNonRootRetNoneTarget queryEmpty :=
refutes_wf_of_execFault (fuel := 3) rfl
/-- Single-frame program invoking `u16::unchecked_add(65535, 1)` via
`TerminatorKind.sysrootCall`. -/
noncomputable def progSysrootAddUbRefute : Program where
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 1
bodies := [
{
identity := "entry"
argumentCount := 0
locals := [.int .i16 false]
basicBlocks := [
{
statements := []
terminator := .sysrootCall
{ kind := .uncheckedAdd, width := .i16, signed := false }
[.constant ⟨.int .i16 false, .scalar (BitVec.ofNat 128 65535)⟩,
.constant ⟨.int .i16 false, .scalar (BitVec.ofNat 128 1)⟩]
⟨0, []⟩ (some 1) .continue_
},
{
statements := []
terminator := .return_
}
]
}
]
/-- Guard `state_sysroot_unchecked_add_ub`: `sysrootNumBinOp .uncheckedAdd` maps
to `.addUnchecked`, so overflowing `u16::unchecked_add` faults `.undefined`. -/
theorem refute_state_sysroot_unchecked_add_ub :
ReachesResult progSysrootAddUbRefute queryEmpty (.fault .undefined) ∧
¬ WellFormed progSysrootAddUbRefute queryEmpty :=
refutes_wf_of_execFault (fuel := 4) rfl
/-- Single-frame program invoking `u16::unchecked_sub(0, 1)` via
`TerminatorKind.sysrootCall`. -/
noncomputable def progSysrootSubUbRefute : Program where
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 1
bodies := [
{
identity := "entry"
argumentCount := 0
locals := [.int .i16 false]
basicBlocks := [
{
statements := []
terminator := .sysrootCall
{ kind := .uncheckedSub, width := .i16, signed := false }
[.constant ⟨.int .i16 false, .scalar (BitVec.ofNat 128 0)⟩,
.constant ⟨.int .i16 false, .scalar (BitVec.ofNat 128 1)⟩]
⟨0, []⟩ (some 1) .continue_
},
{
statements := []
terminator := .return_
}
]
}
]
/-- Guard `state_sysroot_unchecked_sub_ub`: `sysrootNumBinOp .uncheckedSub` maps
to `.subUnchecked`, so underflowing `u16::unchecked_sub` faults `.undefined`. -/
theorem refute_state_sysroot_unchecked_sub_ub :
ReachesResult progSysrootSubUbRefute queryEmpty (.fault .undefined) ∧
¬ WellFormed progSysrootSubUbRefute queryEmpty :=
refutes_wf_of_execFault (fuel := 4) rfl
/-- Single-frame program invoking `u16::unchecked_mul(256, 256)` via
`TerminatorKind.sysrootCall`. -/
noncomputable def progSysrootMulUbRefute : Program where
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 1
bodies := [
{
identity := "entry"
argumentCount := 0
locals := [.int .i16 false]
basicBlocks := [
{
statements := []
terminator := .sysrootCall
{ kind := .uncheckedMul, width := .i16, signed := false }
[.constant ⟨.int .i16 false, .scalar (BitVec.ofNat 128 256)⟩,
.constant ⟨.int .i16 false, .scalar (BitVec.ofNat 128 256)⟩]
⟨0, []⟩ (some 1) .continue_
},
{
statements := []
terminator := .return_
}
]
}
]
/-- Guard `state_sysroot_unchecked_mul_ub`: `sysrootNumBinOp .uncheckedMul` maps
to `.mulUnchecked`, so overflowing `u16::unchecked_mul` faults `.undefined`. -/
theorem refute_state_sysroot_unchecked_mul_ub :
ReachesResult progSysrootMulUbRefute queryEmpty (.fault .undefined) ∧
¬ WellFormed progSysrootMulUbRefute queryEmpty :=
refutes_wf_of_execFault (fuel := 4) rfl
/-- Two-frame program in which a safe entry body calls an intra-crate
`unsafe fn` that returns normally. -/
noncomputable def progUnsafeCalleeRefute : Program where
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 1
bodies := [
{
identity := "entry"
argumentCount := 0
locals := [u32Ty]
basicBlocks := [
{
statements := []
terminator := .call 1 [] ⟨0, []⟩ (some 1) .continue_
},
{
statements := []
terminator := .return_
}
]
},
{
identity := "callee"
isUnsafe := true
argumentCount := 0
locals := [u32Ty]
basicBlocks := [
{
statements := [
.assign ⟨0, []⟩
(.use (.constant ⟨u32Ty, .scalar (BitVec.ofNat 128 7)⟩))]
terminator := .return_
}
]
}
]
/-- Guard `state_calls_admitted_unsafe_callee`: `callsAdmitted` rejects an
intra-crate `.call` to an `unsafe fn`, so `initState` fails closed with
`.unsupported` instead of running the callee without its safety contract. -/
theorem refute_state_calls_admitted_unsafe_callee :
ReachesResult progUnsafeCalleeRefute queryEmpty (.fault .unsupported) ∧
¬ WellFormed progUnsafeCalleeRefute queryEmpty :=
refutes_wf_of_execFault (fuel := 4) rfl
/-- Guard `step_nonroot_return_indirect_local`: `evalNonRootReturn` fails
closed with `.unsupported` when the popped callee frame still holds an
`.indirect` stack allocation, rather than leaking it. -/
theorem refute_step_nonroot_return_indirect_local :
evalNonRootReturn progNonRootRetUninit
{ identity := "callee", argumentCount := 0, locals := [u32Ty],
basicBlocks := [{ statements := [], terminator := .return_ }] }
{ statements := [], terminator := .return_ }
{ defId := 1, blockIdx := 0, stmtIdx := 0,
locals := [.immediate (some (.scalar ⟨.i32, false, BitVec.ofNat 128 7⟩)),
.indirect ⟨1, 0⟩],
retDst? := some ⟨0, []⟩, retTarget? := some 1 }
{ defId := 0, blockIdx := 0, stmtIdx := 0, locals := [.immediate none] }
[] entryMemory ⟨[]⟩ = .fault .unsupported :=
rfl
/-- Guard `step_v2_constant_index_min_len`: `ConstantIndex` rejects arrays
shorter than `minLength` as `.undefined`. -/
theorem refute_step_v2_constant_index_min_len :
constantIndexOffset 2 0 4 false = .error .undefined :=
rfl
/-- Guard `step_v2_constant_index_oob`: `ConstantIndex` rejects out-of-bounds
indices `off ≥ len` as `.undefined`. -/
theorem refute_step_v2_constant_index_oob :
constantIndexOffset 2 3 2 false = .error .undefined :=
rfl
/-- Guard `step_v2_read_deref_proj_raw_misaligned`: reading a sub-field
`(*p).1` (`bool`) through a misaligned `*const (u32, bool)` faults with
`.undefined` even though the `bool` leaf itself has alignment 1. -/
theorem refute_step_v2_read_deref_proj_raw_misaligned :
(match readPlaceV2
[.bool, .rawPtr .shared (.tuple [.int .i32 false, .bool])]
[.immediate none, .immediate (some (.ptr ⟨some 1, 1, .isize⟩))]
{ allocations := [{
allocId := 1
alignLog2 := 2
mutability := .shared
bytes := [
.init 0 none, .init 0 none, .init 0 none, .init 0 none,
.init 0 none, .init 1 none, .init 0 none, .init 0 none
]
live := true
}], nextAllocId := 2 }
false
{ localId := 1, projection := [.deref, .field 1 .bool] } with
| .error .undefined => True
| _ => False) :=
trivial
/-- Guard `step_v2_read_deref_proj_no_prov_misaligned`: reading a zero-sized
element `(*p)[0]` (`[u32; 0]`, align 4) through a provenance-free misaligned
`*const [[u32; 0]; 2]` at address `2` faults with `.undefined`. -/
theorem refute_step_v2_read_deref_proj_no_prov_misaligned :
(match readPlaceV2
[.array (.int .i32 false) 0,
.rawPtr .shared (.array (.array (.int .i32 false) 0) 2)]
[.immediate none, .immediate (some (.ptr ⟨none, 2, .isize⟩))]
MemoryState.empty
false
{ localId := 1, projection := [.deref, .constantIndex 0 1 false] } with
| .error .undefined => True
| _ => False) :=
trivial
/-- `#[repr(C)] struct S1 { x: u64, z: () }` (`size = 8`, `z` at offset `8`). -/
private noncomputable def zstTrailingS1Ty : MirTy :=
.struct_ ⟨201, 8, 3, [0, 8]⟩ [.int .i64 false, .unit]
/-- `#[repr(C)] struct S2 { x: u64, y: u64, z: () }` (`size = 16`, `z` at
offset `16`). -/
private noncomputable def zstTrailingS2Ty : MirTy :=
.struct_ ⟨202, 16, 3, [0, 8, 16]⟩ [.int .i64 false, .int .i64 false, .unit]
/-- `#[repr(C)] struct S0 { z: (), x: u64 }` (`size = 8`, `z` at offset `0`). -/
private noncomputable def zstLeadingS0Ty : MirTy :=
.struct_ ⟨203, 8, 3, [0, 0]⟩ [.unit, .int .i64 false]
/-- `enum SingleZst { A(()) }` (1-variant zero-sized payload enum). -/
private noncomputable def zstSingleEnumTy : MirTy :=
.adtEnum ⟨204, 0, 0, .isize, true, [0], 0, .i8, false, 0, 0, .single⟩
[.struct_ ⟨205, 0, 0, [0]⟩ [.unit]]
/-- `#[repr(C)] struct SE1 { x: u64, e: SingleZst }` (`e` at offset `8`). -/
private noncomputable def zstTrailingEnumSE1Ty : MirTy :=
.struct_ ⟨206, 8, 3, [0, 8]⟩ [.int .i64 false, zstSingleEnumTy]
/-- `#[repr(C)] struct SE2 { x: u64, y: u64, e: SingleZst }` (`e` at offset
`16`). -/
private noncomputable def zstTrailingEnumSE2Ty : MirTy :=
.struct_ ⟨207, 16, 3, [0, 8, 16]⟩
[.int .i64 false, .int .i64 false, zstSingleEnumTy]
/-- `#[repr(C)] struct SE0 { e: SingleZst, x: u64 }` (`e` at offset `0`). -/
private noncomputable def zstLeadingEnumSE0Ty : MirTy :=
.struct_ ⟨208, 8, 3, [0, 0]⟩ [zstSingleEnumTy, .int .i64 false]
/-- 8-byte aligned allocation `1` with liveness `live`. -/
private noncomputable def zstTestMem (live : Bool) : MemoryState :=
{ allocations := [{
allocId := 1
alignLog2 := 3
mutability := .shared
bytes := [
.init 0 none, .init 0 none, .init 0 none, .init 0 none,
.init 0 none, .init 0 none, .init 0 none, .init 0 none
]
live := live
}], nextAllocId := 2 }
/-- Guard `step_v2_read_deref_proj_no_prov_nonzero_zst`: reading a trailing
zero-sized field `(*p).z` (`subOff = 8`) through a provenance-free aligned
raw pointer (`8usize as *const S1`) faults with `.undefined`, while reading a
zero-offset zero-sized field `(*p).z` (`subOff = 0`) still succeeds. -/
theorem refute_step_v2_read_deref_proj_no_prov_nonzero_zst :
let locals : List LocalSlot :=
[.immediate none, .immediate (some (.ptr ⟨none, 8, .isize⟩))]
readPlaceV2 [.unit, .rawPtr .shared zstTrailingS1Ty] locals
MemoryState.empty false
{ localId := 1, projection := [.deref, .field 1 .unit] } =
.error .undefined ∧
readPlaceV2 [.unit, .rawPtr .shared zstLeadingS0Ty] locals
MemoryState.empty false
{ localId := 1, projection := [.deref, .field 0 .unit] } =
.ok (.unit, some .unit, locals, MemoryState.empty) :=
⟨rfl, rfl⟩
/-- Guard `step_v2_read_deref_proj_dangling_nonzero_zst`: reading a trailing
zero-sized field `(*p).z` (`subOff = 8`) through a dangling raw pointer after
`StorageDead` faults with `.undefined`, while the same read on a live
allocation and a zero-offset zero-sized read (`subOff = 0`) on the dangling
allocation both succeed. -/
theorem refute_step_v2_read_deref_proj_dangling_nonzero_zst :
let locals : List LocalSlot :=
[.immediate none, .immediate (some (.ptr ⟨some 1, 0, .isize⟩))]
let deadMem := zstTestMem false
let liveMem := zstTestMem true
readPlaceV2 [.unit, .rawPtr .shared zstTrailingS1Ty] locals
deadMem false
{ localId := 1, projection := [.deref, .field 1 .unit] } =
.error .undefined ∧
readPlaceV2 [.unit, .rawPtr .shared zstTrailingS1Ty] locals
liveMem false
{ localId := 1, projection := [.deref, .field 1 .unit] } =
.ok (.unit, some .unit, locals, liveMem) ∧
readPlaceV2 [.unit, .rawPtr .shared zstLeadingS0Ty] locals
deadMem false
{ localId := 1, projection := [.deref, .field 0 .unit] } =
.ok (.unit, some .unit, locals, deadMem) :=
⟨rfl, rfl, rfl⟩
/-- Guard `step_v2_read_deref_proj_oob_nonzero_zst`: reading a trailing
zero-sized field `(*p).z` (`subOff = 16`) through an out-of-bounds raw pointer
pointing at an 8-byte live allocation (`(&raw const a_u64) as *const S2`)
faults with `.undefined`, while an in-bounds `subOff = 8` read succeeds. -/
theorem refute_step_v2_read_deref_proj_oob_nonzero_zst :
let locals : List LocalSlot :=
[.immediate none, .immediate (some (.ptr ⟨some 1, 0, .isize⟩))]
let liveMem := zstTestMem true
readPlaceV2 [.unit, .rawPtr .shared zstTrailingS2Ty] locals
liveMem false
{ localId := 1, projection := [.deref, .field 2 .unit] } =
.error .undefined ∧
readPlaceV2 [.unit, .rawPtr .shared zstTrailingS1Ty] locals
liveMem false
{ localId := 1, projection := [.deref, .field 1 .unit] } =
.ok (.unit, some .unit, locals, liveMem) :=
⟨rfl, rfl⟩
/-- Guard `step_v2_read_deref_proj_downcast_dangling_nonzero_zst`: downcasting
and reading a trailing zero-sized 1-variant enum field `((*p).e as A).0`
(`subOff = 8`) through a dangling raw pointer faults with `.undefined`, while
the same read on a live allocation and a zero-offset downcast (`subOff = 0`)
on the dangling allocation succeed. -/
theorem refute_step_v2_read_deref_proj_downcast_dangling_nonzero_zst :
let locals : List LocalSlot :=
[.immediate none, .immediate (some (.ptr ⟨some 1, 0, .isize⟩))]
let deadMem := zstTestMem false
let liveMem := zstTestMem true
readPlaceV2 [.unit, .rawPtr .shared zstTrailingEnumSE1Ty] locals
deadMem false
{ localId := 1,
projection := [.deref, .field 1 zstSingleEnumTy, .downcast 0, .field 0 .unit] } =
.error .undefined ∧
readPlaceV2 [.unit, .rawPtr .shared zstTrailingEnumSE1Ty] locals
liveMem false
{ localId := 1,
projection := [.deref, .field 1 zstSingleEnumTy, .downcast 0, .field 0 .unit] } =
.ok (.unit, some .unit, locals, liveMem) ∧
readPlaceV2 [.unit, .rawPtr .shared zstLeadingEnumSE0Ty] locals
deadMem false
{ localId := 1,
projection := [.deref, .field 0 zstSingleEnumTy, .downcast 0, .field 0 .unit] } =
.ok (.unit, some .unit, locals, deadMem) :=
⟨rfl, rfl, rfl⟩
/-- Guard `step_v2_read_deref_proj_downcast_oob_nonzero_zst`: downcasting and
reading a trailing zero-sized 1-variant enum field `((*p).e as A).0`
(`subOff = 16 > 8`) through an out-of-bounds raw pointer faults with
`.undefined`, while an in-bounds `subOff = 8` downcast read succeeds. -/
theorem refute_step_v2_read_deref_proj_downcast_oob_nonzero_zst :
let locals : List LocalSlot :=
[.immediate none, .immediate (some (.ptr ⟨some 1, 0, .isize⟩))]
let liveMem := zstTestMem true
readPlaceV2 [.unit, .rawPtr .shared zstTrailingEnumSE2Ty] locals
liveMem false
{ localId := 1,
projection := [.deref, .field 2 zstSingleEnumTy, .downcast 0, .field 0 .unit] } =
.error .undefined ∧
readPlaceV2 [.unit, .rawPtr .shared zstTrailingEnumSE1Ty] locals
liveMem false
{ localId := 1,
projection := [.deref, .field 1 zstSingleEnumTy, .downcast 0, .field 0 .unit] } =
.ok (.unit, some .unit, locals, liveMem) :=
⟨rfl, rfl⟩
/-- Guard `step_v2_unsize_shared_to_mut`: `CastKind.unsize` rejects widening a
shared `&[T; N]` into `&mut [T]` as `.undefined` even on a `.mut`
allocation. -/
theorem refute_step_v2_unsize_shared_to_mut :
(match evalRvalueV2
[.ref .mut (.slice (.int .i8 false)),
.ref .shared (.array (.int .i8 false) 2)]
[.immediate none, .immediate (some (.ptr ⟨some 1, 0, .isize⟩))]
{ allocations := [{
allocId := 1
alignLog2 := 0
mutability := .mut
bytes := [.init 1 none, .init 2 none]
live := true
}], nextAllocId := 2 }
(.ref .mut (.slice (.int .i8 false)))
(.cast .unsize (.copy ⟨1, []⟩) (.ref .mut (.slice (.int .i8 false)))) with
| .error .undefined => True
| _ => False) :=
trivial
/-- Guard `step_v2_unsize_raw_shared_to_mut`: `CastKind.unsize` rejects
widening `*const [T; N]` into `*mut [T]` as `.undefined`. -/
theorem refute_step_v2_unsize_raw_shared_to_mut :
(match evalRvalueV2
[.rawPtr .mut (.slice (.int .i8 false)),
.rawPtr .shared (.array (.int .i8 false) 2)]
[.immediate none, .immediate (some (.ptr ⟨some 1, 0, .isize⟩))]
{ allocations := [{
allocId := 1
alignLog2 := 0
mutability := .mut
bytes := [.init 1 none, .init 2 none]
live := true
}], nextAllocId := 2 }
(.rawPtr .mut (.slice (.int .i8 false)))
(.cast .unsize (.copy ⟨1, []⟩) (.rawPtr .mut (.slice (.int .i8 false)))) with
| .error .undefined => True
| _ => False) :=
trivial
/-- Guard `step_v2_unsize_src_mut_valid`: `CastKind.unsize` validates the
source `&mut [T; N]` at `srcMut` (`.mut`), faulting `.undefined` over a
`.shared` allocation even when the destination slice is `&[T]` (`.shared`). -/
theorem refute_step_v2_unsize_src_mut_valid :
(match evalRvalueV2
[.ref .shared (.slice (.int .i8 false)),
.ref .mut (.array (.int .i8 false) 2)]
[.immediate none, .immediate (some (.ptr ⟨some 1, 0, .isize⟩))]
{ allocations := [{
allocId := 1
alignLog2 := 0
mutability := .shared
bytes := [.init 1 none, .init 2 none]
live := true
}], nextAllocId := 2 }
(.ref .shared (.slice (.int .i8 false)))
(.cast .unsize (.copy ⟨1, []⟩)
(.ref .shared (.slice (.int .i8 false)))) with
| .error .undefined => True
| _ => False) :=
trivial
/-- Guard `step_v2_resolve_deref_proj_propagates_ub`: resolving an out-of-bounds
`ConstantIndex` through `&mut [u8; 4]` propagates `.error .undefined` rather
than collapsing it to `.error .unsupported`. -/
theorem refute_step_v2_resolve_deref_proj_propagates_ub :
(match resolvePlaceDestV2
[.unit, .ref .mut (.array (.int .i8 false) 4)]
[.immediate none, .immediate (some (.ptr ⟨some 1, 0, .isize⟩))]
{ allocations := [{
allocId := 1
alignLog2 := 0
mutability := .mut
bytes := [.init 0 none, .init 0 none, .init 0 none, .init 0 none]
live := true
}], nextAllocId := 2 }
{ localId := 1, projection := [.deref, .constantIndex 5 4 false] }
(.int .i8 false) with
| .error .undefined => True
| _ => False) :=
trivial
/-- Guard `step_v2_rodata_bytes_data_ty_only`: evaluating `ConstLit.rodataBytes`
at a reference type fails closed with `.error .unsupported` instead of decoding
a null or dangling reference. -/
theorem refute_step_v2_rodata_bytes_data_ty_only :
(match evalOperandToSlotV2
[.unit]
[.immediate none]
emptyMemory
(.constant ⟨.ref .mut (.int .i8 false),
.rodataBytes (List.replicate 8 (.init 0))⟩) with
| .error .unsupported => True
| _ => False) :=
trivial
/-- Guard `step_v2_rodata_ref_mut`: evaluating `.rodataRef` at a mutable
`&mut T` reference type fails closed with `.unsupported`. -/
theorem refute_step_v2_rodata_ref_mut :
(match evalRodataRefConstV2
(.ref .mut (.int .i8 false)) [.init 5] 0 0 none
[.immediate none] emptyMemory with
| .error .unsupported => True
| _ => False) :=
trivial
/-- Guard `step_v2_rodata_slice_ref_mut`: evaluating `.rodataRef` at a mutable
`&mut [T]` slice reference type fails closed with `.unsupported`. -/
theorem refute_step_v2_rodata_slice_ref_mut :
(match evalRodataRefConstV2
(.ref .mut (.slice (.int .i8 false))) [.init 5] 0 0 (some 1)
[.immediate none] emptyMemory with
| .error .unsupported => True
| _ => False) :=
trivial
/-- Guard `step_v2_rodata_raw_ptr_mut`: evaluating `.rodataRef` at a mutable
`*mut T` raw-pointer type fails closed with `.unsupported`. -/
theorem refute_step_v2_rodata_raw_ptr_mut :
(match evalRodataRefConstV2
(.rawPtr .mut (.int .i8 false)) [.init 5] 0 0 none
[.immediate none] emptyMemory with
| .error .unsupported => True
| _ => False) :=
trivial
/-- Guard `step_v2_rodata_raw_slice_mut`: evaluating `.rodataRef` at a mutable
`*mut [T]` raw-slice type fails closed with `.unsupported`. -/
theorem refute_step_v2_rodata_raw_slice_mut :
(match evalRodataRefConstV2
(.rawPtr .mut (.slice (.int .i8 false))) [.init 5] 0 0 (some 1)
[.immediate none] emptyMemory with
| .error .unsupported => True
| _ => False) :=
trivial
/-- Guard `step_v2_array_eq_dangling_ref`: `CoreCallOp.arrayEq` validates
reference operands via `refValidInMem`, faulting `.undefined` on `&mut [u8; 2]`
over a `.shared` allocation (so skipping validation flips to `.ok true`). -/
theorem refute_step_v2_array_eq_dangling_ref :
(match execCoreCallOp
{ allocations := [{
allocId := 1
alignLog2 := 0
mutability := .shared
bytes := [.init 1 none, .init 2 none]
live := true
}], nextAllocId := 2 }
(.arrayEq (.int .i8 false) 2)
[(.ref .mut (.array (.int .i8 false) 2), .ptr ⟨some 1, 0, .isize⟩),
(.ref .shared (.array (.int .i8 false) 2), .ptr ⟨some 1, 0, .isize⟩)]
.bool with
| .error .undefined => True
| _ => False) :=
trivial
/-- Guard `step_v2_core_call_partial_eq_ne_routed`:
`execCoreCallOpWithMemOutcome` routes `CoreCallOp.partialEqNe` to
`execCoreCallOp`, so `ne` on two equal `[u8; 2]` values returns `false`
(dropping the route falls through to the `core` contracts, which fault
`.unsupported`). -/
theorem refute_step_v2_core_call_partial_eq_ne_routed :
(match execCoreCallOpWithMemOutcome
{ allocations := [{
allocId := 1
alignLog2 := 0
mutability := .shared
bytes := [.init 1 none, .init 2 none]
live := true
}], nextAllocId := 2 }
(.partialEqNe (.array (.int .i8 false) 2))
[(.ref .shared (.array (.int .i8 false) 2), .ptr ⟨some 1, 0, .isize⟩),
(.ref .shared (.array (.int .i8 false) 2), .ptr ⟨some 1, 0, .isize⟩)]
.bool with
| .ok (.bool false) _ => True
| _ => False) :=
trivial
/-- Guard `step_v2_borrow_deref_projection_ub`: borrowing an out-of-bounds
constant index below a dereferenced `&mut [u8; 4]` (`&(*_1)[4]`) faults with
`.undefined` (the `projectMemoryLayoutV2` fault), not `.unsupported`. -/
theorem refute_step_v2_borrow_deref_projection_ub :
(match placeAddrV2 [.unit, .ref .mut (.array (.int .i8 false) 4)]
[.immediate none, .immediate (some (.ptr ⟨some 1, 0, .isize⟩))]
emptyMemory true 1 [.deref, .constantIndex 4 5 false] with
| .error .undefined => True
| _ => False) :=
trivial
/-- Guard `step_v2_return_rodata_unsupported`: returning either a `&'static`
reference or a `*const` raw pointer into a callee-allocated `.rodata`
allocation faults with `.fault .unsupported` (neither `.undefined` nor
returning a dangling allocation id). -/
theorem refute_step_v2_return_rodata_unsupported :
let roMem : MemoryState := {
allocations := [{
allocId := 1
alignLog2 := 0
mutability := .shared
bytes := [.init 1 none, .init 2 none]
live := true
}]
nextAllocId := 2
}
let bb : BasicBlock :=
{ statements := [], terminator := .return_, cleanup := false }
let refBody : Body := {
argumentCount := 0
locals := [.ref .shared (.slice (.int .i8 false))]
basicBlocks := [bb]
}
let ptrBody : Body := {
argumentCount := 0
locals := [.rawPtr .shared (.array (.int .i8 false) 2)]
basicBlocks := [bb]
}
let refFrame : FrameState := {
defId := 0
blockIdx := 0
stmtIdx := 0
locals := [.immediate (some (.slicePtr ⟨some 1, 0, .isize⟩ 2))]
}
let ptrFrame : FrameState := {
defId := 0
blockIdx := 0
stmtIdx := 0
locals := [.immediate (some (.ptr ⟨some 1, 0, .isize⟩))]
}
(match evalTerminatorV2 refBody bb refFrame roMem { allocations := [] } with
| .fault .unsupported => True
| _ => False) ∧
(match evalTerminatorV2 ptrBody bb ptrFrame roMem { allocations := [] } with
| .fault .unsupported => True
| _ => False) :=
⟨trivial, trivial⟩
/-- Guard `bytes_v2_ptr_or_ref_alloc_ids_option`: returning `Some` of a
`*const u8` or a `&u8` into a callee-allocated `.rodata` allocation faults
with `.fault .unsupported`, because `ptrOrRefAllocIds` looks through the
`Option` payload. -/
theorem refute_step_v2_return_rodata_option_ptr :
let roMem : MemoryState := {
allocations := [{
allocId := 1
alignLog2 := 0
mutability := .shared
bytes := [.init 1 none]
live := true
}]
nextAllocId := 2
}
let bb : BasicBlock :=
{ statements := [], terminator := .return_, cleanup := false }
let ptrBody : Body := {
argumentCount := 0
locals := [.option (.rawPtr .shared (.int .i8 false))]
basicBlocks := [bb]
}
let refBody : Body := {
argumentCount := 0
locals := [.option (.ref .shared (.int .i8 false))]
basicBlocks := [bb]
}
let frame : FrameState := {
defId := 0
blockIdx := 0
stmtIdx := 0
locals :=
[.immediate (some (.optionVal (some (.ptr ⟨some 1, 0, .isize⟩))))]
}
(match evalTerminatorV2 ptrBody bb frame roMem { allocations := [] } with
| .fault .unsupported => True
| _ => False) ∧
(match evalTerminatorV2 refBody bb frame roMem { allocations := [] } with
| .fault .unsupported => True
| _ => False) :=
⟨trivial, trivial⟩
/-- Guard `step_v2_read_indirect_proj_propagates_error`: reading an unsupported
field projection from an uninitialized `.indirect` local propagates
`.error .unsupported` from `projectMemoryLayoutV2` rather than falling back to
a whole-local load and turning it into `.error .undefined`. -/
theorem refute_step_v2_read_indirect_proj_propagates_error :
(match readPlaceV2
[.unit, .tuple [.int .i8 false, .bool]]
[.immediate none, .indirect ⟨1, 0⟩]
{ allocations := [{
allocId := 1
alignLog2 := 0
mutability := .mut
bytes := [.uninit, .uninit]
live := true
}], nextAllocId := 2 }
false
{ localId := 1, projection := [.field 5 .bool] } with
| .error .unsupported => True
| _ => False) :=
trivial
/-- Guard `step_v2_resolve_local_proj_validates_first`: assigning to an
out-of-bounds projected immediate local faults `.fault .undefined` during
destination resolution before evaluating an `.unsupported` rvalue, and
`updateValAtProjV2` updates `RangeTo`/`RangeFrom` `.field 0`. -/
theorem refute_step_v2_resolve_local_proj_validates_first :
let body : Body := {
argumentCount := 0
locals := [.unit, .array (.int .i8 false) 4]
basicBlocks := []
}
let frame : FrameState := {
defId := 0
blockIdx := 0
stmtIdx := 0
locals := [.immediate none,
.immediate (some (.array [
.scalar ⟨.i8, false, 0⟩, .scalar ⟨.i8, false, 0⟩,
.scalar ⟨.i8, false, 0⟩, .scalar ⟨.i8, false, 0⟩
]))]
}
let stmt : StatementKind :=
.assign
{ localId := 1, projection := [.constantIndex 5 4 false] }
.unsupported
(match evalStatementV2 body frame emptyMemory
{ allocations := [] } stmt with
| .fault .undefined => True
| _ => False) ∧
(match updateValAtProjV2
(.rangeTo (.int .isize false)) (.rangeTo 1)
[.field 0 (.int .isize false)] (.scalar ⟨.isize, false, 7⟩) with
| .ok (.rangeTo 7) => True
| _ => False) ∧
(match updateValAtProjV2
(.rangeFrom (.int .isize false)) (.rangeFrom 2)
[.field 0 (.int .isize false)] (.scalar ⟨.isize, false, 9⟩) with
| .ok (.rangeFrom 9) => True
| _ => False) :=
⟨trivial, trivial, trivial⟩
/-- Profile v2 program under `--panic abort` writing `7 : u8` through `&mut u8`
before failing a non-optional `.divByZero` assert. -/
noncomputable def progMutBeforeAbortV2 : Program := {
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 2
panicStrategy := .abort
hasLocalPanicHandler := false
bodies := [{
argumentCount := 1
locals := [.unit, .ref .mut u8Ty]
basicBlocks := [{
statements := [
.assign { localId := 1, projection := [.deref] }
(.use (.constant ⟨u8Ty, .scalar (BitVec.ofNat 128 7)⟩))
]
terminator :=
.assert (.constant ⟨.bool, .scalar (BitVec.ofNat 128 0)⟩) true
.divByZero 0 .unreachable
}]
isUnsafe := false
identity := "guard_mutation::mut_before_abort_v2"
}]
}
private def cmBeforeAbort : CallerMemory := {
allocations := [{
allocId := 2
alignLog2 := 0
mutability := .mut
bytes := [.init 0 none]
live := true
}]
}
private def cmAfterAbort : CallerMemory := {
allocations := [{
allocId := 2
alignLog2 := 0
mutability := .mut
bytes := [.init 7 none]
live := true
}]
}
/-- Guard `step_v2_assert_abort_extract_caller_mem`: pre-abort `&mut` mutations
must survive in `.aborted (extractCallerMemory callerMem mem1)`. -/
theorem refute_step_v2_assert_abort_extract_caller_mem :
(match initStateV2 progMutBeforeAbortV2
{ args := [.ptr ⟨some 2, 0, .isize⟩], callerMem := cmBeforeAbort } with
| .ok s₀ =>
match evalStepV2 progMutBeforeAbortV2 s₀ with
| .step s₁ =>
match evalStepV2 progMutBeforeAbortV2 s₁ with
| .done (.aborted cm') => cm' = cmAfterAbort
| _ => False
| _ => False
| .error _ => False) :=
rfl
/-- Guard `step_assert_optional_overflow_unsupported`: under `--panic abort`
and without `overflowChecks`, optional overflow checks (`.overflow .add` and
`.overflowNeg`) stay `.fault .unsupported` rather than aborting cleanly,
because codegen elides them when overflow checks are off. -/
theorem refute_step_assert_optional_overflow_unsupported :
evalAssertFailure (.overflow .add) .abort .unreachable
queryEmpty.callerMem false = .fault .unsupported ∧
evalAssertFailure .overflowNeg .abort .unreachable
queryEmpty.callerMem false = .fault .unsupported :=
⟨rfl, rfl⟩
/-- Guard `step_assert_checked_overflow_local_handler_unsupported`: with
`overflowChecks` but a crate-local `#[panic_handler]`, a failed checked overflow
assertion stays `.fault .unsupported` even under `--panic abort`. -/
theorem refute_step_assert_checked_overflow_local_handler_unsupported :
evalAssertFailure (.overflow .add) .abort .unreachable
queryEmpty.callerMem true true = .fault .unsupported ∧
evalAssertFailure .overflowNeg .abort .unreachable
queryEmpty.callerMem true true = .fault .unsupported :=
⟨rfl, rfl⟩
/-- Anti-overreach canary for the two guards above: with `overflowChecks`, no
crate-local `#[panic_handler]`, and `--panic abort`, a failed checked overflow
assertion aborts with the caller memory, while under `--panic unwind` it still
faults. -/
theorem positive_step_assert_checked_overflow_aborts :
evalAssertFailure (.overflow .add) .abort .unreachable
queryEmpty.callerMem false true =
.done (.aborted queryEmpty.callerMem) ∧
evalAssertFailure .overflowNeg .abort .continue_
queryEmpty.callerMem false true =
.done (.aborted queryEmpty.callerMem) ∧
evalAssertFailure (.overflow .shl) .unwind .unreachable
queryEmpty.callerMem false true = .fault .unsupported :=
⟨rfl, rfl, rfl⟩
/-- Guard `step_assert_local_panic_handler_unsupported`: when a crate defines a
crate-local `#[panic_handler]` (`hasLocalPanicHandler = true`), failing safe
assertions stay `.fault .unsupported` even under `--panic abort`. -/
theorem refute_step_assert_local_panic_handler_unsupported :
evalAssertFailure .divByZero .abort .unreachable
queryEmpty.callerMem true = .fault .unsupported ∧
evalAssertFailure .boundsCheck .abort .continue_
queryEmpty.callerMem true = .fault .unsupported :=
⟨rfl, rfl⟩
/-- Profile v2 program under `--panic abort` whose `.nullPtrDeref` assertion
fails despite no local panic handler. -/
noncomputable def progAssertNullDerefV2 : Program := {
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 2
panicStrategy := .abort
hasLocalPanicHandler := false
bodies := [{
argumentCount := 0
locals := [.unit]
basicBlocks := [{
statements := []
terminator :=
.assert (.constant ⟨.bool, .scalar (BitVec.ofNat 128 0)⟩) true
.nullPtrDeref 0 .unreachable
}]
isUnsafe := false
identity := "guard_mutation::assert_null_deref_v2"
}]
}
/-- Guard `step_assert_ptr_deref_undefined`: `.nullPtrDeref` and
`.misalignedPtrDeref` assertions always fault with `.undefined`, even under
`--panic abort` with no crate-local panic handler. -/
theorem refute_step_assert_ptr_deref_undefined :
evalAssertFailure .nullPtrDeref .abort .unreachable
queryEmpty.callerMem false = .fault .undefined ∧
evalAssertFailure .misalignedPtrDeref .abort .unreachable
queryEmpty.callerMem false = .fault .undefined ∧
ReachesResultV2 progAssertNullDerefV2 queryEmpty (.fault .undefined) ∧
¬ WellFormedV2 progAssertNullDerefV2 queryEmpty := by
have hReach :
ReachesResultV2 progAssertNullDerefV2 queryEmpty (.fault .undefined) :=
⟨_, ReachesV2.refl _, ⟨0, rfl, rfl⟩⟩
exact ⟨rfl, rfl, hReach, fun hWf => hWf.2 .undefined hReach⟩
/-- Two-block Profile v1 program executing `TerminatorKind.assert`
on `_1 : bool` with `expected = true`, `msg = .divByZero`, and target
block `1` (which returns `_0 : ()`). -/
noncomputable def progAssertFailedV1 : Program := {
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 1
bodies := [{
argumentCount := 1
locals := [.unit, .bool]
basicBlocks := [
{ statements := []
terminator :=
.assert (.copy ⟨1, []⟩) true .divByZero 1 .continue_ },
{ statements := []
terminator := .return_ }
]
}]
}
/-- Guard `step_assert_v1_failure_faults`: a failing Profile v1
`TerminatorKind.assert` (`b != expected`) faults rather than jumping to
`target`. -/
theorem refute_step_assert_v1_failure_faults :
ReachesResult progAssertFailedV1 { args := [.bool false] }
(.fault .unsupported) ∧
¬ WellFormed progAssertFailedV1 { args := [.bool false] } :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Guard `step_assert_v1_non_bool_unsupported`: Profile v1 `evalTerminator`
refuses non-`.bool` `.assert` condition operands as `.fault .unsupported`. -/
theorem refute_step_assert_v1_non_bool_unsupported :
let body : Body := {
argumentCount := 1
locals := [.unit, u8Ty]
basicBlocks := []
}
let bb : BasicBlock := {
statements := []
terminator := .assert (.copy ⟨1, []⟩) true .divByZero 1 .continue_
}
let frame : FrameState := {
defId := 0
blockIdx := 0
stmtIdx := 0
locals := [.immediate (some .unit),
.immediate (some (scalarNatVal .i8 false 2))]
}
(match evalTerminator body bb frame emptyMemory { allocations := [] } with
| .fault .unsupported => True
| _ => False) :=
trivial
/-- Guard `step_v2_assert_non_bool_unsupported`: Profile v2 `evalTerminatorV2`
refuses non-`.bool` `.assert` condition operands as `.fault .unsupported`. -/
theorem refute_step_v2_assert_non_bool_unsupported :
let body : Body := {
argumentCount := 1
locals := [.unit, u8Ty]
basicBlocks := []
}
let bb : BasicBlock := {
statements := []
terminator := .assert (.copy ⟨1, []⟩) true .divByZero 1 .continue_
}
let frame : FrameState := {
defId := 0
blockIdx := 0
stmtIdx := 0
locals := [.immediate (some .unit),
.immediate (some (scalarNatVal .i8 false 2))]
}
(match evalTerminatorV2 body bb frame emptyMemory { allocations := [] } with
| .fault .unsupported => True
| _ => False) :=
trivial
/-- Guard `step_v2_assign_use_overlap_ub`: `StatementKind.assign` with
`Rvalue.use` / `Rvalue.useRetag` faults `.fault .undefined` on overlapping
non-zero-sized `BackendRepr::Memory` or padded places (`*p = *p` on `[u8; 4]`,
local `a = a` on `[u8; 4]`, and `*p = *p` on padded `(u32, bool)`), while
permitting zero-sized (`[u8; 0]`, `[u32; 0]`), `Scalar` (`u32`,
`([u32; 0], u32)`), padding-free `ScalarPair` (`(u32, u32)`, `(u8, bool)`), and
disjoint element (`a[0] = a[1]`) copies. -/
theorem refute_step_v2_assign_use_overlap_ub :
let arr4Ty : MirTy := .array u8Ty 4
let zstArrTy : MirTy := .array (.int .i32 false) 0
let mem4 : MemoryState := {
allocations := [{
allocId := 2
alignLog2 := 2
mutability := .mut
bytes := [.init 1 none, .init 2 none, .init 3 none, .init 4 none]
live := true
}]
nextAllocId := 3
}
let bodyPtrArr : Body := {
argumentCount := 0
locals := [.unit, .rawPtr .mut arr4Ty]
basicBlocks := []
}
let framePtrArr : FrameState := {
defId := 0, blockIdx := 0, stmtIdx := 0
locals := [.immediate none, .immediate (some (.ptr ⟨some 2, 0, .isize⟩))]
}
let bodyLocArr : Body := {
argumentCount := 0
locals := [.unit, arr4Ty]
basicBlocks := []
}
let frameLocArr : FrameState := {
defId := 0, blockIdx := 0, stmtIdx := 0
locals := [.immediate none, .immediate (some (.array [
.scalar ⟨.i8, false, 1⟩, .scalar ⟨.i8, false, 2⟩,
.scalar ⟨.i8, false, 3⟩, .scalar ⟨.i8, false, 4⟩
]))]
}
let bodyPaddedPair : Body := {
argumentCount := 0
locals := [.unit, .tuple [.int .i32 false, .bool]]
basicBlocks := []
}
let framePaddedPair : FrameState := {
defId := 0, blockIdx := 0, stmtIdx := 0
locals := [.immediate none,
.immediate (some (.tuple [.scalar ⟨.i32, false, 9⟩, .bool true]))]
}
let bodyNoPadPair : Body := {
argumentCount := 0
locals := [.unit, .tuple [u8Ty, .bool], .tuple [.int .i32 false, .int .i32 false],
zstArrTy, .tuple [zstArrTy, .int .i32 false]]
basicBlocks := []
}
let frameNoPadPair : FrameState := {
defId := 0, blockIdx := 0, stmtIdx := 0
locals := [
.immediate none,
.immediate (some (.tuple [.scalar ⟨.i8, false, 9⟩, .bool true])),
.immediate (some (.tuple [.scalar ⟨.i32, false, 1⟩, .scalar ⟨.i32, false, 2⟩])),
.immediate (some (.array [])),
.immediate (some (.tuple [.array [], .scalar ⟨.i32, false, 7⟩]))
]
}
let bodyArrOfArr : Body := {
argumentCount := 0
locals := [.unit, .array arr4Ty 2]
basicBlocks := []
}
let vArr4 : Val := .array [
.scalar ⟨.i8, false, 1⟩, .scalar ⟨.i8, false, 2⟩,
.scalar ⟨.i8, false, 3⟩, .scalar ⟨.i8, false, 4⟩
]
let frameArrOfArr : FrameState := {
defId := 0, blockIdx := 0, stmtIdx := 0
locals := [.immediate none, .immediate (some (.array [vArr4, vArr4]))]
}
-- Negative (must fault `.undefined`):
(match evalStatementV2 bodyPtrArr framePtrArr mem4 { allocations := [] }
(.assign { localId := 1, projection := [.deref] }
(.use (.copy { localId := 1, projection := [.deref] }))) with
| .fault .undefined => True
| _ => False) ∧
(match evalStatementV2 bodyLocArr frameLocArr emptyMemory { allocations := [] }
(.assign { localId := 1, projection := [] }
(.use (.copy { localId := 1, projection := [] }))) with
| .fault .undefined => True
| _ => False) ∧
(match evalStatementV2 bodyPaddedPair framePaddedPair emptyMemory { allocations := [] }
(.assign { localId := 1, projection := [] }
(.use (.copy { localId := 1, projection := [] }))) with
| .fault .undefined => True
| _ => False) ∧
(match evalStatementV2 bodyArrOfArr frameArrOfArr emptyMemory { allocations := [] }
(.assign { localId := 1, projection := [.constantIndex 0 2 false] }
(.use (.copy { localId := 1, projection := [.constantIndex 0 2 false] }))) with
| .fault .undefined => True
| _ => False) ∧
-- Positive anti-overreach (must step cleanly):
(match evalStatementV2 bodyNoPadPair frameNoPadPair emptyMemory { allocations := [] }
(.assign { localId := 1, projection := [] }
(.use (.copy { localId := 1, projection := [] }))) with
| .step _ => True
| _ => False) ∧
(match evalStatementV2 bodyNoPadPair frameNoPadPair emptyMemory { allocations := [] }
(.assign { localId := 2, projection := [] }
(.use (.copy { localId := 2, projection := [] }))) with
| .step _ => True
| _ => False) ∧
(match evalStatementV2 bodyNoPadPair frameNoPadPair emptyMemory { allocations := [] }
(.assign { localId := 3, projection := [] }
(.use (.copy { localId := 3, projection := [] }))) with
| .step _ => True
| _ => False) ∧
(match evalStatementV2 bodyNoPadPair frameNoPadPair emptyMemory { allocations := [] }
(.assign { localId := 4, projection := [] }
(.use (.copy { localId := 4, projection := [] }))) with
| .step _ => True
| _ => False) ∧
(match evalStatementV2 bodyArrOfArr frameArrOfArr emptyMemory { allocations := [] }
(.assign { localId := 1, projection := [.constantIndex 0 2 false] }
(.use (.copy { localId := 1, projection := [.constantIndex 1 2 false] }))) with
| .step _ => True
| _ => False) :=
⟨trivial, trivial, trivial, trivial, trivial, trivial, trivial, trivial, trivial⟩
/-- Guard `step_v2_assign_aggregate_clobber_unsupported`: in-place `Aggregate`
where an earlier field write (`_1.0`) aliases a later operand (`_1.0` in
`_1 = (_1.1, _1.0)`) fails closed with `.fault .unsupported`, whereas
non-clobbering scalar `_1 = (_1.0, _1.1)` steps cleanly. -/
theorem refute_step_v2_assign_aggregate_clobber_unsupported :
let u32Ty : MirTy := .int .i32 false
let body : Body := {
argumentCount := 0
locals := [.unit, .tuple [u32Ty, u32Ty]]
basicBlocks := []
}
let frame : FrameState := {
defId := 0, blockIdx := 0, stmtIdx := 0
locals := [.immediate none,
.immediate (some (.tuple [.scalar ⟨.i32, false, 1⟩, .scalar ⟨.i32, false, 2⟩]))]
}
(match evalStatementV2 body frame emptyMemory { allocations := [] }
(.assign { localId := 1, projection := [] }
(.aggregateTuple [
.copy { localId := 1, projection := [.field 1 u32Ty] },
.copy { localId := 1, projection := [.field 0 u32Ty] }
])) with
| .fault .unsupported => True
| _ => False) ∧
(match evalStatementV2 body frame emptyMemory { allocations := [] }
(.assign { localId := 1, projection := [] }
(.aggregateTuple [
.copy { localId := 1, projection := [.field 0 u32Ty] },
.copy { localId := 1, projection := [.field 1 u32Ty] }
])) with
| .step _ => True
| _ => False) :=
⟨trivial, trivial⟩
/-- Shared locals for the `Range` aggregate hazard refutations: `_1` is the
immediate `Range<usize>` `10..20` and `_2` an immediate `usize`. -/
noncomputable def rangeHazLocals : List MirTy × List LocalSlot :=
([.unit, .range (.int .isize false), .int .isize false],
[.immediate none, .immediate (some (.range 10 20)),
.immediate (some (.scalar ⟨.isize, false, 5⟩))])
/-- Guard `step_v2_assign_aggregate_range_clobber_unsupported`: in-place
`_1 = Range { start: _1.1, end: _1.0 }` reads `_1.0` after the field-0 write
clobbered it (`write_aggregate` copies fields in order), so it fails closed
instead of evaluating both operands against the old `_1`. -/
theorem refute_step_v2_assign_aggregate_range_clobber_unsupported :
checkAssignCopyHazardV2 rangeHazLocals.1 rangeHazLocals.2 emptyMemory
(.local 1) (.range (.int .isize false))
(.aggregateRange (.int .isize false)
(.copy { localId := 1, projection :=
[.field 1 (.int .isize false)] })
(.copy { localId := 1, projection :=
[.field 0 (.int .isize false)] })) =
.error .unsupported :=
rfl
/-- Guard `step_v2_assign_range_field_span`: `Range` field projections on an
immediate local resolve to precise spans, so
`_1 = Range { start: _2, end: _1.1 }` (which reads only the field not yet
written) passes the hazard check. -/
theorem refute_step_v2_assign_range_field_span :
checkAssignCopyHazardV2 rangeHazLocals.1 rangeHazLocals.2 emptyMemory
(.local 1) (.range (.int .isize false))
(.aggregateRange (.int .isize false)
(.copy { localId := 2, projection := [] })
(.copy { localId := 1, projection :=
[.field 1 (.int .isize false)] })) =
.ok () :=
rfl
/-- Shared locals for the `Option` payload hazard refutations:
`_1 : (Option<u32>, u32)`, `_2 : Option<u32>`, and
`_3 : (u32, u32, Option<u32>)`, all immediate. -/
noncomputable def optHazLocals : List MirTy × List LocalSlot :=
let u32Ty : MirTy := .int .i32 false
([.unit, .tuple [.option u32Ty, u32Ty], .option u32Ty,
.tuple [u32Ty, u32Ty, .option u32Ty]],
[.immediate none,
.immediate (some (.tuple [.optionVal (some (.scalar ⟨.i32, false, 7⟩)),
.scalar ⟨.i32, false, 1⟩])),
.immediate (some (.optionVal none)),
.immediate (some (.tuple [.scalar ⟨.i32, false, 1⟩,
.scalar ⟨.i32, false, 2⟩,
.optionVal (some (.scalar ⟨.i32, false, 3⟩))]))])
/-- Guard `step_v2_assign_option_payload_span`: an `Option` payload read
`(_3.2 as Some).0` resolves to a sub-span of `_3.2`, so
`_3 = (_1.1, (_3.2 as Some).0, _2)` passes, while
`_1 = (_2, (_1.0 as Some).0)` reads the payload of the already-overwritten
`_1.0` and fails closed. -/
theorem refute_step_v2_assign_option_payload_span :
let u32Ty : MirTy := .int .i32 false
checkAssignCopyHazardV2 optHazLocals.1 optHazLocals.2 emptyMemory
(.local 3) (.tuple [u32Ty, u32Ty, .option u32Ty])
(.aggregateTuple [
.copy { localId := 1, projection := [.field 1 u32Ty] },
.copy { localId := 3, projection :=
[.field 2 (.option u32Ty), .downcast 1,
.field 0 u32Ty] },
.copy { localId := 2, projection := [] }]) = .ok () ∧
checkAssignCopyHazardV2 optHazLocals.1 optHazLocals.2 emptyMemory
(.local 1) (.tuple [.option u32Ty, u32Ty])
(.aggregateTuple [
.copy { localId := 2, projection := [] },
.copy { localId := 1, projection :=
[.field 0 (.option u32Ty), .downcast 1,
.field 0 u32Ty] }]) = .error .unsupported :=
⟨rfl, rfl⟩
/-- Guard `step_v2_assign_aggregate_unresolved_operand_unsupported`: a later
`Aggregate` operand whose source span cannot be resolved (here the bare
variant place `_1.0 as Some`) fails closed rather than being treated like a
constant. -/
theorem refute_step_v2_assign_aggregate_unresolved_operand_unsupported :
let u32Ty : MirTy := .int .i32 false
checkAssignCopyHazardV2 optHazLocals.1 optHazLocals.2 emptyMemory
(.local 1) (.tuple [.option u32Ty, u32Ty])
(.aggregateTuple [
.copy { localId := 2, projection := [] },
.copy { localId := 1, projection :=
[.field 0 (.option u32Ty), .downcast 1] }]) =
.error .unsupported :=
rfl
/-- Guard `step_v2_assign_aggregate_deref_ptr_clobber_unsupported`: when an
earlier `Aggregate` field write overwrites the memory holding a pointer local
`_2 : *const u32`, a later `copy (*_2)` operand fails closed with
`.fault .unsupported` (for both array destinations and tuple destinations taking
the conservative `baseSpan` path), whereas reading `*_2` at field 0 before `_2`
is overwritten steps cleanly. -/
theorem refute_step_v2_assign_aggregate_deref_ptr_clobber_unsupported :
let u32Ty : MirTy := .int .i32 false
let ptrU32Ty : MirTy := .rawPtr .shared u32Ty
let arr2Ty : MirTy := .array u32Ty 2
let tup3Ty : MirTy := .tuple [u32Ty, u32Ty, u32Ty]
let mem : MemoryState := {
allocations := [
{ allocId := 1, bytes := [
.init 1 none, .init 0 none, .init 0 none, .init 0 none
], alignLog2 := 2, mutability := .mut, live := true },
{ allocId := 2, bytes := [
.init 0 (some 1), .init 0 (some 1), .init 0 (some 1), .init 0 (some 1),
.init 0 (some 1), .init 0 (some 1), .init 0 (some 1), .init 0 (some 1),
.init 0 none, .init 0 none, .init 0 none, .init 0 none
], alignLog2 := 3, mutability := .mut, live := true }
]
nextAllocId := 3
}
let body : Body := {
argumentCount := 0
locals := [
.unit, u32Ty, ptrU32Ty, .rawPtr .mut arr2Ty, .rawPtr .mut tup3Ty
]
basicBlocks := []
}
let frame : FrameState := {
defId := 0, blockIdx := 0, stmtIdx := 0
locals := [
.immediate none,
.immediate (some (.scalar ⟨.i32, false, 7⟩)),
.indirect { allocId := 2, offset := 0 },
.immediate (some (.ptr { allocId := some 2, offsetBytes := 0, width := .isize })),
.immediate (some (.ptr { allocId := some 2, offsetBytes := 0, width := .isize }))
]
}
(match evalStatementV2 body frame mem { allocations := [] }
(.assign { localId := 3, projection := [.deref] }
(.aggregateArray u32Ty [
.copy { localId := 1, projection := [] },
.copy { localId := 2, projection := [.deref] }
])) with
| .fault .unsupported => True
| _ => False) ∧
(match checkAggregateCopyHazardLoopV2 body.locals frame.locals mem
(.memRange 2 0 12) tup3Ty false 0 [] [u32Ty, u32Ty, u32Ty] [
.copy { localId := 1, projection := [] },
.copy { localId := 2, projection := [.deref] },
.copy { localId := 1, projection := [] }
] with
| .error .unsupported => True
| _ => False) ∧
(match checkAggregateCopyHazardLoopV2 body.locals frame.locals mem
(.memRange 2 0 12) tup3Ty false 0 [] [u32Ty, u32Ty, u32Ty] [
.copy { localId := 2, projection := [.deref] },
.copy { localId := 1, projection := [] },
.copy { localId := 1, projection := [] }
] with
| .ok () => True
| _ => False) ∧
(match evalStatementV2 body frame mem { allocations := [] }
(.assign { localId := 3, projection := [.deref] }
(.aggregateArray u32Ty [
.copy { localId := 2, projection := [.deref] },
.copy { localId := 1, projection := [] }
])) with
| .step _ => True
| _ => False) :=
⟨trivial, trivial, trivial, trivial⟩
/-- Guard `step_v2_assign_aggregate_field_overlap_ub`: in-place `Aggregate`
copying a `BackendRepr::Memory` field onto itself (`_1 = (_1.0, _1.1)` on
`([u8; 4], [u8; 4])`) faults `.fault .undefined`. -/
theorem refute_step_v2_assign_aggregate_field_overlap_ub :
let arr4Ty : MirTy := .array u8Ty 4
let vArr4 : Val := .array [
.scalar ⟨.i8, false, 1⟩, .scalar ⟨.i8, false, 2⟩,
.scalar ⟨.i8, false, 3⟩, .scalar ⟨.i8, false, 4⟩
]
let body : Body := {
argumentCount := 0
locals := [.unit, .tuple [arr4Ty, arr4Ty]]
basicBlocks := []
}
let frame : FrameState := {
defId := 0, blockIdx := 0, stmtIdx := 0
locals := [.immediate none, .immediate (some (.tuple [vArr4, vArr4]))]
}
(match evalStatementV2 body frame emptyMemory { allocations := [] }
(.assign { localId := 1, projection := [] }
(.aggregateTuple [
.copy { localId := 1, projection := [.field 0 arr4Ty] },
.copy { localId := 1, projection := [.field 1 arr4Ty] }
])) with
| .fault .undefined => True
| _ => False) :=
trivial
/-- Guard `step_v2_assign_repeat_overlap_ub`: in-place `Rvalue.repeat_`
copying a `BackendRepr::Memory` element `a[0]` into `a = [a[0]; 2]` faults
`.fault .undefined`, while `a = [a[1]; 2]` (disjoint from `a[0]`) steps
cleanly. -/
theorem refute_step_v2_assign_repeat_overlap_ub :
let arr4Ty : MirTy := .array u8Ty 4
let vArr4 : Val := .array [
.scalar ⟨.i8, false, 1⟩, .scalar ⟨.i8, false, 2⟩,
.scalar ⟨.i8, false, 3⟩, .scalar ⟨.i8, false, 4⟩
]
let body : Body := {
argumentCount := 0
locals := [.unit, .array arr4Ty 2]
basicBlocks := []
}
let frame : FrameState := {
defId := 0, blockIdx := 0, stmtIdx := 0
locals := [.immediate none, .immediate (some (.array [vArr4, vArr4]))]
}
(match evalStatementV2 body frame emptyMemory { allocations := [] }
(.assign { localId := 1, projection := [] }
(.repeat_ (.copy { localId := 1, projection := [.constantIndex 0 2 false] })
arr4Ty 2)) with
| .fault .undefined => True
| _ => False) ∧
(match evalStatementV2 body frame emptyMemory { allocations := [] }
(.assign { localId := 1, projection := [] }
(.repeat_ (.copy { localId := 1, projection := [.constantIndex 1 2 false] })
arr4Ty 2)) with
| .step _ => True
| _ => False) :=
⟨trivial, trivial⟩
/-- Guard `state_v2_init_uses_entry_memory_for_args`: end-to-end Profile v2
`Program` execution where the caller passes a dangling raw pointer
`p : *const u8 = ⟨some 2, 0, .isize⟩` with empty `callerMem`, and the callee
promotes a stack local `_2 : u8 = 42` via `&raw const _2` before reading `*p`.
`initStateV2` must advance `nextAllocId` past `2` via `entryMemoryForArgsV2` so
`_2` receives `allocId = 3` and reading dangling `*p` faults `.fault .undefined`
(whereas falling back to `entryMemoryWithCaller` assigns `allocId = 2` to `_2`
and unsoundly returns `42`). -/
theorem refute_state_v2_init_uses_entry_memory_for_args :
let rawU8Const : MirTy := .rawPtr .shared u8Ty
let prog : Program := {
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 2
bodies := [{
argumentCount := 1
locals := [u8Ty, rawU8Const, u8Ty, rawU8Const]
basicBlocks := [{
statements := [
.storageLive 2,
.assign { localId := 2, projection := [] }
(.use (.constant ⟨u8Ty, .scalar (BitVec.ofNat 128 42)⟩)),
.storageLive 3,
.assign { localId := 3, projection := [] }
(.addressOf .shared { localId := 2, projection := [] }),
.assign { localId := 0, projection := [] }
(.use (.copy { localId := 1, projection := [.deref] }))
]
terminator := .return_
}]
isUnsafe := true
identity := "guard_mutation::dangling_raw_ptr_vs_stack_alloc"
}]
}
(match initStateV2 prog
{ args := [.ptr ⟨some 2, 0, .isize⟩], callerMem := { allocations := [] } } with
| .ok s0 =>
match evalStepV2 prog s0 with
| .step s1 =>
match evalStepV2 prog s1 with
| .step s2 =>
match evalStepV2 prog s2 with
| .step s3 =>
match evalStepV2 prog s3 with
| .step s4 => evalStepV2 prog s4 = .fault .undefined
| _ => False
| _ => False
| _ => False
| _ => False
| .error _ => False) :=
rfl
/-- Guard `step_v2_fake_address_of_ref_validity`: `evalFakeAddressOfRvalueV2`
must validate `refValidInMem` when dereferencing a reference base local,
faulting `.undefined` on a null `&mut [u8]`. -/
theorem refute_step_v2_fake_address_of_ref_validity :
(match evalFakeAddressOfRvalueV2
[
.unit,
.ref .mut (.slice (.int .i8 false)),
.rawPtr .shared (.slice (.int .i8 false))
]
[
.immediate (some .unit),
.immediate (some (.slicePtr ⟨none, 0, .isize⟩ 0)),
.immediate none
]
{ allocations := [], nextAllocId := 1 }
(.rawPtr .shared (.slice (.int .i8 false)))
{ localId := 1, projection := [.deref] } with
| .error .undefined => True
| _ => False) :=
trivial
/-- Guard `core_contracts_slice_subslice_in_mut`: `Index::index(0..1)` on a
`&mut [u8]` input over a `.shared` allocation faults with `.undefined` even
though `reqMut = .shared`, because `execSliceSubsliceOutcome` validates the
input at `inMut`. -/
theorem refute_core_contracts_slice_subslice_in_mut :
(match execCoreContractOp sharedInit2Mem
(.sliceIndexRange .shared (.int .i8 false))
[(.ref .mut (.slice (.int .i8 false)), .slicePtr ⟨some 1, 0, .isize⟩ 2),
(.range (.int .isize false), .range 0 1)]
(.ref .shared (.slice (.int .i8 false))) with
| .error .undefined => True
| _ => False) :=
trivial
/-- Guard `step_v2_index_dead_local`: `ProjectionElem.index` through a dead
`usize` index local faults with `.undefined`. -/
theorem refute_step_v2_index_dead_local :
(match evalRvalueV2
[.int .i8 false, .array (.int .i8 false) 2, .int .isize false]
[.immediate none,
.immediate (some (.array [.scalar ⟨.i8, false, BitVec.ofNat 128 1⟩,
.scalar ⟨.i8, false, BitVec.ofNat 128 2⟩])),
.dead]
emptyMemory (.int .i8 false) (.use (.copy ⟨1, [.index 2]⟩)) with
| .error .undefined => True
| _ => False) :=
trivial
/-- Guard `core_contracts_slice_split_at_in_mut`: `slice::split_at(1)` on a
`&mut [u8]` input over a `.shared` allocation faults with `.undefined` even
though `reqMut = .shared`, because `execSliceSplitAtOutcome` validates the
input at `inMut`. -/
theorem refute_core_contracts_slice_split_at_in_mut :
(match execCoreContractOp sharedInit2Mem
(.sliceSplitAt .shared (.int .i8 false))
[(.ref .mut (.slice (.int .i8 false)), .slicePtr ⟨some 1, 0, .isize⟩ 2),
(.int .isize false, .scalar ⟨.isize, false, 1⟩)]
(.tuple [.ref .shared (.slice (.int .i8 false)),
.ref .shared (.slice (.int .i8 false))]) with
| .error .undefined => True
| _ => False) :=
trivial
/-- Guard `step_v2_index_uninit_local`: `ProjectionElem.index` through an
uninitialized `usize` index local faults with `.undefined`. -/
theorem refute_step_v2_index_uninit_local :
(match evalRvalueV2
[.int .i8 false, .array (.int .i8 false) 2, .int .isize false]
[.immediate none,
.immediate (some (.array [.scalar ⟨.i8, false, BitVec.ofNat 128 1⟩,
.scalar ⟨.i8, false, BitVec.ofNat 128 2⟩])),
.immediate none]
emptyMemory (.int .i8 false) (.use (.copy ⟨1, [.index 2]⟩)) with
| .error .undefined => True
| _ => False) :=
trivial
/-- Anti-overreach canary: the same `Index::index` and `split_at` calls on a
`&[u8]` input over the `.shared` allocation succeed. -/
theorem positive_core_contracts_slice_shared_input :
(match execCoreContractOp sharedInit2Mem
(.sliceIndexRange .shared (.int .i8 false))
[(.ref .shared (.slice (.int .i8 false)),
.slicePtr ⟨some 1, 0, .isize⟩ 2),
(.range (.int .isize false), .range 0 1)]
(.ref .shared (.slice (.int .i8 false))) with
| .ok _ => True
| .error _ => False) ∧
(match execCoreContractOp sharedInit2Mem
(.sliceSplitAt .shared (.int .i8 false))
[(.ref .shared (.slice (.int .i8 false)),
.slicePtr ⟨some 1, 0, .isize⟩ 2),
(.int .isize false, .scalar ⟨.isize, false, 1⟩)]
(.tuple [.ref .shared (.slice (.int .i8 false)),
.ref .shared (.slice (.int .i8 false))]) with
| .ok _ => True
| .error _ => False) :=
⟨trivial, trivial⟩
/-- Guard `core_contracts_i128_host_overflow`: 128-bit checked, saturating,
and overflowing arithmetic detect mathematical overflow (`intHostOverflow`)
before `BitVec 128` carrier truncation across unsigned and signed edges. -/
theorem refute_core_contracts_i128_host_overflow :
let u128Ty : MirTy := .int .i128 false
let i128Ty : MirTy := .int .i128 true
let u128Max : ScalarVal :=
⟨.i128, false, BitVec.ofNat 128 340282366920938463463374607431768211455⟩
let u128Zero : ScalarVal := ⟨.i128, false, 0⟩
let u128One : ScalarVal := ⟨.i128, false, 1⟩
let u128Two : ScalarVal := ⟨.i128, false, 2⟩
let i128Max : ScalarVal :=
⟨.i128, true, BitVec.ofNat 128 170141183460469231731687303715884105727⟩
let i128Min : ScalarVal :=
⟨.i128, true, BitVec.ofNat 128 170141183460469231731687303715884105728⟩
let i128One : ScalarVal := ⟨.i128, true, 1⟩
let i128NegOne : ScalarVal :=
⟨.i128, true, BitVec.ofNat 128 340282366920938463463374607431768211455⟩
let u128Two64 : ScalarVal :=
⟨.i128, false, BitVec.ofNat 128 18446744073709551616⟩
execCoreContractOp MemoryState.empty (.numCheckedAdd .i128 false)
[(u128Ty, .scalar u128Max), (u128Ty, .scalar u128One)]
(.option u128Ty) =
.ok (.optionVal none, MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.numCheckedSub .i128 false)
[(u128Ty, .scalar u128Zero), (u128Ty, .scalar u128One)]
(.option u128Ty) =
.ok (.optionVal none, MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.numCheckedAdd .i128 true)
[(i128Ty, .scalar i128Max), (i128Ty, .scalar i128One)]
(.option i128Ty) =
.ok (.optionVal none, MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.numCheckedMul .i128 false)
[(u128Ty, .scalar u128Max), (u128Ty, .scalar u128Two)]
(.option u128Ty) =
.ok (.optionVal none, MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.numSaturatingAdd .i128 false)
[(u128Ty, .scalar u128Max), (u128Ty, .scalar u128One)] u128Ty =
.ok (.scalar u128Max, MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.numSaturatingAdd .i128 true)
[(i128Ty, .scalar i128Max), (i128Ty, .scalar i128One)] i128Ty =
.ok (.scalar i128Max, MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.numSaturatingAdd .i128 true)
[(i128Ty, .scalar i128Min), (i128Ty, .scalar i128NegOne)] i128Ty =
.ok (.scalar i128Min, MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.numOverflowingAdd .i128 false)
[(u128Ty, .scalar u128Max), (u128Ty, .scalar u128One)]
(.tuple [u128Ty, .bool]) =
.ok (.tuple [.scalar u128Zero, .bool true], MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.numOverflowingSub .i128 false)
[(u128Ty, .scalar u128Zero), (u128Ty, .scalar u128One)]
(.tuple [u128Ty, .bool]) =
.ok (.tuple [.scalar u128Max, .bool true], MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.numOverflowingAdd .i128 true)
[(i128Ty, .scalar i128Max), (i128Ty, .scalar i128One)]
(.tuple [i128Ty, .bool]) =
.ok (.tuple [.scalar i128Min, .bool true], MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.numOverflowingMul .i128 false)
[(u128Ty, .scalar u128Two64), (u128Ty, .scalar u128Two64)]
(.tuple [u128Ty, .bool]) =
.ok (.tuple [.scalar u128Zero, .bool true], MemoryState.empty) :=
⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl⟩
/-- Anti-overreach canary: in-bounds 128-bit checked, saturating, and
overflowing arithmetic succeed without false overflow. -/
theorem positive_core_contracts_i128_in_bounds :
let u128Ty : MirTy := .int .i128 false
let u128MaxMinus1 : ScalarVal :=
⟨.i128, false, BitVec.ofNat 128 340282366920938463463374607431768211454⟩
let u128Max : ScalarVal :=
⟨.i128, false, BitVec.ofNat 128 340282366920938463463374607431768211455⟩
let u128One : ScalarVal := ⟨.i128, false, 1⟩
let u128Two : ScalarVal := ⟨.i128, false, 2⟩
let u128Three : ScalarVal := ⟨.i128, false, 3⟩
execCoreContractOp MemoryState.empty (.numCheckedAdd .i128 false)
[(u128Ty, .scalar u128One), (u128Ty, .scalar u128Two)]
(.option u128Ty) =
.ok (.optionVal (some (.scalar u128Three)), MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.numSaturatingAdd .i128 false)
[(u128Ty, .scalar u128MaxMinus1), (u128Ty, .scalar u128One)] u128Ty =
.ok (.scalar u128Max, MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.numOverflowingAdd .i128 false)
[(u128Ty, .scalar u128One), (u128Ty, .scalar u128Two)]
(.tuple [u128Ty, .bool]) =
.ok (.tuple [.scalar u128Three, .bool false], MemoryState.empty) :=
⟨rfl, rfl, rfl⟩
/-- Guard `bytes_v2_slice_uninhabited_elem`: `refValidInMem` rejects
positive-length `&[!]` and `&mut [!]` slices (both provenance-free dangling
pointers and provenance-backed allocations) with `.error .undefined`. -/
theorem refute_bytes_v2_slice_uninhabited_elem :
let mutMem : MemoryState := {
allocations := [{
allocId := 2
alignLog2 := 0
mutability := .mut
bytes := []
live := true
}]
nextAllocId := 3
}
refValidInMem MemoryState.empty .shared (.slice .never)
(.slicePtr ⟨none, 1, .isize⟩ 1) = .error .undefined ∧
refValidInMem MemoryState.empty .mut (.slice .never)
(.slicePtr ⟨none, 1, .isize⟩ 2) = .error .undefined ∧
refValidInMem mutMem .shared (.slice .never)
(.slicePtr ⟨some 2, 0, .isize⟩ 1) = .error .undefined ∧
refValidInMem mutMem .mut (.slice .never)
(.slicePtr ⟨some 2, 0, .isize⟩ 1) = .error .undefined :=
⟨rfl, rfl, rfl, rfl⟩
/-- Anti-overreach canary: empty `&[] : &[!]` (`len = 0`) and positive-length
inhabited ZST `&[()]` slices remain valid under `refValidInMem`. -/
theorem positive_bytes_v2_slice_empty_never_and_zst_unit :
refValidInMem MemoryState.empty .shared (.slice .never)
(.slicePtr ⟨none, 1, .isize⟩ 0) = .ok () ∧
refValidInMem MemoryState.empty .shared (.slice .unit)
(.slicePtr ⟨none, 1, .isize⟩ 3) = .ok () :=
⟨rfl, rfl⟩
/-- Guard `core_contracts_option_unwrap_refs_valid`: `Option::unwrap` on
`Some(&u8)` pointing into a dead allocation faults `.undefined` via
`refsValidInMem`, while a live `Some(&u8)` succeeds. -/
theorem refute_core_contracts_option_unwrap_refs_valid :
let refU8Ty : MirTy := .ref .shared (.int .i8 false)
let deadMem : MemoryState := {
allocations := [{
allocId := 2
alignLog2 := 0
mutability := .shared
bytes := [.init 7 none]
live := false
}]
nextAllocId := 3
}
let liveMem : MemoryState := {
allocations := [{
allocId := 2
alignLog2 := 0
mutability := .shared
bytes := [.init 7 none]
live := true
}]
nextAllocId := 3
}
execCoreContractOp deadMem (.optionUnwrap refU8Ty)
[(.option refU8Ty, .optionVal (some (.ptr ⟨some 2, 0, .isize⟩)))]
refU8Ty = .error .undefined ∧
execCoreContractOp liveMem (.optionUnwrap refU8Ty)
[(.option refU8Ty, .optionVal (some (.ptr ⟨some 2, 0, .isize⟩)))]
refU8Ty = .ok (.ptr ⟨some 2, 0, .isize⟩, liveMem) :=
⟨rfl, rfl⟩
/-- Guard `step_v2_option_discriminant_dst_ty`: projected `Option` discriminant
returns `0isize`/`1isize` for `isize` destination and rejects mismatched
`dstTy` with `.unsupported`. -/
theorem refute_step_v2_option_discriminant_dst_ty :
let optU8Ty : MirTy := .option (.int .i8 false)
let tupTy : MirTy := .tuple [optU8Ty, .int .i8 false]
let locals : List LocalSlot := [
.immediate (some (.tuple [.optionVal (some (.scalar ⟨.i8, false, 9⟩)),
.scalar ⟨.i8, false, 1⟩]))
]
let place : Place := { localId := 0, projection := [.field 0 optU8Ty] }
evalRvalueV2 [tupTy] locals MemoryState.empty (.int .i8 false)
(.discriminant place) = .error .unsupported ∧
evalRvalueV2 [tupTy] locals MemoryState.empty (.int .isize true)
(.discriminant place) =
.ok (.scalar ⟨.isize, true, BitVec.ofNat 128 1⟩, locals,
MemoryState.empty) :=
⟨rfl, rfl⟩
/-- Guard `step_v2_core_panic_local_handler_unsupported`: diverging
`core::panicking::*` calls stay `.fault .unsupported` when
`hasLocalPanicHandler = true`, even under `--panic abort`. -/
theorem refute_step_v2_core_panic_local_handler_unsupported :
evalCorePanicAbort .abort .unreachable queryEmpty.callerMem true =
.fault .unsupported ∧
evalCorePanicAbort .abort .continue_ queryEmpty.callerMem true =
.fault .unsupported :=
⟨rfl, rfl⟩
/-- Guard `step_v2_core_panic_unwind_unsupported`: diverging
`core::panicking::*` calls stay `.fault .unsupported` under `--panic unwind`. -/
theorem refute_step_v2_core_panic_unwind_unsupported :
evalCorePanicAbort .unwind .continue_ queryEmpty.callerMem false =
.fault .unsupported ∧
evalCorePanicAbort .unwind .unreachable queryEmpty.callerMem false =
.fault .unsupported :=
⟨rfl, rfl⟩
/-- Shared valid `&'static str` `"ok"` rodata operand for `.panicAbort`
guard-mutation fixtures. -/
def panicOkStrOperand : Operand :=
.constant ⟨.ref .shared .str, .rodataRef [.init 111, .init 107] 0 0 (some 2)⟩
/-- Profile v2 program under `--panic abort` writing `7 : u8` through `&mut u8`
before executing `.coreCall .panicAbort`. -/
noncomputable def progMutBeforeCorePanicV2 : Program := {
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 2
panicStrategy := .abort
hasLocalPanicHandler := false
bodies := [{
argumentCount := 1
locals := [.unit, .ref .mut u8Ty, .never]
basicBlocks := [{
statements := [
.assign { localId := 1, projection := [.deref] }
(.use (.constant ⟨u8Ty, .scalar (BitVec.ofNat 128 7)⟩))
]
terminator :=
.coreCall .panicAbort [panicOkStrOperand]
{ localId := 2, projection := [] } none .unreachable
}]
isUnsafe := false
identity := "guard_mutation::mut_before_core_panic_v2"
}]
}
/-- Guard `step_v2_core_panic_abort_extract_caller_mem`: pre-abort `&mut`
mutations must survive in `.aborted (extractCallerMemory callerMem mem1)` when
stepping `.coreCall .panicAbort`. -/
theorem refute_step_v2_core_panic_abort_extract_caller_mem :
(match initStateV2 progMutBeforeCorePanicV2
{ args := [.ptr ⟨some 2, 0, .isize⟩], callerMem := cmBeforeAbort } with
| .ok s₀ =>
match evalStepV2 progMutBeforeCorePanicV2 s₀ with
| .step s₁ =>
match evalStepV2 progMutBeforeCorePanicV2 s₁ with
| .done (.aborted cm') => cm' = cmAfterAbort
| _ => False
| _ => False
| .error _ => False) :=
rfl
/-- Guard `step_v2_core_panic_abort_eval_args`:
`.coreCall .panicAbort` evaluates its `&str` argument (including `.rodataRef`
byte-initialization checks) before aborting, so both an uninitialized `&str`
local and an uninitialized `.rodataRef` operand fault `.fault .undefined`
rather than `.aborted`. -/
theorem refute_step_v2_core_panic_abort_eval_args :
let uninitTerm : TerminatorKind :=
.coreCall .panicAbort
[.copy { localId := 1, projection := [] }]
{ localId := 2, projection := [] } none .unreachable
let uninitRodataTerm : TerminatorKind :=
.coreCall .panicAbort
[.constant ⟨.ref .shared .str, .rodataRef [.uninit] 0 0 (some 1)⟩]
{ localId := 2, projection := [] } none .unreachable
let body : Body := {
argumentCount := 0
locals := [.unit, .ref .shared .str, .never]
basicBlocks := [{ statements := [], terminator := uninitTerm }]
}
let frame : FrameState := {
defId := 0
blockIdx := 0
stmtIdx := 0
locals := [.immediate none, .immediate none, .immediate none]
}
evalTerminatorV2 body { statements := [], terminator := uninitTerm }
frame MemoryState.empty { allocations := [] } .abort false =
.fault .undefined ∧
evalTerminatorV2 body { statements := [], terminator := uninitRodataTerm }
frame MemoryState.empty { allocations := [] } .abort false =
.fault .undefined :=
⟨rfl, rfl⟩
/-- Guard `step_v2_core_panic_abort_ref_valid`:
`validatePanicAbortArgs` re-validates `refValidInMem` on a local `&str` operand
passed to `.coreCall .panicAbort`, so a dangling `&str` local (including zero
length into a nonexistent allocation) faults `.fault .undefined` rather than
`.aborted` or `.unsupported`. -/
theorem refute_step_v2_core_panic_abort_ref_valid :
let term : TerminatorKind :=
.coreCall .panicAbort
[.copy { localId := 1, projection := [] }]
{ localId := 2, projection := [] } none .unreachable
let body : Body := {
argumentCount := 0
locals := [.unit, .ref .shared .str, .never]
basicBlocks := [{ statements := [], terminator := term }]
}
let danglingStr : Val := .slicePtr ⟨some 99, 0, .isize⟩ 0
let frame : FrameState := {
defId := 0
blockIdx := 0
stmtIdx := 0
locals :=
[.immediate none, .immediate (some danglingStr), .immediate none]
}
evalTerminatorV2 body { statements := [], terminator := term }
frame MemoryState.empty { allocations := [] } .abort false =
.fault .undefined :=
rfl
/-- Guard `step_v2_core_panic_abort_non_utf8_unsupported`:
`validatePanicAbortArgs` rejects initialized non-UTF-8 `&str` bytes passed to
`.coreCall .panicAbort` as `.fault .unsupported` rather than `.aborted`. -/
theorem refute_step_v2_core_panic_abort_non_utf8_unsupported :
let term : TerminatorKind :=
.coreCall .panicAbort
[.copy { localId := 1, projection := [] }]
{ localId := 2, projection := [] } none .unreachable
let body : Body := {
argumentCount := 0
locals := [.unit, .ref .shared .str, .never]
basicBlocks := [{ statements := [], terminator := term }]
}
let badUtf8Mem : MemoryState := {
nextAllocId := 3
allocations := [{
allocId := 2
bytes := [.init 0xff none]
alignLog2 := 0
mutability := .shared
live := true
}]
}
let badStr : Val := .slicePtr ⟨some 2, 0, .isize⟩ 1
let frame : FrameState := {
defId := 0
blockIdx := 0
stmtIdx := 0
locals := [.immediate none, .immediate (some badStr), .immediate none]
}
evalTerminatorV2 body { statements := [], terminator := term }
frame badUtf8Mem { allocations := [] } .abort false =
.fault .unsupported :=
rfl
/-- Guard `step_v2_ptr_metadata_str_dst_ty`:
`evalRvalueV2` `.unaryOp .ptrMetadata` on `&str` requires `usize` destination
type, returning `.ok` on `usize` and failing closed as `.error .unsupported` on
non-`usize` destinations. -/
theorem refute_step_v2_ptr_metadata_str_dst_ty :
let localsTys : List MirTy := [.int .isize false, .ref .shared .str]
let validStr : Val := .slicePtr ⟨some 2, 0, .isize⟩ 2
let locals : List LocalSlot := [.immediate none, .immediate (some validStr)]
let mem : MemoryState := {
nextAllocId := 3
allocations := [{
allocId := 2
bytes := [.init 111 none, .init 107 none]
alignLog2 := 0
mutability := .shared
live := true
}]
}
evalRvalueV2 localsTys locals mem (.int .isize false)
(.unaryOp .ptrMetadata (.copy { localId := 1, projection := [] })) =
.ok (.scalar ⟨.isize, false, BitVec.ofNat 128 2⟩, locals, mem) ∧
evalRvalueV2 localsTys locals mem .bool
(.unaryOp .ptrMetadata (.copy { localId := 1, projection := [] })) =
.error .unsupported :=
⟨rfl, rfl⟩
/-- Guard `step_v2_ptr_metadata_str_ref_valid`:
`evalRvalueV2` `.unaryOp .ptrMetadata` on `&str` validates `refValidInMem` on
the source slice, faulting `.error .undefined` on a dangling `&str` pointer. -/
theorem refute_step_v2_ptr_metadata_str_ref_valid :
let localsTys : List MirTy := [.int .isize false, .ref .shared .str]
let danglingStr : Val := .slicePtr ⟨some 99, 0, .isize⟩ 3
let locals : List LocalSlot :=
[.immediate none, .immediate (some danglingStr)]
evalRvalueV2 localsTys locals MemoryState.empty (.int .isize false)
(.unaryOp .ptrMetadata (.copy { localId := 1, projection := [] })) =
.error .undefined :=
rfl
/-- Guard `step_v2_core_panic_abort_dead_dst_unsupported`:
`.coreCall .panicAbort` requires its `!` destination local slot to be live
(`some (.immediate _)` or `some (.indirect _)`), failing closed as
`.fault .unsupported` when `dst` is `.dead`. -/
theorem refute_step_v2_core_panic_abort_dead_dst_unsupported :
let term : TerminatorKind :=
.coreCall .panicAbort [panicOkStrOperand]
{ localId := 1, projection := [] } none .unreachable
let body : Body := {
argumentCount := 0
locals := [.unit, .never]
basicBlocks := [{ statements := [], terminator := term }]
}
let frame : FrameState := {
defId := 0
blockIdx := 0
stmtIdx := 0
locals := [.immediate none, .dead]
}
evalTerminatorV2 body { statements := [], terminator := term }
frame MemoryState.empty { allocations := [] } .abort false =
.fault .unsupported :=
rfl
/-- Program copying from a projected place `_1.0`. -/
noncomputable def progCopyProjected : Program :=
mkSingleBlockProg 1 [u32Ty, u32Ty]
[.assign ⟨0, []⟩ (.use (.copy ⟨1, [.field 0 u32Ty]⟩))]
/-- Guard `step_copy_imm_reject_projection`: `Operand.copy` on an immediate
local with a non-empty projection faults with `.unsupported`. -/
theorem refute_step_copy_imm_reject_projection :
ReachesResult progCopyProjected { args := [u32Val 7] }
(.fault .unsupported) ∧
¬ WellFormed progCopyProjected { args := [u32Val 7] } :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Guard `step_copy_indirect_reject_projection`: `Operand.copy` on an
`.indirect` local with a non-empty projection faults with `.unsupported`. -/
theorem refute_step_copy_indirect_reject_projection :
(match initState progCopyProjected { args := [u32Val 7] } with
| .ok s₀ =>
match forceAllocation progCopyProjected s₀ 1 with
| .ok (s₁, _) =>
evalStep progCopyProjected 0 s₁ = .fault .unsupported
| .error _ => False
| .error _ => False) :=
rfl
/-- Program copying `_1 : bool` into `_0 : u32` (type mismatch), used to test
that `evalOperandToSlot`'s static `tyOk` check precedes indirect byte decoding.
-/
noncomputable def progCopyBoolToU32 : Program :=
mkSingleBlockProg 1 [u32Ty, .bool]
[.assign ⟨0, []⟩ (.use (.copy ⟨1, []⟩))]
/-- Guard `step_copy_indirect_tyok_before_load`: copying an `.indirect` `bool`
local whose memory holds invalid byte `2` into a `u32` destination faults
`.unsupported` (static type check) rather than `.undefined` (byte decode). -/
theorem refute_step_copy_indirect_tyok_before_load :
(match initState progCopyBoolToU32 { args := [.bool false] } with
| .ok s₀ =>
match forceAllocation progCopyBoolToU32 s₀ 1 with
| .ok (s₁, mplace) =>
match writeBytes s₁.mem mplace 0 [.init 2 none] with
| .ok memBad =>
evalStep progCopyBoolToU32 0 { s₁ with mem := memBad } =
.fault .unsupported
| .error _ => False
| .error _ => False
| .error _ => False) :=
rfl
/-- Program moving from a projected place `_1.0`. -/
noncomputable def progMoveProjected : Program :=
mkSingleBlockProg 1 [u32Ty, u32Ty]
[.assign ⟨0, []⟩ (.use (.move ⟨1, [.field 0 u32Ty]⟩))]
/-- Guard `step_move_imm_reject_projection`: `Operand.move` on an immediate
local with a non-empty projection faults with `.unsupported`. -/
theorem refute_step_move_imm_reject_projection :
ReachesResult progMoveProjected { args := [u32Val 7] }
(.fault .unsupported) ∧
¬ WellFormed progMoveProjected { args := [u32Val 7] } :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Guard `step_move_indirect_reject_projection`: `Operand.move` on an
`.indirect` local with a non-empty projection faults with `.unsupported`. -/
theorem refute_step_move_indirect_reject_projection :
(match initState progMoveProjected { args := [u32Val 7] } with
| .ok s₀ =>
match forceAllocation progMoveProjected s₀ 1 with
| .ok (s₁, _) =>
evalStep progMoveProjected 0 s₁ = .fault .unsupported
| .error _ => False
| .error _ => False) :=
rfl
/-- Program moving `_1 : bool` into `_0 : u32` (type mismatch). -/
noncomputable def progMoveBoolToU32 : Program :=
mkSingleBlockProg 1 [u32Ty, .bool]
[.assign ⟨0, []⟩ (.use (.move ⟨1, []⟩))]
/-- Guard `step_move_indirect_tyok_before_load`: moving an `.indirect` `bool`
local whose memory holds invalid byte `2` into a `u32` destination faults
`.unsupported` (static type check) rather than `.undefined` (byte decode). -/
theorem refute_step_move_indirect_tyok_before_load :
(match initState progMoveBoolToU32 { args := [.bool false] } with
| .ok s₀ =>
match forceAllocation progMoveBoolToU32 s₀ 1 with
| .ok (s₁, mplace) =>
match writeBytes s₁.mem mplace 0 [.init 2 none] with
| .ok memBad =>
evalStep progMoveBoolToU32 0 { s₁ with mem := memBad } =
.fault .unsupported
| .error _ => False
| .error _ => False
| .error _ => False) :=
rfl
/-- Program executing `switchInt` on a non-primitive-readable `.ordering`
local with an empty branch table (jumping to `bb1` return if not rejected). -/
noncomputable def progSwitchOrderingEmpty : Program where
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 1
bodies := [{
argumentCount := 1
locals := [.unit, .ordering]
basicBlocks := [
{ statements := []
terminator := .switchInt (.copy ⟨1, []⟩) ⟨[], 1⟩ },
{ statements := []
terminator := .return_ }
]
}]
/-- Guard `step_prim_operand_requires_primitive_ty`: `evalPrimitiveOperand`
rejects non-primitive-readable `.ordering` in `switchInt` with `.unsupported`.
-/
theorem refute_step_prim_operand_requires_primitive_ty :
ReachesResult progSwitchOrderingEmpty { args := [.ordering .equal] }
(.fault .unsupported) ∧
¬ WellFormed progSwitchOrderingEmpty { args := [.ordering .equal] } :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Program copying an uninitialized `u8` local `_1` into `_0 : u32`. -/
noncomputable def progUseUninitTypeMismatch : Program :=
mkSingleBlockProg 0 [u32Ty, u8Ty]
[.storageLive 1, .assign ⟨0, []⟩ (.use (.copy ⟨1, []⟩))]
/-- Guard `step_use_type_mismatch`: `evalRvalue .use` rejects mismatched
source/destination types (`u8` into `u32`) with `.unsupported` before
uninitialized `.undefined`. -/
theorem refute_step_use_type_mismatch :
ReachesResult progUseUninitTypeMismatch queryEmpty (.fault .unsupported) ∧
¬ WellFormed progUseUninitTypeMismatch queryEmpty :=
refutes_wf_of_execFault (fuel := 2) rfl
/-- Program casting an uninitialized `.ordering` local `_1` to `u8` via
`CastKind.intToInt`. -/
noncomputable def progCastNonIntLikeSrc : Program :=
mkSingleBlockProg 0 [u8Ty, .ordering]
[.storageLive 1, .assign ⟨0, []⟩ (.cast .intToInt (.copy ⟨1, []⟩) u8Ty)]
/-- Guard `step_cast_requires_intlike_src`: `evalRvalue (.cast .intToInt)`
rejects non-integer-like `.ordering` source with `.unsupported` before
uninitialized `.undefined`. -/
theorem refute_step_cast_requires_intlike_src :
ReachesResult progCastNonIntLikeSrc queryEmpty (.fault .unsupported) ∧
¬ WellFormed progCastNonIntLikeSrc queryEmpty :=
refutes_wf_of_execFault (fuel := 2) rfl
/-- Program reading `Rvalue.discriminant` on a projected enum place `_1.0`. -/
noncomputable def progDiscrProjected : Program :=
mkSingleBlockProg 1 [u8Ty, .enum reprU8EnumTy]
[.assign ⟨0, []⟩ (.discriminant ⟨1, [.field 0 u8Ty]⟩)]
/-- Guard `step_discriminant_imm_reject_projection`: `evalRvalue .discriminant`
rejects a projected immediate place with `.unsupported`. -/
theorem refute_step_discriminant_imm_reject_projection :
ReachesResult progDiscrProjected { args := [.enumVal reprU8EnumTy 0] }
(.fault .unsupported) ∧
¬ WellFormed progDiscrProjected { args := [.enumVal reprU8EnumTy 0] } :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Guard `step_discriminant_indirect_reject_projection`:
`evalRvalue .discriminant` rejects a projected `.indirect` place with
`.unsupported`. -/
theorem refute_step_discriminant_indirect_reject_projection :
(match initState progDiscrProjected { args := [.enumVal reprU8EnumTy 0] } with
| .ok s₀ =>
match forceAllocation progDiscrProjected s₀ 1 with
| .ok (s₁, _) =>
evalStep progDiscrProjected 0 s₁ = .fault .unsupported
| .error _ => False
| .error _ => False) :=
rfl
/-- Program assigning the `.bool` result of `BinOp.eq` into a `u8` destination
`_0`. -/
noncomputable def progWritePlaceTypeMismatch : Program :=
mkSingleBlockProg 2 [u8Ty, u32Ty, u32Ty]
[.assign ⟨0, []⟩ (.binaryOp .eq (.copy ⟨1, []⟩) (.copy ⟨2, []⟩))]
/-- Guard `step_write_place_check_val`: `writePlace` rejects writing a `.bool`
value into a `u8` destination with `.unsupported`. -/
theorem refute_step_write_place_check_val :
ReachesResult progWritePlaceTypeMismatch { args := [u32Val 1, u32Val 1] }
(.fault .unsupported) ∧
¬ WellFormed progWritePlaceTypeMismatch { args := [u32Val 1, u32Val 1] } :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Program executing `StorageDead 1` on a `u32` parameter `_1`. -/
noncomputable def progStorageDeadArg : Program :=
mkSingleBlockProg 1 [.unit, u32Ty] [.storageDead 1] .return_
/-- Guard `step_deallocate_local_indirect`: `deallocateLocal` deallocates the
stack allocation of an `.indirect` local on `StorageDead`, so reading its old
`MemPlace` faults with `.undefined`. -/
theorem refute_step_deallocate_local_indirect :
(match initState progStorageDeadArg { args := [u32Val 7] } with
| .ok s₀ =>
match forceAllocation progStorageDeadArg s₀ 1 with
| .ok (s₁, mplace) =>
match evalStep progStorageDeadArg 0 s₁ with
| .step s₂ =>
readBytes s₂.mem mplace 4 2 = .error .undefined
| _ => False
| .error _ => False
| .error _ => False) :=
rfl
/-- Program re-executing `StorageLive 1` on an already-initialized `u32`
parameter `_1` and then reading `_1`. -/
noncomputable def progStorageLiveReinit : Program :=
mkSingleBlockProg 1 [u32Ty, u32Ty]
[.storageLive 1, .assign ⟨0, []⟩ (.use (.copy ⟨1, []⟩))]
/-- Guard `step_storage_live_reinits_local`: `StorageLive` resets an
already-live non-ZST local to uninitialized so reading it faults `.undefined`.
-/
theorem refute_step_storage_live_reinits_local :
ReachesResult progStorageLiveReinit { args := [u32Val 7] }
(.fault .undefined) ∧
¬ WellFormed progStorageLiveReinit { args := [u32Val 7] } :=
refutes_wf_of_execFault (fuel := 2) rfl
/-- Program executing `StorageDead 0; StorageLive 0; _0 = 7u8; return` on the
return place `_0` (accepted if `StorageDead 0` is not refused). -/
noncomputable def progStorageDeadRet : Program :=
mkSingleBlockProg 0 [u8Ty]
[.storageDead 0, .storageLive 0,
.assign ⟨0, []⟩ (.use (.constant ⟨u8Ty, .scalar (BitVec.ofNat 128 7)⟩))]
.return_
/-- Guard `step_storage_dead_return_place`: `StorageDead 0` faults with
`.unsupported` even when followed by `StorageLive 0` and initialization. -/
theorem refute_step_storage_dead_return_place :
ReachesResult progStorageDeadRet queryEmpty (.fault .unsupported) ∧
¬ WellFormed progStorageDeadRet queryEmpty :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Program writing to a projected destination place `_0.0`. -/
noncomputable def progAssignDstProjected : Program :=
mkSingleBlockProg 1 [u32Ty, u32Ty]
[.assign ⟨0, [.field 0 u32Ty]⟩ (.use (.copy ⟨1, []⟩))]
/-- Guard `step_assign_reject_dst_projection`: `evalStatement .assign` rejects
a non-empty destination projection with `.unsupported`. -/
theorem refute_step_assign_reject_dst_projection :
ReachesResult progAssignDstProjected { args := [u32Val 7] }
(.fault .unsupported) ∧
¬ WellFormed progAssignDstProjected { args := [u32Val 7] } :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Program executing `StatementKind.unsupported`. -/
noncomputable def progUnsupportedStmt : Program :=
mkSingleBlockProg 0 [.unit] [.unsupported] .return_
/-- Guard `step_statement_unsupported_faults`: `StatementKind.unsupported`
faults with `.unsupported`. -/
theorem refute_step_statement_unsupported_faults :
ReachesResult progUnsupportedStmt queryEmpty (.fault .unsupported) ∧
¬ WellFormed progUnsupportedStmt queryEmpty :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Program executing `switchInt` on `u8` with an overflowing case `256`. -/
noncomputable def progSwitchIntOverflow : Program where
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 1
bodies := [{
argumentCount := 1
locals := [.unit, u8Ty]
basicBlocks := [
{ statements := []
terminator := .switchInt (.copy ⟨1, []⟩)
⟨[(BitVec.ofNat 128 256, 1)], 1⟩ },
{ statements := []
terminator := .return_ }
]
}]
/-- Guard `step_switch_int_case_overflow`: `evalSwitchBranches` rejects a `u8`
case value `256` overflowing 8 bits with `.unsupported`. -/
theorem refute_step_switch_int_case_overflow :
ReachesResult progSwitchIntOverflow { args := [u8Val 0] }
(.fault .unsupported) ∧
¬ WellFormed progSwitchIntOverflow { args := [u8Val 0] } :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Program executing `switchInt` on `bool` with invalid case `2`. -/
noncomputable def progSwitchBoolInvalidCase : Program where
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 1
bodies := [{
argumentCount := 1
locals := [.unit, .bool]
basicBlocks := [
{ statements := []
terminator := .switchInt (.copy ⟨1, []⟩)
⟨[(BitVec.ofNat 128 2, 1)], 1⟩ },
{ statements := []
terminator := .return_ }
]
}]
/-- Guard `step_switch_bool_invalid_case`: `evalBoolSwitchBranches` propagates
invalid bool case `2` as `.fault .undefined` rather than falling through. -/
theorem refute_step_switch_bool_invalid_case :
ReachesResult progSwitchBoolInvalidCase { args := [.bool false] }
(.fault .undefined) ∧
¬ WellFormed progSwitchBoolInvalidCase { args := [.bool false] } :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Program executing `switchInt` on `char` with surrogate case `0xD800`. -/
noncomputable def progSwitchCharInvalidCase : Program where
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 1
bodies := [{
argumentCount := 1
locals := [.unit, .char]
basicBlocks := [
{ statements := []
terminator := .switchInt (.copy ⟨1, []⟩)
⟨[(BitVec.ofNat 128 0xd800, 1)], 1⟩ },
{ statements := []
terminator := .return_ }
]
}]
/-- Guard `step_switch_char_invalid_case`: `evalCharSwitchBranches` propagates
surrogate char case `0xD800` as `.fault .undefined` rather than falling
through. -/
theorem refute_step_switch_char_invalid_case :
ReachesResult progSwitchCharInvalidCase { args := [.char 'a'] }
(.fault .undefined) ∧
¬ WellFormed progSwitchCharInvalidCase { args := [.char 'a'] } :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Program whose `bb0` is a cleanup unwind block (`cleanup := true`) with a
`TerminatorKind.return_` terminator. -/
noncomputable def progReturnInCleanupBlock : Program where
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 1
bodies := [{
argumentCount := 0
locals := [.unit]
basicBlocks := [{ statements := [], terminator := .return_, cleanup := true }]
}]
/-- Guard `step_return_in_cleanup_block`: returning from a `cleanup := true`
basic block faults with `.unsupported`. -/
theorem refute_step_return_in_cleanup_block :
ReachesResult progReturnInCleanupBlock queryEmpty (.fault .unsupported) ∧
¬ WellFormed progReturnInCleanupBlock queryEmpty :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Program executing `switchInt` on an overflow pair `(u32, bool)` with a
non-empty branch list. -/
noncomputable def progSwitchOverflowPairBranches : Program where
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 1
bodies := [{
argumentCount := 1
locals := [.unit, .tuple [u32Ty, .bool]]
basicBlocks := [
{ statements := []
terminator := .switchInt (.copy ⟨1, []⟩)
⟨[(BitVec.ofNat 128 0, 1)], 1⟩ },
{ statements := []
terminator := .return_ }
]
}]
/-- Guard `step_switch_overflow_pair_nonempty_branches`: `switchInt` on an
overflow pair with non-empty branches faults with `.unsupported`. -/
theorem refute_step_switch_overflow_pair_nonempty_branches :
ReachesResult progSwitchOverflowPairBranches
{ args := [.tuple [u32Val 0, .bool false]] } (.fault .unsupported) ∧
¬ WellFormed progSwitchOverflowPairBranches
{ args := [.tuple [u32Val 0, .bool false]] } :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Guard `step_unsupported_terminators_fault`: `.unwindResume`, `.coreCall`,
`.call`, and `.unsupported` terminators all fault with `.unsupported`. -/
theorem refute_step_unsupported_terminators_fault :
(ReachesResult (mkSingleBlockProg 0 [.unit] [] .unwindResume) queryEmpty
(.fault .unsupported) ∧
¬ WellFormed (mkSingleBlockProg 0 [.unit] [] .unwindResume) queryEmpty) ∧
(ReachesResult
(mkSingleBlockProg 0 [.unit] []
(.coreCall .sliceLen [] ⟨0, []⟩ none .continue_))
queryEmpty (.fault .unsupported) ∧
¬ WellFormed
(mkSingleBlockProg 0 [.unit] []
(.coreCall .sliceLen [] ⟨0, []⟩ none .continue_))
queryEmpty) ∧
(ReachesResult
(mkSingleBlockProg 0 [.unit] [] (.call 0 [] ⟨0, []⟩ none .continue_))
queryEmpty (.fault .unsupported) ∧
¬ WellFormed
(mkSingleBlockProg 0 [.unit] [] (.call 0 [] ⟨0, []⟩ none .continue_))
queryEmpty) ∧
(ReachesResult (mkSingleBlockProg 0 [.unit] [] .unsupported) queryEmpty
(.fault .unsupported) ∧
¬ WellFormed (mkSingleBlockProg 0 [.unit] [] .unsupported) queryEmpty) :=
⟨refutes_wf_of_execFault (fuel := 1) rfl,
refutes_wf_of_execFault (fuel := 1) rfl,
refutes_wf_of_execFault (fuel := 1) rfl,
refutes_wf_of_execFault (fuel := 1) rfl⟩
/-- Program whose `bb0` jumps to an out-of-bounds basic block index `99`. -/
noncomputable def progGotoOobBlock : Program :=
mkSingleBlockProg 0 [.unit] [] (.goto 99)
/-- Guard `step_oob_block_idx_faults`: `evalStep` faults with `.unsupported`
when `frame.blockIdx` is out of bounds. -/
theorem refute_step_oob_block_idx_faults :
ReachesResult progGotoOobBlock queryEmpty (.fault .unsupported) ∧
¬ WellFormed progGotoOobBlock queryEmpty :=
refutes_wf_of_execFault (fuel := 2) rfl
/-- Program reading an out-of-bounds local `_7` via `Operand.copy`. -/
noncomputable def progOperandCopyOob : Program :=
mkSingleBlockProg 0 [.unit] [.assign ⟨0, []⟩ (.use (.copy ⟨7, []⟩))]
/-- Guard `step_operand_copy_oob_local`: `evalOperandToSlot` `.copy` catch-all
rejects an out-of-bounds local index with `.unsupported`. -/
theorem refute_step_operand_copy_oob_local :
ReachesResult progOperandCopyOob queryEmpty (.fault .unsupported) ∧
¬ WellFormed progOperandCopyOob queryEmpty :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Program reading an out-of-bounds local `_7` via `Operand.move`. -/
noncomputable def progOperandMoveOob : Program :=
mkSingleBlockProg 0 [.unit] [.assign ⟨0, []⟩ (.use (.move ⟨7, []⟩))]
/-- Guard `step_operand_move_oob_local`: `evalOperandToSlot` `.move` catch-all
rejects an out-of-bounds local index with `.unsupported`. -/
theorem refute_step_operand_move_oob_local :
ReachesResult progOperandMoveOob queryEmpty (.fault .unsupported) ∧
¬ WellFormed progOperandMoveOob queryEmpty :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Program computing `Rvalue.discriminant` on a non-enum `u32` local `_1`. -/
noncomputable def progDiscrNonEnumSrc : Program :=
mkSingleBlockProg 1 [u8Ty, u32Ty] [.assign ⟨0, []⟩ (.discriminant ⟨1, []⟩)]
/-- Guard `step_discriminant_non_enum_src`: `evalRvalue .discriminant` rejects
non-enum, non-`Ordering` source locals (`u32`) with `.unsupported`. -/
theorem refute_step_discriminant_non_enum_src :
ReachesResult progDiscrNonEnumSrc { args := [u32Val 5] }
(.fault .unsupported) ∧
¬ WellFormed progDiscrNonEnumSrc { args := [u32Val 5] } :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Guard `step_rvalue_catchall_unsupported`: `evalRvalue` catch-all rejects
unmodeled `.ref`, `.addressOf`, `.cast .unsupported`, and `.unsupported`
rvalues with `.unsupported`. -/
theorem refute_step_rvalue_catchall_unsupported :
(ReachesResult
(mkSingleBlockProg 0 [.unit] [.assign ⟨0, []⟩ (.ref .shared ⟨0, []⟩)])
queryEmpty (.fault .unsupported) ∧
¬ WellFormed
(mkSingleBlockProg 0 [.unit] [.assign ⟨0, []⟩ (.ref .shared ⟨0, []⟩)])
queryEmpty) ∧
(ReachesResult
(mkSingleBlockProg 0 [.unit] [.assign ⟨0, []⟩ (.addressOf .mut ⟨0, []⟩)])
queryEmpty (.fault .unsupported) ∧
¬ WellFormed
(mkSingleBlockProg 0 [.unit] [.assign ⟨0, []⟩ (.addressOf .mut ⟨0, []⟩)])
queryEmpty) ∧
(ReachesResult
(mkSingleBlockProg 0 [.unit]
[.assign ⟨0, []⟩
(.cast .unsupported
(.constant ⟨u8Ty, .scalar (BitVec.ofNat 128 1)⟩) .unit)])
queryEmpty (.fault .unsupported) ∧
¬ WellFormed
(mkSingleBlockProg 0 [.unit]
[.assign ⟨0, []⟩
(.cast .unsupported
(.constant ⟨u8Ty, .scalar (BitVec.ofNat 128 1)⟩) .unit)])
queryEmpty) ∧
(ReachesResult
(mkSingleBlockProg 0 [.unit] [.assign ⟨0, []⟩ .unsupported])
queryEmpty (.fault .unsupported) ∧
¬ WellFormed
(mkSingleBlockProg 0 [.unit] [.assign ⟨0, []⟩ .unsupported])
queryEmpty) :=
⟨refutes_wf_of_execFault (fuel := 1) rfl,
refutes_wf_of_execFault (fuel := 1) rfl,
refutes_wf_of_execFault (fuel := 1) rfl,
refutes_wf_of_execFault (fuel := 1) rfl⟩
/-- Program assigning to an out-of-bounds destination local `_9`. -/
noncomputable def progAssignOobDst : Program :=
mkSingleBlockProg 0 [.unit]
[.assign ⟨9, []⟩ (.use (.constant ⟨u8Ty, .scalar (BitVec.ofNat 128 1)⟩))]
/-- Guard `step_assign_oob_dst`: `evalStatement .assign` rejects an
out-of-bounds `dst.localId` (`none`) with `.unsupported`. -/
theorem refute_step_assign_oob_dst :
ReachesResult progAssignOobDst queryEmpty (.fault .unsupported) ∧
¬ WellFormed progAssignOobDst queryEmpty :=
refutes_wf_of_execFault (fuel := 1) rfl
/-- Profile v2 program whose callee returns a reference to its own stack
local `_1`, which the caller then holds. -/
noncomputable def progReturnToCallerDanglingV2 : Program := {
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 2
bodies := [{
argumentCount := 0
locals := [.int .i8 false, .ref .shared (.int .i8 false)]
basicBlocks := [
{ statements := []
terminator := .call 1 [] { localId := 1, projection := [] } (some 1)
.continue_ },
{ statements := []
terminator := .return_ }]
identity := "guard_mutation::return_to_caller_dangling_main"
}, {
argumentCount := 0
locals := [.ref .shared (.int .i8 false), .int .i8 false]
basicBlocks := [{
statements := [
.assign { localId := 1, projection := [] }
(.use (.constant ⟨.int .i8 false, .scalar (BitVec.ofNat 128 9)⟩)),
.assign { localId := 0, projection := [] }
(.ref .shared { localId := 1, projection := [] })
]
terminator := .return_
}]
identity := "guard_mutation::return_to_caller_dangling_callee"
}]
}
/-- Guard `step_v2_return_to_caller_dangling`: returning from a callee frame
a reference to one of its own (deallocated) stack locals faults with
`.undefined` at the return step. -/
theorem refute_step_v2_return_to_caller_dangling :
(match initStateV2 progReturnToCallerDanglingV2 { args := [] } with
| .ok s₀ =>
match evalStepV2 progReturnToCallerDanglingV2 s₀ with
| .step s₁ =>
match evalStepV2 progReturnToCallerDanglingV2 s₁ with
| .step s₂ =>
match evalStepV2 progReturnToCallerDanglingV2 s₂ with
| .step s₃ =>
match evalStepV2 progReturnToCallerDanglingV2 s₃ with
| .fault .undefined => True
| _ => False
| _ => False
| _ => False
| _ => False
| .error _ => False) :=
trivial
/-- Profile v2 program calling `callee(&u8)`; the caller frame state is built
directly with a reference argument into a deallocated allocation. -/
noncomputable def progCallArgInvalidRefV2 : Program := {
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 2
bodies := [{
argumentCount := 1
locals := [.int .i8 false, .ref .shared (.int .i8 false)]
basicBlocks := [
{ statements := []
terminator := .call 1 [.copy { localId := 1, projection := [] }]
{ localId := 0, projection := [] } (some 1) .continue_ },
{ statements := []
terminator := .return_ }]
identity := "guard_mutation::call_arg_invalid_ref_main"
}, {
argumentCount := 1
locals := [.int .i8 false, .ref .shared (.int .i8 false)]
basicBlocks := [{
statements := [
.assign { localId := 0, projection := [] }
(.use (.copy { localId := 1, projection := [.deref] }))
]
terminator := .return_
}]
identity := "guard_mutation::call_arg_invalid_ref_callee"
}]
}
/-- Memory holding only the deallocated allocation `1`. -/
noncomputable def memDeadAlloc1 : MemoryState :=
{ allocations := [{
allocId := 1
alignLog2 := 0
mutability := .shared
bytes := [.init 7 none]
live := false
}], nextAllocId := 2 }
/-- Guard `step_v2_call_arg_invalid_ref`: an intra-crate call whose reference
argument points into a deallocated allocation faults with `.undefined`
before the callee frame is pushed. -/
theorem refute_step_v2_call_arg_invalid_ref :
(match evalStepV2 progCallArgInvalidRefV2 {
frames := [{
defId := 0
blockIdx := 0
stmtIdx := 0
locals := [.immediate none,
.immediate (some (.ptr ⟨some 1, 0, .isize⟩))]
}]
mem := memDeadAlloc1
} with
| .fault .undefined => True
| _ => False) :=
trivial
/-- Profile v2 program whose caller calls `callee() -> _1` with the
destination `_1` dead (`initStateV2` is bypassed by building the frame
directly), or `callee(move _1) -> _1` in block 1. -/
noncomputable def progCallDestinationV2 : Program := {
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 2
bodies := [{
argumentCount := 0
locals := [.int .i8 false, .int .i8 false]
basicBlocks := [
{ statements := []
terminator := .call 1 [] { localId := 1, projection := [] } (some 2)
.continue_ },
{ statements := []
terminator := .call 2 [.move { localId := 1, projection := [] }]
{ localId := 1, projection := [] } (some 2) .continue_ },
{ statements := []
terminator := .return_ }]
identity := "guard_mutation::call_destination_main"
}, {
argumentCount := 0
locals := [.int .i8 false]
basicBlocks := [{ statements := [], terminator := .return_ }]
identity := "guard_mutation::call_destination_callee"
}, {
argumentCount := 1
locals := [.int .i8 false, .int .i8 false]
basicBlocks := [{ statements := [], terminator := .return_ }]
identity := "guard_mutation::call_destination_callee_arg"
}]
}
/-- Guard `step_v2_call_dead_destination`: a call whose unprojected
destination local is dead faults with `.undefined` before the callee frame is
pushed, even though the callee could diverge. -/
theorem refute_step_v2_call_dead_destination :
(match evalStepV2 progCallDestinationV2 {
frames := [{
defId := 0
blockIdx := 0
stmtIdx := 0
locals := [.immediate none, .dead]
}]
mem := emptyMemory
} with
| .fault .undefined => True
| _ => False) :=
trivial
/-- Guard `step_v2_call_moves_disjoint`: a call whose destination is also a
`move` argument (`callee(move _1) -> _1`) is not definitely disjoint and
faults with `.unsupported`. -/
theorem refute_step_v2_call_moves_disjoint :
(match evalStepV2 progCallDestinationV2 {
frames := [{
defId := 0
blockIdx := 1
stmtIdx := 0
locals := [.immediate none,
.immediate (some (.scalar ⟨.i8, false, BitVec.ofNat 128 3⟩))]
}]
mem := emptyMemory
} with
| .fault .unsupported => True
| _ => False) :=
trivial
/-- Profile v2 program whose caller `_1` (`x: i8`) has had its address taken
into `_2` (`p: *mut i8`), so `_1` lives in memory (`.indirect`). Block 0 calls
`callee(move _1, copy _2) -> _3`, block 1 calls `callee_dst(copy _2) -> _1`,
and block 2 calls `callee(copy _1, move _2) -> _3`. Upstream passes the moved
`_1` in place and protects it (and protects an in-memory destination), so a
callee write through `p` is UB, which Profile v2 does not model. -/
noncomputable def progCallInPlaceV2 : Program := {
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 2
bodies := [{
argumentCount := 0
locals := [.int .i8 false, .int .i8 false,
.rawPtr .mut (.int .i8 false), .int .i8 false]
basicBlocks := [
{ statements := []
terminator := .call 1 [.move { localId := 1, projection := [] },
.copy { localId := 2, projection := [] }]
{ localId := 3, projection := [] } (some 3) .continue_ },
{ statements := []
terminator := .call 2 [.copy { localId := 2, projection := [] }]
{ localId := 1, projection := [] } (some 3) .continue_ },
{ statements := []
terminator := .call 1 [.copy { localId := 1, projection := [] },
.move { localId := 2, projection := [] }]
{ localId := 3, projection := [] } (some 3) .continue_ },
{ statements := []
terminator := .return_ }]
identity := "guard_mutation::call_in_place_main"
}, {
argumentCount := 2
locals := [.int .i8 false, .int .i8 false, .rawPtr .mut (.int .i8 false)]
basicBlocks := [{ statements := [], terminator := .return_ }]
identity := "guard_mutation::call_in_place_callee"
}, {
argumentCount := 1
locals := [.int .i8 false, .rawPtr .mut (.int .i8 false)]
basicBlocks := [{ statements := [], terminator := .return_ }]
identity := "guard_mutation::call_in_place_callee_dst"
}]
}
/-- Memory holding the in-memory caller local `_1` of `progCallInPlaceV2`
(allocation 1, value 1). -/
noncomputable def memCallInPlaceV2 : MemoryState :=
{ allocations := [{
allocId := 1
alignLog2 := 0
mutability := .mut
bytes := [.init 1 none]
live := true
}], nextAllocId := 2 }
/-- Caller frame of `progCallInPlaceV2` at block `bb`: `_1` lives in
allocation 1 and `_2` points to it. -/
noncomputable def frameCallInPlaceV2 (bb : Nat) : FrameState := {
defId := 0
blockIdx := bb
stmtIdx := 0
locals := [.immediate none, .indirect ⟨1, 0⟩,
.immediate (some (.ptr ⟨some 1, 0, .isize⟩)), .immediate none]
}
/-- Guard `step_v2_call_arg_move_indirect`: moving an in-memory local into a
call alongside a raw pointer to it (`callee(move x, copy p)`) faults with
`.unsupported` instead of passing a copy the callee's write through `p`
cannot alias. -/
theorem refute_step_v2_call_arg_move_indirect :
(match evalStepV2 progCallInPlaceV2
{ frames := [frameCallInPlaceV2 0], mem := memCallInPlaceV2 } with
| .fault .unsupported => True
| _ => False) :=
trivial
/-- Guard `step_v2_call_dst_indirect`: a call whose destination lives in
memory (`x = callee_dst(p)`) faults with `.unsupported`. -/
theorem refute_step_v2_call_dst_indirect :
(match evalStepV2 progCallInPlaceV2
{ frames := [frameCallInPlaceV2 1], mem := memCallInPlaceV2 } with
| .fault .unsupported => True
| _ => False) :=
trivial
/-- Guard `step_v2_call_arg_copy_indirect`: copying an in-memory local into a
call that also moves an argument (`callee(copy x, move p)`) faults with
`.unsupported`, as in Profile v1. -/
theorem refute_step_v2_call_arg_copy_indirect :
(match evalStepV2 progCallInPlaceV2
{ frames := [frameCallInPlaceV2 2], mem := memCallInPlaceV2 } with
| .fault .unsupported => True
| _ => False) :=
trivial
/-- Profile v2 program whose safe caller calls an `unsafe` callee. -/
noncomputable def progCallUnsafeCalleeV2 : Program := {
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 2
bodies := [{
argumentCount := 0
locals := [.int .i8 false]
basicBlocks := [
{ statements := []
terminator := .call 1 [] { localId := 0, projection := [] } (some 1)
.continue_ },
{ statements := []
terminator := .return_ }]
identity := "guard_mutation::call_unsafe_callee_main"
}, {
argumentCount := 0
locals := [.int .i8 false]
basicBlocks := [{ statements := [], terminator := .return_ }]
isUnsafe := true
identity := "guard_mutation::call_unsafe_callee"
}]
}
/-- Guard `step_v2_call_unsafe_callee`: an intra-crate call to an `unsafe`
callee, whose safety precondition Profile v2 does not check at the call site,
faults with `.unsupported` instead of pushing the callee frame. -/
theorem refute_step_v2_call_unsafe_callee :
(match evalStepV2 progCallUnsafeCalleeV2 {
frames := [{
defId := 0
blockIdx := 0
stmtIdx := 0
locals := [.immediate none]
}]
mem := emptyMemory
} with
| .fault .unsupported => True
| _ => False) :=
trivial
/-- Guard `step_v2_aggregate_unit_empty_fields`: `Rvalue.aggregateTuple` with
a non-empty operand list targeting `MirTy.unit` must fault `.unsupported`. -/
theorem refute_step_v2_aggregate_unit_empty_fields :
(match evalRvalueV2 [.unit] [.immediate none] emptyMemory .unit
(.aggregateTuple [.constant ⟨.bool, .scalar 1⟩]) with
| .error .unsupported => True
| _ => False) :=
trivial
/-- Anti-overreach canary: `Rvalue.aggregateTuple []` targeting `MirTy.unit`
evaluates cleanly to `Val.unit`. -/
theorem positive_step_v2_aggregate_unit_empty :
(match evalRvalueV2 [.unit] [.immediate none] emptyMemory .unit
(.aggregateTuple []) with
| .ok (.unit, _, _) => True
| _ => False) :=
trivial
/-- Guard `step_v2_sysroot_call_target_admitted`: `evalTerminatorV2` for
`.sysrootCall` must reject a call whose `unwind` edge is `.cleanup _` via
`callTargetAdmitted` rather than executing the arithmetic. -/
theorem refute_step_v2_sysroot_call_target_admitted :
let u64Ty : MirTy := .int .i64 false
let op : SysrootNumOp := ⟨.wrappingAdd, .i64, false⟩
let bb0 : BasicBlock := {
statements := []
terminator := .sysrootCall op
[.copy ⟨1, []⟩, .copy ⟨2, []⟩] ⟨0, []⟩ (some 1) (.cleanup 1)
cleanup := false
}
let bb1 : BasicBlock := {
statements := []
terminator := .return_
cleanup := false
}
let body : Body := {
identity := "refute_v2_sysroot_cleanup"
isUnsafe := false
argumentCount := 2
locals := [u64Ty, u64Ty, u64Ty]
basicBlocks := [bb0, bb1]
}
let frame : FrameState := {
defId := 0
blockIdx := 0
stmtIdx := 0
locals := [.immediate none,
.immediate (some (.scalar ⟨.i64, false, BitVec.ofNat 128 1⟩)),
.immediate (some (.scalar ⟨.i64, false, BitVec.ofNat 128 2⟩))]
}
(match evalTerminatorV2 body bb0 frame emptyMemory emptyCallerMemory
.abort with
| .fault .unsupported => True
| _ => False) :=
trivial
/-- Anti-overreach & overflow-UB canary: Profile v2 `.sysrootCall` wraps on
`wrappingAdd`/`wrappingSub`/`wrappingMul` and faults `.undefined` on
`uncheckedAdd` overflow. -/
theorem positive_step_v2_sysroot_call_wrapping_and_unchecked :
let u64Ty : MirTy := .int .i64 false
let maxU64 : Val := .scalar ⟨.i64, false, BitVec.ofNat 128 (2 ^ 64 - 1)⟩
let oneU64 : Val := .scalar ⟨.i64, false, BitVec.ofNat 128 1⟩
let zeroU64 : Val := .scalar ⟨.i64, false, BitVec.ofNat 128 0⟩
let mkBb (k : SysrootNumKind) : BasicBlock := {
statements := []
terminator := .sysrootCall ⟨k, .i64, false⟩
[.copy ⟨1, []⟩, .copy ⟨2, []⟩] ⟨0, []⟩ (some 1) .unreachable
cleanup := false
}
let bbRet : BasicBlock := {
statements := []
terminator := .return_
cleanup := false
}
let mkBody (k : SysrootNumKind) : Body := {
identity := "pos_v2_sysroot"
isUnsafe := false
argumentCount := 2
locals := [u64Ty, u64Ty, u64Ty]
basicBlocks := [mkBb k, bbRet]
}
let mkFrame (a b : Val) : FrameState := {
defId := 0
blockIdx := 0
stmtIdx := 0
locals := [.immediate none, .immediate (some a), .immediate (some b)]
}
(match evalTerminatorV2 (mkBody .wrappingAdd) (mkBb .wrappingAdd)
(mkFrame maxU64 oneU64) emptyMemory emptyCallerMemory .abort with
| .step s =>
match s.frames with
| [f] =>
f.blockIdx = 1 ∧
Trusted.MirSemantics.getElem? f.locals 0 =
some (.immediate (some zeroU64))
| _ => False
| _ => False) ∧
(match evalTerminatorV2 (mkBody .wrappingSub) (mkBb .wrappingSub)
(mkFrame zeroU64 oneU64) emptyMemory emptyCallerMemory .abort with
| .step s =>
match s.frames with
| [f] =>
f.blockIdx = 1 ∧
Trusted.MirSemantics.getElem? f.locals 0 =
some (.immediate (some maxU64))
| _ => False
| _ => False) ∧
(match evalTerminatorV2 (mkBody .uncheckedAdd) (mkBb .uncheckedAdd)
(mkFrame maxU64 oneU64) emptyMemory emptyCallerMemory .abort with
| .fault .undefined => True
| _ => False) :=
⟨⟨rfl, rfl⟩, ⟨rfl, rfl⟩, trivial⟩
/-- Signed, narrow, diverging, and cleanup-block canaries for Profile v2
`.sysrootCall`: `i32::unchecked_add(MAX, 1)` and `u8::unchecked_sub(0, 1)`
fault `.undefined`, `i16::wrapping_sub(MIN, 1)` wraps to `i16::MAX`, and
`target = none` or `bb.cleanup = true` fault `.unsupported`. -/
theorem canary_step_v2_sysroot_call_signed_narrow_and_refusals :
let i32Ty : MirTy := .int .i32 true
let u8Ty : MirTy := .int .i8 false
let i16Ty : MirTy := .int .i16 true
let u64Ty : MirTy := .int .i64 false
let bbRet : BasicBlock := {
statements := []
terminator := .return_
cleanup := false
}
let args : List Operand := [.copy ⟨1, []⟩, .copy ⟨2, []⟩]
let run (ty : MirTy) (op : SysrootNumOp) (tgt : Option BasicBlockId)
(cl : Bool) (a b : Val) : StepResult State TerminalOut :=
let bb : BasicBlock := {
statements := []
terminator := .sysrootCall op args ⟨0, []⟩ tgt .unreachable
cleanup := cl
}
let body : Body := {
identity := "canary_v2_sysroot"
isUnsafe := false
argumentCount := 2
locals := [ty, ty, ty]
basicBlocks := [bb, bbRet]
}
let frame : FrameState := {
defId := 0
blockIdx := 0
stmtIdx := 0
locals := [.immediate none, .immediate (some a), .immediate (some b)]
}
evalTerminatorV2 body bb frame emptyMemory emptyCallerMemory .abort
(match run i32Ty ⟨.uncheckedAdd, .i32, true⟩ (some 1) false
(.scalar ⟨.i32, true, BitVec.ofNat 128 0x7fffffff⟩)
(.scalar ⟨.i32, true, BitVec.ofNat 128 1⟩) with
| .fault .undefined => True
| _ => False) ∧
(match run u8Ty ⟨.uncheckedSub, .i8, false⟩ (some 1) false
(.scalar ⟨.i8, false, BitVec.ofNat 128 0⟩)
(.scalar ⟨.i8, false, BitVec.ofNat 128 1⟩) with
| .fault .undefined => True
| _ => False) ∧
(match run i16Ty ⟨.wrappingSub, .i16, true⟩ (some 1) false
(.scalar ⟨.i16, true, BitVec.ofNat 128 0x8000⟩)
(.scalar ⟨.i16, true, BitVec.ofNat 128 1⟩) with
| .step s =>
match s.frames with
| [f] =>
f.blockIdx = 1 ∧
Trusted.MirSemantics.getElem? f.locals 0 =
some (.immediate (some (.scalar ⟨.i16, true, BitVec.ofNat 128 0x7fff⟩)))
| _ => False
| _ => False) ∧
(match run u64Ty ⟨.wrappingAdd, .i64, false⟩ none false
(.scalar ⟨.i64, false, BitVec.ofNat 128 1⟩)
(.scalar ⟨.i64, false, BitVec.ofNat 128 2⟩) with
| .fault .unsupported => True
| _ => False) ∧
(match run u64Ty ⟨.wrappingAdd, .i64, false⟩ (some 1) true
(.scalar ⟨.i64, false, BitVec.ofNat 128 1⟩)
(.scalar ⟨.i64, false, BitVec.ofNat 128 2⟩) with
| .fault .unsupported => True
| _ => False) :=
⟨trivial, trivial, ⟨rfl, rfl⟩, trivial, trivial⟩
/-- Helper memory holding a live outer `&u32` slot (allocId 2) pointing to a
live initialized `u32` (allocId 1, value `7`) and a second outer slot
(allocId 3) pointing to a dead `u32` allocation (allocId 4). -/
private noncomputable def nestedU32Mem : MemoryState :=
let liveInnerPtrBytes : List AllocByte :=
[.init 0 (some 1), .init 0 (some 1), .init 0 (some 1), .init 0 (some 1),
.init 0 (some 1), .init 0 (some 1), .init 0 (some 1), .init 0 (some 1)]
let deadInnerPtrBytes : List AllocByte :=
[.init 0 (some 4), .init 0 (some 4), .init 0 (some 4), .init 0 (some 4),
.init 0 (some 4), .init 0 (some 4), .init 0 (some 4), .init 0 (some 4)]
{ allocations := [
{ allocId := 1, alignLog2 := 2, mutability := .shared,
bytes := [.init 7 none, .init 0 none, .init 0 none, .init 0 none],
live := true },
{ allocId := 2, alignLog2 := 3, mutability := .mut,
bytes := liveInnerPtrBytes, live := true },
{ allocId := 3, alignLog2 := 3, mutability := .shared,
bytes := deadInnerPtrBytes, live := true },
{ allocId := 4, alignLog2 := 2, mutability := .shared,
bytes := [.init 7 none, .init 0 none, .init 0 none, .init 0 none],
live := false }
],
nextAllocId := 5 }
/-- Guard `bytes_v2_ref_valid_shared_int_ref_mut_only_shared`: `refValidInMem`
rejects `&mut (&u32)` with `.unsupported` even on a live `.mut` outer
allocation holding a valid inner `&u32`. -/
theorem refute_bytes_v2_ref_valid_shared_int_ref_mut_only_shared :
(match refValidInMem nestedU32Mem .mut (.ref .shared (.int .i32 false))
(.ptr ⟨some 2, 0, .isize⟩) with
| .error .unsupported => True
| _ => False) :=
trivial
/-- Guard `bytes_v2_ref_valid_nested_inner_ref`: `refValidInMem` on a live
`&&u32` whose inner `&u32` points to a dead allocation faults `.undefined`. -/
theorem refute_bytes_v2_ref_valid_nested_inner_ref :
(match refValidInMem nestedU32Mem .shared (.ref .shared (.int .i32 false))
(.ptr ⟨some 3, 0, .isize⟩) with
| .error .undefined => True
| _ => False) ∧
(match refValidInMem nestedU32Mem .shared (.ref .shared (.int .i32 false))
(.ptr ⟨some 2, 0, .isize⟩) with
| .ok () => True
| _ => False) :=
⟨trivial, trivial⟩
/-- Guard `step_v2_read_place_deref_nested_ref_valid`: dereferencing a `&&u32`
local whose stored inner `&u32` is dangling faults `.undefined`. -/
theorem refute_step_v2_read_place_deref_nested_ref_valid :
(match readPlaceV2
[.ref .shared (.ref .shared (.int .i32 false))]
[.immediate (some (.ptr ⟨some 3, 0, .isize⟩))]
nestedU32Mem false ⟨0, [.deref]⟩ with
| .error .undefined => True
| _ => False) :=
trivial
/-- Guard `step_v2_aggregate_ordering_tag_valid`: `Rvalue.aggregateOrdering`
rejects invalid discriminant tags (`2`) with `.unsupported` while accepting
`255` (`Less`), `0` (`Equal`), and `1` (`Greater`). -/
theorem refute_step_v2_aggregate_ordering_tag_valid :
(match evalRvalueV2 [.ordering] [.immediate none] nestedU32Mem .ordering
(.aggregateOrdering 2) with
| .error .unsupported => True
| _ => False) ∧
(match evalRvalueV2 [.ordering] [.immediate none] nestedU32Mem .ordering
(.aggregateOrdering 255) with
| .ok (.ordering .less, _, _) => True
| _ => False) :=
⟨trivial, trivial⟩
/-- Guard `core_contracts_default_val_dst_type`: `CoreCallOp.defaultVal`
rejects a destination type that disagrees with the op's integer type. -/
theorem refute_core_contracts_default_val_dst_type :
(match execCoreContractOp nestedU32Mem (.defaultVal (.int .i8 false)) []
(.int .i32 false) with
| .error .unsupported => True
| _ => False) :=
trivial
/-- Guard `core_contracts_ref_int_partial_eq_second_arg`:
`CoreCallOp.refIntPartialEq` validates and reads the second `&&int` argument,
faulting `.undefined` when the second argument's inner `&u32` is dead. -/
theorem refute_core_contracts_ref_int_partial_eq_second_arg :
let rrU32 := MirTy.ref .shared (.ref .shared (.int .i32 false))
(match execCoreContractOp nestedU32Mem (.refIntPartialEq .i32 false false)
[(rrU32, .ptr ⟨some 2, 0, .isize⟩), (rrU32, .ptr ⟨some 3, 0, .isize⟩)]
.bool with
| .error .undefined => True
| _ => False) ∧
(match execCoreContractOp nestedU32Mem (.refIntPartialEq .i32 false false)
[(rrU32, .ptr ⟨some 2, 0, .isize⟩), (rrU32, .ptr ⟨some 2, 0, .isize⟩)]
.bool with
| .ok (.bool true, _) => True
| _ => False) :=
⟨trivial, trivial⟩
/-- Guard `core_contracts_unit_partial_eq_validates_refs`:
`CoreCallOp.unitPartialEq` validates both `&()` references via `refValidInMem`,
faulting `.undefined` on a null `&()` pointer. -/
theorem refute_core_contracts_unit_partial_eq_validates_refs :
(match execCoreContractOp nestedU32Mem (.unitPartialEq false)
[(.ref .shared .unit, .ptr ⟨none, 0, .isize⟩),
(.ref .shared .unit, .ptr ⟨none, 1, .isize⟩)]
.bool with
| .error .undefined => True
| _ => False) ∧
(match execCoreContractOp nestedU32Mem (.unitPartialEq false)
[(.ref .shared .unit, .ptr ⟨none, 1, .isize⟩),
(.ref .shared .unit, .ptr ⟨none, 1, .isize⟩)]
.bool with
| .ok (.bool true, _) => True
| _ => False) :=
⟨trivial, trivial⟩
/-! ## Profile v2 Drop Glue
Heap buffers for the `Vec`/`Box` drop-glue guards: allocation `1` holds a
4-byte `Vec<u8>` buffer, `2` a 2-byte buffer, and `3` a 1-byte `Box<u8>`
pointee. Allocation `4` is a 24-byte stack slot for an indirect `Vec<u8>`
local or a `&mut Vec<u8>` pointee. -/
noncomputable def dropHeap (aid : AllocId) (n : Nat) : Allocation :=
{ allocId := aid, alignLog2 := 0, mutability := .mut,
bytes := List.replicate n (.init 7 none) }
noncomputable def dropStack : Allocation :=
{ allocId := 4, alignLog2 := 3, mutability := .mut,
bytes := List.replicate 24 .uninit }
noncomputable def dropMem : MemoryState :=
{ nextAllocId := 5,
allocations := [dropHeap 1 4, dropHeap 2 2, dropHeap 3 1, dropStack] }
noncomputable def dropU8 : MirTy := .int .i8 false
noncomputable def dropVec1 : Val := .vec ⟨some 1, 0, .isize⟩ 4 4
noncomputable def dropVec2 : Val := .vec ⟨some 2, 0, .isize⟩ 2 1
noncomputable def dropVecEmpty : Val := .vec ⟨none, 1, .isize⟩ 0 0
/-- Liveness of allocations `a` and `b` after a drop-glue run. -/
noncomputable def dropLive (r : Except FaultKind MemoryState) (a b : AllocId) :
Except FaultKind (Option Bool × Option Bool) :=
r.map (fun m =>
((findAllocation a m.allocations).map (·.live),
(findAllocation b m.allocations).map (·.live)))
/-- Guard `alloc_v2_drop_vec_retire`: dropping a `Vec<u8>` with a nonzero
capacity frees its buffer, so pointers into it dangle afterwards. -/
theorem refute_alloc_v2_drop_vec_retire :
dropLive (dropGlueV2 dropMem (.vec dropU8) dropVec1) 1 2 =
.ok (some false, some true) := rfl
/-- Guard `alloc_v2_drop_box_retire`: dropping a non-zero-sized `Box<u8>`
frees its allocation. -/
theorem refute_alloc_v2_drop_box_retire :
dropLive (dropGlueV2 dropMem (.box dropU8)
(.boxPtr ⟨some 3, 0, .isize⟩ none)) 3 1 = .ok (some false, some true) :=
rfl
/-- Guard `alloc_v2_drop_vec_valid`: dropping a `Vec` handle whose capacity
disagrees with its buffer (8 elements claimed, 4 bytes allocated) faults with
`.undefined` instead of freeing the buffer. -/
theorem refute_alloc_v2_drop_vec_valid :
dropLive (dropGlueV2 dropMem (.vec dropU8) (.vec ⟨some 1, 0, .isize⟩ 8 4))
1 2 = .error .undefined := rfl
/-- Guard `alloc_v2_drop_box_valid`: dropping a `Box<u8>` whose allocation is
not one `u8` (allocation `2` holds 2 bytes) faults with `.undefined`. -/
theorem refute_alloc_v2_drop_box_valid :
dropLive (dropGlueV2 dropMem (.box dropU8)
(.boxPtr ⟨some 2, 0, .isize⟩ none)) 2 1 = .error .undefined := rfl
/-- Guard `alloc_v2_drop_fields`: a tuple drops every field in order, so both
`Vec` buffers of `(Vec<u8>, Vec<u8>)` are freed. -/
theorem refute_alloc_v2_drop_fields :
dropLive (dropGlueV2 dropMem (.tuple [.vec dropU8, .vec dropU8])
(.tuple [dropVec1, dropVec2])) 1 2 = .ok (some false, some false) := rfl
/-- Guard `alloc_v2_drop_array_elems`: an array with drop glue drops every
element (checked on `dropGlueV2` directly; no admitted local type is an array
of `Vec`s yet). -/
theorem refute_alloc_v2_drop_array_elems :
dropLive (dropGlueV2 dropMem (.array (.vec dropU8) 2)
(.array [dropVec1, dropVec2])) 1 2 = .ok (some false, some false) := rfl
/-- Guard `alloc_v2_drop_shape_mismatch_refused`: dropping a value whose shape
does not match a type with drop glue (a scalar as a `Vec<u8>`) faults with
`.unsupported` instead of skipping the glue. -/
theorem refute_alloc_v2_drop_shape_mismatch_refused :
dropLive (dropGlueV2 dropMem (.vec dropU8) (.scalar ⟨.i8, false, 0⟩)) 1 2 =
.error .unsupported := rfl
/-- Guard `alloc_v2_drop_option_some`: dropping `Some(v)` of an
`Option<Vec<u8>>` drops `v` and frees its buffer. -/
theorem refute_alloc_v2_drop_option_some :
dropLive (dropGlueV2 dropMem (.option (.vec dropU8))
(.optionVal (some dropVec1))) 1 2 = .ok (some false, some true) := rfl
/-- `dropMem` plus allocation `5`, the buffer of a one-element
`Vec<Vec<u8>>` (24 bytes), holding the handle `dropVec2`. -/
noncomputable def dropNestedMem : MemoryState :=
let m : MemoryState :=
{ nextAllocId := 6,
allocations := dropMem.allocations ++
[{ allocId := 5, alignLog2 := 3, mutability := .mut,
bytes := List.replicate 24 .uninit }] }
match storeIndirectV2 m (.vec dropU8) ⟨5, 0⟩ dropVec2 with
| .ok m1 => m1
| .error _ => m
/-- `struct Node { v: u8, next: Option<Box<Node>> }`: 16 bytes, `next` at 0
and `v` at 8. -/
noncomputable def drNodeTy : MirTy :=
.recAdt 71 (.struct_ ⟨71, 16, 3, [8, 0]⟩ [dropU8, .option (.box (.recSelf 71))])
/-- The `Node` with `v` and a `next` box to allocation `next`. -/
noncomputable def drNode (v : Nat) (next : Option AllocId) : Val :=
.tuple [.scalar ⟨.i8, false, BitVec.ofNat 128 v⟩,
.optionVal (next.map fun a => .boxPtr ⟨some a, 0, .isize⟩ none)]
/-- A heap allocation `aid` holding `drNode v next`. -/
noncomputable def drNodeAlloc (aid : AllocId) (v : Nat) (next : Option AllocId) :
Allocation :=
{ allocId := aid, alignLog2 := 3, mutability := .mut,
bytes :=
match encodeValV2 profileV2TargetEndian drNodeTy (drNode v next) with
| .ok bs => bs
| .error _ => [] }
/-- Allocation 6 is a `Node` whose `next` owns allocation 5, the last
`Node`. -/
noncomputable def drChainMem : MemoryState :=
{ nextAllocId := 7, allocations := [drNodeAlloc 5 2 none, drNodeAlloc 6 1 (some 5)] }
/-- Guards `alloc_v2_rec_needs_drop`, `alloc_rec_drop_arm`,
`alloc_rec_drop_self`, and `alloc_rec_drop_box_pointee`: a self-recursive
struct has drop glue, and dropping a `Node` that owns a two-node chain frees
both nodes' buffers, inner first, instead of leaving one live. -/
theorem refute_alloc_v2_rec_needs_drop :
dropLive (dropGlueV2 drChainMem drNodeTy (drNode 0 (some 6))) 6 5 =
.ok (some false, some false) := rfl
/-- Guard `alloc_rec_drop_fuel`: the fuel bounds the depth of nested buffers,
and running out faults with `.unsupported` rather than skipping the glue of
the innermost buffer; enough fuel drops the whole chain. -/
theorem refute_alloc_rec_drop_fuel :
dropLive (dropGlueFuelV2 2 drChainMem drNodeTy (drNode 0 (some 6))) 6 5 =
.error .unsupported ∧
dropLive (dropGlueFuelV2 3 drChainMem drNodeTy (drNode 0 (some 6))) 6 5 =
.ok (some false, some false) :=
⟨rfl, rfl⟩
/-- `struct Tree { v: u8, kids: Vec<Tree> }`: 32 bytes, `kids` at 0 and `v`
at 24. -/
noncomputable def drTreeTy : MirTy :=
.recAdt 81 (.struct_ ⟨81, 32, 3, [24, 0]⟩ [dropU8, .vec (.recSelf 81)])
/-- Allocation 8 holds one `Tree` whose empty `kids` owns allocation 9 (a
one-element buffer); the root's `kids` owns allocation 8. -/
noncomputable def drTreeMem : MemoryState :=
{ nextAllocId := 10,
allocations := [
{ allocId := 8, alignLog2 := 3, mutability := .mut,
bytes :=
match encodeValV2 profileV2TargetEndian drTreeTy
(.tuple [.scalar ⟨.i8, false, BitVec.ofNat 128 1⟩,
.vec ⟨some 9, 0, .isize⟩ 1 0]) with
| .ok bs => bs
| .error _ => [] },
{ allocId := 9, alignLog2 := 3, mutability := .mut,
bytes := List.replicate 32 .uninit }] }
/-- Guard `alloc_rec_drop_vec_elems`: dropping a `Tree` drops each element of
its `kids` buffer, so the child's own `kids` buffer is freed too. -/
theorem refute_alloc_rec_drop_vec_elems :
dropLive (dropGlueV2 drTreeMem drTreeTy
(.tuple [.scalar ⟨.i8, false, 0⟩, .vec ⟨some 8, 0, .isize⟩ 1 1])) 8 9 =
.ok (some false, some false) := rfl
/-- Anti-overreach canaries: a double free through a tuple faults, an empty
`Vec` and a `Box<[u8]>` drop without fault, a type without drop glue and a
`None` are no-ops, and a nested `Vec<Vec<u8>>` frees the inner buffer and
then the outer one. -/
theorem canary_alloc_v2_drop_glue :
dropLive (dropGlueV2 dropMem (.tuple [.vec dropU8, .vec dropU8])
(.tuple [dropVec1, dropVec1])) 1 2 = .error .undefined ∧
dropLive (dropGlueV2 dropMem (.vec dropU8) dropVecEmpty) 1 2 =
.ok (some true, some true) ∧
dropLive (dropGlueV2 dropMem (.box (.slice dropU8))
(.boxPtr ⟨some 1, 0, .isize⟩ (some 4))) 1 2 =
.ok (some false, some true) ∧
dropLive (dropGlueV2 dropMem dropU8 (.scalar ⟨.i8, false, 0⟩)) 1 2 =
.ok (some true, some true) ∧
dropLive (dropGlueV2 dropMem (.option (.vec dropU8)) (.optionVal none))
1 2 = .ok (some true, some true) ∧
dropLive (dropGlueV2 dropNestedMem (.vec (.vec dropU8))
(.vec ⟨some 5, 0, .isize⟩ 1 1)) 2 5 = .ok (some false, some false) :=
⟨rfl, rfl, rfl, rfl, rfl, rfl⟩
/-- Memory after dropping `dropVec1` (allocation `1` retired). -/
noncomputable def dropMemAfterVec1 : MemoryState :=
match dropGlueV2 dropMem (.vec dropU8) dropVec1 with
| .ok m => m
| .error _ => dropMem
/-- Canary: after a `Vec<u8>` is dropped, a `&[u8]` into its old buffer is
invalid, and loads through a `&u8` or `*const u8` into it fault with
`.undefined`, while the same accesses succeed before the drop. -/
theorem canary_alloc_v2_dangling_after_drop :
refValidInMem dropMemAfterVec1 .shared (.slice dropU8)
(.slicePtr ⟨some 1, 0, .isize⟩ 4) = .error .undefined ∧
loadIndirectV2 dropMemAfterVec1 dropU8 ⟨1, 0⟩ = .error .undefined ∧
refValidInMem dropMem .shared (.slice dropU8)
(.slicePtr ⟨some 1, 0, .isize⟩ 4) = .ok () ∧
loadIndirectV2 dropMem dropU8 ⟨1, 0⟩ =
.ok (some (.scalar ⟨.i8, false, BitVec.ofNat 128 7⟩)) :=
⟨rfl, rfl, rfl, rfl⟩
/-- Profile v2 program dropping `_1 : Vec<u8>` twice (body 0), and `*_1` with
`_1 : &mut Vec<u8>` twice (body 1). -/
noncomputable def progDropTwiceV2 : Program := {
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 2
bodies := [{
argumentCount := 1
locals := [.unit, .vec dropU8]
basicBlocks := [
{ statements := [], terminator := .drop ⟨1, []⟩ 1 .unreachable },
{ statements := [], terminator := .drop ⟨1, []⟩ 2 .unreachable },
{ statements := [], terminator := .return_ }]
identity := "guard_mutation::drop_twice"
}, {
argumentCount := 1
locals := [.unit, .ref .mut (.vec dropU8)]
basicBlocks := [
{ statements := [], terminator := .drop ⟨1, [.deref]⟩ 1 .unreachable },
{ statements := [], terminator := .drop ⟨1, [.deref]⟩ 2 .unreachable },
{ statements := [], terminator := .return_ }]
identity := "guard_mutation::drop_deref_twice"
}, {
argumentCount := 1
locals := [.unit, .ref .mut dropU8]
basicBlocks := [
{ statements := [], terminator := .drop ⟨1, [.deref]⟩ 1 .unreachable },
{ statements := [], terminator := .return_ }]
identity := "guard_mutation::drop_deref_u8"
}, {
argumentCount := 1
locals := [.unit, .ref .mut (.box dropU8), .ref .shared dropU8, dropU8]
basicBlocks := [
{ statements := [
.assign ⟨2, []⟩
(.cast .boxAsRef (.copy ⟨1, [.deref]⟩) (.ref .shared dropU8))]
terminator := .drop ⟨1, [.deref]⟩ 1 .unreachable },
{ statements := [.assign ⟨3, []⟩ (.use (.copy ⟨2, [.deref]⟩))]
terminator := .return_ }]
identity := "guard_mutation::drop_deref_box_then_use"
}, {
argumentCount := 1
locals := [.unit, .ref .mut (.vec dropU8), .ref .shared dropU8, dropU8,
.ref .shared (.slice dropU8), .ref .shared (.slice dropU8)]
basicBlocks := [
{ statements := [], terminator := .drop ⟨1, [.deref]⟩ 1 .unreachable },
{ statements := [.assign ⟨3, []⟩ (.use (.copy ⟨2, [.deref]⟩))]
terminator := .return_ },
{ statements := [.assign ⟨5, []⟩ (.useRetag (.copy ⟨4, []⟩))]
terminator := .return_ }]
identity := "guard_mutation::drop_deref_vec_then_use"
}]
}
/-- State at block `bb` of body `defId` with `_1` in `slot`, then `rest`, and
memory `mem`. -/
noncomputable def dropStateAt (defId : DefId) (bb : BasicBlockId)
(slot : LocalSlot) (rest : List LocalSlot) (mem : MemoryState) : State :=
{ frames := [{
defId := defId
blockIdx := bb
stmtIdx := 0
locals := .immediate (some .unit) :: slot :: rest
}]
mem := mem }
/-- State at block 0 of body `defId` with `_1` in `slot` and memory `mem`. -/
noncomputable def dropState (defId : DefId) (slot : LocalSlot)
(mem : MemoryState) : State :=
dropStateAt defId 0 slot [] mem
/-- `dropMem` with `v` stored in the stack slot `4`. -/
noncomputable def dropMemWith (v : Val) : MemoryState :=
match storeIndirectV2 dropMem (.vec dropU8) ⟨4, 0⟩ v with
| .ok m => m
| .error _ => dropMem
/-- Fault kind, or liveness of allocation `1`, after one step. -/
noncomputable def dropStepLive (r : StepResult State TerminalOut) :
Except FaultKind (Option Bool) :=
match r with
| .step s => .ok ((findAllocation 1 s.mem.allocations).map (·.live))
| .done _ => .ok none
| .fault k => .error k
/-- The result of a second step after a first one that stepped. -/
noncomputable def dropSecondStep (r : StepResult State TerminalOut) :
Except FaultKind (Option Bool) :=
match r with
| .step s => dropStepLive (evalStepV2 progDropTwiceV2 s)
| _ => .ok none
/-- Guard `step_v2_drop_runs_glue_immediate`: `drop(_1)` of an immediate
`Vec<u8>` local runs its drop glue and frees the buffer. -/
theorem refute_step_v2_drop_runs_glue_immediate :
dropStepLive (evalStepV2 progDropTwiceV2
(dropState 0 (.immediate (some dropVec1)) dropMem)) = .ok (some false) :=
rfl
/-- Guard `step_v2_drop_deinit_immediate`: a dropped immediate local is
deinitialized, so dropping it again faults with `.unsupported` (an empty
`Vec`, which frees nothing, still cannot be dropped twice). -/
theorem refute_step_v2_drop_deinit_immediate :
dropSecondStep (evalStepV2 progDropTwiceV2
(dropState 0 (.immediate (some dropVecEmpty)) dropMem)) =
.error .unsupported := rfl
/-- Guard `step_v2_drop_uninit_immediate`: dropping an uninitialized
(for example moved-out) `Vec` local faults with `.unsupported`; drop
elaboration never leaves such a `Drop`. -/
theorem refute_step_v2_drop_uninit_immediate :
dropStepLive (evalStepV2 progDropTwiceV2
(dropState 0 (.immediate none) dropMem)) = .error .unsupported := rfl
/-- Guard `step_v2_drop_runs_glue_indirect`: `drop(_1)` of a `Vec<u8>` local
stored in memory runs its drop glue. -/
theorem refute_step_v2_drop_runs_glue_indirect :
dropStepLive (evalStepV2 progDropTwiceV2
(dropState 0 (.indirect ⟨4, 0⟩) (dropMemWith dropVec1))) =
.ok (some false) := rfl
/-- Guard `step_v2_drop_deinit_indirect`: a dropped local stored in memory is
deinitialized, so dropping it again faults with `.unsupported`. -/
theorem refute_step_v2_drop_deinit_indirect :
dropSecondStep (evalStepV2 progDropTwiceV2
(dropState 0 (.indirect ⟨4, 0⟩) (dropMemWith dropVecEmpty))) =
.error .unsupported := rfl
/-- Guard `step_v2_drop_uninit_indirect`: dropping an uninitialized `Vec`
local stored in memory faults with `.unsupported`. -/
theorem refute_step_v2_drop_uninit_indirect :
dropStepLive (evalStepV2 progDropTwiceV2
(dropState 0 (.indirect ⟨4, 0⟩) dropMem)) = .error .unsupported := rfl
/-- Guard `step_v2_drop_deref_runs_glue`: `drop(*_1)` with
`_1 : &mut Vec<u8>` runs the drop glue of the pointed-to `Vec`. -/
theorem refute_step_v2_drop_deref_runs_glue :
dropStepLive (evalStepV2 progDropTwiceV2
(dropState 1 (.immediate (some (.ptr ⟨some 4, 0, .isize⟩)))
(dropMemWith dropVec1))) = .ok (some false) := rfl
/-- Guard `step_v2_drop_deref_deinit`: `drop(*_1)` deinitializes the
pointed-to `Vec`, so dropping it again through the same reference faults
with `.undefined` (the reference no longer points to a valid value). -/
theorem refute_step_v2_drop_deref_deinit :
dropSecondStep (evalStepV2 progDropTwiceV2
(dropState 1 (.immediate (some (.ptr ⟨some 4, 0, .isize⟩)))
(dropMemWith dropVecEmpty))) = .error .undefined := rfl
/-- Canary: dropping the same non-empty `Vec<u8>` local twice never frees its
buffer twice; the second drop faults with `.unsupported` on the deinitialized
local before reaching the (dead) buffer. -/
theorem canary_step_v2_drop_twice_faults_before_double_free :
dropSecondStep (evalStepV2 progDropTwiceV2
(dropState 0 (.immediate (some dropVec1)) dropMem)) =
.error .unsupported ∧
dropSecondStep (evalStepV2 progDropTwiceV2
(dropState 0 (.indirect ⟨4, 0⟩) (dropMemWith dropVec1))) =
.error .unsupported :=
⟨rfl, rfl⟩
/-- `dropMem` with the `Box<u8>` handle of allocation `3` stored in the stack
slot `4`. -/
noncomputable def dropMemWithBox : MemoryState :=
match storeIndirectV2 dropMem (.box dropU8) ⟨4, 0⟩
(.boxPtr ⟨some 3, 0, .isize⟩ none) with
| .ok m => m
| .error _ => dropMem
/-- Fault kind, or liveness of allocation `3`, after one step. -/
noncomputable def dropStepLive3 (r : StepResult State TerminalOut) :
Except FaultKind (Option Bool) :=
match r with
| .step s => .ok ((findAllocation 3 s.mem.allocations).map (·.live))
| .done _ => .ok none
| .fault k => .error k
/-- The `StepResult` after `n + 1` steps of `progDropTwiceV2` from `s`, as long
as each earlier step stepped. -/
noncomputable def dropRun (s : State) : Nat → StepResult State TerminalOut
| 0 => evalStepV2 progDropTwiceV2 s
| n + 1 =>
match evalStepV2 progDropTwiceV2 s with
| .step s' => dropRun s' n
| r => r
/-- Fault kind (or `none` on success) of a `StepResult`. -/
noncomputable def dropFault (r : StepResult State TerminalOut) :
Option FaultKind :=
match r with
| .fault k => some k
| _ => none
/-- Guard `step_v2_drop_deref_non_handle`: `drop(*_1)` through a reference to
a pointee without drop glue (here `&mut u8`), which drop elaboration never
leaves a `Drop` on, faults with `.unsupported`. -/
theorem refute_step_v2_drop_deref_non_handle :
dropFault (evalStepV2 progDropTwiceV2
(dropState 2 (.immediate (some (.ptr ⟨some 4, 0, .isize⟩)))
(dropMemWith dropVec1))) = some .unsupported := rfl
/-- Guard `step_v2_drop_deref_dead`: `drop(*_1)` with a dead `_1` faults with
`.undefined`. -/
theorem refute_step_v2_drop_deref_dead :
dropFault (evalStepV2 progDropTwiceV2
(dropState 1 .dead (dropMemWith dropVec1))) = some .undefined := rfl
/-- Guard `step_v2_drop_deref_box`: `drop(*_1)` with `_1 : &mut Box<u8>` runs
the drop glue of the pointed-to `Box`, freeing its allocation. -/
theorem refute_step_v2_drop_deref_box :
dropStepLive3 (dropRun (dropStateAt 3 0
(.immediate (some (.ptr ⟨some 4, 0, .isize⟩)))
[.immediate none, .immediate none] dropMemWithBox) 1) =
.ok (some false) := rfl
/-- Canary: a `&u8` taken from a `Box<u8>` (`BoxAsRef`) before `drop(*_1)`
dangles afterwards, so reading through it faults with `.undefined`; and after
`drop(*_1)` of a `Vec<u8>`, a read through a live `&u8` into its buffer and a
retag of a live `&[u8]` over it both fault with `.undefined`. -/
theorem canary_step_v2_drop_deref_then_dangling_use :
dropFault (dropRun (dropStateAt 3 0
(.immediate (some (.ptr ⟨some 4, 0, .isize⟩)))
[.immediate none, .immediate none] dropMemWithBox) 2) =
some .undefined ∧
dropFault (dropRun (dropStateAt 4 0
(.immediate (some (.ptr ⟨some 4, 0, .isize⟩)))
[.immediate (some (.ptr ⟨some 1, 0, .isize⟩)), .immediate none,
.immediate none, .immediate none] (dropMemWith dropVec1)) 1) =
some .undefined ∧
dropFault (match evalStepV2 progDropTwiceV2 (dropState 4
(.immediate (some (.ptr ⟨some 4, 0, .isize⟩)))
(dropMemWith dropVec1)) with
| .step s =>
evalStepV2 progDropTwiceV2 (dropStateAt 4 2
(.immediate (some (.ptr ⟨some 4, 0, .isize⟩)))
[.immediate none, .immediate none,
.immediate (some (.slicePtr ⟨some 1, 0, .isize⟩ 4)),
.immediate none] s.mem)
| r => r) = some .undefined :=
⟨rfl, rfl, rfl⟩
/-- Anti-overreach canary: before any drop, the same `BoxAsRef` read and the
same `&u8` read succeed. -/
theorem canary_step_v2_drop_deref_use_before_drop_ok :
dropFault (evalStepV2 progDropTwiceV2 (dropStateAt 3 1
(.immediate (some (.ptr ⟨some 4, 0, .isize⟩)))
[.immediate (some (.ptr ⟨some 3, 0, .isize⟩)), .immediate none]
dropMemWithBox)) = none ∧
dropFault (evalStepV2 progDropTwiceV2 (dropStateAt 4 1
(.immediate (some (.ptr ⟨some 4, 0, .isize⟩)))
[.immediate (some (.ptr ⟨some 1, 0, .isize⟩)), .immediate none,
.immediate none, .immediate none] (dropMemWith dropVec1))) = none :=
⟨rfl, rfl⟩
/-- `dropMem` with the `Vec<u8>` handle `dropVec1` stored in a `.shared`
copy of the stack slot `4`. -/
noncomputable def dropMemSharedSlot : MemoryState :=
match dropMemWith dropVec1 with
| m =>
{ m with allocations := m.allocations.map (fun a =>
if Nat.beq a.allocId 4 then { a with mutability := .shared } else a) }
/-- Canary: `drop(*_1)` through a `&mut Vec<u8>` whose handle lives in a
`.shared` allocation faults with `.undefined`. (`readVecFromRef`'s `reqMut`
check and `deinitIndirectV2`'s write to the handle both reject it, so neither
alone is a killable guard.) -/
theorem canary_step_v2_drop_deref_shared_handle :
dropFault (evalStepV2 progDropTwiceV2
(dropState 1 (.immediate (some (.ptr ⟨some 4, 0, .isize⟩)))
dropMemSharedSlot)) = some .undefined := rfl
/-- Canary: a zero-sized `Box<()>` and an empty `Box<[u8]>` (neither owns an
allocation) drop without fault and leave memory unchanged. -/
theorem canary_alloc_v2_drop_zst_boxes :
dropLive (dropGlueV2 dropMem (.box .unit) (.boxPtr ⟨none, 1, .isize⟩ none))
1 3 = .ok (some true, some true) ∧
dropLive (dropGlueV2 dropMem (.box (.slice dropU8))
(.boxPtr ⟨none, 1, .isize⟩ (some 0))) 1 3 =
.ok (some true, some true) :=
⟨rfl, rfl⟩
/-- Profile v2 program whose safe caller invokes a safe callee with a `&&u32`
return local in its signature. -/
noncomputable def progCallNestedRefSigCalleeV2 : Program := {
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 2
bodies := [{
argumentCount := 0
locals := [.unit, .ref .shared (.ref .shared (.int .i32 false))]
basicBlocks := [
{ statements := []
terminator := .call 1 [] { localId := 1, projection := [] } (some 1)
.continue_ },
{ statements := []
terminator := .return_ }]
identity := "guard_mutation::call_nested_ref_sig_main"
}, {
argumentCount := 0
locals := [.ref .shared (.ref .shared (.int .i32 false))]
basicBlocks := [{ statements := [], terminator := .return_ }]
identity := "guard_mutation::call_nested_ref_sig_callee"
}]
}
/-- Guard `step_v2_call_nested_ref_signature`: an intra-crate call to a callee
whose signature contains `&&int` faults with `.unsupported` instead of pushing
the callee frame. -/
theorem refute_step_v2_call_nested_ref_signature :
(match evalStepV2 progCallNestedRefSigCalleeV2 {
frames := [{
defId := 0
blockIdx := 0
stmtIdx := 0
locals := [.immediate none, .immediate none]
}]
mem := emptyMemory
} with
| .fault .unsupported => True
| _ => False) :=
trivial
/-- Guard `core_contracts_next_power_of_two_overflow_trap`: `next_power_of_two`
fails closed via `corePanicTrap` when `self > 2^(BITS - 1)`. -/
theorem refute_core_contracts_next_power_of_two_overflow_trap :
execNextPowerOfTwo .i8 129 = .error corePanicTrap :=
rfl
/-- Guard `core_contracts_next_multiple_of_div_zero_trap`: `next_multiple_of`
fails closed via `corePanicTrap` when `rhs = 0`. -/
theorem refute_core_contracts_next_multiple_of_div_zero_trap :
execNextMultipleOf .i8 0 0 = .error corePanicTrap :=
rfl
/-- Guard `core_contracts_next_multiple_of_overflow_trap`: `next_multiple_of`
fails closed via `corePanicTrap` when the rounded result exceeds `2^BITS - 1`.
-/
theorem refute_core_contracts_next_multiple_of_overflow_trap :
execNextMultipleOf .i8 255 2 = .error corePanicTrap :=
rfl
/-- Guard `core_contracts_next_power_of_two_unsigned_only`: signed
`numNextPowerOfTwo` calls fail closed as `.unsupported`. -/
theorem refute_core_contracts_next_power_of_two_unsigned_only :
execCoreContractOp MemoryState.empty (.numNextPowerOfTwo .i8 true)
[(.int .i8 true, .scalar ⟨.i8, true, 4⟩)] (.int .i8 false) =
.error .unsupported :=
rfl
/-- Guard `core_contracts_next_multiple_of_unsigned_only`: signed
`numNextMultipleOf` calls fail closed as `.unsupported`. -/
theorem refute_core_contracts_next_multiple_of_unsigned_only :
execCoreContractOp MemoryState.empty (.numNextMultipleOf .i8 true)
[(.int .i8 true, .scalar ⟨.i8, true, 4⟩),
(.int .i8 true, .scalar ⟨.i8, true, 2⟩)] (.int .i8 false) =
.error .unsupported :=
rfl
/-- Guard `core_contracts_cmp_min_tie_break`: `Ord::min` returns the first
argument (`self`) when `self` and `other` compare equal. -/
theorem refute_core_contracts_cmp_min_tie_break :
let lU8 : ScalarVal := ⟨.i8, false, BitVec.ofNat 128 5⟩
let rU8 : ScalarVal := ⟨.i8, false, BitVec.ofNat 128 261⟩
execCoreContractOp MemoryState.empty (.cmpMin .i8 false)
[(.int .i8 false, .scalar lU8), (.int .i8 false, .scalar rU8)]
(.int .i8 false) =
.ok (.scalar lU8, MemoryState.empty) :=
rfl
/-- Guard `core_contracts_cmp_max_tie_break`: `Ord::max` returns the second
argument (`other`) when `self` and `other` compare equal. -/
theorem refute_core_contracts_cmp_max_tie_break :
let lU8 : ScalarVal := ⟨.i8, false, BitVec.ofNat 128 5⟩
let rU8 : ScalarVal := ⟨.i8, false, BitVec.ofNat 128 261⟩
execCoreContractOp MemoryState.empty (.cmpMax .i8 false)
[(.int .i8 false, .scalar lU8), (.int .i8 false, .scalar rU8)]
(.int .i8 false) =
.ok (.scalar rU8, MemoryState.empty) :=
rfl
/-- Anti-overreach canaries for core scalar and slice ops: in-bounds
`next_power_of_two`, `next_multiple_of`, `div_ceil`, `checked_shl`,
`count_ones`, `trailing_zeros`, `overflowing_mul`, `mem::size_of`,
`intFromLeBytes`, and `get_unchecked(idx: usize)` continue to succeed. -/
theorem positive_core_scalar_ops_canaries :
execNextPowerOfTwo .i8 128 = .ok ⟨.i8, false, 128⟩ ∧
execNextMultipleOf .i8 13 4 = .ok ⟨.i8, false, 16⟩ ∧
execCoreContractOp MemoryState.empty (.numDivCeil .i8 false)
[(.int .i8 false, .scalar ⟨.i8, false, 13⟩),
(.int .i8 false, .scalar ⟨.i8, false, 4⟩)] (.int .i8 false) =
.ok (.scalar ⟨.i8, false, 4⟩, MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.numCheckedShl .i8 false)
[(.int .i8 false, .scalar ⟨.i8, false, 1⟩),
(.int .i32 false, .scalar ⟨.i32, false, 7⟩)]
(.option (.int .i8 false)) =
.ok (.optionVal (some (.scalar ⟨.i8, false, 128⟩)), MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.numCountOnes .i8 true)
[(.int .i8 true, .scalar ⟨.i8, true, BitVec.ofNat 128 0xff⟩)]
(.int .i32 false) =
.ok (.scalar ⟨.i32, false, 8⟩, MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.numTrailingZeros .i8 false)
[(.int .i8 false, .scalar ⟨.i8, false, 8⟩)] (.int .i32 false) =
.ok (.scalar ⟨.i32, false, 3⟩, MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.numOverflowingMul .i8 false)
[(.int .i8 false, .scalar ⟨.i8, false, 12⟩),
(.int .i8 false, .scalar ⟨.i8, false, 10⟩)]
(.tuple [.int .i8 false, .bool]) =
.ok (.tuple [.scalar ⟨.i8, false, 120⟩, .bool false], MemoryState.empty) ∧
execCoreCallOp MemoryState.empty
(.memSizeOf (.option (.int .i64 false))) [] (.int .isize false) =
.ok (.scalar ⟨.isize, false, 16⟩) ∧
execCoreCallOp MemoryState.empty (.intFromLeBytes .i16 false)
[(.array (.int .i8 false) 2,
.array [.scalar ⟨.i8, false, 0x34⟩, .scalar ⟨.i8, false, 0x12⟩])]
(.int .i16 false) =
.ok (.scalar ⟨.i16, false, 0x1234⟩) ∧
execCoreCallOp sharedInitU16x2Mem .sliceGetUncheckedIndex
[(.ref .shared (.slice (.int .i16 false)),
.slicePtr ⟨some 1, 0, .isize⟩ 2),
(.int .isize false, .scalar ⟨.isize, false, 1⟩)]
(.ref .shared (.int .i16 false)) =
.ok (.ptr ⟨some 1, 2, .isize⟩) :=
⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl⟩
/-- Guard `step_v2_get_unchecked_index_in_mut`: `get_unchecked(idx)` on a
`&mut [u8]` input over a `.shared` allocation faults with `.undefined` even
when returning `&u8`. -/
theorem refute_step_v2_get_unchecked_index_in_mut :
execCoreCallOp sharedInit2Mem .sliceGetUncheckedIndex
[(.ref .mut (.slice (.int .i8 false)),
.slicePtr ⟨some 1, 0, .isize⟩ 2),
(.int .isize false, .scalar ⟨.isize, false, 0⟩)]
(.ref .shared (.int .i8 false)) = .error .undefined :=
rfl
/-- Guard `step_v2_get_unchecked_index_oob`: `get_unchecked(idx)` faults with
`.undefined` when `idx >= len`. -/
theorem refute_step_v2_get_unchecked_index_oob :
execCoreCallOp sharedInit2Mem .sliceGetUncheckedIndex
[(.ref .shared (.slice (.int .i8 false)),
.slicePtr ⟨some 1, 0, .isize⟩ 2),
(.int .isize false, .scalar ⟨.isize, false, 2⟩)]
(.ref .shared (.int .i8 false)) = .error .undefined :=
rfl
/-- Guard `step_v2_get_unchecked_index_elem_stride`: `get_unchecked(1)` on
`&[u16]` advances the element pointer by `lay.size = 2`. -/
theorem refute_step_v2_get_unchecked_index_elem_stride :
execCoreCallOp sharedInitU16x2Mem .sliceGetUncheckedIndex
[(.ref .shared (.slice (.int .i16 false)),
.slicePtr ⟨some 1, 0, .isize⟩ 2),
(.int .isize false, .scalar ⟨.isize, false, 1⟩)]
(.ref .shared (.int .i16 false)) =
.ok (.ptr ⟨some 1, 2, .isize⟩) :=
rfl
/-- Guard `core_contracts_div_ceil_div_zero_trap`: `div_ceil` fails closed via
`corePanicTrap` when `rhs = 0`. -/
theorem refute_core_contracts_div_ceil_div_zero_trap :
execCoreContractOp MemoryState.empty (.numDivCeil .i8 false)
[(.int .i8 false, .scalar ⟨.i8, false, 5⟩),
(.int .i8 false, .scalar ⟨.i8, false, 0⟩)] (.int .i8 false) =
.error corePanicTrap :=
rfl
/-- Guard `core_contracts_div_ceil_unsigned_only`: signed `numDivCeil` calls
fail closed as `.unsupported`. -/
theorem refute_core_contracts_div_ceil_unsigned_only :
execCoreContractOp MemoryState.empty (.numDivCeil .i8 true)
[(.int .i8 true, .scalar ⟨.i8, true, 5⟩),
(.int .i8 true, .scalar ⟨.i8, true, 2⟩)] (.int .i8 false) =
.error .unsupported :=
rfl
/-- Guard `core_contracts_checked_shl_oob_none`: `checked_shl` returns `None`
when the shift amount reaches or exceeds `BITS`. -/
theorem refute_core_contracts_checked_shl_oob_none :
execCoreContractOp MemoryState.empty (.numCheckedShl .i8 false)
[(.int .i8 false, .scalar ⟨.i8, false, 1⟩),
(.int .i32 false, .scalar ⟨.i32, false, 8⟩)]
(.option (.int .i8 false)) =
.ok (.optionVal none, MemoryState.empty) :=
rfl
/-- Guards `core_contracts_leading_zeros_bit_test` and
`core_contracts_leading_zeros_width`: dedicated `u32::leading_zeros` and
`u64::leading_zeros` checks across zero, low-bit, and MSB-set inputs. -/
theorem refute_core_contracts_leading_zeros_u32_u64 :
let u32Ty : MirTy := .int .i32 false
let u64Ty : MirTy := .int .i64 false
execCoreContractOp MemoryState.empty (.numLeadingZeros .i32 false)
[(u32Ty, .scalar ⟨.i32, false, 0⟩)] u32Ty =
.ok (.scalar ⟨.i32, false, 32⟩, MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.numLeadingZeros .i32 false)
[(u32Ty, .scalar ⟨.i32, false, 1⟩)] u32Ty =
.ok (.scalar ⟨.i32, false, 31⟩, MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.numLeadingZeros .i32 false)
[(u32Ty, .scalar ⟨.i32, false, BitVec.ofNat 128 0x80000000⟩)] u32Ty =
.ok (.scalar ⟨.i32, false, 0⟩, MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.numLeadingZeros .i64 false)
[(u64Ty, .scalar ⟨.i64, false, 0⟩)] u32Ty =
.ok (.scalar ⟨.i32, false, 64⟩, MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.numLeadingZeros .i64 false)
[(u64Ty, .scalar ⟨.i64, false, 1⟩)] u32Ty =
.ok (.scalar ⟨.i32, false, 63⟩, MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.numLeadingZeros .i64 false)
[(u64Ty, .scalar ⟨.i64, false, BitVec.ofNat 128 0x8000000000000000⟩)]
u32Ty =
.ok (.scalar ⟨.i32, false, 0⟩, MemoryState.empty) :=
⟨rfl, rfl, rfl, rfl, rfl, rfl⟩
/-- Guard `core_contracts_count_ones_bit_count`: `count_ones` sums set bits
across `u32` and signed `i8` operands. -/
theorem refute_core_contracts_count_ones :
let u32Ty : MirTy := .int .i32 false
execCoreContractOp MemoryState.empty (.numCountOnes .i32 false)
[(u32Ty, .scalar ⟨.i32, false, BitVec.ofNat 128 0x0f0f0f0f⟩)] u32Ty =
.ok (.scalar ⟨.i32, false, 16⟩, MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.numCountOnes .i8 true)
[(.int .i8 true, .scalar ⟨.i8, true, BitVec.ofNat 128 0xff⟩)] u32Ty =
.ok (.scalar ⟨.i32, false, 8⟩, MemoryState.empty) :=
⟨rfl, rfl⟩
/-- Guard `core_contracts_trailing_zeros_bit_test`: `trailing_zeros` stops at
the least-significant set bit for `u32` and `u64` and returns `BITS` for `0`. -/
theorem refute_core_contracts_trailing_zeros :
let u32Ty : MirTy := .int .i32 false
let u64Ty : MirTy := .int .i64 false
execCoreContractOp MemoryState.empty (.numTrailingZeros .i32 false)
[(u32Ty, .scalar ⟨.i32, false, 0⟩)] u32Ty =
.ok (.scalar ⟨.i32, false, 32⟩, MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.numTrailingZeros .i32 false)
[(u32Ty, .scalar ⟨.i32, false, 8⟩)] u32Ty =
.ok (.scalar ⟨.i32, false, 3⟩, MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.numTrailingZeros .i64 false)
[(u64Ty, .scalar ⟨.i64, false, BitVec.ofNat 128 0x100000000⟩)] u32Ty =
.ok (.scalar ⟨.i32, false, 32⟩, MemoryState.empty) :=
⟨rfl, rfl, rfl⟩
/-- Guard `core_contracts_is_multiple_of_zero_rhs`: `0.is_multiple_of(0)` is
`true` while `5.is_multiple_of(0)` is `false`. -/
theorem refute_core_contracts_is_multiple_of_zero_rhs :
let u64Ty : MirTy := .int .i64 false
execCoreContractOp MemoryState.empty (.numIsMultipleOf .i64 false)
[(u64Ty, .scalar ⟨.i64, false, 0⟩), (u64Ty, .scalar ⟨.i64, false, 0⟩)]
.bool = .ok (.bool true, MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.numIsMultipleOf .i64 false)
[(u64Ty, .scalar ⟨.i64, false, 5⟩), (u64Ty, .scalar ⟨.i64, false, 0⟩)]
.bool = .ok (.bool false, MemoryState.empty) :=
⟨rfl, rfl⟩
/-- Guard `core_contracts_is_multiple_of_unsigned_only`: signed
`numIsMultipleOf` fails closed as `.unsupported`. -/
theorem refute_core_contracts_is_multiple_of_unsigned_only :
execCoreContractOp MemoryState.empty (.numIsMultipleOf .i8 true)
[(.int .i8 true, .scalar ⟨.i8, true, 4⟩),
(.int .i8 true, .scalar ⟨.i8, true, 2⟩)] .bool =
.error .unsupported :=
rfl
private noncomputable def mutInit3Mem : MemoryState :=
{ allocations := [{
allocId := 1, alignLog2 := 0, mutability := .mut,
bytes := [.init 10 none, .init 20 none, .init 30 none],
live := true
}], nextAllocId := 2 }
/-- Guard `core_contracts_split_at_mut_bounds_panic`: `split_at_mut` with
`mid > len` returns `.panicked` (which aborts under `--panic abort`). -/
theorem refute_core_contracts_split_at_mut_bounds_panic :
execSliceSplitAtOutcome mutInit3Mem .mut .mut (.int .i8 false)
⟨some 1, 0, .isize⟩ 3 4 = .panicked :=
rfl
/-- Guard `core_contracts_split_at_mut_no_shared_upgrade`: `split_at_mut`
forbids upgrading a `.shared` input slice reference to `.mut`. -/
theorem refute_core_contracts_split_at_mut_no_shared_upgrade :
execSliceSplitAtOutcome mutInit3Mem .mut .shared (.int .i8 false)
⟨some 1, 0, .isize⟩ 3 1 = .fault .undefined :=
rfl
/-- Guard `core_contracts_split_at_mut_suffix_offset_disjoint`: `split_at_mut`
advances the suffix pointer by `mid * size` so both returned `&mut` slices have
disjoint spans. -/
theorem refute_core_contracts_split_at_mut_suffix_offset_disjoint :
let pairTy : MirTy := .tuple [
.ref .mut (.slice (.int .i8 false)),
.ref .mut (.slice (.int .i8 false))
]
match execSliceSplitAtOutcome mutInit3Mem .mut .mut (.int .i8 false)
⟨some 1, 0, .isize⟩ 3 1 with
| .ok v _ => spansPairwiseDisjoint (refAccessSpans pairTy v) = true
| _ => False :=
rfl
/-- Guard `core_contracts_split_at_mut_suffix_len_union`: `split_at_mut` sets
the suffix slice length to `len - mid` so prefix and suffix partition the input
span without exceeding allocation bounds. -/
theorem refute_core_contracts_split_at_mut_suffix_len_union :
execSliceSplitAtOutcome mutInit3Mem .mut .mut (.int .i8 false)
⟨some 1, 0, .isize⟩ 3 1 =
.ok (.tuple [
.slicePtr ⟨some 1, 0, .isize⟩ 1,
.slicePtr ⟨some 1, 1, .isize⟩ 2
]) mutInit3Mem :=
rfl
/-- Guard `step_v2_core_call_dead_destination`: a returning `.coreCall` whose
destination local is `.dead` faults with `.undefined` even when the contract
would panic (`split_at_mut` with `mid > len` under `--panic abort`). -/
theorem refute_step_v2_core_call_dead_destination :
let mutSliceTy : MirTy := .ref .mut (.slice (.int .i8 false))
let pairTy : MirTy := .tuple [mutSliceTy, mutSliceTy]
let bb : BasicBlock := {
statements := []
terminator :=
.coreCall (.sliceSplitAt .mut (.int .i8 false))
[.copy { localId := 1, projection := [] },
.copy { localId := 2, projection := [] }]
{ localId := 0, projection := [] } (some 1) .unreachable
}
let body : Body := {
argumentCount := 2
locals := [pairTy, mutSliceTy, .int .isize false]
basicBlocks := [bb, { statements := [], terminator := .return_ }]
}
let frame : FrameState := {
defId := 0
blockIdx := 0
stmtIdx := 0
locals := [
.dead,
.immediate (some (.slicePtr ⟨some 1, 0, .isize⟩ 3)),
.immediate (some (.scalar ⟨.isize, false, BitVec.ofNat 128 4⟩))
]
}
evalTerminatorV2 body bb frame mutInit3Mem ⟨mutInit3Mem.allocations⟩
.abort false = .fault .undefined :=
rfl
/-- Guard `core_contracts_array_subslice_len_u64_bound`:
`execArraySubsliceOutcome` rejects synthetic array lengths `>= 2^64` as
`.unsupported` before entering `execSliceSubsliceOutcome` (which would fault
`.undefined` on a null pointer). -/
theorem refute_core_contracts_array_subslice_len_u64_bound :
execArraySubsliceOutcome mutInit3Mem .shared .shared .unit (Nat.pow 2 64)
⟨none, 0, .isize⟩ 0 0 = .fault .unsupported :=
rfl
/-- Guard `core_contracts_subslice_oob_panics`: `&s[1..4]` on a 3-element
`&mut [u8]` panics rather than faulting. -/
theorem refute_core_contracts_subslice_oob_panics :
execSliceSubsliceOutcome mutInit3Mem .mut .mut (.int .i8 false)
⟨some 1, 0, .isize⟩ 3 1 4 = .panicked :=
rfl
/-- Guard `core_contracts_split_at_oob_panics`: `split_at(4)` on a 3-element
`&[u8]` panics (`mid > len`) rather than faulting. -/
theorem refute_core_contracts_split_at_oob_panics :
(match execSliceSplitAtOutcome mutInit3Mem .shared .shared (.int .i8 false)
⟨some 1, 0, .isize⟩ 3 4 with
| .fault _ => false
| _ => true) = true :=
rfl
/-- Guard `core_contracts_option_unwrap_none_panics`: `Option::<u8>::unwrap`
on `None` panics rather than faulting. -/
theorem refute_core_contracts_option_unwrap_none_panics :
(match execCoreContractOpOutcome MemoryState.empty
(.optionUnwrap (.int .i8 false))
[(.option (.int .i8 false), .optionVal none)] (.int .i8 false) with
| .panicked => true
| _ => false) = true :=
rfl
/-- A returning `Option::<u8>::unwrap` call on local `_1`. -/
noncomputable def unwrapNoneBody : Body := {
argumentCount := 0
locals := [.int .i8 false, .option (.int .i8 false)]
basicBlocks := [{
statements := []
terminator :=
.coreCall (.optionUnwrap (.int .i8 false))
[.copy { localId := 1, projection := [] }]
{ localId := 0, projection := [] } (some 0) .continue_
}]
}
/-- The frame of `unwrapNoneBody` with `_1 = None`. -/
noncomputable def unwrapNoneFrame : FrameState := {
defId := 0
blockIdx := 0
stmtIdx := 0
locals := [.immediate none, .immediate (some (.optionVal none))]
}
/-- Guard `step_v2_core_call_panic_dispatch`: a returning `core` call that
panics (`Option::unwrap` on `None`) aborts under `--panic abort` without a
local panic handler, but stays `.fault .unsupported` under `--panic unwind`,
with a crate-local `#[panic_handler]`, or on a `.cleanup` unwind edge. -/
theorem refute_step_v2_core_call_panic_dispatch :
let cleanupBb : BasicBlock := {
statements := []
terminator :=
.coreCall (.optionUnwrap (.int .i8 false))
[.copy { localId := 1, projection := [] }]
{ localId := 0, projection := [] } (some 0) (.cleanup 0)
}
let cleanupBody : Body := { unwrapNoneBody with basicBlocks := [cleanupBb] }
(match unwrapNoneBody.basicBlocks with
| [bb] =>
(match evalTerminatorV2 unwrapNoneBody bb unwrapNoneFrame
MemoryState.empty ⟨[]⟩ .abort false with
| .done (.aborted _) => true
| _ => false) &&
(match evalTerminatorV2 unwrapNoneBody bb unwrapNoneFrame
MemoryState.empty ⟨[]⟩ .unwind false with
| .fault .unsupported => true
| _ => false) &&
(match evalTerminatorV2 unwrapNoneBody bb unwrapNoneFrame
MemoryState.empty ⟨[]⟩ .abort true with
| .fault .unsupported => true
| _ => false) &&
(match evalTerminatorV2 cleanupBody cleanupBb unwrapNoneFrame
MemoryState.empty ⟨[]⟩ .abort false with
| .fault .unsupported => true
| _ => false)
| _ => false) = true :=
rfl
/-- Guard `step_v2_core_call_panic_caller_mem`: an aborting `core` call panic
reports caller memory as it is at the call
(`extractCallerMemory callerMem mem1`), not the entry snapshot. Here caller
allocation `1` holds `9` in memory but `7` in the snapshot. -/
theorem refute_step_v2_core_call_panic_caller_mem :
(match unwrapNoneBody.basicBlocks with
| [bb] =>
match evalTerminatorV2 unwrapNoneBody bb unwrapNoneFrame
{ nextAllocId := 2
allocations :=
[{ allocId := 1, alignLog2 := 0, mutability := .mut,
bytes := [.init 9 none], live := true }] }
⟨[{ allocId := 1, alignLog2 := 0, mutability := .mut,
bytes := [.init 7 none], live := true }]⟩ .abort false with
| .done (.aborted cm') =>
cm'.allocations.map (·.bytes) = [[.init 9 none]]
| _ => False
| _ => False) :=
rfl
/-- Guard `alloc_resize_data_only`: `Vec::resize` on `Box` elements would copy
an owned handle, so it is `.unsupported` before any memory access. -/
theorem refute_alloc_resize_data_only :
(match evalVecResizeOutcome emptyMemory (.box .bool) ⟨none, 8, .isize⟩ 0
(.boxPtr ⟨some 1, 0, .isize⟩ none) with
| .fault .unsupported => True
| _ => False) :=
trivial
/-- Guard `alloc_extend_from_slice_data_only`: `Vec::extend_from_slice` on
`Box` elements would copy owned handles, so it is `.unsupported`. -/
theorem refute_alloc_extend_from_slice_data_only :
(match evalVecExtendFromSliceOutcome emptyMemory (.box .bool)
⟨none, 8, .isize⟩ ⟨none, 8, .isize⟩ 0 with
| .fault .unsupported => True
| _ => False) :=
trivial
/-- Allocation 1 holds a live `bool`; allocation 2 a `&bool` pointing at it
and allocation 3 a `&bool` pointing at the missing allocation 9. -/
private noncomputable def nestedBoolMem : MemoryState := {
allocations := [
{ allocId := 1, alignLog2 := 0, mutability := .shared,
bytes := [.init 1 none], live := true },
{ allocId := 2, alignLog2 := 3, mutability := .mut,
bytes := List.replicate 8 (.init 0 (some 1)), live := true },
{ allocId := 3, alignLog2 := 3, mutability := .mut,
bytes := List.replicate 8 (.init 0 (some 9)), live := true }]
nextAllocId := 4
}
/-- Guard `bytes_v2_ref_valid_nested_inner`: a `&&bool` is valid only if the
`&bool` it points at is, so one whose inner reference dangles is invalid. -/
theorem refute_bytes_v2_ref_valid_nested_inner :
refValidInMem nestedBoolMem .shared (.ref .shared .bool)
(.ptr ⟨some 3, 0, .isize⟩) = .error .undefined ∧
refValidInMem nestedBoolMem .shared (.ref .shared .bool)
(.ptr ⟨some 2, 0, .isize⟩) = .ok () :=
⟨rfl, rfl⟩
/-- Guard `bytes_v2_ref_valid_nested_shared_only`: a two-level reference is
only ever shared, so `&mut &bool` validity is `.unsupported` even over valid
memory. -/
theorem refute_bytes_v2_ref_valid_nested_shared_only :
(match refValidInMem nestedBoolMem .mut (.ref .shared .bool)
(.ptr ⟨some 2, 0, .isize⟩) with
| .error .unsupported => True
| _ => False) :=
trivial
/-- Allocation 1 holds a live `bool` in mutable memory and allocation 4 one in
shared memory; allocation 2 holds a reference to allocation 1 and allocation 3
one to allocation 4. -/
private noncomputable def nestedMutBoolMem : MemoryState := {
allocations := [
{ allocId := 1, alignLog2 := 0, mutability := .mut,
bytes := [.init 1 none], live := true },
{ allocId := 2, alignLog2 := 3, mutability := .mut,
bytes := List.replicate 8 (.init 0 (some 1)), live := true },
{ allocId := 3, alignLog2 := 3, mutability := .mut,
bytes := List.replicate 8 (.init 0 (some 4)), live := true },
{ allocId := 4, alignLog2 := 0, mutability := .shared,
bytes := [.init 1 none], live := true }]
nextAllocId := 5
}
/-- Guard `bytes_v2_ref_valid_nested_inner_mut_alloc`: a `& &mut bool` whose
inner reference points into shared memory is invalid, while one pointing into
mutable memory is valid, and a `& &mut ()` (ZST pointee) pointing into live
shared memory is valid (matching `refValidInMem` for `&mut ()`). -/
theorem refute_bytes_v2_ref_valid_nested_inner_mut_alloc :
refValidInMem nestedMutBoolMem .shared (.ref .mut .bool)
(.ptr ⟨some 3, 0, .isize⟩) = .error .undefined ∧
refValidInMem nestedMutBoolMem .shared (.ref .mut .bool)
(.ptr ⟨some 2, 0, .isize⟩) = .ok () ∧
refValidInMem nestedMutBoolMem .shared (.ref .mut .unit)
(.ptr ⟨some 3, 0, .isize⟩) = .ok () :=
⟨rfl, rfl, rfl⟩
/-- Guard `bytes_v2_ref_valid_nested_inner_mut_checked`: the mutable-memory
check applies to an inner `&mut bool` but not to an inner `&bool`, which may
point into shared memory. -/
theorem refute_bytes_v2_ref_valid_nested_inner_mut_checked :
refValidInMem nestedMutBoolMem .shared (.ref .mut .bool)
(.ptr ⟨some 3, 0, .isize⟩) = .error .undefined ∧
refValidInMem nestedMutBoolMem .shared (.ref .shared .bool)
(.ptr ⟨some 3, 0, .isize⟩) = .ok () :=
⟨rfl, rfl⟩
/-- Allocation 1 is the shared-memory heap buffer of the `Box<bool>` handle in
allocation 5, and allocation 6 holds a reference to that handle. -/
private noncomputable def nestedBoxMem : MemoryState := {
allocations := [
{ allocId := 1, alignLog2 := 0, mutability := .shared,
bytes := [.init 1 none], live := true },
{ allocId := 5, alignLog2 := 3, mutability := .mut,
bytes := List.replicate 8 (.init 0 (some 1)), live := true },
{ allocId := 6, alignLog2 := 3, mutability := .mut,
bytes := List.replicate 8 (.init 0 (some 5)), live := true }]
nextAllocId := 7
}
/-- Guard `bytes_v2_ref_valid_nested_inner_mut_heap`: the inner `&mut Box<bool>`
of a `& &mut Box<bool>` must own a mutable heap buffer, as `&mut Box<bool>`
must, so one whose buffer is in shared memory is invalid, while the inner
`&Box<bool>` of a `&&Box<bool>` may own a shared one. -/
theorem refute_bytes_v2_ref_valid_nested_inner_mut_heap :
refValidInMem nestedBoxMem .shared (.ref .mut (.box .bool))
(.ptr ⟨some 6, 0, .isize⟩) = .error .undefined ∧
refValidInMem nestedBoxMem .shared (.ref .shared (.box .bool))
(.ptr ⟨some 6, 0, .isize⟩) = .ok () ∧
refValidInMem nestedBoxMem .mut (.box .bool) (.ptr ⟨some 5, 0, .isize⟩) =
.error .undefined :=
⟨rfl, rfl, rfl⟩
/-- Reading `*x` of a `& &mut bool` local re-validates the inner `&mut bool`:
it faults when that reference points into shared memory or dangles. -/
theorem refute_step_v2_deref_copy_mut_ref_invalid :
(match readPlaceV2 [.unit, .ref .shared (.ref .mut .bool)]
[.immediate none, .immediate (some (.ptr ⟨some 3, 0, .isize⟩))]
nestedMutBoolMem false ⟨1, [.deref]⟩ with
| .error .undefined => True
| _ => False) ∧
(match readPlaceV2 [.unit, .ref .shared (.ref .mut .bool)]
[.immediate none, .immediate (some (.ptr ⟨some 3, 0, .isize⟩))]
nestedBoolMem false ⟨1, [.deref]⟩ with
| .error .undefined => True
| _ => False) :=
⟨trivial, trivial⟩
/-- Anti-overreach canary: reading `*x` of a `& &mut bool` local copies out
the valid inner `&mut bool`, as a match guard on `&mut self` does. -/
theorem positive_step_v2_deref_copy_mut_ref :
(match readPlaceV2 [.unit, .ref .shared (.ref .mut .bool)]
[.immediate none, .immediate (some (.ptr ⟨some 2, 0, .isize⟩))]
nestedMutBoolMem false ⟨1, [.deref]⟩ with
| .ok (ty, some (.ptr p), _, _) =>
MirTy.beq ty (.ref .mut .bool) &&
(match p.allocId with | some 1 => true | _ => false)
| _ => false) = true :=
rfl
/-- Anti-overreach canary: reading `*x` of a `&&bool` local copies out the
valid inner `&bool`. -/
theorem positive_step_v2_deref_copy_shared_ref :
(match readPlaceV2 [.unit, .ref .shared (.ref .shared .bool)]
[.immediate none, .immediate (some (.ptr ⟨some 2, 0, .isize⟩))]
nestedBoolMem false ⟨1, [.deref]⟩ with
| .ok (ty, some (.ptr p), _, _) =>
MirTy.beq ty (.ref .shared .bool) &&
(match p.allocId with | some 1 => true | _ => false)
| _ => false) = true :=
rfl
/-- Canary: no place dereferences twice, so `&**x` of a `&&bool` local is not
an address Profile v2 computes. -/
theorem canary_step_v2_place_addr_double_deref :
(match placeAddrV2 [.unit, .ref .shared (.ref .shared .bool)]
[.immediate none, .immediate (some (.ptr ⟨some 2, 0, .isize⟩))]
nestedBoolMem true 1 [.deref, .deref] with
| .error _ => True
| .ok _ => False) :=
trivial
/-- `&Box<Box<bool>>` at allocation 1: the outer box's buffer (allocation 2)
holds an inner box pointing at the `bool` in allocation 3. -/
def boxOfBoxMem : MemoryState := {
allocations := [
{ allocId := 1, alignLog2 := 3, mutability := .shared,
bytes := List.replicate 8 (.init 0 (some 2)), live := true },
{ allocId := 2, alignLog2 := 3, mutability := .mut,
bytes := List.replicate 8 (.init 0 (some 3)), live := true },
{ allocId := 3, alignLog2 := 0, mutability := .mut,
bytes := [.init 1 none], live := true }]
nextAllocId := 4
}
/-- `&Box<[Box<bool>]>` at allocation 1 (pointer to allocation 2, length 1),
with allocations 2 and 3 as in `boxOfBoxMem`. -/
def boxedSliceOfBoxMem : MemoryState := {
allocations := [
{ allocId := 1, alignLog2 := 3, mutability := .shared,
bytes := List.replicate 8 (.init 0 (some 2)) ++
(.init 1 none :: List.replicate 7 (.init 0 none)), live := true },
{ allocId := 2, alignLog2 := 3, mutability := .mut,
bytes := List.replicate 8 (.init 0 (some 3)), live := true },
{ allocId := 3, alignLog2 := 0, mutability := .mut,
bytes := [.init 1 none], live := true }]
nextAllocId := 4
}
/-- Guard `alloc_box_clone_data_only`: cloning a `Box<Box<bool>>` would copy
the inner owned handle, so it is `.unsupported` even though the outer box is
valid. -/
theorem refute_alloc_box_clone_data_only :
(match evalBoxClone boxOfBoxMem (.box .bool) ⟨some 1, 0, .isize⟩ with
| .error .unsupported => True
| _ => False) :=
trivial
/-- Guard `alloc_box_clone_slice_data_only`: cloning a `Box<[Box<bool>]>`
would copy owned handles, so it is `.unsupported`. -/
theorem refute_alloc_box_clone_slice_data_only :
(match evalBoxClone boxedSliceOfBoxMem (.slice (.box .bool))
⟨some 1, 0, .isize⟩ with
| .error .unsupported => True
| _ => False) :=
trivial
/-- Profile v2 program dropping `_1`, a struct owning a `Vec<u8>` and a
`Box<u8>`. -/
noncomputable def progDropOwnedStructV2 : Program := {
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 2
bodies := [{
argumentCount := 1
locals := [.unit, .struct_ ⟨9, 32, 3, [0, 24]⟩ [.vec dropU8, .box dropU8]]
basicBlocks := [
{ statements := [], terminator := .drop ⟨1, []⟩ 1 .unreachable },
{ statements := [], terminator := .return_ }]
identity := "guard_mutation::drop_owned_struct"
}]
}
/-- Fault kind, or liveness of allocations `1` and `3`, after one step. -/
noncomputable def dropStepLive13 (r : StepResult State TerminalOut) :
Except FaultKind (Option Bool × Option Bool) :=
match r with
| .step s =>
.ok ((findAllocation 1 s.mem.allocations).map (·.live),
(findAllocation 3 s.mem.allocations).map (·.live))
| .done _ => .ok (none, none)
| .fault k => .error k
/-- Guard `alloc_v2_drop_owned_struct`: `drop(_1)` of an immediate struct
owning a `Vec<u8>` and a `Box<u8>` runs its drop glue, which frees both
buffers. This replaces the refutation of the retired guard that refused
such drops before drop glue was modeled. -/
theorem refute_step_v2_drop_owned_struct_frees_buffers :
dropStepLive13 (evalStepV2 progDropOwnedStructV2
(dropState 0 (.immediate (some (.tuple
[dropVec1, .boxPtr ⟨some 3, 0, .isize⟩ none]))) dropMem)) =
.ok (some false, some false) :=
rfl
/-- Guard `state_v2_vec_counts_as_ref`: a `Vec` local counts as a reference,
so a body holding one may not also hold a raw pointer that could reach the
model-internal handle bytes. -/
theorem refute_state_v2_vec_counts_as_ref :
bodyMixesRefsAndRawPtrsV2
{ argumentCount := 0,
locals := [.unit, .vec (.int .i8 false), .rawPtr .shared (.int .i8 false)],
basicBlocks := [] } = true :=
rfl
/-- Guard `alloc_vec_grow_zst_pin`: growing a ZST `Vec` pins its capacity to
`isize::MAX` and never reaches `2^63`, the `None` niche of `Option<Vec<T>>`;
a minimum capacity of `2^63` faults instead. -/
theorem refute_alloc_vec_grow_zst_pin :
vecGrowCap 0 0 5 = some (Nat.pow 2 63 - 1) ∧
vecGrowCap 0 0 (Nat.pow 2 63) = none :=
⟨rfl, rfl⟩
/-- Guard `alloc_vec_with_capacity_zero_bytes_cap`: `Vec::<()>::with_capacity`
of `2^63` allocates nothing and stores capacity `0`, not the requested value
(which is the `None` niche of `Option<Vec<()>>`). -/
theorem refute_alloc_vec_with_capacity_zero_bytes_cap :
(match evalVecWithCapacityOutcome emptyMemory .unit
(UInt64.ofNat (Nat.pow 2 63)) with
| .ok (.vec _ c _) _ => Nat.beq c.toNat 0
| _ => false) = true :=
rfl
/-! ### Projections of self-recursive structs -/
/-- A padding-free stand-in for `MemoryId`, a `struct Node` with fields
`tag: u64`, `id: u64`, and `parent: Option<Box<Node>>` (layout id `7`, fields
at `[16, 0, 8]`), closed. -/
noncomputable def sRecTy : MirTy :=
.recAdt 7 (.struct_ ⟨7, 24, 3, [16, 0, 8]⟩
[.int .i64 false, .int .i64 false, .option (.box (.recSelf 7))])
/-- Guard `step_v2_rec_proj_ty`: a static field projection of a recursive
struct checks the captured field type against the unfolded definition. -/
theorem refute_step_v2_rec_proj_ty :
stepProjectedTyV2 sRecTy [.field 1 (.int .i8 false)] = none :=
rfl
/-- Guard `step_v2_rec_mem_proj_ty`: a memory field projection of a recursive
struct checks the captured field type. -/
theorem refute_step_v2_rec_mem_proj_ty :
projectMemoryLayoutV2 sRecTy [.field 1 (.int .i8 false)] =
.error .unsupported :=
rfl
/-- Guard `step_v2_rec_imm_proj_ty`: an immediate field projection of a
recursive struct checks the captured field type. -/
theorem refute_step_v2_rec_imm_proj_ty :
projectOneElemV2 sRecTy
(.tuple [.scalar ⟨.i64, false, 1⟩, .scalar ⟨.i64, false, 5⟩,
.optionVal none])
(.field 1 (.int .i8 false)) = .error .unsupported :=
rfl
/-- Anti-overreach canary: the `parent` field of a node has the closed type
`Option<Box<Node>>`, at byte offset 8, and the `id` field is the `u64` at
offset 0. -/
theorem positive_step_v2_rec_projections :
stepProjectedTyV2 sRecTy [.field 2 (.option (.box sRecTy))] =
some (.option (.box sRecTy)) ∧
projectMemoryLayoutV2 sRecTy [.field 2 (.option (.box sRecTy))] =
.ok (.option (.box sRecTy), 8) ∧
projectMemoryLayoutV2 sRecTy [.field 1 (.int .i64 false)] =
.ok (.int .i64 false, 0) :=
⟨rfl, rfl, rfl⟩
/-- A body whose local `&Node` has a binder `7` defining the struct with
layout id `8`, which `recTyWfV2` rejects but `isSupportedV2LocalTy` admits. -/
noncomputable def sRecHeadMismatchBody : Body := {
argumentCount := 1
locals :=
[.unit, .ref .shared (.recAdt 7 (.struct_ ⟨8, 16, 3, [0, 8]⟩
[.int .i64 false, .option (.box (.recSelf 7))]))]
basicBlocks := [{ statements := [], terminator := .return_ }]
identity := "guard_mutation::rec_head_mismatch_callee"
}
/-- Guard `step_v2_call_rec_wf`: an intra-crate callee with an ill-formed
recursive local type is not admitted. -/
theorem refute_step_v2_call_rec_wf :
bodyCallAdmittedV2 sRecHeadMismatchBody = false :=
rfl
/-! ### `Option` payload downcasts in memory (`projectMemoryPlaceV2`) -/
/-- The `u8` type. -/
noncomputable def dcU8 : MirTy := .int .i8 false
/-- The `u32` type. -/
noncomputable def dcU32 : MirTy := .int .i32 false
/-- A `u32` scalar value. -/
noncomputable def dcU32Val (n : Nat) : Val :=
.scalar ⟨.i32, false, BitVec.ofNat 128 n⟩
/-- The live allocation `aid`, aligned to `2^align`, holding `v : ty`. -/
noncomputable def dcAlloc (aid : AllocId) (align : Nat) (ty : MirTy) (v : Val) :
Allocation := {
allocId := aid
alignLog2 := align
mutability := .mut
bytes :=
match encodeValV2 profileV2TargetEndian ty v with
| .ok bs => bs
| .error _ => []
}
/-- Allocation 1 is `Some(Box)` owning allocation 2 (a `u8`), 3 is a `None`
`Option<Box<u8>>`, 4 is `Some(7u32)` and 5 a `None` `Option<u32>` (direct
tag), 6 is `Some(true)` (`Option<bool>`, a niche), and 7 is an empty
`Some(Vec<()>)`. -/
noncomputable def dcMem : MemoryState := {
allocations := [
dcAlloc 1 3 (.option (.box dcU8))
(.optionVal (some (.boxPtr ⟨some 2, 0, .isize⟩ none))),
dcAlloc 2 0 dcU8 (.scalar ⟨.i8, false, BitVec.ofNat 128 9⟩),
dcAlloc 3 3 (.option (.box dcU8)) (.optionVal none),
dcAlloc 4 2 (.option dcU32) (.optionVal (some (dcU32Val 7))),
dcAlloc 5 2 (.option dcU32) (.optionVal none),
dcAlloc 6 0 (.option .bool) (.optionVal (some (.bool true))),
dcAlloc 7 3 (.option (.vec .unit))
(.optionVal (some (.vec ⟨none, 1, .isize⟩ 0 0)))]
nextAllocId := 8
}
/-- Guard `step_v2_downcast_none_undefined`: the `Some` payload of an
in-memory `None` is `.undefined`, for both a niche and a direct tag. -/
theorem refute_step_v2_downcast_none_undefined :
projectMemoryPlaceV2 dcMem 3 0 (.option (.box dcU8)) []
[.downcast 1, .field 0 (.box dcU8)] = .error .undefined ∧
projectMemoryPlaceV2 dcMem 5 0 (.option dcU32) []
[.downcast 1, .field 0 dcU32] = .error .undefined :=
⟨rfl, rfl⟩
/-- Guard `step_v2_downcast_niche_offset`: the payload of a null-pointer
niche `Option<Box<u8>>` is at offset 0. -/
theorem refute_step_v2_downcast_niche_offset :
projectMemoryPlaceV2 dcMem 1 0 (.option (.box dcU8)) []
[.downcast 1, .field 0 (.box dcU8)] = .ok (.box dcU8, 0) :=
rfl
/-- Guard `step_v2_downcast_tag_offset`: the payload of a direct-tag
`Option<u32>` follows its 4-byte tag. -/
theorem refute_step_v2_downcast_tag_offset :
projectMemoryPlaceV2 dcMem 4 0 (.option dcU32) []
[.downcast 1, .field 0 dcU32] = .ok (dcU32, 4) :=
rfl
/-- Guard `step_v2_downcast_bool_unit`: `Option<bool>` keeps its payload in
the niche at offset 0, not after a tag, and is unsupported. -/
theorem refute_step_v2_downcast_bool_unit :
projectMemoryPlaceV2 dcMem 6 0 (.option .bool) []
[.downcast 1, .field 0 .bool] = .error .unsupported :=
rfl
/-- Guard `step_v2_downcast_vec_zst`: in-memory payload projection of
`Option<Vec<()>>` remains conservatively unsupported. -/
theorem refute_step_v2_downcast_vec_zst :
projectMemoryPlaceV2 dcMem 7 0 (.option (.vec .unit)) []
[.downcast 1, .field 0 (.vec .unit)] = .error .unsupported :=
rfl
/-- Guard `step_v2_downcast_field_ty`: the downcast field type must be the
payload type. -/
theorem refute_step_v2_downcast_field_ty :
projectMemoryPlaceV2 dcMem 4 0 (.option dcU32) []
[.downcast 1, .field 0 dcU8] = .error .unsupported :=
rfl
/-- A struct whose only field, at offset 0, is an `Option<u32>`, so that
`dcMem`'s allocations 4 and 5 also hold one. -/
noncomputable def dcOptStruct : MirTy :=
.struct_ ⟨77, 8, 2, [0]⟩ [.option dcU32]
/-- Guards `step_v2_read_indirect_downcast` and
`step_v2_read_indirect_field_downcast`: a promoted (`.indirect`) local reads
an `Option` payload through `as Some`, directly or below a struct field, and
the payload of an in-memory `None` is `.undefined`. -/
theorem refute_step_v2_read_indirect_downcast :
readPlaceV2 [.unit, .option dcU32] [.immediate none, .indirect ⟨4, 0⟩]
dcMem false
{ localId := 1, projection := [.downcast 1, .field 0 dcU32] } =
.ok (dcU32, some (dcU32Val 7), [.immediate none, .indirect ⟨4, 0⟩],
dcMem) ∧
readPlaceV2 [.unit, .option dcU32] [.immediate none, .indirect ⟨5, 0⟩]
dcMem false
{ localId := 1, projection := [.downcast 1, .field 0 dcU32] } =
.error .undefined ∧
readPlaceV2 [.unit, dcOptStruct] [.immediate none, .indirect ⟨4, 0⟩]
dcMem false { localId := 1, projection :=
[.field 0 (.option dcU32), .downcast 1, .field 0 dcU32] } =
.ok (dcU32, some (dcU32Val 7), [.immediate none, .indirect ⟨4, 0⟩],
dcMem) :=
⟨rfl, rfl, rfl⟩
/-- The locals of a body whose `_1 : &Option<Box<u8>>` points at allocation
`aid`. -/
noncomputable def dcRefLocals (aid : AllocId) : List LocalSlot :=
[.immediate (some .unit), .immediate (some (.ptr ⟨some aid, 0, .isize⟩))]
/-- The local types `[(), &Option<Box<u8>>]`. -/
noncomputable def dcRefTys : List MirTy :=
[.unit, .ref .shared (.option (.box dcU8))]
/-- Guard `step_v2_downcast_ref_place`: `&((*r) as Some).0` borrows the
payload of the `Option` that `r` points at, and borrowing the payload of a
`None` is `.undefined`. -/
theorem refute_step_v2_downcast_ref_place :
evalRefRvalueV2 dcRefTys (dcRefLocals 1) dcMem (.ref .shared (.box dcU8))
.shared ⟨1, [.deref, .downcast 1, .field 0 (.box dcU8)]⟩ =
.ok (.ptr ⟨some 1, 0, .isize⟩, dcRefLocals 1, dcMem) ∧
evalRefRvalueV2 dcRefTys (dcRefLocals 3) dcMem (.ref .shared (.box dcU8))
.shared ⟨1, [.deref, .downcast 1, .field 0 (.box dcU8)]⟩ =
.error .undefined :=
⟨rfl, rfl⟩
/-- Guard `step_v2_downcast_read_place`: reading `((*r) as Some).0` reads the
payload of the `Option` that `r` points at. -/
theorem refute_step_v2_downcast_read_place :
readDerefProjectedV2 [] dcMem true (.option dcU32)
(.immediate (some (.ptr ⟨some 4, 0, .isize⟩)))
[.downcast 1, .field 0 dcU32] =
.ok (dcU32, some (dcU32Val 7), [], dcMem) :=
rfl
/-- The locals of a body whose `_1 : Option<u32>` lives in allocation 4. -/
noncomputable def dcIndLocals : List LocalSlot :=
[.immediate (some .unit), .indirect ⟨4, 0⟩]
/-- Guard `step_v2_downcast_promoted_place`: `&(x as Some).0` of an
in-memory `Option<u32>` local borrows its payload after the tag. -/
theorem refute_step_v2_downcast_promoted_place :
evalRefRvalueV2 [.unit, .option dcU32] dcIndLocals dcMem (.ref .shared dcU32)
.shared ⟨1, [.downcast 1, .field 0 dcU32]⟩ =
.ok (.ptr ⟨some 4, 4, .isize⟩, dcIndLocals, dcMem) :=
rfl
/-- The local types `[isize, &Option<u32>]`. -/
noncomputable def dcDiscrTys : List MirTy :=
[.int .isize true, .ref .shared (.option dcU32)]
/-- The locals of a body whose `_1 : &Option<u32>` points at allocation
`aid`. -/
noncomputable def dcDiscrLocals (aid : AllocId) : List LocalSlot :=
[.immediate none, .immediate (some (.ptr ⟨some aid, 0, .isize⟩))]
/-- Guard `step_v2_discriminant_deref_option`: `discriminant(*r)` of an
`Option` behind a reference is 1 for `Some` and 0 for `None`. -/
theorem refute_step_v2_discriminant_deref_option :
evalRvalueV2 dcDiscrTys (dcDiscrLocals 4) dcMem (.int .isize true)
(.discriminant ⟨1, [.deref]⟩) =
.ok (.scalar ⟨.isize, true, BitVec.ofNat 128 1⟩, dcDiscrLocals 4, dcMem) ∧
evalRvalueV2 dcDiscrTys (dcDiscrLocals 5) dcMem (.int .isize true)
(.discriminant ⟨1, [.deref]⟩) =
.ok (.scalar ⟨.isize, true, BitVec.ofNat 128 0⟩, dcDiscrLocals 5, dcMem) :=
⟨rfl, rfl⟩
/-- Guard `step_v2_discriminant_local_option_ty`: the destination of an
unprojected immediate `Option` discriminant must be `isize`. -/
theorem refute_step_v2_discriminant_local_option_ty :
evalRvalueV2 [.option dcU32]
[.immediate (some (.optionVal (some (dcU32Val 7))))] dcMem
(.int .i8 true) (.discriminant ⟨0, []⟩) = .error .unsupported :=
rfl
/-- Guard `step_v2_discriminant_indirect_option_ty`: the destination of an
unprojected in-memory `Option` discriminant must be `isize`. -/
theorem refute_step_v2_discriminant_indirect_option_ty :
evalRvalueV2 [.option dcU32] [.indirect ⟨4, 0⟩] dcMem (.int .i8 true)
(.discriminant ⟨0, []⟩) = .error .unsupported :=
rfl
/-- Guard `step_v2_move_option_downcast_indirect`: moving out of `(x as Some).0`
when `x` lives in memory (`.indirect`) faults with `.unsupported` instead of
leaving a live copy behind in memory. -/
theorem refute_step_v2_move_option_downcast_indirect :
evalOperandToSlotV2 [.option (.box dcU8)] [.indirect ⟨1, 0⟩] dcMem
(.move ⟨0, [.downcast 1, .field 0 (.box dcU8)]⟩) =
.error .unsupported :=
rfl
/-! ### Aggregates of self-recursive structs -/
/-- The unfolded `parent` field type of `sRecTy`. -/
noncomputable def sRecParentTy : MirTy := .option (.box sRecTy)
/-- Locals `_0 : Node`, `_1 _2 : u64`, `_3 : Option<Box<Node>>` (`None`). -/
noncomputable def sRecAggTys : List MirTy :=
[sRecTy, .int .i64 false, .int .i64 false, sRecParentTy]
/-- The values of `sRecAggTys`, with `_0` uninitialized. -/
noncomputable def sRecAggLocals : List LocalSlot :=
[.immediate none, .immediate (some (.scalar ⟨.i64, false, 1⟩)),
.immediate (some (.scalar ⟨.i64, false, 5⟩)),
.immediate (some (.optionVal none))]
/-- The operands `copy _1, copy _2, copy _3`. -/
noncomputable def sRecAggOps : List Operand :=
[.copy ⟨1, []⟩, .copy ⟨2, []⟩, .copy ⟨3, []⟩]
/-- Guard `step_v2_rec_aggregate`: a struct aggregate of a recursive struct
builds its value from the fields of the one-step unfolding. -/
theorem refute_step_v2_rec_aggregate :
evalRvalueV2 sRecAggTys sRecAggLocals emptyMemory sRecTy
(.aggregateStruct sRecTy sRecAggOps) =
.ok (.tuple [.scalar ⟨.i64, false, 1⟩, .scalar ⟨.i64, false, 5⟩,
.optionVal none], sRecAggLocals, emptyMemory) :=
rfl
/-- Guard `step_v2_rec_aggregate_field_ty`: the operands must have the
unfolded field types. -/
theorem refute_step_v2_rec_aggregate_field_ty :
evalRvalueV2 sRecAggTys sRecAggLocals emptyMemory sRecTy
(.aggregateStruct sRecTy [.copy ⟨1, []⟩, .copy ⟨3, []⟩, .copy ⟨2, []⟩]) =
.error .unsupported :=
rfl
/-- Guard `step_v2_rec_aggregate_dst`: the destination must have the
recursive struct type. -/
theorem refute_step_v2_rec_aggregate_dst :
evalRvalueV2 sRecAggTys sRecAggLocals emptyMemory (.int .i64 false)
(.aggregateStruct sRecTy sRecAggOps) = .error .unsupported :=
rfl
/-- Body mutating field `1` (`id: u64`) of an immediate `sRecTy` local `_1`. -/
noncomputable def sRecFieldAssignBody : Body := {
identity := "rec_field_assign"
argumentCount := 1
locals := [sRecTy, sRecTy]
basicBlocks := [{
statements := [
.assign ⟨1, [.field 1 (.int .i64 false)]⟩
(.use (.constant ⟨.int .i64 false, .scalar (BitVec.ofNat 128 42)⟩))
]
terminator := .return_
}]
}
/-- Initial frame holding `n = (1, 5, None)` in `_1`. -/
noncomputable def sRecFieldAssignFrame : FrameState := {
defId := 0
blockIdx := 0
stmtIdx := 0
locals := [
.immediate none,
.immediate (some (.tuple [
.scalar ⟨.i64, false, 1⟩,
.scalar ⟨.i64, false, 5⟩,
.optionVal none
]))
]
}
/-- Guard `step_v2_rec_update_proj`: `validatePlaceProjV2` and
`updateValAtProjV2` unfold `.recAdt` so field assignment on an immediate
self-recursive struct local updates the field in place, while a mismatched
field type faults `.unsupported`. -/
theorem refute_step_v2_rec_update_proj :
evalStatementV2 sRecFieldAssignBody sRecFieldAssignFrame emptyMemory ⟨[]⟩
(.assign ⟨1, [.field 1 (.int .i64 false)]⟩
(.use (.constant ⟨.int .i64 false, .scalar (BitVec.ofNat 128 42)⟩))) =
.step {
frames := [{
sRecFieldAssignFrame with
stmtIdx := 1
locals := [
.immediate none,
.immediate (some (.tuple [
.scalar ⟨.i64, false, 1⟩,
.scalar ⟨.i64, false, 42⟩,
.optionVal none
]))
]
}]
callerMem := ⟨[]⟩
mem := emptyMemory
} ∧
validatePlaceProjV2 sRecTy [.field 1 (.int .i32 false)] =
.error .unsupported :=
⟨rfl, rfl⟩
/-- Guard `step_v2_rec_norm_imm_proj_overlap`: `normalizeImmProjPathV2` unfolds
`.recAdt` so an in-place self-copy of a `.memoryCopy` field (`_1.2 = copy _1.2`,
where field `2` has type `Option<Box<Node>>`) faults `.undefined`, whereas
copying from a disjoint local `_2` succeeds. -/
theorem refute_step_v2_rec_norm_imm_proj_overlap :
checkAssignCopyHazardV2 [sRecTy, sRecTy, sRecParentTy]
[.immediate none,
.immediate (some (.tuple [
.scalar ⟨.i64, false, 1⟩,
.scalar ⟨.i64, false, 5⟩,
.optionVal none])),
.immediate (some (.optionVal none))]
emptyMemory
(.localProj 1 sRecTy [.field 2 sRecParentTy])
sRecParentTy
(.use (.copy ⟨1, [.field 2 sRecParentTy]⟩)) = .error .undefined ∧
checkAssignCopyHazardV2 [sRecTy, sRecTy, sRecParentTy]
[.immediate none,
.immediate (some (.tuple [
.scalar ⟨.i64, false, 1⟩,
.scalar ⟨.i64, false, 5⟩,
.optionVal none])),
.immediate (some (.optionVal none))]
emptyMemory
(.localProj 1 sRecTy [.field 2 sRecParentTy])
sRecParentTy
(.use (.move ⟨2, []⟩)) = .ok () :=
⟨rfl, rfl⟩
/-- Guard `step_v2_assign_hazard_option_some`: `checkAssignCopyHazardV2` on
`.aggregateOption` permits `None::<Vec<u8>>` and disjoint `Some(move _1)`, while
rejecting self-overlapping `_0 = Some(move ((_0 as Some).0))` on an immediate
`Option<Vec<u8>>` as `.undefined`. -/
theorem refute_step_v2_assign_hazard_option_some :
let vecU8 : MirTy := .vec (.int .i8 false)
let optVecU8 : MirTy := .option vecU8
let bodyLocs : List MirTy := [optVecU8, vecU8]
let locs : List LocalSlot := [
.immediate (some (.optionVal (some (.vec ⟨none, 1, .isize⟩ 0 0)))),
.immediate (some (.vec ⟨none, 1, .isize⟩ 0 0))
]
checkAssignCopyHazardV2 bodyLocs locs emptyMemory (.local 0) optVecU8
(.aggregateOption 0 vecU8 none) = .ok () ∧
checkAssignCopyHazardV2 bodyLocs locs emptyMemory (.local 0) optVecU8
(.aggregateOption 1 vecU8 (some (.move ⟨1, []⟩))) = .ok () ∧
checkAssignCopyHazardV2 bodyLocs locs emptyMemory (.local 0) optVecU8
(.aggregateOption 1 vecU8
(some (.move ⟨0, [.downcast 1, .field 0 vecU8]⟩))) =
.error .undefined :=
⟨rfl, rfl, rfl⟩
/-- Guard `core_contracts_mem_replace_readonly_zst`: `execMemReplace` on a
zero-sized `()` pointee in a live `.shared` `.rodata` allocation succeeds
(`lay.size == 0`) rather than faulting on `.shared`. -/
theorem refute_core_contracts_mem_replace_readonly_zst :
let m : MemoryState := {
allocations := [{
allocId := 1, alignLog2 := 0, mutability := .shared,
bytes := [], live := true
}]
nextAllocId := 2
}
execMemReplace m .unit ⟨some 1, 0, .isize⟩ .unit = .ok (.unit, m) :=
rfl
/-- Regression canary for `writePlaceV2` / `writePlaceDestV2` `.derefProjected`
and `.derefSlice` arms on read-only allocations: storing a non-zero-sized `u8`
value through a projected struct field (`(*p).1`), projected array element
(`(*p)[1]`), slice element (`(*s)[1]`), or slice-element field (`(*s)[0].1`)
into a live `.shared` allocation resolves to `.derefProjected` / `.derefSlice`
and faults with `.error .undefined` (`WriteToReadOnly` via `storeIndirectV2`
→ `writeBytes`), whereas the identical store into a `.mut` allocation updates
byte `1` and succeeds. -/
theorem canary_step_v2_write_deref_projected_and_slice_readonly_ub :
let u8Ty : MirTy := .int .i8 false
let u8Val : Val := .scalar ⟨.i8, false, BitVec.ofNat 128 7⟩
let pairStructTy : MirTy := .struct_ ⟨101, 2, 0, [0, 1]⟩ [u8Ty, u8Ty]
let arrTy : MirTy := .array u8Ty 2
let p1 : PtrVal := ⟨some 1, 0, .isize⟩
let sharedMem : MemoryState := {
allocations := [{
allocId := 1, alignLog2 := 0, mutability := .shared,
bytes := [.init 0 none, .init 0 none], live := true
}]
nextAllocId := 2
}
let mutMem : MemoryState := {
allocations := [{
allocId := 1, alignLog2 := 0, mutability := .mut,
bytes := [.init 0 none, .init 0 none], live := true
}]
nextAllocId := 2
}
let mutMemUpdated : MemoryState := {
allocations := [{
allocId := 1, alignLog2 := 0, mutability := .mut,
bytes := [.init 0 none, .init 7 none], live := true
}]
nextAllocId := 2
}
let ptrLocs : List LocalSlot := [.immediate (some .unit), .immediate (some (.ptr p1))]
let slice2Locs : List LocalSlot :=
[.immediate (some .unit), .immediate (some (.slicePtr p1 2))]
let slice1Locs : List LocalSlot :=
[.immediate (some .unit), .immediate (some (.slicePtr p1 1))]
-- 1. `.derefProjected` struct field store into `.shared` faults
-- `.undefined` (and succeeds on `.mut`).
resolvePlaceDestV2 [.unit, .ref .mut pairStructTy] ptrLocs sharedMem
{ localId := 1, projection := [.deref, .field 1 u8Ty] } u8Ty =
.ok (.derefProjected pairStructTy ⟨2, 0⟩ u8Ty 1 p1) ∧
writePlaceV2 [.unit, .ref .mut pairStructTy] ptrLocs sharedMem
{ localId := 1, projection := [.deref, .field 1 u8Ty] } u8Ty u8Val =
.error .undefined ∧
writePlaceV2 [.unit, .ref .mut pairStructTy] ptrLocs mutMem
{ localId := 1, projection := [.deref, .field 1 u8Ty] } u8Ty u8Val =
.ok (ptrLocs, mutMemUpdated) ∧
-- 2. `.derefProjected` array-element store into `.shared` faults
-- `.undefined` (and succeeds on `.mut`).
resolvePlaceDestV2 [.unit, .ref .mut arrTy] ptrLocs sharedMem
{ localId := 1, projection := [.deref, .constantIndex 1 2 false] } u8Ty =
.ok (.derefProjected arrTy ⟨2, 0⟩ u8Ty 1 p1) ∧
writePlaceV2 [.unit, .ref .mut arrTy] ptrLocs sharedMem
{ localId := 1, projection := [.deref, .constantIndex 1 2 false] } u8Ty u8Val =
.error .undefined ∧
writePlaceV2 [.unit, .ref .mut arrTy] ptrLocs mutMem
{ localId := 1, projection := [.deref, .constantIndex 1 2 false] } u8Ty u8Val =
.ok (ptrLocs, mutMemUpdated) ∧
-- 3. `.derefSlice` slice-element store into `.shared` faults `.undefined`
-- (and succeeds on `.mut`).
resolvePlaceDestV2 [.unit, .ref .mut (.slice u8Ty)] slice2Locs sharedMem
{ localId := 1, projection := [.deref, .constantIndex 1 2 false] } u8Ty =
.ok (.derefSlice u8Ty 1 1) ∧
writePlaceV2 [.unit, .ref .mut (.slice u8Ty)] slice2Locs sharedMem
{ localId := 1, projection := [.deref, .constantIndex 1 2 false] } u8Ty u8Val =
.error .undefined ∧
writePlaceV2 [.unit, .ref .mut (.slice u8Ty)] slice2Locs mutMem
{ localId := 1, projection := [.deref, .constantIndex 1 2 false] } u8Ty u8Val =
.ok (slice2Locs, mutMemUpdated) ∧
-- 4. `.derefSlice` sub-field store into `.shared` faults `.undefined`
-- (and succeeds on `.mut`).
resolvePlaceDestV2 [.unit, .ref .mut (.slice pairStructTy)] slice1Locs sharedMem
{ localId := 1, projection := [.deref, .constantIndex 0 1 false, .field 1 u8Ty] } u8Ty =
.ok (.derefSlice u8Ty 1 1) ∧
writePlaceV2 [.unit, .ref .mut (.slice pairStructTy)] slice1Locs sharedMem
{ localId := 1, projection := [.deref, .constantIndex 0 1 false, .field 1 u8Ty] }
u8Ty u8Val =
.error .undefined ∧
writePlaceV2 [.unit, .ref .mut (.slice pairStructTy)] slice1Locs mutMem
{ localId := 1, projection := [.deref, .constantIndex 0 1 false, .field 1 u8Ty] }
u8Ty u8Val =
.ok (slice1Locs, mutMemUpdated) :=
⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl⟩
/-- Anti-overreach positive canary for `writePlaceV2` / `writePlaceDestV2`
`.derefProjected` and `.derefSlice` arms on read-only allocations: storing a
zero-sized `()` value through a projected ZST field of a non-zero struct, a ZST
field of a ZST struct, a ZST array element, a ZST slice element, or a ZST field
of a non-zero slice element into a live `.shared` allocation succeeds without
modifying memory. -/
theorem positive_step_v2_write_deref_projected_and_slice_readonly_zst :
let u8Ty : MirTy := .int .i8 false
let mixedStructTy : MirTy := .struct_ ⟨102, 1, 0, [0, 1]⟩ [u8Ty, .unit]
let zstStructTy : MirTy := .struct_ ⟨103, 0, 0, [0]⟩ [.unit]
let zstArrTy : MirTy := .array .unit 2
let p1 : PtrVal := ⟨some 1, 0, .isize⟩
let shared1Mem : MemoryState := {
allocations := [{
allocId := 1, alignLog2 := 0, mutability := .shared,
bytes := [.init 0 none], live := true
}]
nextAllocId := 2
}
let shared0Mem : MemoryState := {
allocations := [{
allocId := 1, alignLog2 := 0, mutability := .shared,
bytes := [], live := true
}]
nextAllocId := 2
}
let ptrLocs : List LocalSlot := [.immediate (some .unit), .immediate (some (.ptr p1))]
let slice2Locs : List LocalSlot :=
[.immediate (some .unit), .immediate (some (.slicePtr p1 2))]
let slice1Locs : List LocalSlot :=
[.immediate (some .unit), .immediate (some (.slicePtr p1 1))]
-- 1. `.derefProjected` ZST field of a non-zero struct in `.shared`
-- succeeds.
resolvePlaceDestV2 [.unit, .ref .mut mixedStructTy] ptrLocs shared1Mem
{ localId := 1, projection := [.deref, .field 1 .unit] } .unit =
.ok (.derefProjected mixedStructTy ⟨1, 0⟩ .unit 1 p1) ∧
writePlaceV2 [.unit, .ref .mut mixedStructTy] ptrLocs shared1Mem
{ localId := 1, projection := [.deref, .field 1 .unit] } .unit .unit =
.ok (ptrLocs, shared1Mem) ∧
-- 2. `.derefProjected` ZST field of a ZST struct in 0-byte `.shared`
-- succeeds.
resolvePlaceDestV2 [.unit, .ref .mut zstStructTy] ptrLocs shared0Mem
{ localId := 1, projection := [.deref, .field 0 .unit] } .unit =
.ok (.derefProjected zstStructTy ⟨0, 0⟩ .unit 0 p1) ∧
writePlaceV2 [.unit, .ref .mut zstStructTy] ptrLocs shared0Mem
{ localId := 1, projection := [.deref, .field 0 .unit] } .unit .unit =
.ok (ptrLocs, shared0Mem) ∧
-- 3. `.derefProjected` ZST array element in 0-byte `.shared` succeeds.
resolvePlaceDestV2 [.unit, .ref .mut zstArrTy] ptrLocs shared0Mem
{ localId := 1, projection := [.deref, .constantIndex 1 2 false] } .unit =
.ok (.derefProjected zstArrTy ⟨0, 0⟩ .unit 0 p1) ∧
writePlaceV2 [.unit, .ref .mut zstArrTy] ptrLocs shared0Mem
{ localId := 1, projection := [.deref, .constantIndex 1 2 false] } .unit .unit =
.ok (ptrLocs, shared0Mem) ∧
-- 4. `.derefSlice` ZST slice element in 0-byte `.shared` succeeds.
resolvePlaceDestV2 [.unit, .ref .mut (.slice .unit)] slice2Locs shared0Mem
{ localId := 1, projection := [.deref, .constantIndex 1 2 false] } .unit =
.ok (.derefSlice .unit 1 0) ∧
writePlaceV2 [.unit, .ref .mut (.slice .unit)] slice2Locs shared0Mem
{ localId := 1, projection := [.deref, .constantIndex 1 2 false] } .unit .unit =
.ok (slice2Locs, shared0Mem) ∧
-- 5. `.derefSlice` ZST field of a non-zero slice element in `.shared`
-- succeeds.
resolvePlaceDestV2 [.unit, .ref .mut (.slice mixedStructTy)] slice1Locs shared1Mem
{ localId := 1, projection := [.deref, .constantIndex 0 1 false, .field 1 .unit] } .unit =
.ok (.derefSlice .unit 1 1) ∧
writePlaceV2 [.unit, .ref .mut (.slice mixedStructTy)] slice1Locs shared1Mem
{ localId := 1, projection := [.deref, .constantIndex 0 1 false, .field 1 .unit] }
.unit .unit =
.ok (slice1Locs, shared1Mem) :=
⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl⟩
/-! ## `srcPlaceCopySpanV2` parity with `readPlaceV2` / `placeAddrV2` -/
private def scsPairTy : MirTy :=
.struct_ ⟨941, 8, 2, [0, 4]⟩ [.int .i32 false, .int .i32 false]
private def scsPairMem : MemoryState :=
{ allocations :=
[{ allocId := 1, bytes := List.replicate 16 (.init 0 none),
alignLog2 := 2, live := true, mutability := .mut }],
nextAllocId := 2 }
private def scsIdxVal (n : Nat) : Val :=
.scalar ⟨.isize, false, BitVec.ofNat 128 n⟩
private def scsVecTy : MirTy := .vec (.int .i8 false)
private def scsOptVecTy : MirTy := .option scsVecTy
private def scsOptVecMem : MemoryState :=
{ allocations :=
[{ allocId := 1, bytes := List.replicate 48 (.init 0 none),
alignLog2 := 3, live := true, mutability := .mut }],
nextAllocId := 2 }
/-- Guard `step_v2_src_span_slice_ptr`: `srcPlaceCopySpanV2` resolves a
runtime-indexed `.slicePtr` element (`(*_1)[_2]`) via `resolveIndexProjsV2`
and `sliceElemAddrV2`, permitting disjoint copies of a `MemoryCopy` struct
while rejecting self-overlapping copies as `.undefined`. -/
theorem refute_step_v2_src_span_slice_ptr :
let bodyLocs : List MirTy :=
[scsPairTy, .ref .mut (.slice scsPairTy), .int .isize false]
let locs : List LocalSlot :=
[ .immediate none,
.immediate (some (.slicePtr ⟨some 1, 0, .isize⟩ 2)),
.immediate (some (scsIdxVal 1)) ]
let src : Place := ⟨1, [.deref, .index 2]⟩
srcPlaceCopySpanV2 bodyLocs locs scsPairMem src =
some (.memRange 1 8 8) ∧
checkAssignCopyHazardV2 bodyLocs locs scsPairMem (.local 0) scsPairTy
(.use (.copy src)) = .ok () ∧
checkAssignCopyHazardV2 bodyLocs locs scsPairMem
(.derefSlice scsPairTy 1 0) scsPairTy (.use (.copy src)) = .ok () ∧
checkAssignCopyHazardV2 bodyLocs locs scsPairMem
(.derefSlice scsPairTy 1 8) scsPairTy (.use (.copy src)) =
.error .undefined ∧
-- OOB and dead index fail closed to `none` / `.error .unsupported`.
srcPlaceCopySpanV2 bodyLocs
[.immediate none, .immediate (some (.slicePtr ⟨some 1, 0, .isize⟩ 2)),
.immediate (some (scsIdxVal 2))] scsPairMem src = none ∧
srcPlaceCopySpanV2 bodyLocs
[.immediate none, .immediate (some (.slicePtr ⟨some 1, 0, .isize⟩ 2)),
.dead] scsPairMem src = none :=
⟨rfl, rfl, rfl, rfl, rfl, rfl⟩
/-- Guard `step_v2_agg_index_clobber`: `checkAggregateCopyHazardLoopV2` fails
closed with `.unsupported` when an earlier Aggregate field write overwrites an
indirect `.index` local read by a later operand (whereas disjoint writes
succeed). -/
theorem refute_step_v2_agg_index_clobber :
let arrTy : MirTy := .array scsPairTy 2
let pairStructTy : MirTy :=
.struct_ ⟨942, 16, 3, [0, 8]⟩ [.int .isize false, scsPairTy]
let bodyLocs : List MirTy := [pairStructTy, arrTy, .int .isize false]
let mem : MemoryState := {
allocations := [
{ allocId := 1, bytes := List.replicate 16 (.init 0 none),
alignLog2 := 2, live := true, mutability := .mut },
{ allocId := 2, bytes := List.replicate 16 (.init 0 none),
alignLog2 := 3, live := true, mutability := .mut },
{ allocId := 3, bytes := List.replicate 16 (.init 0 none),
alignLog2 := 3, live := true, mutability := .mut }
],
nextAllocId := 4
}
let locs : List LocalSlot :=
[.immediate none, .indirect ⟨1, 0⟩, .indirect ⟨3, 0⟩]
let rv : Rvalue := .aggregateStruct pairStructTy [
.constant ⟨.int .isize false, .scalar 5⟩,
.copy ⟨1, [.index 2]⟩
]
-- Writing field 0 into alloc 3 overwrites local 2 (`_i`) before operand 1.
checkAssignCopyHazardV2 bodyLocs locs mem
(.deref pairStructTy ⟨16, 3⟩ ⟨some 3, 0, .isize⟩) pairStructTy rv =
.error .unsupported ∧
-- Dead index local also fails closed once earlier fields are written.
checkAssignCopyHazardV2 bodyLocs
[.immediate none, .indirect ⟨1, 0⟩, .dead] mem
(.deref pairStructTy ⟨16, 3⟩ ⟨some 2, 0, .isize⟩) pairStructTy rv =
.error .unsupported ∧
-- Disjoint aggregate destination succeeds.
checkAssignCopyHazardV2 bodyLocs locs mem
(.deref pairStructTy ⟨16, 3⟩ ⟨some 2, 0, .isize⟩) pairStructTy rv =
.ok () :=
⟨rfl, rfl, rfl⟩
/-- Guard `step_v2_src_span_deref_index`: `srcPlaceCopySpanV2` resolves a
runtime `.index` projection below a sized `.deref` (`(*_1)[_2]`). -/
theorem refute_step_v2_src_span_deref_index :
let arrTy : MirTy := .array scsPairTy 2
let bodyLocs : List MirTy := [scsPairTy, .ref .mut arrTy, .int .isize false]
let locs : List LocalSlot :=
[ .immediate none,
.immediate (some (.ptr ⟨some 1, 0, .isize⟩)),
.immediate (some (scsIdxVal 1)) ]
let src : Place := ⟨1, [.deref, .index 2]⟩
srcPlaceCopySpanV2 bodyLocs locs scsPairMem src =
some (.memRange 1 8 8) ∧
checkAssignCopyHazardV2 bodyLocs locs scsPairMem (.local 0) scsPairTy
(.use (.copy src)) = .ok () ∧
checkAssignCopyHazardV2 bodyLocs locs scsPairMem
(.derefProjected arrTy ⟨16, 2⟩ scsPairTy 8 ⟨some 1, 0, .isize⟩)
scsPairTy (.use (.copy src)) = .error .undefined :=
⟨rfl, rfl, rfl⟩
/-- Guard `step_v2_src_span_deref_downcast`: `srcPlaceCopySpanV2` resolves a
`.downcast` projection below a sized `.deref` via `projectMemoryPlaceV2`. -/
theorem refute_step_v2_src_span_deref_downcast :
let bodyLocs : List MirTy := [scsVecTy, .ref .mut scsOptVecTy]
let locs : List LocalSlot :=
[.immediate none, .immediate (some (.ptr ⟨some 1, 0, .isize⟩))]
let src : Place := ⟨1, [.deref, .downcast 1, .field 0 scsVecTy]⟩
srcPlaceCopySpanV2 bodyLocs locs scsOptVecMem src =
some (.memRange 1 0 24) ∧
checkAssignCopyHazardV2 bodyLocs locs scsOptVecMem (.local 0) scsVecTy
(.use (.copy src)) = .ok () ∧
checkAssignCopyHazardV2 bodyLocs locs scsOptVecMem
(.derefProjected scsOptVecTy ⟨24, 3⟩ scsVecTy 0 ⟨some 1, 0, .isize⟩)
scsVecTy (.use (.copy src)) = .error .undefined :=
⟨rfl, rfl, rfl⟩
/-- Guard `step_v2_src_span_local_index`: `srcPlaceCopySpanV2` resolves a
runtime `.index` projection on both immediate and indirect local arrays. -/
theorem refute_step_v2_src_span_local_index :
let arrTy : MirTy := .array scsPairTy 2
let bodyLocs : List MirTy := [scsPairTy, arrTy, .int .isize false]
let immLocs : List LocalSlot :=
[.immediate none, .immediate none, .immediate (some (scsIdxVal 1))]
let indLocs : List LocalSlot :=
[.immediate none, .indirect ⟨1, 0⟩, .immediate (some (scsIdxVal 1))]
let src : Place := ⟨1, [.index 2]⟩
srcPlaceCopySpanV2 bodyLocs immLocs emptyMemory src =
some (.immPath 1 [.index 1]) ∧
checkAssignCopyHazardV2 bodyLocs immLocs emptyMemory (.local 0) scsPairTy
(.use (.copy src)) = .ok () ∧
checkAssignCopyHazardV2 bodyLocs immLocs emptyMemory
(.localProj 1 arrTy [.constantIndex 1 2 false]) scsPairTy
(.use (.copy src)) = .error .undefined ∧
srcPlaceCopySpanV2 bodyLocs indLocs scsPairMem src =
some (.memRange 1 8 8) ∧
checkAssignCopyHazardV2 bodyLocs indLocs scsPairMem
(.indirectProj scsPairTy ⟨1, 0⟩ 8) scsPairTy (.use (.copy src)) =
.error .undefined :=
⟨rfl, rfl, rfl, rfl, rfl⟩
/-! ### Payload enum downcasts, discriminants, and aggregates -/
/-- A `u16` value. -/
noncomputable def seU16 (n : Nat) : Val := .scalar ⟨.i16, false, BitVec.ofNat 128 n⟩
/-- A `u32` value. -/
noncomputable def seU32 (n : Nat) : Val := .scalar ⟨.i32, false, BitVec.ofNat 128 n⟩
/-- `enum E { A(u32), B(u16), C(u32) }` with a direct `u16` tag at 0. -/
noncomputable def seETy : MirTy :=
.adtEnum ⟨1, 8, 2, .isize, true, [0, 1, 2], 0, .i16, false, 0, 2, .direct⟩
[.struct_ ⟨11, 8, 2, [4]⟩ [.int .i32 false],
.struct_ ⟨12, 8, 2, [2]⟩ [.int .i16 false],
.struct_ ⟨13, 8, 2, [4]⟩ [.int .i32 false]]
/-- Guard `step_v2_adt_downcast_variant`: the field of a variant other than
the one an immediate value holds is `.undefined`. -/
theorem refute_step_v2_adt_downcast_variant :
projectValFieldV2 seETy (.adtVal 1 (.tuple [seU16 4]))
[.downcast 0, .field 0 (.int .i32 false)] = .error .undefined ∧
projectValFieldV2 seETy (.adtVal 1 (.tuple [seU16 4]))
[.downcast 1, .field 0 (.int .i16 false)] =
.ok (.int .i16 false, seU16 4) :=
⟨rfl, rfl⟩
/-- Allocation 1 holds `E::B(4)`, aligned to 4. -/
noncomputable def seMem : MemoryState := {
allocations := [dcAlloc 1 2 seETy (.adtVal 1 (.tuple [seU16 4]))]
nextAllocId := 2
}
/-- Guard `step_v2_adt_mem_downcast_variant`: in memory too, the field of a
variant the enum does not hold is `.undefined`; the field of the variant it
holds is at its offset in the enum. -/
theorem refute_step_v2_adt_mem_downcast_variant :
projectMemoryPlaceV2 seMem 1 0 seETy []
[.downcast 0, .field 0 (.int .i32 false)] = .error .undefined ∧
projectMemoryPlaceV2 seMem 1 0 seETy []
[.downcast 1, .field 0 (.int .i16 false)] = .ok (.int .i16 false, 2) :=
⟨rfl, rfl⟩
/-- The local types `[isize, E, &E]`. -/
noncomputable def seTys : List MirTy :=
[.int .isize true, seETy, .ref .shared seETy]
/-- Locals whose `_1 : E` holds `v` and whose `_2 : &E` points at
allocation 1. -/
noncomputable def seLocals (v : Option Val) : List LocalSlot :=
[.immediate none, .immediate v, .immediate (some (.ptr ⟨some 1, 0, .isize⟩))]
/-- Guards `step_v2_adt_discriminant_uninit` and
`step_v2_adt_discriminant_ty`: `discriminant(x)` of a payload enum is the
held variant's discriminant at its discriminant type, an uninitialized
value is `.undefined`, and any other destination type is unsupported. -/
theorem refute_step_v2_adt_discriminant :
evalRvalueV2 seTys (seLocals (some (.adtVal 2 (.tuple [seU32 9])))) seMem
(.int .isize true) (.discriminant ⟨1, []⟩) =
.ok (.scalar ⟨.isize, true, BitVec.ofNat 128 2⟩,
seLocals (some (.adtVal 2 (.tuple [seU32 9]))), seMem) ∧
evalRvalueV2 seTys (seLocals none) seMem (.int .isize true)
(.discriminant ⟨1, []⟩) = .error .undefined ∧
evalRvalueV2 seTys (seLocals (some (.adtVal 2 (.tuple [seU32 9])))) seMem
(.int .i16 false) (.discriminant ⟨1, []⟩) = .error .unsupported :=
⟨rfl, rfl, rfl⟩
/-- Guard `step_v2_adt_discriminant_deref`: `discriminant(*r)` reads the
enum `r` points at. -/
theorem refute_step_v2_adt_discriminant_deref :
evalRvalueV2 seTys (seLocals none) seMem (.int .isize true)
(.discriminant ⟨2, [.deref]⟩) =
.ok (.scalar ⟨.isize, true, BitVec.ofNat 128 1⟩, seLocals none, seMem) :=
rfl
/-- A `u16` constant operand. -/
noncomputable def seU16Op (n : Nat) : Operand :=
.constant ⟨.int .i16 false, .scalar (BitVec.ofNat 128 n)⟩
/-- Guards `step_v2_adt_aggregate_fields` and `step_v2_adt_aggregate_dst`:
`E::B(x)` needs a `u16` field and an `E` destination. -/
theorem refute_step_v2_adt_aggregate :
evalRvalueV2 seTys (seLocals none) seMem seETy
(.aggregateAdtEnum seETy 1 [seU16Op 4]) =
.ok (.adtVal 1 (.tuple [seU16 4]), seLocals none, seMem) ∧
evalRvalueV2 seTys (seLocals none) seMem seETy
(.aggregateAdtEnum seETy 0 [seU16Op 4]) = .error .unsupported ∧
evalRvalueV2 seTys (seLocals none) seMem (.int .i16 false)
(.aggregateAdtEnum seETy 1 [seU16Op 4]) = .error .unsupported :=
⟨rfl, rfl, rfl⟩
/-- The local types `[isize, E, &mut E]` and `[isize, E, *mut E]`. -/
noncomputable def seMutTys (raw : Bool) : List MirTy :=
[.int .isize true, seETy, if raw then .rawPtr .mut seETy else .ref .mut seETy]
/-- Locals whose `_1 : E` holds `E::B(4)` and whose `_2` points at
allocation 1. -/
noncomputable def seMutLocals : List LocalSlot :=
[.immediate none, .immediate (some (.adtVal 1 (.tuple [seU16 4]))),
.immediate (some (.ptr ⟨some 1, 0, .isize⟩))]
/-- The place `(*_2 as B).0`. -/
noncomputable def seMutPlace : Place :=
⟨2, [.deref, .downcast 1, .field 0 (.int .i16 false)]⟩
/-- Guards `step_v2_adt_mut_downcast_raw` and `step_v2_adt_mut_downcast_kind`:
`&raw mut` of a payload enum variant's field is refused, while `&mut` of a
field of the variant a `.direct` enum holds, outside its tag, and `&` of the
same field are the address of the field, and `&mut` of a field of a variant
it does not hold is `.undefined`. -/
theorem refute_step_v2_adt_mut_downcast :
evalRefRvalueV2 (seMutTys false) seMutLocals seMem
(.ref .mut (.int .i16 false)) .mut seMutPlace =
.ok (.ptr ⟨some 1, 2, .isize⟩, seMutLocals, seMem) ∧
evalRefRvalueV2 (seMutTys false) seMutLocals seMem
(.ref .mut (.int .i32 false)) .mut
⟨2, [.deref, .downcast 0, .field 0 (.int .i32 false)]⟩ =
.error .undefined ∧
evalAddressOfRvalueV2 (seMutTys true) seMutLocals seMem
(.rawPtr .mut (.int .i16 false)) .mut seMutPlace = .error .unsupported ∧
evalRefRvalueV2 (seMutTys false) seMutLocals seMem
(.ref .shared (.int .i16 false)) .shared seMutPlace =
.ok (.ptr ⟨some 1, 2, .isize⟩, seMutLocals, seMem) :=
⟨rfl, rfl, rfl, rfl⟩
/-- `Option<E>` as a payload enum: `None` is the niche `3` of `E`'s tag. -/
noncomputable def seOptTy : MirTy :=
.adtEnum ⟨2, 8, 2, .isize, true, [0, 1], 0, .i16, false, 0, 3,
.niche 1 0 0 3⟩
[.struct_ ⟨21, 8, 2, []⟩ [], .struct_ ⟨22, 8, 2, [0]⟩ [seETy]]
/-- Allocation 1 holds `Some(E::B(4))` and allocation 2 holds `None`. -/
noncomputable def seOptMem : MemoryState := {
allocations := [
dcAlloc 1 2 seOptTy (.adtVal 1 (.tuple [.adtVal 1 (.tuple [seU16 4])])),
dcAlloc 2 2 seOptTy (.adtVal 0 (.tuple []))]
nextAllocId := 3
}
/-- The local types `[isize, Option<E>, &mut Option<E>]`. -/
noncomputable def seOptMutTys : List MirTy :=
[.int .isize true, seOptTy, .ref .mut seOptTy]
/-- Locals whose `_2 : &mut Option<E>` points at allocation 1. -/
noncomputable def seOptMutLocals : List LocalSlot :=
[.immediate none, .immediate none,
.immediate (some (.ptr ⟨some 1, 0, .isize⟩))]
/-- Guard `step_v2_adt_mut_downcast_ref`: `&mut` of the payload of a niche
enum, which overlaps the niche, is refused even when the enum holds that
variant. -/
theorem refute_step_v2_adt_mut_downcast_ref :
evalRefRvalueV2 seOptMutTys seOptMutLocals seOptMem (.ref .mut seETy) .mut
⟨2, [.deref, .downcast 1, .field 0 seETy]⟩ = .error .unsupported :=
rfl
/-- `enum N { A(u16), B(u32) }` with a `u16` niche at 0 in `A`'s field, so `B`
is tagged and its field, at 4, lies outside the tag. -/
noncomputable def seNicheTy : MirTy :=
.adtEnum ⟨3, 8, 2, .isize, true, [0, 1], 0, .i16, false, 0, 3,
.niche 0 1 1 3⟩
[.struct_ ⟨31, 8, 2, [0]⟩ [.int .i16 false],
.struct_ ⟨32, 8, 2, [4]⟩ [.int .i32 false]]
/-- A `.direct` enum whose one variant's `u32` field overlaps its `u16` tag,
which `adtVariantWfV2` rejects. -/
noncomputable def seBadTy : MirTy :=
.adtEnum ⟨4, 8, 2, .isize, true, [0], 0, .i16, false, 0, 0, .direct⟩
[.struct_ ⟨41, 8, 2, [0]⟩ [.int .i32 false]]
/-- A `.direct` enum whose one variant holds an `N` at 8, outside its tag. -/
noncomputable def seOuterTy : MirTy :=
.adtEnum ⟨5, 16, 2, .isize, true, [0], 0, .i16, false, 0, 0, .direct⟩
[.struct_ ⟨51, 16, 2, [8]⟩ [seNicheTy]]
/-- Guards `step_v2_ref_mut_downcast_direct_only`,
`step_v2_ref_mut_downcast_off_tag`, `step_v2_ref_mut_downcast_field_ty`,
`step_v2_ref_mut_downcast_kind`, and `step_v2_ref_mut_downcast_nested`: a
mutable reference through a downcast may change the variant unless every
downcast is of a `.direct` enum and is followed by a field of the recorded
type outside the tag. So a niche enum's tagged field, a field overlapping a
tag, a field at the wrong type, a bare downcast, and a niche enum inside a
`.direct` enum's field are all flagged, while `E`'s `B.0` is not. -/
theorem refute_step_v2_ref_mut_downcast :
projsDowncastMutUnsafeV2 (.ref .mut seNicheTy)
[.deref, .downcast 1, .field 0 (.int .i32 false)] = true ∧
projsDowncastMutUnsafeV2 (.ref .mut seBadTy)
[.deref, .downcast 0, .field 0 (.int .i32 false)] = true ∧
projsDowncastMutUnsafeV2 (.ref .mut seETy)
[.deref, .downcast 1, .field 0 (.int .i32 false)] = true ∧
projsDowncastMutUnsafeV2 (.ref .mut seETy) [.deref, .downcast 1] = true ∧
projsDowncastMutUnsafeV2 (.ref .mut seOuterTy)
[.deref, .downcast 0, .field 0 seNicheTy, .downcast 1,
.field 0 (.int .i32 false)] = true ∧
projsDowncastMutUnsafeV2 (.ref .mut seETy)
[.deref, .downcast 1, .field 0 (.int .i16 false)] = false ∧
projsDowncastMutUnsafeV2 (.ref .mut seOuterTy)
[.deref, .downcast 0, .field 0 seNicheTy] = false :=
⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl⟩
/-- Guard `core_adt_option_shape`: `Option::is_none` on an `Option` that is a
payload enum reads its variant, and the payload enum must have the shape of
`Option<inner>`. -/
theorem refute_core_adt_option_shape :
execCoreContractOp seOptMem (.optionIsNone seETy)
[(.ref .shared seOptTy, .ptr ⟨some 1, 0, .isize⟩)] .bool =
.ok (.bool false, seOptMem) ∧
execCoreContractOp seOptMem (.optionIsNone seETy)
[(.ref .shared seOptTy, .ptr ⟨some 2, 0, .isize⟩)] .bool =
.ok (.bool true, seOptMem) ∧
execCoreContractOp seOptMem (.optionIsSome seETy)
[(.ref .shared seOptTy, .ptr ⟨some 2, 0, .isize⟩)] .bool =
.ok (.bool false, seOptMem) ∧
execCoreContractOp seOptMem (.optionIsNone (.int .i32 false))
[(.ref .shared seOptTy, .ptr ⟨some 1, 0, .isize⟩)] .bool =
.error .unsupported :=
⟨rfl, rfl, rfl, rfl⟩
/-- `Result<Vec<u8>, u8>` with `rustc`'s layout: `Ok` is untagged, and `Err`
is the niche value `2^63` of the `Vec` capacity at offset 0. -/
noncomputable def drResVecTy : MirTy :=
.adtEnum ⟨31, 24, 3, .isize, true, [0, 1], 0, .i64, false, 0,
9223372036854775808, .niche 0 1 1 9223372036854775808⟩
[.struct_ ⟨32, 24, 3, [0]⟩ [.vec dropU8],
.struct_ ⟨33, 24, 3, [8]⟩ [dropU8]]
/-- `Result<u8, Vec<u8>>`: `Err` is untagged and `Ok` is the niche. -/
noncomputable def drResU8Ty : MirTy :=
.adtEnum ⟨34, 24, 3, .isize, true, [0, 1], 0, .i64, false, 0,
9223372036854775808, .niche 1 0 0 9223372036854775808⟩
[.struct_ ⟨35, 24, 3, [8]⟩ [dropU8],
.struct_ ⟨36, 24, 3, [0]⟩ [.vec dropU8]]
/-- Guard `alloc_adt_drop_active_variant`: dropping `Ok(v)` of a
`Result<Vec<u8>, u8>` drops `v` and frees its buffer. -/
theorem refute_alloc_adt_drop_active_variant :
dropLive (dropGlueV2 dropMem drResVecTy (.adtVal 0 (.tuple [dropVec1])))
1 2 = .ok (some false, some true) := rfl
/-- Guard `alloc_adt_drop_nth_variant`: the glue of variant 1 is the glue of
variant 1's payload, so dropping `Err(v)` of a `Result<u8, Vec<u8>>` frees
`v`'s buffer rather than running the (empty) glue of `Ok`'s `u8`. -/
theorem refute_alloc_adt_drop_nth_variant :
dropLive (dropGlueV2 dropMem drResU8Ty (.adtVal 1 (.tuple [dropVec1])))
1 2 = .ok (some false, some true) := rfl
/-- Anti-overreach canaries: dropping `Err(u8)` of a `Result<Vec<u8>, u8>`
touches no buffer, a variant index past the variants faults, and a payload
enum under a recursive binder drops its active variant through the fuelled
glue. -/
theorem canary_alloc_adt_drop_glue :
dropLive (dropGlueV2 dropMem drResVecTy
(.adtVal 1 (.tuple [.scalar ⟨.i8, false, 0⟩]))) 1 2 =
.ok (some true, some true) ∧
dropLive (dropGlueV2 dropMem drResVecTy (.adtVal 2 (.tuple [dropVec1])))
1 2 = .error .unsupported ∧
dropLive (dropGlueV2 dropMem (.recAdt 31 drResVecTy)
(.adtVal 0 (.tuple [dropVec1]))) 1 2 = .ok (some false, some true) :=
⟨rfl, rfl, rfl⟩
/-! ### Recursive payload enums -/
/-- A `u8` value. -/
noncomputable def srU8 (n : Nat) : Val := .scalar ⟨.i8, false, BitVec.ofNat 128 n⟩
/-- The definition of `enum T { Leaf(u8), Node(Box<T>) }` with layout id 5, a
direct `u8` tag at 0, and back edge `.recSelf i`. -/
noncomputable def srDefn (i : Nat) : MirTy :=
.adtEnum ⟨5, 16, 3, .isize, true, [0, 1], 0, .i8, false, 0, 1, .direct⟩
[.struct_ ⟨51, 16, 3, [1]⟩ [.int .i8 false],
.struct_ ⟨52, 16, 3, [8]⟩ [.box (.recSelf i)]]
/-- The closed recursive payload enum `T`. -/
noncomputable def srTy : MirTy := .recAdt 5 (srDefn 5)
/-- Guard `enum_rec_adt_head_enum_id`: a recursive payload enum binder must
carry its enum's layout id, so `T` is well formed and a binder `6` over the
enum with layout id `5` is not. -/
theorem refute_enum_rec_adt_head_enum_id :
recTyWfV2 none srTy = true ∧
recTyWfV2 none (.recAdt 6 (srDefn 6)) = false :=
⟨rfl, rfl⟩
/-- Guard `enum_adt_variants_rec_unfold`: the payload of `T::Node` is a `Box`
of the closed `T`, not of the open back edge. -/
theorem refute_enum_adt_variants_rec_unfold :
adtVariantPayloadV2 srTy 1 = some (.struct_ ⟨52, 16, 3, [8]⟩ [.box srTy]) :=
rfl
/-- Allocation 1 holds `T::Leaf(7)`, aligned to 8. -/
noncomputable def srMem : MemoryState := {
allocations := [dcAlloc 1 3 srTy (.adtVal 0 (.tuple [srU8 7]))]
nextAllocId := 2
}
/-- Guards `step_v2_adt_rec_downcast` and `step_v2_adt_rec_mem_downcast`: the
field of the variant a recursive payload enum holds is readable, immediately
and in memory (at offset 1). -/
theorem refute_step_v2_adt_rec_downcast :
projectValFieldV2 srTy (.adtVal 0 (.tuple [srU8 7]))
[.downcast 0, .field 0 (.int .i8 false)] = .ok (.int .i8 false, srU8 7) ∧
projectMemoryPlaceV2 srMem 1 0 srTy []
[.downcast 0, .field 0 (.int .i8 false)] = .ok (.int .i8 false, 1) :=
⟨rfl, rfl⟩
/-- The local types `[isize, T, &T]`. -/
noncomputable def srTys : List MirTy := [.int .isize true, srTy, .ref .shared srTy]
/-- Locals whose `_1 : T` holds `v` and whose `_2 : &T` points at
allocation 1. -/
noncomputable def srLocals (v : Option Val) : List LocalSlot :=
[.immediate none, .immediate v, .immediate (some (.ptr ⟨some 1, 0, .isize⟩))]
/-- Locals whose `_1 : T` lives in allocation 1. -/
noncomputable def srIndLocals : List LocalSlot :=
[.immediate none, .indirect ⟨1, 0⟩, .immediate (some (.ptr ⟨some 1, 0, .isize⟩))]
/-- Guards `step_v2_adt_rec_discriminant`,
`step_v2_adt_rec_discriminant_deref`, and
`step_v2_adt_rec_discriminant_indirect`: `discriminant(x)` of an immediate
or in-memory local and `discriminant(*r)` of a recursive payload enum are
the held variant's discriminant. -/
theorem refute_step_v2_adt_rec_discriminant :
evalRvalueV2 srTys (srLocals (some (.adtVal 0 (.tuple [srU8 7])))) srMem
(.int .isize true) (.discriminant ⟨1, []⟩) =
.ok (.scalar ⟨.isize, true, BitVec.ofNat 128 0⟩,
srLocals (some (.adtVal 0 (.tuple [srU8 7]))), srMem) ∧
evalRvalueV2 srTys (srLocals none) srMem (.int .isize true)
(.discriminant ⟨2, [.deref]⟩) =
.ok (.scalar ⟨.isize, true, BitVec.ofNat 128 0⟩, srLocals none, srMem) ∧
evalRvalueV2 srTys srIndLocals srMem (.int .isize true)
(.discriminant ⟨1, []⟩) =
.ok (.scalar ⟨.isize, true, BitVec.ofNat 128 0⟩, srIndLocals, srMem) :=
⟨rfl, rfl, rfl⟩
/-- A `u8` constant operand. -/
noncomputable def srU8Op (n : Nat) : Operand :=
.constant ⟨.int .i8 false, .scalar (BitVec.ofNat 128 n)⟩
/-- Guard `step_v2_adt_rec_aggregate`: `T::Leaf(7)` builds variant 0 of the
recursive payload enum. -/
theorem refute_step_v2_adt_rec_aggregate :
evalRvalueV2 srTys (srLocals none) srMem srTy
(.aggregateAdtEnum srTy 0 [srU8Op 7]) =
.ok (.adtVal 0 (.tuple [srU8 7]), srLocals none, srMem) :=
rfl
/-- Non-heap single-field vs two-field payload enum for downcast-move guards:
variant 0 has one `u8` field; variant 1 has two `u8` fields. -/
noncomputable def dmPlainEnumTy : MirTy :=
.adtEnum ⟨91, 4, 0, .isize, true, [0, 1], 0, .i8, false, 0, 1, .direct⟩
[.struct_ ⟨92, 4, 0, [1]⟩ [.int .i8 false],
.struct_ ⟨93, 4, 0, [1, 2]⟩ [.int .i8 false, .int .i8 false]]
/-- Heap-owning single-field payload enum for downcast-move and rodata-const
guards. -/
noncomputable def dmHeapEnumTy : MirTy :=
.adtEnum ⟨94, 16, 3, .isize, true, [0, 1], 0, .i8, false, 0, 1, .direct⟩
[.struct_ ⟨95, 16, 3, [1]⟩ [.int .i8 false],
.struct_ ⟨96, 16, 3, [8]⟩ [.box (.int .i8 false)]]
/-- Zero-sized single-variant payload enum `enum Zst { A(()) }` for
`ConstLit.zeroSized` guards. -/
noncomputable def zstAdtEnumTy : MirTy :=
.adtEnum ⟨97, 0, 0, .isize, true, [0], 0, .i8, false, 0, 0, .single⟩
[.struct_ ⟨98, 0, 0, [0]⟩ [.unit]]
/-- Guards `step_v2_adt_move_downcast_no_heap` and
`step_v2_adt_move_downcast_single_field_only`: moving out of an immediate
payload enum local succeeds for a single-field variant of a non-heap enum, but
fails closed with `.unsupported` when the enum owns a heap handle or the
variant has more than one field. -/
theorem refute_step_v2_adt_move_downcast_guards :
(readPlaceV2 [.unit, dmPlainEnumTy]
[.immediate none, .immediate (some (.adtVal 0 (.tuple [srU8 7])))]
MemoryState.empty true
⟨1, [.downcast 0, .field 0 (.int .i8 false)]⟩).map (·.2.1) =
.ok (some (srU8 7)) ∧
readPlaceV2 [.unit, dmHeapEnumTy]
[.immediate none, .immediate (some (.adtVal 0 (.tuple [srU8 7])))]
MemoryState.empty true
⟨1, [.downcast 0, .field 0 (.int .i8 false)]⟩ =
.error .unsupported ∧
readPlaceV2 [.unit, dmPlainEnumTy]
[.immediate none,
.immediate (some (.adtVal 1 (.tuple [srU8 7, srU8 9])))]
MemoryState.empty true
⟨1, [.downcast 1, .field 0 (.int .i8 false)]⟩ =
.error .unsupported :=
⟨rfl, rfl, rfl⟩
/-- Guard `step_v2_zero_sized_adt_enum`: `evalOperandToSlotV2` decodes
non-heap `.adtEnum` `.rodataBytes` and `.zeroSized` constants, while rejecting
an active heap-owning variant of a `.adtEnum` `.rodataBytes` constant as
`.unsupported`. -/
theorem refute_step_v2_adt_enum_consts :
(evalOperandToSlotV2 [.unit] [.immediate none] MemoryState.empty
(.constant ⟨dmPlainEnumTy,
.rodataBytes [.init 0, .init 7, .uninit, .uninit]⟩)).map (·.2.1) =
.ok (some (.adtVal 0 (.tuple [srU8 7]))) ∧
evalOperandToSlotV2 [.unit] [.immediate none] MemoryState.empty
(.constant ⟨dmHeapEnumTy,
.rodataBytes ([.init 1] ++ List.replicate 15 (.init 0))⟩) =
.error .unsupported ∧
(evalOperandToSlotV2 [.unit] [.immediate none] MemoryState.empty
(.constant ⟨zstAdtEnumTy, .zeroSized⟩)).map (·.2.1) =
.ok (some (.adtVal 0 (.tuple [.unit]))) :=
⟨rfl, rfl, rfl⟩
/-- Guard `enum_rec_keys_plain_adt_enum`: a plain payload enum reusing the
layout id of a recursive binder makes the binders incoherent. -/
theorem refute_enum_rec_keys_plain_adt_enum :
recTysCoherentV2 [srTy] = true ∧
recTysCoherentV2 [srTy,
.adtEnum ⟨5, 16, 3, .isize, true, [0, 1], 0, .i8, false, 0, 1, .direct⟩
[.struct_ ⟨51, 16, 3, [1]⟩ [.int .i8 false],
.struct_ ⟨52, 16, 3, [8]⟩ [.box (.int .i8 false)]]] = false :=
⟨rfl, rfl⟩
/-- `reprU8EnumTy` with both variants at discriminant `10`, which
`enumAdmitted` rejects. -/
noncomputable def dupDiscrEnumTy : EnumTy :=
{ reprU8EnumTy with discriminants := [10, 10] }
/-- Guards `step_v2_fieldless_enum_aggregate_{fields,dst,admitted,variant}`:
variant `1` of a fieldless enum is `Val.enumVal ety 1`, while an operand,
another destination type, an unadmitted enum, or an out-of-range variant is
unsupported. -/
theorem refute_step_v2_fieldless_enum_aggregate :
evalRvalueV2 [] [] MemoryState.empty (.enum reprU8EnumTy)
(.aggregateAdtEnum (.enum reprU8EnumTy) 1 []) =
.ok (.enumVal reprU8EnumTy 1, [], MemoryState.empty) ∧
evalRvalueV2 [] [] MemoryState.empty (.enum reprU8EnumTy)
(.aggregateAdtEnum (.enum reprU8EnumTy) 1 [seU16Op 4]) =
.error .unsupported ∧
evalRvalueV2 [] [] MemoryState.empty (.int .i8 false)
(.aggregateAdtEnum (.enum reprU8EnumTy) 1 []) = .error .unsupported ∧
evalRvalueV2 [] [] MemoryState.empty (.enum dupDiscrEnumTy)
(.aggregateAdtEnum (.enum dupDiscrEnumTy) 1 []) = .error .unsupported ∧
evalRvalueV2 [] [] MemoryState.empty (.enum reprU8EnumTy)
(.aggregateAdtEnum (.enum reprU8EnumTy) 2 []) = .error .unsupported :=
⟨rfl, rfl, rfl, rfl, rfl⟩
/-- `struct { a: u8, b: u8 }`. -/
noncomputable def pmPairTy : MirTy :=
.struct_ ⟨60, 2, 0, [0, 1]⟩ [.int .i8 false, .int .i8 false]
/-- `struct { a: u8, b: () }`, with `b` at offset 1. -/
noncomputable def pmZstTy : MirTy :=
.struct_ ⟨61, 1, 0, [0, 1]⟩ [.int .i8 false, .unit]
/-- A body with `_0 : ()` and `_1 : *const pt`. -/
noncomputable def pmBody (pt : MirTy) : Body := {
argumentCount := 1
locals := [.unit, .rawPtr .shared pt]
basicBlocks := [{ statements := [], terminator := .return_ }]
}
/-- A frame whose `_1` is `slot`. -/
noncomputable def pmFrame (slot : LocalSlot) : FrameState :=
{ defId := 0, blockIdx := 0, stmtIdx := 0,
locals := [.immediate (some .unit), slot] }
/-- Allocation 1 holds two initialized bytes and is live iff `live`. -/
noncomputable def pmMem (live : Bool) : MemoryState := {
allocations := [{
allocId := 1
alignLog2 := 0
mutability := .mut
bytes := [.init 1 none, .init 2 none]
live := live
}]
nextAllocId := 2
}
/-- `_1` points at allocation 1. -/
noncomputable def pmPtr : LocalSlot :=
.immediate (some (.ptr ⟨some 1, 0, .isize⟩))
/-- Guard `step_v2_place_mention_reads_place`: `PlaceMention((*_1).1)` faults
with `.undefined` when `_1` points into a dead allocation or is itself dead,
instead of being skipped. -/
theorem refute_step_v2_place_mention_dangling :
evalStatementV2 (pmBody pmPairTy) (pmFrame pmPtr) (pmMem false) {}
(.placeMention ⟨1, [.deref, .field 1 (.int .i8 false)]⟩) =
.fault .undefined ∧
evalStatementV2 (pmBody pmPairTy) (pmFrame .dead) (pmMem true) {}
(.placeMention ⟨1, [.deref, .field 1 (.int .i8 false)]⟩) =
.fault .undefined :=
⟨rfl, rfl⟩
/-- Guard `step_v2_place_mention_zst_deref`: `PlaceMention((*_1).1)` of a
zero-sized field behind a deref on a live in-bounds allocation is refused with
`.unsupported` by `placeMentionZstDerefV2`, while the same mention on a dead
allocation faults with `.undefined` in `readDerefProjectedV2`. -/
theorem refute_step_v2_place_mention_zst :
evalStatementV2 (pmBody pmZstTy) (pmFrame pmPtr) (pmMem true) {}
(.placeMention ⟨1, [.deref, .field 1 .unit]⟩) = .fault .unsupported ∧
evalStatementV2 (pmBody pmZstTy) (pmFrame pmPtr) (pmMem false) {}
(.placeMention ⟨1, [.deref, .field 1 .unit]⟩) = .fault .undefined :=
⟨rfl, rfl⟩
/-- Guard `step_v2_place_mention_zst_only`: `PlaceMention((*_1).1)` of a
`u8` field of a live allocation steps past the statement and leaves the
locals and memory unchanged. -/
theorem refute_step_v2_place_mention_valid :
evalStatementV2 (pmBody pmPairTy) (pmFrame pmPtr) (pmMem true) {}
(.placeMention ⟨1, [.deref, .field 1 (.int .i8 false)]⟩) =
.step {
frames := [{ pmFrame pmPtr with stmtIdx := 1 }]
callerMem := {}
mem := pmMem true
} :=
rfl
/-- `[u32; 2]` (8 bytes, `isMemoryCopyReprTyV2 = true`). -/
noncomputable def seArr2Ty : MirTy := .array (.int .i32 false) 2
/-- `enum EA { Pair([u32; 2]) }` with a single variant holding `[u32; 2]`. -/
noncomputable def seArrEnumTy : MirTy :=
.adtEnum ⟨98, 8, 2, .isize, true, [0], 0, .i8, false, 0, 0, .single⟩
[.struct_ ⟨99, 8, 2, [0]⟩ [seArr2Ty]]
/-- Guard `step_v2_assign_adt_enum_payload_span`: `normalizeImmProjPathV2`
resolves validated `.adtEnum` and recursive `.recAdt` payload-enum downcasts to
the whole-enum span so disjoint `MemoryCopy` field copies succeed while
same-field overlaps fault `.undefined` and bare downcasts stay `.unsupported`.
-/
theorem refute_step_v2_assign_adt_enum_payload_span :
let boxSr : MirTy := .box srTy
let pairTy : MirTy := .tuple [seArrEnumTy, seArr2Ty]
checkAssignCopyHazardV2 [seArr2Ty, seArrEnumTy]
[.immediate none, .immediate none] emptyMemory
(.local 0) seArr2Ty
(.use (.copy ⟨1, [.downcast 0, .field 0 seArr2Ty]⟩)) = .ok () ∧
normalizeImmProjPathV2 srTy [.downcast 1, .field 0 boxSr] = some [] ∧
checkAssignCopyHazardV2 [pairTy, seArr2Ty]
[.immediate none, .immediate none] emptyMemory
(.local 0) pairTy
(.aggregateTuple [
.copy ⟨0, [.field 0 seArrEnumTy, .downcast 0, .field 0 seArr2Ty]⟩,
.copy ⟨1, []⟩]) = .error .undefined ∧
checkAssignCopyHazardV2 [seArr2Ty, seArrEnumTy]
[.immediate none, .immediate none] emptyMemory
(.local 0) seArr2Ty
(.use (.copy ⟨1, [.downcast 0]⟩)) = .error .unsupported :=
⟨rfl, rfl, rfl, rfl⟩
/-- Guard `step_v2_assign_adt_enum_self_overlap_unsupported`: an
`.aggregateAdtEnum` assignment whose operand overlaps the destination enum fails
closed as `.unsupported` (avoiding false `.undefined` across variants or
fields), while a disjoint source succeeds. -/
theorem refute_step_v2_assign_adt_enum_self_overlap_unsupported :
checkAssignCopyHazardV2 [seArrEnumTy]
[.immediate none] emptyMemory
(.local 0) seArrEnumTy
(.aggregateAdtEnum seArrEnumTy 0
[.copy ⟨0, [.downcast 0, .field 0 seArr2Ty]⟩]) =
.error .unsupported ∧
checkAssignCopyHazardV2 [seArrEnumTy, seArrEnumTy]
[.immediate none, .immediate none] emptyMemory
(.local 0) seArrEnumTy
(.aggregateAdtEnum seArrEnumTy 0
[.copy ⟨1, [.downcast 0, .field 0 seArr2Ty]⟩]) = .ok () :=
⟨rfl, rfl⟩
/-- A `u8` value. -/
noncomputable def tryU8 (n : Nat) : Val := .scalar ⟨.i8, false, BitVec.ofNat 128 n⟩
/-- `Result<u8, err>`, `[Ok(u8), Err(err)]`. The contracts below read only
the variant shapes, not the layout. -/
noncomputable def tryResTy (ok err : MirTy) : MirTy :=
.adtEnum ⟨70, 2, 0, .isize, true, [0, 1], 0, .i8, false, 0, 1, .direct⟩
[.struct_ ⟨71, 2, 0, [1]⟩ [ok], .struct_ ⟨72, 2, 0, [1]⟩ [err]]
/-- `?`'s residual `Result<Infallible, err>`, `Variants::Single { index: 1 }`.
-/
noncomputable def tryResidualTy (err : MirTy) : MirTy :=
.adtEnum ⟨73, 1, 0, .isize, true, [0, 1], 0, .i8, false, 1, 1, .single⟩
[.struct_ ⟨74, 0, 0, [0]⟩ [.never], .struct_ ⟨75, 1, 0, [0]⟩ [err]]
/-- `ControlFlow<b, cont>`, `[Continue(cont), Break(b)]`. -/
noncomputable def tryCfTy (cont b : MirTy) : MirTy :=
.adtEnum ⟨76, 2, 0, .isize, true, [0, 1], 0, .i8, false, 0, 1, .direct⟩
[.struct_ ⟨77, 2, 0, [1]⟩ [cont], .struct_ ⟨78, 2, 0, [1]⟩ [b]]
/-- `Option<inner>` as a payload enum, `[None, Some(inner)]`. -/
noncomputable def tryOptTy (inner : MirTy) : MirTy :=
.adtEnum ⟨79, 2, 0, .isize, true, [0, 1], 0, .i8, false, 0, 1, .direct⟩
[.struct_ ⟨80, 2, 0, []⟩ [], .struct_ ⟨81, 2, 0, [1]⟩ [inner]]
/-- `?`'s residual `Option<Infallible>`, `Variants::Single { index: 0 }`. -/
noncomputable def tryOptResidualTy : MirTy :=
.adtEnum ⟨82, 0, 0, .isize, true, [0, 1], 0, .i8, false, 0, 0, .single⟩
[.struct_ ⟨83, 0, 0, []⟩ [], .struct_ ⟨84, 0, 0, [0]⟩ [.never]]
/-- `u8`, `u16`, and the `ControlFlow` that `Result<u8, u8>::branch` returns.
-/
noncomputable def tryU8Ty : MirTy := .int .i8 false
noncomputable def tryU16Ty : MirTy := .int .i16 false
noncomputable def tryResCfTy : MirTy :=
tryCfTy tryU8Ty (tryResidualTy tryU8Ty)
/-- Guards `core_try_branch_result_*`, `core_adt_result_shape_{ok,err}`, and
`core_adt_control_flow_{continue,break}`: `Result<u8, u8>::branch` maps
`Ok(4)` to `Continue(4)` and `Err(5)` to `Break(Err(5))`, while another
source `Result` or a destination other than
`ControlFlow<Result<Infallible, u8>, u8>` is unsupported. -/
theorem refute_core_try_branch_result :
execCoreContractOp MemoryState.empty (.tryBranchResult tryU8Ty tryU8Ty)
[(tryResTy tryU8Ty tryU8Ty, .adtVal 0 (.tuple [tryU8 4]))]
tryResCfTy =
.ok (.adtVal 0 (.tuple [tryU8 4]), MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.tryBranchResult tryU8Ty tryU8Ty)
[(tryResTy tryU8Ty tryU8Ty, .adtVal 1 (.tuple [tryU8 5]))]
tryResCfTy =
.ok (.adtVal 1 (.tuple [.adtVal 1 (.tuple [tryU8 5])]),
MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.tryBranchResult tryU8Ty tryU8Ty)
[(tryResTy tryU16Ty tryU8Ty, .adtVal 1 (.tuple [tryU8 5]))]
tryResCfTy = .error .unsupported ∧
execCoreContractOp MemoryState.empty (.tryBranchResult tryU8Ty tryU8Ty)
[(tryResTy tryU8Ty tryU16Ty, .adtVal 1 (.tuple [tryU8 5]))]
tryResCfTy = .error .unsupported ∧
execCoreContractOp MemoryState.empty (.tryBranchResult tryU8Ty tryU8Ty)
[(tryResTy tryU8Ty tryU8Ty, .adtVal 1 (.tuple [tryU8 5]))]
(tryCfTy tryU8Ty (tryResidualTy tryU16Ty)) = .error .unsupported ∧
execCoreContractOp MemoryState.empty (.tryBranchResult tryU8Ty tryU8Ty)
[(tryResTy tryU8Ty tryU8Ty, .adtVal 1 (.tuple [tryU8 5]))]
(tryCfTy tryU8Ty (tryResTy tryU8Ty tryU8Ty)) = .error .unsupported ∧
execCoreContractOp MemoryState.empty (.tryBranchResult tryU8Ty tryU8Ty)
[(tryResTy tryU8Ty tryU8Ty, .adtVal 1 (.tuple [tryU8 5]))]
(tryCfTy tryU16Ty (tryResidualTy tryU8Ty)) = .error .unsupported :=
⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl⟩
/-- Guards `core_try_branch_option_*` and `core_adt_option_residual`:
`Option<u8>::branch`, on an `Option` or a payload-enum `Option`, maps
`Some(4)` to `Continue(4)` and `None` to `Break(None)`, while another source
`Option` or a destination other than `ControlFlow<Option<Infallible>, u8>` is
unsupported. -/
theorem refute_core_try_branch_option :
execCoreContractOp MemoryState.empty (.tryBranchOption tryU8Ty)
[(.option tryU8Ty, .optionVal (some (tryU8 4)))]
(tryCfTy tryU8Ty tryOptResidualTy) =
.ok (.adtVal 0 (.tuple [tryU8 4]), MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.tryBranchOption tryU8Ty)
[(.option tryU8Ty, .optionVal none)]
(tryCfTy tryU8Ty tryOptResidualTy) =
.ok (.adtVal 1 (.tuple [.adtVal 0 (.tuple [])]), MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.tryBranchOption tryU8Ty)
[(.option tryU16Ty, .optionVal none)]
(tryCfTy tryU8Ty tryOptResidualTy) = .error .unsupported ∧
execCoreContractOp MemoryState.empty (.tryBranchOption tryU8Ty)
[(.option tryU8Ty, .optionVal none)]
(tryCfTy tryU8Ty (tryResidualTy tryU8Ty)) = .error .unsupported ∧
execCoreContractOp MemoryState.empty (.tryBranchOption tryU8Ty)
[(.option tryU8Ty, .optionVal none)]
(tryCfTy tryU8Ty (tryOptTy tryU8Ty)) = .error .unsupported ∧
execCoreContractOp MemoryState.empty (.tryBranchOption tryU8Ty)
[(tryOptTy tryU8Ty, .adtVal 1 (.tuple [tryU8 4]))]
(tryCfTy tryU8Ty tryOptResidualTy) =
.ok (.adtVal 0 (.tuple [tryU8 4]), MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.tryBranchOption tryU8Ty)
[(tryOptTy tryU8Ty, .adtVal 0 (.tuple []))]
(tryCfTy tryU8Ty tryOptResidualTy) =
.ok (.adtVal 1 (.tuple [.adtVal 0 (.tuple [])]), MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.tryBranchOption tryU8Ty)
[(tryOptTy tryU16Ty, .adtVal 0 (.tuple []))]
(tryCfTy tryU8Ty tryOptResidualTy) = .error .unsupported ∧
execCoreContractOp MemoryState.empty (.tryBranchOption tryU8Ty)
[(tryOptTy tryU8Ty, .adtVal 0 (.tuple []))]
(tryCfTy tryU16Ty tryOptResidualTy) = .error .unsupported :=
⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl⟩
/-- Guards `core_from_residual_result_*`: `Result<u8, u8>::from_residual`
maps the residual `Err(5)` to `Err(5)` only when the residual's and the
destination's error types are both `u8`, so that `From` is the identity. -/
theorem refute_core_from_residual_result :
execCoreContractOp MemoryState.empty
(.fromResidualResult tryU8Ty tryU8Ty)
[(tryResidualTy tryU8Ty, .adtVal 1 (.tuple [tryU8 5]))]
(tryResTy tryU8Ty tryU8Ty) =
.ok (.adtVal 1 (.tuple [tryU8 5]), MemoryState.empty) ∧
execCoreContractOp MemoryState.empty
(.fromResidualResult tryU8Ty tryU8Ty)
[(tryResidualTy tryU16Ty, .adtVal 1 (.tuple [tryU8 5]))]
(tryResTy tryU8Ty tryU8Ty) = .error .unsupported ∧
execCoreContractOp MemoryState.empty
(.fromResidualResult tryU8Ty tryU8Ty)
[(tryResidualTy tryU8Ty, .adtVal 1 (.tuple [tryU8 5]))]
(tryResTy tryU8Ty tryU16Ty) = .error .unsupported :=
⟨rfl, rfl, rfl⟩
/-- Guards `core_from_residual_option_*`: `Option<u8>::from_residual` maps
the residual `None` to `None`, as an `Option` or a payload-enum `Option`,
while another residual or destination is unsupported. -/
theorem refute_core_from_residual_option :
execCoreContractOp MemoryState.empty (.fromResidualOption tryU8Ty)
[(tryOptResidualTy, .adtVal 0 (.tuple []))] (.option tryU8Ty) =
.ok (.optionVal none, MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.fromResidualOption tryU8Ty)
[(tryOptResidualTy, .adtVal 0 (.tuple []))] (tryOptTy tryU8Ty) =
.ok (.adtVal 0 (.tuple []), MemoryState.empty) ∧
execCoreContractOp MemoryState.empty (.fromResidualOption tryU8Ty)
[(tryOptTy tryU8Ty, .adtVal 0 (.tuple []))] (.option tryU8Ty) =
.error .unsupported ∧
execCoreContractOp MemoryState.empty (.fromResidualOption tryU8Ty)
[(tryOptResidualTy, .adtVal 0 (.tuple []))] (.option tryU16Ty) =
.error .unsupported ∧
execCoreContractOp MemoryState.empty (.fromResidualOption tryU8Ty)
[(tryOptResidualTy, .adtVal 0 (.tuple []))] (tryOptTy tryU16Ty) =
.error .unsupported :=
⟨rfl, rfl, rfl, rfl, rfl⟩
/-- Shared `&u8` type and dangling pointer for `?` call-boundary validity
refutations. -/
noncomputable def tryRefU8Ty : MirTy := .ref .shared tryU8Ty
noncomputable def tryDanglingPtr : Val := .ptr ⟨some 9, 0, .isize⟩
/-- A live 1-byte heap allocation for aliasing `Box<u8>` pair refutations. -/
noncomputable def tryBoxPairTy : MirTy := .tuple [.box tryU8Ty, .box tryU8Ty]
noncomputable def tryAliasedBoxPair : Val :=
.tuple [.boxPtr ⟨some 1, 0, .isize⟩ none, .boxPtr ⟨some 1, 0, .isize⟩ none]
noncomputable def tryOneByteMem : MemoryState :=
{ nextAllocId := 2
allocations := [{ allocId := 1, alignLog2 := 0, mutability := .mut,
bytes := [.init 7 none], live := true }] }
/-- Guards `core_try_payload_refs_valid`, `core_try_payload_spans_disjoint`,
`core_try_branch_result_{ok,err}_valid`, `core_try_branch_option{,_adt}_valid`,
and `core_from_residual_result_valid`: by-value payloads crossing a `?`
`Try::branch` or `FromResidual::from_residual` call boundary reject dangling
references and aliasing owned handles with `.error .undefined`. -/
theorem refute_core_try_payload_valid :
execCoreContractOp MemoryState.empty (.tryBranchResult tryRefU8Ty tryU8Ty)
[(tryResTy tryRefU8Ty tryU8Ty, .adtVal 0 (.tuple [tryDanglingPtr]))]
(tryCfTy tryRefU8Ty (tryResidualTy tryU8Ty)) = .error .undefined ∧
execCoreContractOp MemoryState.empty (.tryBranchResult tryU8Ty tryRefU8Ty)
[(tryResTy tryU8Ty tryRefU8Ty, .adtVal 1 (.tuple [tryDanglingPtr]))]
(tryCfTy tryU8Ty (tryResidualTy tryRefU8Ty)) = .error .undefined ∧
execCoreContractOp MemoryState.empty (.tryBranchOption tryRefU8Ty)
[(.option tryRefU8Ty, .optionVal (some tryDanglingPtr))]
(tryCfTy tryRefU8Ty tryOptResidualTy) = .error .undefined ∧
execCoreContractOp MemoryState.empty (.tryBranchOption tryRefU8Ty)
[(tryOptTy tryRefU8Ty, .adtVal 1 (.tuple [tryDanglingPtr]))]
(tryCfTy tryRefU8Ty tryOptResidualTy) = .error .undefined ∧
execCoreContractOp MemoryState.empty (.fromResidualResult tryU8Ty tryRefU8Ty)
[(tryResidualTy tryRefU8Ty, .adtVal 1 (.tuple [tryDanglingPtr]))]
(tryResTy tryU8Ty tryRefU8Ty) = .error .undefined ∧
execCoreContractOp tryOneByteMem (.tryBranchResult tryBoxPairTy tryU8Ty)
[(tryResTy tryBoxPairTy tryU8Ty, .adtVal 0 (.tuple [tryAliasedBoxPair]))]
(tryCfTy tryBoxPairTy (tryResidualTy tryU8Ty)) = .error .undefined :=
⟨rfl, rfl, rfl, rfl, rfl, rfl⟩
/-- `struct S { v: Vec<u8>, n: u32 }` with `v` at offset 0 and `n` at 24. -/
noncomputable def pdStructTy : MirTy :=
.struct_ ⟨90, 32, 3, [0, 24]⟩ [.vec dropU8, .int .i32 false]
/-- Profile v2 program dropping `(*_1).0` with `_1 : &mut S` twice (body 0),
`*_1` with `_1 : &mut Option<Vec<u8>>` (body 1), `_1.1` of a local
`(Vec<u8>, Vec<u8>)` twice (body 2), `(*_1).1 : u32` (body 3), `_1.0` of a
local `(u8, Vec<u8>)` (body 4), and `(*_1)[0]` with `_1 : &mut [Vec<u8>; 1]`
(body 5). -/
noncomputable def progDropProjV2 : Program := {
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 2
bodies := [{
argumentCount := 1
locals := [.unit, .ref .mut pdStructTy]
basicBlocks := [
{ statements := []
terminator := .drop ⟨1, [.deref, .field 0 (.vec dropU8)]⟩ 1
.unreachable },
{ statements := []
terminator := .drop ⟨1, [.deref, .field 0 (.vec dropU8)]⟩ 2
.unreachable },
{ statements := [], terminator := .return_ }]
identity := "guard_mutation::drop_deref_field_twice"
}, {
argumentCount := 1
locals := [.unit, .ref .mut (.option (.vec dropU8))]
basicBlocks := [
{ statements := [], terminator := .drop ⟨1, [.deref]⟩ 1 .unreachable },
{ statements := [], terminator := .return_ }]
identity := "guard_mutation::drop_deref_option_vec"
}, {
argumentCount := 1
locals := [.unit, .tuple [.vec dropU8, .vec dropU8]]
basicBlocks := [
{ statements := []
terminator := .drop ⟨1, [.field 1 (.vec dropU8)]⟩ 1 .unreachable },
{ statements := []
terminator := .drop ⟨1, [.field 1 (.vec dropU8)]⟩ 2 .unreachable },
{ statements := [], terminator := .return_ }]
identity := "guard_mutation::drop_tuple_field_twice"
}, {
argumentCount := 1
locals := [.unit, .ref .mut pdStructTy]
basicBlocks := [
{ statements := []
terminator := .drop ⟨1, [.deref, .field 1 (.int .i32 false)]⟩ 1
.unreachable },
{ statements := [], terminator := .return_ }]
identity := "guard_mutation::drop_deref_field_no_glue"
}, {
argumentCount := 1
locals := [.unit, .tuple [dropU8, .vec dropU8]]
basicBlocks := [
{ statements := [], terminator := .drop ⟨1, [.field 0 dropU8]⟩ 1
.unreachable },
{ statements := [], terminator := .return_ }]
identity := "guard_mutation::drop_tuple_field_no_glue"
}, {
argumentCount := 1
locals := [.unit, .ref .mut (.array (.vec dropU8) 1)]
basicBlocks := [
{ statements := []
terminator := .drop ⟨1, [.deref, .constantIndex 0 1 false]⟩ 1
.unreachable },
{ statements := [], terminator := .return_ }]
identity := "guard_mutation::drop_deref_constant_index"
}, {
argumentCount := 2
locals := [.unit, .ref .mut (.array (.vec dropU8) 2), .int .isize false]
basicBlocks := [
{ statements := []
terminator := .drop ⟨1, [.deref, .index 2]⟩ 1 .unreachable },
{ statements := [], terminator := .return_ }]
identity := "guard_mutation::drop_deref_index"
}, {
argumentCount := 1
locals := [.unit, .ref .mut (.option (.vec dropU8))]
basicBlocks := [
{ statements := []
terminator := .drop ⟨1, [.deref, .downcast 1, .field 0 (.vec dropU8)]⟩
1 .unreachable },
{ statements := [], terminator := .return_ }]
identity := "guard_mutation::drop_deref_downcast"
}, {
argumentCount := 2
locals := [.unit, .ref .mut (.slice (.vec dropU8)), .int .isize false]
basicBlocks := [
{ statements := []
terminator := .drop ⟨1, [.deref, .index 2]⟩ 1 .unreachable },
{ statements := [], terminator := .return_ }]
identity := "guard_mutation::drop_deref_slice_index"
}]
}
/-- `dropMem` plus allocation `5` (of `size` bytes) holding `S` with
`v = dropVec1` (allocation `1`) and `n = 9`, or `Some(dropVec1)` when
`opt`. -/
noncomputable def pdMem (size : Nat) (opt : Bool) : MemoryState :=
let bytes : List AllocByte :=
if opt then
match encodeValV2 profileV2TargetEndian (.option (.vec dropU8))
(.optionVal (some dropVec1)) with
| .ok bs => bs
| .error _ => []
else
match encodeValV2 profileV2TargetEndian pdStructTy
(.tuple [dropVec1, .scalar ⟨.i32, false, BitVec.ofNat 128 9⟩]) with
| .ok bs => bs
| .error _ => []
{ nextAllocId := 6,
allocations := dropMem.allocations ++
[{ allocId := 5, alignLog2 := 3, mutability := .mut,
bytes := bytes.take size }] }
/-- State at block 0 of `progDropProjV2` body `defId` with `_1` in `slot`. -/
noncomputable def pdState (defId : DefId) (slot : LocalSlot)
(mem : MemoryState) : State :=
dropState defId slot mem
/-- `_1 = &mut *alloc5`. -/
noncomputable def pdPtr : LocalSlot := .immediate (some (.ptr ⟨some 5, 0, .isize⟩))
/-- Fault kind, or liveness of allocation `a`, after `n + 1` steps. -/
noncomputable def pdLive (a : AllocId) (s : State) (n : Nat) :
Except FaultKind (Option Bool) :=
let rec go (s : State) : Nat → StepResult State TerminalOut
| 0 => evalStepV2 progDropProjV2 s
| k + 1 =>
match evalStepV2 progDropProjV2 s with
| .step s' => go s' k
| r => r
match go s n with
| .step s' => .ok ((findAllocation a s'.mem.allocations).map (·.live))
| .done _ => .ok none
| .fault k => .error k
/-- Guard `step_v2_drop_deref_field_runs_glue`: `drop((*_1).0)` with
`_1 : &mut S` runs the drop glue of the `Vec` field, freeing allocation
`1`. -/
theorem refute_step_v2_drop_deref_field_runs_glue :
pdLive 1 (pdState 0 pdPtr (pdMem 32 false)) 0 = .ok (some false) := rfl
/-- Guard `step_v2_drop_deref_field_deinit`: `drop((*_1).0)` deinitializes the
field, so dropping it again faults with `.unsupported` (an uninitialized
value) rather than freeing allocation `1` a second time. -/
theorem refute_step_v2_drop_deref_field_deinit :
pdLive 1 (pdState 0 pdPtr (pdMem 32 false)) 1 = .error .unsupported :=
rfl
/-- Guard `step_v2_drop_deref_field_bounds`: the whole pointee must be in
bounds, even when the dropped field is: with allocation `5` cut to the `Vec`
field's 24 bytes, `drop((*_1).0)` faults with `.undefined`. -/
theorem refute_step_v2_drop_deref_field_bounds :
pdLive 1 (pdState 0 pdPtr (pdMem 24 false)) 0 = .error .undefined := rfl
/-- Guard `step_v2_drop_deref_generic_pointee`: `drop(*_1)` with
`_1 : &mut Option<Vec<u8>>` runs the drop glue of the `Some` payload. -/
theorem refute_step_v2_drop_deref_generic_pointee :
pdLive 1 (pdState 1 pdPtr (pdMem 24 true)) 0 = .ok (some false) := rfl
/-- Guard `step_v2_drop_tuple_field_runs_glue`: `drop(_1.1)` of a local
`(Vec<u8>, Vec<u8>)` runs the drop glue of field 1, freeing allocation `2`
and leaving allocation `1` (field 0) live. -/
theorem refute_step_v2_drop_tuple_field_runs_glue :
pdLive 2 (pdState 2 (.immediate (some (.tuple [dropVec1, dropVec2])))
dropMem) 0 = .ok (some false) ∧
pdLive 1 (pdState 2 (.immediate (some (.tuple [dropVec1, dropVec2])))
dropMem) 0 = .ok (some true) :=
⟨rfl, rfl⟩
/-- The slot of `_1` after one step of `progDropProjV2` body `defId`. -/
noncomputable def pdSlot1 (s : State) : Option LocalSlot :=
match evalStepV2 progDropProjV2 s with
| .step s' =>
match s'.frames with
| f :: _ => Trusted.MirSemantics.getElem? f.locals 1
| [] => none
| _ => none
/-- Guard `step_v2_drop_tuple_field_moves`: `drop(_1.1)` moves field 1 out of
the tuple, as `move _1.1` does, leaving field 0 in a partial tuple, and a
second `drop(_1.1)` faults with `.undefined`. -/
theorem refute_step_v2_drop_tuple_field_moves :
pdSlot1 (pdState 2 (.immediate (some (.tuple [dropVec1, dropVec2])))
dropMem) = some (.partialTuple [some dropVec1, none]) ∧
pdLive 2 (pdState 2 (.immediate (some (.tuple [dropVec1, dropVec2])))
dropMem) 1 = .error .undefined :=
⟨rfl, rfl⟩
/-- Guard `step_v2_drop_tuple_field_no_glue`: `drop(_1.0)` of a `u8` field,
which has no drop glue and which drop elaboration never leaves a `Drop` on,
faults with `.unsupported`. -/
theorem refute_step_v2_drop_tuple_field_no_glue :
pdLive 1 (pdState 4 (.immediate (some (.tuple
[.scalar ⟨.i8, false, 0⟩, dropVec1]))) dropMem) 0 = .error .unsupported :=
rfl
/-- `dropMem` plus allocation `5` holding `[dropVec1, dropVec2]` (buffers in
allocations `1` and `2`). -/
noncomputable def pdArrMem : MemoryState :=
{ nextAllocId := 6,
allocations := dropMem.allocations ++
[{ allocId := 5, alignLog2 := 3, mutability := .mut,
bytes :=
match encodeValV2 profileV2TargetEndian (.array (.vec dropU8) 2)
(.array [dropVec1, dropVec2]) with
| .ok bs => bs
| .error _ => [] }] }
/-- Body 6 with `_1 = &mut *alloc5` and `_2` in `idx`. -/
noncomputable def pdIdxState (idx : LocalSlot) : State :=
dropStateAt 6 0 pdPtr [idx] pdArrMem
/-- A `usize` local holding `n`. -/
noncomputable def pdUsize (n : Nat) : LocalSlot :=
.immediate (some (.scalar ⟨.isize, false, BitVec.ofNat 128 n⟩))
/-- Guard `step_v2_drop_deref_index_resolves`: `drop((*_1)[_2])` with
`_2 = 1` reads the index local and drops element 1, freeing allocation `2`
and leaving element 0's allocation `1` live. -/
theorem refute_step_v2_drop_deref_index_resolves :
pdLive 2 (pdIdxState (pdUsize 1)) 0 = .ok (some false) ∧
pdLive 1 (pdIdxState (pdUsize 1)) 0 = .ok (some true) :=
⟨rfl, rfl⟩
/-- Canary: an out-of-bounds index (`_2 = 2` into `[_; 2]`) and a dead index
local fault with `.undefined`; `drop((*_1)[0])` through a constant index
drops element 0; `drop(((*_1) as Some).0)` is refused, since a downcast may
not follow the dereference; and an element of a `&mut [Vec<u8>]` slice is
refused. -/
theorem canary_step_v2_drop_deref_index_refusals :
pdLive 2 (pdIdxState (pdUsize 2)) 0 = .error .undefined ∧
pdLive 2 (pdIdxState .dead) 0 = .error .undefined ∧
pdLive 1 (pdState 5 pdPtr (pdMem 24 false)) 0 = .ok (some false) ∧
pdLive 1 (pdState 7 pdPtr (pdMem 24 true)) 0 = .error .unsupported ∧
pdLive 1 (dropStateAt 8 0
(.immediate (some (.slicePtr ⟨some 5, 0, .isize⟩ 2)))
[pdUsize 0] pdArrMem) 0 = .error .unsupported :=
⟨rfl, rfl, rfl, rfl, rfl⟩
/-- Canary: `drop((*_1).1)` of a `u32` field faults with `.unsupported`, and
`drop((*_1).0)` through a dead reference local faults with `.undefined`. -/
theorem canary_step_v2_drop_deref_field_refusals :
pdLive 1 (pdState 3 pdPtr (pdMem 32 false)) 0 = .error .unsupported ∧
pdLive 1 (pdState 0 .dead (pdMem 32 false)) 0 = .error .undefined :=
⟨rfl, rfl⟩
/-- Profile v2 program comparing two `&&bool` locals through `core`'s
`<&A as PartialEq<&B>>` forwarding impl (`TerminatorKind.callVia`). Block 0
calls `ne` on `bool_eq` (body 1, returning `true`), block 1 calls `eq` on a
callee returning `u8` (body 2), and block 2 calls `eq` on a callee taking a
single `&bool` (body 3). -/
noncomputable def progCallViaRefEqV2 : Program := {
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 2
bodies := [{
argumentCount := 0
locals := [.bool, .ref .shared (.ref .shared .bool),
.ref .shared (.ref .shared .bool)]
basicBlocks := [
{ statements := []
terminator := .callVia (.refPartialEq true) 1
[.copy ⟨1, []⟩, .copy ⟨2, []⟩] ⟨0, []⟩ (some 3) .continue_ },
{ statements := []
terminator := .callVia (.refPartialEq false) 2
[.copy ⟨1, []⟩, .copy ⟨2, []⟩] ⟨0, []⟩ (some 3) .continue_ },
{ statements := []
terminator := .callVia (.refPartialEq false) 3
[.copy ⟨1, []⟩, .copy ⟨2, []⟩] ⟨0, []⟩ (some 3) .continue_ },
{ statements := []
terminator := .return_ }]
identity := "guard_mutation::call_via_ref_eq_main"
}, {
argumentCount := 2
locals := [.bool, .ref .shared .bool, .ref .shared .bool]
basicBlocks := [{
statements := [
.assign ⟨0, []⟩ (.use (.constant ⟨.bool, .scalar 1⟩))
]
terminator := .return_
}]
identity := "guard_mutation::call_via_ref_eq_bool_eq"
}, {
argumentCount := 2
locals := [.int .i8 false, .ref .shared .bool, .ref .shared .bool]
basicBlocks := [{ statements := [], terminator := .return_ }]
identity := "guard_mutation::call_via_ref_eq_u8_eq"
}, {
argumentCount := 1
locals := [.bool, .ref .shared .bool]
basicBlocks := [{ statements := [], terminator := .return_ }]
identity := "guard_mutation::call_via_ref_eq_unary_eq"
}]
}
/-- The `progCallViaRefEqV2` caller at block `blk` with `_1 = a` and
`_2 = b`, over `nestedBoolMem`. -/
noncomputable def callViaRefEqS0 (blk : Nat) (a b : AllocId) : State := {
frames := [{
defId := 0
blockIdx := blk
stmtIdx := 0
locals := [.immediate none,
.immediate (some (.ptr ⟨some a, 0, .isize⟩)),
.immediate (some (.ptr ⟨some b, 0, .isize⟩))]
}]
mem := nestedBoolMem
}
/-- Guard `step_v2_call_via_ref_eq_negates`: `<&bool as PartialEq>::ne`
forwarding to a `bool_eq` that returns `true` writes `false` to the caller's
destination when the callee returns. -/
theorem refute_step_v2_call_via_ref_eq_negates :
(match evalStepV2 progCallViaRefEqV2 (callViaRefEqS0 0 2 2) with
| .step s₁ =>
match evalStepV2 progCallViaRefEqV2 s₁ with
| .step s₂ =>
match evalStepV2 progCallViaRefEqV2 s₂ with
| .step s₃ =>
match s₃.frames with
| [{ locals := .immediate (some (.bool false)) :: _, .. }] =>
True
| _ => False
| _ => False
| _ => False
| _ => False) :=
trivial
/-- Guard `step_v2_call_via_ref_eq_bool_sig`: forwarding
`<&A as PartialEq>::eq` to a callee whose return type is not `bool` faults
with `.unsupported` before the callee frame is pushed. -/
theorem refute_step_v2_call_via_ref_eq_bool_sig :
(match evalStepV2 progCallViaRefEqV2 (callViaRefEqS0 1 2 2) with
| .fault .unsupported => True
| _ => False) :=
trivial
/-- Guard `step_v2_call_via_outer_ref_validity`: entering the forwarding
`eq` validates each whole `&&bool` argument, so an argument whose outer
reference is valid but whose inner `&bool` dangles (allocation 3 points at
the missing allocation 9) faults with `.undefined` before `*a` and `*b` are
passed on, even to a callee whose signature (one `&bool`) would not accept
them. -/
theorem refute_step_v2_call_via_outer_ref_validity :
(match evalStepV2 progCallViaRefEqV2 (callViaRefEqS0 2 3 2) with
| .fault .undefined => True
| _ => False) :=
trivial
/-- Guard `step_v2_call_via_deref_inner_arg`: the callee receives `*a` (the
`&bool` stored in allocation 2, pointing at allocation 1), not the outer
`&&bool` `a` itself. -/
theorem refute_step_v2_call_via_deref_inner_arg :
(match evalStepV2 progCallViaRefEqV2 (callViaRefEqS0 0 2 2) with
| .step s₁ =>
match s₁.frames with
| { locals := [_, .immediate (some (.ptr ⟨some 1, _, _⟩)),
.immediate (some (.ptr ⟨some 1, _, _⟩))], .. } :: _ => True
| _ => False
| _ => False) :=
trivial
/-- Profile v2 program cloning boxes through `<Box<T> as Clone>::clone`
(`TerminatorKind.callVia`), with `_2 : &Box<u8>`, `_4 : &Box<()>`, and
`_5 : &Box<i8>`:
- block 0 clones `*_2` into `_1` with `<u8 as Clone>::clone` (body 1,
returning `*self`);
- block 1 clones `*_2` into `_1` with a callee returning `i16` (body 3);
- block 2 clones `*_5` into `_1` as a `Box<u8>` with body 1;
- block 3 clones `*_4` into `_3` with `<() as Clone>::clone` (body 2). -/
noncomputable def progCallViaBoxCloneV2 : Program := {
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 2
bodies := [{
argumentCount := 0
locals := [.unit, .box (.int .i8 false),
.ref .shared (.box (.int .i8 false)), .box .unit,
.ref .shared (.box .unit), .ref .shared (.box (.int .i8 true))]
basicBlocks := [
{ statements := []
terminator := .callVia (.boxClone (.int .i8 false)) 1
[.copy ⟨2, []⟩] ⟨1, []⟩ (some 4) .continue_ },
{ statements := []
terminator := .callVia (.boxClone (.int .i8 false)) 3
[.copy ⟨2, []⟩] ⟨1, []⟩ (some 4) .continue_ },
{ statements := []
terminator := .callVia (.boxClone (.int .i8 false)) 1
[.copy ⟨5, []⟩] ⟨1, []⟩ (some 4) .continue_ },
{ statements := []
terminator := .callVia (.boxClone .unit) 2
[.copy ⟨4, []⟩] ⟨3, []⟩ (some 4) .continue_ },
{ statements := []
terminator := .return_ }]
identity := "guard_mutation::call_via_box_clone_main"
}, {
argumentCount := 1
locals := [.int .i8 false, .ref .shared (.int .i8 false)]
basicBlocks := [{
statements := [
.assign ⟨0, []⟩ (.use (.copy ⟨1, [.deref]⟩))
]
terminator := .return_
}]
identity := "guard_mutation::call_via_box_clone_u8_clone"
}, {
argumentCount := 1
locals := [.unit, .ref .shared .unit]
basicBlocks := [{ statements := [], terminator := .return_ }]
identity := "guard_mutation::call_via_box_clone_unit_clone"
}, {
argumentCount := 1
locals := [.int .i16 false, .ref .shared (.int .i8 false)]
basicBlocks := [{ statements := [], terminator := .return_ }]
identity := "guard_mutation::call_via_box_clone_i16_clone"
}]
}
/-- Allocation 1 is the heap buffer of a `Box<u8>` holding `7`, and
allocation 2 holds that box. -/
noncomputable def boxCloneMem : MemoryState := {
allocations := [
{ allocId := 1, alignLog2 := 0, mutability := .mut,
bytes := [.init 7 none], live := true },
{ allocId := 2, alignLog2 := 3, mutability := .shared,
bytes := List.replicate 8 (.init 0 (some 1)), live := true }]
nextAllocId := 3
}
/-- The `progCallViaBoxCloneV2` caller at block `blk`, with `_2`, `_4`, and
`_5` pointing at the box in allocation 2. -/
noncomputable def callViaBoxCloneS0 (blk : Nat) : State := {
frames := [{
defId := 0
blockIdx := blk
stmtIdx := 0
locals := [.immediate none, .immediate none,
.immediate (some (.ptr ⟨some 2, 0, .isize⟩)), .immediate none,
.immediate (some (.ptr ⟨some 2, 0, .isize⟩)),
.immediate (some (.ptr ⟨some 2, 0, .isize⟩))]
}]
mem := boxCloneMem
}
/-- Guard `step_v2_call_via_box_clone_writes_dst`: the call allocates the
clone's buffer (allocation 3) and holds the new box in `dst` while the callee
runs, which is where the return finds it. -/
theorem refute_step_v2_call_via_box_clone_writes_dst :
(match evalStepV2 progCallViaBoxCloneV2 (callViaBoxCloneS0 0) with
| .step s₁ =>
match s₁.frames with
| [_, { locals := [_, .immediate (some (.boxPtr ⟨some 3, _, _⟩ none)),
_, _, _, _], .. }] => True
| _ => False
| _ => False) :=
trivial
/-- Guard `step_v2_box_clone_store_writes_result`: when `<u8 as Clone>::clone`
returns, its result `7` is written into the clone's buffer, and the caller
continues at block 4. -/
theorem refute_step_v2_box_clone_store_writes_result :
(match evalStepV2 progCallViaBoxCloneV2 (callViaBoxCloneS0 0) with
| .step s₁ =>
match evalStepV2 progCallViaBoxCloneV2 s₁ with
| .step s₂ =>
match evalStepV2 progCallViaBoxCloneV2 s₂ with
| .step s₃ =>
(s₃.frames.map (·.blockIdx),
(findAllocation 3 s₃.mem.allocations).map (·.bytes)) =
([4], some [.init 7 none])
| _ => False
| _ => False
| _ => False) :=
rfl
/-- Guard `step_v2_call_via_box_clone_ret_sig`: cloning a `Box<u8>` with a
callee that returns `i16` rather than `u8` is `.unsupported` before the
callee frame is pushed. -/
theorem refute_step_v2_call_via_box_clone_ret_sig :
(match evalStepV2 progCallViaBoxCloneV2 (callViaBoxCloneS0 1) with
| .fault .unsupported => True
| _ => False) :=
trivial
/-- Guard `step_v2_call_via_box_clone_arg_pointee`: a `Box<u8>` clone whose
argument is a valid `&Box<i8>` is `.unsupported` rather than reading the
`i8` buffer as a `u8`. -/
theorem refute_step_v2_call_via_box_clone_arg_pointee :
(match evalStepV2 progCallViaBoxCloneV2 (callViaBoxCloneS0 2) with
| .fault .unsupported => True
| _ => False) :=
trivial
/-- Guard `step_v2_call_via_box_clone_zst_dangling`: cloning a `Box<()>`
allocates nothing, and the new box holds a dangling pointer without
provenance (`Box::new_uninit_in` for a zero-sized `T`). -/
theorem refute_step_v2_call_via_box_clone_zst_dangling :
(match evalStepV2 progCallViaBoxCloneV2 (callViaBoxCloneS0 3) with
| .step s₁ =>
match s₁.frames with
| [_, { locals := [_, _, _,
.immediate (some (.boxPtr ⟨none, _, _⟩ none)), _, _], .. }] =>
True
| _ => False
| _ => False) :=
trivial
/-- Guard `step_v2_box_clone_store_checks_ret`: a returned value that is not
a valid pointee is `.unsupported`, even for a zero-sized pointee, for which
nothing would be written. -/
theorem refute_step_v2_box_clone_store_checks_ret :
(match storeBoxCloneResultV2 { statements := [], terminator := .return_ }
{ defId := 0
blockIdx := 0
stmtIdx := 0
locals := [.immediate none,
.immediate (some (.boxPtr ⟨none, 1, .isize⟩ none))] }
[] emptyMemory { allocations := [] } ⟨1, []⟩ 1 .unit
(.bool true) with
| .fault .unsupported => True
| _ => False) :=
trivial
/-- Memory extending `nestedBoolMem` with an indirect slot (alloc 4) holding
a valid `&&bool` pointing at alloc 2, used to exercise `callInPlaceArgsV2` in
`evalCallViaV2`. -/
private noncomputable def callViaInPlaceMem : MemoryState := {
allocations := nestedBoolMem.allocations ++ [{
allocId := 4, alignLog2 := 3, mutability := .mut,
bytes := List.replicate 8 (.init 0 (some 2)), live := true
}]
nextAllocId := 5
}
/-- Caller executing `CallVia.refPartialEq` with a moved argument (`_1`) so
an `.indirect` `_1` triggers `callInPlaceArgsV2`. -/
private noncomputable def progCallViaInPlaceV2 : Program := {
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 2
bodies := [{
argumentCount := 0
locals := [.bool, .ref .shared (.ref .shared .bool),
.ref .shared (.ref .shared .bool)]
basicBlocks := [
{ statements := []
terminator := .callVia (.refPartialEq false) 1
[.move ⟨1, []⟩, .copy ⟨2, []⟩] ⟨0, []⟩ (some 1) .continue_ },
{ statements := []
terminator := .return_ }]
identity := "guard_mutation::call_via_in_place_main"
}, {
argumentCount := 2
locals := [.bool, .ref .shared .bool, .ref .shared .bool]
basicBlocks := [{
statements := [
.assign ⟨0, []⟩ (.use (.constant ⟨.bool, .scalar 1⟩))
]
terminator := .return_
}]
identity := "guard_mutation::call_via_in_place_bool_eq"
}]
}
/-- Guard `step_v2_call_via_in_place_args`: `evalCallViaV2` rejects a call
whose moved argument lives in memory (`callInPlaceArgsV2`), matching
`evalCallV2`. -/
theorem refute_step_v2_call_via_in_place_args :
(match evalStepV2 progCallViaInPlaceV2 {
frames := [{
defId := 0
blockIdx := 0
stmtIdx := 0
locals := [.immediate none, .indirect ⟨4, 0⟩,
.immediate (some (.ptr ⟨some 2, 0, .isize⟩))]
}]
mem := callViaInPlaceMem
} with
| .fault .unsupported => True
| _ => False) :=
trivial
/-- Guard `step_v2_call_via_indirect_dst`: `evalCallViaV2` rejects a call
whose destination lives in memory (`localIsIndirectV2`), matching
`evalCallV2`. -/
theorem refute_step_v2_call_via_indirect_dst :
(match evalStepV2 progCallViaRefEqV2 {
frames := [{
defId := 0
blockIdx := 0
stmtIdx := 0
locals := [.indirect ⟨1, 0⟩,
.immediate (some (.ptr ⟨some 2, 0, .isize⟩)),
.immediate (some (.ptr ⟨some 2, 0, .isize⟩))]
}]
mem := nestedBoolMem
} with
| .fault .unsupported => True
| _ => False) :=
trivial
/-- `struct T { a: [Vec<u8>; 2], n: u32 }` with `a` at offset 0 and `n` at
48. -/
noncomputable def plArrStructTy : MirTy :=
.struct_ ⟨91, 56, 3, [0, 48]⟩ [.array (.vec dropU8) 2, .int .i32 false]
/-- Profile v2 program dropping `_1.0` of a local `S` (body 0), `_1.0[_2]` of
a local `T` (body 1), and `(_1 as Some).0` of a local `Option<Vec<u8>>`
(body 2). -/
noncomputable def progDropLocalV2 : Program := {
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 2
bodies := [{
argumentCount := 1
locals := [.unit, pdStructTy]
basicBlocks := [
{ statements := []
terminator := .drop ⟨1, [.field 0 (.vec dropU8)]⟩ 1 .unreachable },
{ statements := []
terminator := .drop ⟨1, [.field 0 (.vec dropU8)]⟩ 2 .unreachable },
{ statements := [], terminator := .return_ }]
identity := "guard_mutation::drop_local_field_twice"
}, {
argumentCount := 2
locals := [.unit, plArrStructTy, .int .isize false]
basicBlocks := [
{ statements := []
terminator := .drop
⟨1, [.field 0 (.array (.vec dropU8) 2), .index 2]⟩ 1 .unreachable },
{ statements := [], terminator := .return_ }]
identity := "guard_mutation::drop_local_field_index"
}, {
argumentCount := 1
locals := [.unit, .option (.vec dropU8)]
basicBlocks := [
{ statements := []
terminator := .drop ⟨1, [.downcast 1, .field 0 (.vec dropU8)]⟩ 1
.unreachable },
{ statements := [], terminator := .return_ }]
identity := "guard_mutation::drop_local_downcast"
}]
}
/-- `S` with `v = dropVec1` and `n = 9`. -/
noncomputable def plSVal : Val :=
.tuple [dropVec1, .scalar ⟨.i32, false, BitVec.ofNat 128 9⟩]
/-- `T` with `a = [dropVec1, dropVec2]` and `n = 9`. -/
noncomputable def plTVal : Val :=
.tuple [.array [dropVec1, dropVec2], .scalar ⟨.i32, false, BitVec.ofNat 128 9⟩]
/-- The final state, or fault kind, after `n + 1` steps of
`progDropLocalV2`. -/
noncomputable def plRun (s : State) (n : Nat) :
StepResult State TerminalOut :=
let rec go (s : State) : Nat → StepResult State TerminalOut
| 0 => evalStepV2 progDropLocalV2 s
| k + 1 =>
match evalStepV2 progDropLocalV2 s with
| .step s' => go s' k
| r => r
go s n
/-- Fault kind, or liveness of allocation `a`, after `n + 1` steps. -/
noncomputable def plLive (a : AllocId) (s : State) (n : Nat) :
Except FaultKind (Option Bool) :=
match plRun s n with
| .step s' => .ok ((findAllocation a s'.mem.allocations).map (·.live))
| .done _ => .ok none
| .fault k => .error k
/-- The slot of `_1` after one step. -/
noncomputable def plSlot1 (s : State) : Option LocalSlot :=
match plRun s 0 with
| .step s' =>
match s'.frames with
| f :: _ => Trusted.MirSemantics.getElem? f.locals 1
| [] => none
| _ => none
/-- Guard `step_v2_drop_local_field`: `drop(_1.0)` of a local `S` held
directly in its slot runs the `Vec` field's drop glue, freeing allocation
`1`; and so it does for `S` already in memory (allocation `5`). -/
theorem refute_step_v2_drop_local_field :
plLive 1 (dropState 0 (.immediate (some plSVal)) dropMem) 0 =
.ok (some false) ∧
plLive 1 (dropState 0 (.indirect ⟨5, 0⟩) (pdMem 32 false)) 0 =
.ok (some false) :=
⟨rfl, rfl⟩
/-- Guard `step_v2_drop_local_keeps_promotion`: the drop moves `_1` to its
stack allocation (`5`, the next id), where it stays, so the dropped field is
uninitialized there: a second `drop(_1.0)` faults with `.unsupported` rather
than freeing allocation `1` again. -/
theorem refute_step_v2_drop_local_keeps_promotion :
plSlot1 (dropState 0 (.immediate (some plSVal)) dropMem) =
some (.indirect ⟨5, 0⟩) ∧
plLive 1 (dropState 0 (.immediate (some plSVal)) dropMem) 1 =
.error .unsupported :=
⟨rfl, rfl⟩
/-- Guards `step_v2_drop_local_place` and `step_v2_drop_local_index_resolves`:
`drop(_1.0[_2])` of a local `T` with `_2 = 1` reads the index local and drops
element 1, freeing allocation `2` and leaving element 0's allocation `1`
live, and `drop((_1 as Some).0)` of a local `Option<Vec<u8>>`, a place that
does not start with a field, runs the payload's drop glue in place, freeing
allocation `1`. -/
theorem refute_step_v2_drop_local_place :
plLive 2 (dropStateAt 1 0 (.immediate (some plTVal)) [pdUsize 1] dropMem)
0 = .ok (some false) ∧
plLive 1 (dropStateAt 1 0 (.immediate (some plTVal)) [pdUsize 1] dropMem)
0 = .ok (some true) ∧
plLive 1 (dropState 2 (.immediate (some (.optionVal (some dropVec1))))
dropMem) 0 = .ok (some false) :=
⟨rfl, rfl, rfl⟩
/-- Canary: an out-of-bounds index (`_2 = 2`), a dead index local, and a dead
local fault with `.undefined`, and `drop((_1 as Some).0)` of a local
`Option<Vec<u8>>` runs the payload's drop glue in place, freeing allocation
`1`. -/
theorem canary_step_v2_drop_local_refusals :
plLive 2 (dropStateAt 1 0 (.immediate (some plTVal)) [pdUsize 2] dropMem)
0 = .error .undefined ∧
plLive 2 (dropStateAt 1 0 (.immediate (some plTVal)) [.dead] dropMem)
0 = .error .undefined ∧
plLive 1 (dropState 0 .dead dropMem) 0 = .error .undefined ∧
plLive 1 (dropState 2 (.immediate (some (.optionVal (some dropVec1))))
dropMem) 0 = .ok (some false) :=
⟨rfl, rfl, rfl, rfl⟩
/-- `struct U { b: u8, s: S }` with `s` at offset 0 and `b` at 32. -/
noncomputable def pmOuterTy : MirTy :=
.struct_ ⟨92, 40, 3, [32, 0]⟩ [.int .i8 false, pdStructTy]
/-- `struct Tree { val: i64, kids: Vec<Tree> }` with `kids` at offset 0 and
`val` at 24. -/
noncomputable def pmTreeTy : MirTy :=
.recAdt 97 (.struct_ ⟨97, 32, 3, [24, 0]⟩ [.int .i64 false, .vec (.recSelf 97)])
/-- Profile v2 program moving `_1.0` out of a local `S` into `_2` twice
(body 0), `(_1.1).0` out of a local `U` into `_2` (body 1), and `_1.1` out
of a local `Tree` into `_2` (body 2). -/
noncomputable def progMoveLocalV2 : Program := {
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 2
bodies := [{
argumentCount := 1
locals := [.unit, pdStructTy, .vec dropU8]
basicBlocks := [
{ statements := [
.assign ⟨2, []⟩ (.use (.move ⟨1, [.field 0 (.vec dropU8)]⟩)),
.assign ⟨2, []⟩ (.use (.move ⟨1, [.field 0 (.vec dropU8)]⟩))]
terminator := .return_ }]
identity := "guard_mutation::move_local_field_twice"
}, {
argumentCount := 1
locals := [.unit, pmOuterTy, .vec dropU8]
basicBlocks := [
{ statements := [
.assign ⟨2, []⟩ (.use (.move
⟨1, [.field 1 pdStructTy, .field 0 (.vec dropU8)]⟩))]
terminator := .return_ }]
identity := "guard_mutation::move_local_nested_field"
}, {
argumentCount := 1
locals := [.unit, pmTreeTy, .vec pmTreeTy]
basicBlocks := [
{ statements := [
.assign ⟨2, []⟩ (.use (.move ⟨1, [.field 1 (.vec pmTreeTy)]⟩))]
terminator := .return_ }]
identity := "guard_mutation::move_rec_struct_field"
}]
}
/-- The state, or fault kind, after `n + 1` steps of `progMoveLocalV2`. -/
noncomputable def pmRun (s : State) (n : Nat) :
StepResult State TerminalOut :=
let rec go (s : State) : Nat → StepResult State TerminalOut
| 0 => evalStepV2 progMoveLocalV2 s
| k + 1 =>
match evalStepV2 progMoveLocalV2 s with
| .step s' => go s' k
| r => r
go s n
/-- Fault kind, or the slots of `_1` and `_2`, after `n + 1` steps. -/
noncomputable def pmSlots (s : State) (n : Nat) :
Except FaultKind (Option LocalSlot × Option LocalSlot) :=
match pmRun s n with
| .step s' =>
match s'.frames with
| f :: _ =>
.ok (Trusted.MirSemantics.getElem? f.locals 1,
Trusted.MirSemantics.getElem? f.locals 2)
| [] => .ok (none, none)
| .done _ => .ok (none, none)
| .fault k => .error k
/-- Body `defId` at its first statement with `_1` holding `v` and `_2`
uninitialized. -/
noncomputable def pmState (defId : DefId) (v : Val) : State :=
dropStateAt defId 0 (.immediate (some v)) [.immediate none] dropMem
/-- Guards `step_v2_move_local_field` and
`step_v2_move_local_keeps_promotion`: `_2 = move _1.0` out of a local `S`
moves `_1` to its stack allocation (`5`) and gives `_2` the `Vec`. -/
theorem refute_step_v2_move_local_field :
pmSlots (pmState 0 plSVal) 0 =
.ok (some (.indirect ⟨5, 0⟩), some (.immediate (some dropVec1))) :=
rfl
/-- Guard `step_v2_move_local_deinit`: the move deinitializes the field, so a
second `move _1.0` faults with `.undefined` rather than duplicating the
`Vec`. -/
theorem refute_step_v2_move_local_deinit :
pmSlots (pmState 0 plSVal) 1 = .error .undefined := rfl
/-- Guard `step_v2_hazard_rec_struct_path`: `_2 = move _1.1` out of a local
`Tree` held directly in its slot passes the copy-hazard check, which follows
the recursive struct's unfolding, and gives `_2` the `Vec`. -/
theorem refute_step_v2_hazard_rec_struct_path :
pmSlots (pmState 2 (.tuple [.scalar ⟨.i64, false, 0⟩, dropVecEmpty])) 0 =
.ok (some (.indirect ⟨5, 0⟩), some (.immediate (some dropVecEmpty))) :=
rfl
/-- Guard `step_v2_move_local_nested`: `_2 = move (_1.1).0` out of a local
`U` gives `_2` the inner `Vec`. -/
theorem refute_step_v2_move_local_nested :
pmSlots (pmState 1 (.tuple [.scalar ⟨.i8, false, 0⟩, plSVal])) 0 =
.ok (some (.indirect ⟨5, 0⟩), some (.immediate (some dropVec1))) :=
rfl
/-- `Option<Vec<u8>>`, whose `None` is the `Vec` pointer's null niche. -/
noncomputable def pvOptTy : MirTy := .option (.vec dropU8)
/-- `struct W { o: Option<Vec<u8>>, n: u32 }` with `o` at offset 0 and `n` at
24. -/
noncomputable def pvStructTy : MirTy :=
.struct_ ⟨93, 32, 3, [0, 24]⟩ [pvOptTy, .int .i32 false]
/-- `(_1.0 as Some).0`, the `Vec` inside `W`'s `o`. -/
noncomputable def pvPayload : Place :=
⟨1, [.field 0 pvOptTy, .downcast 1, .field 0 (.vec dropU8)]⟩
/-- Profile v2 program moving `(_1.0 as Some).0` out of a local `W` into `_2`
and then reading `discriminant(_1.0)` into `_3` (body 0), and dropping
`(_1.0 as Some).0` and then reading `discriminant(_1.0)` into `_3`
(body 1). -/
noncomputable def progVariantV2 : Program := {
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 2
bodies := [{
argumentCount := 1
locals := [.unit, pvStructTy, .vec dropU8, .int .isize true]
basicBlocks := [
{ statements := [
.assign ⟨2, []⟩ (.use (.move pvPayload)),
.assign ⟨3, []⟩ (.discriminant ⟨1, [.field 0 pvOptTy]⟩)]
terminator := .return_ }]
identity := "guard_mutation::move_variant_field"
}, {
argumentCount := 1
locals := [.unit, pvStructTy, .vec dropU8, .int .isize true]
basicBlocks := [
{ statements := [], terminator := .drop pvPayload 1 .unreachable },
{ statements := [
.assign ⟨3, []⟩ (.discriminant ⟨1, [.field 0 pvOptTy]⟩)]
terminator := .return_ }]
identity := "guard_mutation::drop_variant_field"
}]
}
/-- Fault kind, or the slot of `_3` and the liveness of allocation `1`, after
`n + 1` steps of `progVariantV2`. -/
noncomputable def pvAfter (s : State) (n : Nat) :
Except FaultKind (Option LocalSlot × Option Bool) :=
let rec go (s : State) : Nat → StepResult State TerminalOut
| 0 => evalStepV2 progVariantV2 s
| k + 1 =>
match evalStepV2 progVariantV2 s with
| .step s' => go s' k
| r => r
match go s n with
| .step s' =>
match s'.frames with
| f :: _ =>
.ok (Trusted.MirSemantics.getElem? f.locals 3,
(findAllocation 1 s'.mem.allocations).map (·.live))
| [] => .ok (none, none)
| .done _ => .ok (none, none)
| .fault k => .error k
/-- Body `defId` with `_1 = W { o: Some(dropVec1), n: 9 }`. -/
noncomputable def pvState (defId : DefId) : State :=
dropStateAt defId 0 (.immediate (some (.tuple [.optionVal (some dropVec1),
.scalar ⟨.i32, false, BitVec.ofNat 128 9⟩]))) [.immediate none,
.immediate none] dropMem
/-- The `isize` discriminant `1` (`Some`). -/
noncomputable def pvSome : LocalSlot :=
.immediate (some (.scalar ⟨.isize, true, BitVec.ofNat 128 1⟩))
/-- Guard `step_v2_move_local_downcast_keeps_bytes`: moving
`(_1.0 as Some).0` out leaves `o`'s bytes in place, so reading the niche tag
of `o` afterwards is well-defined and still gives `Some`. -/
theorem refute_step_v2_move_local_downcast_keeps_bytes :
pvAfter (pvState 0) 1 = .ok (some pvSome, some true) := rfl
/-- Guard `step_v2_drop_local_downcast`: dropping `(_1.0 as Some).0` runs the
`Vec`'s drop glue, freeing allocation `1`, and leaves `o`'s bytes in place,
so its niche tag still reads as `Some`. -/
theorem refute_step_v2_drop_local_downcast :
pvAfter (pvState 1) 1 = .ok (some pvSome, some false) := rfl
/-- `enum E2 { A(Box<u8>, Vec<u8>) }`: one variant, with the `Vec` at offset
0 and the `Box` at 24. -/
noncomputable def pvE2Ty : MirTy :=
.adtEnum ⟨94, 32, 3, .isize, true, [0], 0, .i8, false, 0, 0, .single⟩
[.struct_ ⟨95, 32, 3, [24, 0]⟩ [.box dropU8, .vec dropU8]]
/-- `struct W2 { e: E2, n: u32 }` with `e` at offset 0 and `n` at 32. -/
noncomputable def pvW2Ty : MirTy :=
.struct_ ⟨96, 40, 3, [0, 32]⟩ [pvE2Ty, .int .i32 false]
/-- `(_1.0 as A).i` of a local `W2`. -/
noncomputable def pvE2Field (i : Nat) (ty : MirTy) : Place :=
⟨1, [.field 0 pvE2Ty, .downcast 0, .field i ty]⟩
/-- Profile v2 program dropping `(_1.0 as A).0` and then `(_1.0 as A).1` of a
local `W2` (body 0), moving `(_1.0 as A).1` (`Vec`, `.memoryCopy`) into `_2`
and then dropping `(_1.0 as A).0` (body 1), and moving `(_1.0 as A).0` into
`_2` and then `(_1.0 as A).1` into `_3` (body 2). -/
noncomputable def progVariant2V2 : Program := {
scope := .unit
pointerWidthBits := 64
mirProfileVersion := 2
bodies := [{
argumentCount := 1
locals := [.unit, pvW2Ty, .box dropU8]
basicBlocks := [
{ statements := []
terminator := .drop (pvE2Field 0 (.box dropU8)) 1 .unreachable },
{ statements := []
terminator := .drop (pvE2Field 1 (.vec dropU8)) 2 .unreachable },
{ statements := [], terminator := .return_ }]
identity := "guard_mutation::drop_variant_two_heap_fields"
}, {
argumentCount := 1
locals := [.unit, pvW2Ty, .vec dropU8]
basicBlocks := [
{ statements := [.assign ⟨2, []⟩ (.use (.move (pvE2Field 1 (.vec dropU8))))]
terminator := .drop (pvE2Field 0 (.box dropU8)) 1 .unreachable },
{ statements := [], terminator := .return_ }]
identity := "guard_mutation::move_then_drop_variant_field"
}, {
argumentCount := 1
locals := [.unit, pvW2Ty, .box dropU8, .vec dropU8]
basicBlocks := [
{ statements := [
.assign ⟨2, []⟩ (.use (.move (pvE2Field 0 (.box dropU8)))),
.assign ⟨3, []⟩ (.use (.move (pvE2Field 1 (.vec dropU8))))]
terminator := .return_ }]
identity := "guard_mutation::move_two_variant_fields"
}]
}
/-- Fault kind, or the liveness of allocations `1` (the `Vec`'s buffer) and
`3` (the `Box`'s), after `n + 1` steps of `progVariant2V2`. -/
noncomputable def pv2Live (s : State) (n : Nat) :
Except FaultKind (Option Bool × Option Bool) :=
let rec go (s : State) : Nat → StepResult State TerminalOut
| 0 => evalStepV2 progVariant2V2 s
| k + 1 =>
match evalStepV2 progVariant2V2 s with
| .step s' => go s' k
| r => r
match go s n with
| .step s' =>
.ok ((findAllocation 1 s'.mem.allocations).map (·.live),
(findAllocation 3 s'.mem.allocations).map (·.live))
| .done _ => .ok (none, none)
| .fault k => .error k
/-- Body `defId` with `_1 = W2 { e: A(Box(alloc 3), dropVec1), n: 9 }`. -/
noncomputable def pv2State (defId : DefId) : State :=
dropStateAt defId 0 (.immediate (some (.tuple [.adtVal 0 (.tuple
[.boxPtr ⟨some 3, 0, .isize⟩ none, dropVec1]),
.scalar ⟨.i32, false, BitVec.ofNat 128 9⟩]))) [.immediate none,
.immediate none] dropMem
/-- Guard `step_v2_hazard_indirect_variant_path`: after
`_2 = move (_1.0 as A).0` moves `_1` to its stack allocation, the copy-hazard
check of
`_3 = move (_1.0 as A).1` resolves the variant field there, so both moves
succeed and free nothing. -/
theorem refute_step_v2_hazard_indirect_variant_path :
pv2Live (pv2State 2) 1 = .ok (some true, some true) := rfl
/-- Canary: after a variant's first heap field is dropped (its `Box` freed)
or moved out, the downcast that reaches the second field still reads the
enum, so dropping both fields one at a time, and moving one out and then
dropping the other, both succeed and free exactly the dropped buffers. -/
theorem canary_step_v2_variant_two_heap_fields :
pv2Live (pv2State 0) 0 = .ok (some true, some false) ∧
pv2Live (pv2State 0) 1 = .ok (some false, some false) ∧
pv2Live (pv2State 1) 1 = .ok (some true, some false) :=
⟨rfl, rfl, rfl⟩
/-! ## Nested moves out of tuple locals (`moveTuplePathV2`)
`match (&v[i], opt) { (_, Some(a)) => .. }` moves `a` out of the tuple
temporary with `move ((_t.1 as Some).0)`. A tuple has no layout, so the leaf
is projected from the tuple's value. -/
/-- The `u8` value `n`. -/
noncomputable def mtU8 (n : Nat) : Val := .scalar ⟨.i8, false, BitVec.ofNat 128 n⟩
/-- `(u8, Option<u8>)`. -/
noncomputable def mtOptTy : MirTy :=
.tuple [.int .i8 false, .option (.int .i8 false)]
/-- `((u8, u8), u8)`. -/
noncomputable def mtNestTy : MirTy :=
.tuple [.tuple [.int .i8 false, .int .i8 false], .int .i8 false]
/-- `(u8, Option<[u8; 2]>)`. -/
noncomputable def mtArrTy : MirTy :=
.tuple [.int .i8 false, .option (.array (.int .i8 false) 2)]
/-- Locals `_0 = ()` and `_1 = v`. -/
noncomputable def mtLocals (v : Val) : List LocalSlot :=
[.immediate (some .unit), .immediate (some v)]
/-- The variant-field path `(_1.1 as Some).0` of `mtOptTy`, with field `1`
typed `ty1`. -/
noncomputable def mtSomePath (ty1 : MirTy) : Place :=
{ localId := 1,
projection := [.field 1 ty1, .downcast 1, .field 0 (.int .i8 false)] }
/-- Guard `step_v2_move_tuple_dispatch`: `move ((_1.1 as Some).0)` out of a
tuple local returns the payload. A tuple cannot move to memory, so routing
the move to `moveLocalPlaceV2` would refuse it. -/
theorem refute_step_v2_move_tuple_dispatch :
readPlaceV2 [.unit, mtOptTy]
(mtLocals (.tuple [mtU8 3, .optionVal (some (mtU8 5))]))
MemoryState.empty true (mtSomePath (.option (.int .i8 false))) =
.ok (.int .i8 false, some (mtU8 5),
mtLocals (.tuple [mtU8 3, .optionVal (some (mtU8 5))]),
MemoryState.empty) :=
rfl
/-- Guard `step_v2_move_tuple_downcast_keeps`: a move through a variant
leaves the tuple as it was (the copy-move reading of `moveLocalPlaceV2`), so
the field enclosing the enum stays readable. Moving the payload of `None`
faults with `.undefined`. -/
theorem refute_step_v2_move_tuple_downcast_keeps :
(match readPlaceV2 [.unit, mtOptTy]
(mtLocals (.tuple [mtU8 3, .optionVal (some (mtU8 5))]))
MemoryState.empty true (mtSomePath (.option (.int .i8 false))) with
| .ok (_, _, locals1, _) =>
locals1 = mtLocals (.tuple [mtU8 3, .optionVal (some (mtU8 5))])
| .error _ => False) ∧
(match readPlaceV2 [.unit, mtOptTy]
(mtLocals (.tuple [mtU8 3, .optionVal none]))
MemoryState.empty true (mtSomePath (.option (.int .i8 false))) with
| .error .undefined => True
| _ => False) :=
⟨rfl, trivial⟩
/-- Guard `step_v2_move_tuple_requires_downcast`: `move ((_1.0).1)` without a
variant downcast fails closed with `.unsupported` instead of deinitializing
the whole field `_1.0` and falsely faulting sibling sub-fields as
`.undefined`. -/
theorem refute_step_v2_move_tuple_requires_downcast :
(match readPlaceV2 [.unit, mtNestTy]
(mtLocals (.tuple [.tuple [mtU8 1, mtU8 2], mtU8 3]))
MemoryState.empty true
{ localId := 1,
projection := [.field 0 (.tuple [.int .i8 false, .int .i8 false]),
.field 1 (.int .i8 false)] } with
| .error .unsupported => True
| _ => False) :=
trivial
/-- Guard `step_v2_move_tuple_field_or_downcast`: a nested tuple move through
a constant index (`move (((_1.1 as Some).0)[0])`) is not modeled and fails
closed even when the path contains a downcast. -/
theorem refute_step_v2_move_tuple_field_or_downcast :
(match readPlaceV2 [.unit, mtArrTy]
(mtLocals (.tuple [mtU8 3, .optionVal (some (.array [mtU8 1, mtU8 2]))]))
MemoryState.empty true
{ localId := 1,
projection := [.field 1 (.option (.array (.int .i8 false) 2)),
.downcast 1, .field 0 (.array (.int .i8 false) 2),
.constantIndex 0 2 false] } with
| .error .unsupported => True
| _ => False) :=
trivial
/-- Guard `step_v2_move_tuple_field_type`: a path whose field `1` is typed
`u16`, not the tuple's `Option<u8>`, is refused. -/
theorem refute_step_v2_move_tuple_field_type :
(match readPlaceV2 [.unit, mtOptTy]
(mtLocals (.tuple [mtU8 3, .optionVal (some (mtU8 5))]))
MemoryState.empty true (mtSomePath (.int .i16 false)) with
| .error .unsupported => True
| _ => False) :=
trivial
/-- `(u8, Option<Vec<u8>>)`. -/
noncomputable def mtVecTy : MirTy := .tuple [dropU8, .option (.vec dropU8)]
/-- Guard `step_v2_drop_tuple_path`: `drop((_1.1 as Some).0)` of a tuple
local `(u8, Option<Vec<u8>>)` held in its slot, which drop elaboration leaves
after a `match` on a tuple temporary, runs the `Vec`'s drop glue, freeing its
buffer (allocation `1`), and leaves the tuple in place, as a move through a
variant does. -/
theorem refute_step_v2_drop_tuple_path :
(match dropProjectedV2 [.unit, mtVecTy]
(mtLocals (.tuple [mtU8 3, .optionVal (some dropVec1)])) dropMem
{ localId := 1,
projection := [.field 1 (.option (.vec dropU8)), .downcast 1,
.field 0 (.vec dropU8)] } with
| .ok (locals1, mem1) =>
.ok (locals1, (findAllocation 1 mem1.allocations).map (·.live))
| .error k => .error k) =
(.ok (mtLocals (.tuple [mtU8 3, .optionVal (some dropVec1)]), some false) :
Except FaultKind (List LocalSlot × Option Bool)) :=
rfl
/-- Recursive payload enum `{ Empty, Rec(Box<Self>) }` used for `.rodata`
active-variant and raw-pointer refutation guards. -/
noncomputable def rodataRecAdtTy : MirTy :=
.recAdt 900
(.adtEnum
⟨900, 16, 3, .isize, true, [0, 1], 0, .i8, false, 0, 1, .direct⟩
[.struct_ ⟨901, 16, 3, []⟩ [],
.struct_ ⟨902, 16, 3, [8]⟩ [.box (.recSelf 900)]])
/-- Guard `step_v2_rodata_adt_active_variant_data_only`: evaluating a
`.rodataBytes` constant of a recursive enum whose active variant owns a
`Box<Self>` fails closed with `.error .unsupported`. -/
theorem refute_step_v2_rodata_adt_active_variant_data_only :
(match evalOperandToSlotV2
[.unit]
[.immediate none]
emptyMemory
(.constant ⟨rodataRecAdtTy,
.rodataBytes
(.init 1 :: List.replicate 7 .uninit ++
[.init 8, .init 0, .init 0, .init 0,
.init 0, .init 0, .init 0, .init 0])⟩) with
| .error .unsupported => True
| _ => False) :=
trivial
/-- Canary: a heap-free non-recursive payload enum constant whose active
variant holds an `Option<u32>` (`Result<Option<u32>, ()>::Ok(Some(5))`) is
admitted by `rodataAdtVariantDataOkV2` and decodes cleanly. -/
theorem canary_rodata_adt_option_field_admitted :
let resOptTy : MirTy :=
.adtEnum
⟨920, 12, 2, .isize, true, [0, 1], 0, .i8, false, 0, 1, .direct⟩
[.struct_ ⟨921, 12, 2, [4]⟩ [.option (.int .i32 false)],
.struct_ ⟨922, 12, 2, []⟩ []]
(match evalOperandToSlotV2 [.unit] [.immediate none] emptyMemory
(.constant ⟨resOptTy,
.rodataBytes
[.init 0, .uninit, .uninit, .uninit,
.init 1, .init 0, .init 0, .init 0,
.init 5, .init 0, .init 0, .init 0]⟩) with
| .ok (_, some (.adtVal 0 (.tuple [.optionVal (some (.scalar sv))])), _, _) =>
sv.bits = BitVec.ofNat 128 5
| _ => False) :=
rfl
/-- Guard `step_v2_rodata_ref_pointee_ok`: evaluating a `.rodataRef` shared
reference to a recursive enum whose active variant owns a `Box<Self>` fails
closed with `.error .unsupported`. -/
theorem refute_step_v2_rodata_ref_pointee_ok :
(match evalRodataRefConstV2
(.ref .shared rodataRecAdtTy)
(.init 1 :: List.replicate 7 .uninit ++
[.init 8, .init 0, .init 0, .init 0,
.init 0, .init 0, .init 0, .init 0])
3 0 none
[.immediate none] emptyMemory with
| .error .unsupported => True
| _ => False) :=
trivial
/-- Guard `step_v2_rodata_raw_ptr_data_ty_only`: evaluating a `.rodataRef`
raw pointer to a recursive enum fails closed with `.error .unsupported` even
when the active variant is heap-free. -/
theorem refute_step_v2_rodata_raw_ptr_data_ty_only :
(match evalRodataRefConstV2
(.rawPtr .shared rodataRecAdtTy)
(.init 0 :: List.replicate 15 .uninit)
3 0 none
[.immediate none] emptyMemory with
| .error .unsupported => True
| _ => False) :=
trivial
/-- Guard `core_scalar_clone_prim_only`: `CoreCallOp.scalarClone` fails closed
with `.error .unsupported` on non-primitive types such as `.unit` even when
backed by a valid shared reference. -/
theorem refute_core_scalar_clone_prim_only :
let m : MemoryState :=
{ allocations := [{
allocId := 1
alignLog2 := 0
mutability := .shared
bytes := [.init 0]
live := true }]
, nextAllocId := 2 }
execCoreContractOp m (.scalarClone .unit)
[(.ref .shared .unit, .ptr ⟨some 1, 0, .isize⟩)] .unit =
.error .unsupported :=
rfl
/-- Guard `core_scalar_clone_ty_match`: `CoreCallOp.scalarClone` fails closed
with `.error .unsupported` when the receiver pointee or destination type
disagrees with the operation's primitive type. -/
theorem refute_core_scalar_clone_ty_match :
let m : MemoryState :=
{ allocations := [{
allocId := 1
alignLog2 := 1
mutability := .shared
bytes := [.init 1, .init 0]
live := true }]
, nextAllocId := 2 }
execCoreContractOp m (.scalarClone (.int .i8 false))
[(.ref .shared (.int .i16 false), .ptr ⟨some 1, 0, .isize⟩)]
(.int .i8 false) = .error .unsupported ∧
execCoreContractOp m (.scalarClone (.int .i8 false))
[(.ref .shared (.int .i8 false), .ptr ⟨some 1, 0, .isize⟩)]
(.int .i16 false) = .error .unsupported :=
⟨rfl, rfl⟩
/-- Guard `core_scalar_clone_invalid_bytes`: `CoreCallOp.scalarClone` faults
with `.error .undefined` when `loadIndirectV2` returns `.ok none` on
uninitialized bytes. -/
theorem refute_core_scalar_clone_invalid_bytes :
let m : MemoryState :=
{ allocations := [{
allocId := 1
alignLog2 := 0
mutability := .shared
bytes := [.uninit]
live := true }]
, nextAllocId := 2 }
execCoreContractOp m (.scalarClone .bool)
[(.ref .shared .bool, .ptr ⟨some 1, 0, .isize⟩)]
.bool = .error .undefined :=
rfl
/-- Guard `step_v2_move_option_heap_keeps_discriminant`: moving
`((_1 as Some).0)` out of an immediate heap-owning `Option<Box<u8>>` local
leaves `_1` intact so a subsequent drop-elaborated `discriminant(_1)` returns
`1` instead of faulting `.undefined`, while moving out of a non-heap
`Option<u32>` still deinitializes `_1`. -/
theorem refute_step_v2_move_option_heap_keeps_discriminant :
let optBoxTy : MirTy := .option (.box (.int .i8 false))
let optU32Ty : MirTy := .option (.int .i32 false)
let boxVal : Val := .ptr ⟨some 1, 0, .isize⟩
let mem : MemoryState :=
{ allocations := [{
allocId := 1
alignLog2 := 0
mutability := .mut
bytes := [.init 7]
live := true }]
, nextAllocId := 2 }
(match readPlaceV2 [.unit, optBoxTy]
[.immediate none, .immediate (some (.optionVal (some boxVal)))]
mem true ⟨1, [.downcast 1, .field 0 (.box (.int .i8 false))]⟩ with
| .ok (_, _, locals1, mem1) =>
match evalRvalueV2 [.unit, optBoxTy] locals1 mem1 (.int .isize true)
(.discriminant ⟨1, []⟩) with
| .ok (v, _, _) => Except.ok v
| .error k => Except.error k
| .error k => Except.error k) = Except.ok (Val.scalar ⟨.isize, true, 1⟩) ∧
(match readPlaceV2 [.unit, optU32Ty]
[.immediate none, .immediate (some (.optionVal (some (Val.scalar ⟨.i32, false, 9⟩))))]
MemoryState.empty true ⟨1, [.downcast 1, .field 0 (.int .i32 false)]⟩ with
| .ok (_, _, locals1, mem1) =>
match evalRvalueV2 [.unit, optU32Ty] locals1 mem1 (.int .isize true)
(.discriminant ⟨1, []⟩) with
| .ok (v, _, _) => Except.ok v
| .error k => Except.error k
| .error k => Except.error k) = Except.error .undefined :=
⟨rfl, rfl⟩
end GuardMutation