blob: bbf17ba53de3007a1ca362cad22dd8865e487b5c [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 Trusted.Framework
public import Trusted.CppAst
public import Trusted.CppSemantics.State
public import Trusted.CppSemantics.Memory
public import Trusted.CppSemantics.Eval
public import Trusted.CppSemantics.Step
@[expose] public section
namespace Trusted.CppSemantics
open Trusted.CppAst Trusted.Framework
/-!
# Rung-0 C11 ExecutionModel Instance (`Trusted.CppSemantics`)
Plugs Rung-0 C11 small-step semantics directly into
`Trusted.Framework.ExecutionModel` (`CppProfileRung0`) with
`OracleGrade.unbridged "cpp_rung0_c11"`, `defaultCppDownstreamGaps`, and the
model-pinned root obligation `CppEnvelopeTheorem`.
-/
/-- Canonical frontend-lowering, compiler-flag, downstream compilation, and
hardware execution stages outside a Pass-1 C11/C++20 AST proof. In particular,
`cpp_lang_policy_flags` discloses that the trusted claim's `CppLangPolicy`
fields (`pointerWidthBits`, `littleEndian`, `intAligns`, `charIsSigned`,
`strictAliasing`, `signedOverflow`, and `exceptionsOff`) must match the actual
Clang target data layout and compilation flags (`-fno-exceptions`,
`-fno-strict-aliasing`, `-fwrapv`, char signedness, and ABI alignments). -/
@[reducible] def defaultCppDownstreamGaps : List DisclosedGap :=
[ .unverifiedDownstream "clang_ast_lowering",
.unverifiedDownstream "cpp_lang_policy_flags",
.unverifiedDownstream "clang_opt",
.unverifiedDownstream "llvm_codegen",
.unverifiedDownstream "linker",
.unverifiedDownstream "microarch_timing" ]
/-- Model-wide assumption ledger for `CppProfileRung0`: single-threaded
isolation of all memory accessed during the call
(`DisclosedGap.callerMemoryThreadIsolation "cpp_rung0_c11"`, matching
`MirProfileV2`), untyped caller-pointer subobject/lifetime discipline
(`DisclosedGap.callerRawPtrAliasing "cpp_rung0_c11"`, including absence of
caller-supplied subobject pointers into padded enclosing records), and
`defaultCppDownstreamGaps`. -/
@[reducible] def defaultCppModelGaps : List DisclosedGap :=
.callerMemoryThreadIsolation "cpp_rung0_c11" ::
.callerRawPtrAliasing "cpp_rung0_c11" ::
defaultCppDownstreamGaps
/-- Project `CppTerminalOut` into `Trusted.Framework.TerminalOutcome`. -/
noncomputable def mapCppTerminalOut :
CppTerminalOut → TerminalOutcome CppVal CppMemory
| .returned out => .returned out.ret out.mem
/-- Lift `CppBehavior` to `TerminalOutcome CppVal CppMemory`. -/
@[reducible] def CppProduces (prog : CppProgram) (q : CppQuery)
(res : TerminalOutcome CppVal CppMemory) : Prop :=
∃ out : CppTerminalOut, CppBehavior prog q out ∧ mapCppTerminalOut out = res
/-- Check that every body has a non-empty, pairwise-distinct `identity`. -/
noncomputable def cppBodiesUniqueAux (seen : List String) :
List CppBody → Bool
| [] => true
| b :: rest =>
!(b.identity == "") &&
strNotSeen b.identity seen &&
cppBodiesUniqueAux (b.identity :: seen) rest
/-- Pairwise-distinct non-empty body identity check for `CppProgram`. -/
noncomputable def cppBodiesHaveUniqueIdentities (bodies : List CppBody) :
Bool :=
cppBodiesUniqueAux [] bodies
/-- `true` iff every parameter type in `tys` is padding-free (`checkCppVal`
admits a canonical zero-initialized value for it). -/
noncomputable def paramsAdmitted (policy : CppLangPolicy)
(records : List CppRecordDef) : List CppTy → Bool
| [] => true
| t :: ts =>
tyHasNoPadding policy records true 16 t &&
paramsAdmitted policy records ts
/-- `true` iff every `paramNonNull` flag pairs with a pointer parameter to a
sized, aligned pointee and fresh allocations for all such pointees fit below
`ptrAddrBound policy` (ensuring `CppEntryDom` is constructively inhabited). -/
noncomputable def refParamsInhabited (policy : CppLangPolicy)
(records : List CppRecordDef) (mem : CppMemory) :
List Bool → List CppTy → Bool
| [], _ => Nat.blt mem.nextAddr (ptrAddrBound policy)
| _ :: _, [] => false
| false :: fs, _ :: ts => refParamsInhabited policy records mem fs ts
| true :: fs, t :: ts =>
match t with
| .ptr pointee _ _ _ =>
match cppTySize? policy records pointee,
cppTyAlign? policy records pointee with
| some sz, some al =>
let (_, mem') := allocStack mem sz al false
Nat.blt mem'.nextAddr (ptrAddrBound policy) &&
refParamsInhabited policy records mem' fs ts
| _, _ => false
| _ => false
/-- Static admission check on a `CppBody`. `restrict`-qualified pointers and
zero-length arrays are rejected everywhere in its signature or locals, and
`b.sig` must have a constructively inhabited `CppEntryDom` under `p` (preventing
vacuous `NonVacuousEntry` satisfaction on unmodeled parameter types). -/
noncomputable def cppBodyAdmitted (p : CppProgram) (b : CppBody) : Bool :=
let mem0 : CppMemory := { allocs := [], nextAllocId := 1, nextAddr := 4096 }
!(b.identity == "") &&
CppTy.noRestrictList b.sig.params && CppTy.noRestrict b.sig.ret &&
CppTy.nonZeroArrayList b.sig.params && CppTy.nonZeroArray b.sig.ret &&
Nat.ble b.sig.paramNonNull.length b.sig.params.length &&
retSized p.policy p.records b.sig.ret &&
paramsAdmitted p.policy p.records b.sig.params &&
refParamsInhabited p.policy p.records mem0 b.sig.paramNonNull
b.sig.params &&
if b.isExternal then
true
else
bodyRuntimeAdmitted p b
/-- Static admission check on a `CppProgram` against expected `policy` and
record layout table `records` (which `CppProfileRung0` also uses for entry
and return validity, so it must be exactly `p.records`). Strict-aliasing
programs are not admitted: integer types record only their width, so the
model cannot tell `long` from `long long` as C11 §6.5p7 requires. -/
noncomputable def cppProgramAdmitted (policy : CppLangPolicy)
(records : List CppRecordDef) (p : CppProgram) : Bool :=
CppLangPolicy.beq p.policy policy &&
cppPolicyAdmitted p.policy &&
CppRecordDef.beqList p.records records &&
cppRecordsValid policy p.records &&
!p.bodies.isEmpty &&
Nat.blt p.entryDefId p.bodies.length
/-- Entry domain predicate for Rung-0 C11 functions. -/
def CppEntryDom (policy : CppLangPolicy)
(records : List CppRecordDef) (body : CppBody) (q : CppQuery) : Prop :=
validCppMemory policy q.mem = true ∧
checkCppArgs policy records q.args body.sig.params = true ∧
refArgsOk policy records q.mem body.sig.paramNonNull body.sig.params
q.args = true ∧
argsLiveInMem policy records q.mem q.args body.sig.params = true
/-- Return validity predicate for Rung-0 C11 functions. -/
def CppReturnValid (policy : CppLangPolicy)
(records : List CppRecordDef) (body : CppBody) (ret : CppVal)
(mem : CppMemory) : Prop :=
validCppMemory policy mem = true ∧
checkCppVal policy records ret body.sig.ret = true ∧
valLiveInMem policy records mem ret body.sig.ret = true
/-- Override `entryDefId` to execute body `defId` as the root function. -/
noncomputable def cppExecForBody (p : CppProgram) (defId : Nat) : CppProgram :=
{ p with entryDefId := defId }
/-- Rung-0 C11 `ExecutionModel` parameterized by `policy` and the `records`
layout table, which admission requires to equal the program's own. Unbridged
until a Pass-2 correspondence to a reference C semantics lands
(`OracleGrade.unbridged "cpp_rung0_c11"`). -/
@[reducible] noncomputable def CppProfileRung0 (policy : CppLangPolicy)
(records : List CppRecordDef) :
ExecutionModel CppProgram CppBody CppSignature CppQuery CppVal CppMemory :=
{ profileId := "cpp_rung0_c11"
oracleGrade := .unbridged "cpp_rung0_c11"
programAdmitted := cppProgramAdmitted policy records
bodyAdmitted := cppBodyAdmitted
isPartialScope := CppProgram.isPartial
bodyAt := fun p defId => cppGetElem? p.bodies defId
uniqueIdentities := fun p => cppBodiesHaveUniqueIdentities p.bodies
bodyIdentity := CppBody.identity
bodyIsUnsafe := fun _ => true
bodyIsExternal := CppBody.isExternal
bodyMatchesSig := fun b sig => CppSignature.beq b.sig sig
modelGaps := defaultCppModelGaps
requiredGaps := fun _ => []
claimShapeGaps := fun _ => []
entryDom := CppEntryDom policy records
returnValid := CppReturnValid policy records
memValid := fun m => validCppMemory policy m = true
execForBody := cppExecForBody
wellFormed := CppWellFormed
produces := CppProduces
diverges := CppDiverges
faultsUB := CppFaultsUB }
/-- C11 verified contract entry alias. -/
abbrev CppVerifiedEntry :=
VerifiedEntry CppSignature CppQuery CppVal CppMemory
/-- C11 external callee stub alias. -/
abbrev CppAssumedStub :=
AssumedStub CppSignature CppQuery CppVal CppMemory
/-- C11 existential UB refutation entry alias. -/
abbrev CppRefutationEntry :=
RefutationEntry CppSignature CppQuery
/-- Model-pinned structured Rung-0 C11 verification obligation, fixing
`ExecutionModel` to `CppProfileRung0 policy records` inside `Trusted.*`. -/
@[reducible] def CppEnvelopeTheorem
(policy : CppLangPolicy)
(program : CppProgram)
(entries : List CppVerifiedEntry)
(stubs : List CppAssumedStub)
(refutations : List CppRefutationEntry)
(claimShapes : List ClaimShape)
(gaps : List DisclosedGap)
(records : List CppRecordDef) : Prop :=
EnvelopeTheorem
(mkEnvelope (CppProfileRung0 policy records) program entries stubs
refutations claimShapes gaps)
end Trusted.CppSemantics
end