blob: d3ed7cc03111d981b03ff02660d4161679587c0f [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.UInt.BasicAux
public import Init.Data.Nat.Div.Basic
public import Init.Data.Nat.Bitwise.Basic
public import Init.Data.Int.Basic
public import Trusted.CppAst
public import Trusted.CppSemantics.State
@[expose] public section
namespace Trusted.CppSemantics
open Trusted.CppAst
/-!
# Rung-0 C11 Memory, Provenance, and Alignment (`Trusted.CppSemantics.Memory`)
Tactic-free Ring-0 memory rules implementing ILP32/LP64 target-parameterized
type layout, allocation-id and subobject-range provenance, intrinsic
allocation-alignment and bounds checks, endian-parameterized integer byte
codecs, and `.uninit` / `.ptrFrag` classification. Programs compiled with
strict aliasing are not admitted; accesses under such a policy fail closed with
`.unsupported`.
-/
/-- Pointer size in bytes from `policy` (`4` on ILP32, `8` on LP64). -/
noncomputable def ptrByteSize (policy : CppLangPolicy) : Nat :=
Nat.div policy.pointerWidthBits 8
/-- Exclusive upper bound `2^pointerWidthBits` on target addresses (`2^32` on
ILP32, `2^64` on LP64). -/
noncomputable def ptrAddrBound (policy : CppLangPolicy) : Nat :=
Nat.pow 2 policy.pointerWidthBits
/-- Exclusive upper bound `2^(pointerWidthBits - 1)` (`PTRDIFF_MAX + 1`: `2^31`
on ILP32, `2^63` on LP64) on single-object byte sizes and pointer-addition byte
displacements (matching Clang/LLVM `getelementptr inbounds` and
`Trusted.MirSemantics.isizeMaxBytes`). -/
noncomputable def maxObjSizeBytes (policy : CppLangPolicy) : Nat :=
Nat.pow 2 (policy.pointerWidthBits - 1)
/-- Maximum alignment `2^29` bytes accepted by this model (conservatively
matching `Trusted.MirSemantics` `alignLog2 <= 29`). -/
noncomputable def maxAlignBytes : Nat := Nat.pow 2 29
/-- `true` iff `policy` specifies an admitted C11/C++20 target profile:
`-fno-exceptions`, `-fno-strict-aliasing`, 32-bit (ILP32) or 64-bit (LP64)
pointers, and a well-formed `AbiAlignTable` bounded by `2^29`. Both
little-endian and big-endian targets are admitted (big-endian bit-fields fail
closed at evaluation). -/
noncomputable def cppPolicyAdmitted (policy : CppLangPolicy) : Bool :=
policy.exceptionsOff &&
!policy.strictAliasing &&
(Nat.beq policy.pointerWidthBits 32 || Nat.beq policy.pointerWidthBits 64) &&
policy.intAligns.valid
(if Nat.beq policy.pointerWidthBits 32 then .p32 else .p64) 29
/-- `true` iff `a` is a positive power-of-two alignment at most `2^29` (C11
§6.2.8p3, C++20 [basic.align]p4). -/
noncomputable def validAlignBytes (a : Nat) : Bool :=
Nat.blt 0 a && Nat.ble a maxAlignBytes &&
Nat.beq (Nat.land a (a - 1)) 0
/-- ABI alignment in bytes of a fixed-width integer from `policy.intAligns`
(e.g., `4` for `int64_t` on `i686`, `8` for `__int128` on `s390x`/`arm`/
`powerpc`). -/
noncomputable def cppIntAlign (policy : CppLangPolicy) : CppIntWidth → Nat
| .w8 => Nat.pow 2 policy.intAligns.i8AlignLog2
| .w16 => Nat.pow 2 policy.intAligns.i16AlignLog2
| .w32 => Nat.pow 2 policy.intAligns.i32AlignLog2
| .w64 => Nat.pow 2 policy.intAligns.i64AlignLog2
| .w128 => Nat.pow 2 policy.intAligns.i128AlignLog2
/-- Non-zero byte size `< maxObjSizeBytes policy` of a `CppTy` (`none` for
`.void`, zero-length or over-sized arrays, zero-sized/over-sized/misaligned
records, or unknown records; C11 §6.7.6.2p1, §6.7.2.1p8, C++20 [dcl.array]p1,
[intro.object]p9). -/
noncomputable def cppTySize? (policy : CppLangPolicy)
(records : List CppRecordDef) : CppTy → Option Nat
| .void => none
| .bool => some 1
| .int w _ _ => some w.byteSize
| .ptr _ _ _ _ => some (ptrByteSize policy)
| .array elem n =>
if Nat.beq n 0 then none
else
match cppTySize? policy records elem with
| some esz =>
let sz := esz * n
if Nat.blt sz (maxObjSizeBytes policy) then some sz else none
| none => none
| .record rid =>
match findRecord? records rid with
| some r =>
if Nat.blt 0 r.sizeBytes &&
Nat.blt r.sizeBytes (maxObjSizeBytes policy) &&
validAlignBytes r.alignBytes then
some r.sizeBytes
else none
| none => none
/-- Alignment in bytes of a sized `CppTy`, consulting `policy.intAligns`. -/
noncomputable def cppTyAlign? (policy : CppLangPolicy)
(records : List CppRecordDef) : CppTy → Option Nat
| .void => none
| .bool => some 1
| .int w _ _ => some (cppIntAlign policy w)
| .ptr _ _ _ _ => some (Nat.pow 2 policy.intAligns.ptrAlignLog2)
| .array elem n =>
match cppTySize? policy records (.array elem n) with
| some _ => cppTyAlign? policy records elem
| none => none
| .record rid =>
match findRecord? records rid with
| some r =>
if Nat.blt 0 r.sizeBytes &&
Nat.blt r.sizeBytes (maxObjSizeBytes policy) &&
validAlignBytes r.alignBytes then
some r.alignBytes
else none
| none => none
/-- `true` iff `fields`, starting at bit `cursor`, are listed in ascending
order and cover every bit up to `endBits` exactly once, every field is named
(an unnamed bit-field is padding), every bit-field is an integer no wider than
its type, and every non-bit-field member starts on a byte boundary and
satisfies `chk`. -/
noncomputable def fieldsDense (policy : CppLangPolicy)
(records : List CppRecordDef) (chk : CppTy → Bool) (cursor endBits : Nat) :
List CppFieldDecl → Bool
| [] => Nat.beq cursor endBits
| f :: fs =>
!(f.name == "") && !f.isConst && Nat.beq f.offsetBits cursor &&
match f.bitWidth with
| some w =>
-- A `bool` bit-field, or one wider than its integer type, has
-- padding bits (C++20 [class.bit]p1).
(match f.ty with
| .int fw _ _ => Nat.blt 0 w && Nat.ble w fw.bitWidth
| _ => false) &&
fieldsDense policy records chk (cursor + w) endBits fs
| none =>
Nat.beq (Nat.mod cursor 8) 0 && chk f.ty &&
match cppTySize? policy records f.ty with
| some sz =>
fieldsDense policy records chk (cursor + sz * 8) endBits fs
| none => false
/-- `true` iff `ty` is non-zero-sized and every bit of a `ty` object belongs to
its value representation (no padding bytes or bits), within `fuel` levels of
nesting. `bool` has seven padding bits (C11 §6.2.6.2p1) and counts as
padding-free only when `boolOk`; unions, zero-sized types, and unknown records
never do. -/
noncomputable def tyHasNoPadding (policy : CppLangPolicy)
(records : List CppRecordDef) (boolOk : Bool) : Nat → CppTy → Bool
| 0, _ => false
| _ + 1, .void => false
| _ + 1, .bool => boolOk
| _ + 1, .int _ _ _ => true
| _ + 1, .ptr _ _ _ _ => true
| fuel + 1, .array elem n =>
(match cppTySize? policy records (.array elem n) with
| some _ => true
| none => false) &&
tyHasNoPadding policy records boolOk fuel elem
| fuel + 1, .record rid =>
match findRecord? records rid with
| some r =>
!r.isUnion && Nat.blt 0 r.sizeBytes &&
Nat.blt r.sizeBytes (maxObjSizeBytes policy) &&
validAlignBytes r.alignBytes &&
fieldsDense policy records (tyHasNoPadding policy records boolOk fuel)
0 (r.sizeBytes * 8) r.fields
| none => false
/-- Check whether `id` is absent from `seen`. -/
noncomputable def strNotSeen (id : String) : List String → Bool
| [] => true
| x :: rest => !(id == x) && strNotSeen id rest
/-- Elementwise predicate check over `List CppTy`. -/
noncomputable def allTysOk (chk : CppTy → Bool) : List CppTy → Bool
| [] => true
| t :: ts => chk t && allTysOk chk ts
/-- `true` iff by-value `.array`/`.record` nesting in `ty` is acyclic within
`fuel` steps (pointer pointees need not be unwrapped). -/
noncomputable def tyAcyclic (records : List CppRecordDef) :
Nat → CppTy → Bool
| 0, _ => false
| _ + 1, .void | _ + 1, .bool | _ + 1, .int _ _ _ | _ + 1, .ptr _ _ _ _ =>
true
| fuel + 1, .array e _ => tyAcyclic records fuel e
| fuel + 1, .record rid =>
match findRecord? records rid with
| some r => allTysOk (tyAcyclic records fuel) (r.fields.map CppFieldDecl.ty)
| none => false
/-- Validated `(offsetBits, widthBits)` span of field `f` inside a record of
size `endBits` bits: rejects `const`, `restrict`, and zero-length-array fields,
requires byte alignment for non-bit-field members, and bounds every field span
within `endBits`. -/
noncomputable def fieldBitSpan? (policy : CppLangPolicy)
(records : List CppRecordDef) (endBits : Nat) (f : CppFieldDecl) :
Option (Nat × Nat) :=
if f.isConst || !f.ty.noRestrict || !f.ty.nonZeroArray then none
else
match f.bitWidth with
| some w =>
if f.name == "" then
if Nat.ble (f.offsetBits + w) endBits then some (f.offsetBits, w)
else none
else
let tyOk := match f.ty with
| .bool => Nat.blt 0 w && Nat.ble w 8
| .int fw _ _ => Nat.blt 0 w && Nat.ble w fw.bitWidth
| _ => false
if tyOk && Nat.ble (f.offsetBits + w) endBits then
some (f.offsetBits, w)
else none
| none =>
if (f.name == "") || !Nat.beq (Nat.mod f.offsetBits 8) 0 then none
else
match cppTySize? policy records f.ty with
| some fsz =>
if Nat.ble (f.offsetBits + fsz * 8) endBits then
some (f.offsetBits, fsz * 8)
else none
| none => none
/-- `true` iff bit span `[lo, lo + len)` is disjoint from every span in
`spans` (zero-width unnamed bit-fields overlap nothing). -/
noncomputable def bitSpanDisjointFrom (lo len : Nat) :
List (Nat × Nat) → Bool
| [] => true
| (lo2, len2) :: rest =>
(Nat.beq len 0 || Nat.beq len2 0 ||
Nat.ble (lo + len) lo2 || Nat.ble (lo2 + len2) lo) &&
bitSpanDisjointFrom lo len rest
/-- `true` iff every field in `fs` has a valid in-bounds bit span pairwise
disjoint from earlier spans in `seen`. -/
noncomputable def fieldsLayoutValid (policy : CppLangPolicy)
(records : List CppRecordDef) (endBits : Nat)
(seen : List (Nat × Nat)) : List CppFieldDecl → Bool
| [] => true
| f :: fs =>
match fieldBitSpan? policy records endBits f with
| some (lo, len) =>
bitSpanDisjointFrom lo len seen &&
fieldsLayoutValid policy records endBits ((lo, len) :: seen) fs
| none => false
/-- Validate `records` sequentially against `allRecords`. -/
noncomputable def cppRecordsValidAux (policy : CppLangPolicy)
(allRecords : List CppRecordDef) (seen : List String) :
List CppRecordDef → Bool
| [] => true
| r :: rest =>
!(r.recordId == "") && strNotSeen r.recordId seen &&
!r.isUnion && Nat.blt 0 r.sizeBytes &&
Nat.blt r.sizeBytes (maxObjSizeBytes policy) &&
validAlignBytes r.alignBytes &&
Nat.beq (Nat.mod r.sizeBytes r.alignBytes) 0 &&
allTysOk (tyAcyclic allRecords (allRecords.length + 16))
(r.fields.map CppFieldDecl.ty) &&
fieldsLayoutValid policy allRecords (r.sizeBytes * 8) [] r.fields &&
cppRecordsValidAux policy allRecords (r.recordId :: seen) rest
/-- `true` iff `records` has unique non-empty IDs, non-zero-sized/aligned
non-`union` definitions whose `sizeBytes` is a multiple of `alignBytes`,
acyclic by-value containment, no `const`/`restrict`/ZST fields, and in-bounds
pairwise-disjoint field spans. -/
noncomputable def cppRecordsValid (policy : CppLangPolicy)
(records : List CppRecordDef) : Bool :=
cppRecordsValidAux policy records [] records
/-- Look up an allocation by `allocId`. -/
noncomputable def findAlloc? (aid : Nat) : List CppAlloc → Option CppAlloc
| [] => none
| a :: rest =>
if Nat.beq a.allocId aid then some a else findAlloc? aid rest
/-- Replace an allocation matching `aid` in `allocs`. -/
noncomputable def replaceAlloc? (aid : Nat) (newAlloc : CppAlloc) :
List CppAlloc → Option (List CppAlloc)
| [] => none
| a :: rest =>
if Nat.beq a.allocId aid then some (newAlloc :: rest)
else
match replaceAlloc? aid newAlloc rest with
| some rest' => some (a :: rest')
| none => none
/-- Return `true` iff `aid` does not appear in `seen`. -/
noncomputable def allocIdNotSeen (aid : Nat) : List Nat → Bool
| [] => true
| x :: rest => !Nat.beq aid x && allocIdNotSeen aid rest
/-- One past the last address occupied by `a` (a zero-sized allocation
occupies one address, so distinct objects have distinct addresses). -/
noncomputable def allocEnd (a : CppAlloc) : Nat :=
a.baseAddr + (if Nat.blt 0 a.sizeBytes then a.sizeBytes else 1)
/-- `true` iff every pointer-provenance fragment in `bs` carries `0 < aid` and
`aid < nextId` (so fresh `allocStack` IDs starting at `mem.nextAllocId` never
collide with pre-existing provenance fragments in caller memory). -/
noncomputable def bytesProvIdsBounded (nextId : Nat) : List CppByte → Bool
| [] => true
| .ptrFrag _ aid _ _ _ :: rest =>
Nat.blt 0 aid && Nat.blt aid nextId && bytesProvIdsBounded nextId rest
| _ :: rest => bytesProvIdsBounded nextId rest
/-- Validate `CppAlloc` list invariants (non-zero unique IDs `< nextId`,
`sizeBytes < maxObjSizeBytes policy`, power-of-two `alignBytes <= 2^29`,
non-zero aligned `baseAddr`, `bytes.length == sizeBytes`, bounded provenance
IDs, and every allocation below `nextAddr`, so later stack allocations cannot
overlap it). -/
noncomputable def allocsValidAux (policy : CppLangPolicy) (seen : List Nat)
(nextId nextAddr : Nat) : List CppAlloc → Bool
| [] => true
| a :: rest =>
Nat.blt 0 a.allocId && Nat.blt a.allocId nextId &&
allocIdNotSeen a.allocId seen &&
Nat.blt a.sizeBytes (maxObjSizeBytes policy) &&
validAlignBytes a.alignBytes &&
Nat.blt 0 a.baseAddr && Nat.beq (Nat.mod a.baseAddr a.alignBytes) 0 &&
Nat.beq a.bytes.length a.sizeBytes &&
bytesProvIdsBounded nextId a.bytes &&
Nat.ble (allocEnd a) nextAddr &&
allocsValidAux policy (a.allocId :: seen) nextId nextAddr rest
/-- `true` iff `a` is dead or overlaps no live allocation in `others`. -/
noncomputable def allocDisjointFrom (a : CppAlloc) : List CppAlloc → Bool
| [] => true
| b :: rest =>
(!a.live || !b.live || Nat.ble (allocEnd a) b.baseAddr ||
Nat.ble (allocEnd b) a.baseAddr) && allocDisjointFrom a rest
/-- `true` iff the live allocations in `allocs` occupy disjoint addresses. -/
noncomputable def allocsDisjoint : List CppAlloc → Bool
| [] => true
| a :: rest => allocDisjointFrom a rest && allocsDisjoint rest
/-- Validate `CppMemory` well-formedness: every allocation, and so every
in-bounds or one-past-the-end address, lies below
`nextAddr < ptrAddrBound policy`. -/
noncomputable def validCppMemory (policy : CppLangPolicy)
(mem : CppMemory) : Bool :=
Nat.blt 0 mem.nextAllocId && Nat.blt 0 mem.nextAddr &&
Nat.blt mem.nextAddr (ptrAddrBound policy) &&
allocsValidAux policy [] mem.nextAllocId mem.nextAddr mem.allocs &&
allocsDisjoint mem.allocs
/-- Align `addr` upward to a multiple of `align`. -/
noncomputable def alignUp (addr align : Nat) : Nat :=
let rem := Nat.mod addr align
if Nat.beq rem 0 then addr else addr + (align - rem)
/-- Allocate a live stack object initialized to `.uninit` bytes. -/
noncomputable def allocStack (mem : CppMemory) (sizeBytes alignBytes : Nat)
(isConst : Bool) : Nat × CppMemory :=
let align := if Nat.blt 0 alignBytes then alignBytes else 1
let base := alignUp mem.nextAddr align
let aid := mem.nextAllocId
let alloc : CppAlloc := {
allocId := aid, sizeBytes := sizeBytes, alignBytes := align,
live := true, isConst := isConst,
bytes := cppReplicate sizeBytes .uninit, baseAddr := base
}
let bump := if Nat.blt 0 sizeBytes then sizeBytes else 1
(aid, { allocs := alloc :: mem.allocs, nextAllocId := aid + 1,
nextAddr := alignUp (base + bump) 16 })
/-- `true` iff `addr` inside `alloc` is aligned to `reqAlign` under every
conforming placement of `alloc`: `alloc.alignBytes` is a multiple of `reqAlign`
and the byte offset `addr - alloc.baseAddr` is a multiple of `reqAlign` (C11
§6.2.8, §6.5.3.2p4; C++20 [basic.align]). -/
noncomputable def allocAlignedAt (alloc : CppAlloc) (addr reqAlign : Nat) :
Bool :=
Nat.blt 0 reqAlign &&
Nat.beq (Nat.mod alloc.alignBytes reqAlign) 0 &&
Nat.ble alloc.baseAddr addr &&
Nat.beq (Nat.mod (addr - alloc.baseAddr) reqAlign) 0
/-- `true` iff `aid` names an allocation in `mem` at which `addr` satisfies
`allocAlignedAt _ addr reqAlign`. -/
noncomputable def ptrTargetAligned (mem : CppMemory) (aid : Option Nat)
(addr reqAlign : Nat) : Bool :=
match aid with
| none => false
| some id =>
match findAlloc? id mem.allocs with
| some alloc => allocAlignedAt alloc addr reqAlign
| none => false
/-- Mark allocation `aid` dead (`live := false`). -/
noncomputable def freeAlloc (mem : CppMemory) (aid : Nat) : CppMemory :=
match findAlloc? aid mem.allocs with
| none => mem
| some a =>
match replaceAlloc? aid { a with live := false } mem.allocs with
| some allocs' => { mem with allocs := allocs' }
| none => mem
/-- Mark a list of stack allocations dead on function return. -/
noncomputable def freeAllocs (mem : CppMemory) : List Nat → CppMemory
| [] => mem
| aid :: rs => freeAllocs (freeAlloc mem aid) rs
/-- `true` iff allocation `aid` exists and is live. -/
noncomputable def ptrLive (mem : CppMemory) (aid : Nat) : Bool :=
match findAlloc? aid mem.allocs with
| some a => a.live
| none => false
/-- `true` iff `[addr, addr + len)` lies inside live allocation `aid`. -/
noncomputable def placeInBounds (mem : CppMemory) (aid : Option Nat)
(addr len : Nat) : Bool :=
match aid with
| none => false
| some id =>
match findAlloc? id mem.allocs with
| none => false
| some a =>
a.live && Nat.ble a.baseAddr addr &&
Nat.ble (addr - a.baseAddr + len) a.sizeBytes
/-- `true` iff `[addr, addr + len)` lies inside subobject range `sr` (no
range means the whole allocation, checked separately). -/
noncomputable def subRangeContains (sr : Option (Nat × Nat))
(addr len : Nat) : Bool :=
match sr with
| none => true
| some (lo, sz) => Nat.ble lo addr && Nat.ble (addr + len) (lo + sz)
/-- `true` iff pointer `(id, addr, sr)` points into live allocation `id` or
one past its end, and `sr` (if any) is a range inside the allocation that
contains `addr` or ends at it. -/
noncomputable def ptrInRangeOrEnd (policy : CppLangPolicy) (mem : CppMemory)
(id addr : Nat) (sr : Option (Nat × Nat)) : Bool :=
match findAlloc? id mem.allocs with
| none => false
| some a =>
a.live && Nat.blt a.sizeBytes (maxObjSizeBytes policy) &&
Nat.ble a.baseAddr addr &&
Nat.ble addr (a.baseAddr + a.sizeBytes) &&
match sr with
| none => true
| some (lo, sz) =>
Nat.blt sz (maxObjSizeBytes policy) &&
Nat.ble a.baseAddr lo &&
Nat.ble (lo + sz) (a.baseAddr + a.sizeBytes) &&
Nat.ble lo addr && Nat.ble addr (lo + sz)
/-- Structural equality on `Option (Nat × Nat)`. -/
noncomputable def optRangeBeq : Option (Nat × Nat) → Option (Nat × Nat) → Bool
| none, none => true
| some (a1, b1), some (a2, b2) => Nat.beq a1 a2 && Nat.beq b1 b2
| _, _ => false
/-- Encode unsigned integer `uval` into `nbytes` little-endian `CppByte`s. -/
noncomputable def encodeIntBytesLe (nbytes : Nat) (uval : Nat) : List CppByte :=
match nbytes with
| 0 => []
| k + 1 =>
.data (UInt8.ofNat (Nat.mod uval 256)) ::
encodeIntBytesLe k (Nat.div uval 256)
/-- Encode unsigned integer `uval` into `nbytes` `CppByte`s in the byte order
selected by `littleEndian` (`true` = little-endian, `false` = big-endian). -/
noncomputable def encodeIntBytes (littleEndian : Bool) (nbytes : Nat)
(uval : Nat) : List CppByte :=
let le := encodeIntBytesLe nbytes uval
if littleEndian then le else le.reverse
/-- Decode little-endian `CppByte`s; fails (`none`) on `.uninit`/`.ptrFrag`. -/
noncomputable def decodeIntBytesLe : List CppByte → Option Nat
| [] => some 0
| .data b :: rest =>
match decodeIntBytesLe rest with
| some hi => some (b.toNat + 256 * hi)
| none => none
| .uninit :: _ => none
| .ptrFrag _ _ _ _ _ :: _ => none
/-- Decode `CppByte`s in the byte order selected by `littleEndian`; fails
(`none`) on `.uninit`/`.ptrFrag`. -/
noncomputable def decodeIntBytes (littleEndian : Bool) (bs : List CppByte) :
Option Nat :=
decodeIntBytesLe (if littleEndian then bs else bs.reverse)
/-- Encode pointer provenance/address/subobject range (with static pointee
`ptee`) into `remaining` `CppByte`s. -/
noncomputable def encodePtrBytesAux (ptee : CppTy) (aid : Option Nat)
(addr : Nat) (sr : Option (Nat × Nat)) (idx remaining : Nat) :
List CppByte :=
match remaining with
| 0 => []
| k + 1 =>
let b := match aid with
| some id => CppByte.ptrFrag ptee id addr sr idx
| none =>
CppByte.data
(UInt8.ofNat (Nat.mod (Nat.div addr (Nat.pow 256 idx)) 256))
b :: encodePtrBytesAux ptee aid addr sr (idx + 1) k
/-- Verify consecutive `ptrFrag` bytes for `(expectedPtee, aid, addr, sr)`. -/
noncomputable def decodePtrFragsAux (expectedPtee : CppTy) (aid addr : Nat)
(sr : Option (Nat × Nat)) (idx : Nat) : List CppByte → Bool
| [] => true
| .ptrFrag p2 id2 a2 sr2 i2 :: rest =>
CppTy.beq p2 expectedPtee && Nat.beq aid id2 && Nat.beq addr a2 &&
optRangeBeq sr sr2 && Nat.beq idx i2 &&
decodePtrFragsAux expectedPtee aid addr sr (idx + 1) rest
| _ :: _ => false
/-- Decode pointer bytes for `expectedPtee`; fails on `.uninit`, mixed or
mismatched-pointee provenance fragments (preventing `*(U **)&p` from bypassing
`.ptrCast`), or non-zero raw data bytes (only all-zero data bytes decode to
`NULL`, `.ptr none 0 none`). -/
noncomputable def decodePtrBytes (littleEndian : Bool) (expectedPtee : CppTy)
(bs : List CppByte) : Option CppVal :=
match bs with
| .ptrFrag p0 aid addr sr 0 :: rest =>
if CppTy.beq p0 expectedPtee &&
decodePtrFragsAux expectedPtee aid addr sr 1 rest then
some (.ptr (some aid) addr sr)
else none
| _ =>
match decodeIntBytes littleEndian bs with
| some addr =>
if Nat.beq addr 0 then some (.ptr none 0 none) else none
| none => none
/-- Encode a typed `CppVal` into raw `CppByte`s. -/
noncomputable def encodeValBytes (policy : CppLangPolicy)
(records : List CppRecordDef) (v : CppVal) (ty : CppTy) :
Option (List CppByte) :=
match v, ty with
| .bool b, .bool =>
some [.data (UInt8.ofNat (if b then 1 else 0))]
| .int w1 s1 bits, .int w2 s2 _ =>
if CppIntWidth.beq w1 w2 && Signedness.beq s1 s2 then
some (encodeIntBytes policy.littleEndian w1.byteSize bits)
else none
| .ptr aid addr sr, .ptr ptee _ _ _ =>
some (encodePtrBytesAux ptee aid addr sr 0 (ptrByteSize policy))
| .aggregate bs, .array elem n =>
match cppTySize? policy records (.array elem n) with
| some sz => if Nat.beq bs.length sz then some bs else none
| none => none
| .aggregate bs, .record rid =>
match findRecord? records rid with
| some r => if Nat.beq bs.length r.sizeBytes then some bs else none
| none => none
| _, _ => none
/-- Decode raw `CppByte`s into a typed `CppVal` (scalar `.uninit` -> `none`). -/
noncomputable def decodeValBytes (policy : CppLangPolicy)
(records : List CppRecordDef) (bs : List CppByte) (ty : CppTy) :
Option CppVal :=
match ty with
| .void => none
| .bool =>
match bs with
| [.data b] =>
if Nat.beq b.toNat 0 then some (.bool false)
else if Nat.beq b.toNat 1 then some (.bool true)
else none
| _ => none
| .int w s _ =>
if Nat.beq bs.length w.byteSize then
match decodeIntBytes policy.littleEndian bs with
| some u => some (.int w s (Nat.mod u (Nat.pow 2 w.bitWidth)))
| none => none
else none
| .ptr expectedPtee _ _ _ =>
if Nat.beq bs.length (ptrByteSize policy) then
decodePtrBytes policy.littleEndian expectedPtee bs
else none
| .array elem n =>
match cppTySize? policy records (.array elem n) with
| some sz => if Nat.beq bs.length sz then some (.aggregate bs) else none
| none => none
| .record rid =>
match findRecord? records rid with
| some r =>
if Nat.beq bs.length r.sizeBytes then some (.aggregate bs) else none
| none => none
/-- `true` iff every byte is an initialized data byte (no `.uninit` and no
pointer-provenance fragment). -/
noncomputable def bytesAllData : List CppByte → Bool
| [] => true
| .data _ :: rest => bytesAllData rest
| .uninit :: _ => false
| .ptrFrag _ _ _ _ _ :: _ => false
/-- `true` iff at least one byte in `bs` is `.uninit`. -/
noncomputable def bytesHasUninit : List CppByte → Bool
| [] => false
| .uninit :: _ => true
| _ :: rest => bytesHasUninit rest
/-- `true` iff `ptr (aid, addr, sr)` is a well-formed pointer value under
`policy`: either `NULL` (`aid = none`, `addr = 0`, `sr = none`), or a
provenance-carrying pointer (`aid = some id`) whose address and subobject range
lie below `ptrAddrBound policy` (and inside live allocation `id` when `memOpt`
is given). -/
noncomputable def ptrValOk (policy : CppLangPolicy) (memOpt : Option CppMemory)
(aid : Option Nat) (addr : Nat) (sr : Option (Nat × Nat)) : Bool :=
match aid with
| none => Nat.beq addr 0 && optRangeBeq sr none
| some id =>
Nat.blt 0 id && Nat.blt addr (ptrAddrBound policy) &&
(match sr with
| none => true
| some (lo, sz) =>
Nat.blt sz (maxObjSizeBytes policy) &&
Nat.ble lo addr && Nat.ble addr (lo + sz) &&
Nat.blt (lo + sz) (ptrAddrBound policy)) &&
match memOpt with
| some mem => ptrInRangeOrEnd policy mem id addr sr
| none => true
/-- `true` iff `n` consecutive `esz`-byte chunks of `bs` each satisfy `chk`. -/
noncomputable def aggElemsValid (chk : List CppByte → Bool) (esz : Nat) :
Nat → List CppByte → Bool
| 0, _ => true
| n + 1, bs => chk (bs.take esz) && aggElemsValid chk esz n (bs.drop esz)
/-- `true` iff every field of a record in bytes `bs` holds a valid value:
members by `chk`, bit-fields by having only initialized data bytes. -/
noncomputable def aggFieldsValid (policy : CppLangPolicy)
(records : List CppRecordDef) (chk : List CppByte → CppTy → Bool)
(bs : List CppByte) : List CppFieldDecl → Bool
| [] => true
| f :: fs =>
(match f.bitWidth with
| some w =>
bytesAllData
(cppListSlice bs (Nat.div f.offsetBits 8)
(Nat.div (f.offsetBits + w + 7) 8 - Nat.div f.offsetBits 8))
| none =>
Nat.beq (Nat.mod f.offsetBits 8) 0 &&
match cppTySize? policy records f.ty with
| some fsz => chk (cppListSlice bs (Nat.div f.offsetBits 8) fsz) f.ty
| none => false) &&
aggFieldsValid policy records chk bs fs
/-- `true` iff bytes `bs` hold a valid value of type `ty` member by member:
every scalar initialized, every `bool` `0` or `1`, and every pointer well
formed (`ptrValOk`), within `fuel` levels of nesting. Because C11 §6.2.6.1p6
defines aggregate values even when a member is indeterminate while C++20
[class.copy.ctor]p14 and [basic.indet]p2 perform memberwise copy (faulting on
an indeterminate scalar member), failed `aggBytesValid` on an aggregate load or
return is classified as `.unsupported` rather than `.undefined`. -/
noncomputable def aggBytesValid (policy : CppLangPolicy)
(records : List CppRecordDef) (memOpt : Option CppMemory) :
Nat → List CppByte → CppTy → Bool
| 0, _, _ => false
| _ + 1, _, .void => false
| _ + 1, bs, .bool =>
match bs with
| [.data b] => Nat.beq b.toNat 0 || Nat.beq b.toNat 1
| _ => false
| _ + 1, bs, .int w _ _ =>
Nat.beq bs.length w.byteSize &&
match decodeIntBytes policy.littleEndian bs with
| some _ => true
| none => false
| _ + 1, bs, .ptr expectedPtee _ _ _ =>
Nat.beq bs.length (ptrByteSize policy) &&
match decodePtrBytes policy.littleEndian expectedPtee bs with
| some (.ptr aid addr sr) => ptrValOk policy memOpt aid addr sr
| _ => false
| fuel + 1, bs, .array elem n =>
match cppTySize? policy records elem with
| some esz =>
Nat.beq bs.length (esz * n) &&
aggElemsValid
(fun chunk => aggBytesValid policy records memOpt fuel chunk elem)
esz n bs
| none => false
| fuel + 1, bs, .record rid =>
match findRecord? records rid with
| some r =>
!r.isUnion && Nat.beq bs.length r.sizeBytes &&
aggFieldsValid policy records (aggBytesValid policy records memOpt fuel)
bs r.fields
| none => false
/-- Check that `v` is a canonical value of type `ty`: integers in range,
pointers below `ptrAddrBound policy` with well-formed ranges, and aggregates of
padding-free types whose members are all valid. -/
noncomputable def checkCppVal (policy : CppLangPolicy)
(records : List CppRecordDef) (v : CppVal) (ty : CppTy) : Bool :=
match v, ty with
| .void, .void => true
| .bool _, .bool => true
| .int w1 s1 bits, .int w2 s2 _ =>
CppIntWidth.beq w1 w2 && Signedness.beq s1 s2 &&
Nat.blt bits (Nat.pow 2 w1.bitWidth)
| .ptr aid addr sr, .ptr _ _ _ _ => ptrValOk policy none aid addr sr
| .aggregate bs, .array elem n =>
tyHasNoPadding policy records true 16 (.array elem n) &&
aggBytesValid policy records none 16 bs (.array elem n)
| .aggregate bs, .record rid =>
tyHasNoPadding policy records true 16 (.record rid) &&
aggBytesValid policy records none 16 bs (.record rid)
| _, _ => false
/-- Check that argument values match parameter types elementwise. -/
noncomputable def checkCppArgs (policy : CppLangPolicy)
(records : List CppRecordDef) : List CppVal → List CppTy → Bool
| [], [] => true
| v :: vs, t :: ts =>
checkCppVal policy records v t && checkCppArgs policy records vs ts
| _, _ => false
/-- `true` iff every pointer in value `v` of type `ty` (including inside an
aggregate) points into, or one past, a live allocation of `mem` (C11 §6.2.4p2:
a pointer to a dead object is indeterminate). -/
noncomputable def valLiveInMem (policy : CppLangPolicy)
(records : List CppRecordDef) (mem : CppMemory) (v : CppVal) (ty : CppTy) :
Bool :=
match v with
| .ptr aid addr sr => ptrValOk policy (some mem) aid addr sr
| .aggregate bs => aggBytesValid policy records (some mem) 16 bs ty
| _ => true
/-- `valLiveInMem` for every argument against its parameter type. -/
noncomputable def argsLiveInMem (policy : CppLangPolicy)
(records : List CppRecordDef) (mem : CppMemory) :
List CppVal → List CppTy → Bool
| v :: vs, t :: ts =>
valLiveInMem policy records mem v t &&
argsLiveInMem policy records mem vs ts
| _, _ => true
/-- Shared provenance, liveness, constness, intrinsic-alignment, and
allocation/subobject-bounds guard for `readMemory` and `writeMemory`. Fails
closed with `.unsupported` under a strict-aliasing policy, on `restrict`
pointer types, on zero-sized types, and on by-value accesses to types with
padding (whose padding bytes a copy would make indeterminate). `alignCap`
lowers the required alignment for members of packed records. -/
noncomputable def validateMemAccess (policy : CppLangPolicy)
(records : List CppRecordDef) (mem : CppMemory) (allocId : Option Nat)
(addr : Nat) (subRange : Option (Nat × Nat)) (accessTy : CppTy)
(isWrite : Bool) (alignCap : Option Nat) :
Except CppFaultKind (Nat × CppAlloc × Nat × Nat) :=
if policy.strictAliasing || !CppTy.noRestrict accessTy ||
!tyHasNoPadding policy records true 16 accessTy then
.error .unsupported
else
match cppTySize? policy records accessTy,
cppTyAlign? policy records accessTy with
| some sz, some tyAlign =>
let align := match alignCap with
| some c => if Nat.blt 0 c && Nat.blt c tyAlign then c else tyAlign
| none => tyAlign
match allocId with
| none => .error .undefined
| some aid =>
match findAlloc? aid mem.allocs with
| none => .error .undefined
| some alloc =>
if !alloc.live || (isWrite && alloc.isConst) ||
!allocAlignedAt alloc addr align ||
!subRangeContains subRange addr sz then
.error .undefined
else
let off := addr - alloc.baseAddr
if Nat.blt alloc.sizeBytes (off + sz) then .error .undefined
else .ok (aid, alloc, off, sz)
| _, _ => .error .unsupported
/-- Classify a failed decode or aggregate member check on `slice` at
`accessTy`: character-type reads of `.uninit` or `.ptrFrag` bytes, integer or
`bool` reads of `.ptrFrag` bytes, mixed pointer fragments, and aggregates with
uninitialized, invalid, or dangling members step to `.unsupported` (defined in
C11 §6.2.6.1p4–p6 or implementation-defined), whereas reading `.uninit` or an
invalid `bool` data byte at a non-character scalar type is `.undefined`. -/
noncomputable def classifyBadLoad (slice : List CppByte) :
CppTy → CppFaultKind
| .int _ _ isCharLike =>
if isCharLike || !bytesHasUninit slice then .unsupported
else .undefined
| .bool =>
if bytesAllData slice || bytesHasUninit slice then .undefined
else .unsupported
| .ptr _ _ _ _ =>
if bytesHasUninit slice then .undefined else .unsupported
| .array _ _ | .record _ | .void => .unsupported
/-- Read a value of type `accessTy` from `(allocId, addr)` within `subRange`.
Non-character scalar `.uninit`, invalid `bool` data bytes, and dangling scalar
pointers fault `.undefined`; character-typed reads of `.uninit`/`.ptrFrag`
bytes, pointer-fragment reinterpretation, and aggregates with unset or dangling
members fail closed with `.unsupported`. -/
noncomputable def readMemory (policy : CppLangPolicy)
(records : List CppRecordDef) (mem : CppMemory) (allocId : Option Nat)
(addr : Nat) (subRange : Option (Nat × Nat)) (accessTy : CppTy)
(alignCap : Option Nat) : Except CppFaultKind CppVal :=
match validateMemAccess policy records mem allocId addr subRange accessTy
false alignCap with
| .error k => .error k
| .ok (_, alloc, off, sz) =>
let slice := cppListSlice alloc.bytes off sz
match decodeValBytes policy records slice accessTy with
| some v =>
if valLiveInMem policy records mem v accessTy then .ok v
else
match accessTy with
| .ptr _ _ _ _ => .error .undefined
| _ => .error (classifyBadLoad slice accessTy)
| none => .error (classifyBadLoad slice accessTy)
/-- Write a value of type `accessTy` to `(allocId, addr)` within `subRange`. -/
noncomputable def writeMemory (policy : CppLangPolicy)
(records : List CppRecordDef) (mem : CppMemory) (allocId : Option Nat)
(addr : Nat) (subRange : Option (Nat × Nat)) (accessTy : CppTy)
(v : CppVal) (alignCap : Option Nat) : Except CppFaultKind CppMemory :=
match validateMemAccess policy records mem allocId addr subRange accessTy
true alignCap with
| .error k => .error k
| .ok (aid, alloc, off, _) =>
match encodeValBytes policy records v accessTy with
| none => .error .unsupported
| some encoded =>
match cppListWriteSlice alloc.bytes off encoded with
| none => .error .undefined
| some bytes' =>
let alloc' := { alloc with bytes := bytes' }
match replaceAlloc? aid alloc' mem.allocs with
| some allocs' => .ok { mem with allocs := allocs' }
| none => .error .undefined
/-- Read `len` raw `CppByte`s at `(allocId, addr)` as a character-array access
without requiring initialized bytes (used by bit-field accesses; `forWrite`
additionally rejects `const` allocations). -/
noncomputable def readRawBytes (policy : CppLangPolicy)
(records : List CppRecordDef) (mem : CppMemory) (allocId : Option Nat)
(addr : Nat) (subRange : Option (Nat × Nat)) (forWrite : Bool)
(len : Nat) : Except CppFaultKind (List CppByte) :=
match validateMemAccess policy records mem allocId addr subRange
(.array (.int .w8 .unsigned true) len) forWrite none with
| .error k => .error k
| .ok (_, alloc, off, sz) => .ok (cppListSlice alloc.bytes off sz)
/-- Overwrite raw bytes at `(allocId, addr)` as a character-type access
(bit-field stores). -/
noncomputable def writeRawBytes (policy : CppLangPolicy)
(records : List CppRecordDef) (mem : CppMemory) (allocId : Option Nat)
(addr : Nat) (subRange : Option (Nat × Nat)) (bs : List CppByte) :
Except CppFaultKind CppMemory :=
match validateMemAccess policy records mem allocId addr subRange
(.array (.int .w8 .unsigned true) bs.length) true none with
| .error k => .error k
| .ok (aid, alloc, off, _) =>
match cppListWriteSlice alloc.bytes off bs with
| none => .error .undefined
| some bytes' =>
match replaceAlloc? aid { alloc with bytes := bytes' } mem.allocs with
| some allocs' => .ok { mem with allocs := allocs' }
| none => .error .undefined
/-- Classify `bitIdx` against named bit-fields in `fields`: `(inIntBf, inAnyBf)`
(`f.name == ""` unnamed bit-fields are padding per C11 §6.7.2.1p12, and `bool`
bit-fields carry padding bits). -/
noncomputable def classifyNamedBitfieldBit (bitIdx : Nat) :
List CppFieldDecl → Bool × Bool
| [] => (false, false)
| f :: fs =>
let (rInt, rAny) := classifyNamedBitfieldBit bitIdx fs
match f.bitWidth with
| some w =>
if !(f.name == "") && Nat.ble f.offsetBits bitIdx &&
Nat.blt bitIdx (f.offsetBits + w) then
let isInt := match f.ty with | .int _ _ _ => true | _ => false
(isInt || rInt, true)
else (rInt, rAny)
| none => (rInt, rAny)
/-- Return `(intBits, anyNamedBf)` across `[baseBit, baseBit + k)`. -/
noncomputable def byteBitfieldStats (baseBit : Nat)
(fields : List CppFieldDecl) : Nat → Nat × Bool
| 0 => (0, false)
| k + 1 =>
let (cnt, anyB) := byteBitfieldStats baseBit fields k
let (inInt, inAny) := classifyNamedBitfieldBit (baseBit + k) fields
((if inInt then 1 else 0) + cnt, inAny || anyB)
/-- `true` iff byte `bOff` lies inside a non-bit-field member of `fields`. -/
noncomputable def byteInRegularField (policy : CppLangPolicy)
(records : List CppRecordDef) (bOff : Nat) : List CppFieldDecl → Bool
| [] => false
| f :: fs =>
let hit := match f.bitWidth with
| none =>
Nat.beq (Nat.mod f.offsetBits 8) 0 &&
match cppTySize? policy records f.ty with
| some fsz =>
Nat.ble (Nat.div f.offsetBits 8) bOff &&
Nat.blt bOff (Nat.div f.offsetBits 8 + fsz)
| none => false
| some _ => false
hit || byteInRegularField policy records bOff fs
/-- Scrub top-level padding bytes of a record starting at byte `bOff`: regular
member bytes and bytes fully packed (`8/8` bits) with named integer bit-fields
are kept; pure padding bytes become `.uninit`; mixed bit-field/padding bytes
keep `.uninit` if already uninitialized and otherwise fail (`none`) because
byte-granular `CppByte` cannot separate initialized bit-field bits from
unspecified padding bits in the same byte. -/
noncomputable def scrubRecordTopBytes (policy : CppLangPolicy)
(records : List CppRecordDef) (fields : List CppFieldDecl)
(bOff : Nat) : List CppByte → Option (List CppByte)
| [] => some []
| b :: rest =>
let (intCnt, anyBf) := byteBitfieldStats (bOff * 8) fields 8
let bOpt : Option CppByte :=
if byteInRegularField policy records bOff fields || Nat.beq intCnt 8 then
some b
else if !anyBf then some .uninit
else match b with | .uninit => some .uninit | _ => none
match bOpt,
scrubRecordTopBytes policy records fields (bOff + 1) rest with
| some hd, some tl => some (hd :: tl)
| _, _ => none
/-- Recursively scrub padding inside each non-bit-field member of `fields`. -/
noncomputable def scrubRegularFields (policy : CppLangPolicy)
(records : List CppRecordDef)
(scrubChild : CppTy → List CppByte → Option (List CppByte))
(bs : List CppByte) : List CppFieldDecl → Option (List CppByte)
| [] => some bs
| f :: fs =>
match f.bitWidth with
| some _ => scrubRegularFields policy records scrubChild bs fs
| none =>
match cppTySize? policy records f.ty with
| none => none
| some fsz =>
let f0 := Nat.div f.offsetBits 8
match scrubChild f.ty (cppListSlice bs f0 fsz) with
| none => none
| some sub =>
match cppListWriteSlice bs f0 sub with
| none => none
| some bs' => scrubRegularFields policy records scrubChild bs' fs
/-- Scrub `n` consecutive `esz`-byte array element slices in `bs`. -/
noncomputable def scrubArrayChunks
(scrubElem : List CppByte → Option (List CppByte)) (esz : Nat) :
Nat → List CppByte → Option (List CppByte)
| 0, [] => some []
| 0, _ :: _ => none
| n + 1, bs =>
match scrubElem (bs.take esz),
scrubArrayChunks scrubElem esz n (bs.drop esz) with
| some hd, some tl => some (hd ++ tl)
| _, _ => none
/-- Replace all padding bytes inside `bs` of type `ty` with `.uninit` (C11
§6.2.6.1p6, §6.7.9p10/p21). -/
noncomputable def scrubTyPaddingSlice (policy : CppLangPolicy)
(records : List CppRecordDef) :
Nat → CppTy → List CppByte → Option (List CppByte)
| 0, _, _ | _ + 1, .void, _ => none
| _ + 1, .bool, bs | _ + 1, .int _ _ _, bs | _ + 1, .ptr _ _ _ _, bs =>
some bs
| fuel + 1, .array elem n, bs =>
match cppTySize? policy records elem with
| none => none
| some esz =>
if !Nat.beq bs.length (esz * n) then none
else scrubArrayChunks (scrubTyPaddingSlice policy records fuel elem)
esz n bs
| fuel + 1, .record rid, bs =>
match findRecord? records rid with
| none => none
| some r =>
if r.isUnion || !Nat.beq bs.length r.sizeBytes then none
else
match scrubRecordTopBytes policy records r.fields 0 bs with
| none => none
| some top =>
scrubRegularFields policy records
(scrubTyPaddingSlice policy records fuel) top r.fields
/-- Invalidate padding bytes of each enclosing `(allocId, recAddr, recordId)`
after a member or bit-field store (C11 §6.2.6.1p6). -/
noncomputable def clobberEnclosingRecords (policy : CppLangPolicy)
(records : List CppRecordDef) (mem : CppMemory) :
List (Option Nat × Nat × String) → Except CppFaultKind CppMemory
| [] => .ok mem
| (some aid, recAddr, rid) :: rest =>
match findRecord? records rid, findAlloc? aid mem.allocs with
| some r, some alloc =>
let off := recAddr - alloc.baseAddr
match scrubTyPaddingSlice policy records (records.length + 16)
(.record rid) (cppListSlice alloc.bytes off r.sizeBytes) with
| none => .error .unsupported
| some scrubbed =>
match cppListWriteSlice alloc.bytes off scrubbed with
| none => .error .undefined
| some bytes' =>
match replaceAlloc? aid { alloc with bytes := bytes' } mem.allocs with
| none => .error .undefined
| some allocs' =>
clobberEnclosingRecords policy records
{ mem with allocs := allocs' } rest
| _, none => .error .undefined
| none, _ => .error .unsupported
| (none, _, _) :: _ => .error .unsupported
/-- Zero-initialize the `ty` object at `(allocId, addr)` within `subRange`:
value-representation bytes become `0`, while record padding bytes remain
`.uninit` (C11 §6.7.9p10/p21 vs. C++20 [dcl.init]p6). -/
noncomputable def writeZeroMemory (policy : CppLangPolicy)
(records : List CppRecordDef) (mem : CppMemory) (allocId : Option Nat)
(addr : Nat) (subRange : Option (Nat × Nat)) (ty : CppTy)
(alignCap : Option Nat) : Except CppFaultKind CppMemory :=
if policy.strictAliasing || !CppTy.noRestrict ty then .error .unsupported
else
match cppTySize? policy records ty, cppTyAlign? policy records ty with
| some sz, some tyAlign =>
let align := match alignCap with
| some c => if Nat.blt 0 c && Nat.blt c tyAlign then c else tyAlign
| none => tyAlign
match allocId with
| none => .error .undefined
| some aid =>
match findAlloc? aid mem.allocs with
| none => .error .undefined
| some alloc =>
if !alloc.live || alloc.isConst || !allocAlignedAt alloc addr align ||
!subRangeContains subRange addr sz ||
Nat.blt alloc.sizeBytes (addr - alloc.baseAddr + sz) then
.error .undefined
else
match scrubTyPaddingSlice policy records (records.length + 16) ty
(cppReplicate sz (.data (UInt8.ofNat 0))) with
| none => .error .unsupported
| some zeroBytes =>
match cppListWriteSlice alloc.bytes (addr - alloc.baseAddr)
zeroBytes with
| none => .error .undefined
| some bytes' =>
match replaceAlloc? aid { alloc with bytes := bytes' }
mem.allocs with
| some allocs' => .ok { mem with allocs := allocs' }
| none => .error .undefined
| _, _ => .error .unsupported
/-- C++ zero-initialized value of scalar `ty`. -/
noncomputable def zeroValOf? (ty : CppTy) : Option CppVal :=
match ty with
| .void => none
| .bool => some (.bool false)
| .int w s _ => some (.int w s 0)
| .ptr _ _ _ _ => some (.ptr none 0 none)
| _ => none
/-- Interpret integer `CppVal` as mathematical `Int`. -/
noncomputable def cppIntToMathInt (w : CppIntWidth) (s : Signedness)
(u : Nat) : Int :=
match s with
| .unsigned => Int.ofNat u
| .signed =>
let half := Nat.pow 2 (w.bitWidth - 1)
if Nat.blt u half then Int.ofNat u
else Int.negSucc (Nat.pow 2 w.bitWidth - u - 1)
/-- Pointer addition (`base + offset * sizeof(elemTy)`), enforcing live
provenance, target `PTRDIFF_MAX` (`< maxObjSizeBytes policy`) object-size and
byte-displacement bounds, intrinsic allocation alignment for `elemTy`, and that
the result stays within the pointer's subobject range, or its allocation if it
has none, or one past its end (C11 §6.5.6p8). `NULL + 0` and misaligned
`base`/result addresses step to `.unsupported`. -/
noncomputable def ptrAddOffset (policy : CppLangPolicy)
(records : List CppRecordDef) (mem : CppMemory) (elemTy : CppTy)
(base : CppVal) (offset : CppVal) : Except CppFaultKind CppVal :=
match cppTySize? policy records elemTy,
cppTyAlign? policy records elemTy with
| some elemSize, some elemAlign =>
match base, offset with
| .ptr (some aid) addr sr, .int ow os obits =>
match findAlloc? aid mem.allocs with
| none => .error .undefined
| some alloc =>
let srValid := match sr with
| none => true
| some (l, sz) =>
Nat.blt sz (maxObjSizeBytes policy) && Nat.ble alloc.baseAddr l &&
Nat.ble (l + sz) (alloc.baseAddr + alloc.sizeBytes)
if !Nat.blt alloc.sizeBytes (maxObjSizeBytes policy) || !srValid then
.error .unsupported
else
let lo := match sr with
| some (l, _) => l
| none => alloc.baseAddr
let hi := match sr with
| some (l, sz) => l + sz
| none => alloc.baseAddr + alloc.sizeBytes
if !alloc.live || Nat.blt addr lo || Nat.blt hi addr then
.error .undefined
else if !allocAlignedAt alloc addr elemAlign then
.error .unsupported
else
match cppIntToMathInt ow os obits with
| Int.ofNat k =>
let delta := k * elemSize
let newAddr := addr + delta
if !Nat.blt delta (maxObjSizeBytes policy) ||
!Nat.ble newAddr hi then
.error .undefined
else if !allocAlignedAt alloc newAddr elemAlign then
.error .unsupported
else .ok (.ptr (some aid) newAddr sr)
| Int.negSucc k =>
let delta := (k + 1) * elemSize
if !Nat.blt delta (maxObjSizeBytes policy) ||
!Nat.ble (lo + delta) addr
then
.error .undefined
else if !allocAlignedAt alloc (addr - delta) elemAlign then
.error .unsupported
else .ok (.ptr (some aid) (addr - delta) sr)
| .ptr none addr sr, .int _ _ obits =>
if Nat.beq addr 0 && optRangeBeq sr none && Nat.beq obits 0 then
.error .unsupported
else .error .undefined
| _, _ => .error .unsupported
| _, _ => .error .unsupported
end Trusted.CppSemantics
end