blob: 2268eeee5abf5dfd98609afe07a6e53a0199d703 [file]
-- Copyright 2026 The Fuchsia Authors
--
-- Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
-- <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
-- license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
-- This file may not be copied, modified, or distributed except according to
-- those terms.
-- anneal-trust-tier: candidate:refinement
module
prelude
public import Init.NotationExtra
public import Init.Data.List.Basic
public import Init.Data.Int.Basic
public import Init.Data.Nat.Div.Basic
public import Init.Data.Nat.Bitwise.Basic
public import Trusted.CppAst
public import Trusted.CppSemantics.State
public import Trusted.CppSemantics.Memory
@[expose] public section
namespace Trusted.CppSemantics
open Trusted.CppAst
/-!
# Rung-0 C11 Expression and Place Evaluation (`Trusted.CppSemantics.Eval`)
Tactic-free Ring-0 evaluator for side-effect-free SSENF `CppExpr` and
`CppPlace` trees enforcing C11 `isoUB`/`wrapv` integer rules, division/shift
UB, allocation-id and subobject-range pointer arithmetic and dereference
bounds, intrinsic alignment, and `.uninit` / `.ptrFrag` classification.
-/
/-- `2^k` helper. -/
noncomputable def pow2 (k : Nat) : Nat := Nat.pow 2 k
/-- Return `true` iff mathematical integer `x` lies in `[-2^(W-1), 2^(W-1)-1]`.
-/
noncomputable def signedInRange (w : CppIntWidth) (x : Int) : Bool :=
let half := pow2 (w.bitWidth - 1)
match x with
| Int.ofNat n => Nat.blt n half
| Int.negSucc n => Nat.blt n half
/-- Convert mathematical `Int` to canonical `W`-bit unsigned representation. -/
noncomputable def ofSignedIntWrap (w : CppIntWidth) (x : Int) : Nat :=
let m := pow2 w.bitWidth
match x with
| Int.ofNat n => Nat.mod n m
| Int.negSucc n =>
let r := Nat.mod (n + 1) m
if Nat.beq r 0 then 0 else m - r
/-- Sign flag on `Int` (`true` iff strictly negative). -/
noncomputable def intIsNeg : Int → Bool
| Int.ofNat _ => false
| Int.negSucc _ => true
/-- Absolute value of `Int`. -/
noncomputable def intAbs : Int → Nat
| Int.ofNat n => n
| Int.negSucc n => n + 1
/-- Construct an `Int` from sign flag and magnitude. -/
noncomputable def intFromSignMag (neg : Bool) (mag : Nat) : Int :=
if neg then
match mag with
| 0 => Int.ofNat 0
| k + 1 => Int.negSucc k
else Int.ofNat mag
/-- Boolean equality on `Int`. -/
noncomputable def intBeq : Int → Int → Bool
| Int.ofNat a, Int.ofNat b => Nat.beq a b
| Int.negSucc a, Int.negSucc b => Nat.beq a b
| _, _ => false
/-- Strict less-than on `Int`. -/
noncomputable def intBlt : Int → Int → Bool
| Int.ofNat a, Int.ofNat b => Nat.blt a b
| Int.negSucc _, Int.ofNat _ => true
| Int.ofNat _, Int.negSucc _ => false
| Int.negSucc a, Int.negSucc b => Nat.blt b a
/-- Check whether `x = INT_MIN` for signed width `w`. -/
noncomputable def isSignedMin (w : CppIntWidth) (x : Int) : Bool :=
match x with
| Int.negSucc n => Nat.beq (n + 1) (pow2 (w.bitWidth - 1))
| Int.ofNat _ => false
/-- Apply `isoUB` vs. `wrapv` signed overflow policy to result `r`. -/
noncomputable def finishSignedArith (policy : CppLangPolicy) (w : CppIntWidth)
(r : Int) : Except CppFaultKind CppVal :=
match policy.signedOverflow with
| .isoUB =>
if signedInRange w r then .ok (.int w .signed (ofSignedIntWrap w r))
else .error .undefined
| .wrapv => .ok (.int w .signed (ofSignedIntWrap w r))
/-- Evaluate a unary operator `op` on value `v`. -/
noncomputable def evalUnOp (policy : CppLangPolicy) (mem : CppMemory)
(op : CppUnOp) (v : CppVal) : Except CppFaultKind CppVal :=
match op, v with
| .neg, .int w .unsigned bits =>
let m := pow2 w.bitWidth
.ok (.int w .unsigned (if Nat.beq bits 0 then 0 else Nat.mod (m - bits) m))
| .neg, .int w .signed bits =>
finishSignedArith policy w (Int.neg (cppIntToMathInt w .signed bits))
| .bitNot, .int w s bits =>
let m := pow2 w.bitWidth
.ok (.int w s (Nat.mod (Nat.xor bits (m - 1)) m))
| .logNot, .bool b => .ok (.bool (!b))
| .logNot, .int _ _ bits => .ok (.bool (Nat.beq bits 0))
| .logNot, .ptr aid addr sr =>
match aid with
| none =>
if Nat.beq addr 0 && optRangeBeq sr none then .ok (.bool true)
else .error .unsupported
| some id => if ptrLive mem id then .ok (.bool false) else .error .undefined
| _, _ => .error .unsupported
/-- Evaluate an integer binary operator `op` on `(w, s, aBits, bBits)`. -/
noncomputable def evalIntBinOp (policy : CppLangPolicy) (op : CppBinOp)
(w : CppIntWidth) (s : Signedness) (aBits bBits : Nat) :
Except CppFaultKind CppVal :=
let bw := w.bitWidth
let m := pow2 bw
match s with
| .unsigned =>
match op with
| .add => .ok (.int w .unsigned (Nat.mod (aBits + bBits) m))
| .sub =>
.ok (.int w .unsigned (Nat.mod (aBits + m - Nat.mod bBits m) m))
| .mul => .ok (.int w .unsigned (Nat.mod (aBits * bBits) m))
| .div =>
if Nat.beq bBits 0 then .error .undefined
else .ok (.int w .unsigned (Nat.div aBits bBits))
| .rem =>
if Nat.beq bBits 0 then .error .undefined
else .ok (.int w .unsigned (Nat.mod aBits bBits))
| .shl =>
if Nat.ble bw bBits then .error .undefined
else .ok (.int w .unsigned (Nat.mod (Nat.shiftLeft aBits bBits) m))
| .shr =>
if Nat.ble bw bBits then .error .undefined
else .ok (.int w .unsigned (Nat.shiftRight aBits bBits))
| .bitAnd => .ok (.int w .unsigned (Nat.mod (Nat.land aBits bBits) m))
| .bitOr => .ok (.int w .unsigned (Nat.mod (Nat.lor aBits bBits) m))
| .bitXor => .ok (.int w .unsigned (Nat.mod (Nat.xor aBits bBits) m))
| .eq => .ok (.bool (Nat.beq aBits bBits))
| .ne => .ok (.bool (!Nat.beq aBits bBits))
| .lt => .ok (.bool (Nat.blt aBits bBits))
| .le => .ok (.bool (Nat.ble aBits bBits))
| .gt => .ok (.bool (Nat.blt bBits aBits))
| .ge => .ok (.bool (Nat.ble bBits aBits))
| .signed =>
let a := cppIntToMathInt w .signed aBits
let b := cppIntToMathInt w .signed bBits
match op with
| .add => finishSignedArith policy w (Int.add a b)
| .sub => finishSignedArith policy w (Int.sub a b)
| .mul => finishSignedArith policy w (Int.mul a b)
| .div =>
if intBeq b (Int.ofNat 0) || (isSignedMin w a && intBeq b (Int.negSucc 0))
then .error .undefined
else
let q := intFromSignMag (!(intIsNeg a == intIsNeg b))
(Nat.div (intAbs a) (intAbs b))
.ok (.int w .signed (ofSignedIntWrap w q))
| .rem =>
if intBeq b (Int.ofNat 0) || (isSignedMin w a && intBeq b (Int.negSucc 0))
then .error .undefined
else
let r := intFromSignMag (intIsNeg a) (Nat.mod (intAbs a) (intAbs b))
.ok (.int w .signed (ofSignedIntWrap w r))
| .shl =>
match b with
| Int.negSucc _ => .error .undefined
| Int.ofNat sh =>
if Nat.ble bw sh then .error .undefined
else
-- Shifting a negative value, or into or past the sign bit, is
-- undefined in C11 §6.5.7p4 (`-fwrapv` covers only additive and
-- multiplicative overflow) but defined in C++20 [expr.shift]p2.
match a with
| Int.negSucc _ => .error .unsupported
| Int.ofNat an =>
let shifted := Nat.shiftLeft an sh
if Nat.blt shifted (pow2 (bw - 1)) then
.ok (.int w .signed shifted)
else .error .unsupported
| .shr =>
match b with
| Int.negSucc _ => .error .undefined
| Int.ofNat sh =>
if Nat.ble bw sh then .error .undefined
else
-- Arithmetic right shift of negative signed values matches C++20
-- [expr.shift]p3 and Clang's implementation-defined C11 §6.5.7p5
-- choice.
match a with
| Int.ofNat an => .ok (.int w .signed (Nat.shiftRight an sh))
| Int.negSucc _ =>
let fill := m - pow2 (bw - sh)
.ok (.int w .signed
(Nat.mod (Nat.lor (Nat.shiftRight aBits sh) fill) m))
| .bitAnd => .ok (.int w .signed (Nat.mod (Nat.land aBits bBits) m))
| .bitOr => .ok (.int w .signed (Nat.mod (Nat.lor aBits bBits) m))
| .bitXor => .ok (.int w .signed (Nat.mod (Nat.xor aBits bBits) m))
| .eq => .ok (.bool (intBeq a b))
| .ne => .ok (.bool (!intBeq a b))
| .lt => .ok (.bool (intBlt a b))
| .le => .ok (.bool (intBlt a b || intBeq a b))
| .gt => .ok (.bool (intBlt b a))
| .ge => .ok (.bool (intBlt b a || intBeq b a))
/-- `true` iff `addr` is one past the end of allocation `aid`. -/
noncomputable def ptrAtEnd (mem : CppMemory) (aid addr : Nat) : Bool :=
match findAlloc? aid mem.allocs with
| some a => Nat.beq addr (a.baseAddr + a.sizeBytes)
| none => false
/-- `true` iff `addr` is one past the end of subobject range `sr`. -/
noncomputable def atRangeEnd (sr : Option (Nat × Nat)) (addr : Nat) : Bool :=
match sr with
| some (lo, sz) => Nat.beq addr (lo + sz)
| none => false
/-- Pointer equality under C11 §6.5.9p6 and C++20 [expr.eq]p3. Comparing a
pointer to a dead or missing allocation is `.undefined` (its value is
indeterminate). A one-past-the-end pointer may equal the start of an adjacent
object, which C makes `true` and C++ leaves unspecified, so equal addresses
in distinct allocations or subobjects with one at its end are `.unsupported`;
so is comparing a provenance-carrying pointer with a non-null integer-derived
one. -/
noncomputable def ptrEqResult (mem : CppMemory) (aid1 : Option Nat)
(addr1 : Nat) (sr1 : Option (Nat × Nat)) (aid2 : Option Nat) (addr2 : Nat)
(sr2 : Option (Nat × Nat)) : Except CppFaultKind Bool :=
match aid1, aid2 with
| none, none =>
if Nat.beq addr1 0 && optRangeBeq sr1 none &&
Nat.beq addr2 0 && optRangeBeq sr2 none then .ok true
else .error .unsupported
| some id1, some id2 =>
if !ptrLive mem id1 || !ptrLive mem id2 then .error .undefined
else if Nat.beq id1 id2 then
if !Nat.beq addr1 addr2 then .ok false
else if !optRangeBeq sr1 sr2 &&
(atRangeEnd sr1 addr1 || atRangeEnd sr2 addr2) then
.error .unsupported
else .ok true
else if ptrAtEnd mem id1 addr1 || ptrAtEnd mem id2 addr2 then
.error .unsupported
else .ok false
| some id1, none =>
if !ptrLive mem id1 then .error .undefined
else if Nat.beq addr2 0 && optRangeBeq sr2 none then .ok false
else .error .unsupported
| none, some id2 =>
if !ptrLive mem id2 then .error .undefined
else if Nat.beq addr1 0 && optRangeBeq sr1 none then .ok false
else .error .unsupported
/-- Evaluate pointer comparison operators under C11 §6.5.8 / §6.5.9.
Relational comparison of pointers into distinct live objects or subobjects, of
a live pointer with `NULL`, or of two provenance-free pointers is undefined in
C11 §6.5.8p5 but unspecified or defined in C++20 [expr.rel]p4, so all step to
`.unsupported`; dangling pointers step to `.undefined`. -/
noncomputable def evalPtrBinOp (mem : CppMemory) (op : CppBinOp)
(aid1 : Option Nat) (addr1 : Nat) (sr1 : Option (Nat × Nat))
(aid2 : Option Nat) (addr2 : Nat) (sr2 : Option (Nat × Nat)) :
Except CppFaultKind CppVal :=
match op with
| .eq =>
match ptrEqResult mem aid1 addr1 sr1 aid2 addr2 sr2 with
| .ok b => .ok (.bool b)
| .error k => .error k
| .ne =>
match ptrEqResult mem aid1 addr1 sr1 aid2 addr2 sr2 with
| .ok b => .ok (.bool (!b))
| .error k => .error k
| .lt | .le | .gt | .ge =>
match aid1, aid2 with
| some id1, some id2 =>
if !ptrLive mem id1 || !ptrLive mem id2 then .error .undefined
else if !Nat.beq id1 id2 || !optRangeBeq sr1 sr2 then .error .unsupported
else
match op with
| .lt => .ok (.bool (Nat.blt addr1 addr2))
| .le => .ok (.bool (Nat.ble addr1 addr2))
| .gt => .ok (.bool (Nat.blt addr2 addr1))
| .ge => .ok (.bool (Nat.ble addr2 addr1))
| _ => .error .unsupported
| some id1, none =>
if !ptrLive mem id1 then .error .undefined
else .error .unsupported
| none, some id2 =>
if !ptrLive mem id2 then .error .undefined
else .error .unsupported
| none, none => .error .unsupported
| _ => .error .unsupported
/-- Evaluate a binary operator `op` on `(lv, rv)`. -/
noncomputable def evalBinOp (policy : CppLangPolicy) (mem : CppMemory)
(op : CppBinOp) (lv rv : CppVal) : Except CppFaultKind CppVal :=
match lv, rv with
| .int w1 s1 a, .int w2 s2 b =>
if CppIntWidth.beq w1 w2 && Signedness.beq s1 s2 then
evalIntBinOp policy op w1 s1 a b
else
match op with
| .shl | .shr =>
match cppIntToMathInt w2 s2 b with
| Int.negSucc _ => .error .undefined
| Int.ofNat rn =>
if Nat.ble w1.bitWidth rn then .error .undefined
else evalIntBinOp policy op w1 s1 a rn
| _ => .error .unsupported
| .ptr aid1 addr1 sr1, .ptr aid2 addr2 sr2 =>
evalPtrBinOp mem op aid1 addr1 sr1 aid2 addr2 sr2
| .bool a, .bool b =>
match op with
| .eq => .ok (.bool (a == b))
| .ne => .ok (.bool (a != b))
| _ => .error .unsupported
| _, _ => .error .unsupported
/-- Mark allocation `aid` read-only. -/
noncomputable def setAllocConst (mem : CppMemory) (aid : Nat) :
Except CppFaultKind CppMemory :=
match findAlloc? aid mem.allocs with
| none => .error .undefined
| some a =>
match replaceAlloc? aid { a with isConst := true } mem.allocs with
| some allocs' => .ok { mem with allocs := allocs' }
| none => .error .undefined
/-- Force local `lid` into stack memory, returning `(allocId, frame', mem')`.
-/
noncomputable def forceLocalToMemory (prog : CppProgram) (body : CppBody)
(frame : CppFrame) (mem : CppMemory) (lid : LocalId) :
Except CppFaultKind (Nat × CppFrame × CppMemory) :=
match cppGetElem? body.locals lid, cppGetElem? frame.locals lid with
| some decl, some slot =>
match slot with
| .dead => .error .undefined
| .stackAddr aid => .ok (aid, frame, mem)
| .uninit | .val _ =>
match cppTySize? prog.policy prog.records decl.ty,
cppTyAlign? prog.policy prog.records decl.ty with
| some sz, some al =>
let (aid, mem1) := allocStack mem sz al false
let memRes : Except CppFaultKind CppMemory :=
if !Nat.blt mem1.nextAddr (ptrAddrBound prog.policy) then
.error .unsupported
else
match slot with
| .val v =>
match findAlloc? aid mem1.allocs with
| some alloc =>
-- A `const` local becomes read-only storage once its value is
-- written.
match writeMemory prog.policy prog.records mem1 (some aid)
alloc.baseAddr none decl.ty v none with
| .ok mem2 =>
if decl.isConst then setAllocConst mem2 aid else .ok mem2
| .error k => .error k
| none => .error .undefined
-- Taking the address of (or memberwise-initializing) an uninitialized
-- `const` local lacks a post-initializer freeze boundary in `CppStmt`
-- and fails closed with `.unsupported` rather than freezing early.
| _ => if decl.isConst then .error .unsupported else .ok mem1
match memRes, cppSetElem? frame.locals lid (.stackAddr aid) with
| .ok mem2, some locs' =>
.ok (aid, { frame with locals := locs',
stackAllocs := aid :: frame.stackAllocs },
mem2)
| .error k, _ => .error k
| _, none => .error .unsupported
| _, _ => .error .unsupported
| _, _ => .error .unsupported
/-- Read a scalar or immediate local `lid` from `frame`/`mem`. An immediate
value must have a padding-free type; reading an uninitialized character or
aggregate local is `.unsupported` (C11 §6.3.2.1p2 vs. C++20 [basic.indet]p2),
reading an uninitialized non-character scalar or dangling scalar pointer is
`.undefined`, and an immediate aggregate with a dangling member pointer is
`.unsupported` (C11 §6.2.6.1p6 vs. C++20 [class.copy.ctor]p14). -/
noncomputable def readLocalScalar (prog : CppProgram) (body : CppBody)
(frame : CppFrame) (mem : CppMemory) (lid : LocalId) :
Except CppFaultKind CppVal :=
match cppGetElem? body.locals lid, cppGetElem? frame.locals lid with
| some decl, some slot =>
match slot with
| .dead =>
if !tyHasNoPadding prog.policy prog.records true 16 decl.ty then
.error .unsupported
else .error .undefined
| .uninit =>
if !tyHasNoPadding prog.policy prog.records true 16 decl.ty then
.error .unsupported
else
match decl.ty with
| .int _ _ isCharLike =>
if isCharLike then .error .unsupported else .error .undefined
| .bool | .ptr _ _ _ _ => .error .undefined
| .array _ _ | .record _ | .void => .error .unsupported
| .val v =>
if !tyHasNoPadding prog.policy prog.records true 16 decl.ty then
.error .unsupported
else if valLiveInMem prog.policy prog.records mem v decl.ty then .ok v
else
match decl.ty with
| .ptr _ _ _ _ => .error .undefined
| _ => .error .unsupported
| .stackAddr aid =>
match findAlloc? aid mem.allocs with
| some alloc =>
readMemory prog.policy prog.records mem (some aid) alloc.baseAddr none
decl.ty none
| none => .error .undefined
| _, _ => .error .unsupported
/-- Resolved memory address `(allocId, addr, ty)`. `alignCap` is the smallest
`alignBytes` of the records whose members were projected to reach the address,
so a member of a packed record is accessed at the record's alignment (as
through the record lvalue) rather than its type's. `subRange` is the subobject
(member or array) the address lies in, if narrower than the whole allocation; a
pointer formed from the address keeps it. `enclosingRecords` records enclosing
structs projected since the base or last `.deref` (`.addrOf` rejects subobject
pointers into padded records; caller-supplied pointers are governed by
`DisclosedGap.callerRawPtrAliasing "cpp_rung0_c11"`). -/
structure ResolvedAddr where
allocId : Option Nat
addr : Nat
ty : CppTy
alignCap : Option Nat := none
subRange : Option (Nat × Nat) := none
enclosingRecords : List (Option Nat × Nat × String) := []
/-- Lower an alignment cap to at most `a`. -/
noncomputable def alignCapMin (cap : Option Nat) (a : Nat) : Nat :=
match cap with
| some c => if Nat.blt c a then c else a
| none => a
/-- Check `*p` for `p = (aid, addr, sr)` of pointee type `pointee`, returning
the pointee's size. The pointee must lie entirely inside a live allocation
and inside `sr`, suitably aligned against the allocation's intrinsic alignment
(C11 §6.5.3.2p4, C++20 [basic.life]p6), so a null, dangling, misaligned, or
one-past-the-end `p` is `.undefined`. When `terminalAddrOf`, the dereference is
the operand of `&` (`&*p`, `&p[i]`), which C11 §6.5.3.2p3 evaluates without
accessing `*p` but C++ does not, so a failure on a live or null `p` is
`.unsupported` instead. -/
noncomputable def derefCheck (prog : CppProgram) (mem : CppMemory)
(terminalAddrOf : Bool) (aid : Option Nat) (addr : Nat)
(sr : Option (Nat × Nat)) (pointee : CppTy) : Except CppFaultKind Nat :=
match cppTySize? prog.policy prog.records pointee,
cppTyAlign? prog.policy prog.records pointee with
| some sz, some al =>
if placeInBounds mem aid addr sz && subRangeContains sr addr sz &&
ptrTargetAligned mem aid addr al then .ok sz
else if terminalAddrOf then
match aid with
| some id => if ptrLive mem id then .error .unsupported
else .error .undefined
| none => .error .unsupported
else .error .undefined
| _, _ => .error .unsupported
/-- The subobject range of the object `*p` designates: unchanged for the
operand of `&`, the pointee itself when `p` carries a range, and none (the
whole allocation) otherwise. -/
noncomputable def derefRange (terminalAddrOf : Bool) (addr sz : Nat)
(sr : Option (Nat × Nat)) : Option (Nat × Nat) :=
if terminalAddrOf then sr
else
match sr with
| some _ => some (addr, sz)
| none => none
/-- Step through remaining `CppProjElem`s from a resolved memory address.
`forAddrOf` marks the place as the operand of `&`. -/
noncomputable def resolveProjChain (prog : CppProgram) (body : CppBody)
(frame : CppFrame) (mem : CppMemory) (forAddrOf : Bool)
(cur : ResolvedAddr) :
List CppProjElem → Except CppFaultKind ResolvedAddr
| [] => .ok cur
| proj :: rest =>
match proj with
| .deref =>
match cur.ty with
| .ptr pointee _ _ _ =>
match readMemory prog.policy prog.records mem cur.allocId cur.addr
cur.subRange cur.ty cur.alignCap with
| .ok (.ptr aid' addr' sr') =>
let term := forAddrOf && rest.isEmpty
match derefCheck prog mem term aid' addr' sr' pointee with
| .ok sz =>
resolveProjChain prog body frame mem forAddrOf
{ allocId := aid', addr := addr', ty := pointee,
subRange := derefRange term addr' sz sr' }
rest
| .error k => .error k
| .error k => .error k
| .ok _ => .error .unsupported
| _ => .error .unsupported
| .field recId fIdx fTy =>
match findRecord? prog.records recId with
| some rec =>
match cppGetElem? rec.fields fIdx,
cppTySize? prog.policy prog.records fTy with
| some fld, some fsz =>
match fld.bitWidth with
| none =>
if fld.isConst || !CppTy.beq cur.ty (.record recId) ||
!CppTy.beq fld.ty fTy || !Nat.beq (Nat.mod fld.offsetBits 8) 0 ||
!Nat.ble (Nat.div fld.offsetBits 8 + fsz) rec.sizeBytes then
.error .unsupported
else
let a := cur.addr + Nat.div fld.offsetBits 8
if !placeInBounds mem cur.allocId a fsz ||
!subRangeContains cur.subRange a fsz then .error .undefined
else
resolveProjChain prog body frame mem forAddrOf
{ cur with addr := a, ty := fTy,
alignCap :=
some (alignCapMin cur.alignCap rec.alignBytes),
subRange := some (a, fsz),
enclosingRecords :=
(cur.allocId, cur.addr, recId) ::
cur.enclosingRecords }
rest
| some _ => .error .unsupported
| _, _ => .error .unsupported
| none => .error .unsupported
| .index elemTy idxLocal =>
match readLocalScalar prog body frame mem idxLocal with
| .error k => .error k
| .ok idxVal =>
let term := forAddrOf && rest.isEmpty
match cur.ty with
| .ptr ptee _ _ _ =>
-- `p[i]` is `*(p + i)` (C11 §6.5.2.1p2).
if !CppTy.beq ptee elemTy then .error .unsupported
else
match readMemory prog.policy prog.records mem cur.allocId cur.addr
cur.subRange cur.ty cur.alignCap with
| .error k => .error k
| .ok bp =>
match ptrAddOffset prog.policy prog.records mem elemTy bp
idxVal with
| .ok (.ptr aid' addr' sr') =>
match derefCheck prog mem term aid' addr' sr' elemTy with
| .ok esz =>
resolveProjChain prog body frame mem forAddrOf
{ allocId := aid', addr := addr', ty := elemTy,
subRange := derefRange term addr' esz sr' }
rest
| .error k => .error k
| .error k => .error k
| .ok _ => .error .unsupported
| .array arrElem arrLen =>
-- Indexing an array subobject in place: the index must be in
-- bounds (`&a[len]` is the C-only one-past-the-end exception).
-- Terminal `&a[k]` (`a + k`, C11 §6.5.3.2p3) keeps the array
-- `[cur.addr, cur.addr + arrLen * esz)` for `elemTy *` arithmetic,
-- while non-terminal indexing narrows to element `k` (`esz` bytes)
-- so nested projections and direct accesses stay within element `k`.
if !CppTy.beq arrElem elemTy then .error .unsupported
else
match cppTySize? prog.policy prog.records (.array arrElem arrLen),
cppTySize? prog.policy prog.records elemTy, idxVal with
| some arrBytes, some esz, .int iw is ibits =>
match cppIntToMathInt iw is ibits with
| Int.ofNat k =>
if !placeInBounds mem cur.allocId cur.addr arrBytes ||
!subRangeContains cur.subRange cur.addr arrBytes then
.error .undefined
else if Nat.blt k arrLen then
let elemAddr := cur.addr + k * esz
let nextSr :=
if term then some (cur.addr, arrBytes)
else some (elemAddr, esz)
resolveProjChain prog body frame mem forAddrOf
{ cur with addr := elemAddr, ty := elemTy,
subRange := nextSr }
rest
else if term && Nat.beq k arrLen then .error .unsupported
else .error .undefined
| Int.negSucc _ => .error .undefined
| _, _, _ => .error .unsupported
| _ => .error .unsupported
| .bitfield _ _ _ _ _ => .error .unsupported
/-- Resolve a `CppPlace` to a `ResolvedAddr` (forcing base to memory only when
needed). `forAddrOf` marks the place as the operand of `&`. -/
noncomputable def resolvePlaceAddr (prog : CppProgram) (body : CppBody)
(frame : CppFrame) (mem : CppMemory) (forAddrOf : Bool) (place : CppPlace) :
Except CppFaultKind (ResolvedAddr × CppFrame × CppMemory) :=
let forceAndResolve (projs : List CppProjElem) :=
match forceLocalToMemory prog body frame mem place.base with
| .error k => .error k
| .ok (aid, f', m') =>
match cppGetElem? body.locals place.base, findAlloc? aid m'.allocs with
| some decl, some alloc =>
match resolveProjChain prog body f' m' forAddrOf
{ allocId := some aid, addr := alloc.baseAddr,
ty := decl.ty } projs with
| .ok r => .ok (r, f', m')
| .error k => .error k
| _, _ => .error .undefined
match place.projs with
| [] => forceAndResolve []
| .deref :: rest =>
match cppGetElem? body.locals place.base with
| some decl =>
match decl.ty with
| .ptr pointee _ _ _ =>
match readLocalScalar prog body frame mem place.base with
| .ok (.ptr aid addr sr) =>
let term := forAddrOf && rest.isEmpty
match derefCheck prog mem term aid addr sr pointee with
| .ok sz =>
match resolveProjChain prog body frame mem forAddrOf
{ allocId := aid, addr := addr, ty := pointee,
subRange := derefRange term addr sz sr }
rest with
| .ok r => .ok (r, frame, mem)
| .error k => .error k
| .error k => .error k
| .error k => .error k
| .ok _ => .error .unsupported
| _ => .error .unsupported
| none => .error .unsupported
| .index elemTy idxLocal :: rest =>
match cppGetElem? body.locals place.base with
| some decl =>
match decl.ty with
| .ptr ptee _ _ _ =>
if !CppTy.beq ptee elemTy then .error .unsupported
else
match readLocalScalar prog body frame mem place.base,
readLocalScalar prog body frame mem idxLocal with
| .ok basePtr, .ok idxVal =>
match ptrAddOffset prog.policy prog.records mem elemTy basePtr
idxVal with
| .ok (.ptr aid addr sr) =>
let term := forAddrOf && rest.isEmpty
match derefCheck prog mem term aid addr sr elemTy with
| .ok esz =>
match resolveProjChain prog body frame mem forAddrOf
{ allocId := aid, addr := addr, ty := elemTy,
subRange := derefRange term addr esz sr } rest with
| .ok r => .ok (r, frame, mem)
| .error k => .error k
| .error k => .error k
| .error k => .error k
| .ok _ => .error .unsupported
| .error k, _ => .error k
| _, .error k => .error k
| _ => forceAndResolve (.index elemTy idxLocal :: rest)
| none => .error .unsupported
| .field fRec fIdx fTy :: rest =>
forceAndResolve (.field fRec fIdx fTy :: rest)
| .bitfield r i o w s :: rest =>
forceAndResolve (.bitfield r i o w s :: rest)
/-- Split a projection chain ending in `.bitfield` into the record prefix and
`(recordId, fieldIdx, offsetBits, bitWidth, isSigned)`. -/
noncomputable def splitBitfield :
List CppProjElem →
Option (List CppProjElem × String × Nat × Nat × Nat × Bool)
| [] => none
| [.bitfield rid idx o w s] => some ([], rid, idx, o, w, s)
| p :: rest =>
match splitBitfield rest with
| some (pre, bf) => some (p :: pre, bf)
| none => none
/-- Check that a `.bitfield rid idx o w sgn` projection is well-formed: the
target is little-endian (big-endian bit-field layout is unaudited and must fail
closed with `.unsupported` before `assignOverlapCheck` / `bitfieldPlaced` can
classify an access as `.undefined`), `r.ty` is `.record rid`, and field `idx`
of `rid` is a named bit-field of type `ty`, an integer type with signedness
`sgn` at least `w > 0` bits wide, at bit offset `o` of width `w` inside the
record. -/
noncomputable def bitfieldOk (prog : CppProgram) (r : ResolvedAddr)
(rid : String) (idx o w : Nat) (sgn : Bool) (ty : CppTy) : Bool :=
prog.policy.littleEndian &&
CppTy.beq r.ty (.record rid) && Nat.blt 0 w &&
match findRecord? prog.records rid with
| none => false
| some rec =>
Nat.blt 0 rec.alignBytes && Nat.ble (o + w) (rec.sizeBytes * 8) &&
match cppGetElem? rec.fields idx with
| none => false
| some fld =>
!(fld.name == "") && !fld.isConst && Nat.beq fld.offsetBits o &&
optNatBeq fld.bitWidth (some w) && CppTy.beq fld.ty ty &&
match fld.ty with
| .int fw s _ =>
Nat.ble w fw.bitWidth &&
Signedness.beq s (if sgn then .signed else .unsigned)
| _ => false
/-- Check that the record holding a bit-field lies entirely inside a live
allocation and its subobject range, aligned for the record against the
allocation's intrinsic alignment (C11 §6.5.3.2p4): a bit-field access accesses
its record's storage unit. -/
noncomputable def bitfieldPlaced (prog : CppProgram) (mem : CppMemory)
(r : ResolvedAddr) (rid : String) : Bool :=
match findRecord? prog.records rid with
| none => false
| some rec =>
Nat.blt 0 rec.sizeBytes &&
placeInBounds mem r.allocId r.addr rec.sizeBytes &&
subRangeContains r.subRange r.addr rec.sizeBytes &&
ptrTargetAligned mem r.allocId r.addr
(alignCapMin r.alignCap rec.alignBytes)
/-- First byte and byte count covering bits `[o, o + w)`. -/
noncomputable def bitSpan (o w : Nat) : Nat × Nat :=
(Nat.div o 8, Nat.div (o + w + 7) 8 - Nat.div o 8)
/-- Read bit-field bits `[o, o + w)` of the record at `r` as `ty`
(little-endian bit order, sign-extended iff `sgn`; big-endian bit-fields fail
closed with `.unsupported`). -/
noncomputable def readBitfield (prog : CppProgram) (mem : CppMemory)
(r : ResolvedAddr) (o w : Nat) (sgn : Bool) (ty : CppTy) :
Except CppFaultKind CppVal :=
if !prog.policy.littleEndian then .error .unsupported
else
match ty, bitSpan o w with
| .int tw ts _, (b0, n) =>
match readRawBytes prog.policy prog.records mem r.allocId (r.addr + b0)
r.subRange false n with
| .ok bs =>
match decodeIntBytes prog.policy.littleEndian bs with
| none => .error (classifyBadLoad bs ty)
| some u =>
let field := Nat.mod (Nat.shiftRight u (Nat.mod o 8)) (pow2 w)
let x : Int :=
if sgn && Nat.ble (pow2 (w - 1)) field then
Int.subNatNat field (pow2 w)
else Int.ofNat field
.ok (.int tw ts (ofSignedIntWrap tw x))
| .error k => .error k
| _, _ => .error .unsupported
/-- Patch `bs` with bit-mask `mask` and pre-shifted value bits `valBits`
(little-endian). A fully covered byte (`mask % 256 == 255`) is overwritten even
if previously `.uninit` or `.ptrFrag`; a partially covered byte must already be
`.data`, else `none`. -/
noncomputable def patchBitfieldBytes (mask valBits : Nat) :
List CppByte → Option (List CppByte)
| [] => some []
| b :: rest =>
let m8 := Nat.mod mask 256
let v8 := Nat.mod valBits 256
let b' : Option CppByte :=
if Nat.beq m8 255 then some (.data (UInt8.ofNat v8))
else
match b with
| .data old =>
let keep := Nat.land old.toNat (255 - m8)
some (.data (UInt8.ofNat (Nat.lor keep (Nat.land v8 m8))))
| .uninit | .ptrFrag _ _ _ _ _ => none
match b', patchBitfieldBytes (Nat.div mask 256)
(Nat.div valBits 256) rest with
| some hd, some tl => some (hd :: tl)
| _, _ => none
/-- Store `v` (truncated modulo `2^w` per C++20 [conv.integral]p3 and Clang's
implementation-defined C11 §6.3.1.3p3 choice) into bit-field bits `[o, o + w)`
of the record at `r` by per-byte read-modify-write. Fully covered bytes may
overwrite `.uninit` storage; partially overwriting an uninitialized or
pointer-fragment byte is `.unsupported` (fail closed), as are big-endian
bit-field stores. -/
noncomputable def writeBitfield (prog : CppProgram) (mem : CppMemory)
(r : ResolvedAddr) (o w : Nat) (v : CppVal) :
Except CppFaultKind CppMemory :=
if !prog.policy.littleEndian then .error .unsupported
else
match v, bitSpan o w with
| .int _ _ bits, (b0, n) =>
let sh := Nat.mod o 8
match readRawBytes prog.policy prog.records mem r.allocId (r.addr + b0)
r.subRange true n with
| .ok bs =>
let mask := Nat.shiftLeft (pow2 w - 1) sh
let valBits := Nat.shiftLeft (Nat.mod bits (pow2 w)) sh
match patchBitfieldBytes mask valBits bs with
| none => .error .unsupported
| some bs' =>
writeRawBytes prog.policy prog.records mem r.allocId (r.addr + b0)
r.subRange bs'
| .error k => .error k
| _, _ => .error .unsupported
/-- Read a value of type `ty` from `place`. -/
noncomputable def readPlaceVal (prog : CppProgram) (body : CppBody)
(frame : CppFrame) (mem : CppMemory) (place : CppPlace) (ty : CppTy) :
Except CppFaultKind (CppVal × CppFrame × CppMemory) :=
match splitBitfield place.projs with
| some (pre, rid, idx, o, w, sgn) =>
match resolvePlaceAddr prog body frame mem false
{ place with projs := pre } with
| .error k => .error k
| .ok (r, f', m') =>
if !bitfieldOk prog r rid idx o w sgn ty then .error .unsupported
else if !bitfieldPlaced prog m' r rid then .error .undefined
else
match readBitfield prog m' r o w sgn ty with
| .ok v => .ok (v, f', m')
| .error k => .error k
| none =>
match place.projs with
| [] =>
match cppGetElem? body.locals place.base with
| none => .error .unsupported
| some decl =>
if !CppTy.beq decl.ty ty then .error .unsupported
else
match readLocalScalar prog body frame mem place.base with
| .ok v => .ok (v, frame, mem)
| .error k => .error k
| _ :: _ =>
match resolvePlaceAddr prog body frame mem false place with
| .error k => .error k
| .ok (r, f', m') =>
if !CppTy.beq r.ty ty then .error .unsupported
else
match readMemory prog.policy prog.records m' r.allocId r.addr
r.subRange ty r.alignCap with
| .ok v => .ok (v, f', m')
| .error k => .error k
/-- Write a value `v` of type `ty` into `place`. An immediate local must have
a padding-free type (a padded value is never copied by value), and a `const`
local may only be initialized, never overwritten. -/
noncomputable def writePlaceVal (prog : CppProgram) (body : CppBody)
(frame : CppFrame) (mem : CppMemory) (place : CppPlace) (ty : CppTy)
(v : CppVal) : Except CppFaultKind (CppFrame × CppMemory) :=
match splitBitfield place.projs with
| some (pre, rid, idx, o, w, sgn) =>
match resolvePlaceAddr prog body frame mem false
{ place with projs := pre } with
| .error k => .error k
| .ok (r, f', m') =>
if !bitfieldOk prog r rid idx o w sgn ty ||
!checkCppVal prog.policy prog.records v ty then .error .unsupported
else if !bitfieldPlaced prog m' r rid then .error .undefined
else
match writeBitfield prog m' r o w v with
| .ok m'' =>
match clobberEnclosingRecords prog.policy prog.records m''
((r.allocId, r.addr, rid) :: r.enclosingRecords) with
| .ok m3 => .ok (f', m3)
| .error k => .error k
| .error k => .error k
| none =>
match place.projs with
| [] =>
match cppGetElem? body.locals place.base with
| none => .error .unsupported
| some decl =>
if !CppTy.beq decl.ty ty then .error .unsupported
else
match cppGetElem? frame.locals place.base with
| none => .error .unsupported
| some .dead => .error .undefined
| some (.stackAddr aid) =>
match findAlloc? aid mem.allocs with
| some alloc =>
match writeMemory prog.policy prog.records mem (some aid)
alloc.baseAddr none ty v none with
| .ok m' => .ok (frame, m')
| .error k => .error k
| none => .error .undefined
| some .uninit =>
if !tyHasNoPadding prog.policy prog.records true 16 decl.ty then
.error .unsupported
else
match cppSetElem? frame.locals place.base (.val v) with
| some locs' => .ok ({ frame with locals := locs' }, mem)
| none => .error .unsupported
| some (.val _) =>
if !tyHasNoPadding prog.policy prog.records true 16 decl.ty then
.error .unsupported
else if decl.isConst then .error .undefined
else
match cppSetElem? frame.locals place.base (.val v) with
| some locs' => .ok ({ frame with locals := locs' }, mem)
| none => .error .unsupported
| _ :: _ =>
match resolvePlaceAddr prog body frame mem false place with
| .error k => .error k
| .ok (r, f', m') =>
if !CppTy.beq r.ty ty then .error .unsupported
else
match writeMemory prog.policy prog.records m' r.allocId r.addr
r.subRange ty v r.alignCap with
| .ok m'' =>
match clobberEnclosingRecords prog.policy prog.records m''
r.enclosingRecords with
| .ok m3 => .ok (f', m3)
| .error k => .error k
| .error k => .error k
/-- The pointee of a non-`restrict` pointer type, if `ty` is one. -/
noncomputable def ptrTyPointee? : CppTy → Option CppTy
| .ptr p _ r _ => if !r && CppTy.noRestrict p then some p else none
| _ => none
/-- Check a unary result `res` against the expression's declared type `ty`:
`!` yields `bool`, and `-`/`~` yield an integer of `ty`'s width and sign. -/
noncomputable def unResTyOk (op : CppUnOp) (ty : CppTy) (res : CppVal) : Bool :=
match op, ty, res with
| .logNot, .bool, .bool _ => true
| .neg, .int tw ts _, .int w s _ =>
CppIntWidth.beq w tw && Signedness.beq s ts
| .bitNot, .int tw ts _, .int w s _ =>
CppIntWidth.beq w tw && Signedness.beq s ts
| _, _, _ => false
/-- Check a binary result `res` against the expression's declared type
`resTy`: comparisons yield `bool`, and arithmetic, shift, and bitwise
operators yield an integer of `resTy`'s width and sign. -/
noncomputable def binResTyOk (op : CppBinOp) (resTy : CppTy) (res : CppVal) :
Bool :=
match op with
| .eq | .ne | .lt | .le | .gt | .ge =>
match resTy, res with
| .bool, .bool _ => true
| _, _ => false
| _ =>
match resTy, res with
| .int tw ts _, .int w s _ => CppIntWidth.beq w tw && Signedness.beq s ts
| _, _ => false
/-- Check that `ptrTy` is a non-`restrict` pointer to `elemTy`. -/
noncomputable def ptrAddTyOk (elemTy ptrTy : CppTy) : Bool :=
match ptrTyPointee? ptrTy with
| some p => CppTy.beq p elemTy
| none => false
/-- Target alignment and subobject-range policy for `ptrCast` to `toPtrTy`:
- `cv void*` (`some (1, none)`): preserves `sr` (`derefCheck` and
`ptrAddOffset` still reject `.void`).
- Character pointer `char*`/`signed char*`/`unsigned char*`
(`isCharLike = true`, `some (1, none)`): preserves `sr` on non-decay casts so
byte-wise object inspection may step within the designated object or subobject
(C11 §6.2.6.1p4, §6.3.2.3p7), while `ArrayToPointerDecay`
(`char a[2][4]; a[0]`) still narrows to the decayed `char[N]` subobject.
- Any other sized object pointer `T*` (`some (al, some sz)`): narrows `sr` to a
single `T` element `some (addr, sz)` inside the existing allocation/subobject
range (or sets `some (addr, 0)` when `addr` is already one past the end of the
source allocation or `sr`), preventing `(T *)&s` from stepping into sibling
struct members or array elements (C11 §6.5.6p7–p8, C++20 [expr.add]p4). -/
noncomputable def ptrCastTargetInfo? (policy : CppLangPolicy)
(records : List CppRecordDef) (toPtrTy : CppTy) :
Option (Nat × Option Nat) :=
match ptrTyPointee? toPtrTy with
| none => none
| some .void => some (1, none)
| some (.int .w8 _ true) => some (1, none)
| some ptee =>
match cppTySize? policy records ptee, cppTyAlign? policy records ptee with
| some sz, some al => some (al, some sz)
| _, _ => none
/-- Static pointee type of a non-`restrict` pointer-valued `CppExpr`, if any. -/
noncomputable def exprPtrPointee? : CppExpr → Option CppTy
| .nullPtr ty => ptrTyPointee? ty
| .readPlace _ ty => ptrTyPointee? ty
| .addrOf _ ptrTy => ptrTyPointee? ptrTy
| .ptrAdd _ ptrTy _ _ => ptrTyPointee? ptrTy
| .ptrCast toPtrTy _ => ptrTyPointee? toPtrTy
| .bitCast _ toTy _ => ptrTyPointee? toTy
| _ => none
/-- Check that when `expectedTy` is a pointer or aggregate type, `e` carries
compatible static pointee/aggregate type metadata so pointer provenance cannot
be laundered across incompatible types without `.ptrCast` (either directly or
inside an array or record copy or `.bitCast`). -/
noncomputable def exprPtrCompat (expectedTy : CppTy) (e : CppExpr) : Bool :=
match expectedTy with
| .ptr _ _ _ _ =>
match ptrTyPointee? expectedTy, exprPtrPointee? e with
| some dp, some rp => CppTy.beq dp rp
| _, _ => false
| .array _ _ | .record _ =>
match e with
| .readPlace _ srcTy => CppTy.beq expectedTy srcTy
| .bitCast _ toTy _ => CppTy.beq expectedTy toTy
| _ => false
| _ => true
/-- Elementwise `exprPtrCompat` check for call argument lists. -/
noncomputable def exprListPtrCompat : List CppTy → List CppExpr → Bool
| [], [] => true
| t :: ts, e :: es => exprPtrCompat t e && exprListPtrCompat ts es
| _, _ => false
/-- Narrow subobject range `sr` when casting live pointer `(id, addr, sr)` to a
non-character object pointer of pointee size `sz`: if `[addr, addr + sz)` fits
within `alloc` and `sr`, narrow to `some (addr, sz)`; if `addr` is one past the
end of `alloc` or `sr`, keep `some (addr, 0)` so no positive offset or
dereference can advance further; otherwise `none` (`.unsupported`, e.g. casting
a pointer to a smaller object into a pointer to a larger type). -/
noncomputable def narrowPtrCastRange? (mem : CppMemory) (id addr : Nat)
(sr : Option (Nat × Nat)) (sz : Nat) : Option (Option (Nat × Nat)) :=
if placeInBounds mem (some id) addr sz && subRangeContains sr addr sz then
some (some (addr, sz))
else if ptrAtEnd mem id addr || atRangeEnd sr addr then
some (some (addr, 0))
else none
/-- Compute target subobject range `sr'` when casting `(id, addr, sr)` from
`arg` to `toPtrTy`: same-pointee `cv` casts preserve `sr` (C11 §6.3.2.3p2);
direct `ArrayToPointerDecay` (`arg = .addrOf _ (T[N]*)` to `cv T*`) sets
`some (addr, sizeof(T[N]))`; non-`cv`, non-decay casts away from pointers to
padded types fail closed (`none`, preventing C11 §6.7.2.1p15 / byte-offset
stores from bypassing `clobberEnclosingRecords`); any other cast from
`T (*)[N]` clamps `sr` to the `T[N]` subobject via `narrowPtrCastRange?` before
converting; and other `U*` casts preserve `sr` on `void*`/byte targets (C11
§6.2.6.1p4, §6.3.2.3p7), reject `T (*)[N]`, and narrow via `narrowPtrCastRange?`
on sized `V*` targets (C11 §6.5.6p7–p8, C++20 [expr.add]p4; conservatively
rejecting `T* -> void* -> T*` array round trips, sound under `.unbridged`). -/
noncomputable def ptrCastRange? (policy : CppLangPolicy)
(records : List CppRecordDef) (mem : CppMemory) (id addr : Nat)
(sr : Option (Nat × Nat)) (toPtrTy : CppTy) (szOpt : Option Nat)
(arg : CppExpr) : Option (Option (Nat × Nat)) :=
match exprPtrPointee? arg, ptrTyPointee? toPtrTy with
| some fromPtee, some toPtee =>
if CppTy.beq fromPtee toPtee then some sr
else
let fromPadFree := match fromPtee with
| .void => true
| _ => tyHasNoPadding policy records true (records.length + 16)
fromPtee
let castToTarget (effSr : Option (Nat × Nat)) :
Option (Option (Nat × Nat)) :=
if !fromPadFree then none
else
match szOpt, toPtee with
| none, _ => some effSr
| some _, .array _ _ => none
| some sz, _ => narrowPtrCastRange? mem id addr effSr sz
match fromPtee with
| .array arrElem _ =>
match cppTySize? policy records fromPtee with
| none => none
| some arrSz =>
let clampArr :=
match narrowPtrCastRange? mem id addr sr arrSz with
| some srArr => castToTarget srArr
| none => none
match arg with
| .addrOf _ _ =>
if CppTy.beq arrElem toPtee then
if placeInBounds mem (some id) addr arrSz &&
subRangeContains sr addr arrSz then
some (some (addr, arrSz))
else none
else clampArr
| _ => clampArr
| _ => castToTarget sr
| _, _ => none
/-- `true` iff every enclosing record on `enc` is padding-free, so taking a
subobject pointer cannot later mutate a member without invalidating enclosing
record padding (C11 §6.2.6.1p6). -/
noncomputable def enclosingRecordsPaddingFree (policy : CppLangPolicy)
(records : List CppRecordDef) :
List (Option Nat × Nat × String) → Bool
| [] => true
| (_, _, rid) :: rest =>
tyHasNoPadding policy records true (records.length + 16) (.record rid) &&
enclosingRecordsPaddingFree policy records rest
/-- Evaluate a pure SSENF `CppExpr` structurally. -/
noncomputable def evalExpr (prog : CppProgram) (body : CppBody)
(frame : CppFrame) (mem : CppMemory) :
CppExpr → Except CppFaultKind (CppVal × CppFrame × CppMemory)
| .constInt w s _ v =>
match s with
| .unsigned => .ok (.int w .unsigned (ofSignedIntWrap w v), frame, mem)
| .signed =>
match finishSignedArith prog.policy w v with
| .ok res => .ok (res, frame, mem)
| .error k => .error k
| .constBool b => .ok (.bool b, frame, mem)
| .nullPtr ty =>
match ptrTyPointee? ty with
| some _ => .ok (.ptr none 0 none, frame, mem)
| none => .error .unsupported
| .readPlace place ty => readPlaceVal prog body frame mem place ty
| .addrOf place ptrTy =>
match resolvePlaceAddr prog body frame mem true place with
| .ok (r, f', m') =>
match ptrTyPointee? ptrTy with
| some ptee =>
if !CppTy.beq ptee r.ty ||
!enclosingRecordsPaddingFree prog.policy prog.records
r.enclosingRecords then
.error .unsupported
else
match cppTyAlign? prog.policy prog.records ptee with
| some al =>
if ptrTargetAligned m' r.allocId r.addr al then
.ok (.ptr r.allocId r.addr r.subRange, f', m')
else .error .unsupported
| none => .error .unsupported
| none => .error .unsupported
| .error k => .error k
| .unary op ty arg =>
match evalExpr prog body frame mem arg with
| .error k => .error k
| .ok (v, f1, m1) =>
match evalUnOp prog.policy m1 op v with
| .ok res =>
if unResTyOk op ty res then .ok (res, f1, m1) else .error .unsupported
| .error k => .error k
| .binary op resTy lhs rhs =>
match evalExpr prog body frame mem lhs with
| .error k => .error k
| .ok (lv, f1, m1) =>
match evalExpr prog body f1 m1 rhs with
| .error k => .error k
| .ok (rv, f2, m2) =>
match evalBinOp prog.policy m2 op lv rv with
| .ok res =>
if binResTyOk op resTy res then .ok (res, f2, m2)
else .error .unsupported
| .error k => .error k
| .intCast fromW fromS toW toS _ arg =>
-- Narrowing conversion to a signed integer wraps modulo `2^W` with no
-- signal, matching C++20 [conv.integral]p3 and Clang's
-- implementation-defined C11 §6.3.1.3p3 behavior.
match evalExpr prog body frame mem arg with
| .error k => .error k
| .ok (.int w s bits, f1, m1) =>
if CppIntWidth.beq w fromW && Signedness.beq s fromS then
let x := cppIntToMathInt fromW fromS bits
.ok (.int toW toS (ofSignedIntWrap toW x), f1, m1)
else .error .unsupported
| .ok (.void, _) | .ok (.bool _, _) | .ok (.ptr _ _ _, _)
| .ok (.aggregate _, _) => .error .unsupported
| .intToBool arg =>
match evalExpr prog body frame mem arg with
| .error k => .error k
| .ok (.int _ _ bits, f1, m1) => .ok (.bool (!Nat.beq bits 0), f1, m1)
| .ok (.bool b, f1, m1) => .ok (.bool b, f1, m1)
| .ok (.ptr none addr sr, f1, m1) =>
if Nat.beq addr 0 && optRangeBeq sr none then .ok (.bool false, f1, m1)
else .error .unsupported
| .ok (.ptr (some aid) _ _, f1, m1) =>
if ptrLive m1 aid then .ok (.bool true, f1, m1) else .error .undefined
| .ok _ => .error .unsupported
| .boolToInt w s arg =>
match evalExpr prog body frame mem arg with
| .error k => .error k
| .ok (.bool b, f1, m1) => .ok (.int w s (if b then 1 else 0), f1, m1)
| .ok _ => .error .unsupported
| .ptrAdd elemTy ptrTy base offset =>
if !ptrAddTyOk elemTy ptrTy || !exprPtrCompat ptrTy base then
.error .unsupported
else
match evalExpr prog body frame mem base with
| .error k => .error k
| .ok (bv, f1, m1) =>
match evalExpr prog body f1 m1 offset with
| .error k => .error k
| .ok (ov, f2, m2) =>
match ptrAddOffset prog.policy prog.records m2 elemTy bv ov with
| .ok res => .ok (res, f2, m2)
| .error k => .error k
| .ptrCast toPtrTy arg =>
match evalExpr prog body frame mem arg with
| .error k => .error k
| .ok (.ptr aid addr sr, f1, m1) =>
match ptrCastTargetInfo? prog.policy prog.records toPtrTy with
| none => .error .unsupported
| some (reqAlign, szOpt) =>
match aid with
| none =>
if Nat.beq addr 0 && optRangeBeq sr none then
.ok (.ptr none 0 none, f1, m1)
else .error .unsupported
| some id =>
if !ptrLive m1 id then .error .undefined
else if !ptrTargetAligned m1 (some id) addr reqAlign then
.error .unsupported
else
match ptrCastRange? prog.policy prog.records m1 id addr sr toPtrTy
szOpt arg with
| some sr' => .ok (.ptr (some id) addr sr', f1, m1)
| none => .error .unsupported
| .ok _ => .error .unsupported
| .bitCast fromTy toTy arg =>
match evalExpr prog body frame mem arg with
| .error k => .error k
| .ok (v, f1, m1) =>
-- C++20 [bit.cast]p2: padding bits of `fromTy` (including `bool`'s)
-- yield indeterminate result bits, and a `bool` result must hold a valid
-- value, so both types must be padding-free with no `bool`. Every source
-- byte must be initialized data: pointer provenance and indeterminate
-- bytes are not modeled through `bit_cast`.
if !exprPtrCompat fromTy arg ||
!checkCppVal prog.policy prog.records v fromTy ||
!tyHasNoPadding prog.policy prog.records false 16 fromTy ||
!tyHasNoPadding prog.policy prog.records false 16 toTy then
.error .unsupported
else
match cppTySize? prog.policy prog.records fromTy,
cppTySize? prog.policy prog.records toTy,
encodeValBytes prog.policy prog.records v fromTy with
| some s1, some s2, some bs =>
if !Nat.beq s1 s2 || !bytesAllData bs then .error .unsupported
else
match decodeValBytes prog.policy prog.records bs toTy with
| some r =>
if checkCppVal prog.policy prog.records r toTy then
.ok (r, f1, m1)
else .error .unsupported
| none => .error .unsupported
| _, _, _ => .error .unsupported
/-- Evaluate a list of call arguments left-to-right. -/
noncomputable def evalExprList (prog : CppProgram) (body : CppBody)
(frame : CppFrame) (mem : CppMemory) :
List CppExpr → Except CppFaultKind (List CppVal × CppFrame × CppMemory)
| [] => .ok ([], frame, mem)
| e :: es =>
match evalExpr prog body frame mem e with
| .error k => .error k
| .ok (v, f1, m1) =>
match evalExprList prog body f1 m1 es with
| .error k => .error k
| .ok (vs, f2, m2) => .ok (v :: vs, f2, m2)
end Trusted.CppSemantics
end