| -- 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. | |
| -- anneal-trust-tier: candidate:mir_semantics | |
| module | |
| prelude | |
| public import Init.NotationExtra | |
| public import Init.Data.BitVec.BasicAux | |
| public import Init.Control.Except | |
| public import Trusted.MirAst | |
| public import Trusted.MirModel | |
| public import Trusted.MirSemantics.Ops | |
| public import Trusted.MirSemantics.Enum | |
| public import Trusted.MirSemantics.State | |
| public import Trusted.MirSemantics.Layout | |
| public import Trusted.MirSemantics.Memory | |
| public import Trusted.MirSemantics.Bytes | |
| public import Trusted.MirSemantics.CoreContracts | |
| public import Trusted.MirSemantics.AllocContracts | |
| @[expose] public section | |
| namespace Trusted.MirSemantics | |
| open Trusted.MirAst | |
| /-! | |
| # Small-Step Execution Rules (`Trusted.MirSemantics.Step`) | |
| Constant, operand, rvalue, place-write, statement, terminator, and single-step | |
| transition rules (`evalStep`) for $M_{\text{anneal}}$. | |
| -/ | |
| /-- Stage 1 of operand evaluation (`eval_operand` and `eval_place_to_op` in | |
| `compiler/rustc_const_eval/src/interpret/operand.rs`, `rust-lang/rust` | |
| `8144389c895da997dbdecaa635e41d6a50be6ffd`, and | |
| `Miri.Interpreter.OperandMachine.evalOperand` in | |
| `vendor/lean-miri/Miri/Interpreter/OperandMachine.lean` with opt-in | |
| `deinitMovedPlace = true`): | |
| > "let op = match mir_op { | |
| > // FIXME: do some more logic on `move` to invalidate the old location | |
| > &Copy(place) | &Move(place) => self.eval_place_to_op(place, layout)?, | |
| > ... | |
| > Constant(constant) => { | |
| > ... self.eval_mir_constant(&c, constant.span, layout)? | |
| > } | |
| > };" | |
| > (`compiler/rustc_const_eval/src/interpret/operand.rs`, `rust-lang/rust` | |
| > `8144389c895da997dbdecaa635e41d6a50be6ffd`) | |
| > | |
| > "let mut op = self.local_to_op( | |
| > place.local, | |
| > if place.projection.is_empty() { layout } else { None }, | |
| > )?; | |
| > for elem in place.projection.iter() { | |
| > op = self.project(&op, elem)? | |
| > }" | |
| > (`compiler/rustc_const_eval/src/interpret/operand.rs`, `rust-lang/rust` | |
| > `8144389c895da997dbdecaa635e41d6a50be6ffd`) | |
| Matching `eval_place_to_op`, local bounds and liveness (`.dead` -> UB) are | |
| checked before inspecting `place.projection` (`.unsupported` on non-empty | |
| projections). Note that upstream `eval_operand` currently leaves move | |
| invalidation unimplemented (as recorded in the `FIXME` above). As a | |
| deliberate, conservative over-approximation (sound because deinitializing can | |
| only introduce faults on subsequent reads), `evalOperandToSlot` resolves an | |
| `Operand` to `(ty : MirTy, optVal : Option Val, locals' : List LocalSlot, | |
| mem' : MemoryState)` without yet requiring `optVal` to be initialized | |
| (`some v`), and deinitializes moved non-ZST locals. | |
| An `.indirect place` local is read from memory with `loadIndirect` | |
| (`local_to_op` returns `Operand::Indirect`, and the caller's read checks the | |
| bytes). The caller's static type check `tyOk` runs before that read and before | |
| any move deinitialization, so an ill-typed use of an `.indirect` local faults | |
| with `.unsupported` even when its memory is dead, out of bounds, or holds | |
| invalid bytes. This matches `lean-miri`, where `OperandMachine.evalOperand` | |
| resolves an indirect place without touching memory, and the consumer checks | |
| the type (`MemoryOperand.readImmediate`'s primitive-readability check, or | |
| `Place.copyRuntimePlaceNoValidate`'s layout-compatibility check) before | |
| reading the bytes and deinitializing a moved place. Resolving an `.immediate` | |
| local or a constant reads no memory, so for those operands the caller checks | |
| the type after resolution with the same result. | |
| - `.copy place`: reads `(ty, optVal)` without mutating `locals` or `mem`. | |
| - `.move place` on an `.immediate` local: reads `(ty, optVal)` and | |
| conservatively transitions `locals[place.localId]` to `liveUninitSlot ty` | |
| (preserving `.immediate (some .unit)` on `MirTy.unit` and | |
| `.immediate (some (.enumVal ety 0))` on admitted 1-variant `.zeroSized` | |
| `MirTy.enum`, and setting all other local types to `.immediate none`, | |
| matching `OperandMachine.evalOperand` with opt-in `deinitMovedPlace = true`). | |
| - `.move place` on an `.indirect mplace` local: reads `(ty, optVal)` and marks | |
| the value's bytes at `mplace` uninitialized (`deinitIndirect`; zero-sized | |
| types have no bytes, so their unique value survives as in the immediate | |
| case). | |
| - `.constant c`: decodes constant literal without mutating `locals` or `mem`. | |
| -/ | |
| noncomputable def evalOperandToSlot (bodyLocals : List MirTy) | |
| (locals : List LocalSlot) (mem : MemoryState) (tyOk : MirTy → Bool) : | |
| Operand → | |
| Except FaultKind (MirTy × Option Val × List LocalSlot × MemoryState) | |
| | .copy place => | |
| match getElem? bodyLocals place.localId, | |
| getElem? locals place.localId with | |
| | some _, some .dead => .error .undefined | |
| | some ty, some (.immediate optVal) => | |
| if !place.projection.isEmpty then | |
| .error .unsupported | |
| else | |
| .ok (ty, optVal, locals, mem) | |
| | some ty, some (.indirect mplace) => | |
| if !place.projection.isEmpty then | |
| .error .unsupported | |
| else if !tyOk ty then | |
| .error .unsupported | |
| else | |
| match loadIndirect mem ty mplace with | |
| | .ok optVal => .ok (ty, optVal, locals, mem) | |
| | .error k => .error k | |
| | _, _ => .error .unsupported | |
| | .move place => | |
| match getElem? bodyLocals place.localId, | |
| getElem? locals place.localId with | |
| | some _, some .dead => .error .undefined | |
| | some ty, some (.immediate optVal) => | |
| if !place.projection.isEmpty then | |
| .error .unsupported | |
| else | |
| match setElem? locals place.localId (liveUninitSlot ty) with | |
| | some locals' => .ok (ty, optVal, locals', mem) | |
| | none => .error .unsupported | |
| | some ty, some (.indirect mplace) => | |
| if !place.projection.isEmpty then | |
| .error .unsupported | |
| else if !tyOk ty then | |
| .error .unsupported | |
| else | |
| match loadIndirect mem ty mplace with | |
| | .error k => .error k | |
| | .ok optVal => | |
| match deinitIndirect mem ty mplace with | |
| | .ok mem' => .ok (ty, optVal, locals, mem') | |
| | .error k => .error k | |
| | _, _ => .error .unsupported | |
| | .constant c => | |
| match evalConstLit c.ty c.lit with | |
| | .ok v => .ok (c.ty, some v, locals, mem) | |
| | .error k => .error k | |
| /-- Stage 2 of operand evaluation (`evalOperandToSlot` followed by | |
| `read_immediate` in | |
| `compiler/rustc_const_eval/src/interpret/operand.rs`, `rust-lang/rust` | |
| `8144389c895da997dbdecaa635e41d6a50be6ffd`, and | |
| `Miri.Interpreter.MemoryOperand.readImmediate` in | |
| `vendor/lean-miri/Miri/Interpreter/MemoryOperand.lean`): | |
| > "if !matches!( | |
| > op.layout().backend_repr, | |
| > BackendRepr::Scalar(abi::Scalar::Initialized { .. }) | |
| > | BackendRepr::ScalarPair { ... } | |
| > ) { | |
| > span_bug!( | |
| > self.cur_span(), | |
| > \"primitive read not possible for type: {}\", | |
| > op.layout().ty | |
| > ); | |
| > } | |
| > let imm = self.read_immediate_raw(op)?.right().unwrap(); | |
| > if matches!(*imm, Immediate::Uninit) { | |
| > throw_ub!(InvalidUninitBytes(None)); | |
| > }" | |
| > (`compiler/rustc_const_eval/src/interpret/operand.rs`, `rust-lang/rust` | |
| > `8144389c895da997dbdecaa635e41d6a50be6ffd`) | |
| Used by `.binaryOp`, `.unaryOp`, and `.switchInt`. Checks | |
| `isPrimitiveReadableTy ty` on the static type first (`.unsupported` on | |
| non-primitives such as `.unit`; `evalOperandToSlot` performs this check before | |
| reading an `.indirect` local's memory), and then checks initialization (`optVal | |
| = some v`, faulting with `.undefined` on uninitialized storage). -/ | |
| noncomputable def evalPrimitiveOperand (bodyLocals : List MirTy) | |
| (locals : List LocalSlot) (mem : MemoryState) (opnd : Operand) : | |
| Except FaultKind (Val × List LocalSlot × MemoryState) := | |
| match evalOperandToSlot bodyLocals locals mem isPrimitiveReadableTy opnd with | |
| | .error k => .error k | |
| | .ok (ty, optVal, locals', mem') => | |
| if !isPrimitiveReadableTy ty then | |
| .error .unsupported | |
| else | |
| match optVal with | |
| | some v => .ok (v, locals', mem') | |
| | none => .error .undefined | |
| /-- Result of `Rvalue.discriminant` on a local of admitted fieldless enum type | |
| `ety` whose value is `optVal`: the variant's declared discriminant as a scalar | |
| of `(ety.discrWidth, ety.discrSigned)`, with `locals` and `mem` unchanged. | |
| Matches `read_discriminant` and `discriminant_for_variant` in | |
| `compiler/rustc_const_eval/src/interpret/discriminant.rs` (`rust-lang/rust` | |
| `8144389c895da997dbdecaa635e41d6a50be6ffd`) and `Miri.Interpreter.Discriminant`: | |
| > "let discr_layout = self.layout_of(ty.discriminant_ty(*self.tcx))?; | |
| > let discr_value = match ty.discriminant_for_variant(*self.tcx, variant) { | |
| > Some(discr) => { | |
| > ... | |
| > assert_eq!(discr.ty, discr_layout.ty); | |
| > Scalar::from_uint(discr.val, discr_layout.size) | |
| > } | |
| > ... | |
| > }; | |
| > interp_ok(ImmTy::from_scalar(discr_value, discr_layout))" | |
| An uninitialized (`none`) scalar-tagged enum value faults with `.error | |
| .undefined`, whereas an inhabited 1-variant ZST enum (`ety.tagRepr = | |
| .zeroSized`, `Variants::Single { index: 0 }`) returns `ety.discriminants[0]` | |
| without reading tag bytes. -/ | |
| noncomputable def evalDiscriminantOfVal (ety : EnumTy) (optVal : Option Val) | |
| (locals : List LocalSlot) (mem : MemoryState) : | |
| Except FaultKind (Val × List LocalSlot × MemoryState) := | |
| if !enumAdmitted ety then | |
| .error .unsupported | |
| else | |
| -- For 1-variant `.zeroSized` enums, `Miri`'s `readDiscriminant` | |
| -- (`Variants::Single { index: 0 }`) returns variant `0` without reading | |
| -- tag bytes even if a slot holds `.immediate none` (`Uninit`), preserving | |
| -- universal 1-step lockstep over arbitrary `FrameState`s. | |
| match ety.tagRepr, optVal with | |
| | .zeroSized, none => | |
| match getElem? ety.discriminants 0 with | |
| | some disc => | |
| .ok (.scalar ⟨ety.discrWidth, ety.discrSigned, | |
| truncateBits ety.discrWidth (BitVec.ofNat 128 disc)⟩, locals, mem) | |
| | none => .error .unsupported | |
| | .zeroSized, some (.enumVal ety' v) => | |
| if EnumTy.beq ety ety' && Nat.beq v 0 then | |
| match getElem? ety.discriminants 0 with | |
| | some disc => | |
| .ok (.scalar ⟨ety.discrWidth, ety.discrSigned, | |
| truncateBits ety.discrWidth (BitVec.ofNat 128 disc)⟩, locals, mem) | |
| | none => .error .unsupported | |
| else | |
| .error .unsupported | |
| | .zeroSized, some _ => .error .unsupported | |
| | .scalar _ _, none => .error .undefined | |
| | .scalar _ _, some (.enumVal ety' v) => | |
| if EnumTy.beq ety ety' && Nat.blt v ety.discriminants.length then | |
| match getElem? ety.discriminants v with | |
| | some disc => | |
| .ok (.scalar ⟨ety.discrWidth, ety.discrSigned, | |
| truncateBits ety.discrWidth (BitVec.ofNat 128 disc)⟩, locals, mem) | |
| | none => .error .unsupported | |
| else | |
| .error .unsupported | |
| | .scalar _ _, some _ => .error .unsupported | |
| /-- Result of `Rvalue.discriminant` at destination type `dstTy` on a payload | |
| enum with layout `l` whose value is `optVal`: the held variant's declared | |
| discriminant as a scalar of the enum's discriminant type | |
| (`discriminant_for_variant`, | |
| `compiler/rustc_const_eval/src/interpret/discriminant.rs:221-240`, | |
| `rust-lang/rust` `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`), with `locals` | |
| and `mem` unchanged. An uninitialized value, including one whose tag did | |
| not decode (`adtDecodeVariantV2`), is `.undefined`. -/ | |
| noncomputable def evalAdtDiscriminantOfVal (l : AdtEnumLayout) (dstTy : MirTy) | |
| (optVal : Option Val) (locals : List LocalSlot) (mem : MemoryState) : | |
| Except FaultKind (Val × List LocalSlot × MemoryState) := | |
| if !MirTy.beq dstTy (.int l.discrWidth l.discrSigned) then | |
| .error .unsupported | |
| else | |
| match optVal with | |
| | none => .error .undefined | |
| | some (.adtVal i _) => | |
| match getElem? l.discriminants i with | |
| | some d => | |
| .ok (.scalar ⟨l.discrWidth, l.discrSigned, | |
| truncateBits l.discrWidth (BitVec.ofNat 128 d)⟩, locals, mem) | |
| | none => .error .unsupported | |
| | some _ => .error .unsupported | |
| /-- Result of `Rvalue.discriminant` on a local of type `core::cmp::Ordering` | |
| whose value is `optVal`: the `i8` discriminant (`orderingTagBits`: `-1_i8`, | |
| `0_i8`, or `1_i8`) as a scalar of `(.i8, true)`, with `locals` and `mem` | |
| unchanged. `Ordering` is a `#[repr(i8)]` fieldless enum whose tag is its | |
| discriminant, so this matches `read_discriminant` and | |
| `discriminant_for_variant` as `evalDiscriminantOfVal` does for scalar-tagged | |
| enums; an uninitialized (`none`) value faults with `.error .undefined`. -/ | |
| noncomputable def evalOrderingDiscriminantOfVal (optVal : Option Val) | |
| (locals : List LocalSlot) (mem : MemoryState) : | |
| Except FaultKind (Val × List LocalSlot × MemoryState) := | |
| match optVal with | |
| | none => .error .undefined | |
| | some (.ordering ord) => | |
| .ok (.scalar ⟨.i8, true, BitVec.ofNat 128 (orderingTagBits ord)⟩, locals, | |
| mem) | |
| | some _ => .error .unsupported | |
| /-- Evaluate `Rvalue.discriminant` on an `Option<T>` value slot, returning | |
| `0isize` for `None` and `1isize` for `Some(_)`. -/ | |
| noncomputable def evalOptionDiscriminantOfVal (optVal : Option Val) | |
| (locals : List LocalSlot) (mem : MemoryState) : | |
| Except FaultKind (Val × List LocalSlot × MemoryState) := | |
| match optVal with | |
| | none => .error .undefined | |
| | some (.optionVal optV) => | |
| let idx := match optV with | none => 0 | some _ => 1 | |
| .ok (.scalar ⟨.isize, true, BitVec.ofNat 128 idx⟩, locals, mem) | |
| | some _ => .error .unsupported | |
| /-- Evaluate an `Rvalue` for a destination of type `dstTy`, following the RHS | |
| cases of `eval_rvalue_into_place` | |
| (`compiler/rustc_const_eval/src/interpret/step.rs`, `rust-lang/rust` | |
| `8144389c895da997dbdecaa635e41d6a50be6ffd`) and | |
| `Miri.Interpreter.Rvalue.evalRvalueIntoPlace` (`Miri/Interpreter/Rvalue.lean`), | |
| together with Anneal's conservative `Operand.move` deinitialization | |
| (`evalOperandToSlot`). `evalStatement` evaluates this RHS before checking | |
| destination liveness and writing `dst` in `writePlace`, matching `rustc` and | |
| `lean-miri` for unprojected sized locals (where `local_to_place` does not check | |
| liveness and `DeadLocal` fires at write time; an unmodeled RHS can return | |
| `.unsupported` before write-time `DeadLocal`, and `.use` checks uninitialized | |
| input before writing while `rustc`'s `copy_op` validates after writing, with | |
| both producing `.undefined`): | |
| - `.use opnd`: resolves `(srcTy, optVal, locals₁, mem₁) ← evalOperandToSlot`, | |
| checks `srcTy = dstTy` (`copyRuntimePlaceNoValidate`; for an `.indirect` | |
| local, `evalOperandToSlot` checks it before reading memory), then checks | |
| `optVal = some v` (validity check in `copy_op` / `copyRuntimePlace`). | |
| - `.binaryOp op lhs rhs`: evaluates `lhs` and then `rhs` left-to-right via | |
| `evalPrimitiveOperand` (threading `locals₁` and `mem₁` from `lhs` into | |
| `rhs`), then applies `evalBinOp`. | |
| - `.unaryOp op opnd`: evaluates `opnd` via `evalPrimitiveOperand`, then applies | |
| `evalUnOp`. | |
| - `.cast .intToInt opnd castTy`: resolves `(srcTy, optVal, locals₁, mem₁) ← | |
| evalOperandToSlot`, checks that `srcTy` is integer-like (`isIntLikeTy`, | |
| matching `Miri.Interpreter.Cast.cast`'s source-type validity check, which | |
| precedes `read_immediate`), then checks `optVal = some v` (`read_immediate`'s | |
| uninitialized check), and applies `evalIntToIntCast v castTy`, which rejects | |
| targets other than integers and `char`. (`castTypesValid` guarantees | |
| `castTy = dstTy`.) | |
| - `.discriminant place`: reads an unprojected local of admitted fieldless enum | |
| type `.enum ety` or of type `.ordering` (from its `.immediate` value or, for | |
| an `.indirect` local, with `loadIndirect`) and returns | |
| `evalDiscriminantOfVal ety` or `evalOrderingDiscriminantOfVal`. Reading | |
| `.discriminant` from a `.dead` local faults with `.error .undefined`. -/ | |
| noncomputable def evalRvalue (bodyLocals : List MirTy) (locals : List LocalSlot) | |
| (mem : MemoryState) (dstTy : MirTy) : | |
| Rvalue → Except FaultKind (Val × List LocalSlot × MemoryState) | |
| | .use opnd => | |
| match evalOperandToSlot bodyLocals locals mem | |
| (fun srcTy => MirTy.beq srcTy dstTy) opnd with | |
| | .error k => .error k | |
| | .ok (srcTy, optVal, locals₁, mem₁) => | |
| if !(MirTy.beq srcTy dstTy) then | |
| .error .unsupported | |
| else | |
| match optVal with | |
| | some v => .ok (v, locals₁, mem₁) | |
| | none => .error .undefined | |
| | .binaryOp op lhs rhs => | |
| match evalPrimitiveOperand bodyLocals locals mem lhs with | |
| | .error k => .error k | |
| | .ok (lVal, locals₁, mem₁) => | |
| match evalPrimitiveOperand bodyLocals locals₁ mem₁ rhs with | |
| | .error k => .error k | |
| | .ok (rVal, locals₂, mem₂) => | |
| match evalBinOp op lVal rVal with | |
| | .error k => .error k | |
| | .ok res => .ok (res, locals₂, mem₂) | |
| | .unaryOp op opnd => | |
| match evalPrimitiveOperand bodyLocals locals mem opnd with | |
| | .error k => .error k | |
| | .ok (v, locals₁, mem₁) => | |
| match evalUnOp op v with | |
| | .error k => .error k | |
| | .ok res => .ok (res, locals₁, mem₁) | |
| | .cast .intToInt opnd castTy => | |
| match evalOperandToSlot bodyLocals locals mem isIntLikeTy opnd with | |
| | .error k => .error k | |
| | .ok (srcTy, optVal, locals₁, mem₁) => | |
| if !isIntLikeTy srcTy then | |
| .error .unsupported | |
| else | |
| match optVal with | |
| | none => .error .undefined | |
| | some v => | |
| match evalIntToIntCast v castTy with | |
| | .error k => .error k | |
| | .ok res => .ok (res, locals₁, mem₁) | |
| | .discriminant place => | |
| match getElem? bodyLocals place.localId, | |
| getElem? locals place.localId with | |
| | some _, some .dead => .error .undefined | |
| | some srcTy, some (.immediate optVal) => | |
| if !place.projection.isEmpty then | |
| .error .unsupported | |
| else | |
| match srcTy with | |
| | .enum ety => evalDiscriminantOfVal ety optVal locals mem | |
| | .ordering => evalOrderingDiscriminantOfVal optVal locals mem | |
| | _ => .error .unsupported | |
| | some srcTy, some (.indirect mplace) => | |
| if !place.projection.isEmpty then | |
| .error .unsupported | |
| else | |
| match srcTy with | |
| | .enum ety => | |
| match loadIndirect mem srcTy mplace with | |
| | .error k => .error k | |
| | .ok optVal => evalDiscriminantOfVal ety optVal locals mem | |
| | .ordering => | |
| match loadIndirect mem srcTy mplace with | |
| | .error k => .error k | |
| | .ok optVal => evalOrderingDiscriminantOfVal optVal locals mem | |
| | _ => .error .unsupported | |
| | _, _ => .error .unsupported | |
| | _ => .error .unsupported | |
| /-- Write `val` into an unprojected `dst : Place` of known `dstTy : MirTy` in | |
| `locals`: checks `checkVal val dstTy` first (matching | |
| `Rvalue.assertRvalueLayout`), then checks `dst` liveness (matching | |
| `Place.writePlaceImmediate`). An `.immediate` local takes `val` directly; an | |
| `.indirect mplace` local stores `val`'s bytes at `mplace` (`storeIndirect`, | |
| matching `write_immediate_no_validate`'s `Left(mplace)` case in | |
| `compiler/rustc_const_eval/src/interpret/place.rs`, `rust-lang/rust` | |
| `8144389c895da997dbdecaa635e41d6a50be6ffd`). -/ | |
| noncomputable def writePlace (locals : List LocalSlot) (mem : MemoryState) | |
| (dstLocalId : LocalId) (dstTy : MirTy) (val : Val) : | |
| Except FaultKind (List LocalSlot × MemoryState) := | |
| if !checkVal val dstTy then | |
| .error .unsupported | |
| else | |
| match getElem? locals dstLocalId with | |
| | none => .error .unsupported | |
| | some .dead => .error .undefined | |
| | some (.immediate _) => | |
| match setElem? locals dstLocalId (.immediate (some val)) with | |
| | some locals' => .ok (locals', mem) | |
| | none => .error .unsupported | |
| | some (.indirect mplace) => | |
| match storeIndirect mem dstTy mplace val with | |
| | .ok mem' => .ok (locals, mem') | |
| | .error k => .error k | |
| | some (.partialTuple _) => .error .unsupported | |
| /-- Release the storage of the replaced local value `old`, matching | |
| `deallocate_local` in `compiler/rustc_const_eval/src/interpret/stack.rs` | |
| (`rust-lang/rust` `8144389c895da997dbdecaa635e41d6a50be6ffd`): | |
| > "fn deallocate_local(&mut self, local: LocalValue<M::Provenance>) -> | |
| > InterpResult<'tcx> { | |
| > if let LocalValue::Live(Operand::Indirect(MemPlace { ptr, .. })) = local | |
| > { | |
| > ... | |
| > self.deallocate_ptr(ptr, None, MemoryKind::Stack)?; | |
| > }; | |
| > interp_ok(()) | |
| > }" -/ | |
| noncomputable def deallocateLocal (mem : MemoryState) : | |
| LocalSlot → Except FaultKind MemoryState | |
| | .indirect mplace => deallocateStack mem mplace | |
| | _ => .ok mem | |
| /-- Evaluate a single `StatementKind` in `frame`, matching `eval_statement` in | |
| `compiler/rustc_const_eval/src/interpret/step.rs` and `storage_live` / | |
| `storage_dead` in `compiler/rustc_const_eval/src/interpret/stack.rs` | |
| (`rust-lang/rust` `8144389c895da997dbdecaa635e41d6a50be6ffd`): | |
| > "pub fn eval_statement(&mut self, stmt: &mir::Statement<'tcx>) -> | |
| > InterpResult<'tcx> { | |
| > ... | |
| > match &stmt.kind { | |
| > Assign((place, rvalue)) => self.eval_rvalue_into_place(rvalue, | |
| > *place)?, | |
| > ... | |
| > StorageLive(local) => { self.storage_live(*local)?; } | |
| > StorageDead(local) => { self.storage_dead(*local)?; } | |
| > ... | |
| > } | |
| > }" | |
| > (`compiler/rustc_const_eval/src/interpret/step.rs`, `rust-lang/rust` | |
| > `8144389c895da997dbdecaa635e41d6a50be6ffd`) | |
| > | |
| > "// If the local is already live, deallocate its old memory. | |
| > let old = mem::replace(&mut self.frame_mut().locals[local].value, | |
| > local_val); | |
| > self.deallocate_local(old)?;" | |
| > (`storage_live_dyn`, `compiler/rustc_const_eval/src/interpret/stack.rs`) | |
| > | |
| > "assert!(local != mir::RETURN_PLACE, \"Cannot make return place dead\"); | |
| > ... | |
| > // If the local is already dead, this is a NOP. | |
| > let old = mem::replace(&mut self.frame_mut().locals[local].value, | |
| > LocalValue::Dead); | |
| > self.deallocate_local(old)?;" | |
| > (`storage_dead`, `compiler/rustc_const_eval/src/interpret/stack.rs`, | |
| > `rust-lang/rust` `8144389c895da997dbdecaa635e41d6a50be6ffd`) | |
| - `.storageLive localId` sets `locals[localId] := liveUninitSlot localTy` for | |
| any in-bounds `localId < frame.locals.length` (and faults with `.unsupported` | |
| on out-of-bounds `localId`), then deallocates the old value's storage | |
| (`deallocateLocal`). | |
| - `.storageDead 0` or out-of-bounds `.storageDead localId` faults with | |
| `.unsupported` (`StackError.cannotMakeReturnPlaceDead` / | |
| `StackError.invalidLocal`); otherwise `.storageDead localId` sets | |
| `locals[localId] := .dead` and deallocates the old value's storage. | |
| - `.assign dst rvalue` resolves `dst`'s local bounds and `dstTy` first, then | |
| evaluates `rvalue` (yielding `(val, localsAfterRval, memAfterRval)`), then | |
| checks `checkVal` and `dst` liveness in `writePlace`, matching `rustc` and | |
| `lean-miri` for unprojected sized locals (where `local_to_place` does not | |
| check liveness and `DeadLocal` fires at write time; an unmodeled RHS can | |
| fault `.unsupported` before write-time `DeadLocal`, and `.use` checks | |
| uninitialized input before writing while `rustc`'s `copy_op` validates after | |
| writing, both producing `.undefined`). | |
| - `.placeMention _` faults with `.unsupported`: Profile v1 does not model | |
| projected places. -/ | |
| noncomputable def evalStatement (body : Body) (frame : FrameState) | |
| (mem : MemoryState) (callerMem : CallerMemory) (stmt : StatementKind) : | |
| StepResult State TerminalOut := | |
| match stmt with | |
| | .nop => | |
| .step { | |
| frames := [{ frame with stmtIdx := frame.stmtIdx + 1 }] | |
| callerMem | |
| mem | |
| } | |
| | .storageLive localId => | |
| match getElem? body.locals localId with | |
| | none => .fault .unsupported | |
| | some localTy => | |
| match getElem? frame.locals localId with | |
| | none => .fault .unsupported | |
| | some old => | |
| match setElem? frame.locals localId (liveUninitSlot localTy) with | |
| | none => .fault .unsupported | |
| | some locals' => | |
| match deallocateLocal mem old with | |
| | .error k => .fault k | |
| | .ok mem' => | |
| .step { | |
| frames := [{ | |
| frame with | |
| stmtIdx := frame.stmtIdx + 1 | |
| locals := locals' | |
| }] | |
| callerMem | |
| mem := mem' | |
| } | |
| | .storageDead localId => | |
| if Nat.beq localId 0 then | |
| .fault .unsupported | |
| else | |
| match getElem? frame.locals localId with | |
| | none => .fault .unsupported | |
| | some old => | |
| match setElem? frame.locals localId .dead with | |
| | none => .fault .unsupported | |
| | some locals' => | |
| match deallocateLocal mem old with | |
| | .error k => .fault k | |
| | .ok mem' => | |
| .step { | |
| frames := [{ | |
| frame with | |
| stmtIdx := frame.stmtIdx + 1 | |
| locals := locals' | |
| }] | |
| callerMem | |
| mem := mem' | |
| } | |
| | .assign dst rvalue => | |
| if !dst.projection.isEmpty then | |
| .fault .unsupported | |
| else | |
| match getElem? body.locals dst.localId with | |
| | none => .fault .unsupported | |
| | some dstTy => | |
| match evalRvalue body.locals frame.locals mem dstTy rvalue with | |
| | .error k => .fault k | |
| | .ok (val, localsAfterRval, memAfterRval) => | |
| match writePlace localsAfterRval memAfterRval dst.localId dstTy | |
| val with | |
| | .error k => .fault k | |
| | .ok (localsAfterWrite, memAfterWrite) => | |
| .step { | |
| frames := [{ | |
| frame with | |
| stmtIdx := frame.stmtIdx + 1 | |
| locals := localsAfterWrite | |
| }] | |
| callerMem | |
| mem := memAfterWrite | |
| } | |
| | .placeMention _ | .unsupported => .fault .unsupported | |
| /-- Evaluate a `SwitchTargets` branch list against discriminant bits `discrBits` | |
| at width `w`, matching `SwitchInt` in | |
| `compiler/rustc_const_eval/src/interpret/step.rs` (`rust-lang/rust` | |
| `8144389c895da997dbdecaa635e41d6a50be6ffd`), `ScalarInt::try_from_uint` in | |
| `compiler/rustc_middle/src/ty/consts/int.rs`, and `compareSwitchCase` | |
| (`Scalar.fromUInt` -> `ScalarInt.tryFromUInt`) in | |
| `Miri.Interpreter.ExecutionMachine.stepHooks` | |
| (`vendor/lean-miri/Miri/Interpreter/ExecutionMachine.lean`): | |
| > "for (const_int, target) in targets.iter() { | |
| > ... | |
| > let res = self.binary_op( | |
| > mir::BinOp::Eq, | |
| > &discr, | |
| > &ImmTy::from_uint(const_int, discr.layout), | |
| > )?; | |
| > if res.to_scalar().to_bool()? { | |
| > target_block = target; | |
| > break; | |
| > } | |
| > }" | |
| > (`compiler/rustc_const_eval/src/interpret/step.rs`, `rust-lang/rust` | |
| > `8144389c895da997dbdecaa635e41d6a50be6ffd`) | |
| > "pub fn try_from_uint(i: impl Into<u128>, size: Size) -> Option<Self> { | |
| > let (r, overflow) = Self::truncate_from_uint(i, size); | |
| > if overflow { None } else { Some(r) } | |
| > }" | |
| > (`compiler/rustc_middle/src/ty/consts/int.rs`, `rust-lang/rust` | |
| > `8144389c895da997dbdecaa635e41d6a50be6ffd`) | |
| If `caseBits` overflows width `w` (`truncateBits w caseBits != caseBits`), | |
| `Scalar.fromUInt` throws `.scalarInt (.integerConversionOverflow _)`, which | |
| `ScalarOps.scalarError` maps to `.invalidProgram` (`.error .unsupported`); | |
| otherwise `evalSwitchBranches` compares `truncateBits w discrBits == | |
| truncateBits w caseBits` up to the first matching branch, returning `.ok | |
| otherwise` when no branch matches. -/ | |
| noncomputable def evalSwitchBranches (w : IntWidth) (discrBits : BitVec 128) | |
| (otherwise : BasicBlockId) : | |
| List (BitVec 128 × BasicBlockId) → Except FaultKind BasicBlockId | |
| | [] => .ok otherwise | |
| | (caseBits, target) :: rest => | |
| if truncateBits w caseBits != caseBits then | |
| .error .unsupported | |
| else if truncateBits w discrBits == truncateBits w caseBits then | |
| .ok target | |
| else | |
| evalSwitchBranches w discrBits otherwise rest | |
| /-- Evaluate a `SwitchTargets` branch list against a boolean discriminant | |
| `discr`, matching `compareSwitchCase` in | |
| `Miri.Interpreter.ExecutionMachine.stepHooks` | |
| (`vendor/lean-miri/Miri/Interpreter/ExecutionMachine.lean`), where each case | |
| value is checked at 1-byte layout via `Scalar.fromUInt` | |
| (`ScalarInt.tryFromUInt`) and compared via `ScalarOps.binary .Eq` | |
| (`Scalar.toBool` on both operands): | |
| - `caseBits` overflowing 1 byte (`truncateBits .i8 caseBits != caseBits`) fails | |
| `Scalar.fromUInt` with `.invalidProgram` (`.error .unsupported`); | |
| - `0` (`false`) and `1` (`true`) match `!discr` and `discr`; | |
| - `2..255` trigger `ScalarIntError.invalidBool` and fault with `.error | |
| .undefined`. -/ | |
| noncomputable def evalBoolSwitchBranches (discr : Bool) | |
| (otherwise : BasicBlockId) : | |
| List (BitVec 128 × BasicBlockId) → Except FaultKind BasicBlockId | |
| | [] => .ok otherwise | |
| | (caseBits, target) :: rest => | |
| match evalConstLit .bool (.scalar caseBits) with | |
| | .ok (.bool false) => | |
| if !discr then .ok target else evalBoolSwitchBranches discr otherwise rest | |
| | .ok (.bool true) => | |
| if discr then .ok target else evalBoolSwitchBranches discr otherwise rest | |
| | .error k => | |
| .error k | |
| | .ok _ => | |
| .error .unsupported | |
| /-- Evaluate a `SwitchTargets` branch list against a `char` discriminant | |
| `discr`, matching `compareSwitchCase` in | |
| `Miri.Interpreter.ExecutionMachine.stepHooks` | |
| (`vendor/lean-miri/Miri/Interpreter/ExecutionMachine.lean`), where each case | |
| value is checked at the 4-byte `char` layout via `Scalar.fromUInt` | |
| (`ScalarInt.tryFromUInt`) and compared via `ScalarOps.binary .Eq` | |
| (`Scalar.toChar` on both operands, then `IntegerOps.binaryChar`): | |
| - `caseBits` overflowing 4 bytes fails `Scalar.fromUInt` with | |
| `.invalidProgram` (`.error .unsupported`); | |
| - a `caseBits` that is not a Unicode scalar value triggers | |
| `ScalarIntError.invalidChar` and faults with `.error .undefined`; | |
| - otherwise the case matches when it equals `discr`. These are exactly the | |
| outcomes of `evalConstLit .char (.scalar caseBits)`. -/ | |
| noncomputable def evalCharSwitchBranches (discr : Char) | |
| (otherwise : BasicBlockId) : | |
| List (BitVec 128 × BasicBlockId) → Except FaultKind BasicBlockId | |
| | [] => .ok otherwise | |
| | (caseBits, target) :: rest => | |
| match evalConstLit .char (.scalar caseBits) with | |
| | .ok (.char c) => | |
| if Nat.beq discr.toNat c.toNat then | |
| .ok target | |
| else | |
| evalCharSwitchBranches discr otherwise rest | |
| | .error k => | |
| .error k | |
| | .ok _ => | |
| .error .unsupported | |
| /-- Assign the frame location to `(target, 0)`, matching | |
| `Miri.Interpreter.ControlFlow.goToBlock` (`Miri/Interpreter/ControlFlow.lean`: | |
| target block existence is checked at the start of the next step in `evalStep` / | |
| `Step.step`). -/ | |
| noncomputable def jumpToBlock (frame : FrameState) (mem : MemoryState) | |
| (callerMem : CallerMemory) (target : BasicBlockId) : | |
| StepResult State TerminalOut := | |
| .step { | |
| frames := [{ frame with blockIdx := target, stmtIdx := 0 }] | |
| callerMem | |
| mem | |
| } | |
| /-- Outcome of a failing `TerminatorKind.assert` under `panicStrategy` and | |
| `unwind`, matching `rustc`'s `TerminatorKind::Assert` and `UnwindAction` | |
| (`compiler/rustc_middle/src/mir/syntax.rs`, lines 853-863, `rust-lang/rust` | |
| `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`), | |
| `AssertKind::is_optional_overflow_check` | |
| (`compiler/rustc_middle/src/mir/terminator.rs`, lines 164-168), codegen | |
| elision (`compiler/rustc_codegen_ssa/src/mir/block.rs`, lines 714-716), and | |
| `assert_panic` (`compiler/rustc_const_eval/src/interpret/step.rs`, lines | |
| 622-631): | |
| > "Evaluates the operand, which must have type `bool`. If it is not equal to | |
| > `expected`, initiates a panic. Initiating a panic corresponds to a `Call` | |
| > terminator with some unspecified constant as the function to call, all the | |
| > operands stored in the `AssertMessage` as parameters, and `None` for the | |
| > destination. Keep in mind that the `cleanup` path is not necessarily executed | |
| > even in the case of a panic, for example in `-C panic=abort`. If the | |
| > assertion does not fail, execution continues at the specified basic block. | |
| > | |
| > When overflow checking is disabled and this is run-time MIR (as opposed to | |
| > compile-time MIR that is used for CTFE), the following variants of this | |
| > terminator behave as `goto target`: | |
| > - `OverflowNeg(..)`, | |
| > - `Overflow(op, ..)` if op is add, sub, mul, shl, shr, but NOT div or rem." | |
| > (`compiler/rustc_middle/src/mir/syntax.rs`) | |
| > | |
| > "pub fn is_optional_overflow_check(&self) -> bool { | |
| > use AssertKind::*; | |
| > use BinOp::*; | |
| > matches!( | |
| > self, | |
| > OverflowNeg(..) | Overflow(Add | Sub | Mul | Shl | Shr, ..) | |
| > ) | |
| > }" | |
| > (`compiler/rustc_middle/src/mir/terminator.rs`) | |
| > | |
| > "if !bx.sess().overflow_checks() && msg.is_optional_overflow_check() { | |
| > const_cond = Some(expected); | |
| > }" | |
| > (`compiler/rustc_codegen_ssa/src/mir/block.rs`) | |
| > | |
| > "Assert { ref cond, expected, ref msg, target, unwind } => { | |
| > let ignored = | |
| > M::ignore_optional_overflow_checks(self) | |
| > && msg.is_optional_overflow_check(); | |
| > let cond_val = | |
| > self.read_scalar(&self.eval_operand(cond, None)?)?.to_bool()?; | |
| > if ignored || expected == cond_val { | |
| > self.go_to_block(target); | |
| > } else { | |
| > M::assert_panic(self, msg, unwind)?; | |
| > } | |
| > }" | |
| > (`compiler/rustc_const_eval/src/interpret/step.rs`) | |
| In `rustc` / Miri (`Miri.Interpreter.Panic.assertPanic`), failing | |
| `MisalignedPointerDereference` and `NullPointerDereference` assertions invoke | |
| defined non-unwinding panic lang items rather than triggering UB directly. | |
| While panic lang-item shims remain unmodeled, `misalignedPtrDeref` and | |
| `nullPtrDeref` fail closed as `.fault .unsupported` (never `.fault .undefined`) | |
| so existential UB refutations (`existsWitness`) cannot certify UB on defined | |
| nounwind panics. Non-optional safe panics (`boundsCheck`, `overflow .div`, | |
| `overflow .rem`, `divByZero`, `remByZero`) terminate cleanly with | |
| `.aborted callerMem` iff `hasLocalPanicHandler = false`, | |
| `panicStrategy = .abort`, and `unwind ≠ .cleanup _`. When a crate defines a | |
| crate-local `#[panic_handler]` (`hasLocalPanicHandler = true`), failing safe | |
| asserts stay `.fault .unsupported` because the unverified handler can execute | |
| arbitrary code or diverge. Optional overflow checks | |
| (`overflow .add|.sub|.mul|.shl|.shr`, `overflowNeg`) abort under the same | |
| conditions only when `overflowChecks = true`, that is, when the program was | |
| captured under `-Coverflow-checks=yes`, where codegen keeps them as runtime | |
| panics. With `overflowChecks = false` they stay `.fault .unsupported`: codegen | |
| then elides inherited optional overflow asserts | |
| (`#[rustc_inherit_overflow_checks]`) as `goto target` rather than aborting. | |
| Under `--panic unwind` or `.cleanup _`, all failed safe asserts fail closed as | |
| `.fault .unsupported`. -/ | |
| noncomputable def evalAssertFailure (msg : AssertKind) | |
| (panicStrategy : PanicStrategy) (unwind : UnwindAction) | |
| (callerMem : CallerMemory) (hasLocalPanicHandler : Bool := true) | |
| (overflowChecks : Bool := false) : | |
| StepResult State TerminalOut := | |
| match msg with | |
| | .misalignedPtrDeref | .nullPtrDeref => .fault .unsupported | |
| | .boundsCheck | .overflow .div | .overflow .rem | |
| | .divByZero | .remByZero => | |
| if hasLocalPanicHandler then | |
| .fault .unsupported | |
| else | |
| match panicStrategy, unwind with | |
| | .abort, .continue_ | .abort, .unreachable | .abort, .terminate => | |
| .done (.aborted callerMem) | |
| | _, _ => .fault .unsupported | |
| | .overflow .add | .overflow .sub | .overflow .mul | .overflow .shl | |
| | .overflow .shr | .overflowNeg => | |
| if !overflowChecks || hasLocalPanicHandler then | |
| .fault .unsupported | |
| else | |
| match panicStrategy, unwind with | |
| | .abort, .continue_ | .abort, .unreachable | .abort, .terminate => | |
| .done (.aborted callerMem) | |
| | _, _ => .fault .unsupported | |
| | .overflow _ | .unsupported => .fault .unsupported | |
| /-- Shared abort-termination rule for diverging | |
| `core::panicking::{panic, panic_nounwind}` calls (`CoreCallOp.panicAbort`) and | |
| for safe unconditional `core`/`alloc` contract panics | |
| (`CoreCallOutcome.panicked` | |
| from `execCoreCallOpWithMemOutcome`): terminates cleanly with | |
| `.aborted callerMem` iff `hasLocalPanicHandler = false`, | |
| `panicStrategy = .abort`, and `unwind ≠ .cleanup _`; otherwise fails closed as | |
| `.fault .unsupported`. | |
| At pinned `rust-lang/rust` `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`: | |
| - `core::panicking::panic` (`library/core/src/panicking.rs:138-151`) and | |
| `core::panicking::panic_nounwind` (`library/core/src/panicking.rs:224-226`) | |
| wrap their `&'static str` message via `fmt::Arguments::from_str(expr)` and | |
| delegate to `panic_fmt` (`:60-81`) and `panic_nounwind_fmt` (`:95-124`), | |
| which invoke the `#[lang = "panic_impl"]` handler (`:67-80` and `:108-122`): | |
| > pub const fn panic(expr: &'static str) -> ! { | |
| > ... | |
| > panic_fmt(fmt::Arguments::from_str(expr)); | |
| > } | |
| > unsafe extern "Rust" { | |
| > #[lang = "panic_impl"] | |
| > fn panic_impl(pi: &PanicInfo<'_>) -> !; | |
| > } | |
| > | |
| > let pi = PanicInfo::new( | |
| > &fmt, | |
| > Location::caller(), | |
| > /* can_unwind */ true, | |
| > /* force_no_backtrace */ false, | |
| > ); | |
| > ... | |
| > unsafe { panic_impl(&pi) } | |
| > unsafe extern "Rust" { | |
| > #[lang = "panic_impl"] | |
| > fn panic_impl(pi: &PanicInfo<'_>) -> !; | |
| > } | |
| > | |
| > // PanicInfo with the `can_unwind` flag set to false forces an abort. | |
| > let pi = PanicInfo::new( | |
| > &fmt, | |
| > Location::caller(), | |
| > /* can_unwind */ false, | |
| > force_no_backtrace, | |
| > ); | |
| > ... | |
| > unsafe { panic_impl(&pi) } | |
| - Without a crate-local `#[panic_handler]` (`hasLocalPanicHandler = false`), | |
| `std`'s default handler | |
| (`library/std/src/panicking.rs:680-694,776-840,874-877`) | |
| runs `panic_with_hook` (aborting directly via `crate::process::abort()` when | |
| `!can_unwind` at `:831-837`) and otherwise calls `rust_panic` -> | |
| `__rust_start_panic`: | |
| > if !can_unwind { | |
| > ... | |
| > crate::process::abort(); | |
| > } | |
| > | |
| > rust_panic(payload) | |
| > fn rust_panic(msg: &mut dyn PanicPayload) -> ! { | |
| > let code = unsafe { __rust_start_panic(msg) }; | |
| > rtabort!("failed to initiate panic, error {code}") | |
| > } | |
| - Under `-C panic=abort` (`panicStrategy = .abort`), the linked `panic_abort` | |
| runtime (`library/panic_abort/src/lib.rs:33-51` and | |
| `library/std/src/rt.rs:32-34`) aborts the process without unwinding across | |
| any caller `UnwindAction` (`continue_`, `unreachable`, or `terminate`; | |
| `cleanup` blocks are absent under `-C panic=abort` and fail closed): | |
| > pub unsafe fn __rust_start_panic(_payload: &mut dyn PanicPayload) -> u32 { | |
| > ... | |
| > unsafe extern "Rust" { | |
| > // This is defined in std::rt. | |
| > #[rustc_std_internal_symbol] | |
| > safe fn __rust_abort() -> !; | |
| > } | |
| > | |
| > __rust_abort() | |
| > } | |
| > fn __rust_abort() { | |
| > crate::process::abort(); | |
| > } | |
| Panic hooks and `#[panic_handler]` execution are outside the MIR machine | |
| (recorded explicitly in the `--panic abort` verification receipt assumption); | |
| when `hasLocalPanicHandler = true`, `panicStrategy = .unwind`, or | |
| `unwind = .cleanup _`, this rule fails closed as `.fault .unsupported`. -/ | |
| noncomputable def evalCorePanicAbort (panicStrategy : PanicStrategy) | |
| (unwind : UnwindAction) (callerMem : CallerMemory) | |
| (hasLocalPanicHandler : Bool := true) : | |
| StepResult State TerminalOut := | |
| if hasLocalPanicHandler then | |
| .fault .unsupported | |
| else | |
| match panicStrategy, unwind with | |
| | .abort, .continue_ | .abort, .unreachable | .abort, .terminate => | |
| .done (.aborted callerMem) | |
| | _, _ => .fault .unsupported | |
| /-- Evaluate a basic block's `TerminatorKind` when | |
| `frame.stmtIdx == bb.statements.length`, matching `eval_terminator` in | |
| `compiler/rustc_const_eval/src/interpret/step.rs` (`rust-lang/rust` | |
| `8144389c895da997dbdecaa635e41d6a50be6ffd`): | |
| > "fn eval_terminator(&mut self, terminator: &mir::Terminator<'tcx>) -> | |
| > InterpResult<'tcx> { | |
| > ... | |
| > match terminator.kind { | |
| > Return => { | |
| > self.return_from_current_stack_frame(/* unwinding */ false)? | |
| > } | |
| > Goto { target, loop_hint_attrs: _ } => self.go_to_block(target), | |
| > SwitchInt { ref discr, ref targets } => { ... } | |
| > ... | |
| > Unreachable => throw_ub!(Unreachable), | |
| > Assert { ref cond, expected, ref msg, target, unwind } => { | |
| > ... | |
| > } | |
| > ... | |
| > } | |
| > }" | |
| > (`compiler/rustc_const_eval/src/interpret/step.rs`, `rust-lang/rust` | |
| > `8144389c895da997dbdecaa635e41d6a50be6ffd`; `Assert` also matches | |
| > `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`) | |
| `Return` reads `_0`'s value (from memory with `loadIndirect` if `_0` is | |
| `.indirect`); an uninitialized or dead `_0` faults with `.undefined`. | |
| `Assert` evaluates `cond` to `.bool`; if equal to `expected` it jumps to | |
| `target`, otherwise it fails closed with `.fault .unsupported` while panic | |
| lang-item shims remain unmodeled in Profile v1 (preserving non-circular | |
| bidirectional correspondence with `M_ref`'s `PurePanicHooks`). -/ | |
| noncomputable def evalTerminator (body : Body) (bb : BasicBlock) | |
| (frame : FrameState) (mem : MemoryState) (callerMem : CallerMemory) | |
| (_panicStrategy : PanicStrategy := .unwind) | |
| (_hasLocalPanicHandler : Bool := true) : | |
| StepResult State TerminalOut := | |
| match bb.terminator with | |
| | .goto target => jumpToBlock frame mem callerMem target | |
| | .return_ => | |
| if bb.cleanup then | |
| .fault .unsupported | |
| else | |
| match getElem? frame.locals 0 with | |
| | some (.immediate (some retVal)) => | |
| .done (.returned ⟨retVal, callerMem⟩) | |
| | some (.immediate none) | some .dead => .fault .undefined | |
| -- Profile v1 never creates partially moved tuples. | |
| | some (.partialTuple _) => .fault .unsupported | |
| | some (.indirect mplace) => | |
| match getElem? body.locals 0 with | |
| | none => .fault .unsupported | |
| | some retTy => | |
| match loadIndirect mem retTy mplace with | |
| | .ok (some retVal) => .done (.returned ⟨retVal, callerMem⟩) | |
| | .ok none => .fault .undefined | |
| | .error k => .fault k | |
| | none => .fault .unsupported | |
| | .unreachable => | |
| .fault .undefined | |
| | .switchInt discr targets => | |
| match evalPrimitiveOperand body.locals frame.locals mem discr with | |
| | .error k => .fault k | |
| | .ok (discrVal, localsAfterDiscr, memAfterDiscr) => | |
| let targetRes : Except FaultKind BasicBlockId := | |
| match discrVal with | |
| | .scalar sv => | |
| evalSwitchBranches sv.width sv.bits targets.otherwise targets.branches | |
| | .bool b => | |
| evalBoolSwitchBranches b targets.otherwise targets.branches | |
| | .char c => | |
| evalCharSwitchBranches c targets.otherwise targets.branches | |
| | _ => | |
| -- An overflow pair is primitive-readable, but `compareSwitchCase`'s | |
| -- `ScalarOps.binary .Eq` rejects it, so only an empty branch list | |
| -- (which compares nothing) jumps to `otherwise`. | |
| match targets.branches with | |
| | [] => .ok targets.otherwise | |
| | _ :: _ => .error .unsupported | |
| match targetRes with | |
| | .error k => .fault k | |
| | .ok target => | |
| jumpToBlock { frame with locals := localsAfterDiscr } memAfterDiscr | |
| callerMem target | |
| | .assert cond expected _ target _ => | |
| match evalPrimitiveOperand body.locals frame.locals mem cond with | |
| | .error k => .fault k | |
| | .ok (condVal, locals1, mem1) => | |
| match condVal with | |
| | .bool b => | |
| if b == expected then | |
| jumpToBlock { frame with locals := locals1 } mem1 callerMem target | |
| else | |
| .fault .unsupported | |
| | _ => .fault .unsupported | |
| | .unwindResume | .call _ _ _ _ _ | .coreCall _ _ _ _ _ | |
| | .sysrootCall _ _ _ _ _ | .callNe _ _ _ _ _ | .callVia _ _ _ _ _ _ | |
| | .drop _ _ _ | .unsupported => | |
| .fault .unsupported | |
| /-! | |
| ## Profile v2 Memory, Reference, Raw-Pointer, and Core-Primitive Evaluation | |
| -/ | |
| /-- Signed `BinOp.offset` in Profile v2: handles both non-negative and negative | |
| `isize` element offsets inside a live allocation (failing `.undefined` on | |
| out-of-bounds or overflow past `isize::MAX`). | |
| `BinOp::Offset` has `ptr::offset` semantics | |
| (`compiler/rustc_middle/src/mir/syntax.rs:1410-1411`, `rust-lang/rust` | |
| `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`): | |
| > "* `Offset` has the same semantics as [`offset`](pointer::offset), except | |
| > that the second parameter may be a `usize` as well." | |
| The interpreter computes `count * size` with an overflow check, then requires | |
| the signed byte range to be in bounds of a live allocation | |
| (`compiler/rustc_const_eval/src/interpret/intrinsics.rs:1034-1041`, same | |
| pin): | |
| > "// The offset must be in bounds starting from `ptr`. | |
| > self.check_ptr_access_signed( | |
| > ptr, | |
| > offset_bytes, | |
| > CheckInAllocMsg::InboundsPointerArithmetic, | |
| > )?; | |
| > // This also implies that there is no overflow, so we are done. | |
| > interp_ok(ptr.wrapping_signed_offset(offset_bytes, self))" | |
| In `check_and_deref_ptr` (`memory.rs:531-534,546-552`), size 0 is always | |
| accepted. Otherwise the range is `[offset, offset + size)` for `size >= 0`, or | |
| `[offset - |size|, offset)` for `size < 0`, and it must lie within the | |
| allocation. The non-negative case reuses `ptrAddInMem`. The negative case | |
| checks `delta < 2^63`, provenance, liveness, `offset <= len`, and | |
| `delta <= offset`. Both `isize` and `usize` counts (`IntWidth.isize`) are | |
| accepted. Conservative divergences: a zero offset still requires a live | |
| allocation, and a negative count with a zero-sized pointee and no provenance | |
| is `.undefined`. -/ | |
| noncomputable def evalPtrOffsetV2 (mem : MemoryState) (elemSize : Nat) | |
| (p : PtrVal) (countVal : Val) : Except FaultKind Val := | |
| match countVal with | |
| | .scalar sv => | |
| if !IntWidth.beq sv.width .isize then | |
| .error .unsupported | |
| else | |
| match decodeScalar sv with | |
| | .ofNat n => | |
| match ptrAddInMem mem elemSize p n with | |
| | .ok p' => .ok (.ptr p') | |
| | .error k => .error k | |
| | .negSucc k => | |
| let absCount := k + 1 | |
| let delta := absCount * elemSize | |
| if !Nat.blt delta isizeMaxBytes then | |
| .error .undefined | |
| else | |
| match p.allocId with | |
| | none => .error .undefined | |
| | some aid => | |
| match findAllocation aid mem.allocations with | |
| | none => .error .undefined | |
| | some a => | |
| if !a.live || !Nat.ble p.offsetBytes.toNat a.bytes.length || | |
| !Nat.ble delta p.offsetBytes.toNat then | |
| .error .undefined | |
| else | |
| .ok (.ptr { p with | |
| offsetBytes := UInt64.ofNat (p.offsetBytes.toNat - delta) }) | |
| | _ => .error .unsupported | |
| /-- Promote local `localId` from `.immediate` to a stack `.indirect` | |
| allocation in `mem` when its address is taken (`Rvalue.ref` / | |
| `Rvalue.addressOf`), initializing stack bytes if the local holds an immediate | |
| value. | |
| This mirrors the interpreter's `force_allocation`, which `Rvalue::Ref` and | |
| `Rvalue::RawPtr` both call | |
| (`compiler/rustc_const_eval/src/interpret/place.rs:983-986,1004-1015`, | |
| `rust-lang/rust` `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`): | |
| > "/// Ensures that a place is in memory, and returns where it is. If the place | |
| > /// currently refers to a local that doesn't yet have a matching allocation, | |
| > /// create such an allocation. This is essentially `force_to_memplace`. | |
| > ... | |
| > let mplace = self.allocate(local_layout, MemoryKind::Stack)?; | |
| > // Preserve old value. (As an optimization, we can skip this if it | |
| > // was uninit.) | |
| > if !matches!(local_val, Immediate::Uninit) { | |
| > // We don't have to validate as we can assume the local was | |
| > // already valid for its type. We must not use any part of | |
| > // `place` here, that could be a projection to a part of the | |
| > // local! | |
| > self.write_immediate_to_mplace_no_validate( | |
| > local_val, | |
| > local_layout, | |
| > mplace.mplace, | |
| > )?; | |
| > }" | |
| A `.dead` local (after `StorageDead`) faults with `.undefined`. Unsized local | |
| types fail closed. -/ | |
| noncomputable def promoteLocalToMemory (bodyLocals : List MirTy) | |
| (locals : List LocalSlot) (mem : MemoryState) (localId : LocalId) : | |
| Except FaultKind (MirTy × MemPlace × List LocalSlot × MemoryState) := | |
| match getElem? bodyLocals localId, getElem? locals localId with | |
| | some _, some .dead => .error .undefined | |
| | some localTy, some (.indirect mplace) => | |
| if isUnsizedTy localTy then | |
| .error .unsupported | |
| else | |
| .ok (localTy, mplace, locals, mem) | |
| | some localTy, some (.immediate optVal) => | |
| match layoutOfTyV2 localTy with | |
| | none => .error .unsupported | |
| | some lay => | |
| let (mem1, mplace) := allocateStack mem lay | |
| match optVal with | |
| | none => | |
| match setElem? locals localId (.indirect mplace) with | |
| | some locals1 => .ok (localTy, mplace, locals1, mem1) | |
| | none => .error .unsupported | |
| | some v => | |
| match storeIndirectV2 mem1 localTy mplace v with | |
| | .error k => .error k | |
| | .ok mem2 => | |
| match setElem? locals localId (.indirect mplace) with | |
| | some locals1 => .ok (localTy, mplace, locals1, mem2) | |
| | none => .error .unsupported | |
| | _, _ => .error .unsupported | |
| /-- Compute the zero-based element index for `ProjectionElem.constantIndex` | |
| (`ConstantIndex { offset, min_length, from_end }` in | |
| `compiler/rustc_middle/src/mir/syntax.rs`, `rust-lang/rust` | |
| `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`): | |
| > "The thing being indexed must be at least this long -- otherwise, the | |
| > projection is UB. | |
| > | |
| > For arrays this is always the exact length." | |
| > "If `true`, `offset` is a 1-based offset from the end of the slice. | |
| > Always false when indexing an array." | |
| Returns `.error .undefined` when `len < minLength` or `offset` is out of | |
| range. -/ | |
| noncomputable def constantIndexOffset (len off minLen : Nat) | |
| (fromEnd : Bool) : Except FaultKind Nat := | |
| if !Nat.ble minLen len then | |
| .error .undefined | |
| else if fromEnd then | |
| if Nat.beq off 0 || !Nat.ble off len then | |
| .error .undefined | |
| else | |
| .ok (len - off) | |
| else | |
| if !Nat.blt off len then | |
| .error .undefined | |
| else | |
| .ok off | |
| /-- Project one tuple, range, or fixed-size array element through an immediate | |
| `Val` in Profile v2, factored out so `projectValFieldV2`'s equation lemma | |
| stays free of `Quot.sound`. -/ | |
| noncomputable def projectOneElemV2 (ty : MirTy) (v : Val) | |
| (proj : ProjectionElem) : Except FaultKind (MirTy × Val) := | |
| match proj with | |
| | .field idx fTy => | |
| match ty with | |
| | .tuple ts => | |
| match v with | |
| | .tuple vs => | |
| match getElem? ts idx, getElem? vs idx with | |
| | some elemTy, some elemVal => | |
| if !MirTy.beq elemTy fTy then | |
| .error .unsupported | |
| else | |
| .ok (elemTy, elemVal) | |
| | _, _ => .error .unsupported | |
| | _ => .error .unsupported | |
| | .rangeTo (.int .isize false) => | |
| match v with | |
| | .rangeTo e => | |
| if !Nat.beq idx 0 || !MirTy.beq fTy (.int .isize false) then | |
| .error .unsupported | |
| else | |
| .ok (.int .isize false, | |
| .scalar ⟨.isize, false, | |
| truncateBits .isize (BitVec.ofNat 128 e.toNat)⟩) | |
| | _ => .error .unsupported | |
| | .rangeFrom (.int .isize false) => | |
| match v with | |
| | .rangeFrom s => | |
| if !Nat.beq idx 0 || !MirTy.beq fTy (.int .isize false) then | |
| .error .unsupported | |
| else | |
| .ok (.int .isize false, | |
| .scalar ⟨.isize, false, | |
| truncateBits .isize (BitVec.ofNat 128 s.toNat)⟩) | |
| | _ => .error .unsupported | |
| | .range (.int .isize false) => | |
| match v with | |
| | .range s e => | |
| if !MirTy.beq fTy (.int .isize false) then | |
| .error .unsupported | |
| else if Nat.beq idx 0 then | |
| .ok (.int .isize false, | |
| .scalar ⟨.isize, false, | |
| truncateBits .isize (BitVec.ofNat 128 s.toNat)⟩) | |
| else if Nat.beq idx 1 then | |
| .ok (.int .isize false, | |
| .scalar ⟨.isize, false, | |
| truncateBits .isize (BitVec.ofNat 128 e.toNat)⟩) | |
| else | |
| .error .unsupported | |
| | _ => .error .unsupported | |
| | .struct_ _ fs => | |
| match v with | |
| | .tuple vs => | |
| match getElem? fs idx, getElem? vs idx with | |
| | some elemTy, some elemVal => | |
| if !MirTy.beq elemTy fTy then | |
| .error .unsupported | |
| else | |
| .ok (elemTy, elemVal) | |
| | _, _ => .error .unsupported | |
| | _ => .error .unsupported | |
| -- A recursive struct's fields have the types of its one-step unfolding, | |
| -- in which `Box<Self>` is the closed `Box<.recAdt id defn>`. | |
| | .recAdt id defn => | |
| match unfoldRecV2 id defn, v with | |
| | .struct_ _ fs, .tuple vs => | |
| match getElem? fs idx, getElem? vs idx with | |
| | some elemTy, some elemVal => | |
| if !MirTy.beq elemTy fTy then | |
| .error .unsupported | |
| else | |
| .ok (elemTy, elemVal) | |
| | _, _ => .error .unsupported | |
| | _, _ => .error .unsupported | |
| | _ => .error .unsupported | |
| | .constantIndex off minLen fromEnd => | |
| match ty with | |
| | .array elem len => | |
| match v with | |
| | .array vs => | |
| if !Nat.beq vs.length len then | |
| .error .unsupported | |
| else | |
| match constantIndexOffset len off minLen fromEnd with | |
| | .error k => .error k | |
| | .ok idx => | |
| match getElem? vs idx with | |
| | some elemVal => .ok (elem, elemVal) | |
| | none => .error .undefined | |
| | _ => .error .unsupported | |
| | _ => .error .unsupported | |
| | .deref => .error .unsupported | |
| | .downcast _ => .error .unsupported | |
| | .index _ => .error .unsupported | |
| | .unsupported => .error .unsupported | |
| /-- Project tuple, range, `Option` payload (`.downcast 1` then `.field 0`), | |
| payload enum variant field (`.downcast v` then `.field i`), or fixed-size | |
| array elements through an immediate `Val` in Profile v2. The field of a | |
| variant other than the one the value holds is `.undefined`, as for `None`: | |
| `rustc`'s `project_downcast` does not read the discriminant, but the MIR it | |
| builds for a `match` downcasts only after testing it. -/ | |
| noncomputable def projectValFieldV2 (ty : MirTy) (v : Val) : | |
| List ProjectionElem → Except FaultKind (MirTy × Val) | |
| | [] => .ok (ty, v) | |
| | .downcast vi :: .field fi fTy :: rest => | |
| match ty, v with | |
| | .option inner, .optionVal optV => | |
| if !Nat.beq vi 1 || !Nat.beq fi 0 || !MirTy.beq inner fTy then | |
| .error .unsupported | |
| else | |
| match optV with | |
| | some innerVal => projectValFieldV2 inner innerVal rest | |
| | none => .error .undefined | |
| | _, .adtVal w p => | |
| match adtVariantsV2 ty with | |
| | none => .error .unsupported | |
| | some vs => | |
| match getElem? vs vi with | |
| | none => .error .unsupported | |
| | some pTy => | |
| if !Nat.beq vi w then | |
| .error .undefined | |
| else | |
| match projectOneElemV2 pTy p (.field fi fTy) with | |
| | .error k => .error k | |
| | .ok (eTy, eV) => projectValFieldV2 eTy eV rest | |
| | _, _ => .error .unsupported | |
| | proj :: rest => | |
| match projectOneElemV2 ty v proj with | |
| | .error k => .error k | |
| | .ok (elemTy, elemVal) => projectValFieldV2 elemTy elemVal rest | |
| /-- Project a memory-backed `MirTy` along `.constantIndex` / fixed-layout | |
| `.field` projections (`overflowPair`, `RangeTo`/`RangeFrom`, and struct fields | |
| at their `StructLayout.fieldOffsets`), returning the leaf `MirTy` and | |
| cumulative byte offset from the base allocation offset. -/ | |
| noncomputable def projectMemoryLayoutV2 : | |
| MirTy → List ProjectionElem → Except FaultKind (MirTy × Nat) | |
| | ty, [] => .ok (ty, 0) | |
| | .struct_ l fs, .field idx fTy :: rest => | |
| match getElem? fs idx, getElem? l.fieldOffsets idx with | |
| | some elemTy, some off => | |
| if !MirTy.beq elemTy fTy then | |
| .error .unsupported | |
| else | |
| match projectMemoryLayoutV2 elemTy rest with | |
| | .error k => .error k | |
| | .ok (leafTy, subOff) => .ok (leafTy, off + subOff) | |
| | _, _ => .error .unsupported | |
| | .recAdt id defn, .field idx fTy :: rest => | |
| match unfoldRecV2 id defn with | |
| | .struct_ l fs => | |
| match getElem? fs idx, getElem? l.fieldOffsets idx with | |
| | some elemTy, some off => | |
| if !MirTy.beq elemTy fTy then | |
| .error .unsupported | |
| else | |
| match projectMemoryLayoutV2 elemTy rest with | |
| | .error k => .error k | |
| | .ok (leafTy, subOff) => .ok (leafTy, off + subOff) | |
| | _, _ => .error .unsupported | |
| | _ => .error .unsupported | |
| | .array elem len, .constantIndex off minLen fromEnd :: rest => | |
| match layoutOfTyV2 elem with | |
| | none => .error .unsupported | |
| | some elemLay => | |
| match constantIndexOffset len off minLen fromEnd with | |
| | .error k => .error k | |
| | .ok idx => | |
| match projectMemoryLayoutV2 elem rest with | |
| | .error k => .error k | |
| | .ok (leafTy, subOff) => .ok (leafTy, idx * elemLay.size + subOff) | |
| | .tuple [.int w s, .bool], .field 0 fTy :: rest => | |
| if !MirTy.beq (.int w s) fTy then | |
| .error .unsupported | |
| else | |
| projectMemoryLayoutV2 (.int w s) rest | |
| | .tuple [.int w _, .bool], .field 1 fTy :: rest => | |
| if !MirTy.beq .bool fTy then | |
| .error .unsupported | |
| else | |
| match projectMemoryLayoutV2 .bool rest with | |
| | .error k => .error k | |
| | .ok (leafTy, subOff) => .ok (leafTy, (intLayout w).size + subOff) | |
| | .rangeTo (.int .isize false), .field 0 fTy :: rest | |
| | .rangeFrom (.int .isize false), .field 0 fTy :: rest => | |
| if !MirTy.beq (.int .isize false) fTy then | |
| .error .unsupported | |
| else | |
| projectMemoryLayoutV2 (.int .isize false) rest | |
| | _, _ => .error .unsupported | |
| /-- The byte offset of the `Some` payload within an `Option<inner>` in Profile | |
| v2 memory, following `layoutOfTyV2` and `decodeValV2`: `0` for the niche of | |
| `&T` and `Box<T>` (a null pointer) and of `Vec<T>` (capacity `2^63`), and the | |
| tag size `2^align` for a direct-tag layout. `Option<bool>`, `Option<()>`, and | |
| payloads without an `Option` layout have none. | |
| `Option<Vec<T>>` with a zero-sized `T` remains conservatively refused here: | |
| upstream `RawVecInner::capacity` returns `usize::MAX` for ZSTs rather than | |
| reading `cap`, so in-place payload projection on `Option<Vec<ZST>>` is left | |
| unsupported. -/ | |
| noncomputable def optionSomeOffsetV2 (inner : MirTy) : Option Nat := | |
| match inner with | |
| | .ref _ _ | .box _ => some 0 | |
| | .vec e => | |
| match layoutOfTyV2 e with | |
| | some lay => if Nat.beq lay.size 0 then none else some 0 | |
| | none => none | |
| | .bool | .unit => none | |
| | _ => | |
| if !isOptionPayloadSupportedV2 inner then | |
| none | |
| else | |
| match layoutOfTyV2 inner with | |
| | none => none | |
| | some lay => some (Nat.pow 2 lay.alignLog2) | |
| /-- Resolve a projected place in allocation `aid` whose projections may | |
| include `Option` payload downcasts (`.downcast 1` then `.field 0`) or payload | |
| enum variant downcasts (`.downcast v` then `.field i`), returning the leaf | |
| type and its byte offset in `aid`. The place `ty` starts at byte | |
| `base`, and `pre` holds the projections since `ty` not yet applied, which | |
| `projectMemoryLayoutV2` resolves statically. | |
| `projectMemoryLayoutV2` has no downcast: the `Some` payload exists only when | |
| the `Option` holds `Some`. So the whole `Option` is read first | |
| (`loadIndirectV2`), which faults on uninitialized or out-of-bounds memory, and | |
| a `None` (or uninitialized) discriminant is `.undefined`. This is stricter | |
| than Rust, where projecting a place does not read the discriminant, but the | |
| MIR that `rustc` builds for a `match` downcasts only after testing it. A | |
| payload enum likewise is read whole, and a variant other than `v` is | |
| `.undefined`; variant `v`'s payload struct starts at the enum's first byte, | |
| with its fields at their offsets in the enum. Any other downcast is | |
| unsupported. -/ | |
| noncomputable def projectMemoryPlaceV2 (mem : MemoryState) (aid : AllocId) : | |
| Nat → MirTy → List ProjectionElem → List ProjectionElem → | |
| Except FaultKind (MirTy × Nat) | |
| | base, ty, pre, [] => | |
| match projectMemoryLayoutV2 ty pre with | |
| | .error k => .error k | |
| | .ok (leafTy, off) => .ok (leafTy, base + off) | |
| | base, ty, pre, .downcast vi :: .field fi fTy :: rest => | |
| match projectMemoryLayoutV2 ty pre with | |
| | .error k => .error k | |
| | .ok (.option inner, off) => | |
| if !Nat.beq vi 1 || !Nat.beq fi 0 then .error .unsupported else | |
| match optionSomeOffsetV2 inner with | |
| | none => .error .unsupported | |
| | some someOff => | |
| if !MirTy.beq inner fTy then | |
| .error .unsupported | |
| else | |
| match loadIndirectV2 mem (.option inner) ⟨aid, base + off⟩ with | |
| | .error k => .error k | |
| | .ok (some (.optionVal (some _))) => | |
| projectMemoryPlaceV2 mem aid (base + off + someOff) inner [] rest | |
| | .ok (some (.optionVal none)) | .ok none => .error .undefined | |
| | .ok (some _) => .error .unsupported | |
| | .ok (eTy, off) => | |
| match adtVariantPayloadV2 eTy vi with | |
| | none => .error .unsupported | |
| | some pTy => | |
| match loadIndirectV2 mem eTy ⟨aid, base + off⟩ with | |
| | .error k => .error k | |
| | .ok (some (.adtVal w _)) => | |
| if !Nat.beq w vi then | |
| .error .undefined | |
| else | |
| projectMemoryPlaceV2 mem aid (base + off) pTy [.field fi fTy] rest | |
| | .ok none => .error .undefined | |
| | .ok (some _) => .error .unsupported | |
| | base, ty, pre, p :: rest => | |
| projectMemoryPlaceV2 mem aid base ty (pre ++ [p]) rest | |
| /-- Step a static `MirTy` along a tail of field, `ConstantIndex`, and `Index` | |
| projections. -/ | |
| noncomputable def stepProjectedTyV2 : MirTy → List ProjectionElem → Option MirTy | |
| | ty, [] => some ty | |
| | .tuple fs, .field idx fTy :: rest => | |
| match getElem? fs idx with | |
| | some t => if MirTy.beq t fTy then stepProjectedTyV2 t rest else none | |
| | none => none | |
| | .struct_ _ fs, .field idx fTy :: rest => | |
| match getElem? fs idx with | |
| | some t => if MirTy.beq t fTy then stepProjectedTyV2 t rest else none | |
| | none => none | |
| | .recAdt id defn, .field idx fTy :: rest => | |
| match unfoldRecV2 id defn with | |
| | .struct_ _ fs => | |
| match getElem? fs idx with | |
| | some t => if MirTy.beq t fTy then stepProjectedTyV2 t rest else none | |
| | none => none | |
| | _ => none | |
| | .rangeTo (.int .isize false), .field 0 fTy :: rest | |
| | .rangeFrom (.int .isize false), .field 0 fTy :: rest => | |
| if MirTy.beq (.int .isize false) fTy then stepProjectedTyV2 fTy rest else none | |
| | .range (.int .isize false), .field idx fTy :: rest => | |
| if (Nat.beq idx 0 || Nat.beq idx 1) && | |
| MirTy.beq (.int .isize false) fTy then | |
| stepProjectedTyV2 fTy rest | |
| else | |
| none | |
| | .array elem _, .constantIndex _ _ _ :: rest => stepProjectedTyV2 elem rest | |
| | .array elem _, .index _ :: rest => stepProjectedTyV2 elem rest | |
| | _, _ => none | |
| /-- Step the static `MirTy` of a dereferenced unsized slice pointee `[T]` | |
| along a leading element projection (`Index` or `ConstantIndex`) and the | |
| projections that follow it. -/ | |
| noncomputable def sliceProjectedTyV2 : | |
| MirTy → List ProjectionElem → Option MirTy | |
| | .slice elem, .index _ :: rest => stepProjectedTyV2 elem rest | |
| | .slice elem, .constantIndex _ _ _ :: rest => stepProjectedTyV2 elem rest | |
| | _, _ => none | |
| /-- Resolve the static `MirTy` of a `Place` in Profile v2, supporting single- | |
| step leading `.deref` (into a sized pointee or, followed by an element | |
| projection, a slice), `.field`, `.constantIndex`, and `.index` projections. -/ | |
| noncomputable def placeProjectedTyV2 (bodyLocals : List MirTy) | |
| (place : Place) : Option MirTy := | |
| match getElem? bodyLocals place.localId with | |
| | none => none | |
| | some baseTy => | |
| match place.projection with | |
| | .deref :: rest => | |
| match baseTy with | |
| | .ref _ pt | .rawPtr _ pt => | |
| if isUnsizedTy pt then sliceProjectedTyV2 pt rest | |
| else stepProjectedTyV2 pt rest | |
| | _ => none | |
| | projs => stepProjectedTyV2 baseTy projs | |
| /-- Read the `usize` index of a `ProjectionElem.index localId` projection from | |
| local `localId`, matching `project` in | |
| `compiler/rustc_const_eval/src/interpret/projection.rs` (`rust-lang/rust` | |
| `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`): | |
| > "Index(local) => { | |
| > let layout = self.layout_of(self.tcx.types.usize)?; | |
| > let n = self.local_to_op(local, Some(layout))?; | |
| > let n = self.read_target_usize(&n)?; | |
| > self.project_index(base, n)? | |
| > }" | |
| The local must have type `usize`. A dead or uninitialized index local faults | |
| with `.undefined` (`local_to_op` raises `DeadLocal`, and `read_target_usize` | |
| rejects uninitialized bytes). -/ | |
| noncomputable def readIndexLocalV2 (bodyLocals : List MirTy) | |
| (locals : List LocalSlot) (mem : MemoryState) (localId : LocalId) : | |
| Except FaultKind Nat := | |
| match getElem? bodyLocals localId, getElem? locals localId with | |
| | some (.int .isize false), some .dead => .error .undefined | |
| | some (.int .isize false), some (.immediate none) => .error .undefined | |
| | some (.int .isize false), some (.immediate (some (.scalar sv))) => | |
| if IntWidth.beq sv.width .isize && !sv.signed then | |
| .ok sv.bits.toNat | |
| else | |
| .error .unsupported | |
| | some (.int .isize false), some (.indirect mplace) => | |
| match loadIndirectV2 mem (.int .isize false) mplace with | |
| | .ok (some (.scalar sv)) => .ok sv.bits.toNat | |
| | .ok none => .error .undefined | |
| | .ok (some _) => .error .unsupported | |
| | .error k => .error k | |
| | _, _ => .error .unsupported | |
| /-- Prepend projection `p` to a resolved projection list. -/ | |
| noncomputable def consResolvedProjV2 (p : ProjectionElem) : | |
| Except FaultKind (List ProjectionElem) → | |
| Except FaultKind (List ProjectionElem) | |
| | .ok rest => .ok (p :: rest) | |
| | .error k => .error k | |
| /-- Replace every `ProjectionElem.index localId` in `projs` with | |
| `.constantIndex i (i + 1) false`, where `i` is the value of local `localId` | |
| (`readIndexLocalV2`). | |
| The two projections agree on every array and slice of length `len` | |
| (`compiler/rustc_const_eval/src/interpret/projection.rs`, `rust-lang/rust` | |
| `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`): `project_index` faults when | |
| `i >= len` ("if index >= len { ... throw_ub!(BoundsCheckFailed { len, index | |
| }); }"), and `project_constant_index` faults when `len < i + 1` ("if n < | |
| min_length { ... throw_ub!(BoundsCheckFailed { len: min_length, index: n | |
| }); }") before projecting to index `offset = i`. -/ | |
| noncomputable def resolveIndexProjsV2 (bodyLocals : List MirTy) | |
| (locals : List LocalSlot) (mem : MemoryState) : | |
| List ProjectionElem → Except FaultKind (List ProjectionElem) | |
| | [] => .ok [] | |
| | .index l :: rest => | |
| match readIndexLocalV2 bodyLocals locals mem l with | |
| | .error k => .error k | |
| | .ok i => | |
| consResolvedProjV2 (.constantIndex i (i + 1) false) | |
| (resolveIndexProjsV2 bodyLocals locals mem rest) | |
| | .deref :: rest => | |
| consResolvedProjV2 .deref (resolveIndexProjsV2 bodyLocals locals mem rest) | |
| | .field idx ty :: rest => | |
| consResolvedProjV2 (.field idx ty) | |
| (resolveIndexProjsV2 bodyLocals locals mem rest) | |
| | .constantIndex off minLen fromEnd :: rest => | |
| consResolvedProjV2 (.constantIndex off minLen fromEnd) | |
| (resolveIndexProjsV2 bodyLocals locals mem rest) | |
| | .downcast v :: rest => | |
| consResolvedProjV2 (.downcast v) | |
| (resolveIndexProjsV2 bodyLocals locals mem rest) | |
| | .unsupported :: rest => | |
| consResolvedProjV2 .unsupported | |
| (resolveIndexProjsV2 bodyLocals locals mem rest) | |
| /-- Resolve the element place `(*p)[i].rest` of a slice `[elem]` addressed by | |
| the wide pointer `(p, len)`, where `projs` starts with the element projection | |
| `.constantIndex` (after `resolveIndexProjsV2`), returning the leaf type, its | |
| allocation, and its byte offset. | |
| The element index must be in bounds (`constantIndexOffset`), and the whole | |
| element must lie in bounds of a live allocation at its alignment | |
| (`.undefined` otherwise). A provenance-free pointer (a dangling slice of | |
| zero-sized elements) is unsupported. -/ | |
| noncomputable def sliceElemAddrV2 (mem : MemoryState) (elem : MirTy) | |
| (p : PtrVal) (len : Nat) : | |
| List ProjectionElem → Except FaultKind (MirTy × AllocId × Nat) | |
| | .constantIndex off minLen fromEnd :: rest => | |
| match layoutOfTyV2 elem with | |
| | none => .error .unsupported | |
| | some elemLay => | |
| match constantIndexOffset len off minLen fromEnd with | |
| | .error k => .error k | |
| | .ok idx => | |
| match projectMemoryLayoutV2 elem rest with | |
| | .error k => .error k | |
| | .ok (leafTy, subOff) => | |
| match p.allocId with | |
| | none => .error .unsupported | |
| | some aid => | |
| match findAllocation aid mem.allocations with | |
| | none => .error .undefined | |
| | some a => | |
| let elemOff := p.offsetBytes.toNat + idx * elemLay.size | |
| if !a.live || !isInBounds a elemOff elemLay.size || | |
| !isAligned a elemOff elemLay.alignLog2 then | |
| .error .undefined | |
| else | |
| .ok (leafTy, aid, elemOff + subOff) | |
| | _ => .error .unsupported | |
| /-- Read the dereferenced slice element place `(*p)[i].rest` in Profile v2, | |
| where `slot` holds the wide pointer of type `.ref/.rawPtr _ pt`. (`readPlaceV2` | |
| refuses a `move` of a `.deref` place before reaching here.) -/ | |
| noncomputable def readDerefSliceV2 (locals : List LocalSlot) | |
| (mem : MemoryState) (pt : MirTy) (slot : LocalSlot) | |
| (rest : List ProjectionElem) : | |
| Except FaultKind (MirTy × Option Val × List LocalSlot × MemoryState) := | |
| match pt with | |
| | .slice elem => | |
| let ptrRes : Except FaultKind (Option Val) := | |
| match slot with | |
| | .dead | .partialTuple _ => .error .undefined | |
| | .immediate optVal => .ok optVal | |
| | .indirect mplace => loadIndirectV2 mem (.rawPtr .shared pt) mplace | |
| match ptrRes with | |
| | .error k => .error k | |
| | .ok none => .error .undefined | |
| | .ok (some (.slicePtr p len)) => | |
| match sliceElemAddrV2 mem elem p len.toNat rest with | |
| | .error k => .error k | |
| | .ok (leafTy, aid, off) => | |
| match loadIndirectV2 mem leafTy ⟨aid, off⟩ with | |
| | .error k => .error k | |
| | .ok optVal => .ok (leafTy, optVal, locals, mem) | |
| | .ok (some _) => .error .unsupported | |
| | _ => .error .unsupported | |
| /-- Read a dereferenced projected place (`*p` followed by `.constantIndex` / | |
| `.field` projections) in Profile v2, including slice element places | |
| `(*p)[i].rest` (`readDerefSliceV2`). Both references (`isRef = true`) and raw | |
| pointers (`isRef = false`) require base-pointer alignment to `pt`; references | |
| additionally require the whole enclosing pointee `pt` to be live and in bounds, | |
| while raw pointers check liveness/bounds on the projected leaf access and, for | |
| any non-zero projection offset, require live provenance with the offset and | |
| leaf span in bounds even when the leaf is zero-sized. | |
| In `rustc_const_eval` (`rust-lang/rust` | |
| `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`), `project_field` | |
| (`compiler/rustc_const_eval/src/interpret/projection.rs:200`) offsets the place | |
| with `OffsetMode::Inbounds`: | |
| > "base.offset_with_meta(offset, OffsetMode::Inbounds, meta, field_layout, | |
| > self)" | |
| `MemPlace::offset_with_meta_` | |
| (`compiler/rustc_const_eval/src/interpret/place.rs:88-91`) dispatches | |
| `OffsetMode::Inbounds` to `ptr_offset_inbounds`: | |
| > "let ptr = match mode { | |
| > OffsetMode::Inbounds => { | |
| > ecx.ptr_offset_inbounds(self.ptr, offset.bytes().try_into().unwrap())? | |
| > }" | |
| and `ptr_offset_inbounds` | |
| (`compiler/rustc_const_eval/src/interpret/intrinsics.rs:1034-1039`) checks | |
| provenance, liveness, and bounds via `check_ptr_access_signed`: | |
| > "// The offset must be in bounds starting from `ptr`. | |
| > self.check_ptr_access_signed( | |
| > ptr, | |
| > offset_bytes, | |
| > CheckInAllocMsg::InboundsPointerArithmetic, | |
| > )?;" | |
| which delegates to `check_and_deref_ptr` (quoted on `readBytes`), skipping | |
| provenance, liveness, and bounds checks only when `offset_bytes == 0`. -/ | |
| noncomputable def readDerefProjectedV2 (locals : List LocalSlot) | |
| (mem : MemoryState) (isRef : Bool) (pt : MirTy) (slot : LocalSlot) | |
| (rest : List ProjectionElem) : | |
| Except FaultKind (MirTy × Option Val × List LocalSlot × MemoryState) := | |
| if isUnsizedTy pt then | |
| readDerefSliceV2 locals mem pt slot rest | |
| else | |
| match layoutOfTyV2 pt with | |
| | none => .error .unsupported | |
| | some ptLay => | |
| let ptrRes : Except FaultKind (Option Val) := | |
| match slot with | |
| | .dead | .partialTuple _ => .error .undefined | |
| | .immediate optVal => .ok optVal | |
| | .indirect mplace => loadIndirectV2 mem (.rawPtr .shared pt) mplace | |
| match ptrRes with | |
| | .error k => .error k | |
| | .ok none => .error .undefined | |
| | .ok (some (.ptr pv)) => | |
| match projectMemoryLayoutV2 pt rest with | |
| -- An `Option` payload downcast reads the discriminant in memory | |
| -- (`projectMemoryPlaceV2`); any other failure is unchanged. | |
| | .error k => | |
| match pv.allocId with | |
| | none => .error k | |
| | some aid => | |
| match projectMemoryPlaceV2 mem aid pv.offsetBytes.toNat pt [] rest with | |
| | .error k' => .error k' | |
| | .ok (leafTy, off) => | |
| match layoutOfTyV2 leafTy, findAllocation aid mem.allocations with | |
| | none, _ => .error .unsupported | |
| | _, none => .error .undefined | |
| | some leafLay, some a => | |
| if !isAligned a pv.offsetBytes.toNat ptLay.alignLog2 || | |
| (isRef && (!a.live || | |
| !isInBounds a pv.offsetBytes.toNat ptLay.size)) || | |
| (!isRef && Nat.blt 0 leafLay.size && !a.live) || | |
| !Nat.blt off (Nat.pow 2 64) then | |
| .error .undefined | |
| else | |
| -- References already checked whole-pointee liveness and | |
| -- bounds above; for raw pointers, non-zero projection | |
| -- offsets require live in-bounds provenance even for ZSTs. | |
| match isRef with | |
| | true => | |
| match loadIndirectV2 mem leafTy ⟨aid, off⟩ with | |
| | .error k => .error k | |
| | .ok optVal => .ok (leafTy, optVal, locals, mem) | |
| | false => | |
| if (Nat.blt pv.offsetBytes.toNat off && !a.live) || | |
| (Nat.blt pv.offsetBytes.toNat off && | |
| !isInBounds a off leafLay.size) then | |
| .error .undefined | |
| else | |
| match loadIndirectV2 mem leafTy ⟨aid, off⟩ with | |
| | .error k => .error k | |
| | .ok optVal => .ok (leafTy, optVal, locals, mem) | |
| | .ok (leafTy, subOff) => | |
| match layoutOfTyV2 leafTy with | |
| | none => .error .unsupported | |
| | some leafLay => | |
| match pv.allocId with | |
| | none => | |
| let addr := pv.offsetBytes.toNat + subOff | |
| -- Base alignment to `ptLay.alignLog2` also guarantees leaf | |
| -- alignment for every non-packed `projectMemoryLayoutV2` offset. | |
| let badBaseAlign := | |
| !Nat.beq (Nat.mod pv.offsetBytes.toNat (Nat.pow 2 ptLay.alignLog2)) 0 | |
| let badRefBase := | |
| isRef && (Nat.beq pv.offsetBytes.toNat 0 || Nat.blt 0 ptLay.size) | |
| let badProjOffset := Nat.blt 0 subOff | |
| let badLeaf := | |
| !Nat.blt addr (Nat.pow 2 64) || Nat.beq addr 0 || Nat.blt 0 leafLay.size | |
| if badBaseAlign || badRefBase || badProjOffset || badLeaf then | |
| .error .undefined | |
| else | |
| match decodeValV2 profileV2TargetEndian leafTy [] with | |
| | .error k => .error k | |
| | .ok optVal => .ok (leafTy, optVal, locals, mem) | |
| | some aid => | |
| match findAllocation aid mem.allocations with | |
| | none => .error .undefined | |
| | some a => | |
| if !isAligned a pv.offsetBytes.toNat ptLay.alignLog2 || | |
| (isRef && (!a.live || !isInBounds a pv.offsetBytes.toNat ptLay.size)) || | |
| (!isRef && Nat.blt 0 leafLay.size && !a.live) || | |
| !Nat.blt (pv.offsetBytes.toNat + subOff) (Nat.pow 2 64) then | |
| .error .undefined | |
| else | |
| -- References already checked whole-pointee liveness and | |
| -- bounds above; for raw pointers, non-zero projection | |
| -- offsets require live in-bounds provenance even for ZSTs. | |
| match isRef with | |
| | true => | |
| match loadIndirectV2 mem leafTy ⟨aid, pv.offsetBytes.toNat + subOff⟩ with | |
| | .error k => .error k | |
| | .ok optVal => .ok (leafTy, optVal, locals, mem) | |
| | false => | |
| if (Nat.blt 0 subOff && !a.live) || | |
| (Nat.blt 0 subOff && | |
| !isInBounds a pv.offsetBytes.toNat (subOff + leafLay.size)) then | |
| .error .undefined | |
| else | |
| match loadIndirectV2 mem leafTy ⟨aid, pv.offsetBytes.toNat + subOff⟩ with | |
| | .error k => .error k | |
| | .ok optVal => .ok (leafTy, optVal, locals, mem) | |
| | .ok (some _) => .error .unsupported | |
| /-- Per-field initialization of a tuple held directly in a local slot: | |
| `some (vs.map some)` for an initialized immediate tuple `vs`, `some fs` for a | |
| partially moved tuple, and `none` otherwise. -/ | |
| noncomputable def tupleSlotFields? : LocalSlot → Option (List (Option Val)) | |
| | .immediate (some (.tuple vs)) => some (vs.map some) | |
| | .partialTuple fs => some fs | |
| | _ => none | |
| /-- Return `true` when `projs` contains a `.downcast`. -/ | |
| noncomputable def projsHaveDowncastV2 : List ProjectionElem → Bool | |
| | [] => false | |
| | .downcast _ :: _ => true | |
| | _ :: rest => projsHaveDowncastV2 rest | |
| /-- A `move` out of the field chain `l.rest` of the local `l`, with no | |
| dereference (`move (_l.f)`, `move ((_l.f).g)`, `move ((_l.f as V).i)`), the | |
| shape `rustc` emits for a partial move out of a struct or out of a variant of | |
| an enum field. The local is first moved to its stack allocation | |
| (`promoteLocalToMemory`, as taking a reference to it does; a local already | |
| there stays put). The leaf at `rest`, whose projections may be field, | |
| constant-index, and variant (`.downcast v` then `.field i`) ones | |
| (`projectMemoryPlaceV2`, which reads the whole enum at a downcast and faults | |
| with `.undefined` unless it holds `v`), is loaded (`loadIndirectV2` | |
| validates it; an uninitialized leaf is `.undefined`, as reading a moved-out | |
| local is). | |
| MIR leaves open whether a move deinitializes its place (see `readPlaceV2`). | |
| Without a downcast the leaf is deinitialized, the stricter reading: the | |
| place is a local rather than caller memory, and a body that reads the moved | |
| field again faults rather than reading the stale bytes. Through a downcast | |
| the leaf is left in place, the reading Miri implements: a variant's field may | |
| hold a niche enum's tag, and a later downcast reads the whole enum, so | |
| deinitializing the field would make both fault. MIR never reads a moved | |
| field again, and drop elaboration never drops an enum whole after a partial | |
| move out of it, so leaving the bytes changes no execution of a body `rustc` | |
| emits. The locals returned are those after the promotion. -/ | |
| noncomputable def moveLocalPlaceV2 (bodyLocals : List MirTy) | |
| (locals : List LocalSlot) (mem : MemoryState) (place : Place) : | |
| Except FaultKind (MirTy × Option Val × List LocalSlot × MemoryState) := | |
| match promoteLocalToMemory bodyLocals locals mem place.localId with | |
| | .error k => .error k | |
| | .ok (lt, mp, locals1, mem1) => | |
| match projectMemoryPlaceV2 mem1 mp.allocId mp.offset lt [] place.projection | |
| with | |
| | .error k => .error k | |
| | .ok (leafTy, off) => | |
| let leaf : MemPlace := ⟨mp.allocId, off⟩ | |
| match loadIndirectV2 mem1 leafTy leaf with | |
| | .error k => .error k | |
| | .ok none => .error .undefined | |
| | .ok (some v) => | |
| if projsHaveDowncastV2 place.projection then | |
| .ok (leafTy, some v, locals1, mem1) | |
| else | |
| match deinitIndirectV2 mem1 leafTy leaf with | |
| | .error k => .error k | |
| | .ok mem2 => .ok (leafTy, some v, locals1, mem2) | |
| /-- Return `true` when every element of `projs` is a `.field` or a | |
| `.downcast`. -/ | |
| noncomputable def projsFieldOrDowncastV2 : List ProjectionElem → Bool | |
| | [] => true | |
| | .field _ _ :: rest | .downcast _ :: rest => projsFieldOrDowncastV2 rest | |
| | _ :: _ => false | |
| /-- A `move` out of the nested field/variant chain `(_t.idx).rest` (`rest` | |
| non-empty, holding only `.field` and `.downcast` elements, and containing at | |
| least one `.downcast`) of a tuple `_t` held directly in its local slot `slot`, | |
| such as `move ((_t.1 as Some).0)` after a `match` on a tuple temporary. A | |
| tuple has no layout, so `moveLocalPlaceV2` cannot move it to memory; the leaf | |
| is projected from the value of field `idx` instead (`projectValFieldV2`, | |
| which faults with `.undefined` on a variant the value does not hold), and the | |
| tuple is left in place, as `moveLocalPlaceV2` does through a downcast. A | |
| nested non-downcast tuple move (`move ((_t.0).1)`) fails closed with | |
| `.unsupported` because `LocalSlot.partialTuple` tracks only top-level field | |
| initialization and cannot deinitialize a single sub-field without falsely | |
| faulting sibling sub-fields. -/ | |
| noncomputable def moveTuplePathV2 (locals : List LocalSlot) | |
| (mem : MemoryState) (fs : List (Option Val)) | |
| (ts : List MirTy) (idx : Nat) (fTy : MirTy) | |
| (rest : List ProjectionElem) : | |
| Except FaultKind (MirTy × Option Val × List LocalSlot × MemoryState) := | |
| if !projsFieldOrDowncastV2 rest then | |
| .error .unsupported | |
| else if !projsHaveDowncastV2 rest then | |
| .error .unsupported | |
| else | |
| match getElem? ts idx, getElem? fs idx with | |
| | some elemTy, some (some elemVal) => | |
| if !MirTy.beq elemTy fTy then | |
| .error .unsupported | |
| else | |
| match projectValFieldV2 elemTy elemVal rest with | |
| | .error k => .error k | |
| | .ok (leafTy, leafVal) => | |
| .ok (leafTy, some leafVal, locals, mem) | |
| | some _, some none => .error .undefined | |
| | _, _ => .error .unsupported | |
| /-- Read a projected `Place` in Profile v2, supporting unprojected locals, | |
| immediate tuple/range/array `.field`/`.constantIndex` projections, and `.deref` | |
| (optionally followed by sub-projections) on sized references and raw pointers. | |
| `isMove` additionally deinitializes unprojected locals (and memory slots for | |
| indirect stack moves). A `move` of a `.deref` place fails closed with | |
| `.unsupported`. Projections of an `.indirect` local resolve with | |
| `projectMemoryPlaceV2`, as those of a deref place do, so an `Option` payload | |
| downcast (`(x as Some).0`) reads the whole `Option` first. | |
| A `move` of a single-level `.field` of a tuple held directly in a local | |
| deinitializes only that field, leaving the local as a | |
| `LocalSlot.partialTuple`. Rustc emits this shape under `-Coverflow-checks=yes`: | |
| `assert(!move (_t.1: bool))` followed by `_r = move (_t.0: T)` on an | |
| overflow pair `_t`. The moved field takes its `liveUninitSlot` value, as a | |
| moved unprojected local does, so reading it again faults with `.undefined` | |
| unless it is zero-sized. Reading a partially moved tuple as a whole also | |
| faults with `.undefined`. Once every field is uninitialized the slot is | |
| `.immediate none` again, the state a whole-tuple move leaves. MIR leaves open | |
| whether a move deinitializes its place (see below), but the tuple is a local | |
| rather than caller memory, so a body that never reads the moved field again, | |
| as every verified body must, behaves the same under either reading. A move | |
| out of a nested field chain of such a tuple is `moveTuplePathV2`. Every other | |
| move out of a field chain of a local (a field of a struct local, a nested | |
| field, or a field of a local already in memory) is `moveLocalPlaceV2`, which | |
| moves the field out of the local's stack allocation. | |
| The deref case follows the Reference | |
| (`src/behavior-considered-undefined.md:26-28`, `rust-lang/reference` | |
| `ad35aca481751a06afeb23820a672b0f3b11a476`): | |
| > "* Accessing (loading from or storing to) a place that is [dangling] or | |
| > [based on a misaligned pointer]." | |
| The interpreter turns `*p` into a place aligned for the pointee type | |
| (`deref_pointer`), and `get_place_alloc` checks bounds and liveness before | |
| alignment (`compiler/rustc_const_eval/src/interpret/place.rs:490-497`, | |
| `rust-lang/rust` `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`): | |
| > "let (size, _align) = self | |
| > .size_and_align_of_val(mplace)? | |
| > .unwrap_or((mplace.layout.size, mplace.layout.align.abi)); | |
| > // We check alignment separately, and *after* checking everything else. | |
| > // If an access is both OOB and misaligned, we want to see the bounds error. | |
| > let a = self.get_ptr_alloc(mplace.ptr(), size)?; | |
| > self.check_misalign(mplace.mplace.misaligned, CheckAlignMsg::BasedOn)?;" | |
| `get_ptr_alloc` skips the bounds and liveness checks for size 0 | |
| (`check_and_deref_ptr`). `loadIndirectV2` reuses `readBytes`, which has | |
| exactly that split. | |
| `move` of a `.deref` place is rejected because MIR leaves its effect | |
| unspecified (`compiler/rustc_middle/src/mir/syntax.rs:1310-1319`, same | |
| `rust-lang/rust` pin): | |
| > "Creates a value by performing loading the place, just like the `Copy` | |
| > operand. | |
| > | |
| > This *may* additionally overwrite the place with `uninit` bytes, depending | |
| > on how we decide in [UCG#188]. You should not emit MIR that may attempt a | |
| > subsequent second load of this place without first re-initializing it. | |
| > | |
| > **Needs clarification:** The operational impact of `Move` is unclear. | |
| > Currently (both in Miri and codegen) it has no effect at all unless it | |
| > appears in an argument to `Call`; for `Call` it allows the argument to be | |
| > passed to the callee "in-place", i.e. the callee might just get a reference | |
| > to this place instead of a full copy." | |
| Deinitializing the pointee could expose `uninit` caller bytes on return | |
| (`extractCallerMemory`) where the real program leaves the old bytes, and | |
| treating the move as a copy would pick the other resolution. Failing closed | |
| avoids committing to either. -/ | |
| noncomputable def readPlaceV2 (bodyLocals : List MirTy) (locals : List LocalSlot) | |
| (mem : MemoryState) (isMove : Bool) (place : Place) : | |
| Except FaultKind (MirTy × Option Val × List LocalSlot × MemoryState) := | |
| match getElem? bodyLocals place.localId, getElem? locals place.localId with | |
| | some _, some .dead => .error .undefined | |
| | some baseTy, some slot => | |
| match place.projection with | |
| | [] => | |
| if !isSupportedV2LocalTy baseTy then | |
| .error .unsupported | |
| else | |
| match slot with | |
| | .dead => .error .undefined | |
| | .partialTuple _ => .error .undefined | |
| | .immediate optVal => | |
| if isMove then | |
| match setElem? locals place.localId (liveUninitSlot baseTy) with | |
| | some locals1 => .ok (baseTy, optVal, locals1, mem) | |
| | none => .error .unsupported | |
| else | |
| .ok (baseTy, optVal, locals, mem) | |
| | .indirect mplace => | |
| match loadIndirectV2 mem baseTy mplace with | |
| | .error k => .error k | |
| | .ok optVal => | |
| if isMove then | |
| match deinitIndirectV2 mem baseTy mplace with | |
| | .ok mem1 => .ok (baseTy, optVal, locals, mem1) | |
| | .error k => .error k | |
| else | |
| .ok (baseTy, optVal, locals, mem) | |
| | .deref :: rest => | |
| if isMove then | |
| .error .unsupported | |
| else if !rest.isEmpty then | |
| match resolveIndexProjsV2 bodyLocals locals mem rest with | |
| | .error k => .error k | |
| | .ok rest' => | |
| match baseTy with | |
| | .ref _ pt => | |
| readDerefProjectedV2 locals mem true pt slot rest' | |
| | .rawPtr _ pt => | |
| readDerefProjectedV2 locals mem false pt slot rest' | |
| | _ => .error .unsupported | |
| else | |
| match baseTy with | |
| | .ref _ pt | .rawPtr _ pt => | |
| if isUnsizedTy pt then | |
| .error .unsupported | |
| else | |
| match layoutOfTyV2 pt with | |
| | none => .error .unsupported | |
| | some lay => | |
| let ptrRes : Except FaultKind (Option Val) := | |
| match slot with | |
| | .dead | .partialTuple _ => .error .undefined | |
| | .immediate optVal => .ok optVal | |
| | .indirect mplace => loadIndirectV2 mem baseTy mplace | |
| match ptrRes with | |
| | .error k => .error k | |
| | .ok none => .error .undefined | |
| | .ok (some (.ptr pv)) => | |
| match pv.allocId with | |
| -- No provenance: only a zero-sized access at a non-null | |
| -- aligned address is accepted (`without_provenance` permits | |
| -- zero-sized accesses "if suitably aligned"; see | |
| -- `library/core/src/ptr/mod.rs:887-890` at `rust-lang/rust` | |
| -- `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`). Null is | |
| -- rejected even for ZSTs. That matches `core::ptr` ("*every* | |
| -- non-null pointer", `ptr/mod.rs:19`) and is stricter than | |
| -- the Reference ("even if it is a null pointer", | |
| -- `behavior-considered-undefined.md:142-143` at | |
| -- `ad35aca481751a06afeb23820a672b0f3b11a476`) and rustc's | |
| -- `check_null.rs:69`. The two sources conflict for | |
| -- integer-derived pointers: the Reference | |
| -- (`types/pointer.md:73`) says an integer-*transmuted* pointer | |
| -- "may not be dereferenced (not even if `T` has [size zero])", | |
| -- whereas `core::ptr` permits the zero-sized access. This arm | |
| -- follows `core::ptr`, the library contract unsafe code is | |
| -- written against. | |
| | none => | |
| if Nat.beq pv.offsetBytes.toNat 0 || Nat.blt 0 lay.size || | |
| !Nat.beq (Nat.mod pv.offsetBytes.toNat (Nat.pow 2 lay.alignLog2)) 0 then | |
| .error .undefined | |
| else | |
| match decodeValV2 profileV2TargetEndian pt [] with | |
| | .error k => .error k | |
| | .ok optVal => .ok (pt, optVal, locals, mem) | |
| | some aid => | |
| match loadIndirectV2 mem pt ⟨aid, pv.offsetBytes.toNat⟩ with | |
| | .error k => .error k | |
| | .ok optVal => | |
| match pt, optVal with | |
| -- An inner reference is read only if it is valid. A | |
| -- `&mut T` read from behind a shared reference is the | |
| -- `deref_copy` a match guard on `&mut self` reads its | |
| -- binding with; capture refuses every use of the copy | |
| -- but reads through it (`check_nested_mut_ref_copies`), | |
| -- so it is never written through. | |
| | .ref _ _, some v => | |
| if !refsValidInMem mem pt v then | |
| .error .undefined | |
| else | |
| .ok (pt, some v, locals, mem) | |
| | _, _ => .ok (pt, optVal, locals, mem) | |
| | .ok (some _) => .error .unsupported | |
| | _ => .error .unsupported | |
| | .field idx fTy :: rest => | |
| if isMove then | |
| if !rest.isEmpty then | |
| match slot with | |
| | .dead | .immediate none => .error .undefined | |
| | _ => | |
| match baseTy, tupleSlotFields? slot with | |
| | .tuple ts, some fs => | |
| moveTuplePathV2 locals mem fs ts idx fTy rest | |
| | _, _ => moveLocalPlaceV2 bodyLocals locals mem place | |
| else | |
| match slot with | |
| | .dead | .immediate none => .error .undefined | |
| | _ => | |
| match baseTy, tupleSlotFields? slot with | |
| | .tuple ts, some fs => | |
| match getElem? ts idx, getElem? fs idx with | |
| | some elemTy, some (some elemVal) => | |
| if !MirTy.beq elemTy fTy then | |
| .error .unsupported | |
| else | |
| let movedVal : Option Val := | |
| match liveUninitSlot elemTy with | |
| | .immediate v => v | |
| | _ => none | |
| match setElem? fs idx movedVal with | |
| | some fs' => | |
| let slot' : LocalSlot := | |
| if fs'.all Option.isNone then .immediate none | |
| else .partialTuple fs' | |
| match setElem? locals place.localId slot' with | |
| | some locals1 => .ok (elemTy, some elemVal, locals1, mem) | |
| | none => .error .unsupported | |
| | none => .error .unsupported | |
| | some _, some none => .error .undefined | |
| | _, _ => .error .unsupported | |
| | _, _ => moveLocalPlaceV2 bodyLocals locals mem place | |
| else | |
| -- Resolve `Index` projections in `rest` (`t.f[i]`) before reading. | |
| match resolveIndexProjsV2 bodyLocals locals mem place.projection with | |
| | .error k => .error k | |
| | .ok projs => | |
| match slot with | |
| | .dead | .immediate none => .error .undefined | |
| | .immediate (some v) => | |
| match projectValFieldV2 baseTy v projs with | |
| | .error k => .error k | |
| | .ok (fty, fv) => .ok (fty, some fv, locals, mem) | |
| | .indirect mplace => | |
| -- As for a deref place, an `Option` payload downcast reads the | |
| -- whole `Option` first (`projectMemoryPlaceV2`). | |
| match projectMemoryPlaceV2 mem mplace.allocId mplace.offset baseTy | |
| [] projs with | |
| | .error k => .error k | |
| | .ok (leafTy, off) => | |
| match loadIndirectV2 mem leafTy ⟨mplace.allocId, off⟩ with | |
| | .error k => .error k | |
| | .ok optVal => .ok (leafTy, optVal, locals, mem) | |
| | .partialTuple fs => | |
| if !rest.isEmpty then | |
| .error .unsupported | |
| else | |
| match baseTy with | |
| | .tuple ts => | |
| match getElem? ts idx, getElem? fs idx with | |
| | some elemTy, some (some elemVal) => | |
| if !MirTy.beq elemTy fTy then .error .unsupported | |
| else .ok (elemTy, some elemVal, locals, mem) | |
| | some _, some none => .error .undefined | |
| | _, _ => .error .unsupported | |
| | _ => .error .unsupported | |
| | .constantIndex _ _ _ :: _ | .downcast _ :: _ | .index _ :: _ => | |
| -- Only an immediate `Option` local (`(x as Some).0`) or a single-field | |
| -- variant of a non-heap-owning immediate payload enum (`(x as V).0`) | |
| -- may be moved out of through a downcast: non-heap moves deinitialize | |
| -- the whole local below, while a heap-owning `Option` local | |
| -- (`Option<Vec<T>>`, `Option<Box<P>>`) is left in place so drop | |
| -- elaboration's `discriminant(_x)` check on conditional partial moves | |
| -- succeeds (matching `moveLocalPlaceV2` and `moveTuplePathV2`). | |
| -- Multi-field variants, heap-owning payload enums, and in-memory locals | |
| -- stay refused. | |
| let allowDowncastMove := | |
| match baseTy, place.projection, slot with | |
| | .option _, [.downcast 1, .field 0 _], .immediate _ => true | |
| | .adtEnum _ vs, [.downcast vidx, .field 0 _], .immediate _ => | |
| if tyHasHeapHandleV2 baseTy then false | |
| else | |
| match getElem? vs vidx with | |
| | some (.struct_ _ [_]) => true | |
| | _ => false | |
| | _, _, _ => false | |
| if isMove && !allowDowncastMove then | |
| .error .unsupported | |
| else | |
| match resolveIndexProjsV2 bodyLocals locals mem place.projection with | |
| | .error k => .error k | |
| | .ok projs => | |
| match slot with | |
| | .dead | .immediate none => .error .undefined | |
| | .partialTuple _ => .error .unsupported | |
| | .immediate (some v) => | |
| match projectValFieldV2 baseTy v projs with | |
| | .error k => .error k | |
| | .ok (fty, fv) => | |
| if isMove then | |
| if tyHasHeapHandleV2 baseTy then | |
| .ok (fty, some fv, locals, mem) | |
| else | |
| match setElem? locals place.localId (liveUninitSlot baseTy) with | |
| | some locals1 => .ok (fty, some fv, locals1, mem) | |
| | none => .error .unsupported | |
| else | |
| .ok (fty, some fv, locals, mem) | |
| | .indirect mplace => | |
| match projectMemoryPlaceV2 mem mplace.allocId mplace.offset baseTy | |
| [] projs with | |
| | .error k => .error k | |
| | .ok (leafTy, off) => | |
| match loadIndirectV2 mem leafTy ⟨mplace.allocId, off⟩ with | |
| | .error k => .error k | |
| | .ok optVal => .ok (leafTy, optVal, locals, mem) | |
| | .unsupported :: _ => .error .unsupported | |
| | _, _ => .error .unsupported | |
| /-- Return `true` when `ty` is an owned payload enum (`.adtEnum` or | |
| `.recAdt _ (.adtEnum _ _)`) whose active variant decoded from provenance-free | |
| `bytes` is heap-free owned data (`isOwnedDataTyV2 vTy` and | |
| `!tyHasHeapHandleV2 vTy`), guaranteeing that decoding the constant never | |
| fabricates a `Vec`/`Box` heap handle or `RecSelf` from `.rodata` while | |
| admitting heap-free `Option` and nested payload-enum fields. -/ | |
| noncomputable def rodataAdtVariantDataOkV2 (ty : MirTy) | |
| (bytes : List AllocByte) : Bool := | |
| if !isOwnedDataTyV2 ty then | |
| false | |
| else | |
| let adt? : Option (AdtEnumLayout × List MirTy) := | |
| match ty with | |
| | .adtEnum l vs => some (l, vs) | |
| | .recAdt _ (.adtEnum l vs) => some (l, vs) | |
| | _ => none | |
| match adt? with | |
| | none => false | |
| | some (l, vs) => | |
| match layoutOfTyV2 ty with | |
| | none => false | |
| | some lay => | |
| if !Nat.beq bytes.length lay.size then | |
| false | |
| else | |
| match adtDecodeVariantV2 profileV2TargetEndian l bytes with | |
| | .ok (some i) => | |
| match getElem? vs i with | |
| | some vTy => isOwnedDataTyV2 vTy && !tyHasHeapHandleV2 vTy | |
| | none => false | |
| | _ => false | |
| /-- Return `true` when sized `.rodataRef` pointee `pt` at `offsetBytes` in | |
| `allocBytes` is either pure V2 data or an owned payload enum whose active | |
| variant is heap-free owned data. -/ | |
| noncomputable def rodataPointeeOkV2 (pt : MirTy) (allocBytes : List AllocByte) | |
| (offsetBytes : Nat) : Bool := | |
| isSupportedV2DataTy pt || | |
| match layoutOfTyV2 pt with | |
| | some lay => | |
| rodataAdtVariantDataOkV2 pt | |
| ((allocBytes.drop offsetBytes).take lay.size) | |
| | none => false | |
| /-- Evaluate an immutable `.rodata` constant reference/slice by allocating a | |
| read-only provenance-free `Allocation` in `mem` and checking `refValidInMem` | |
| for reference types. Mutable `&mut`/`*mut` constants into read-only memory and | |
| out-of-range sizes, alignments, offsets, or lengths fail closed with | |
| `.unsupported`. | |
| A shared `&str` constant must additionally hold valid UTF-8 | |
| (`strSliceUtf8InMem`). The Reference requires only that a `str` value be | |
| initialized (`src/behavior-considered-undefined.md:180-181`, | |
| `rust-lang/reference` `ad35aca481751a06afeb23820a672b0f3b11a476`), so UTF-8 is | |
| a library safety invariant rather than a validity invariant. Initialized | |
| non-UTF-8 bytes therefore fail closed with `.unsupported` rather than | |
| `.undefined`, mirroring `validatePanicAbortArgs` and the capture-side check in | |
| `validate_constant`. -/ | |
| noncomputable def evalRodataRefConstV2 (ty : MirTy) (bytes : List RodataByte) | |
| (alignLog2 offsetBytes : Nat) (sliceLen : Option Nat) | |
| (locals : List LocalSlot) (mem : MemoryState) : | |
| Except FaultKind (MirTy × Option Val × List LocalSlot × MemoryState) := | |
| if !Nat.blt bytes.length isizeMaxBytes || !Nat.ble alignLog2 29 || | |
| !Nat.blt offsetBytes (Nat.pow 2 64) then | |
| .error .unsupported | |
| else | |
| let allocBytes := bytes.map rodataByteToAllocByte | |
| let (mem1, aid) := allocRodataMemory mem allocBytes alignLog2 | |
| let ptr : PtrVal := ⟨some aid, UInt64.ofNat offsetBytes, .isize⟩ | |
| match ty, sliceLen with | |
| | .ref reqMut (.slice elem), some len => | |
| if !Nat.blt len (Nat.pow 2 64) then | |
| .error .unsupported | |
| else if Mutability.beq reqMut .mut then | |
| .error .unsupported | |
| else | |
| let v : Val := .slicePtr ptr (UInt64.ofNat len) | |
| match refValidInMem mem1 .shared (.slice elem) v with | |
| | .error k => .error k | |
| | .ok () => .ok (ty, some v, locals, mem1) | |
| | .ref reqMut .str, some len => | |
| if !Nat.blt len (Nat.pow 2 64) then | |
| .error .unsupported | |
| else if Mutability.beq reqMut .mut then | |
| .error .unsupported | |
| else | |
| let v : Val := .slicePtr ptr (UInt64.ofNat len) | |
| match refValidInMem mem1 .shared .str v with | |
| | .error k => .error k | |
| | .ok () => | |
| if !strSliceUtf8InMem mem1 ptr (UInt64.ofNat len) then | |
| .error .unsupported | |
| else | |
| .ok (ty, some v, locals, mem1) | |
| | .rawPtr reqMut (.slice _), some len => | |
| if !Nat.blt len (Nat.pow 2 64) then | |
| .error .unsupported | |
| else if Mutability.beq reqMut .mut then | |
| .error .unsupported | |
| else | |
| .ok (ty, some (.slicePtr ptr (UInt64.ofNat len)), locals, mem1) | |
| | .ref reqMut pt, none => | |
| if isUnsizedTy pt || !rodataPointeeOkV2 pt allocBytes offsetBytes then | |
| .error .unsupported | |
| else if Mutability.beq reqMut .mut then | |
| .error .unsupported | |
| else | |
| let v : Val := .ptr ptr | |
| match refValidInMem mem1 .shared pt v with | |
| | .error k => .error k | |
| | .ok () => .ok (ty, some v, locals, mem1) | |
| | .rawPtr reqMut pt, none => | |
| if isUnsizedTy pt || !isSupportedV2DataTy pt then | |
| .error .unsupported | |
| else if Mutability.beq reqMut .mut then | |
| .error .unsupported | |
| else | |
| .ok (ty, some (.ptr ptr), locals, mem1) | |
| | _, _ => .error .unsupported | |
| /-- Stage 1 of Profile v2 operand evaluation. -/ | |
| noncomputable def evalOperandToSlotV2 (bodyLocals : List MirTy) | |
| (locals : List LocalSlot) (mem : MemoryState) : | |
| Operand → Except FaultKind (MirTy × Option Val × List LocalSlot × MemoryState) | |
| | .copy place => readPlaceV2 bodyLocals locals mem false place | |
| | .move place => readPlaceV2 bodyLocals locals mem true place | |
| | .constant c => | |
| match c.lit with | |
| | .scalar _ => | |
| match evalConstLit c.ty c.lit with | |
| | .ok v => .ok (c.ty, some v, locals, mem) | |
| | .error k => .error k | |
| | .zeroSized => | |
| match c.ty with | |
| | .struct_ l fs => | |
| -- A zero-sized struct constant (`ConstValue::ZeroSized`) has no | |
| -- bytes; its value is decoded from the empty byte list. | |
| match decodeValV2 profileV2TargetEndian (.struct_ l fs) [] with | |
| | .ok (some v) => .ok (c.ty, some v, locals, mem) | |
| | .ok none => .error .undefined | |
| | .error k => .error k | |
| | .adtEnum l vs => | |
| -- A zero-sized payload enum constant (`ConstValue::ZeroSized`) has no | |
| -- bytes; `decodeValV2` checks `layoutOfTyV2` (rejecting any non-ZST | |
| -- field) and decodes its single variant from the empty byte list. | |
| match decodeValV2 profileV2TargetEndian (.adtEnum l vs) [] with | |
| | .ok (some v) => .ok (c.ty, some v, locals, mem) | |
| | .ok none => .error .undefined | |
| | .error k => .error k | |
| | _ => | |
| match evalConstLit c.ty c.lit with | |
| | .ok v => .ok (c.ty, some v, locals, mem) | |
| | .error k => .error k | |
| | .rodataBytes bytes => | |
| let allocBytes := bytes.map rodataByteToAllocByte | |
| if !isSupportedV2DataTy c.ty && | |
| !rodataAdtVariantDataOkV2 c.ty allocBytes then | |
| .error .unsupported | |
| else | |
| match decodeValV2 profileV2TargetEndian c.ty allocBytes with | |
| | .ok (some v) => .ok (c.ty, some v, locals, mem) | |
| | .ok none => .error .undefined | |
| | .error k => .error k | |
| | .rodataRef bytes alignLog2 offsetBytes sliceLen => | |
| evalRodataRefConstV2 c.ty bytes alignLog2 offsetBytes sliceLen locals mem | |
| /-- Stage 2 of Profile v2 operand evaluation for primitive values. -/ | |
| noncomputable def evalPrimitiveOperandV2 (bodyLocals : List MirTy) | |
| (locals : List LocalSlot) (mem : MemoryState) (opnd : Operand) : | |
| Except FaultKind (Val × List LocalSlot × MemoryState) := | |
| match evalOperandToSlotV2 bodyLocals locals mem opnd with | |
| | .error k => .error k | |
| | .ok (ty, optVal, locals1, mem1) => | |
| if !isPrimitiveReadableTy ty then | |
| .error .unsupported | |
| else | |
| match optVal with | |
| | some v => .ok (v, locals1, mem1) | |
| | none => .error .undefined | |
| /-- Evaluate a list of operands left-to-right in Profile v2, requiring each | |
| operand to be initialized. -/ | |
| noncomputable def evalArgOperandsV2 (bodyLocals : List MirTy) | |
| (locals : List LocalSlot) (mem : MemoryState) : | |
| List Operand → Except FaultKind (List (MirTy × Val) × List LocalSlot × MemoryState) | |
| | [] => .ok ([], locals, mem) | |
| | opnd :: rest => | |
| match evalOperandToSlotV2 bodyLocals locals mem opnd with | |
| | .error k => .error k | |
| | .ok (_, none, _, _) => .error .undefined | |
| | .ok (ty, some v, locals1, mem1) => | |
| match evalArgOperandsV2 bodyLocals locals1 mem1 rest with | |
| | .error k => .error k | |
| | .ok (vs, locals2, mem2) => .ok ((ty, v) :: vs, locals2, mem2) | |
| /-- Extract values only from an argument list when tuple-constructing. -/ | |
| noncomputable def argValues : List (MirTy × Val) → List Val | |
| | [] => [] | |
| | (_, v) :: rest => v :: argValues rest | |
| /-- Return `true` when `ty` is a `*const T` raw pointer type. -/ | |
| noncomputable def isConstRawPtrTy : MirTy → Bool | |
| | .rawPtr .shared _ => true | |
| | _ => false | |
| /-- Check pointer-to-pointer cast compatibility in Profile v2 (preserving | |
| provenance while disallowing forging references or mismatched slice elements). | |
| `CastKind::PtrToPtr` is the identity on the pointer value whenever source and | |
| target have the same size | |
| (`compiler/rustc_const_eval/src/interpret/cast.rs:197-200`, `rust-lang/rust` | |
| `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`): | |
| > "// Handle casting any ptr to raw ptr (might be a wide ptr). | |
| > if cast_to.size == src.layout.size { | |
| > // Thin or wide pointer that just has the ptr kind of target type | |
| > // changed. | |
| > return interp_ok(ImmTy::from_immediate(**src, cast_to));" | |
| Profile v2 supports thin-to-thin casts, and wide `[E]`-to-`[E]` casts with | |
| the same element type. Both preserve the address, provenance, and length. | |
| Dropping the metadata (wide to thin, `cast.rs:201-207`) fails closed with | |
| `.unsupported`. Only raw-pointer sources are accepted, because MIR never | |
| expresses a reference-to-raw conversion as a cast (see `CastKind.ptrToPtr`). | |
| A `*const T` to `*mut T` cast also fails closed with `.unsupported`. Profile | |
| v2 models no aliasing rules, and `allocateStack` makes every local's | |
| allocation writable. In MIR that `rustc` accepts, the cast is the only way a | |
| v2 body can obtain a writable pointer into a local it may not mutate | |
| (`&raw const x as *mut T` with `x` not `mut`). The Rust Reference makes | |
| writing through such a pointer undefined behavior | |
| (`src/behavior-considered-undefined.md:50-57`, `rust-lang/reference` | |
| `ad35aca481751a06afeb23820a672b0f3b11a476`): | |
| > "* Mutating immutable bytes. | |
| > ... | |
| > The bytes owned by an immutable binding or immutable `static` are | |
| > immutable, unless those bytes are part of an [`UnsafeCell<U>`]." | |
| The borrow checker rejects `&raw mut x` unless `x` is `mut`, and `&raw mut *p` | |
| for `p : *const T`; Profile v2 has no `UnsafeCell`; and `writePlaceV2` | |
| refuses stores through `*const T`. Refusing this cast removes that route. -/ | |
| noncomputable def evalPtrToPtrCastV2 (srcTy : MirTy) (srcVal : Val) | |
| (castTy : MirTy) : Except FaultKind Val := | |
| match castTy with | |
| | .rawPtr castMut castPt => | |
| if isConstRawPtrTy srcTy && Mutability.beq castMut .mut then | |
| .error .unsupported | |
| else | |
| match srcTy, srcVal with | |
| | .rawPtr _ srcPt, .ptr p => | |
| if isUnsizedTy srcPt || isUnsizedTy castPt then | |
| .error .unsupported | |
| else | |
| .ok (.ptr p) | |
| | .rawPtr _ (.slice srcElem), .slicePtr p len => | |
| match castPt with | |
| | .slice castElem => | |
| if MirTy.beq srcElem castElem then | |
| .ok (.slicePtr p len) | |
| else | |
| .error .unsupported | |
| | _ => .error .unsupported | |
| | _, _ => .error .unsupported | |
| | _ => .error .unsupported | |
| /-- Return `true` when the projections `projs` of a place of type `ty` | |
| downcast anything other than an `Option`: a payload enum (`.adtEnum`), or a | |
| type that the static walk below loses track of (conservatively). The walk | |
| follows each `.field`'s recorded type, the pointee of a `.deref`, and the | |
| element of an array or slice index. | |
| A pointer that permits writes to a payload enum variant's field could store | |
| bytes at the tag of a niche enum, whose untagged variant's fields overlap the | |
| niche, without the check `adtFinishEncodeV2` makes when a whole enum value is | |
| written. So `Rvalue.addressOf` refuses a mutable raw borrow through such a | |
| downcast (`.unsupported`), as `rustc-capture` does (`ir.rs` `check_place`, | |
| which also refuses writes), and `Rvalue.ref` refuses a mutable borrow except | |
| of a field through which no valid store changes the variant | |
| (`projsDowncastMutUnsafeV2`). Writes through a downcast place are already | |
| refused: `resolvePlaceDestV2` has no downcast. -/ | |
| noncomputable def projsDowncastNonOptionV2 : MirTy → List ProjectionElem → Bool | |
| | _, [] => false | |
| | ty, .downcast _ :: rest => | |
| match ty with | |
| | .option _ => projsDowncastNonOptionV2 ty rest | |
| | _ => true | |
| | _, .field _ fTy :: rest => projsDowncastNonOptionV2 fTy rest | |
| | ty, .deref :: rest => | |
| match ty with | |
| | .ref _ pt | .rawPtr _ pt | .box pt => projsDowncastNonOptionV2 pt rest | |
| | _ => projsHaveDowncastV2 rest | |
| | ty, .index _ :: rest | ty, .constantIndex _ _ _ :: rest => | |
| match ty with | |
| | .array elem _ | .slice elem => projsDowncastNonOptionV2 elem rest | |
| | _ => projsHaveDowncastV2 rest | |
| | _, .unsupported :: rest => projsHaveDowncastV2 rest | |
| /-- The layout of a payload enum, recursive or not (as `adtVariantsV2`). -/ | |
| noncomputable def adtEnumLayoutV2 : MirTy → Option AdtEnumLayout | |
| | .adtEnum l _ => some l | |
| | .recAdt id defn => | |
| match unfoldRecV2 id defn with | |
| | .adtEnum l _ => some l | |
| | _ => none | |
| | _ => none | |
| /-- Return `true` when field `fi` (of type `fTy`) of variant `vi` of the | |
| payload enum `ty` lies outside the enum's tag, so that no store through a | |
| pointer to the field changes which variant the enum holds: the enum has | |
| `.direct` encoding, variant `vi` is a struct whose field `fi` has type `fTy` | |
| and a layout, and the field's byte span `(offset, size)` is disjoint from | |
| the tag's (`adtTagSpanV2`). `adtVariantWfV2` already requires this of every | |
| tagged variant; checking it here keeps the borrow rule independent of that. | |
| A niche enum's untagged variant overlaps the niche, so `.niche`, and | |
| `.single`, are refused. -/ | |
| noncomputable def adtDirectFieldOffTagV2 (ty : MirTy) (vi fi : Nat) | |
| (fTy : MirTy) : Bool := | |
| match adtEnumLayoutV2 ty, adtVariantPayloadV2 ty vi with | |
| | some l, some (.struct_ sl fs) => | |
| match l.encoding, getElem? sl.fieldOffsets fi, getElem? fs fi with | |
| | .direct, some off, some ty' => | |
| if !MirTy.beq ty' fTy then | |
| false | |
| else | |
| match layoutOfTyV2 fTy with | |
| | some lay => natSpanDisjointWith (off, lay.size) [adtTagSpanV2 l] | |
| | none => false | |
| | _, _, _ => false | |
| | _, _ => false | |
| mutual | |
| /-- The values that the `w` bytes at offset `off` of the encoding | |
| (`encodeValV2`) of any valid value of type `ty` can hold, read as an | |
| unsigned integer, as closed ranges `(lo, hi)`, or `none` when those bytes | |
| are not one whole scalar of a kind modeled here (failing closed): | |
| - `.bool`: its one byte is `0` or `1`; | |
| - `.option (.int _ _)`: its `TagEncoding::Direct` tag of `2^alignLog2` | |
| bytes at offset `0` is `0` (`None`) or `1` (`Some`); | |
| - `.vec _`: its capacity word at `vecCapOffsetV2` is at most `isize::MAX` | |
| (`checkValV2`); | |
| - `.struct_ l fs`: the bytes of the field that contains the whole span; a | |
| span in padding, or across a field boundary, is `none`. | |
| Each of these bytes is initialized and carries no provenance. -/ | |
| noncomputable def nicheScalarRangesV2 : | |
| MirTy → Nat → Nat → Option (List (Nat × Nat)) | |
| | .bool, off, w => | |
| if Nat.beq off 0 && Nat.beq w 1 then some [(0, 1)] else none | |
| | .option (.int iw sg), off, w => | |
| match layoutOfTyV2 (.int iw sg) with | |
| | some lay => | |
| if Nat.beq off 0 && Nat.beq w (Nat.pow 2 lay.alignLog2) then | |
| some [(0, 1)] | |
| else none | |
| | none => none | |
| | .vec _, off, w => | |
| if Nat.beq off vecCapOffsetV2 && Nat.beq w 8 then | |
| some [(0, Nat.pow 2 63 - 1)] | |
| else none | |
| | .struct_ l fs, off, w => nicheFieldRangesV2 l.fieldOffsets fs off w | |
| | _, _, _ => none | |
| /-- `nicheScalarRangesV2` of the field among `fs` (at the offsets `os`) | |
| whose bytes contain the span `(off, w)`. -/ | |
| noncomputable def nicheFieldRangesV2 : | |
| List Nat → List MirTy → Nat → Nat → Option (List (Nat × Nat)) | |
| | o :: os, f :: fs, off, w => | |
| match layoutOfTyV2 f with | |
| | none => none | |
| | some lay => | |
| if Nat.ble o off && Nat.ble (off + w) (o + lay.size) then | |
| nicheScalarRangesV2 f (off - o) w | |
| else if Nat.ble (off + w) o || Nat.ble (o + lay.size) off then | |
| nicheFieldRangesV2 os fs off w | |
| else none | |
| | _, _, _, _ => none | |
| end | |
| /-- Return `true` when every value in the ranges `rs`, as the tag of a | |
| payload enum with layout `l` and encoding `.niche _ first last start`, | |
| decodes as the untagged variant (`adtDecodeVariantV2`): it is outside the | |
| niche values `start + k` for `k <= last - first` and inside the tag's valid | |
| range from `l.tagValidStart` to `l.tagValidEnd`, both wrapping modulo | |
| `2^bitWidth` of the tag. A range `(lo, hi)` with `lo` at niche-relative | |
| value `n` holds exactly the relative values `n ..= n + (hi - lo)`. -/ | |
| noncomputable def nicheRangesUntaggedV2 (l : AdtEnumLayout) | |
| (first last start : Nat) : List (Nat × Nat) → Bool | |
| | [] => true | |
| | (lo, hi) :: rs => | |
| let m := Nat.pow 2 l.tagWidth.bitWidth | |
| let n := adtNicheRelV2 m start lo | |
| let v := adtNicheRelV2 m l.tagValidStart lo | |
| Nat.ble lo hi && Nat.blt hi m && Nat.blt start m && | |
| Nat.blt l.tagValidStart m && Nat.blt l.tagValidEnd m && | |
| Nat.blt (last - first) n && Nat.blt (n + (hi - lo)) m && | |
| Nat.ble (v + (hi - lo)) (adtNicheRelV2 m l.tagValidStart l.tagValidEnd) && | |
| nicheRangesUntaggedV2 l first last start rs | |
| /-- Return `true` when field `fi` (of type `fTy`) of the untagged variant | |
| `vi` of the `.niche`-encoded payload enum `ty` may be borrowed mutably: no | |
| store of a valid `fTy` through the reference can change which variant the | |
| enum holds. The untagged variant has no tag of its own; its payload's bytes | |
| at the tag are what make it decode as that variant (`adtFinishEncodeV2`). | |
| So either the field's byte span is disjoint from the tag's (`adtTagSpanV2`), | |
| or it contains the whole tag, and every value the tag bytes of a valid | |
| `fTy` can hold (`nicheScalarRangesV2`) decodes as the untagged variant | |
| (`nicheRangesUntaggedV2`). Any other case, including a tag in the field's | |
| padding, is refused. -/ | |
| noncomputable def adtNicheFieldUntaggedV2 (ty : MirTy) (vi fi : Nat) | |
| (fTy : MirTy) : Bool := | |
| match adtEnumLayoutV2 ty, adtVariantPayloadV2 ty vi with | |
| | some l, some (.struct_ sl fs) => | |
| match l.encoding, getElem? sl.fieldOffsets fi, getElem? fs fi with | |
| | .niche u first last start, some off, some ty' => | |
| if !Nat.beq vi u || !MirTy.beq ty' fTy || Nat.blt last first then | |
| false | |
| else | |
| match layoutOfTyV2 fTy with | |
| | none => false | |
| | some lay => | |
| let tag := adtTagSpanV2 l | |
| if natSpanDisjointWith (off, lay.size) [tag] then | |
| true | |
| else if Nat.ble off tag.1 && | |
| Nat.ble (tag.1 + tag.2) (off + lay.size) then | |
| match nicheScalarRangesV2 fTy (tag.1 - off) tag.2 with | |
| | some rs => nicheRangesUntaggedV2 l first last start rs | |
| | none => false | |
| else | |
| false | |
| | _, _, _ => false | |
| | _, _ => false | |
| /-- Return `true` when a mutable reference to the place with projections | |
| `projs` from a base of type `ty` could change which variant some payload | |
| enum holds: as `projsDowncastNonOptionV2`, except that the field of a | |
| payload enum variant that lies outside the tag (`adtDirectFieldOffTagV2`), | |
| or a field of a niche enum's untagged variant that no valid store can move | |
| into the niche (`adtNicheFieldUntaggedV2`), is admitted. | |
| `projectMemoryPlaceV2` resolves such a field only when the enum holds | |
| variant `vi` (`.undefined` otherwise), and the reference spans exactly the | |
| field's bytes, so a store through it either leaves the tag alone or writes | |
| tag bytes that still decode as `vi`. -/ | |
| noncomputable def projsDowncastMutUnsafeV2 : MirTy → List ProjectionElem → Bool | |
| | _, [] => false | |
| | ty, .downcast vi :: .field fi fTy :: rest => | |
| match ty with | |
| | .option _ => projsDowncastMutUnsafeV2 fTy rest | |
| | _ => | |
| !(adtDirectFieldOffTagV2 ty vi fi fTy || | |
| adtNicheFieldUntaggedV2 ty vi fi fTy) || | |
| projsDowncastMutUnsafeV2 fTy rest | |
| | ty, .downcast _ :: rest => | |
| match ty with | |
| | .option _ => projsDowncastMutUnsafeV2 ty rest | |
| | _ => true | |
| | _, .field _ fTy :: rest => projsDowncastMutUnsafeV2 fTy rest | |
| | ty, .deref :: rest => | |
| match ty with | |
| | .ref _ pt | .rawPtr _ pt | .box pt => projsDowncastMutUnsafeV2 pt rest | |
| | _ => projsHaveDowncastV2 rest | |
| | ty, .index _ :: rest | ty, .constantIndex _ _ _ :: rest => | |
| match ty with | |
| | .array elem _ | .slice elem => projsDowncastMutUnsafeV2 elem rest | |
| | _ => projsHaveDowncastV2 rest | |
| | _, .unsupported :: rest => projsHaveDowncastV2 rest | |
| /-- Resolve a projected place (after `resolveIndexProjsV2`) of local | |
| `localId` to the memory address of its leaf for `Rvalue.ref` and | |
| `Rvalue.addressOf` in Profile v2, returning the leaf type, the mutability | |
| that the base admits, the leaf pointer, and the updated locals and memory: | |
| - `.deref :: rest` dereferences a reference (when `viaRef`) or a raw pointer | |
| (otherwise); the other pointer kind is unsupported, as for `[.deref]` in | |
| `evalRefRvalueV2` and `evalAddressOfRvalueV2`. A sized pointee | |
| must be live, in bounds, and aligned (as for reads in | |
| `readDerefProjectedV2`), and the leaf is at | |
| `projectMemoryLayoutV2 pt rest`. A slice pointee addresses an element | |
| place (`sliceElemAddrV2`). | |
| - Any other projection list addresses a field or element of the local, which | |
| is first moved to memory (`promoteLocalToMemory`, as `rustc`'s | |
| `force_allocation` does for a place whose address is taken). | |
| A provenance-free pointer base is unsupported. -/ | |
| noncomputable def placeAddrV2 (bodyLocals : List MirTy) | |
| (locals : List LocalSlot) (mem : MemoryState) (viaRef : Bool) | |
| (localId : LocalId) : | |
| List ProjectionElem → | |
| Except FaultKind | |
| (MirTy × Mutability × PtrVal × List LocalSlot × MemoryState) | |
| | .deref :: rest => | |
| match getElem? bodyLocals localId, getElem? locals localId with | |
| | some _, some .dead => .error .undefined | |
| | some baseTy, some slot => | |
| let baseInfo : Option (Mutability × MirTy) := | |
| match viaRef, baseTy with | |
| | true, .ref m pt | false, .rawPtr m pt => some (m, pt) | |
| | _, _ => none | |
| match baseInfo with | |
| | none => .error .unsupported | |
| | some (srcMut, pt) => | |
| let ptrRes : Except FaultKind (Option Val) := | |
| match slot with | |
| | .dead | .partialTuple _ => .error .undefined | |
| | .immediate optVal => .ok optVal | |
| | .indirect mplace => loadIndirectV2 mem baseTy mplace | |
| match ptrRes with | |
| | .error k => .error k | |
| | .ok none => .error .undefined | |
| | .ok (some (.slicePtr p len)) => | |
| match pt with | |
| | .slice elem => | |
| match sliceElemAddrV2 mem elem p len.toNat rest with | |
| | .error k => .error k | |
| | .ok (leafTy, aid, off) => | |
| .ok (leafTy, srcMut, ⟨some aid, UInt64.ofNat off, .isize⟩, | |
| locals, mem) | |
| | _ => .error .unsupported | |
| | .ok (some (.ptr p)) => | |
| if isUnsizedTy pt then | |
| .error .unsupported | |
| else | |
| match layoutOfTyV2 pt, projectMemoryLayoutV2 pt rest with | |
| | none, _ => .error .unsupported | |
| -- An `Option` payload downcast reads the discriminant in memory | |
| -- (`projectMemoryPlaceV2`); any other failure is unchanged. | |
| | some ptLay, .error k => | |
| match p.allocId with | |
| | none => .error k | |
| | some aid => | |
| match projectMemoryPlaceV2 mem aid p.offsetBytes.toNat pt [] rest with | |
| | .error k' => .error k' | |
| | .ok (leafTy, off) => | |
| match findAllocation aid mem.allocations with | |
| | none => .error .undefined | |
| | some a => | |
| if !a.live || !isInBounds a p.offsetBytes.toNat ptLay.size || | |
| !isAligned a p.offsetBytes.toNat ptLay.alignLog2 then | |
| .error .undefined | |
| else | |
| .ok (leafTy, srcMut, ⟨some aid, UInt64.ofNat off, .isize⟩, | |
| locals, mem) | |
| | some ptLay, .ok (leafTy, subOff) => | |
| match p.allocId with | |
| | none => .error .unsupported | |
| | some aid => | |
| match findAllocation aid mem.allocations with | |
| | none => .error .undefined | |
| | some a => | |
| if !a.live || !isInBounds a p.offsetBytes.toNat ptLay.size || | |
| !isAligned a p.offsetBytes.toNat ptLay.alignLog2 then | |
| .error .undefined | |
| else | |
| .ok (leafTy, srcMut, | |
| ⟨some aid, UInt64.ofNat (p.offsetBytes.toNat + subOff), | |
| .isize⟩, locals, mem) | |
| | .ok (some _) => .error .unsupported | |
| | _, _ => .error .unsupported | |
| | projs => | |
| match promoteLocalToMemory bodyLocals locals mem localId with | |
| | .error k => .error k | |
| | .ok (localTy, mplace, locals1, mem1) => | |
| match projectMemoryLayoutV2 localTy projs with | |
| | .error _ => | |
| match projectMemoryPlaceV2 mem1 mplace.allocId mplace.offset localTy [] | |
| projs with | |
| | .error k => .error k | |
| | .ok (leafTy, off) => | |
| .ok (leafTy, .mut, ⟨some mplace.allocId, UInt64.ofNat off, .isize⟩, | |
| locals1, mem1) | |
| | .ok (leafTy, subOff) => | |
| .ok (leafTy, .mut, | |
| ⟨some mplace.allocId, UInt64.ofNat (mplace.offset + subOff), .isize⟩, | |
| locals1, mem1) | |
| /-- Evaluate `Rvalue.ref` in Profile v2 (`&local`, or the reborrow `&*r` of a | |
| reference local `r`). | |
| `Rvalue::Ref` forces the place into memory and yields a pointer to it | |
| (`compiler/rustc_const_eval/src/interpret/step.rs:208-211`, `rust-lang/rust` | |
| `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`): | |
| > "Ref(_, borrow_kind, place) => { | |
| > let src = self.eval_place(place)?; | |
| > let place = self.force_allocation(&src)?; | |
| > let mut val = ImmTy::from_immediate(place.to_ref(self), dest.layout);" | |
| The value produced must be a valid reference, so `refValidInMem` checks it. | |
| Retagging is not modeled; see `BodyVerifiedV2`. A `&mut *r` through a shared | |
| `r : &T` returns `.undefined`, an arm that MIR type checking makes | |
| unreachable. `&*p` for a raw pointer `p` is `.unsupported`. A body containing | |
| it would mix reference and non-fake raw-pointer locals, which | |
| `BodyStaticAdmittedV2` rejects anyway. Any other projected place is borrowed | |
| at its `placeAddrV2` address (after `resolveIndexProjsV2`), with the same | |
| mutability, type, and validity checks. -/ | |
| noncomputable def evalRefRvalueV2 (bodyLocals : List MirTy) | |
| (locals : List LocalSlot) (mem : MemoryState) (dstTy : MirTy) | |
| (reqMut : Mutability) (place : Place) : | |
| Except FaultKind (Val × List LocalSlot × MemoryState) := | |
| match place.projection with | |
| | [] => | |
| match promoteLocalToMemory bodyLocals locals mem place.localId with | |
| | .error k => .error k | |
| | .ok (localTy, mplace, locals1, mem1) => | |
| if !MirTy.beq dstTy (.ref reqMut localTy) then | |
| .error .unsupported | |
| else | |
| let rv : Val := .ptr ⟨some mplace.allocId, UInt64.ofNat mplace.offset, .isize⟩ | |
| match refValidInMem mem1 reqMut localTy rv with | |
| | .error k => .error k | |
| | .ok () => .ok (rv, locals1, mem1) | |
| | [.deref] => | |
| match getElem? bodyLocals place.localId, getElem? locals place.localId with | |
| | some _, some .dead => .error .undefined | |
| | some baseTy, some slot => | |
| match baseTy with | |
| | .ref srcMut pt => | |
| if Mutability.beq srcMut .shared && Mutability.beq reqMut .mut then | |
| .error .undefined | |
| else if !MirTy.beq dstTy (.ref reqMut pt) then | |
| .error .unsupported | |
| else | |
| let ptrRes : Except FaultKind (Option Val) := | |
| match slot with | |
| | .dead | .partialTuple _ => .error .undefined | |
| | .immediate optVal => .ok optVal | |
| | .indirect mplace => loadIndirectV2 mem baseTy mplace | |
| match ptrRes with | |
| | .error k => .error k | |
| | .ok none => .error .undefined | |
| | .ok (some v) => | |
| match refValidInMem mem reqMut pt v with | |
| | .error k => .error k | |
| | .ok () => .ok (v, locals, mem) | |
| | _ => .error .unsupported | |
| | _, _ => .error .unsupported | |
| | projs => | |
| match resolveIndexProjsV2 bodyLocals locals mem projs with | |
| | .error k => .error k | |
| | .ok projs' => | |
| let baseTy := (getElem? bodyLocals place.localId).getD .unsupported | |
| if Mutability.beq reqMut .mut && | |
| projsDowncastMutUnsafeV2 baseTy projs' then | |
| .error .unsupported | |
| else | |
| match placeAddrV2 bodyLocals locals mem true place.localId projs' with | |
| | .error k => .error k | |
| | .ok (leafTy, srcMut, ptr, locals1, mem1) => | |
| if Mutability.beq srcMut .shared && Mutability.beq reqMut .mut then | |
| .error .undefined | |
| else if !MirTy.beq dstTy (.ref reqMut leafTy) then | |
| .error .unsupported | |
| else | |
| match refValidInMem mem1 reqMut leafTy (.ptr ptr) with | |
| | .error k => .error k | |
| | .ok () => .ok (.ptr ptr, locals1, mem1) | |
| /-- Evaluate `Rvalue.addressOf` in Profile v2 (`&raw const/mut local`, or | |
| `&raw const/mut *p` of a raw-pointer local `p`). | |
| `Rvalue::RawPtr` also forces the place into memory (`promoteLocalToMemory`) | |
| and produces a pointer without any validity check. The Reference permits a raw | |
| borrow even of a place based on a misaligned pointer | |
| (`src/behavior-considered-undefined.md:118-124`, `rust-lang/reference` | |
| `ad35aca481751a06afeb23820a672b0f3b11a476`): | |
| > "`&raw const`/`&raw mut` on such a place is allowed. | |
| > | |
| > `&`/`&mut` on a place requires the alignment of the field type (or else the | |
| > program would be "producing an invalid value"), which generally is a less | |
| > restrictive requirement than being based on an aligned pointer." | |
| `&raw *r` for a reference `r` is `.unsupported`. A body containing it would | |
| mix reference and non-fake raw-pointer locals, which `BodyStaticAdmittedV2` | |
| rejects anyway. `&raw mut *p` through a `*const T` returns `.undefined`, like | |
| `&mut *r` through a shared `r` in `evalRefRvalueV2`. MIR borrow checking makes | |
| that arm unreachable, and refusing it keeps a `*const T` from yielding a | |
| `*mut T` here, as `evalPtrToPtrCastV2` does for casts. Any other projected | |
| place yields its `placeAddrV2` address (after `resolveIndexProjsV2`), with | |
| the same mutability refusal. -/ | |
| noncomputable def evalAddressOfRvalueV2 (bodyLocals : List MirTy) | |
| (locals : List LocalSlot) (mem : MemoryState) (dstTy : MirTy) | |
| (reqMut : Mutability) (place : Place) : | |
| Except FaultKind (Val × List LocalSlot × MemoryState) := | |
| match place.projection with | |
| | [] => | |
| match promoteLocalToMemory bodyLocals locals mem place.localId with | |
| | .error k => .error k | |
| | .ok (localTy, mplace, locals1, mem1) => | |
| if !MirTy.beq dstTy (.rawPtr reqMut localTy) then | |
| .error .unsupported | |
| else | |
| .ok (.ptr ⟨some mplace.allocId, UInt64.ofNat mplace.offset, .isize⟩, locals1, mem1) | |
| | [.deref] => | |
| match getElem? bodyLocals place.localId, getElem? locals place.localId with | |
| | some _, some .dead => .error .undefined | |
| | some baseTy, some slot => | |
| match baseTy with | |
| | .rawPtr srcMut pt => | |
| if Mutability.beq srcMut .shared && Mutability.beq reqMut .mut then | |
| .error .undefined | |
| else if !MirTy.beq dstTy (.rawPtr reqMut pt) then | |
| .error .unsupported | |
| else | |
| let ptrRes : Except FaultKind (Option Val) := | |
| match slot with | |
| | .dead | .partialTuple _ => .error .undefined | |
| | .immediate optVal => .ok optVal | |
| | .indirect mplace => loadIndirectV2 mem baseTy mplace | |
| match ptrRes with | |
| | .error k => .error k | |
| | .ok none => .error .undefined | |
| | .ok (some v) => .ok (v, locals, mem) | |
| | _ => .error .unsupported | |
| | _, _ => .error .unsupported | |
| | projs => | |
| match resolveIndexProjsV2 bodyLocals locals mem projs with | |
| | .error k => .error k | |
| | .ok projs' => | |
| let baseTy := (getElem? bodyLocals place.localId).getD .unsupported | |
| if Mutability.beq reqMut .mut && | |
| projsDowncastNonOptionV2 baseTy projs' then | |
| .error .unsupported | |
| else | |
| match placeAddrV2 bodyLocals locals mem false place.localId projs' with | |
| | .error k => .error k | |
| | .ok (leafTy, srcMut, ptr, locals1, mem1) => | |
| if Mutability.beq srcMut .shared && Mutability.beq reqMut .mut then | |
| .error .undefined | |
| else if !MirTy.beq dstTy (.rawPtr reqMut leafTy) then | |
| .error .unsupported | |
| else | |
| .ok (.ptr ptr, locals1, mem1) | |
| /-- Check that the static types of evaluated operands `typed` equal `tys`. -/ | |
| noncomputable def typedArgsMatchV2 : List (MirTy × Val) → List MirTy → Bool | |
| | [], [] => true | |
| | (ty, _) :: rest, t :: ts => MirTy.beq ty t && typedArgsMatchV2 rest ts | |
| | _, _ => false | |
| /-- Evaluate `Rvalue.fakeAddressOf` (`RawPtrKind::FakeForPtrMetadata`) in | |
| Profile v2 (`&raw const (fake) (*s)`). | |
| Upstream `compiler/rustc_middle/src/mir/syntax.rs#L180-L192` (`rust-lang/rust` | |
| `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`) specifies: | |
| > "In terms of the operational semantics (i.e., Miri), this is equivalent to | |
| > `RawPtrKind::Mut`, but will never incur a retag." | |
| Matches `Miri.Interpreter.Rvalue` (`| .RawPtr kind src`) with | |
| `kind = .FakeForPtrMetadata` (`vendor/lean-miri/Miri/Interpreter/Rvalue.lean` | |
| and `PointerPlaceMachine.lean`): | |
| 1. Only `[.deref]` places are admitted (`rustc` emits `FakeForPtrMetadata` | |
| exclusively on dereferenced places for `PtrMetadata` queries). | |
| 2. On a reference base local (`.ref srcMut pt`), dereferencing checks | |
| `refValidInMem mem srcMut pt v` without Stacked/Tree Borrows retagging and | |
| yields `v` at destination type `.rawPtr .shared pt`. Checking | |
| `refValidInMem` is conservatively stricter than | |
| `PointerPlaceMachine.dereference` (it can only add faults on invalid | |
| references, consistent with `evalRefRvalueV2`). | |
| 3. On a raw-pointer base local (`.rawPtr _ pt`), dereferencing reads `v` | |
| without pointee bounds/alignment checks (matching raw-pointer place | |
| dereference) and yields `v` at destination type `.rawPtr .shared pt`. -/ | |
| noncomputable def evalFakeAddressOfRvalueV2 (bodyLocals : List MirTy) | |
| (locals : List LocalSlot) (mem : MemoryState) (dstTy : MirTy) | |
| (place : Place) : | |
| Except FaultKind (Val × List LocalSlot × MemoryState) := | |
| match place.projection with | |
| | [.deref] => | |
| match getElem? bodyLocals place.localId, getElem? locals place.localId with | |
| | some _, some .dead => .error .undefined | |
| | some baseTy, some slot => | |
| let readSlot : Except FaultKind (Option Val) := | |
| match slot with | |
| | .dead | .partialTuple _ => .error .undefined | |
| | .immediate optVal => .ok optVal | |
| | .indirect mplace => loadIndirectV2 mem baseTy mplace | |
| match baseTy with | |
| | .ref srcMut pt => | |
| if isOverflowPairTy pt || !MirTy.beq dstTy (.rawPtr .shared pt) then | |
| .error .unsupported | |
| else | |
| match readSlot with | |
| | .error k => .error k | |
| | .ok none => .error .undefined | |
| | .ok (some v) => | |
| match refValidInMem mem srcMut pt v with | |
| | .error k => .error k | |
| | .ok () => .ok (v, locals, mem) | |
| | .rawPtr _ pt => | |
| if isOverflowPairTy pt || !MirTy.beq dstTy (.rawPtr .shared pt) then | |
| .error .unsupported | |
| else | |
| match readSlot with | |
| | .error k => .error k | |
| | .ok none => .error .undefined | |
| | .ok (some v) => .ok (v, locals, mem) | |
| | _ => .error .unsupported | |
| | _, _ => .error .unsupported | |
| | _ => .error .unsupported | |
| /-- Evaluate `CastKind.boxAsRef`: the shared dereference `&*b` of a | |
| `Box<pt>` value, checking `refValidInMem mem .shared pt` of the result. -/ | |
| noncomputable def evalCastKindV2 (mem : MemoryState) (dstTy srcTy : MirTy) | |
| (val : Val) (castTy : MirTy) : Except FaultKind Val := | |
| if !MirTy.beq dstTy castTy then | |
| .error .unsupported | |
| else | |
| match srcTy, val, castTy with | |
| | .box pt, .boxPtr p optLen, .ref .shared castPt => | |
| if !MirTy.beq pt castPt then | |
| .error .unsupported | |
| else | |
| let ptrRes : Except FaultKind Val := | |
| match pt, optLen with | |
| | .slice _, some len => .ok (.slicePtr p len) | |
| | _, none => | |
| if isUnsizedTy pt then .error .unsupported else .ok (.ptr p) | |
| | _, _ => .error .unsupported | |
| match ptrRes with | |
| | .error k => .error k | |
| | .ok ptrVal => | |
| match refValidInMem mem .shared pt ptrVal with | |
| | .error k => .error k | |
| | .ok () => .ok ptrVal | |
| | _, _, _ => .error .unsupported | |
| /-- Evaluate `.aggregateAdtEnum enumTy vi fields` on a fieldless enum | |
| `enumTy = .enum ety`: the payload-free variant `vi` is the tag-only value | |
| `Val.enumVal ety vi`, whose discriminant `ety.discriminants[vi]` is the | |
| in-memory tag. It takes no operands, needs `enumTy` as its destination type | |
| and an admitted `ety`, and `vi` must name a variant. Every other type is | |
| unsupported. -/ | |
| noncomputable def evalFieldlessEnumAggregateV2 (locals : List LocalSlot) | |
| (mem : MemoryState) (dstTy enumTy : MirTy) (vi : Nat) | |
| (fields : List Operand) : | |
| Except FaultKind (Val × List LocalSlot × MemoryState) := | |
| match enumTy with | |
| | .enum ety => | |
| if !fields.isEmpty || !MirTy.beq dstTy enumTy || !enumAdmitted ety || | |
| !Nat.blt vi ety.discriminants.length then | |
| .error .unsupported | |
| else | |
| .ok (.enumVal ety vi, locals, mem) | |
| | _ => .error .unsupported | |
| /-- Evaluate an `Rvalue` in Profile v2. | |
| The Profile v2 arms correspond to rustc as follows (`rust-lang/rust` | |
| `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`, `rust-lang/reference` | |
| `ad35aca481751a06afeb23820a672b0f3b11a476`). | |
| - `.useRetag` is `Use(op, WithRetag::Yes)` | |
| (`compiler/rustc_middle/src/mir/syntax.rs:1364-1365`): | |
| > "/// Yields the operand unchanged, except for a potential retag. | |
| > Use(Operand<'tcx>, WithRetag)," | |
| Profile v2 does not model Stacked or Tree Borrows tags. Instead it | |
| re-validates every contained reference (`refsValidInMem`). A copied | |
| reference is produced and considered live | |
| (`src/behavior-considered-undefined.md:44-45`): | |
| > " * Each time a reference or box is dereferenced or reborrowed, it is | |
| > considered live. | |
| > * Each time a reference or box is passed to or returned from a function, | |
| > it is considered live." | |
| This under-approximates aliasing UB (see `BodyVerifiedV2`) and | |
| over-approximates validity UB by requiring initialized pointees. | |
| - `.binaryOp .offset` is `BinOp::Offset` on a raw pointer whose result type | |
| equals the left operand type (see `evalPtrOffsetV2`). | |
| - `.unaryOp .ptrMetadata` is `UnOp::PtrMetadata` | |
| (`compiler/rustc_middle/src/mir/syntax.rs:1608-1611`): | |
| > "Gets the metadata `M` from a `*const`/`*mut`/`&`/`&mut` to `impl | |
| > Pointee<Metadata = M>`. | |
| > | |
| > For example, this will give a `()` from `*const i32`, a `usize` from `&mut | |
| > [u8]`, or a `ptr::DynMetadata<dyn Foo>` (internally a pointer) from a `*mut | |
| > dyn Foo`." | |
| The interpreter returns the slice metadata, or `ImmTy::uninit` of `()` for | |
| thin pointers | |
| (`compiler/rustc_const_eval/src/interpret/operator.rs:487-500`). Lean | |
| returns `.unit` for thin pointers, which is equivalent for a ZST. For | |
| reference operands Lean also re-checks `refValidInMem`, which is | |
| conservative. | |
| - `.cast .ptrToPtr` is `CastKind::PtrToPtr` (see `evalPtrToPtrCastV2`). | |
| - `.cast .boxAsRef` is the shared dereference `&*b` of a `Box` (see | |
| `evalCastKindV2`). | |
| - `.cast .intToPtr` is `CastKind::PointerWithExposedProvenance` from `usize`. | |
| The result has no provenance, exactly as in the CTFE machine | |
| (`compiler/rustc_const_eval/src/interpret/machine.rs:743-746`): | |
| > "// Allow these casts, but make the pointer not dereferenceable. | |
| > // (I.e., they behave like transmutation.) | |
| > // This is correct because no pointers can ever be exposed in | |
| > // compile-time evaluation. | |
| > interp_ok(Pointer::without_provenance(addr))" | |
| At runtime the cast is "An address-to-pointer cast that picks up an exposed | |
| provenance" (`compiler/rustc_middle/src/mir/syntax.rs:1496`). Dropping | |
| provenance is therefore conservative: the pointer can be used only for | |
| zero-sized accesses. | |
| - `.ref`, `.addressOf`, and `.fakeAddressOf` are `Rvalue::Ref` and | |
| `Rvalue::RawPtr` (see `evalRefRvalueV2`, `evalAddressOfRvalueV2`, and | |
| `evalFakeAddressOfRvalueV2`). | |
| - `.aggregateTuple []` into `.unit` evaluates to `Val.unit`; as a ZST | |
| aggregate write it stores zero bytes (no memory write). | |
| - `.aggregateRangeTo` and `.aggregateRangeFrom` construct the one-field | |
| `core::ops::RangeTo { end }` and `RangeFrom { start }` with `Idx = usize` | |
| (field layout quoted at `MirTy.rangeTo`). | |
| - `.aggregateAdtEnum (.enum ety) vi []` constructs variant `vi` of a | |
| fieldless enum (see `evalFieldlessEnumAggregateV2`). | |
| - `.aggregateOrdering tagBits` constructs `core::cmp::Ordering` from its | |
| `#[repr(i8)]` discriminant bit pattern (`255` = `Less`, `0` = `Equal`, | |
| `1` = `Greater`, matching `library/core/src/cmp.rs:400-415`, `rust-lang/rust` | |
| `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`); any other bit pattern fails | |
| closed with `.unsupported`. -/ | |
| noncomputable def evalRvalueV2 (bodyLocals : List MirTy) (locals : List LocalSlot) | |
| (mem : MemoryState) (dstTy : MirTy) : | |
| Rvalue → Except FaultKind (Val × List LocalSlot × MemoryState) | |
| | .use opnd => | |
| match evalOperandToSlotV2 bodyLocals locals mem opnd with | |
| | .error k => .error k | |
| | .ok (srcTy, optVal, locals1, mem1) => | |
| if !MirTy.beq srcTy dstTy then | |
| .error .unsupported | |
| else | |
| match optVal with | |
| | some v => .ok (v, locals1, mem1) | |
| | none => .error .undefined | |
| | .useRetag opnd => | |
| match evalOperandToSlotV2 bodyLocals locals mem opnd with | |
| | .error k => .error k | |
| | .ok (srcTy, optVal, locals1, mem1) => | |
| if !MirTy.beq srcTy dstTy then | |
| .error .unsupported | |
| else | |
| match optVal with | |
| | none => .error .undefined | |
| | some v => | |
| if !refsValidInMem mem1 srcTy v then | |
| .error .undefined | |
| else | |
| .ok (v, locals1, mem1) | |
| | .binaryOp .offset lhs rhs => | |
| match evalOperandToSlotV2 bodyLocals locals mem lhs with | |
| | .error k => .error k | |
| | .ok (lhsTy, optLhsVal, locals1, mem1) => | |
| match optLhsVal with | |
| | none => .error .undefined | |
| | some (.ptr p) => | |
| match lhsTy with | |
| | .rawPtr _ pt => | |
| if isUnsizedTy pt || !MirTy.beq dstTy lhsTy then | |
| .error .unsupported | |
| else | |
| match layoutOfTyV2 pt with | |
| | none => .error .unsupported | |
| | some lay => | |
| match evalOperandToSlotV2 bodyLocals locals1 mem1 rhs with | |
| | .error k => .error k | |
| | .ok (_, none, _, _) => .error .undefined | |
| | .ok (_, some rVal, locals2, mem2) => | |
| match evalPtrOffsetV2 mem2 lay.size p rVal with | |
| | .error k => .error k | |
| | .ok res => .ok (res, locals2, mem2) | |
| | _ => .error .unsupported | |
| | some _ => .error .unsupported | |
| | .binaryOp op lhs rhs => | |
| match evalPrimitiveOperandV2 bodyLocals locals mem lhs with | |
| | .error k => .error k | |
| | .ok (lVal, locals1, mem1) => | |
| match evalPrimitiveOperandV2 bodyLocals locals1 mem1 rhs with | |
| | .error k => .error k | |
| | .ok (rVal, locals2, mem2) => | |
| match evalBinOp op lVal rVal with | |
| | .error k => .error k | |
| | .ok res => .ok (res, locals2, mem2) | |
| | .unaryOp .ptrMetadata opnd => | |
| match evalOperandToSlotV2 bodyLocals locals mem opnd with | |
| | .error k => .error k | |
| | .ok (_, none, _, _) => .error .undefined | |
| | .ok (srcTy, some val, locals1, mem1) => | |
| match srcTy, val with | |
| | .ref srcMut (.slice elem), .slicePtr p len => | |
| if !MirTy.beq dstTy (.int .isize false) then | |
| .error .unsupported | |
| else | |
| match refValidInMem mem1 srcMut (.slice elem) (.slicePtr p len) with | |
| | .error k => .error k | |
| | .ok () => | |
| .ok (.scalar ⟨.isize, false, | |
| truncateBits .isize (BitVec.ofNat 128 len.toNat)⟩, | |
| locals1, mem1) | |
| | .ref .shared .str, .slicePtr p len => | |
| if !MirTy.beq dstTy (.int .isize false) then | |
| .error .unsupported | |
| else | |
| match refValidInMem mem1 .shared .str (.slicePtr p len) with | |
| | .error k => .error k | |
| | .ok () => | |
| .ok (.scalar ⟨.isize, false, | |
| truncateBits .isize (BitVec.ofNat 128 len.toNat)⟩, | |
| locals1, mem1) | |
| | .rawPtr _ (.slice _), .slicePtr _ len => | |
| if !MirTy.beq dstTy (.int .isize false) then | |
| .error .unsupported | |
| else | |
| .ok (.scalar ⟨.isize, false, truncateBits .isize (BitVec.ofNat 128 len.toNat)⟩, | |
| locals1, mem1) | |
| | .ref srcMut pt, .ptr p => | |
| if isUnsizedTy pt || !MirTy.beq dstTy .unit then | |
| .error .unsupported | |
| else | |
| match refValidInMem mem1 srcMut pt (.ptr p) with | |
| | .error k => .error k | |
| | .ok () => .ok (.unit, locals1, mem1) | |
| | .rawPtr _ pt, .ptr _ => | |
| if isUnsizedTy pt || !MirTy.beq dstTy .unit then | |
| .error .unsupported | |
| else | |
| .ok (.unit, locals1, mem1) | |
| | _, _ => .error .unsupported | |
| | .unaryOp op opnd => | |
| match evalPrimitiveOperandV2 bodyLocals locals mem opnd with | |
| | .error k => .error k | |
| | .ok (v, locals1, mem1) => | |
| match evalUnOp op v with | |
| | .error k => .error k | |
| | .ok res => .ok (res, locals1, mem1) | |
| | .cast .intToInt opnd castTy => | |
| match evalOperandToSlotV2 bodyLocals locals mem opnd with | |
| | .error k => .error k | |
| | .ok (srcTy, optCastVal, locals1, mem1) => | |
| if !isIntLikeTy srcTy || !MirTy.beq dstTy castTy then | |
| .error .unsupported | |
| else | |
| match optCastVal with | |
| | some castV => | |
| match evalIntToIntCast castV castTy with | |
| | .error k => .error k | |
| | .ok res => .ok (res, locals1, mem1) | |
| | none => .error .undefined | |
| | .cast .ptrToPtr opnd castTy => | |
| if !MirTy.beq dstTy castTy then | |
| .error .unsupported | |
| else | |
| match evalOperandToSlotV2 bodyLocals locals mem opnd with | |
| | .error k => .error k | |
| | .ok (_, none, _, _) => .error .undefined | |
| | .ok (srcTy, some v, locals1, mem1) => | |
| match evalPtrToPtrCastV2 srcTy v castTy with | |
| | .error k => .error k | |
| | .ok res => .ok (res, locals1, mem1) | |
| | .cast .intToPtr opnd castTy => | |
| if !MirTy.beq dstTy castTy then | |
| .error .unsupported | |
| else | |
| match castTy with | |
| | .rawPtr _ pt => | |
| if isUnsizedTy pt then | |
| .error .unsupported | |
| else | |
| match evalOperandToSlotV2 bodyLocals locals mem opnd with | |
| | .error k => .error k | |
| | .ok (.int .isize false, some (.scalar sv), locals1, mem1) => | |
| .ok (.ptr ⟨none, UInt64.ofNat sv.bits.toNat, .isize⟩, locals1, mem1) | |
| | .ok (_, none, _, _) => .error .undefined | |
| | .ok (_, _, _, _) => .error .unsupported | |
| | _ => .error .unsupported | |
| | .cast .unsize opnd castTy => | |
| if !MirTy.beq dstTy castTy then | |
| .error .unsupported | |
| else | |
| match evalOperandToSlotV2 bodyLocals locals mem opnd with | |
| | .error k => .error k | |
| | .ok (_, none, _, _) => .error .undefined | |
| | .ok (srcTy, some v, locals1, mem1) => | |
| match srcTy, castTy, v with | |
| | .ref srcMut (.array srcElem len), .ref dstMut (.slice dstElem), .ptr p => | |
| if !MirTy.beq srcElem dstElem || !Nat.blt len (Nat.pow 2 64) then | |
| .error .unsupported | |
| else if Mutability.beq srcMut .shared && | |
| Mutability.beq dstMut .mut then | |
| .error .undefined | |
| else | |
| match refValidInMem mem1 srcMut (.array srcElem len) (.ptr p) with | |
| | .error k => .error k | |
| | .ok () => | |
| let sv : Val := .slicePtr p (UInt64.ofNat len) | |
| match refValidInMem mem1 dstMut (.slice dstElem) sv with | |
| | .error k => .error k | |
| | .ok () => .ok (sv, locals1, mem1) | |
| | .rawPtr srcMut (.array srcElem len), | |
| .rawPtr dstMut (.slice dstElem), .ptr p => | |
| if !MirTy.beq srcElem dstElem || !Nat.blt len (Nat.pow 2 64) then | |
| .error .unsupported | |
| else if Mutability.beq srcMut .shared && | |
| Mutability.beq dstMut .mut then | |
| .error .undefined | |
| else | |
| .ok (.slicePtr p (UInt64.ofNat len), locals1, mem1) | |
| | _, _, _ => .error .unsupported | |
| | .cast .boxAsRef opnd castTy => | |
| match evalOperandToSlotV2 bodyLocals locals mem opnd with | |
| | .error k => .error k | |
| | .ok (_, none, _, _) => .error .undefined | |
| | .ok (srcTy, some val, locals1, mem1) => | |
| match evalCastKindV2 mem1 dstTy srcTy val castTy with | |
| | .error k => .error k | |
| | .ok res => .ok (res, locals1, mem1) | |
| | .discriminant place => | |
| if !place.projection.isEmpty then | |
| match readPlaceV2 bodyLocals locals mem false place with | |
| | .error k => .error k | |
| | .ok (srcTy, optVal, locals1, mem1) => | |
| match srcTy with | |
| | .enum ety => | |
| if !MirTy.beq dstTy (.int ety.discrWidth ety.discrSigned) then | |
| .error .unsupported | |
| else | |
| evalDiscriminantOfVal ety optVal locals1 mem1 | |
| | .ordering => | |
| if !MirTy.beq dstTy (.int .i8 true) then | |
| .error .unsupported | |
| else | |
| evalOrderingDiscriminantOfVal optVal locals1 mem1 | |
| | .option _ => | |
| if !MirTy.beq dstTy (.int .isize true) then | |
| .error .unsupported | |
| else | |
| evalOptionDiscriminantOfVal optVal locals1 mem1 | |
| | .adtEnum l _ | .recAdt _ (.adtEnum l _) => | |
| evalAdtDiscriminantOfVal l dstTy optVal locals1 mem1 | |
| | _ => .error .unsupported | |
| else | |
| match getElem? bodyLocals place.localId, getElem? locals place.localId with | |
| | some _, some .dead => .error .undefined | |
| | some srcTy, some (.immediate optVal) => | |
| match srcTy with | |
| | .enum ety => | |
| if !MirTy.beq dstTy (.int ety.discrWidth ety.discrSigned) then | |
| .error .unsupported | |
| else | |
| evalDiscriminantOfVal ety optVal locals mem | |
| | .ordering => | |
| if !MirTy.beq dstTy (.int .i8 true) then | |
| .error .unsupported | |
| else | |
| evalOrderingDiscriminantOfVal optVal locals mem | |
| | .option _ => | |
| if !MirTy.beq dstTy (.int .isize true) then | |
| .error .unsupported | |
| else | |
| evalOptionDiscriminantOfVal optVal locals mem | |
| | .adtEnum l _ | .recAdt _ (.adtEnum l _) => | |
| evalAdtDiscriminantOfVal l dstTy optVal locals mem | |
| | _ => .error .unsupported | |
| | some srcTy, some (.indirect mplace) => | |
| match srcTy with | |
| | .enum ety => | |
| if !MirTy.beq dstTy (.int ety.discrWidth ety.discrSigned) then | |
| .error .unsupported | |
| else | |
| match loadIndirectV2 mem srcTy mplace with | |
| | .error k => .error k | |
| | .ok optVal => evalDiscriminantOfVal ety optVal locals mem | |
| | .ordering => | |
| if !MirTy.beq dstTy (.int .i8 true) then | |
| .error .unsupported | |
| else | |
| match loadIndirectV2 mem srcTy mplace with | |
| | .error k => .error k | |
| | .ok optVal => evalOrderingDiscriminantOfVal optVal locals mem | |
| | .option _ => | |
| if !MirTy.beq dstTy (.int .isize true) then | |
| .error .unsupported | |
| else | |
| match loadIndirectV2 mem srcTy mplace with | |
| | .error k => .error k | |
| | .ok optVal => evalOptionDiscriminantOfVal optVal locals mem | |
| | .adtEnum l _ | .recAdt _ (.adtEnum l _) => | |
| match loadIndirectV2 mem srcTy mplace with | |
| | .error k => .error k | |
| | .ok optVal => evalAdtDiscriminantOfVal l dstTy optVal locals mem | |
| | _ => .error .unsupported | |
| | _, _ => .error .unsupported | |
| | .ref reqMut place => evalRefRvalueV2 bodyLocals locals mem dstTy reqMut place | |
| | .addressOf reqMut place => evalAddressOfRvalueV2 bodyLocals locals mem dstTy reqMut place | |
| | .fakeAddressOf place => | |
| evalFakeAddressOfRvalueV2 bodyLocals locals mem dstTy place | |
| | .aggregateTuple fields => | |
| match dstTy with | |
| | .unit => | |
| if fields.isEmpty then | |
| .ok (.unit, locals, mem) | |
| else | |
| .error .unsupported | |
| | .tuple fieldTys => | |
| match evalArgOperandsV2 bodyLocals locals mem fields with | |
| | .error k => .error k | |
| | .ok (typedVals, locals1, mem1) => | |
| let vs := argValues typedVals | |
| if !checkValV2List vs fieldTys then | |
| .error .unsupported | |
| else | |
| .ok (.tuple vs, locals1, mem1) | |
| | _ => .error .unsupported | |
| | .aggregateArray elemTy elems => | |
| match dstTy with | |
| | .array dstElem dstLen => | |
| if !MirTy.beq elemTy dstElem || !Nat.beq elems.length dstLen then | |
| .error .unsupported | |
| else | |
| match evalArgOperandsV2 bodyLocals locals mem elems with | |
| | .error k => .error k | |
| | .ok (typedVals, locals1, mem1) => | |
| let vs := argValues typedVals | |
| if !checkValUniformV2 (fun v => checkValV2 v dstElem) vs then | |
| .error .unsupported | |
| else | |
| .ok (.array vs, locals1, mem1) | |
| | _ => .error .unsupported | |
| | .repeat_ op elemTy count => | |
| match dstTy with | |
| | .array dstElem dstLen => | |
| if !MirTy.beq elemTy dstElem || !Nat.beq count dstLen then | |
| .error .unsupported | |
| else | |
| match evalOperandToSlotV2 bodyLocals locals mem op with | |
| | .error k => .error k | |
| | .ok (opTy, optVal, locals1, mem1) => | |
| if !MirTy.beq opTy elemTy then | |
| .error .unsupported | |
| else | |
| match optVal with | |
| | none => .error .undefined | |
| | some v => | |
| if !checkValV2 v elemTy then | |
| .error .unsupported | |
| else | |
| .ok (.array (List.replicate count v), locals1, mem1) | |
| | _ => .error .unsupported | |
| | .aggregateRangeTo elemTy endOp => | |
| match elemTy with | |
| | .int .isize false => | |
| if !MirTy.beq dstTy (.rangeTo (.int .isize false)) then | |
| .error .unsupported | |
| else | |
| match evalOperandToSlotV2 bodyLocals locals mem endOp with | |
| | .error k => .error k | |
| | .ok (.int .isize false, some (.scalar sv), locals1, mem1) => | |
| .ok (.rangeTo (UInt64.ofNat sv.bits.toNat), locals1, mem1) | |
| | .ok (_, none, _, _) => .error .undefined | |
| | .ok (_, _, _, _) => .error .unsupported | |
| | _ => .error .unsupported | |
| | .aggregateRangeFrom elemTy startOp => | |
| match elemTy with | |
| | .int .isize false => | |
| if !MirTy.beq dstTy (.rangeFrom (.int .isize false)) then | |
| .error .unsupported | |
| else | |
| match evalOperandToSlotV2 bodyLocals locals mem startOp with | |
| | .error k => .error k | |
| | .ok (.int .isize false, some (.scalar sv), locals1, mem1) => | |
| .ok (.rangeFrom (UInt64.ofNat sv.bits.toNat), locals1, mem1) | |
| | .ok (_, none, _, _) => .error .undefined | |
| | .ok (_, _, _, _) => .error .unsupported | |
| | _ => .error .unsupported | |
| | .aggregateRange elemTy startOp endOp => | |
| match elemTy with | |
| | .int .isize false => | |
| if !MirTy.beq dstTy (.range (.int .isize false)) then | |
| .error .unsupported | |
| else | |
| match evalOperandToSlotV2 bodyLocals locals mem startOp with | |
| | .error k => .error k | |
| | .ok (.int .isize false, some (.scalar sSv), locals1, mem1) => | |
| match evalOperandToSlotV2 bodyLocals locals1 mem1 endOp with | |
| | .error k => .error k | |
| | .ok (.int .isize false, some (.scalar eSv), locals2, mem2) => | |
| let s := UInt64.ofNat sSv.bits.toNat | |
| let e := UInt64.ofNat eSv.bits.toNat | |
| .ok (.range s e, locals2, mem2) | |
| | .ok (_, none, _, _) => .error .undefined | |
| | .ok (_, _, _, _) => .error .unsupported | |
| | .ok (_, none, _, _) => .error .undefined | |
| | .ok (_, _, _, _) => .error .unsupported | |
| | _ => .error .unsupported | |
| | .aggregateOption variantIdx innerTy payload => | |
| if !MirTy.beq dstTy (.option innerTy) then | |
| .error .unsupported | |
| else | |
| match variantIdx, payload with | |
| | 0, none => .ok (.optionVal none, locals, mem) | |
| | 1, some pOp => | |
| match evalOperandToSlotV2 bodyLocals locals mem pOp with | |
| | .error k => .error k | |
| | .ok (pTy, some pVal, locals1, mem1) => | |
| if !MirTy.beq pTy innerTy || !checkValV2 pVal innerTy then | |
| .error .unsupported | |
| else | |
| .ok (.optionVal (some pVal), locals1, mem1) | |
| | .ok (_, none, _, _) => .error .undefined | |
| | _, _ => .error .unsupported | |
| | .aggregateStruct structTy fields => | |
| match structTy with | |
| | .struct_ _ fieldTys => | |
| if !MirTy.beq dstTy structTy then | |
| .error .unsupported | |
| else | |
| match evalArgOperandsV2 bodyLocals locals mem fields with | |
| | .error k => .error k | |
| | .ok (typedVals, locals1, mem1) => | |
| let vs := argValues typedVals | |
| if !typedArgsMatchV2 typedVals fieldTys || | |
| !checkValV2List vs fieldTys then | |
| .error .unsupported | |
| else | |
| .ok (.tuple vs, locals1, mem1) | |
| -- A recursive struct's fields have the types of its one-step unfolding, | |
| -- in which `Box<Self>` is the closed `Box<.recAdt id defn>`. | |
| | .recAdt id defn => | |
| match unfoldRecV2 id defn with | |
| | .struct_ _ fieldTys => | |
| if !MirTy.beq dstTy structTy then | |
| .error .unsupported | |
| else | |
| match evalArgOperandsV2 bodyLocals locals mem fields with | |
| | .error k => .error k | |
| | .ok (typedVals, locals1, mem1) => | |
| let vs := argValues typedVals | |
| if !typedArgsMatchV2 typedVals fieldTys || | |
| !checkValV2List vs fieldTys then | |
| .error .unsupported | |
| else | |
| .ok (.tuple vs, locals1, mem1) | |
| | _ => .error .unsupported | |
| | _ => .error .unsupported | |
| -- Variant `vi` of a payload enum holds its fields' values as the `.tuple` | |
| -- of its payload struct. | |
| | .aggregateAdtEnum enumTy vi fields => | |
| match adtVariantsV2 enumTy, layoutOfTyV2 enumTy with | |
| | some vs, some _ => | |
| match getElem? vs vi with | |
| | some (.struct_ _ fieldTys) => | |
| if !MirTy.beq dstTy enumTy then | |
| .error .unsupported | |
| else | |
| match evalArgOperandsV2 bodyLocals locals mem fields with | |
| | .error k => .error k | |
| | .ok (typedVals, locals1, mem1) => | |
| let vals := argValues typedVals | |
| if !typedArgsMatchV2 typedVals fieldTys || | |
| !checkValV2List vals fieldTys then | |
| .error .unsupported | |
| else | |
| .ok (.adtVal vi (.tuple vals), locals1, mem1) | |
| | _ => .error .unsupported | |
| | _, _ => evalFieldlessEnumAggregateV2 locals mem dstTy enumTy vi fields | |
| | .aggregateOrdering tagBits => | |
| if !MirTy.beq dstTy .ordering then | |
| .error .unsupported | |
| else | |
| match orderingOfTagBits tagBits with | |
| | some ord => .ok (.ordering ord, locals, mem) | |
| | none => .error .unsupported | |
| | .cast .unsupported _ _ | .unsupported => .error .unsupported | |
| /-- Update an immediate `Val` along a non-empty `.field` / `.constantIndex` | |
| projection path in Profile v2. -/ | |
| noncomputable def updateValAtProjV2 : | |
| MirTy → Val → List ProjectionElem → Val → Except FaultKind Val | |
| | ty, _, [], newVal => | |
| if checkValV2 newVal ty then .ok newVal else .error .unsupported | |
| | .array elem len, .array vs, .constantIndex off minLen fromEnd :: rest, newVal => | |
| if !Nat.beq vs.length len then | |
| .error .unsupported | |
| else | |
| match constantIndexOffset len off minLen fromEnd with | |
| | .error k => .error k | |
| | .ok idx => | |
| match getElem? vs idx with | |
| | none => .error .undefined | |
| | some oldElem => | |
| match updateValAtProjV2 elem oldElem rest newVal with | |
| | .error k => .error k | |
| | .ok elem' => | |
| match setElem? vs idx elem' with | |
| | some vs' => .ok (.array vs') | |
| | none => .error .unsupported | |
| | .tuple fs, .tuple vs, .field idx fTy :: rest, newVal => | |
| match getElem? fs idx, getElem? vs idx with | |
| | some elemTy, some oldElem => | |
| if !MirTy.beq elemTy fTy then | |
| .error .unsupported | |
| else | |
| match updateValAtProjV2 elemTy oldElem rest newVal with | |
| | .error k => .error k | |
| | .ok elem' => | |
| match setElem? vs idx elem' with | |
| | some vs' => .ok (.tuple vs') | |
| | none => .error .unsupported | |
| | _, _ => .error .unsupported | |
| | .rangeTo (.int .isize false), .rangeTo oldEnd, .field 0 fTy :: rest, | |
| newVal => | |
| if !MirTy.beq (.int .isize false) fTy then | |
| .error .unsupported | |
| else | |
| match updateValAtProjV2 (.int .isize false) | |
| (.scalar ⟨.isize, false, BitVec.ofNat 128 oldEnd.toNat⟩) | |
| rest newVal with | |
| | .error k => .error k | |
| | .ok (.scalar sv) => .ok (.rangeTo (UInt64.ofNat sv.bits.toNat)) | |
| | .ok _ => .error .unsupported | |
| | .rangeFrom (.int .isize false), .rangeFrom oldStart, .field 0 fTy :: rest, | |
| newVal => | |
| if !MirTy.beq (.int .isize false) fTy then | |
| .error .unsupported | |
| else | |
| match updateValAtProjV2 (.int .isize false) | |
| (.scalar ⟨.isize, false, BitVec.ofNat 128 oldStart.toNat⟩) | |
| rest newVal with | |
| | .error k => .error k | |
| | .ok (.scalar sv) => .ok (.rangeFrom (UInt64.ofNat sv.bits.toNat)) | |
| | .ok _ => .error .unsupported | |
| | .range (.int .isize false), .range oldStart oldEnd, .field idx fTy :: rest, | |
| newVal => | |
| if !MirTy.beq (.int .isize false) fTy then | |
| .error .unsupported | |
| else if Nat.beq idx 0 then | |
| match updateValAtProjV2 (.int .isize false) | |
| (.scalar ⟨.isize, false, BitVec.ofNat 128 oldStart.toNat⟩) | |
| rest newVal with | |
| | .error k => .error k | |
| | .ok (.scalar sv) => .ok (.range (UInt64.ofNat sv.bits.toNat) oldEnd) | |
| | .ok _ => .error .unsupported | |
| else if Nat.beq idx 1 then | |
| match updateValAtProjV2 (.int .isize false) | |
| (.scalar ⟨.isize, false, BitVec.ofNat 128 oldEnd.toNat⟩) | |
| rest newVal with | |
| | .error k => .error k | |
| | .ok (.scalar sv) => .ok (.range oldStart (UInt64.ofNat sv.bits.toNat)) | |
| | .ok _ => .error .unsupported | |
| else | |
| .error .unsupported | |
| | .struct_ _ fs, .tuple vs, .field idx fTy :: rest, newVal => | |
| match getElem? fs idx, getElem? vs idx with | |
| | some elemTy, some oldElem => | |
| if !MirTy.beq elemTy fTy then | |
| .error .unsupported | |
| else | |
| match updateValAtProjV2 elemTy oldElem rest newVal with | |
| | .error k => .error k | |
| | .ok elem' => | |
| match setElem? vs idx elem' with | |
| | some vs' => .ok (.tuple vs') | |
| | none => .error .unsupported | |
| | _, _ => .error .unsupported | |
| | .recAdt id defn, .tuple vs, .field idx fTy :: rest, newVal => | |
| match unfoldRecV2 id defn with | |
| | .struct_ _ fs => | |
| match getElem? fs idx, getElem? vs idx with | |
| | some elemTy, some oldElem => | |
| if !MirTy.beq elemTy fTy then | |
| .error .unsupported | |
| else | |
| match updateValAtProjV2 elemTy oldElem rest newVal with | |
| | .error k => .error k | |
| | .ok elem' => | |
| match setElem? vs idx elem' with | |
| | some vs' => .ok (.tuple vs') | |
| | none => .error .unsupported | |
| | _, _ => .error .unsupported | |
| | _ => .error .unsupported | |
| | _, _, _, _ => .error .unsupported | |
| /-- Validate a non-deref `.field` / `.constantIndex` projection tail against | |
| `baseTy` before rvalue evaluation (`eval_rvalue_into_place` destination-first | |
| order), returning `.error .undefined` for out-of-bounds `ConstantIndex`, | |
| `.error .unsupported` for ill-typed or unmodeled projections, or `.ok leafTy`. | |
| Tuple and struct fields validate alike, as `updateValAtProjV2` updates both. | |
| -/ | |
| noncomputable def validatePlaceProjV2 : | |
| MirTy → List ProjectionElem → Except FaultKind MirTy | |
| | ty, [] => .ok ty | |
| | .array elem len, .constantIndex off minLen fromEnd :: rest => | |
| match constantIndexOffset len off minLen fromEnd with | |
| | .error k => .error k | |
| | .ok _ => validatePlaceProjV2 elem rest | |
| | .tuple fs, .field idx fTy :: rest | |
| | .struct_ _ fs, .field idx fTy :: rest => | |
| match getElem? fs idx with | |
| | some t => | |
| if MirTy.beq t fTy then validatePlaceProjV2 t rest | |
| else .error .unsupported | |
| | none => .error .unsupported | |
| | .recAdt id defn, .field idx fTy :: rest => | |
| match unfoldRecV2 id defn with | |
| | .struct_ _ fs => | |
| match getElem? fs idx with | |
| | some t => | |
| if MirTy.beq t fTy then validatePlaceProjV2 t rest | |
| else .error .unsupported | |
| | none => .error .unsupported | |
| | _ => .error .unsupported | |
| | .rangeTo (.int .isize false), .field 0 fTy :: rest | |
| | .rangeFrom (.int .isize false), .field 0 fTy :: rest => | |
| if MirTy.beq (.int .isize false) fTy then | |
| validatePlaceProjV2 (.int .isize false) rest | |
| else .error .unsupported | |
| | .range (.int .isize false), .field idx fTy :: rest => | |
| if (Nat.beq idx 0 || Nat.beq idx 1) && | |
| MirTy.beq (.int .isize false) fTy then | |
| validatePlaceProjV2 (.int .isize false) rest | |
| else .error .unsupported | |
| | _, _ => .error .unsupported | |
| /-- Destination of a Profile v2 store, resolved by `resolvePlaceDestV2` | |
| before the value to store is computed: an unprojected local `localId`, a | |
| projected local `localId`, a resolved indirect-local sub-place, the pointee | |
| type `pointee` (with layout `lay`) of a dereferenced pointer local, a | |
| dereferenced projected sub-place, or the leaf (type `leafTy`, at offset `off` | |
| of allocation `aid`) of a slice element place `(*p)[i].rest`. -/ | |
| inductive PlaceDestV2 where | |
| | local (localId : LocalId) | |
| | localProj (localId : LocalId) (baseTy : MirTy) | |
| (projs : List ProjectionElem) | |
| | indirectProj (leafTy : MirTy) (mplace : MemPlace) (subOff : Nat) | |
| | deref (pointee : MirTy) (lay : LayoutData) (pv : PtrVal) | |
| | derefProjected (pointee : MirTy) (ptLay : LayoutData) | |
| (leafTy : MirTy) (subOff : Nat) (pv : PtrVal) | |
| | derefSlice (leafTy : MirTy) (aid : AllocId) (off : Nat) | |
| /-- Resolve the destination `dst : Place` of a Profile v2 store against | |
| `locals` and `mem`, without accessing the destination itself. | |
| This is the place evaluation that `rustc` performs before it evaluates an | |
| assignment's rvalue (`compiler/rustc_const_eval/src/interpret/step.rs:157-162`, | |
| `rust-lang/rust` `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`): | |
| > "pub fn eval_rvalue_into_place( | |
| > ... | |
| > let dest = self.eval_place(place)?;" | |
| and `lean-miri` matches (`Miri/Interpreter/Rvalue.lean:49-53`: "Destination | |
| evaluation is always first"). For `(*ptr)` (optionally followed by sub- | |
| projections) it reads the pointer value out of `ptr`'s slot and checks the | |
| pointer's static type, but checks nothing about the pointed-to allocation. | |
| Those access checks belong to the store itself (`writePlaceDestV2`). An | |
| unprojected local resolves to the local itself; whether it is stored in place | |
| or in its stack allocation is decided at the store, as `rustc` does for | |
| `Place::Local`. | |
| `.index` projections are first replaced by the value of their index local | |
| (`resolveIndexProjsV2`), as `eval_place` reads them. A slice element place | |
| `(*p)[i].rest` is the one projection that inspects the pointed-to allocation | |
| here: its element address must be in bounds of the slice and of a live | |
| allocation (`sliceElemAddrV2`), because `rustc` projects slice elements with | |
| an in-bounds pointer offset during place evaluation. | |
| Stores through `*const T` or `&T` return `.undefined`. MIR type checking | |
| makes that arm unreachable. -/ | |
| noncomputable def resolvePlaceDestV2 (bodyLocals : List MirTy) | |
| (locals : List LocalSlot) (mem : MemoryState) (dst : Place) | |
| (dstTy : MirTy) : Except FaultKind PlaceDestV2 := | |
| match dst.projection with | |
| | [] => .ok (.local dst.localId) | |
| | projs0 => | |
| match resolveIndexProjsV2 bodyLocals locals mem projs0 with | |
| | .error k => .error k | |
| | .ok projs => | |
| match projs with | |
| | [] => .ok (.local dst.localId) | |
| | [.deref] => | |
| match getElem? bodyLocals dst.localId, getElem? locals dst.localId with | |
| | some _, some .dead => .error .undefined | |
| | some ptrTy, some slot => | |
| match ptrTy with | |
| | .ref ptrMut pt | .rawPtr ptrMut pt => | |
| if isUnsizedTy pt || !MirTy.beq pt dstTy then | |
| .error .unsupported | |
| else if !Mutability.beq ptrMut .mut then | |
| .error .undefined | |
| else | |
| match layoutOfTyV2 pt with | |
| | none => .error .unsupported | |
| | some lay => | |
| let ptrRes : Except FaultKind (Option Val) := | |
| match slot with | |
| | .dead | .partialTuple _ => .error .undefined | |
| | .immediate optVal => .ok optVal | |
| | .indirect mplace => loadIndirectV2 mem ptrTy mplace | |
| match ptrRes with | |
| | .error k => .error k | |
| | .ok none => .error .undefined | |
| | .ok (some (.ptr pv)) => .ok (.deref pt lay pv) | |
| | .ok (some _) => .error .unsupported | |
| | _ => .error .unsupported | |
| | _, _ => .error .unsupported | |
| | .deref :: rest => | |
| match getElem? bodyLocals dst.localId, getElem? locals dst.localId with | |
| | some _, some .dead => .error .undefined | |
| | some ptrTy, some slot => | |
| match ptrTy with | |
| | .ref ptrMut pt | .rawPtr ptrMut pt => | |
| if isUnsizedTy pt then | |
| if !Mutability.beq ptrMut .mut then | |
| .error .undefined | |
| else | |
| match pt with | |
| | .slice elem => | |
| let ptrRes : Except FaultKind (Option Val) := | |
| match slot with | |
| | .dead | .partialTuple _ => .error .undefined | |
| | .immediate optVal => .ok optVal | |
| | .indirect mplace => loadIndirectV2 mem ptrTy mplace | |
| match ptrRes with | |
| | .error k => .error k | |
| | .ok none => .error .undefined | |
| | .ok (some (.slicePtr p len)) => | |
| match sliceElemAddrV2 mem elem p len.toNat rest with | |
| | .error k => .error k | |
| | .ok (leafTy, aid, off) => | |
| if !MirTy.beq leafTy dstTy then | |
| .error .unsupported | |
| else | |
| .ok (.derefSlice leafTy aid off) | |
| | .ok (some _) => .error .unsupported | |
| | _ => .error .unsupported | |
| else if !Mutability.beq ptrMut .mut then | |
| .error .undefined | |
| else | |
| match layoutOfTyV2 pt, projectMemoryLayoutV2 pt rest with | |
| | none, _ => .error .unsupported | |
| | _, .error k => .error k | |
| | some ptLay, .ok (leafTy, subOff) => | |
| if !MirTy.beq leafTy dstTy then | |
| .error .unsupported | |
| else | |
| let ptrRes : Except FaultKind (Option Val) := | |
| match slot with | |
| | .dead | .partialTuple _ => .error .undefined | |
| | .immediate optVal => .ok optVal | |
| | .indirect mplace => loadIndirectV2 mem ptrTy mplace | |
| match ptrRes with | |
| | .error k => .error k | |
| | .ok none => .error .undefined | |
| | .ok (some (.ptr pv)) => | |
| .ok (.derefProjected pt ptLay leafTy subOff pv) | |
| | .ok (some _) => .error .unsupported | |
| | _ => .error .unsupported | |
| | _, _ => .error .unsupported | |
| | projs => | |
| match getElem? bodyLocals dst.localId, getElem? locals dst.localId with | |
| | some _, some .dead => .error .undefined | |
| | some baseTy, some (.immediate _) => | |
| match validatePlaceProjV2 baseTy projs with | |
| | .error k => .error k | |
| | .ok leafTy => | |
| if !MirTy.beq leafTy dstTy then | |
| .error .unsupported | |
| else | |
| .ok (.localProj dst.localId baseTy projs) | |
| | some baseTy, some (.indirect mplace) => | |
| match projectMemoryLayoutV2 baseTy projs with | |
| | .error k => .error k | |
| | .ok (leafTy, subOff) => | |
| if !MirTy.beq leafTy dstTy then | |
| .error .unsupported | |
| else | |
| .ok (.indirectProj leafTy mplace subOff) | |
| | _, _ => .error .unsupported | |
| /-- Store `val` of type `dstTy` at the destination `dest` resolved by | |
| `resolvePlaceDestV2`, against the current `locals` and `mem`. Supports | |
| unprojected locals, dereference stores `(*ptr) = val`, and projected | |
| field/`ConstantIndex` places (requiring provenance-backed live aligned | |
| in-bounds storage). | |
| A deref store uses the same access rules as `readPlaceV2`, implemented by | |
| `storeIndirectV2` → `writeBytes`. Non-empty writes also require a `.mut` | |
| allocation (`WriteToReadOnly`). A zero-sized write performs no mutation | |
| (`src/behavior-considered-undefined.md:57`, `rust-lang/reference` | |
| `ad35aca481751a06afeb23820a672b0f3b11a476`): | |
| > "A mutation is any write of more than 0 bytes which overlaps with any of the | |
| > relevant bytes (even if that write does not change the memory contents)." -/ | |
| noncomputable def writePlaceDestV2 (locals : List LocalSlot) | |
| (mem : MemoryState) (dest : PlaceDestV2) (dstTy : MirTy) (val : Val) : | |
| Except FaultKind (List LocalSlot × MemoryState) := | |
| if !checkValV2 val dstTy then | |
| .error .unsupported | |
| else | |
| match dest with | |
| | .local localId => | |
| match getElem? locals localId with | |
| | none => .error .unsupported | |
| | some .dead => .error .undefined | |
| | some (.immediate _) | some (.partialTuple _) => | |
| match setElem? locals localId (.immediate (some val)) with | |
| | some locals1 => .ok (locals1, mem) | |
| | none => .error .unsupported | |
| | some (.indirect mplace) => | |
| match storeIndirectV2 mem dstTy mplace val with | |
| | .ok mem1 => .ok (locals, mem1) | |
| | .error k => .error k | |
| | .deref pt lay pv => | |
| match pv.allocId with | |
| -- No provenance: only a zero-sized write at a non-null | |
| -- aligned address is accepted. Null is rejected even for | |
| -- ZSTs (conservative). See the matching arm of `readPlaceV2`. | |
| | none => | |
| if Nat.beq pv.offsetBytes.toNat 0 || Nat.blt 0 lay.size || | |
| !Nat.beq (Nat.mod pv.offsetBytes.toNat (Nat.pow 2 lay.alignLog2)) 0 then | |
| .error .undefined | |
| else | |
| match encodeValV2 profileV2TargetEndian pt val with | |
| | .error k => .error k | |
| | .ok [] => .ok (locals, mem) | |
| | .ok (_ :: _) => .error .unsupported | |
| | some aid => | |
| match findAllocation aid mem.allocations with | |
| | none => .error .undefined | |
| | some a => | |
| if Nat.blt 0 lay.size && | |
| (!a.live || !Mutability.beq a.mutability .mut) then | |
| .error .undefined | |
| else | |
| match storeIndirectV2 mem pt ⟨aid, pv.offsetBytes.toNat⟩ val with | |
| | .ok mem1 => .ok (locals, mem1) | |
| | .error k => .error k | |
| | .localProj localId baseTy projs => | |
| match getElem? locals localId with | |
| | none => .error .unsupported | |
| | some .dead => .error .undefined | |
| | some (.immediate (some oldVal)) => | |
| match updateValAtProjV2 baseTy oldVal projs val with | |
| | .error k => .error k | |
| | .ok updated => | |
| match setElem? locals localId (.immediate (some updated)) with | |
| | some locals1 => .ok (locals1, mem) | |
| | none => .error .unsupported | |
| | some (.immediate none) | some (.partialTuple _) => .error .unsupported | |
| | some (.indirect mplace) => | |
| match projectMemoryLayoutV2 baseTy projs with | |
| | .error k => .error k | |
| | .ok (leafTy, subOff) => | |
| if !MirTy.beq leafTy dstTy then | |
| .error .unsupported | |
| else | |
| match storeIndirectV2 mem leafTy ⟨mplace.allocId, mplace.offset + subOff⟩ val with | |
| | .ok mem1 => .ok (locals, mem1) | |
| | .error k => .error k | |
| | .indirectProj leafTy mplace subOff => | |
| match storeIndirectV2 mem leafTy ⟨mplace.allocId, mplace.offset + subOff⟩ val with | |
| | .ok mem1 => .ok (locals, mem1) | |
| | .error k => .error k | |
| | .derefProjected _pt ptLay leafTy subOff pv => | |
| match pv.allocId with | |
| | none => | |
| if Nat.beq pv.offsetBytes.toNat 0 || Nat.blt 0 ptLay.size || | |
| !Nat.beq (Nat.mod pv.offsetBytes.toNat (Nat.pow 2 ptLay.alignLog2)) 0 then | |
| .error .undefined | |
| else | |
| match encodeValV2 profileV2TargetEndian leafTy val with | |
| | .error k => .error k | |
| | .ok [] => .ok (locals, mem) | |
| | .ok (_ :: _) => .error .unsupported | |
| | some aid => | |
| match findAllocation aid mem.allocations with | |
| | none => .error .undefined | |
| | some a => | |
| if !a.live || | |
| !isInBounds a pv.offsetBytes.toNat ptLay.size || | |
| !isAligned a pv.offsetBytes.toNat ptLay.alignLog2 then | |
| .error .undefined | |
| else | |
| match storeIndirectV2 mem leafTy ⟨aid, pv.offsetBytes.toNat + subOff⟩ val with | |
| | .ok mem1 => .ok (locals, mem1) | |
| | .error k => .error k | |
| | .derefSlice leafTy aid off => | |
| match findAllocation aid mem.allocations with | |
| | none => .error .undefined | |
| | some a => | |
| if !a.live then | |
| .error .undefined | |
| else | |
| match storeIndirectV2 mem leafTy ⟨aid, off⟩ val with | |
| | .ok mem1 => .ok (locals, mem1) | |
| | .error k => .error k | |
| /-- Write `val` into `dst : Place` in Profile v2, resolving `dst` and storing | |
| to it against the same `locals` and `mem` (`resolvePlaceDestV2`, then | |
| `writePlaceDestV2`). Assignments resolve their destination before evaluating | |
| their rvalue instead (see `evalStatementV2`). -/ | |
| noncomputable def writePlaceV2 (bodyLocals : List MirTy) (locals : List LocalSlot) | |
| (mem : MemoryState) (dst : Place) (dstTy : MirTy) (val : Val) : | |
| Except FaultKind (List LocalSlot × MemoryState) := | |
| match resolvePlaceDestV2 bodyLocals locals mem dst dstTy with | |
| | .error k => .error k | |
| | .ok dest => writePlaceDestV2 locals mem dest dstTy val | |
| /-- Determine the static pointee/destination type of `dst : Place` in | |
| Profile v2. Fast-paths `[]` and `[.deref]` inline so proofs unfolding only | |
| `placeStaticTyV2` do not need to unfold `placeProjectedTyV2`. -/ | |
| noncomputable def placeStaticTyV2 (bodyLocals : List MirTy) (dst : Place) : | |
| Option MirTy := | |
| match getElem? bodyLocals dst.localId, dst.projection with | |
| | some ty, [] => some ty | |
| | some (.ref _ pt), [.deref] | some (.rawPtr _ pt), [.deref] => | |
| if isUnsizedTy pt then none else some pt | |
| | _, [] | _, [.deref] => none | |
| | _, _ => placeProjectedTyV2 bodyLocals dst | |
| /-- Representation class governing whether `StatementKind.assign` copies a | |
| sized Profile v2 value as zero bytes (`zst`), as a padding-free immediate | |
| (`scalar` / `scalarPair`), or via `copy_nonoverlapping` memory copy | |
| (`memoryCopy`). | |
| In MIR (`compiler/rustc_middle/src/mir/syntax.rs:328-335`, `rust-lang/rust` | |
| `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`): | |
| > "We currently require that the LHS place not overlap with any place read as | |
| > part of computation of the RHS for some rvalues. This requirement is under | |
| > discussion in [#68364]. Specifically, overlap is permitted only for | |
| > assignments of a type with `BackendRepr::Scalar | BackendRepr::ScalarPair` | |
| > where all the scalar fields are | |
| > [`Scalar::Initialized`][rustc_abi::Scalar::Initialized]." | |
| In `rustc_const_eval`'s `copy_op_no_validate` | |
| (`compiler/rustc_const_eval/src/interpret/place.rs:901-922, 970-977`, | |
| `rust-lang/rust` `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`): | |
| > "If the source has padding, we want to always do a mem-to-mem copy to ensure | |
| > consistent padding in the target independent of layout choices." | |
| > "left_size + right_size != src.layout().size" | |
| > "BackendRepr::Memory { .. } => true," | |
| > "Setting `nonoverlapping` here only has an effect when we don't hit the | |
| > fast-path above, but that should at least match what LLVM does where `memcpy` | |
| > is also only used when the type does not have Scalar/ScalarPair layout." | |
| > "self.mem_copy(src.ptr(), dest.ptr(), dest_size, /*nonoverlapping*/ true)?;" | |
| Vendored `lean-miri` (`anneal/vendor/lean-miri/Miri/Interpreter/Place.lean`, | |
| lines 339-381, commit `c92d1d9754c9dd585b6b9d6949ae67e5e4665d6a`, | |
| `copyRuntimePlaceNoValidate`) mirrors this directly: | |
| > "`copy.memoryCopy` enforces `nonoverlapping = true` (per `PlaceCopyHooks` and | |
| > `Allocation.copyRepeatedly`), so any overlapping copy with initialized bytes | |
| > fails with `.copyRangesOverlap` UB before reaching deinitialization" | |
| Thus `Rvalue::Use` and per-field `Aggregate` writes take the non-overlapping | |
| memory-copy path whenever `size > 0` and either the type has | |
| `BackendRepr::Memory` (arrays `[T; N]` with `N > 0` and non-ZST `T`, tuples | |
| with `>= 3` scalars, or alignment-inflated tuples such as `([u64; 0], u32, u32)` | |
| and `([u32; 0], u8)` where aggregate alignment exceeds scalar alignment per | |
| `rustc_abi::LayoutCalculator::univariant`) or has padding bytes | |
| (`src_has_padding = true`, e.g. `(u32, bool)` or `(u32, u8)`). -/ | |
| inductive CopyReprV2 where | |
| | zst (alignLog2 : Nat) | |
| | scalar (alignLog2 : Nat) | |
| | scalarPair (elemAlignLog2 : Nat) | |
| | memoryCopy | |
| /-- Accumulator for flattening tuple fields when classifying `CopyReprV2`. -/ | |
| inductive TupleCopyPayloadV2 where | |
| | none | |
| | oneScalar (alignLog2 : Nat) | |
| | twoScalars (elemAlignLog2 : Nat) | |
| | memory | |
| mutual | |
| /-- Classify `ty` into its `CopyReprV2` representation class. -/ | |
| noncomputable def copyReprOfTyV2 : MirTy → CopyReprV2 | |
| | .unit | .never => .zst 0 | |
| | .bool | .ordering => .scalar 0 | |
| | .int w _ => .scalar (intLayout w).alignLog2 | |
| | .char => .scalar 2 | |
| | .enum ety => | |
| if !enumAdmitted ety then | |
| .memoryCopy | |
| else | |
| match ety.tagRepr with | |
| | .zeroSized => .zst 0 | |
| | .scalar tagW _ => .scalar (intLayout tagW).alignLog2 | |
| | .rangeTo (.int .isize false) | .rangeFrom (.int .isize false) => .scalar 3 | |
| | .range (.int .isize false) => .scalarPair 3 | |
| -- A `Box<T>` handle is a pointer (`Unique<T>`), so `rustc` gives it the | |
| -- reference's `Scalar`/`ScalarPair` representation. | |
| | .ref _ pt | .rawPtr _ pt | .box pt => | |
| if isUnsizedTy pt then .scalarPair 3 else .scalar 3 | |
| | .array elem len => | |
| match copyReprOfTyV2 elem with | |
| | .zst a => .zst a | |
| | .scalar a | .scalarPair a => | |
| if Nat.beq len 0 then .zst a else .memoryCopy | |
| | .memoryCopy => | |
| if Nat.beq len 0 then | |
| match layoutOfArrayV2 elem with | |
| | some l => .zst l.alignLog2 | |
| | none => .memoryCopy | |
| else | |
| .memoryCopy | |
| | .tuple fs => | |
| let (maxA, payload) := copyReprOfTupleFieldsV2 fs | |
| match payload with | |
| | .none => .zst maxA | |
| | .oneScalar a => if Nat.ble maxA a then .scalar a else .memoryCopy | |
| | .twoScalars a => if Nat.ble maxA a then .scalarPair a else .memoryCopy | |
| | .memory => .memoryCopy | |
| -- `Option<T>` stays `.memoryCopy` (the strictest class) even where `rustc` | |
| -- picks `Scalar`/`ScalarPair`: a `None` payload is uninit, so we do not | |
| -- claim the immediate-copy path. A `Vec` handle (pointer, capacity, | |
| -- length) has three scalars and is therefore `BackendRepr::Memory`. | |
| -- Structs (recursive or not) and payload enums, whose field order, tag, | |
| -- and padding come from `rustc`'s layout, are classified the same | |
| -- conservative way. An inline back edge has no layout. | |
| | .option _ | .vec _ | .struct_ _ _ | .recAdt _ _ | .recSelf _ | |
| | .adtEnum _ _ | .slice _ | |
| | .str | .rangeTo _ | .rangeFrom _ | .range _ | .unsupported => .memoryCopy | |
| noncomputable def copyReprOfTupleFieldsV2 : | |
| List MirTy → Nat × TupleCopyPayloadV2 | |
| | [] => (0, .none) | |
| | f :: fs => | |
| let (restMaxA, restPayload) := copyReprOfTupleFieldsV2 fs | |
| match copyReprOfTyV2 f with | |
| | .zst fa => (Nat.max fa restMaxA, restPayload) | |
| | .scalar fa => | |
| let nextPayload := | |
| match restPayload with | |
| | .none => .oneScalar fa | |
| | .oneScalar a1 => | |
| if Nat.beq fa a1 then .twoScalars fa else .memory | |
| | .twoScalars _ | .memory => .memory | |
| (Nat.max fa restMaxA, nextPayload) | |
| | .scalarPair fa => | |
| let nextPayload := | |
| match restPayload with | |
| | .none => .twoScalars fa | |
| | _ => .memory | |
| (Nat.max fa restMaxA, nextPayload) | |
| | .memoryCopy => (restMaxA, .memory) | |
| end | |
| /-- Return `true` iff `ty` copies through `copy_nonoverlapping` (`size > 0` | |
| with `BackendRepr::Memory` or layout padding). -/ | |
| noncomputable def isMemoryCopyReprTyV2 (ty : MirTy) : Bool := | |
| match copyReprOfTyV2 ty with | |
| | .memoryCopy => true | |
| | _ => false | |
| /-- Normalized projection step inside an unpromoted immediate local slot. -/ | |
| inductive ImmProjStepV2 where | |
| | field (idx : Nat) | |
| | index (idx : Nat) | |
| /-- Storage span of a place for `Assign` overlap / in-place aliasing checks. -/ | |
| inductive CopyPlaceSpanV2 where | |
| | memRange (allocId : AllocId) (offset size : Nat) | |
| | immPath (localId : LocalId) (steps : List ImmProjStepV2) | |
| /-- Symmetric prefix relation on immediate-local projection paths: two paths in | |
| the same immediate local overlap iff one is a prefix of the other. -/ | |
| noncomputable def immProjPrefixSymV2 : | |
| List ImmProjStepV2 → List ImmProjStepV2 → Bool | |
| | [], _ => true | |
| | _, [] => true | |
| | .field i :: r1, .field j :: r2 => Nat.beq i j && immProjPrefixSymV2 r1 r2 | |
| | .index i :: r1, .index j :: r2 => Nat.beq i j && immProjPrefixSymV2 r1 r2 | |
| | _, _ => false | |
| /-- Return `true` when two `CopyPlaceSpanV2` storage spans overlap on `> 0` | |
| bytes (or share an immediate-local sub-place prefix). -/ | |
| noncomputable def copySpansOverlapV2 : CopyPlaceSpanV2 → CopyPlaceSpanV2 → Bool | |
| | .memRange a1 off1 sz1, .memRange a2 off2 sz2 => | |
| Nat.beq a1 a2 && Nat.blt 0 sz1 && Nat.blt 0 sz2 && | |
| Nat.blt off1 (off2 + sz2) && Nat.blt off2 (off1 + sz1) | |
| | .immPath l1 p1, .immPath l2 p2 => | |
| Nat.beq l1 l2 && immProjPrefixSymV2 p1 p2 | |
| | _, _ => false | |
| /-- Normalize a non-deref projection path on an immediate local of `baseTy`. -/ | |
| noncomputable def normalizeImmProjPathV2 : | |
| MirTy → List ProjectionElem → Option (List ImmProjStepV2) | |
| | _, [] => some [] | |
| | .tuple fs, .field idx fTy :: rest | .struct_ _ fs, .field idx fTy :: rest => | |
| match getElem? fs idx with | |
| | some elemTy => | |
| if !MirTy.beq elemTy fTy then none | |
| else (normalizeImmProjPathV2 elemTy rest).map (.field idx :: ·) | |
| | none => none | |
| | .rangeTo (.int .isize false), .field 0 fTy :: rest | |
| | .rangeFrom (.int .isize false), .field 0 fTy :: rest => | |
| if !MirTy.beq (.int .isize false) fTy then none | |
| else (normalizeImmProjPathV2 (.int .isize false) rest).map (.field 0 :: ·) | |
| | .range (.int .isize false), .field idx fTy :: rest => | |
| if !Nat.blt idx 2 || !MirTy.beq (.int .isize false) fTy then none | |
| else | |
| (normalizeImmProjPathV2 (.int .isize false) rest).map (.field idx :: ·) | |
| -- A recursive struct's fields are those of its unfolding (`unfoldRecV2`), | |
| -- as for `projectMemoryLayoutV2`. | |
| | .recAdt id defn, .field idx fTy :: rest => | |
| match unfoldRecV2 id defn with | |
| | .struct_ _ fs => | |
| match getElem? fs idx with | |
| | some elemTy => | |
| if !MirTy.beq elemTy fTy then none | |
| else (normalizeImmProjPathV2 elemTy rest).map (.field idx :: ·) | |
| | none => none | |
| | _ => none | |
| -- The `Some` payload is the only sub-place of an immediate `Option`, so it | |
| -- is normalized as field `0`; a write to the whole `Option` overlaps it. | |
| | .option inner, .downcast 1 :: .field 0 fTy :: rest => | |
| if !MirTy.beq inner fTy then none | |
| else (normalizeImmProjPathV2 inner rest).map (.field 0 :: ·) | |
| -- Payload enum downcasts (`MirTy.adtEnum` and recursive payload enums | |
| -- `MirTy.recAdt _ (.adtEnum _)`): variants share the enum's storage at | |
| -- variant-dependent offsets, so a validated downcast path normalizes to `[]` | |
| -- (whole-enum span), preserving disjointness for distinct locals and outer | |
| -- struct/tuple sibling fields while detecting any same-enum overlap. | |
| | ty, .downcast vi :: rest => | |
| let isField := match rest with | .field _ _ :: _ => true | _ => false | |
| if !isField then none | |
| else | |
| match adtVariantPayloadV2 ty vi with | |
| | some pTy => (normalizeImmProjPathV2 pTy rest).map (fun _ => []) | |
| | none => none | |
| | .array elem len, .constantIndex off minLen fromEnd :: rest => | |
| match constantIndexOffset len off minLen fromEnd with | |
| | .ok idx => (normalizeImmProjPathV2 elem rest).map (.index idx :: ·) | |
| | .error _ => none | |
| | _, _ => none | |
| /-- Compute the `CopyPlaceSpanV2` of a resolved assignment destination `dest` | |
| of type `dstTy` against pre-rvalue `locals`. -/ | |
| noncomputable def destCopySpanV2 (locals : List LocalSlot) (dest : PlaceDestV2) | |
| (dstTy : MirTy) : Option CopyPlaceSpanV2 := | |
| match dest with | |
| | .local lid => | |
| match getElem? locals lid with | |
| | some (.indirect mplace) => | |
| (layoutOfTyV2 dstTy).map (fun lay => .memRange mplace.allocId mplace.offset lay.size) | |
| | some (.immediate _) | some (.partialTuple _) => some (.immPath lid []) | |
| | _ => none | |
| | .localProj lid baseTy projs => | |
| match getElem? locals lid with | |
| | some (.indirect mplace) => | |
| match projectMemoryLayoutV2 baseTy projs, layoutOfTyV2 dstTy with | |
| | .ok (_, subOff), some lay => | |
| some (.memRange mplace.allocId (mplace.offset + subOff) lay.size) | |
| | _, _ => none | |
| | some (.immediate _) | some (.partialTuple _) => | |
| (normalizeImmProjPathV2 baseTy projs).map (.immPath lid ·) | |
| | _ => none | |
| | .indirectProj leafTy mplace subOff => | |
| (layoutOfTyV2 leafTy).map (fun lay => | |
| .memRange mplace.allocId (mplace.offset + subOff) lay.size) | |
| | .deref _ lay pv => | |
| pv.allocId.map (fun aid => .memRange aid pv.offsetBytes.toNat lay.size) | |
| | .derefProjected _ _ leafTy subOff pv => | |
| match pv.allocId, layoutOfTyV2 leafTy with | |
| | some aid, some lay => | |
| some (.memRange aid (pv.offsetBytes.toNat + subOff) lay.size) | |
| | _, _ => none | |
| | .derefSlice leafTy aid off => | |
| (layoutOfTyV2 leafTy).map (fun lay => .memRange aid off lay.size) | |
| /-- Sub-destination span for field/element `idx` of an `AggregateTuple` | |
| (`isArray = false`) or `AggregateArray` (`isArray = true`) written into `base` | |
| of aggregate type `aggTy`. -/ | |
| noncomputable def destAggregateSubSpanV2 (base : CopyPlaceSpanV2) | |
| (aggTy elemTy : MirTy) (isArray : Bool) (idx : Nat) : | |
| Option CopyPlaceSpanV2 := | |
| match base with | |
| | .immPath lid steps => | |
| let step := if isArray then ImmProjStepV2.index idx else .field idx | |
| some (.immPath lid (steps ++ [step])) | |
| | .memRange aid baseOff _ => | |
| if isArray then | |
| (layoutOfTyV2 elemTy).map (fun lay => | |
| .memRange aid (baseOff + idx * lay.size) lay.size) | |
| else | |
| match aggTy with | |
| | .tuple [.int w _, .bool] => | |
| if Nat.beq idx 0 then | |
| some (.memRange aid baseOff (intLayout w).size) | |
| else if Nat.beq idx 1 then | |
| some (.memRange aid (baseOff + (intLayout w).size) 1) | |
| else | |
| none | |
| | _ => none | |
| /-- Sub-destination span for the `Some` payload of an `AggregateOption` written | |
| into `base`. -/ | |
| noncomputable def destOptionSomeSpanV2 (base : CopyPlaceSpanV2) | |
| (elemTy : MirTy) : Option CopyPlaceSpanV2 := | |
| match base with | |
| | .immPath lid steps => some (.immPath lid (steps ++ [.field 0])) | |
| | .memRange aid baseOff _ => | |
| match optionSomeOffsetV2 elemTy, layoutOfTyV2 elemTy with | |
| | some someOff, some lay => | |
| some (.memRange aid (baseOff + someOff) lay.size) | |
| | _, _ => none | |
| /-- Compute the `CopyPlaceSpanV2` of a source `Place` against pre-rvalue | |
| `locals` and `mem`, matching `readPlaceV2` and `placeAddrV2` on `.index`, | |
| `.slicePtr` (`sliceElemAddrV2`), and downcast projections | |
| (`projectMemoryPlaceV2`). -/ | |
| noncomputable def srcPlaceCopySpanV2 (bodyLocals : List MirTy) | |
| (locals : List LocalSlot) (mem : MemoryState) (place : Place) : | |
| Option CopyPlaceSpanV2 := | |
| match getElem? bodyLocals place.localId, getElem? locals place.localId with | |
| | some baseTy, some slot => | |
| match place.projection with | |
| | [] => | |
| match slot with | |
| | .indirect mplace => | |
| (layoutOfTyV2 baseTy).map (fun lay => | |
| .memRange mplace.allocId mplace.offset lay.size) | |
| | .immediate _ | .partialTuple _ => some (.immPath place.localId []) | |
| | .dead => none | |
| | .deref :: rest => | |
| match baseTy with | |
| | .ref _ pt | .rawPtr _ pt => | |
| let ptrOpt : Option Val := | |
| match slot with | |
| | .immediate optVal => optVal | |
| | .indirect mplace => | |
| match loadIndirectV2 mem baseTy mplace with | |
| | .ok optVal => optVal | |
| | .error _ => none | |
| | .dead | .partialTuple _ => none | |
| match ptrOpt with | |
| | some (.ptr pv) => | |
| match pv.allocId with | |
| | none => none | |
| | some aid => | |
| if rest.isEmpty then | |
| (layoutOfTyV2 pt).map (fun lay => | |
| .memRange aid pv.offsetBytes.toNat lay.size) | |
| else | |
| match resolveIndexProjsV2 bodyLocals locals mem rest with | |
| | .error _ => none | |
| | .ok rest' => | |
| match projectMemoryLayoutV2 pt rest' with | |
| | .ok (leafTy, subOff) => | |
| (layoutOfTyV2 leafTy).map (fun lay => | |
| .memRange aid (pv.offsetBytes.toNat + subOff) lay.size) | |
| | .error _ => | |
| match projectMemoryPlaceV2 mem aid pv.offsetBytes.toNat pt | |
| [] rest' with | |
| | .ok (leafTy, off) => | |
| (layoutOfTyV2 leafTy).map (fun lay => | |
| .memRange aid off lay.size) | |
| | .error _ => none | |
| | some (.slicePtr p len) => | |
| match pt with | |
| | .slice elem => | |
| match resolveIndexProjsV2 bodyLocals locals mem rest with | |
| | .error _ => none | |
| | .ok rest' => | |
| match sliceElemAddrV2 mem elem p len.toNat rest' with | |
| | .ok (leafTy, aid, off) => | |
| (layoutOfTyV2 leafTy).map (fun lay => | |
| .memRange aid off lay.size) | |
| | .error _ => none | |
| | _ => none | |
| | _ => none | |
| | _ => none | |
| | projs => | |
| match resolveIndexProjsV2 bodyLocals locals mem projs with | |
| | .error _ => none | |
| | .ok projs' => | |
| match slot with | |
| | .indirect mplace => | |
| -- A place through a variant resolves as a move out of it does | |
| -- (`moveLocalPlaceV2`), reading the enum at the downcast. | |
| if projsHaveDowncastV2 projs' then | |
| match projectMemoryPlaceV2 mem mplace.allocId mplace.offset baseTy | |
| [] projs' with | |
| | .ok (leafTy, off) => | |
| (layoutOfTyV2 leafTy).map (fun lay => | |
| .memRange mplace.allocId off lay.size) | |
| | .error _ => none | |
| else | |
| match projectMemoryLayoutV2 baseTy projs' with | |
| | .ok (leafTy, subOff) => | |
| (layoutOfTyV2 leafTy).map (fun lay => | |
| .memRange mplace.allocId (mplace.offset + subOff) lay.size) | |
| | .error _ => none | |
| | .immediate _ | .partialTuple _ => | |
| (normalizeImmProjPathV2 baseTy projs').map (.immPath place.localId ·) | |
| | .dead => none | |
| | _, _ => none | |
| /-- Compute the `CopyPlaceSpanV2` of an `Operand` (`none` for `.constant`). -/ | |
| noncomputable def operandCopySpanV2 (bodyLocals : List MirTy) | |
| (locals : List LocalSlot) (mem : MemoryState) : | |
| Operand → Option CopyPlaceSpanV2 | |
| | .copy p | .move p => srcPlaceCopySpanV2 bodyLocals locals mem p | |
| | .constant _ => none | |
| /-- Compute the storage span of the pointer local read when evaluating a | |
| `.deref` projection in an `Aggregate` operand (`none` for `.constant` or | |
| operands without `.deref`; `some none` when a `.deref` operand's base pointer | |
| local has an unresolved storage span). -/ | |
| noncomputable def operandDerefBaseSpanV2 (bodyLocals : List MirTy) | |
| (locals : List LocalSlot) (mem : MemoryState) : | |
| Operand → Option (Option CopyPlaceSpanV2) | |
| | .copy p | .move p => | |
| let hasDeref := | |
| p.projection.any (fun e => match e with | .deref => true | _ => false) | |
| if hasDeref then | |
| some (srcPlaceCopySpanV2 bodyLocals locals mem | |
| { localId := p.localId, projection := [] }) | |
| else | |
| none | |
| | .constant _ => none | |
| /-- Check whether any runtime `.index idxLocal` local read while evaluating | |
| `op` is overwritten by an earlier field write in `writtenSpans`. Fails closed | |
| (`true`) whenever `writtenSpans` is non-empty and an index local has an | |
| unresolved storage span (`none`). -/ | |
| noncomputable def operandIndexClobberedByV2 (bodyLocals : List MirTy) | |
| (locals : List LocalSlot) (mem : MemoryState) | |
| (writtenSpans : List CopyPlaceSpanV2) : Operand → Bool | |
| | .copy p | .move p => | |
| p.projection.any fun elem => | |
| match elem with | |
| | .index idxLid => | |
| match srcPlaceCopySpanV2 bodyLocals locals mem | |
| { localId := idxLid, projection := [] } with | |
| | none => !writtenSpans.isEmpty | |
| | some idxSpan => | |
| writtenSpans.any (fun w => copySpansOverlapV2 w idxSpan) | |
| | _ => false | |
| | .constant _ => false | |
| /-- Walk aggregate operands left-to-right matching `rustc`'s `write_aggregate` | |
| (`compiler/rustc_const_eval/src/interpret/step.rs:334-340`, `rust-lang/rust` | |
| `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`): | |
| > "for (field_index, operand) in operands.iter_enumerated() {" | |
| > " let field_dest = self.project_field(&variant_dest, field_index)?;" | |
| > " let op = self.eval_operand(operand, Some(field_dest.layout))?;" | |
| > " self.copy_op_no_validate(&op, &field_dest, /*allow_transmute*/ false)?;" | |
| > "}" | |
| and vendored `lean-miri`'s `Miri.Interpreter.writeAggregate` | |
| (`anneal/vendor/lean-miri/Miri/Interpreter/Aggregate.lean:42-74`, commit | |
| `c92d1d9754c9dd585b6b9d6949ae67e5e4665d6a`), which loops over | |
| `[:operands.size]` and executes `h.copyOpNoValidate choice operand field false`. | |
| If an earlier field write `writtenSpans` overlaps a later operand's source | |
| span, the pointer local read by a later `.deref` operand, or any runtime | |
| `.index` local read by a later operand, fail closed with `.error .unsupported`; | |
| if operand `idx` overlaps its own destination field span and | |
| `isMemoryCopyReprTyV2 fieldTy`, fault `.error .undefined` (`copy_nonoverlapping` | |
| UB). A non-constant operand whose source span cannot be resolved also fails | |
| closed with `.error .unsupported` whenever either check could apply (an earlier | |
| field was written, or `fieldTy` copies through memory). -/ | |
| noncomputable def checkAggregateCopyHazardLoopV2 (bodyLocals : List MirTy) | |
| (locals : List LocalSlot) (mem : MemoryState) (baseSpan : CopyPlaceSpanV2) | |
| (aggTy : MirTy) (isArray : Bool) (idx : Nat) | |
| (writtenSpans : List CopyPlaceSpanV2) : | |
| List MirTy → List Operand → Except FaultKind Unit | |
| | [], [] => .ok () | |
| | fieldTy :: restTys, op :: restOps => | |
| let opSpanOpt := operandCopySpanV2 bodyLocals locals mem op | |
| let unresolved := | |
| match op, opSpanOpt with | |
| | .constant _, _ => false | |
| | _, none => true | |
| | _, some _ => false | |
| let clobberedByEarlier := | |
| match opSpanOpt with | |
| | none => false | |
| | some opSpan => writtenSpans.any (fun w => copySpansOverlapV2 w opSpan) | |
| let ptrClobberedByEarlier := | |
| match operandDerefBaseSpanV2 bodyLocals locals mem op with | |
| | none => false | |
| | some none => !writtenSpans.isEmpty | |
| | some (some ptrSpan) => | |
| writtenSpans.any (fun w => copySpansOverlapV2 w ptrSpan) | |
| let indexClobberedByEarlier := | |
| operandIndexClobberedByV2 bodyLocals locals mem writtenSpans op | |
| if clobberedByEarlier then | |
| .error .unsupported | |
| else if unresolved && | |
| (!writtenSpans.isEmpty || isMemoryCopyReprTyV2 fieldTy) then | |
| .error .unsupported | |
| else if ptrClobberedByEarlier then | |
| .error .unsupported | |
| else if indexClobberedByEarlier then | |
| .error .unsupported | |
| else | |
| match destAggregateSubSpanV2 baseSpan aggTy fieldTy isArray idx with | |
| | none => | |
| let wholeOverlap := | |
| match opSpanOpt with | |
| | none => false | |
| | some opSpan => copySpansOverlapV2 baseSpan opSpan | |
| if wholeOverlap then | |
| .error .unsupported | |
| else | |
| checkAggregateCopyHazardLoopV2 bodyLocals locals mem baseSpan aggTy | |
| isArray (idx + 1) (baseSpan :: writtenSpans) restTys restOps | |
| | some subSpan => | |
| let selfOverlap := | |
| match opSpanOpt with | |
| | none => false | |
| | some opSpan => copySpansOverlapV2 subSpan opSpan | |
| if selfOverlap && isMemoryCopyReprTyV2 fieldTy then | |
| .error .undefined | |
| else | |
| checkAggregateCopyHazardLoopV2 bodyLocals locals mem baseSpan aggTy | |
| isArray (idx + 1) (subSpan :: writtenSpans) restTys restOps | |
| | _, _ => .error .unsupported | |
| /-- Post-store non-overlap and in-place aggregate hazard check for Profile v2 | |
| `StatementKind.assign`. Fast-paths non-copy rvalues and immediate/ZST `.use` | |
| assignments definitionally so proof obligations on scalar, pointer, slice, and | |
| zero-sized copies reduce by `rfl`. | |
| For `Rvalue.repeat_`, this matches `rustc`'s `write_repeat` | |
| (`compiler/rustc_const_eval/src/interpret/step.rs:366-388`, `rust-lang/rust` | |
| `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`): | |
| > "let first = self.project_index(&dest, 0)?;" | |
| > "self.copy_op(&src, &first)?;" | |
| > "self.mem_copy_repeatedly(" | |
| > " first_ptr," | |
| > " rest_ptr," | |
| > " elem_size," | |
| > " length - 1," | |
| > " /*nonoverlapping:*/ true," | |
| > ")?;" | |
| and vendored `lean-miri`'s `Miri.Interpreter.writeRepeat` | |
| (`anneal/vendor/lean-miri/Miri/Interpreter/Aggregate.lean:76-95`, commit | |
| `c92d1d9754c9dd585b6b9d6949ae67e5e4665d6a`): | |
| > "Positive lengths copy once and replicate the resulting bytes; the source can | |
| > alias the destination, so evaluating/copying every element would be | |
| > incorrect." | |
| Accordingly, when `count > 0` and `isMemoryCopyReprTyV2 elemTy`, only overlap | |
| between `op` and element `0` (`first`) faults `.undefined`; overlap with | |
| elements `1..count` is well-defined because `copy_op` copies `src` into element | |
| `0` once before `mem_copy_repeatedly` replicates element `0` into the remaining | |
| elements. -/ | |
| noncomputable def checkAssignCopyHazardV2 (bodyLocals : List MirTy) | |
| (locals : List LocalSlot) (mem : MemoryState) (dest : PlaceDestV2) | |
| (dstTy : MirTy) : Rvalue → Except FaultKind Unit | |
| | .use (.copy src) | .use (.move src) | |
| | .useRetag (.copy src) | .useRetag (.move src) => | |
| if !isMemoryCopyReprTyV2 dstTy then | |
| .ok () | |
| else | |
| match destCopySpanV2 locals dest dstTy, | |
| srcPlaceCopySpanV2 bodyLocals locals mem src with | |
| | some dSpan, some sSpan => | |
| if copySpansOverlapV2 dSpan sSpan then | |
| .error .undefined | |
| else | |
| .ok () | |
| | _, _ => .error .unsupported | |
| | .aggregateTuple fields => | |
| match copyReprOfTyV2 dstTy with | |
| | .zst _ => .ok () | |
| | _ => | |
| match dstTy, destCopySpanV2 locals dest dstTy with | |
| | .tuple fieldTys, some baseSpan => | |
| checkAggregateCopyHazardLoopV2 bodyLocals locals mem baseSpan dstTy false | |
| 0 [] fieldTys fields | |
| | _, _ => .error .unsupported | |
| | .aggregateStruct _ fields => | |
| match copyReprOfTyV2 dstTy with | |
| | .zst _ => .ok () | |
| | _ => | |
| match dstTy, destCopySpanV2 locals dest dstTy with | |
| | .struct_ _ fieldTys, some baseSpan => | |
| checkAggregateCopyHazardLoopV2 bodyLocals locals mem baseSpan dstTy | |
| false 0 [] fieldTys fields | |
| -- A recursive struct's fields have the types of its one-step unfolding, | |
| -- which `evalRvalueV2` checks the operands against. | |
| | .recAdt id defn, some baseSpan => | |
| match unfoldRecV2 id defn with | |
| | .struct_ _ fieldTys => | |
| checkAggregateCopyHazardLoopV2 bodyLocals locals mem baseSpan dstTy | |
| false 0 [] fieldTys fields | |
| | _ => .error .unsupported | |
| | _, _ => .error .unsupported | |
| | .aggregateAdtEnum _ variantIdx fields => | |
| -- A variant without fields copies no operand. | |
| if fields.isEmpty then | |
| .ok () | |
| else | |
| match copyReprOfTyV2 dstTy with | |
| | .zst _ => .ok () | |
| | _ => | |
| match adtVariantsV2 dstTy, destCopySpanV2 locals dest dstTy with | |
| | some vs, some baseSpan => | |
| match getElem? vs variantIdx with | |
| | some (.struct_ _ fieldTys) => | |
| if fields.any (fun op => | |
| match operandCopySpanV2 bodyLocals locals mem op with | |
| | some opSpan => copySpansOverlapV2 baseSpan opSpan | |
| | none => false) then | |
| .error .unsupported | |
| else | |
| checkAggregateCopyHazardLoopV2 bodyLocals locals mem baseSpan | |
| dstTy false 0 [] fieldTys fields | |
| | _ => .error .unsupported | |
| | _, _ => .error .unsupported | |
| | .aggregateArray elemTy elems => | |
| match copyReprOfTyV2 dstTy with | |
| | .zst _ => .ok () | |
| | _ => | |
| match destCopySpanV2 locals dest dstTy with | |
| | some baseSpan => | |
| checkAggregateCopyHazardLoopV2 bodyLocals locals mem baseSpan dstTy true | |
| 0 [] (List.replicate elems.length elemTy) elems | |
| | none => .error .unsupported | |
| | .repeat_ op elemTy count => | |
| if Nat.beq count 0 || !isMemoryCopyReprTyV2 elemTy then | |
| .ok () | |
| else | |
| match op with | |
| | .constant _ => .ok () | |
| | .copy src | .move src => | |
| match destCopySpanV2 locals dest dstTy, | |
| srcPlaceCopySpanV2 bodyLocals locals mem src with | |
| | some baseSpan, some opSpan => | |
| match destAggregateSubSpanV2 baseSpan dstTy elemTy true 0 with | |
| | some firstSpan => | |
| if copySpansOverlapV2 firstSpan opSpan then | |
| .error .undefined | |
| else | |
| .ok () | |
| | none => | |
| if copySpansOverlapV2 baseSpan opSpan then | |
| .error .unsupported | |
| else | |
| .ok () | |
| | _, _ => .error .unsupported | |
| | .use (.constant _) | .useRetag (.constant _) | |
| | .binaryOp _ _ _ | .unaryOp _ _ | .cast _ _ _ | .discriminant _ | |
| | .ref _ _ | .addressOf _ _ | .fakeAddressOf _ | .aggregateRangeTo _ _ | |
| | .aggregateRangeFrom _ _ | .aggregateOrdering _ | .unsupported => .ok () | |
| | .aggregateRange elemTy startOp endOp => | |
| match copyReprOfTyV2 dstTy with | |
| | .zst _ => .ok () | |
| | _ => | |
| match destCopySpanV2 locals dest dstTy with | |
| | some baseSpan => | |
| checkAggregateCopyHazardLoopV2 bodyLocals locals mem baseSpan dstTy | |
| false 0 [] [elemTy, elemTy] [startOp, endOp] | |
| | none => .error .unsupported | |
| -- `None` and constant payloads perform no place-to-place copy; `Some(op)` | |
| -- checks whether `op` overlaps the `Some` payload destination when `elemTy` | |
| -- copies through memory (`write_aggregate` / `writeAggregate`). | |
| | .aggregateOption _ _ none | |
| | .aggregateOption _ _ (some (.constant _)) => .ok () | |
| | .aggregateOption _ elemTy (some (.copy src)) | |
| | .aggregateOption _ elemTy (some (.move src)) => | |
| if !isMemoryCopyReprTyV2 elemTy then | |
| .ok () | |
| else | |
| match destCopySpanV2 locals dest dstTy, | |
| srcPlaceCopySpanV2 bodyLocals locals mem src with | |
| | some baseSpan, some opSpan => | |
| match destOptionSomeSpanV2 baseSpan elemTy with | |
| | some someSpan => | |
| if copySpansOverlapV2 someSpan opSpan then | |
| .error .undefined | |
| else | |
| .ok () | |
| | none => | |
| if copySpansOverlapV2 baseSpan opSpan then | |
| .error .unsupported | |
| else | |
| .ok () | |
| | _, _ => .error .unsupported | |
| /-- Whether a `PlaceMention` of `place`, whose leaf type `readPlaceV2` found | |
| to be `ty`, is refused because the leaf is zero-sized (or has no layout) and | |
| `place` goes through a deref. Non-zero raw-pointer projection offsets already | |
| fault with `.undefined` in `readDerefProjectedV2` without live in-bounds | |
| provenance; zero-offset zero-sized reads check neither bounds nor liveness | |
| (`readBytes`), so refusing zero-sized leaves behind a deref here remains a | |
| conservative fail-closed rule (see `evalStatementV2`). -/ | |
| noncomputable def placeMentionZstDerefV2 (place : Place) (ty : MirTy) : | |
| Bool := | |
| match place.projection with | |
| | .deref :: _ => | |
| match layoutOfTyV2 ty with | |
| | some lay => Nat.beq lay.size 0 | |
| | none => true | |
| | _ => false | |
| /-- Evaluate one `StatementKind` in Profile v2. | |
| `.assign dst rvalue` resolves `dst` against the state before the rvalue runs | |
| (`resolvePlaceDestV2`, following `eval_rvalue_into_place`), then evaluates | |
| `rvalue`, then stores into the resolved destination against the state the | |
| rvalue left (`writePlaceDestV2`). So `*_1 = PtrMetadata(move _1)` reads the | |
| pointer in `_1` before the rvalue moves out of `_1`. | |
| `.placeMention place` computes `place` and discards it. In | |
| `rustc_const_eval` | |
| (`compiler/rustc_const_eval/src/interpret/step.rs#L116-L119`, | |
| `rust-lang/rust` `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`): | |
| > "// Evaluate the place expression, without reading from it. | |
| > PlaceMention(place) => { | |
| > let _ = self.eval_place(**place)?; | |
| > }" | |
| `eval_place` reads each dereferenced pointer (`deref_pointer` calls | |
| `read_immediate`, `compiler/rustc_const_eval/src/interpret/place.rs#L466-L482`) | |
| and each index local, offsets fields with `OffsetMode::Inbounds` | |
| (`project_field`), and bounds-checks indices (`project_index`) | |
| (`compiler/rustc_const_eval/src/interpret/projection.rs#L150-L200`, | |
| `#L248-L260`, and `#L405-L429`; same `rust-lang/rust` pin). This model | |
| evaluates the place as a non-moving read (`readPlaceV2 .. false place`), | |
| keeps the locals and memory unchanged, and discards the value. That read | |
| does everything `eval_place` does and more: it also requires the base | |
| local to be live, checks the active variant of a downcast, and loads and | |
| validates the value. So every fault of `eval_place` (a dead or | |
| uninitialized pointer local, a dangling or misaligned deref, an | |
| out-of-bounds index) is also a fault here, and the model may fault where | |
| Miri does not. That is conservative for proving the absence of undefined | |
| behavior. | |
| Zero-sized leaves behind a deref are conservatively refused with `.unsupported` | |
| (`placeMentionZstDerefV2`): `readDerefProjectedV2` faults with `.undefined` on | |
| any non-zero raw-pointer projection offset without live in-bounds provenance, | |
| while zero-offset zero-sized reads check neither bounds nor liveness. -/ | |
| noncomputable def evalStatementV2 (body : Body) (frame : FrameState) | |
| (mem : MemoryState) (callerMem : CallerMemory) (stmt : StatementKind) : | |
| StepResult State TerminalOut := | |
| match stmt with | |
| | .nop => | |
| .step { | |
| frames := [{ frame with stmtIdx := frame.stmtIdx + 1 }] | |
| callerMem | |
| mem | |
| } | |
| | .storageLive localId => | |
| match getElem? body.locals localId, getElem? frame.locals localId with | |
| | some localTy, some old => | |
| match setElem? frame.locals localId (liveUninitSlot localTy) with | |
| | none => .fault .unsupported | |
| | some locals1 => | |
| match deallocateLocal mem old with | |
| | .error k => .fault k | |
| | .ok mem1 => | |
| .step { | |
| frames := [{ | |
| frame with | |
| stmtIdx := frame.stmtIdx + 1 | |
| locals := locals1 | |
| }] | |
| callerMem | |
| mem := mem1 | |
| } | |
| | _, _ => .fault .unsupported | |
| | .storageDead localId => | |
| if Nat.beq localId 0 then | |
| .fault .unsupported | |
| else | |
| match getElem? frame.locals localId with | |
| | none => .fault .unsupported | |
| | some old => | |
| match setElem? frame.locals localId .dead with | |
| | none => .fault .unsupported | |
| | some locals1 => | |
| match deallocateLocal mem old with | |
| | .error k => .fault k | |
| | .ok mem1 => | |
| .step { | |
| frames := [{ | |
| frame with | |
| stmtIdx := frame.stmtIdx + 1 | |
| locals := locals1 | |
| }] | |
| callerMem | |
| mem := mem1 | |
| } | |
| | .assign dst rvalue => | |
| match placeStaticTyV2 body.locals dst with | |
| | none => .fault .unsupported | |
| | some dstTy => | |
| match resolvePlaceDestV2 body.locals frame.locals mem dst dstTy with | |
| | .error k => .fault k | |
| | .ok dest => | |
| match evalRvalueV2 body.locals frame.locals mem dstTy rvalue with | |
| | .error k => .fault k | |
| | .ok (val, locals1, mem1) => | |
| match writePlaceDestV2 locals1 mem1 dest dstTy val with | |
| | .error k => .fault k | |
| | .ok (locals2, mem2) => | |
| match checkAssignCopyHazardV2 body.locals frame.locals mem dest | |
| dstTy rvalue with | |
| | .error k => .fault k | |
| | .ok () => | |
| .step { | |
| frames := [{ | |
| frame with | |
| stmtIdx := frame.stmtIdx + 1 | |
| locals := locals2 | |
| }] | |
| callerMem | |
| mem := mem2 | |
| } | |
| | .placeMention place => | |
| match readPlaceV2 body.locals frame.locals mem false place with | |
| | .error k => .fault k | |
| | .ok (ty, _, _, _) => | |
| if placeMentionZstDerefV2 place ty then | |
| .fault .unsupported | |
| else | |
| .step { | |
| frames := [{ frame with stmtIdx := frame.stmtIdx + 1 }] | |
| callerMem | |
| mem | |
| } | |
| | .unsupported => .fault .unsupported | |
| /-- Element-wise equality helper over two value lists using a fixed element | |
| comparator (factored out for structural recursion in `arrayValEqV2`). -/ | |
| noncomputable def valEqListWith | |
| (f : Val → Val → Except FaultKind Bool) : | |
| List Val → List Val → Except FaultKind Bool | |
| | [], [] => .ok true | |
| | x :: xs, y :: ys => | |
| match f x y with | |
| | .ok true => valEqListWith f xs ys | |
| | .ok false => .ok false | |
| | .error k => .error k | |
| | _, _ => .error .unsupported | |
| /-- Structural value equality for `CoreCallOp.arrayEq` on Profile v2 scalar, | |
| unit, ordering, and nested fixed-size array elements. -/ | |
| noncomputable def arrayValEqV2 : MirTy → Val → Val → Except FaultKind Bool | |
| | .int _ _, x, y | |
| | .bool, x, y | |
| | .char, x, y => | |
| match evalBinOp .eq x y with | |
| | .ok (.bool b) => .ok b | |
| | .ok _ => .error .unsupported | |
| | .error k => .error k | |
| | .unit, .unit, .unit => .ok true | |
| | .ordering, .ordering .less, .ordering .less | |
| | .ordering, .ordering .equal, .ordering .equal | |
| | .ordering, .ordering .greater, .ordering .greater => .ok true | |
| | .ordering, .ordering _, .ordering _ => .ok false | |
| | .array elem _, .array xs, .array ys => | |
| valEqListWith (arrayValEqV2 elem) xs ys | |
| | _, _, _ => .error .unsupported | |
| /-- Load the pointee value of type `ty` behind a valid reference pointer `p` | |
| (a provenance-free pointer addresses a zero-sized value decoded from no | |
| bytes). -/ | |
| noncomputable def loadRefPointeeV2 (m : MemoryState) (ty : MirTy) | |
| (p : PtrVal) : Except FaultKind Val := | |
| match p.allocId with | |
| | none => | |
| match decodeValV2 profileV2TargetEndian ty [] with | |
| | .ok (some v) => .ok v | |
| | .ok none => .error .undefined | |
| | .error k => .error k | |
| | some aid => | |
| match loadIndirectV2 m ty ⟨aid, p.offsetBytes.toNat⟩ with | |
| | .ok (some v) => .ok v | |
| | .ok none => .error .undefined | |
| | .error k => .error k | |
| /-- Extract `u8` scalar byte values from a captured `[u8; N]` value. -/ | |
| noncomputable def byteArrayVals? : List Val → Option (List UInt8) | |
| | [] => some [] | |
| | .scalar sv :: rest => | |
| if IntWidth.beq sv.width .i8 && !sv.signed && sv.wf then | |
| match byteArrayVals? rest with | |
| | some bs => some (UInt8.ofNat sv.bits.toNat :: bs) | |
| | none => none | |
| else | |
| none | |
| | _ => none | |
| /-- Execute a closed-world `CoreCallOp` primitive in Profile v2 against memory | |
| `m`. Every argument and result is checked against the callee's `core` | |
| signature, and any mismatch is `.unsupported`. | |
| - `.sliceLen`: `<[T]>::len(&self)` is `ptr::metadata(self)` | |
| (`library/core/src/slice/mod.rs:116-118`, `rust-lang/rust` | |
| `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`), so it reads no element and is | |
| admitted for every slice element type `refValidInMem` admits. Lean also | |
| re-validates the `&[T]` argument, which is conservative: a reference passed | |
| to a function is considered live. | |
| - `.sliceGetUncheckedRangeTo`/`RangeFrom`/`Range`: see | |
| `sliceGetUncheckedCheck`. The input integer-slice reference is | |
| validated at its own mutability `inMut`. Capture produces these only for | |
| `get_unchecked(&self)` on `[Int]`, as `&[Int] -> &[Int]`, so the | |
| `&[Int] -> &mut [Int]` arm (`.undefined`) is unreachable. | |
| - `.sliceGetUncheckedIndex`: `<[T]>::get_unchecked(idx: usize) -> &T` for | |
| sized ref-free elements (`library/core/src/slice/index.rs:237-255`, | |
| `rust-lang/rust` `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`), UB when | |
| `idx >= len`. | |
| - `.ptrAdd`: see `ptrAddInMem`. | |
| - `.usizeUncheckedSub`: UB exactly when `rhs > lhs`, which is the | |
| precondition of `usize::unchecked_sub` | |
| (`library/core/src/num/uint_macros.rs:1139-1146`, same pin): | |
| > "assert_unsafe_precondition!( | |
| > check_language_ub, | |
| > concat!(stringify!($SelfT), "::unchecked_sub cannot overflow"), | |
| > ( | |
| > lhs: $SelfT = self, | |
| > rhs: $SelfT = rhs, | |
| > ) => !lhs.overflowing_sub(rhs).1, | |
| > );" | |
| - `.intFromLeBytes`: reconstructs an integer from `[u8; size_of::<Self>()]` | |
| via `natOfLeBytes`, matching | |
| `library/core/src/num/{uint_macros.rs:4083-4085,int_macros.rs:3885-3887}` | |
| (same pin): | |
| > "pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self { | |
| > Self::from_le(Self::from_ne_bytes(bytes)) | |
| > }" | |
| - `.memSizeOf`: returns `lay.size` from `layoutOfTyV2 ty` for sized Profile v2 | |
| types, matching `library/core/src/mem/mod.rs:373-375` (same pin). A size of | |
| `isize::MAX + 1` bytes or more, which `rustc`'s layout computation rejects, | |
| fails closed with `.unsupported` instead of truncating: | |
| > "pub const fn size_of<T>() -> usize { | |
| > <T as SizedTypeProperties>::SIZE | |
| > }" | |
| A failed `core` precondition faults with `.undefined` instead of panicking, | |
| so no call unwinds (see `UnwindAction`). -/ | |
| noncomputable def execCoreCallOp (m : MemoryState) (op : CoreCallOp) | |
| (args : List (MirTy × Val)) (dstTy : MirTy) : Except FaultKind Val := | |
| match op, args with | |
| | .sliceLen, [(.ref reqMut (.slice elem), .slicePtr p len)] => | |
| if !MirTy.beq dstTy (.int .isize false) then | |
| .error .unsupported | |
| else | |
| match refValidInMem m reqMut (.slice elem) (.slicePtr p len) with | |
| | .error k => .error k | |
| | .ok () => | |
| .ok (.scalar ⟨.isize, false, truncateBits .isize (BitVec.ofNat 128 len.toNat)⟩) | |
| | .sliceGetUncheckedRangeTo, | |
| [(.ref inMut (.slice (.int w s)), .slicePtr p len), | |
| (.rangeTo (.int .isize false), .rangeTo endOff)] => | |
| match dstTy with | |
| | .ref outMut (.slice (.int outW outS)) => | |
| if !IntWidth.beq w outW || !(s == outS) then | |
| .error .unsupported | |
| else if Mutability.beq inMut .shared && Mutability.beq outMut .mut then | |
| .error .undefined | |
| else | |
| match refValidInMem m inMut (.slice (.int w s)) (.slicePtr p len) with | |
| | .error k => .error k | |
| | .ok () => | |
| sliceGetUncheckedCheck m p len.toNat 0 endOff.toNat w.byteSize | |
| | _ => .error .unsupported | |
| | .sliceGetUncheckedRangeFrom, | |
| [(.ref inMut (.slice (.int w s)), .slicePtr p len), | |
| (.rangeFrom (.int .isize false), .rangeFrom startOff)] => | |
| match dstTy with | |
| | .ref outMut (.slice (.int outW outS)) => | |
| if !IntWidth.beq w outW || !(s == outS) then | |
| .error .unsupported | |
| else if Mutability.beq inMut .shared && Mutability.beq outMut .mut then | |
| .error .undefined | |
| else | |
| match refValidInMem m inMut (.slice (.int w s)) (.slicePtr p len) with | |
| | .error k => .error k | |
| | .ok () => | |
| sliceGetUncheckedCheck m p len.toNat startOff.toNat len.toNat | |
| w.byteSize | |
| | _ => .error .unsupported | |
| | .sliceGetUncheckedRange, | |
| [(.ref inMut (.slice (.int w s)), .slicePtr p len), | |
| (.range (.int .isize false), .range startOff endOff)] => | |
| match dstTy with | |
| | .ref outMut (.slice (.int outW outS)) => | |
| if !IntWidth.beq w outW || !(s == outS) then | |
| .error .unsupported | |
| else if Mutability.beq inMut .shared && Mutability.beq outMut .mut then | |
| .error .undefined | |
| else | |
| match refValidInMem m inMut (.slice (.int w s)) (.slicePtr p len) with | |
| | .error k => .error k | |
| | .ok () => | |
| sliceGetUncheckedCheck m p len.toNat startOff.toNat endOff.toNat | |
| w.byteSize | |
| | _ => .error .unsupported | |
| | .sliceGetUncheckedIndex, | |
| [(.ref inMut (.slice elem), .slicePtr p len), | |
| (.int .isize false, .scalar idxSv)] => | |
| match dstTy with | |
| | .ref outMut outElem => | |
| if !isSizedNoRefV2Ty elem || !MirTy.beq elem outElem then | |
| .error .unsupported | |
| else if Mutability.beq inMut .shared && Mutability.beq outMut .mut then | |
| .error .undefined | |
| else | |
| match refValidInMem m inMut (.slice elem) (.slicePtr p len) with | |
| | .error k => .error k | |
| | .ok () => | |
| let idx := (truncateBits .isize idxSv.bits).toNat | |
| if !Nat.blt idx len.toNat then | |
| .error .undefined | |
| else | |
| match layoutOfTyV2 elem with | |
| | none => .error .unsupported | |
| | some lay => | |
| match ptrAddInMem m lay.size p idx with | |
| | .error k => .error k | |
| | .ok p' => .ok (.ptr p') | |
| | _ => .error .unsupported | |
| | .ptrAdd reqMut pointee, | |
| [(.rawPtr argMut argPt, .ptr p), (.int .isize false, .scalar countSv)] => | |
| if !Mutability.beq reqMut argMut || !MirTy.beq pointee argPt || | |
| !MirTy.beq dstTy (.rawPtr reqMut pointee) || isUnsizedTy pointee then | |
| .error .unsupported | |
| else | |
| match layoutOfTyV2 pointee with | |
| | none => .error .unsupported | |
| | some lay => | |
| match ptrAddInMem m lay.size p countSv.bits.toNat with | |
| | .error k => .error k | |
| | .ok p' => .ok (.ptr p') | |
| | .usizeUncheckedSub, | |
| [(.int .isize false, .scalar lSv), (.int .isize false, .scalar rSv)] => | |
| if !MirTy.beq dstTy (.int .isize false) then | |
| .error .unsupported | |
| else if !Nat.ble rSv.bits.toNat lSv.bits.toNat then | |
| .error .undefined | |
| else | |
| let diff := lSv.bits.toNat - rSv.bits.toNat | |
| .ok (.scalar ⟨.isize, false, truncateBits .isize (BitVec.ofNat 128 diff)⟩) | |
| | .intToLeBytes w s, [(.int argW argS, .scalar sv)] => | |
| if !IntWidth.beq w argW || !IntWidth.beq sv.width w || | |
| s != argS || sv.signed != s || | |
| !MirTy.beq dstTy (.array (.int .i8 false) w.byteSize) || !sv.wf then | |
| .error .unsupported | |
| else | |
| let bytes := leBytesOfNat w.byteSize sv.bits.toNat | |
| .ok (.array (bytes.map (fun b => .scalar ⟨.i8, false, BitVec.ofNat 128 b.toNat⟩))) | |
| | .intFromLeBytes w s, [(.array (.int .i8 false) len, .array vs)] => | |
| if !Nat.beq len w.byteSize || !Nat.beq vs.length w.byteSize || | |
| !MirTy.beq dstTy (.int w s) then | |
| .error .unsupported | |
| else | |
| match byteArrayVals? vs with | |
| | none => .error .unsupported | |
| | some bs => | |
| let raw := natOfLeBytes bs | |
| .ok (.scalar ⟨w, s, truncateBits w (BitVec.ofNat 128 raw)⟩) | |
| | .memSizeOf ty, [] => | |
| if !MirTy.beq dstTy (.int .isize false) || isUnsizedTy ty || | |
| !isSupportedV2LocalTy ty then | |
| .error .unsupported | |
| else | |
| match layoutOfTyV2 ty with | |
| | none => .error .unsupported | |
| | some lay => | |
| if !Nat.blt lay.size isizeMaxBytes then | |
| .error .unsupported | |
| else | |
| .ok (.scalar ⟨.isize, false, | |
| truncateBits .isize (BitVec.ofNat 128 lay.size)⟩) | |
| | .arrayEq elem len, | |
| [(.ref m1 (.array e1 n1), .ptr p1), (.ref m2 (.array e2 n2), .ptr p2)] => | |
| if !MirTy.beq dstTy .bool || !MirTy.beq elem e1 || !MirTy.beq elem e2 || | |
| !Nat.beq len n1 || !Nat.beq len n2 || !isArrayEqElemSupported elem then | |
| .error .unsupported | |
| else | |
| match refValidInMem m m1 (.array elem len) (.ptr p1), | |
| refValidInMem m m2 (.array elem len) (.ptr p2) with | |
| | .error k, _ => .error k | |
| | _, .error k => .error k | |
| | .ok (), .ok () => | |
| let loadArr (p : PtrVal) : Except FaultKind (List Val) := | |
| match p.allocId with | |
| | none => | |
| match decodeValV2 profileV2TargetEndian (.array elem len) [] with | |
| | .ok (some (.array vs)) => .ok vs | |
| | .ok _ => .error .unsupported | |
| | .error k => .error k | |
| | some aid => | |
| match loadIndirectV2 m (.array elem len) ⟨aid, p.offsetBytes.toNat⟩ with | |
| | .ok (some (.array vs)) => .ok vs | |
| | .ok none => .error .undefined | |
| | .ok (some _) => .error .unsupported | |
| | .error k => .error k | |
| match loadArr p1, loadArr p2 with | |
| | .error k, _ => .error k | |
| | _, .error k => .error k | |
| | .ok vs1, .ok vs2 => | |
| match valEqListWith (arrayValEqV2 elem) vs1 vs2 with | |
| | .ok b => .ok (.bool b) | |
| | .error k => .error k | |
| -- `<T as PartialEq>::ne` on a primitive or fixed array `T` is the negation | |
| -- of the structural `eq`, as in `core`'s provided method | |
| -- (`library/core/src/cmp.rs`, `rust-lang/rust` | |
| -- `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`): | |
| -- "fn ne(&self, other: &Rhs) -> bool {" ... "!self.eq(other)". | |
| | .partialEqNe ty, [(.ref m1 t1, .ptr p1), (.ref m2 t2, .ptr p2)] => | |
| if !MirTy.beq dstTy .bool || !MirTy.beq ty t1 || !MirTy.beq ty t2 || | |
| !isArrayEqElemSupported ty then | |
| .error .unsupported | |
| else | |
| match refValidInMem m m1 ty (.ptr p1), refValidInMem m m2 ty (.ptr p2) with | |
| | .error k, _ => .error k | |
| | _, .error k => .error k | |
| | .ok (), .ok () => | |
| match loadRefPointeeV2 m ty p1, loadRefPointeeV2 m ty p2 with | |
| | .error k, _ => .error k | |
| | _, .error k => .error k | |
| | .ok v1, .ok v2 => | |
| match arrayValEqV2 ty v1 v2 with | |
| | .ok b => .ok (.bool !b) | |
| | .error k => .error k | |
| | _, _ => .error .unsupported | |
| /-- Whether local `localId` of `locals` is an `.indirect` stack allocation. -/ | |
| noncomputable def localIsIndirectV2 (locals : List LocalSlot) | |
| (localId : LocalId) : Bool := | |
| match getElem? locals localId with | |
| | some (.indirect _) => true | |
| | _ => false | |
| /-- Operand admission for a `.coreCall`, checked by `evalTerminatorV2` before | |
| the operands are evaluated. Only the operations that overwrite `*dest` and | |
| return the old value (`.memReplace`, `.optionTake`, `execMemReplace`) are | |
| restricted: | |
| - The moved operands and the destination must be pairwise distinct | |
| unprojected locals (`moveDefinitelyDisjoint`), as for `evalCallV2`. | |
| - The destination local must not live in memory (`localIsIndirectV2`). Only | |
| a local in memory can overlap `*dest`, and Profile v2 does not model a | |
| result write that overlaps the write through `dest` (`.unsupported`). | |
| - A `.memReplace` whose type owns heap buffers (`tyHasHeapHandleV2`) must | |
| move its source (`Operand.move`) or pass a constant (`Operand.constant`, | |
| whose active variant is already restricted to heap-free owned data). A copy | |
| would give each buffer two owners. -/ | |
| noncomputable def coreCallOperandsAdmittedV2 (locals : List LocalSlot) | |
| (op : CoreCallOp) (args : List Operand) (dst : Place) : Bool := | |
| match op with | |
| | .memReplace ty => | |
| moveDefinitelyDisjoint args dst && | |
| !localIsIndirectV2 locals dst.localId && | |
| (match args with | |
| | [_, .move _] | [_, .constant _] => true | |
| | _ => !tyHasHeapHandleV2 ty) | |
| | .optionTake _ => | |
| moveDefinitelyDisjoint args dst && !localIsIndirectV2 locals dst.localId | |
| | _ => true | |
| /-- Execute any `CoreCallOp` in Profile v2, threading updated `MemoryState` | |
| for memory-mutating core contracts (`CoreContracts`) while delegating | |
| slice, raw-pointer, integer byte-conversion, equality, and `size_of` | |
| primitives to `execCoreCallOp`. The diverging `.panicAbort` never returns, so | |
| a returning call fails closed with `.unsupported` (`evalTerminatorV2` handles | |
| its `target = none` form). Exhaustive matching over `CoreCallOp` ensures new | |
| constructors cannot silently fall through to the wrong executor. Safe | |
| unconditional `CoreContracts` panics return `.panicked`. -/ | |
| noncomputable def execCoreCallWithMemOutcome (m : MemoryState) | |
| (op : CoreCallOp) (args : List (MirTy × Val)) (dstTy : MirTy) : | |
| CoreCallOutcome := | |
| match op with | |
| | .sliceLen | .sliceGetUncheckedRangeTo | .sliceGetUncheckedRangeFrom | |
| | .sliceGetUncheckedRange | .sliceGetUncheckedIndex | .ptrAdd _ _ | |
| | .usizeUncheckedSub | .intToLeBytes _ _ | .intFromLeBytes _ _ | .memSizeOf _ | |
| | .arrayEq _ _ | |
| | .partialEqNe _ => | |
| match execCoreCallOp m op args dstTy with | |
| | .ok v => .ok v m | |
| | .error k => .fault k | |
| | .sliceIndexRange _ _ | .sliceIndexRangeFrom _ _ | .sliceIsEmpty _ | |
| | .sliceSplitAt _ _ | .numIsMultipleOf _ _ | .numNextMultipleOf _ _ | |
| | .numDivCeil _ _ | .numCheckedAdd _ _ | .numCheckedMul _ _ | |
| | .numCheckedSub _ _ | .numCheckedShl _ _ | .numSaturatingAdd _ _ | |
| | .numWrappingShl _ _ | .numWrappingShr _ _ | .numLeadingZeros _ _ | |
| | .numCountOnes _ _ | .numTrailingZeros _ _ | .numNextPowerOfTwo _ _ | |
| | .numOverflowingAdd _ _ | .numOverflowingSub _ _ | .numOverflowingMul _ _ | |
| | .cmpMin _ _ | .cmpMax _ _ | .memReplace _ | .optionIsSome _ | |
| | .optionIsNone _ | .optionTake _ | .optionUnwrap _ | .tryBranchResult _ _ | |
| | .tryBranchOption _ | .fromResidualResult _ _ | .fromResidualOption _ | |
| | .defaultVal _ | .refIntPartialEq _ _ _ | .unitPartialEq _ | |
| | .scalarClone _ | .vecNew _ | |
| | .vecWithCapacity _ | .vecLen | .vecPush | .vecResize | .vecExtendFromSlice | |
| | .vecIndex | .vecIndexMut | .vecDeref | .vecDerefMut | .vecReserve | |
| | .boxFromVec | .boxDeref | .boxDerefMut | .boxClone | .boxNew _ => | |
| execCoreContractOpOutcome m op args dstTy | |
| | .panicAbort => .fault .unsupported | |
| /-- Validate the evaluated `&str` argument of `CoreCallOp.panicAbort` | |
| (`core::panicking::{panic, panic_nounwind}`) against `m`, requiring a single | |
| shared `&str` wide pointer (`Val.slicePtr` with `isize` pointer width) that | |
| satisfies `refValidInMem m .shared .str` (live, aligned, non-null, initialized | |
| bytes per `src/behavior-considered-undefined.md:44-45,69-73,180-181`, | |
| `rust-lang/reference` `ad35aca481751a06afeb23820a672b0f3b11a476`) and contains | |
| valid UTF-8 bytes (`strSliceUtf8InMem`). | |
| At `rust-lang/rust` `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`, | |
| `core::panicking::{panic, panic_nounwind}` wraps `expr: &'static str` via | |
| `fmt::Arguments::from_str(expr)` (`library/core/src/panicking.rs:150,225`), and | |
| `Arguments::as_str()` (`library/core/src/fmt/mod.rs:871-889`) reconstructs | |
| `&'static str` with `str::from_utf8_unchecked` | |
| (`library/core/src/str/converts.rs:178-182`): | |
| > "pub const fn as_str(&self) -> Option<&'static str> { | |
| > ... | |
| > if bits & 1 == 1 { | |
| > // SAFETY: This fmt::Arguments stores a &'static str. See encoding | |
| > // documentation above. | |
| > Some(unsafe { | |
| > str::from_utf8_unchecked(crate::slice::from_raw_parts( | |
| > self.template.as_ptr(), | |
| > bits >> 1, | |
| > )) | |
| > }) | |
| > } else { | |
| > None | |
| > } | |
| > }" | |
| > "pub const unsafe fn from_utf8_unchecked(v: &[u8]) -> &str { | |
| > // SAFETY: the caller must guarantee that the bytes `v` are valid UTF-8. | |
| > // Also relies on `&str` and `&[u8]` having the same layout. | |
| > unsafe { mem::transmute(v) } | |
| > }" | |
| If `refValidInMem` succeeds (`[undefined.validity.str]`) but `strSliceUtf8InMem` | |
| is `false`, `validatePanicAbortArgs` fails closed with `.error .unsupported` | |
| (conservative when a custom panic hook or absent stderr output avoids calling | |
| `Arguments::as_str()`, while rejecting `WellFormedV2` on non-UTF-8 | |
| `&'static str` inputs without an explicit UTF-8 `safetyPre`). -/ | |
| noncomputable def validatePanicAbortArgs (m : MemoryState) : | |
| List (MirTy × Val) → Except FaultKind Unit | |
| | [(.ref .shared .str, .slicePtr p len)] => | |
| if !IntWidth.beq p.width .isize then | |
| .error .unsupported | |
| else | |
| match refValidInMem m .shared .str (.slicePtr p len) with | |
| | .error k => .error k | |
| | .ok () => | |
| if !strSliceUtf8InMem m p len then | |
| .error .unsupported | |
| else | |
| .ok () | |
| | _ => .error .unsupported | |
| /-- Execute a Profile v2 `CoreCallOp` in `m`, returning `CoreCallOutcome`. | |
| Heap-allocating contracts go through `execAllocCoreCallOutcome` and every other | |
| op through `execCoreCallWithMemOutcome`. Safe unconditional panics (`Vec` | |
| indexing out of bounds, `Vec` capacity overflow, out-of-bounds slice and array | |
| ranges, `split_at` past length, and `Option::unwrap` on `None`) return | |
| `.panicked` for `evalTerminatorV2` to dispatch via `evalCorePanicAbort`. -/ | |
| noncomputable def execCoreCallOpWithMemOutcome (m : MemoryState) | |
| (op : CoreCallOp) (args : List (MirTy × Val)) (dstTy : MirTy) : | |
| CoreCallOutcome := | |
| match execAllocCoreCallOutcome m op args dstTy with | |
| | some res => res | |
| | none => execCoreCallWithMemOutcome m op args dstTy | |
| /-- Allocation ids of the returning frame's in-memory (`.indirect`) locals, | |
| which `rustc` deallocates when it pops the frame. -/ | |
| noncomputable def frameLocalAllocIds : List LocalSlot → List AllocId | |
| | [] => [] | |
| | .indirect mplace :: rest => mplace.allocId :: frameLocalAllocIds rest | |
| | _ :: rest => frameLocalAllocIds rest | |
| /-- Allocation ids of `allocs`. -/ | |
| noncomputable def allocIdsOf : List Allocation → List AllocId | |
| | [] => [] | |
| | a :: rest => a.allocId :: allocIdsOf rest | |
| /-- Allocations created during the call that are still live on return: the | |
| mutable ones absent from the caller's `callerIds` that are not one of the | |
| returning frame's local allocations (`frameIds`). In Profile v2 these are the | |
| heap buffers of the `Vec` and `Box` contracts | |
| (`Trusted.MirSemantics.AllocContracts`), which outlive the call. Callee | |
| `.rodata` allocations (`.shared`, `isRodataAllocId`) are excluded: no returned | |
| value may point into them (`hasEscapingRodataPtr`). -/ | |
| noncomputable def calleeLiveAllocations (callerIds frameIds : List AllocId) : | |
| List Allocation → List Allocation | |
| | [] => [] | |
| | a :: rest => | |
| if a.live && Mutability.beq a.mutability .mut && | |
| natNotElem a.allocId callerIds && natNotElem a.allocId frameIds then | |
| a :: calleeLiveAllocations callerIds frameIds rest | |
| else | |
| calleeLiveAllocations callerIds frameIds rest | |
| /-- Caller-visible memory on a Profile v2 return: the caller's allocations as | |
| updated by the call (`extractCallerMemory`), followed by the heap buffers the | |
| call created and did not free (`calleeLiveAllocations`), so a returned or | |
| grown `Vec`/`Box` buffer is visible to `post`. The returning frame's local | |
| allocations are not visible. -/ | |
| noncomputable def extractReturnMemoryV2 (callerMem : CallerMemory) | |
| (mem : MemoryState) (frameLocals : List LocalSlot) : CallerMemory := | |
| ⟨(extractCallerMemory callerMem mem).allocations ++ | |
| calleeLiveAllocations (allocIdsOf callerMem.allocations) | |
| (frameLocalAllocIds frameLocals) mem.allocations⟩ | |
| /-- Whether local `localId` is `r : &mut Vec<T>` or `r : &mut Box<P>`, whose | |
| `Drop` of `(*r)` goes through the `Vec`/`Box` handle readers | |
| (`readVecFromRef`, `readBoxFromRef`) rather than `dropProjectedV2`. -/ | |
| noncomputable def isDropHandleRefV2 (bodyLocals : List MirTy) | |
| (localId : LocalId) : Bool := | |
| match getElem? bodyLocals localId with | |
| | some (.ref .mut (.vec _)) | some (.ref .mut (.box _)) => true | |
| | _ => false | |
| /-- The `Drop` of the place `(*r).rest` with `r : &mut pt` holding `pv`. It is | |
| the drop half of an assignment through a mutable reference (`*r = v`, | |
| `(*r).f = v`, `(*r).f[i] = v`), which `rustc` lowers to a `Drop` of the old | |
| value followed by the store. `rest` has had its `.index` projections resolved | |
| to `.constantIndex` (`resolveIndexProjsV2`), and `projectMemoryLayoutV2` | |
| admits only field and constant-index projections, bounds-checking the index | |
| against the array length (`.undefined` when out of bounds). A downcast is | |
| `.unsupported`: deinitializing a variant's field in place could leave a niche | |
| enum's tag bytes inconsistent with its payload, so only whole enums are | |
| dropped. | |
| As for writes through `r` (`writePlaceDestV2`), the whole pointee must be live, | |
| mutable, in bounds, and aligned. The leaf value is loaded (`loadIndirectV2` | |
| validates it, and an uninitialized value, which drop elaboration never leaves | |
| behind, is `.unsupported`), its drop glue runs (`dropGlueV2`, which handles | |
| self-recursive values with fuel), and the leaf is deinitialized, as the | |
| unprojected arms do. A leaf type without drop glue, which drop elaboration | |
| never leaves a `Drop` on, a leaf type that is not a supported local type | |
| (which bounds the types `dropGlueV2` reaches), and a pointer without | |
| provenance are `.unsupported`. -/ | |
| noncomputable def dropDerefPlaceV2 (mem : MemoryState) (pt : MirTy) | |
| (pv : PtrVal) (rest : List ProjectionElem) : | |
| Except FaultKind MemoryState := | |
| match layoutOfTyV2 pt, projectMemoryLayoutV2 pt rest, pv.allocId with | |
| | none, _, _ => .error .unsupported | |
| | _, .error k, _ => .error k | |
| | _, _, none => .error .unsupported | |
| | some ptLay, .ok (leafTy, subOff), some aid => | |
| if !isSupportedV2LocalTy leafTy then | |
| .error .unsupported | |
| else if !tyNeedsDropV2 leafTy then | |
| .error .unsupported | |
| else | |
| match findAllocation aid mem.allocations with | |
| | none => .error .undefined | |
| | some a => | |
| if !a.live || !Mutability.beq a.mutability .mut || | |
| !isInBounds a pv.offsetBytes.toNat ptLay.size || | |
| !isAligned a pv.offsetBytes.toNat ptLay.alignLog2 then | |
| .error .undefined | |
| else | |
| let leaf : MemPlace := ⟨aid, pv.offsetBytes.toNat + subOff⟩ | |
| match loadIndirectV2 mem leafTy leaf with | |
| | .error k => .error k | |
| | .ok none => .error .unsupported | |
| | .ok (some v) => | |
| match dropGlueV2 mem leafTy v with | |
| | .error k => .error k | |
| | .ok mem1 => deinitIndirectV2 mem1 leafTy leaf | |
| /-- The `Drop` of a projected place `l.rest` rooted at the local `l`, with no | |
| dereference: the drop half of an assignment into a field or element of a | |
| local (`s.f[i] = v`), or the drop of a field a partial move left behind. The | |
| local is first moved to its stack allocation (`promoteLocalToMemory`, as | |
| taking a reference to it does; a local already there stays put), then `rest` | |
| has its `.index` projections resolved (`resolveIndexProjsV2`, `.undefined` on | |
| a dead or uninitialized index local), and the leaf is dropped in place as | |
| through a reference to the local (`dropDerefPlaceV2`), which admits field | |
| and constant-index projections, with constant indices bounds-checked. | |
| A place through a variant (`(l.f as V).i`), which drop elaboration leaves | |
| for the fields a partial move out of the variant did not take, is resolved | |
| by `projectMemoryPlaceV2` instead (`.undefined` unless the enum holds `V`). | |
| Its drop glue runs and the field is left in place, as `moveLocalPlaceV2` | |
| leaves a field moved out through a variant: a variant's field may hold a | |
| niche enum's tag, which a later downcast to drop another field reads. MIR | |
| never drops the field again nor drops the enum whole. The leaf type must be | |
| a supported local type with drop glue. A local's stack place starts its | |
| allocation (`allocateStack`), so the pointer is `⟨mp.allocId, 0⟩`; any other | |
| place is `.unsupported`. The locals returned are those after the | |
| promotion. -/ | |
| noncomputable def dropLocalPlaceV2 (bodyLocals : List MirTy) | |
| (locals : List LocalSlot) (mem : MemoryState) (place : Place) : | |
| Except FaultKind (List LocalSlot × MemoryState) := | |
| match promoteLocalToMemory bodyLocals locals mem place.localId with | |
| | .error k => .error k | |
| | .ok (lt, mp, locals1, mem1) => | |
| if !Nat.beq mp.offset 0 then .error .unsupported else | |
| match resolveIndexProjsV2 bodyLocals locals1 mem1 place.projection with | |
| | .error k => .error k | |
| | .ok resolved => | |
| if projsHaveDowncastV2 resolved then | |
| match projectMemoryPlaceV2 mem1 mp.allocId mp.offset lt [] resolved with | |
| | .error k => .error k | |
| | .ok (leafTy, off) => | |
| if !isSupportedV2LocalTy leafTy || !tyNeedsDropV2 leafTy then | |
| .error .unsupported | |
| else | |
| match loadIndirectV2 mem1 leafTy ⟨mp.allocId, off⟩ with | |
| | .error k => .error k | |
| | .ok none => .error .unsupported | |
| | .ok (some v) => | |
| match dropGlueV2 mem1 leafTy v with | |
| | .error k => .error k | |
| | .ok mem2 => .ok (locals1, mem2) | |
| else | |
| match dropDerefPlaceV2 mem1 lt | |
| ⟨some mp.allocId, 0, .isize⟩ resolved with | |
| | .ok mem2 => .ok (locals1, mem2) | |
| | .error k => .error k | |
| /-- The `Drop` of a projected place, returning the locals and memory after it: | |
| - `(*r).rest` with `r : &mut pt` (`rest` possibly empty) is | |
| `dropDerefPlaceV2`, which leaves the locals unchanged. As `rustc` evaluates | |
| the place before dropping it, the pointer is read first and then every index | |
| local in `rest` (`resolveIndexProjsV2`); a dead `r` or index local is | |
| `.undefined`, as for any read of it. A wide pointer (to a slice, which has | |
| no layout) is `.unsupported`. | |
| - A field `t.i` of a tuple local held directly in its slot, or a field | |
| chain `(t.i).rest` of one (`moveTuplePathV2`), is moved out of the tuple as | |
| `move` of the same place is (`readPlaceV2`, which leaves the other fields | |
| in place, faults on a field already moved out, and leaves a variant's field | |
| in place), and then its drop glue runs. Its type must be a supported local | |
| type with drop glue. | |
| - Every other place rooted at a local is `dropLocalPlaceV2`, which drops it | |
| through the local's stack allocation. | |
| Every other place is `.unsupported`. -/ | |
| noncomputable def dropProjectedV2 (bodyLocals : List MirTy) | |
| (locals : List LocalSlot) (mem : MemoryState) (place : Place) : | |
| Except FaultKind (List LocalSlot × MemoryState) := | |
| match place.projection with | |
| | .deref :: rest => | |
| match getElem? bodyLocals place.localId, getElem? locals place.localId with | |
| | some (.ref .mut pt), some slot => | |
| let ptrRes : Except FaultKind (Option Val) := | |
| match slot with | |
| | .dead | .partialTuple _ => .error .undefined | |
| | .immediate optVal => .ok optVal | |
| | .indirect mp => loadIndirectV2 mem (.ref .mut pt) mp | |
| match ptrRes with | |
| | .error k => .error k | |
| | .ok none => .error .undefined | |
| | .ok (some (.ptr pv)) => | |
| match resolveIndexProjsV2 bodyLocals locals mem rest with | |
| | .error k => .error k | |
| | .ok resolved => | |
| match dropDerefPlaceV2 mem pt pv resolved with | |
| | .ok mem1 => .ok (locals, mem1) | |
| | .error k => .error k | |
| | .ok (some _) => .error .unsupported | |
| | _, _ => .error .unsupported | |
| | .field _ _ :: _ => | |
| match getElem? bodyLocals place.localId, getElem? locals place.localId with | |
| | some (.tuple _), some (.immediate _) | |
| | some (.tuple _), some (.partialTuple _) => | |
| match readPlaceV2 bodyLocals locals mem true place with | |
| | .error k => .error k | |
| | .ok (_, none, _, _) => .error .unsupported | |
| | .ok (fTy, some v, locals1, mem1) => | |
| if !isSupportedV2LocalTy fTy || !tyNeedsDropV2 fTy then | |
| .error .unsupported | |
| else | |
| match dropGlueV2 mem1 fTy v with | |
| | .error k => .error k | |
| | .ok mem2 => .ok (locals1, mem2) | |
| | _, _ => dropLocalPlaceV2 bodyLocals locals mem place | |
| | _ :: _ => dropLocalPlaceV2 bodyLocals locals mem place | |
| | [] => .error .unsupported | |
| /-- Evaluate a basic block's `TerminatorKind` in Profile v2. | |
| `.return_` faults with `.undefined` unless every returned reference is | |
| valid, belongs to caller memory, and has `&mut` spans disjoint from the other | |
| returned spans. A returned value is "produced", so it must be valid | |
| (`src/behavior-considered-undefined.md:69-73`, `rust-lang/reference` | |
| `ad35aca481751a06afeb23820a672b0f3b11a476`): | |
| > "* Producing an [invalid value][invalid-values]. "Producing" a value happens | |
| > any time a value is assigned to or read from a place, passed to a | |
| > function/primitive operation or returned from a function/primitive | |
| > operation." | |
| Returned references are also considered live for the aliasing rules (lines | |
| 44-45 there). Popping the frame deallocates the callee's locals | |
| (`compiler/rustc_const_eval/src/interpret/stack.rs:442-453`, `rust-lang/rust` | |
| `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`), so a reference into callee stack | |
| memory would dangle (`refsStayInCallerMem`). Conservative divergence: a | |
| reference to a zero-sized callee local never dangles in Rust, but Lean rejects | |
| it. | |
| Heap buffers that the call created and did not free stay visible to the | |
| caller (`extractReturnMemoryV2`). | |
| `.assert` continues when the condition matches `expected`. Otherwise the | |
| terminator "initiates a panic" | |
| (`compiler/rustc_middle/src/mir/syntax.rs:853-854`). The | |
| `MisalignedPointerDereference` and `NullPointerDereference` asserts are | |
| inserted by the `-Zub-checks` passes | |
| (`compiler/rustc_mir_transform/src/check_pointers.rs:24-42`) in front of | |
| pointer dereferences. In `rustc` / Miri, | |
| `AssertKind::MisalignedPointerDereference` and | |
| `AssertKind::NullPointerDereference` invoke defined non-unwinding panic lang | |
| items rather than raising UB directly, so `evalAssertFailure` fails closed as | |
| `.fault .unsupported` (never `.fault .undefined`) while panic lang-item shims | |
| remain unmodeled. Every failed assert delegates to `evalAssertFailure`: under | |
| `--panic abort` without a crate-local `#[panic_handler]` and with a non-cleanup | |
| unwind action, non-optional safe panics return | |
| `.done (.aborted (extractCallerMemory callerMem mem1))`, and so do optional | |
| overflow checks when `overflowChecks = true`; optional overflow checks without | |
| `overflowChecks`, crates with a crate-local `#[panic_handler]`, cleanup | |
| unwinds, pointer-dereference check panics, and `--panic unwind` stay | |
| `.fault .unsupported`. | |
| A returning `.coreCall op args dst (some target) unwind` validates that `dst` | |
| is unprojected, its operands are admitted by `coreCallOperandsAdmittedV2` | |
| (`.fault .unsupported` otherwise), and `dst` is typed in `body.locals` and live | |
| in `locals1` after evaluating `args` (`none => .fault .unsupported`, | |
| `some .dead => .fault .undefined`, matching `evalCallV2`, so a dead destination | |
| faults UB rather than aborting cleanly). When `execCoreCallOpWithMemOutcome` | |
| reports `.panicked` (a safe unconditional `core`/`alloc` contract panic, such | |
| as an out-of-bounds slice or array range or `Vec` index, `split_at` past | |
| length, `Option::unwrap` on `None`, or `Vec` capacity overflow), it delegates | |
| to `evalCorePanicAbort` carrying `extractCallerMemory callerMem mem1`. | |
| Diverging `.coreCall .panicAbort args dst none unwind` validates `dst` | |
| (`MirTy.never` with a live local slot in `frame.locals`), evaluates `args` via | |
| `evalArgOperandsV2` (`validatePanicAbortArgs`), and delegates to | |
| `evalCorePanicAbort` carrying `extractCallerMemory callerMem mem1`. In | |
| `vendor/lean-miri/Miri/Interpreter/Call.lean:670` and `Place.lean:80-86`, | |
| `evalCallTerminator` evaluates `dest` via `localToPlace`, which does not check | |
| slot liveness on sized locals (`MirTy.never` is sized `⟨0, 0⟩`), and a | |
| diverging call never writes `destPlace`, so Miri aborts rather than raising UB | |
| on a `.dead` destination. Rejecting `none` or `some .dead` on `dst` as | |
| `.fault .unsupported` here is stricter than Miri and fail-closed (`rustc` never | |
| emits a dead destination on a call). | |
| `.sysrootCall` executes `sysrootNumBody op` atomically, which is equivalent to | |
| pushing and returning a frame because `sysrootNumBody` has no memory effects | |
| and `callTargetAdmitted` requires unprojected arguments and destination. | |
| Arguments are evaluated left-to-right before writing the destination, matching | |
| `rustc`; unchecked arithmetic overflow faults `.undefined`, and diverging | |
| (`target = none`) or cleanup calls fault `.unsupported`. -/ | |
| noncomputable def evalTerminatorV2 (body : Body) (bb : BasicBlock) | |
| (frame : FrameState) (mem : MemoryState) (callerMem : CallerMemory) | |
| (panicStrategy : PanicStrategy := .unwind) | |
| (hasLocalPanicHandler : Bool := true) | |
| (overflowChecks : Bool := false) : | |
| StepResult State TerminalOut := | |
| match bb.terminator with | |
| | .goto target => jumpToBlock frame mem callerMem target | |
| | .return_ => | |
| if bb.cleanup then | |
| .fault .unsupported | |
| else | |
| match getElem? body.locals 0 with | |
| | none => .fault .unsupported | |
| | some retTy => | |
| let retRes : Except FaultKind Val := | |
| match getElem? frame.locals 0 with | |
| | some (.immediate (some v)) => .ok v | |
| | some (.immediate none) | some .dead | some (.partialTuple _) => .error .undefined | |
| | some (.indirect mplace) => | |
| match loadIndirectV2 mem retTy mplace with | |
| | .ok (some v) => .ok v | |
| | .ok none => .error .undefined | |
| | .error k => .error k | |
| | none => .error .unsupported | |
| match retRes with | |
| | .error k => .fault k | |
| | .ok retVal => | |
| if hasEscapingRodataPtr callerMem mem retTy retVal then | |
| .fault .unsupported | |
| else if !refsStayInCallerMem callerMem retTy retVal || | |
| !refsValidInMem mem retTy retVal || | |
| !spansPairwiseDisjoint (valueAccessSpans mem retTy retVal) then | |
| .fault .undefined | |
| else | |
| .done (.returned | |
| ⟨retVal, extractReturnMemoryV2 callerMem mem frame.locals⟩) | |
| | .unreachable => .fault .undefined | |
| | .switchInt discr targets => | |
| match evalPrimitiveOperandV2 body.locals frame.locals mem discr with | |
| | .error k => .fault k | |
| | .ok (discrVal, localsAfterDiscr, memAfterDiscr) => | |
| let targetRes : Except FaultKind BasicBlockId := | |
| match discrVal with | |
| | .scalar sv => | |
| evalSwitchBranches sv.width sv.bits targets.otherwise targets.branches | |
| | .bool b => | |
| evalBoolSwitchBranches b targets.otherwise targets.branches | |
| | .char c => | |
| evalCharSwitchBranches c targets.otherwise targets.branches | |
| | _ => | |
| match targets.branches with | |
| | [] => .ok targets.otherwise | |
| | _ :: _ => .error .unsupported | |
| match targetRes with | |
| | .error k => .fault k | |
| | .ok target => | |
| jumpToBlock { frame with locals := localsAfterDiscr } memAfterDiscr | |
| callerMem target | |
| | .assert cond expected msg target unwind => | |
| match evalPrimitiveOperandV2 body.locals frame.locals mem cond with | |
| | .error k => .fault k | |
| | .ok (condVal, locals1, mem1) => | |
| match condVal with | |
| | .bool b => | |
| if b == expected then | |
| jumpToBlock { frame with locals := locals1 } mem1 callerMem target | |
| else | |
| evalAssertFailure msg panicStrategy unwind | |
| (extractCallerMemory callerMem mem1) hasLocalPanicHandler | |
| overflowChecks | |
| | _ => .fault .unsupported | |
| | .coreCall op args dst (some target) unwind => | |
| if !dst.projection.isEmpty || | |
| !coreCallOperandsAdmittedV2 frame.locals op args dst then | |
| .fault .unsupported | |
| else | |
| match getElem? body.locals dst.localId with | |
| | none => .fault .unsupported | |
| | some dstTy => | |
| match evalArgOperandsV2 body.locals frame.locals mem args with | |
| | .error k => .fault k | |
| | .ok (typedArgs, locals1, mem1) => | |
| match getElem? locals1 dst.localId with | |
| | none => .fault .unsupported | |
| | some .dead => .fault .undefined | |
| | some _ => | |
| match execCoreCallOpWithMemOutcome mem1 op typedArgs dstTy with | |
| | .fault k => .fault k | |
| | .panicked => | |
| evalCorePanicAbort panicStrategy unwind | |
| (extractCallerMemory callerMem mem1) hasLocalPanicHandler | |
| | .ok resVal mem2 => | |
| match writePlaceV2 body.locals locals1 mem2 dst dstTy resVal with | |
| | .error k => .fault k | |
| | .ok (locals2, mem3) => | |
| jumpToBlock { frame with locals := locals2 } mem3 callerMem | |
| target | |
| | .coreCall .panicAbort args dst none unwind => | |
| if !dst.projection.isEmpty then | |
| .fault .unsupported | |
| else | |
| match getElem? body.locals dst.localId, | |
| getElem? frame.locals dst.localId with | |
| | some .never, some (.immediate _) | |
| | some .never, some (.indirect _) => | |
| match evalArgOperandsV2 body.locals frame.locals mem args with | |
| | .error k => .fault k | |
| | .ok (typedArgs, _, mem1) => | |
| match validatePanicAbortArgs mem1 typedArgs with | |
| | .error k => .fault k | |
| | .ok () => | |
| evalCorePanicAbort panicStrategy unwind | |
| (extractCallerMemory callerMem mem1) hasLocalPanicHandler | |
| | _, _ => .fault .unsupported | |
| | .drop place target _ => | |
| -- A `Drop` of a type without drop glue is a no-op upstream ("After drop | |
| -- elaboration: `Drop` terminators are a complete nop for types that have | |
| -- no drop glue."), and `rustc`'s `eval_terminator` jumps straight to | |
| -- `target` ("This is the branch we enter if and only if the dropped type | |
| -- has no drop glue whatsoever. ... we do nothing here."). For other types | |
| -- it runs the drop glue ("`Drop` terminators behave exactly like a call | |
| -- to `core::mem::drop_glue` with a reference to the given place"), which | |
| -- `dropGlueV2` models (`compiler/rustc_middle/src/mir/syntax.rs:744-746`, | |
| -- `rust-lang/rust` `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`). In both | |
| -- cases, as with `Operand.move`, Profile v2 then conservatively | |
| -- deinitializes the dropped place, which can only make later reads fault. | |
| -- | |
| -- Drop elaboration never leaves a `Drop` on a place that may be | |
| -- uninitialized: `ElaborateDropsCtxt::drop_style` returns | |
| -- `(false, _, _) => DropStyle::Dead` for a place that is not maybe-init, | |
| -- and `elaborate_drop` replaces that `Drop` with a `Goto`; a maybe-init, | |
| -- maybe-uninit place is guarded by a drop flag | |
| -- (`compiler/rustc_mir_transform/src/elaborate_drops.rs:187-192` and | |
| -- `compiler/rustc_mir_transform/src/elaborate_drops.rs:500-506`, same | |
| -- pin). Dropping an uninitialized value with drop glue therefore cannot | |
| -- happen in captured MIR and faults with `.unsupported` instead of | |
| -- silently succeeding. | |
| -- | |
| -- The admitted places are an unprojected local of a supported local type | |
| -- (`isSupportedV2LocalTy`, which bounds the owned types `dropGlueV2` can | |
| -- reach); for types with drop glue, `(*r)` and `(*r).f..` with | |
| -- `r : &mut T` (the drop half of `*r = new` and `(*r).f = new`): through | |
| -- the handle readers for `r : &mut Vec<T>` or `r : &mut Box<P>`, and | |
| -- otherwise `dropProjectedV2`, as are a field `t.i` of a tuple local, whose | |
| -- value is moved out as by `Operand.move` before its drop glue runs, and | |
| -- field and element places of a local (`s.f[i]`), dropped in place in the | |
| -- local's stack allocation. Every other place faults with `.unsupported`. | |
| match place.projection with | |
| | [] => | |
| match getElem? body.locals place.localId, | |
| getElem? frame.locals place.localId with | |
| | some ty, some (.immediate optVal) => | |
| if !isSupportedV2LocalTy ty then | |
| .fault .unsupported | |
| else | |
| let glueRes : Except FaultKind MemoryState := | |
| if !tyNeedsDropV2 ty then | |
| .ok mem | |
| else | |
| match optVal with | |
| | none => .error .unsupported | |
| | some v => dropGlueV2 mem ty v | |
| match glueRes with | |
| | .error k => .fault k | |
| | .ok mem1 => | |
| match setElem? frame.locals place.localId (liveUninitSlot ty) with | |
| | some locals1 => | |
| jumpToBlock { frame with locals := locals1 } mem1 callerMem | |
| target | |
| | none => .fault .unsupported | |
| | some ty, some (.indirect mplace) => | |
| if !isSupportedV2LocalTy ty then | |
| .fault .unsupported | |
| else | |
| let glueRes : Except FaultKind MemoryState := | |
| if !tyNeedsDropV2 ty then | |
| .ok mem | |
| else | |
| match loadIndirectV2 mem ty mplace with | |
| | .error k => .error k | |
| | .ok none => .error .unsupported | |
| | .ok (some v) => dropGlueV2 mem ty v | |
| match glueRes with | |
| | .error k => .fault k | |
| | .ok mem1 => | |
| match deinitIndirectV2 mem1 ty mplace with | |
| | .ok mem2 => jumpToBlock frame mem2 callerMem target | |
| | .error k => .fault k | |
| | _, _ => .fault .unsupported | |
| | [.deref] => | |
| if !isDropHandleRefV2 body.locals place.localId then | |
| match dropProjectedV2 body.locals frame.locals mem place with | |
| | .ok (locals1, mem1) => | |
| jumpToBlock { frame with locals := locals1 } mem1 callerMem target | |
| | .error k => .fault k | |
| else | |
| match getElem? body.locals place.localId, | |
| getElem? frame.locals place.localId with | |
| | some (.ref .mut pt), some slot => | |
| -- Only `Vec` and `Box` pointees reach this arm (`isDropHandleRefV2`); | |
| -- any other pointee would fault with `.unsupported` (`handleRes`). | |
| -- The reference's own type was admitted with the body | |
| -- (`isSupportedV2LocalTy`), and `readVecFromRef`/`readBoxFromRef` | |
| -- check the element or pointee type again. | |
| let ptrRes : Except FaultKind (Option Val) := | |
| match slot with | |
| | .dead | .partialTuple _ => .error .undefined | |
| | .immediate optVal => .ok optVal | |
| | .indirect mplace => loadIndirectV2 mem (.ref .mut pt) mplace | |
| match ptrRes with | |
| | .error k => .fault k | |
| | .ok (some (.ptr selfPtr)) => | |
| let handleRes : Except FaultKind Val := | |
| match pt with | |
| | .vec elem => | |
| match readVecFromRef mem true elem selfPtr with | |
| | .error k => .error k | |
| | .ok v => .ok v.toVal | |
| | .box pointee => | |
| match readBoxFromRef mem true pointee selfPtr with | |
| | .error k => .error k | |
| | .ok b => .ok (.boxPtr b.ptr b.len) | |
| | _ => .error .unsupported | |
| match handleRes, selfPtr.allocId with | |
| | .error k, _ => .fault k | |
| | _, none => .fault .undefined | |
| | .ok v, some aid => | |
| match dropGlueV2 mem pt v with | |
| | .error k => .fault k | |
| | .ok mem1 => | |
| match deinitIndirectV2 mem1 pt | |
| ⟨aid, selfPtr.offsetBytes.toNat⟩ with | |
| | .ok mem2 => jumpToBlock frame mem2 callerMem target | |
| | .error k => .fault k | |
| | .ok _ => .fault .undefined | |
| | _, _ => .fault .unsupported | |
| | _ => | |
| match dropProjectedV2 body.locals frame.locals mem place with | |
| | .ok (locals1, mem1) => | |
| jumpToBlock { frame with locals := locals1 } mem1 callerMem target | |
| | .error k => .fault k | |
| | .sysrootCall op args dst (some target) unwind => | |
| if !callTargetAdmitted body bb (sysrootNumBody op) args dst | |
| (some target) unwind then | |
| .fault .unsupported | |
| else | |
| let expectedTy : MirTy := .int op.width op.signed | |
| match evalArgOperandsV2 body.locals frame.locals mem args with | |
| | .error k => .fault k | |
| | .ok (typedArgs, locals1, mem1) => | |
| match typedArgs with | |
| | [(_, v1), (_, v2)] => | |
| match evalBinOp (sysrootNumBinOp op.kind) v1 v2 with | |
| | .error k => .fault k | |
| | .ok resVal => | |
| match writePlaceV2 body.locals locals1 mem1 dst expectedTy | |
| resVal with | |
| | .error k => .fault k | |
| | .ok (locals2, mem2) => | |
| jumpToBlock { frame with locals := locals2 } mem2 callerMem | |
| target | |
| | _ => .fault .unsupported | |
| | .coreCall _ _ _ none _ | .sysrootCall _ _ _ none _ | |
| | .unwindResume | .call _ _ _ _ _ | .callNe _ _ _ _ _ | |
| | .callVia _ _ _ _ _ _ | .unsupported => | |
| .fault .unsupported | |
| /-- Static admission of a callee body for a Profile v2 intra-crate call: | |
| the per-body checks of `initStateV2` (non-empty blocks, in-bounds argument | |
| count and storage annotations, well-typed `Discriminant` and `Cast` | |
| destinations and `Assert` conditions, and supported local types) and the | |
| reference/raw-pointer separation, `.fakeAddressOf` discipline, and | |
| `&&int`-free signatures of `Trusted.MirSemantics.BodyStaticAdmittedV2` | |
| (`bodyMixesRefsAndRawPtrsV2`, `bodyFakeAddressOfValidV2`, | |
| `bodyHasNestedRefSignatureV2`), and well-formed self-recursive struct types | |
| (`recTyWfV2`), so every frame on the stack satisfies the same static | |
| invariants as an entry body. | |
| The callee must also be safe (`isUnsafe = false`). An `unsafe` callee may | |
| assume a caller-supplied safety precondition (`Specs.safety`, see | |
| `Trusted.MirAst.Body`) that Profile v2 does not check at the call site, and | |
| that precondition can exclude behavior the model does not treat as UB (such | |
| as aliasing violations), so calls to `unsafe` callees fail closed. -/ | |
| noncomputable def bodyCallAdmittedV2 (callee : Body) : Bool := | |
| !callee.isExternal && | |
| !callee.isUnsafe && | |
| !callee.basicBlocks.isEmpty && | |
| Nat.blt callee.argumentCount callee.locals.length && | |
| storageAnnotationsInBounds callee && | |
| discriminantTypesValidV2 callee && | |
| castTypesValid callee && | |
| assertConditionTypesValid callee && | |
| callee.locals.all isSupportedV2LocalTy && | |
| !bodyMixesRefsAndRawPtrsV2 callee && | |
| bodyFakeAddressOfValidV2 callee && | |
| !bodyHasNestedRefSignatureV2 callee && | |
| callee.locals.all (recTyWfV2 none) | |
| /-- Lift a single-frame `StepResult` onto an ambient `callers` tail stack. | |
| When `callers = []`, return `res` directly so single-frame steps reduce | |
| definitionally to the underlying statement or terminator transition. -/ | |
| noncomputable def attachCallers (callers : List FrameState) | |
| (res : StepResult State TerminalOut) : StepResult State TerminalOut := | |
| match callers with | |
| | [] => res | |
| | _ :: _ => | |
| match res with | |
| | .step s' => .step { s' with frames := s'.frames ++ callers } | |
| | .done out => .done out | |
| | .fault k => .fault k | |
| /-- Whether a Profile v2 call would pass an argument that already lives in | |
| memory, mirroring Profile v1's `evalCallArg`: a `move` of an `.indirect` | |
| local (which upstream passes in place, `FnArg::InPlace`), or a `copy` of an | |
| `.indirect` local when the call also moves an argument. -/ | |
| noncomputable def callInPlaceArgsV2 (locals : List LocalSlot) | |
| (args : List Operand) : Bool := | |
| let hasMove : Bool := | |
| args.any (fun a => match a with | .move _ => true | _ => false) | |
| args.any (fun a => | |
| match a with | |
| | .move place => localIsIndirectV2 locals place.localId | |
| | .copy place => hasMove && localIsIndirectV2 locals place.localId | |
| | .constant _ => false) | |
| /-- Evaluate a direct intra-crate call `callee(args) -> dst` (and the | |
| `eq` call of `TerminatorKind.callNe`) in Profile v2, matching the `Call` case | |
| of `eval_terminator` in `compiler/rustc_const_eval/src/interpret/step.rs` | |
| (`rust-lang/rust` `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`): | |
| > "self.eval_callee_and_args(terminator, func, args, &destination)?;" | |
| > "let destination = self.eval_place(destination)?;" | |
| > "self.init_fn_call(" | |
| - The call must return (`target = some _`) without a cleanup unwind edge, | |
| and `dst` must be an unprojected local whose type is the callee's return | |
| type `locals[0]`. | |
| - The `move` arguments and `dst` must be unprojected, pairwise distinct | |
| locals (`moveDefinitelyDisjoint`, upstream's `move_definitely_disjoint` | |
| plus Profile v1's ban on projected moved places), and none of them may | |
| already live in memory (`callInPlaceArgsV2`, `localIsIndirectV2`), as in | |
| Profile v1's `evalCallArg` and `evalCallTerminator`. Even for disjoint | |
| arguments, upstream passes a moved `.indirect` local in place and protects | |
| it, and protects an `.indirect` destination, for the duration of the call | |
| (`protectArgument` in `Miri.Interpreter.Call`), so a callee write through | |
| a raw pointer to either is UB. Profile v2 does not model in-place passing | |
| or protectors and fails closed (`.unsupported`), also for an `.indirect` | |
| copied argument when the call moves an argument. Profile v1 also rejects | |
| a partially moved tuple (`.partialTuple`) destination, but only because | |
| Profile v1 never creates one; here the return overwrites the whole local | |
| (`writePlaceV2`), as an assignment does, which is well defined upstream. | |
| - The callee body `p.bodies[callee]` must pass `bodyCallAdmittedV2`. | |
| - The arguments are evaluated left to right (`evalArgOperandsV2`, moving out | |
| of moved caller locals). Then `dst` must be live (`.undefined` otherwise), | |
| as `eval_place` of a dead local is UB even if the callee never returns. | |
| - The arguments must match the callee's parameter types statically and by | |
| value, and, as at entry (`initStateV2`), every reference argument must be | |
| valid and mutable references must not overlap (`.undefined` otherwise). | |
| - The callee frame starts at block 0 with locals initialized like an entry | |
| frame (`initLocalsLoop`) and records the return place `dst` and | |
| continuation `target` (`retDst?`/`retTarget?`). The caller frame keeps its | |
| location at the call terminator, from which `evalReturnToCallerV2` reads | |
| whether to negate the result (`.callNe`). -/ | |
| noncomputable def evalCallV2 (p : Program) (body : Body) (frame : FrameState) | |
| (callers : List FrameState) (mem : MemoryState) (callerMem : CallerMemory) | |
| (callee : DefId) (args : List Operand) (dst : Place) | |
| (target : Option BasicBlockId) (unwind : UnwindAction) : | |
| StepResult State TerminalOut := | |
| match target, unwind with | |
| | none, _ | some _, .cleanup _ => .fault .unsupported | |
| | some _, _ => | |
| if !moveDefinitelyDisjoint args dst then | |
| .fault .unsupported | |
| else if callInPlaceArgsV2 frame.locals args then | |
| .fault .unsupported | |
| else if localIsIndirectV2 frame.locals dst.localId then | |
| .fault .unsupported | |
| else | |
| match getElem? body.locals dst.localId, getElem? p.bodies callee with | |
| | some dstTy, some calleeBody => | |
| if !bodyCallAdmittedV2 calleeBody then | |
| .fault .unsupported | |
| else | |
| let paramTys := | |
| (calleeBody.locals.drop 1).take calleeBody.argumentCount | |
| match getElem? calleeBody.locals 0 with | |
| | none => .fault .unsupported | |
| | some retTy => | |
| if !MirTy.beq retTy dstTy then | |
| .fault .unsupported | |
| else | |
| match evalArgOperandsV2 body.locals frame.locals mem args with | |
| | .error k => .fault k | |
| | .ok (typedArgs, locals1, mem1) => | |
| match getElem? locals1 dst.localId with | |
| | none => .fault .unsupported | |
| | some .dead => .fault .undefined | |
| | some _ => | |
| let argVals := argValues typedArgs | |
| if !typedArgsMatchV2 typedArgs paramTys || | |
| !checkArgsMatchV2 argVals paramTys then | |
| .fault .unsupported | |
| else if !refsValidInMemList mem1 paramTys argVals || | |
| !spansPairwiseDisjoint | |
| (valueAccessSpansList mem1 paramTys argVals) then | |
| .fault .undefined | |
| else | |
| let calleeFrame : FrameState := { | |
| defId := callee | |
| blockIdx := 0 | |
| stmtIdx := 0 | |
| locals := | |
| initLocalsLoop calleeBody argVals 0 calleeBody.locals | |
| retDst? := some dst | |
| retTarget? := target | |
| } | |
| .step { | |
| frames := | |
| calleeFrame :: { frame with locals := locals1 } :: callers | |
| callerMem | |
| mem := mem1 | |
| } | |
| | _, _ => .fault .unsupported | |
| /-- Static types only from an evaluated argument list. -/ | |
| noncomputable def argTypes : List (MirTy × Val) → List MirTy | |
| | [] => [] | |
| | (t, _) :: rest => t :: argTypes rest | |
| /-- The `&A` values that the evaluated `&&A` arguments `args` of a | |
| `CallVia.refPartialEq` call point to, as `core`'s forwarding body reads them | |
| with `*self` and `*other` (`TerminatorKind.callVia`). Each argument must be a | |
| shared reference to a shared reference, and the loaded inner reference must | |
| be initialized (`.undefined` otherwise). -/ | |
| noncomputable def derefSharedRefArgsV2 (mem : MemoryState) : | |
| List (MirTy × Val) → Except FaultKind (List (MirTy × Val)) | |
| | [] => .ok [] | |
| | (.ref .shared (.ref .shared pt), .ptr p) :: rest => | |
| match p.allocId with | |
| | none => .error .undefined | |
| | some aid => | |
| match loadIndirectV2 mem (.ref .shared pt) ⟨aid, p.offsetBytes.toNat⟩ | |
| with | |
| | .error k => .error k | |
| | .ok none => .error .undefined | |
| | .ok (some inner) => | |
| match derefSharedRefArgsV2 mem rest with | |
| | .error k => .error k | |
| | .ok vs => .ok ((.ref .shared pt, inner) :: vs) | |
| | _ :: _ => .error .unsupported | |
| /-- Enter the captured callee `calleeBody` (`callee`) with the evaluated | |
| arguments `typedArgs`, as the tail of `evalCallV2` does: the arguments must | |
| match the callee's parameter types statically and by value, every reference | |
| argument must be valid and mutable references must not overlap | |
| (`.undefined` otherwise), and the callee frame starts at block 0, recording | |
| the return place `dst` and continuation `target`. -/ | |
| noncomputable def enterCalleeV2 (frame : FrameState) | |
| (callers : List FrameState) (callerMem : CallerMemory) (callee : DefId) | |
| (calleeBody : Body) (typedArgs : List (MirTy × Val)) | |
| (locals1 : List LocalSlot) (mem1 : MemoryState) (dst : Place) | |
| (target : Option BasicBlockId) : StepResult State TerminalOut := | |
| let paramTys := (calleeBody.locals.drop 1).take calleeBody.argumentCount | |
| let argVals := argValues typedArgs | |
| if !typedArgsMatchV2 typedArgs paramTys || | |
| !checkArgsMatchV2 argVals paramTys then | |
| .fault .unsupported | |
| else if !refsValidInMemList mem1 paramTys argVals || | |
| !spansPairwiseDisjoint (refAccessSpansList paramTys argVals) then | |
| .fault .undefined | |
| else | |
| let calleeFrame : FrameState := { | |
| defId := callee | |
| blockIdx := 0 | |
| stmtIdx := 0 | |
| locals := initLocalsLoop calleeBody argVals 0 calleeBody.locals | |
| retDst? := some dst | |
| retTarget? := target | |
| } | |
| .step { | |
| frames := calleeFrame :: { frame with locals := locals1 } :: callers | |
| callerMem | |
| mem := mem1 | |
| } | |
| /-- `ty` is `Option<Ordering>`, the return type of `PartialOrd::partial_cmp`, | |
| which `rustc` lays out as a payload enum (`adtOptionShapeV2`). -/ | |
| noncomputable def isOptionOrderingTyV2 : MirTy → Bool | |
| | .adtEnum _ vs => adtOptionShapeV2 .ordering vs | |
| | _ => false | |
| /-- The `bool` that `PartialOrd`'s provided `lt`, `le`, `gt`, or `ge` | |
| (`CallVia.partialOrd greater orEqual`) returns for the `Option<Ordering>` | |
| `partial_cmp` returned, as `self.partial_cmp(other).is_some_and(Ordering::is_*)` | |
| computes it: `None` (variant 0) gives `false`, and `Some(o)` (variant 1) | |
| gives `!greater` for `Less`, `orEqual` for `Equal`, and `greater` for | |
| `Greater`. Any other value is `.unsupported`. -/ | |
| noncomputable def partialOrdResultV2 (greater orEqual : Bool) : | |
| Val → Except FaultKind Val | |
| | .adtVal 0 (.tuple []) => .ok (.bool false) | |
| | .adtVal 1 (.tuple [.ordering .less]) => .ok (.bool !greater) | |
| | .adtVal 1 (.tuple [.ordering .equal]) => .ok (.bool orEqual) | |
| | .adtVal 1 (.tuple [.ordering .greater]) => .ok (.bool greater) | |
| | _ => .error .unsupported | |
| /-- Evaluate `TerminatorKind.callVia via callee args dst target unwind` in | |
| Profile v2: a call of a sysroot function whose body only prepares the | |
| arguments of one call to the captured body `p.bodies[callee]` (`CallVia`), | |
| executed as that call. | |
| As in `evalCallV2`, the call must return without a cleanup unwind edge, the | |
| moved arguments and `dst` must be pairwise distinct unprojected locals, no | |
| argument may trigger unmodeled in-place passing (`callInPlaceArgsV2`), `dst` | |
| must not be an indirect local (`localIsIndirectV2`), the callee must pass | |
| `bodyCallAdmittedV2`, the arguments are evaluated left to right, and `dst` | |
| must be live. | |
| - `.refPartialEq negate`: there are two arguments, and the callee returns | |
| `bool`, as does `dst`. Entering | |
| `core`'s forwarding function checks its two `&&A` arguments as any call | |
| does (`refsValidInMemList` and `spansPairwiseDisjoint`, `.undefined` | |
| otherwise); its body then reads `*self` and `*other` | |
| (`derefSharedRefArgsV2`) and calls the callee with them | |
| (`enterCalleeV2`). `evalReturnToCallerV2` negates the result when | |
| `negate` holds. The forwarding frame itself has no other effect, so it is | |
| not materialized. | |
| - `.boxClone pointee`: the callee returns `pointee`, a sized owned data type | |
| (`isOwnedDataTyV2`), and `dst` is a `Box<pointee>`. `Box::clone`'s frame | |
| entry checks its `&Box<pointee>` argument as any call does; its body | |
| borrows `&**self` (`readBoxFromRef`), allocates the box | |
| (`Box::new_uninit_in`: `allocHeapBuffer`, or a dangling pointer for a | |
| zero-sized `pointee`), and calls the callee with that borrow | |
| (`enterCalleeV2`). The new box is held in `dst` until the callee returns, | |
| when `evalReturnToCallerV2` writes the result into it | |
| (`storeBoxCloneResultV2`). `rustc` would hold it in `Box::clone`'s frame | |
| instead, and write it to `dst` on return; since `pointee` is owned data, | |
| the callee cannot reach `dst` through its argument, so it cannot tell the | |
| difference. | |
| - `.partialOrd _ _`: there are two arguments, the callee returns | |
| `Option<Ordering>` (`isOptionOrderingTyV2`), and `dst` is a `bool`. The | |
| provided method passes its `&A` arguments unchanged to `partial_cmp`, so | |
| the callee is entered with them (`enterCalleeV2`, which checks them as the | |
| provided method's own frame entry would). `evalReturnToCallerV2` maps the | |
| result to a `bool` (`partialOrdResultV2`). The provided method's frame has | |
| no other effect, so it is not materialized. -/ | |
| noncomputable def evalCallViaV2 (p : Program) (body : Body) (frame : FrameState) | |
| (callers : List FrameState) (mem : MemoryState) (callerMem : CallerMemory) | |
| (via : CallVia) (callee : DefId) (args : List Operand) (dst : Place) | |
| (target : Option BasicBlockId) (unwind : UnwindAction) : | |
| StepResult State TerminalOut := | |
| match target, unwind with | |
| | none, _ | some _, .cleanup _ => .fault .unsupported | |
| | some _, _ => | |
| if !(moveDefinitelyDisjoint args dst) then | |
| .fault .unsupported | |
| else if callInPlaceArgsV2 frame.locals args then | |
| .fault .unsupported | |
| else if localIsIndirectV2 frame.locals dst.localId then | |
| .fault .unsupported | |
| else | |
| match getElem? body.locals dst.localId, getElem? p.bodies callee with | |
| | some dstTy, some calleeBody => | |
| if !bodyCallAdmittedV2 calleeBody then | |
| .fault .unsupported | |
| else | |
| match getElem? calleeBody.locals 0 with | |
| | none => .fault .unsupported | |
| | some retTy => | |
| match via with | |
| | .refPartialEq _ => | |
| if !MirTy.beq retTy .bool || !MirTy.beq dstTy .bool || | |
| !Nat.beq args.length 2 then | |
| .fault .unsupported | |
| else | |
| match evalArgOperandsV2 body.locals frame.locals mem args with | |
| | .error k => .fault k | |
| | .ok (outerArgs, locals1, mem1) => | |
| match getElem? locals1 dst.localId with | |
| | none => .fault .unsupported | |
| | some .dead => .fault .undefined | |
| | some _ => | |
| let outerTys := argTypes outerArgs | |
| let outerVals := argValues outerArgs | |
| if !refsValidInMemList mem1 outerTys outerVals || | |
| !spansPairwiseDisjoint | |
| (refAccessSpansList outerTys outerVals) then | |
| .fault .undefined | |
| else | |
| match derefSharedRefArgsV2 mem1 outerArgs with | |
| | .error k => .fault k | |
| | .ok typedArgs => | |
| enterCalleeV2 frame callers callerMem callee | |
| calleeBody typedArgs locals1 mem1 dst target | |
| | .boxClone pointee => | |
| if !MirTy.beq retTy pointee || !MirTy.beq dstTy (.box pointee) || | |
| isUnsizedTy pointee || !isOwnedDataTyV2 pointee then | |
| .fault .unsupported | |
| else | |
| match layoutOfTyV2 pointee, | |
| evalArgOperandsV2 body.locals frame.locals mem args with | |
| | none, _ => .fault .unsupported | |
| | _, .error k => .fault k | |
| | some lay, .ok (outerArgs, locals1, mem1) => | |
| match getElem? locals1 dst.localId with | |
| | none => .fault .unsupported | |
| | some .dead => .fault .undefined | |
| | some _ => | |
| let outerTys := argTypes outerArgs | |
| let outerVals := argValues outerArgs | |
| if !refsValidInMemList mem1 outerTys outerVals || | |
| !spansPairwiseDisjoint | |
| (refAccessSpansList outerTys outerVals) then | |
| .fault .undefined | |
| else | |
| match outerArgs with | |
| | [(.ref .shared (.box pt), .ptr selfPtr)] => | |
| if !MirTy.beq pt pointee then | |
| .fault .unsupported | |
| else | |
| match readBoxFromRef mem1 false pointee selfPtr with | |
| | .error k => .fault k | |
| | .ok b => | |
| match b.len with | |
| | some _ => .fault .unsupported | |
| | none => | |
| let (mem2, newPtr) := | |
| if Nat.beq lay.size 0 then | |
| (mem1, danglingAligned lay.alignLog2) | |
| else | |
| allocHeapBuffer mem1 lay.size lay.alignLog2 | |
| match writePlaceV2 body.locals locals1 mem2 dst | |
| (.box pointee) (.boxPtr newPtr none) with | |
| | .error k => .fault k | |
| | .ok (locals2, mem3) => | |
| enterCalleeV2 frame callers callerMem callee | |
| calleeBody | |
| [(.ref .shared pointee, .ptr b.ptr)] | |
| locals2 mem3 dst target | |
| | _ => .fault .unsupported | |
| | .partialOrd _ _ => | |
| if !isOptionOrderingTyV2 retTy || !MirTy.beq dstTy .bool || | |
| !Nat.beq args.length 2 then | |
| .fault .unsupported | |
| else | |
| match evalArgOperandsV2 body.locals frame.locals mem args with | |
| | .error k => .fault k | |
| | .ok (typedArgs, locals1, mem1) => | |
| match getElem? locals1 dst.localId with | |
| | none => .fault .unsupported | |
| | some .dead => .fault .undefined | |
| | some _ => | |
| match typedArgs with | |
| | [(.ref .shared ty1, _), (.ref .shared ty2, _)] => | |
| if !MirTy.beq ty1 ty2 then | |
| .fault .unsupported | |
| else | |
| enterCalleeV2 frame callers callerMem callee calleeBody | |
| typedArgs locals1 mem1 dst target | |
| | _ => .fault .unsupported | |
| | _, _ => .fault .unsupported | |
| /-- Deallocate the stack allocations of a popped frame's locals | |
| (`deallocateLocal` on every slot). -/ | |
| noncomputable def deallocateFrameLocalsV2 (mem : MemoryState) : | |
| List LocalSlot → Except FaultKind MemoryState | |
| | [] => .ok mem | |
| | slot :: rest => | |
| match deallocateLocal mem slot with | |
| | .error k => .error k | |
| | .ok mem1 => deallocateFrameLocalsV2 mem1 rest | |
| /-- Finish a `CallVia.boxClone pointee` call that the callee has returned | |
| from with `retVal`: write `retVal` into the box that `evalCallViaV2` holds in | |
| the caller's `dst` (`ptr::write(dst, src.clone())` in `CopySpec::clone_one`), | |
| leaving `dst` unchanged, and continue the caller at `t`. `retVal` must be a | |
| valid `pointee`, and nothing is written for a zero-sized `pointee`. -/ | |
| noncomputable def storeBoxCloneResultV2 (callerBb : BasicBlock) | |
| (caller : FrameState) (rest : List FrameState) (mem : MemoryState) | |
| (callerMem : CallerMemory) (dst : Place) (t : BasicBlockId) | |
| (pointee : MirTy) (retVal : Val) : StepResult State TerminalOut := | |
| if !Nat.beq caller.stmtIdx callerBb.statements.length || | |
| !dst.projection.isEmpty || !checkValV2 retVal pointee then | |
| .fault .unsupported | |
| else | |
| let boxRes : Except FaultKind (Option Val) := | |
| match getElem? caller.locals dst.localId with | |
| | some (.immediate v) => .ok v | |
| | some (.indirect mplace) => loadIndirectV2 mem (.box pointee) mplace | |
| | _ => .error .unsupported | |
| match boxRes, layoutOfTyV2 pointee with | |
| | .error k, _ => .fault k | |
| | .ok (some (.boxPtr p none)), some lay => | |
| let memRes : Except FaultKind MemoryState := | |
| if Nat.beq lay.size 0 then | |
| .ok mem | |
| else | |
| match p.allocId, | |
| encodeValV2 profileV2TargetEndian pointee retVal with | |
| | none, _ => .error .undefined | |
| | _, .error k => .error k | |
| | some aid, .ok bytes => | |
| writeBytes mem ⟨aid, p.offsetBytes.toNat⟩ lay.alignLog2 bytes | |
| match memRes with | |
| | .error k => .fault k | |
| | .ok mem2 => | |
| .step { | |
| frames := { caller with blockIdx := t, stmtIdx := 0 } :: rest | |
| callerMem | |
| mem := mem2 | |
| } | |
| | .ok _, _ => .fault .unsupported | |
| /-- Return from callee frame `frame` to `caller` in Profile v2, matching | |
| `return_from_current_stack_frame` in | |
| `compiler/rustc_const_eval/src/interpret/call.rs` and `cleanup_stack_frame` | |
| in `compiler/rustc_const_eval/src/interpret/stack.rs` (`rust-lang/rust` | |
| `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`): | |
| > "// Remove the frame from the stack. | |
| > let frame = self.pop_stack_frame_raw()?; | |
| > // Copy the return value and remember the return continuation. | |
| > if !unwinding { | |
| > self.copy_op_allow_transmute(&return_op, frame.return_place())?;" | |
| > (`call.rs`) | |
| > | |
| > "// Cleanup: deallocate locals. | |
| > ... | |
| > for local in &frame.locals { | |
| > self.deallocate_local(local.value)?; | |
| > }" | |
| > (`stack.rs`) | |
| The callee's `_0` must be initialized. The callee's stack allocations are | |
| deallocated, after which every reference in the returned value must still be | |
| valid with non-overlapping mutable references (so a reference into the | |
| popped frame faults with `.undefined`). The value is written to the return | |
| place `frame.retDst?` that `evalCallV2` recorded, and the caller continues at | |
| `frame.retTarget?`. The caller frame is still at its call terminator, which | |
| decides how the value is stored: a `.callNe` negates it, a | |
| `.callVia (.refPartialEq negate)` negates it when `negate` is set, a | |
| `.callVia (.partialOrd greater orEqual)` maps the `Option<Ordering>` to a | |
| `bool` (`partialOrdResultV2`), and a `.callVia (.boxClone _)` writes it into | |
| the heap buffer of the pending box held in the return place | |
| (`storeBoxCloneResultV2`). -/ | |
| noncomputable def evalReturnToCallerV2 (p : Program) (body : Body) | |
| (bb : BasicBlock) (frame caller : FrameState) (rest : List FrameState) | |
| (mem : MemoryState) (callerMem : CallerMemory) : | |
| StepResult State TerminalOut := | |
| if bb.cleanup then | |
| .fault .unsupported | |
| else | |
| match getElem? body.locals 0 with | |
| | none => .fault .unsupported | |
| | some retTy => | |
| let retRes : Except FaultKind Val := | |
| match getElem? frame.locals 0 with | |
| | some (.immediate (some v)) => .ok v | |
| | some (.immediate none) | some .dead | some (.partialTuple _) => | |
| .error .undefined | |
| | some (.indirect mplace) => | |
| match loadIndirectV2 mem retTy mplace with | |
| | .ok (some v) => .ok v | |
| | .ok none => .error .undefined | |
| | .error k => .error k | |
| | none => .error .unsupported | |
| match retRes with | |
| | .error k => .fault k | |
| | .ok retVal => | |
| match deallocateFrameLocalsV2 mem frame.locals with | |
| | .error k => .fault k | |
| | .ok mem1 => | |
| if !refsValidInMem mem1 retTy retVal || | |
| !spansPairwiseDisjoint (valueAccessSpans mem1 retTy retVal) then | |
| .fault .undefined | |
| else | |
| match frame.retDst?, frame.retTarget? with | |
| | some dst, some t => | |
| match activeFrameBody p caller with | |
| | none => .fault .unsupported | |
| | some callerBody => | |
| match getElem? callerBody.basicBlocks caller.blockIdx with | |
| | none => .fault .unsupported | |
| | some callerBb => | |
| match callerBb.terminator with | |
| | .callVia (.boxClone pt) _ _ _ _ _ => | |
| storeBoxCloneResultV2 callerBb caller rest mem1 callerMem | |
| dst t pt retVal | |
| | _ => | |
| let resRes : Except FaultKind Val := | |
| match callerBb.terminator, retVal with | |
| | .call _ _ _ _ _, _ => .ok retVal | |
| | .callNe _ _ _ _ _, .bool b => .ok (.bool !b) | |
| | .callVia (.refPartialEq negate) _ _ _ _ _, .bool b => | |
| .ok (.bool (if negate then !b else b)) | |
| | .callVia (.partialOrd greater orEqual) _ _ _ _ _, v => | |
| partialOrdResultV2 greater orEqual v | |
| | _, _ => .error .unsupported | |
| match resRes, getElem? callerBody.locals dst.localId with | |
| | .error k, _ => .fault k | |
| | .ok _, none => .fault .unsupported | |
| | .ok resVal, some dstTy => | |
| if !Nat.beq caller.stmtIdx callerBb.statements.length || | |
| !dst.projection.isEmpty then | |
| .fault .unsupported | |
| else | |
| match writePlaceV2 callerBody.locals caller.locals mem1 | |
| dst dstTy resVal with | |
| | .error k => .fault k | |
| | .ok (locals2, mem2) => | |
| .step { | |
| frames := { | |
| caller with | |
| blockIdx := t | |
| stmtIdx := 0 | |
| locals := locals2 | |
| } :: rest | |
| callerMem | |
| mem := mem2 | |
| } | |
| | _, _ => .fault .unsupported | |
| /-- Single small-step transition in Profile v2. | |
| The active frame is the head of `s.frames`, and its body is | |
| `activeFrameBody` (Profile v2 never creates `sysrootOp?` frames). A `.call` or | |
| `.callNe` terminator pushes a callee frame (`evalCallV2`), as does a | |
| `.callVia` terminator (`evalCallViaV2`). A `.return_` | |
| terminator in the outermost frame finishes the execution (`evalTerminatorV2`), | |
| while in a callee frame it pops the frame and resumes the caller | |
| (`evalReturnToCallerV2`). Every other statement and terminator steps the | |
| active frame alone, with the caller frames unchanged (`attachCallers`). -/ | |
| noncomputable def evalStepV2 (p : Program) (s : State) : | |
| StepResult State TerminalOut := | |
| match s.frames with | |
| | frame :: callers => | |
| match activeFrameBody p frame with | |
| | none => .fault .unsupported | |
| | some body => | |
| match getElem? body.basicBlocks frame.blockIdx with | |
| | none => .fault .unsupported | |
| | some bb => | |
| match getElem? bb.statements frame.stmtIdx with | |
| | some stmt => | |
| attachCallers callers | |
| (evalStatementV2 body frame s.mem s.callerMem stmt) | |
| | none => | |
| if Nat.beq frame.stmtIdx bb.statements.length then | |
| match bb.terminator with | |
| | .call callee args dst target unwind => | |
| evalCallV2 p body frame callers s.mem s.callerMem callee args | |
| dst target unwind | |
| | .callNe eqCallee args dst target unwind => | |
| evalCallV2 p body frame callers s.mem s.callerMem eqCallee args | |
| dst target unwind | |
| | .callVia via callee args dst target unwind => | |
| evalCallViaV2 p body frame callers s.mem s.callerMem via callee | |
| args dst target unwind | |
| | .return_ => | |
| match callers with | |
| | [] => | |
| evalTerminatorV2 body bb frame s.mem s.callerMem | |
| p.panicStrategy p.hasLocalPanicHandler p.overflowChecks | |
| | caller :: rest => | |
| evalReturnToCallerV2 p body bb frame caller rest s.mem | |
| s.callerMem | |
| | _ => | |
| attachCallers callers | |
| (evalTerminatorV2 body bb frame s.mem s.callerMem | |
| p.panicStrategy p.hasLocalPanicHandler p.overflowChecks) | |
| else | |
| .fault .unsupported | |
| | [] => .fault .unsupported | |
| /-- Choice-indexed wrapper for Profile v2 deterministic small-step | |
| evaluation. -/ | |
| noncomputable def evalStepV2Choice (p : Program) (_c : Choice) (s : State) : | |
| StepResult State TerminalOut := | |
| evalStepV2 p s | |
| /-- Evaluate a single call argument against its declared callee parameter type | |
| `paramTy`, returning the passed value and updated `(locals, mem)`. Matches | |
| `evalFnCallArgumentAt` (`deinitMovedPlace = true`) and `passArgument` | |
| (`copyRuntimePlace`'s validity check) in `Miri.Interpreter.Call`, which model | |
| `eval_fn_call_argument` in `compiler/rustc_const_eval/src/interpret/step.rs` | |
| and `pass_argument` in `compiler/rustc_const_eval/src/interpret/call.rs` | |
| (`rust-lang/rust` `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`): | |
| > /// Evaluate the arguments of a function call | |
| > ... | |
| > mir::Operand::Move(place) => { | |
| > let place = self.eval_place(*place)?; | |
| > if move_definitely_disjoint { | |
| > /// Initialize a single callee argument, checking the types for compatibility. | |
| `rustc` passes a moved argument in place (`FnArg::InPlace`) when it already | |
| lives in memory. Profile version 1 has no in-memory argument passing, so an | |
| `.indirect` moved slot (or an `.indirect` copied slot when the call also moves | |
| an argument) fails closed with `.unsupported`. -/ | |
| noncomputable def evalCallArg (callerLocalsTys : List MirTy) | |
| (locals : List LocalSlot) (mem : MemoryState) (hasMove : Bool) | |
| (opnd : Operand) (paramTy : MirTy) : | |
| Except FaultKind (Val × List LocalSlot × MemoryState) := | |
| let indirectBlocked : Bool := | |
| match opnd with | |
| | .copy place => | |
| hasMove && | |
| match getElem? locals place.localId with | |
| | some (.indirect _) => true | |
| | _ => false | |
| | .move place => | |
| match getElem? locals place.localId with | |
| | some (.indirect _) => true | |
| | _ => false | |
| | _ => false | |
| if indirectBlocked then | |
| .error .unsupported | |
| else | |
| match evalOperandToSlot callerLocalsTys locals mem | |
| (fun srcTy => MirTy.beq srcTy paramTy) opnd with | |
| | .error k => .error k | |
| | .ok (srcTy, optVal, locals', mem') => | |
| if !MirTy.beq srcTy paramTy then | |
| .error .unsupported | |
| else | |
| match optVal with | |
| | some v => .ok (v, locals', mem') | |
| | none => .error .undefined | |
| /-- Evaluate a call's argument operands left-to-right against `paramTys`, | |
| accumulating argument values and threading moved-place deinitialization through | |
| the caller's `locals` and `mem`. -/ | |
| noncomputable def evalCallArgs (callerLocalsTys : List MirTy) | |
| (locals : List LocalSlot) (mem : MemoryState) (hasMove : Bool) : | |
| List Operand → List MirTy → | |
| Except FaultKind (List Val × List LocalSlot × MemoryState) | |
| | [], [] => .ok ([], locals, mem) | |
| | opnd :: restArgs, paramTy :: restParams => | |
| match evalCallArg callerLocalsTys locals mem hasMove opnd paramTy with | |
| | .error k => .error k | |
| | .ok (v, locals₁, mem₁) => | |
| match evalCallArgs callerLocalsTys locals₁ mem₁ hasMove restArgs | |
| restParams with | |
| | .error k => .error k | |
| | .ok (vs, locals₂, mem₂) => .ok (v :: vs, locals₂, mem₂) | |
| | _, _ => .error .unsupported | |
| /-- Execute a direct `.call` or `.sysrootCall` terminator: validate call-site | |
| preconditions (`callTargetAdmitted` and static callee validity), evaluate | |
| arguments left-to-right (deinitializing moved non-ZST caller slots), check that | |
| the caller's destination slot is live (`.dead` -> `.undefined`), initialize the | |
| callee's frame (`initLocalsLoop`), and push it onto `callers`. This follows | |
| `eval_callee_and_args` (`compiler/rustc_const_eval/src/interpret/step.rs`) | |
| and `init_stack_frame` (`compiler/rustc_const_eval/src/interpret/call.rs`) in | |
| `rust-lang/rust` `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`: | |
| > // The first order of business is to figure out the callee signature. | |
| The callee frame records the return place `dst` and continuation `target` | |
| (`retDst?`/`retTarget?`), which `evalNonRootReturn` consumes. -/ | |
| noncomputable def evalCallTerminator (callerBody : Body) (bb : BasicBlock) | |
| (caller : FrameState) (callers : List FrameState) (mem : MemoryState) | |
| (callerMem : CallerMemory) (calleeDefId : DefId) | |
| (sysrootOp? : Option SysrootNumOp) (calleeBody : Body) | |
| (args : List Operand) (dst : Place) (target : Option BasicBlockId) | |
| (unwind : UnwindAction) : StepResult State TerminalOut := | |
| if !callTargetAdmitted callerBody bb calleeBody args dst target unwind || | |
| calleeBody.isExternal || | |
| calleeBody.basicBlocks.isEmpty || | |
| !storageAnnotationsInBounds calleeBody || | |
| !discriminantTypesValid calleeBody || | |
| !castTypesValid calleeBody || | |
| !assignTypesValid calleeBody || | |
| !calleeBody.locals.all isSupportedScalarOrUnitTy then | |
| .fault .unsupported | |
| else | |
| let hasMove : Bool := | |
| args.any (fun a => match a with | .move _ => true | _ => false) | |
| let paramTys := (calleeBody.locals.drop 1).take calleeBody.argumentCount | |
| match evalCallArgs callerBody.locals caller.locals mem hasMove args | |
| paramTys with | |
| | .error k => .fault k | |
| | .ok (argVals, callerLocals', mem') => | |
| match getElem? callerLocals' dst.localId with | |
| | none => .fault .unsupported | |
| | some .dead => .fault .undefined | |
| | some (.indirect _) => .fault .unsupported | |
| -- Profile v1 never creates partially moved tuples. | |
| | some (.partialTuple _) => .fault .unsupported | |
| | some (.immediate _) => | |
| let calleeLocals := | |
| initLocalsLoop calleeBody argVals 0 calleeBody.locals | |
| let calleeFrame : FrameState := { | |
| defId := calleeDefId | |
| blockIdx := 0 | |
| stmtIdx := 0 | |
| locals := calleeLocals | |
| sysrootOp? := sysrootOp? | |
| retDst? := some dst | |
| retTarget? := target | |
| } | |
| let caller' : FrameState := { caller with locals := callerLocals' } | |
| .step { | |
| frames := calleeFrame :: caller' :: callers | |
| callerMem := callerMem | |
| mem := mem' | |
| } | |
| /-- Whether any slot in `locals` is an `.indirect` stack allocation. -/ | |
| noncomputable def localsHaveIndirect (locals : List LocalSlot) : Bool := | |
| locals.any (fun slot => match slot with | .indirect _ => true | _ => false) | |
| /-- Execute a non-root `TerminatorKind.return_`: read callee `_0` (`.dead` or | |
| uninitialized -> `.undefined`), write it into `caller`'s return destination | |
| `dst`, pop the callee frame, and transfer control in `caller` to | |
| `blockIdx := tgt, stmtIdx := 0` (or fault with `.undefined` when | |
| `retTarget? = none`, matching | |
| `Miri.Interpreter.ControlFlow.returnToBlock none`). This follows | |
| `return_from_current_stack_frame` and `return_to_block` in | |
| `compiler/rustc_const_eval/src/interpret/{call,eval_context}.rs` | |
| (`rust-lang/rust` `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`): | |
| > // Remove the frame from the stack. | |
| > let frame = self.pop_stack_frame_raw()?; | |
| > // Copy the return value and remember the return continuation. | |
| > if !unwinding { | |
| > self.copy_op_allow_transmute(&return_op, frame.return_place())?; | |
| > if let Some(target) = target { | |
| > self.go_to_block(target); | |
| > interp_ok(()) | |
| > } else { | |
| > throw_ub!(Unreachable) | |
| > } | |
| Popping a frame also deallocates its in-memory locals (`cleanup_stack_frame` | |
| in `compiler/rustc_const_eval/src/interpret/stack.rs`): | |
| > // Cleanup: deallocate locals. | |
| > ... | |
| > if cleanup { | |
| > for local in &frame.locals { | |
| > self.deallocate_local(local.value)?; | |
| > } | |
| $M_{\text{anneal}}$ does not model that deallocation, so a callee frame with | |
| any `.indirect` local (`localsHaveIndirect`) fails closed with `.unsupported` | |
| instead of leaking a live stack allocation. Profile version 1 never creates | |
| such a callee local. -/ | |
| noncomputable def evalNonRootReturn (p : Program) (calleeBody : Body) | |
| (bb : BasicBlock) (callee : FrameState) (caller : FrameState) | |
| (restCallers : List FrameState) (mem : MemoryState) | |
| (callerMem : CallerMemory) : StepResult State TerminalOut := | |
| if bb.cleanup || localsHaveIndirect callee.locals then | |
| .fault .unsupported | |
| else | |
| let retRead : Except FaultKind Val := | |
| match getElem? callee.locals 0 with | |
| | some (.immediate (some retVal)) => .ok retVal | |
| | some (.immediate none) | some .dead => .error .undefined | |
| -- Profile v1 never creates partially moved tuples. | |
| | some (.partialTuple _) => .error .unsupported | |
| | some (.indirect mplace) => | |
| match getElem? calleeBody.locals 0 with | |
| | none => .error .unsupported | |
| | some retTy => | |
| match loadIndirect mem retTy mplace with | |
| | .ok (some retVal) => .ok retVal | |
| | .ok none => .error .undefined | |
| | .error k => .error k | |
| | none => .error .unsupported | |
| match retRead with | |
| | .error k => .fault k | |
| | .ok retVal => | |
| match callee.retDst? with | |
| | none => .fault .unsupported | |
| | some dst => | |
| if !dst.projection.isEmpty then | |
| .fault .unsupported | |
| else | |
| match activeFrameBody p caller with | |
| | none => .fault .unsupported | |
| | some callerBody => | |
| match getElem? callerBody.locals dst.localId with | |
| | none => .fault .unsupported | |
| | some dstTy => | |
| match writePlace caller.locals mem dst.localId dstTy retVal with | |
| | .error k => .fault k | |
| | .ok (callerLocals', mem') => | |
| match callee.retTarget? with | |
| | none => .fault .undefined | |
| | some tgt => | |
| .step { | |
| frames := { | |
| caller with | |
| blockIdx := tgt | |
| stmtIdx := 0 | |
| locals := callerLocals' | |
| } :: restCallers | |
| callerMem := callerMem | |
| mem := mem' | |
| } | |
| /-- Total single-step evaluator of $M_{\text{anneal}}$ over running `State`s, | |
| matching `InterpCx::step` in `compiler/rustc_const_eval/src/interpret/step.rs` | |
| (`rust-lang/rust` `8144389c895da997dbdecaa635e41d6a50be6ffd`): | |
| > "pub fn step(&mut self) -> InterpResult<'tcx, bool> { | |
| > if self.stack().is_empty() { | |
| > return interp_ok(false); | |
| > } | |
| > ... | |
| > let basic_block = &self.body().basic_blocks[loc.block]; | |
| > if let Some(stmt) = basic_block.statements.get(loc.statement_index) { | |
| > ... | |
| > self.eval_statement(stmt)?; | |
| > ... | |
| > self.frame_mut().loc.as_mut().left().unwrap().statement_index += 1; | |
| > return interp_ok(true); | |
| > } | |
| > ... | |
| > let terminator = basic_block.terminator(); | |
| > self.eval_terminator(terminator)?; | |
| > ... | |
| > interp_ok(true) | |
| > }" | |
| Out-of-bounds `frame.blockIdx` faults with `.fault .unsupported` (matching | |
| `Miri.Interpreter.Step.step` `StepError.invalidBlock`). -/ | |
| noncomputable def evalStep (p : Program) (_c : Choice) (s : State) : | |
| StepResult State TerminalOut := | |
| match s.frames with | |
| | frame :: callers => | |
| match activeFrameBody p frame with | |
| | none => .fault .unsupported | |
| | some body => | |
| match getElem? body.basicBlocks frame.blockIdx with | |
| | none => .fault .unsupported | |
| | some bb => | |
| match getElem? bb.statements frame.stmtIdx with | |
| | some stmt => | |
| attachCallers callers | |
| (evalStatement body frame s.mem s.callerMem stmt) | |
| | none => | |
| if Nat.beq frame.stmtIdx bb.statements.length then | |
| match bb.terminator with | |
| | .call callee args dst target unwind => | |
| match getElem? p.bodies callee with | |
| | none => .fault .unsupported | |
| | some calleeBody => | |
| evalCallTerminator body bb frame callers s.mem s.callerMem | |
| callee none calleeBody args dst target unwind | |
| | .sysrootCall op args dst target unwind => | |
| evalCallTerminator body bb frame callers s.mem s.callerMem | |
| 0 (some op) (sysrootNumBody op) args dst target unwind | |
| | .return_ => | |
| match callers with | |
| | [] => | |
| evalTerminator body bb frame s.mem s.callerMem p.panicStrategy | |
| p.hasLocalPanicHandler | |
| | caller :: rest => | |
| evalNonRootReturn p body bb frame caller rest s.mem s.callerMem | |
| | _ => | |
| attachCallers callers | |
| (evalTerminator body bb frame s.mem s.callerMem p.panicStrategy | |
| p.hasLocalPanicHandler) | |
| else | |
| .fault .unsupported | |
| | [] => .fault .unsupported | |
| /-- Move the immediate local `localId` of the single active frame into a fresh | |
| stack allocation, returning the new state and the local's memory place. | |
| Matches `force_allocation` in | |
| `compiler/rustc_const_eval/src/interpret/place.rs` (`rust-lang/rust` | |
| `8144389c895da997dbdecaa635e41d6a50be6ffd`) and | |
| `Miri.Interpreter.forceAllocation` | |
| (`vendor/lean-miri/Miri/Interpreter/Place.lean`): | |
| > "let whole_local = match self.frame_mut().locals[local].access_mut()? { | |
| > &mut Operand::Immediate(local_val) => { | |
| > // We need to make an allocation. | |
| > ... | |
| > let local_layout = self.layout_of_local(&self.frame(), local, None)?; | |
| > assert!(local_layout.is_sized(), \"unsized locals cannot be | |
| > immediate\"); | |
| > let mplace = self.allocate(local_layout, MemoryKind::Stack)?; | |
| > // Preserve old value. (As an optimization, we can skip this if it | |
| > // was uninit.) | |
| > if !matches!(local_val, Immediate::Uninit) { | |
| > // We don't have to validate as we can assume the local was | |
| > // already valid for its type. ... | |
| > self.write_immediate_to_mplace_no_validate( | |
| > local_val, | |
| > local_layout, | |
| > mplace.mplace, | |
| > )?; | |
| > } | |
| > M::after_local_moved_to_memory(self, local, &mplace)?; | |
| > ... | |
| > *self.frame_mut().locals[local].access_mut().unwrap() = | |
| > Operand::Indirect(mplace.mplace); | |
| > mplace.mplace | |
| > } | |
| > &mut Operand::Indirect(mplace) => mplace, // this already was an indirect | |
| > // local | |
| > };" | |
| - A `.dead` local faults with `.undefined` (`access_mut` raises `DeadLocal`). | |
| - An `.indirect place` local is already in memory and is returned unchanged. | |
| - An `.immediate optVal` local of type `ty` gets a fresh stack allocation of | |
| layout `layoutOfTy ty` (`allocateStack`). An initialized value is stored | |
| without validation (`storeIndirect`); an uninitialized value leaves the | |
| allocation's bytes uninitialized. The slot becomes `.indirect place`. | |
| `rustc` forces an allocation when a place expression needs the local's | |
| address: a projection, a reference or raw pointer to the local, or an argument | |
| or return place passed in memory. Profile version 1 rejects all of these | |
| (`.unsupported`), so no profile-version-1 `evalStep` calls `forceAllocation`; | |
| `CanaryMemoryLifecycleAnnealClaim` applies it between steps to exercise | |
| `.indirect` locals. -/ | |
| noncomputable def forceAllocation (p : Program) (s : State) | |
| (localId : LocalId) : Except FaultKind (State × MemPlace) := | |
| match s.frames with | |
| | [frame] => | |
| match getElem? p.bodies frame.defId with | |
| | none => .error .unsupported | |
| | some body => | |
| match getElem? body.locals localId, getElem? frame.locals localId with | |
| | some _, some .dead => .error .undefined | |
| | some _, some (.indirect place) => .ok (s, place) | |
| | some ty, some (.immediate optVal) => | |
| match layoutOfTy ty with | |
| | none => .error .unsupported | |
| | some layout => | |
| let (mem₁, place) := allocateStack s.mem layout | |
| let stored : Except FaultKind MemoryState := | |
| match optVal with | |
| | none => .ok mem₁ | |
| | some v => storeIndirect mem₁ ty place v | |
| match stored with | |
| | .error k => .error k | |
| | .ok mem₂ => | |
| match setElem? frame.locals localId (.indirect place) with | |
| | none => .error .unsupported | |
| | some locals' => | |
| .ok ({ s with | |
| frames := [{ frame with locals := locals' }] | |
| mem := mem₂ }, place) | |
| | _, _ => .error .unsupported | |
| | _ => .error .unsupported | |
| end Trusted.MirSemantics | |
| end |