Harden .olean companion validation, Pass 1/2 replay, and SpecPreflight (#382) Close `.olean` artifact parsing, companion-part validation, Pass 1/2 correspondence replay, and `SpecPreflight` parse-tree inspection gaps across `TrustedBoundary.lean`, `SpecPreflight.lean`, `trusted/audit/src/repo_audit.rs`, and `trusted/cargo-anneal/src/`: - Enforce pre-import `.olean*` and foundation `.ir.sig`/`.ir` binary region-chain checks (`validateOleanRegionChain`, `validateOleanPartsPreImport`) across Pass 1 `audit`, Pass 2 `correspondence-preflight` and `correspondence-audit` (traversing all reachable search-path imports, including transitive sysroot dependencies that a caller search-path entry could shadow, by parsing `.olean*` bytes directly without calling `CompactedRegion.read`), `target-audit`, and `SpecPreflight.lean` `target-consts`. Require `baseAddr % 65536 == 0`, `baseAddr + bytes.size < UInt64.size`, 8-byte-aligned in-bounds 56-byte `ModuleData` root objects on both primary and companion parts, non-sysroot `.ir`/`.ir.sig` rejection across Pass 1 and Pass 2 (verifying both the file and its containing directory reside under the sysroot and unlinking stray Pass 1 unsandboxed `.ir*` siblings in `repo_audit.rs`), and pre-import `isModule` consistency on the primary part before companion checks against preflight source metadata (`moduleIsModule` / `requireAllModuleIsModule` enforced fail-closed in both Rust and Lean, rejecting non-boolean flags). - Validate companion `.olean` / `.olean.server` / `.olean.private` parts uniformly across Pass 1 `audit`, Pass 2 `correspondence-audit` (including `.vendorMiri`), and `target-audit` via shared `validateCompanionOleanParts` (checking companion `imports`, header-inventory integrity, constant parity, and `extraConstNames` parity/collision guards), and check `extraConstNames` across all parts in `SpecPreflight.collectTargetConsts`. - Add an interim `sameConstantShape` parity check in `replayKernelEnv` (with a `FIXME` note pending a unified post-replay audit environment) so forged `.olean` metadata flags that survive kernel replay cannot diverge from replayed declarations. - Harden Pass 2 `.vendorMiri` auditing: enforce `extraConstNames` collision checks, companion validation, compiler-override checks (permitting `[init]` under `loadExts := false` while rejecting `implemented_by`, `extern`, `csimp`, `export`, `cpass`, `builtin_init`, `constant_fold`, and postponed entries), vendor alias validation (`validateVendorAliases`), and full axiom-cone replay of `vendorAlternateProofs` before the empty-correspondence early return in `verifyCorrConesAndClaims`. - Promote `.olean.server` and `.olean.private` sidecars (and discard `.ir` / `.ir.sig`) for `module`-mode modules compiled in Pass 2 `compile_pass2_dag_with_root`. - Tighten `SpecPreflight`, `TrustedBoundary`, `cargo-anneal`, and `ci/redteam/olean_audit.lean` syntax/header/transitive guards: reject `Name.anonymous` in `isValidSourceIdent` while validating Lean parser `hygieneInfoKind` nodes explicitly; inspect all comma- separated `open ... renaming` items via `getSepArgs` and assert `openRenamingItem` / `.isIdent`; persist `export` aliases across `... in ...`, `mutual ... end`, `section ... end`, and `namespace ... end` scopes under their absolute exported name (`exportNs ++ aliasId`, covering nested partial closes followed by reopening or `open`) with bounded-fixpoint explicit-alias expansion in `candidateOpenNamespaces`; collect optional `let rec` helpers in `structure` / `class` default field initializers; forbid `computedFields` / `computedField`, `sorryAx`, and direct or transitive `Std.Sync` / `Std.Sync.*` imports and constants uniformly across Lean preflight/audit, `toolchain.rs`, `ndjson_comparator.rs`, and `ci/redteam/olean_audit.lean`; and restrict `allowTheoryImportAll` (`import all Init.Data.Nat.Bitwise.Basic`) strictly to `Anneal.NatBitwise` across `inspectSource`, `inspectHeader`, `targetAudit`, and `target.rs`. - Update companion-part guard-mutation anchors in `ci/check_guard_mutation.py` to match `validateCompanionOleanParts` and add regression tests covering Pass 1/2 companion/alignment/shape/ vendor/shadowed-sysroot/foundation-IR checks, Pass 2 `module`-mode sidecar promotion, `target-audit` / `target-consts` alignment and companion `extraConstNames`, header and `Std.Sync` bans, compiled `structure` default `let rec` helper naming, multi-hop and nested-namespace `export` persistence, and `SpecPreflight` / repo parse-tree vectors. Agent-authored-by: AI agent acting on joshlf's behalf
diff --git a/ci/check_guard_mutation.py b/ci/check_guard_mutation.py index 425b980..53432a2 100644 --- a/ci/check_guard_mutation.py +++ b/ci/check_guard_mutation.py
@@ -13230,39 +13230,39 @@ guard_id="target_audit_reject_companion_extra_const", target_file="trusted/audit/TrustedBoundary.lean", mode="target-audit", - description="targetAudit rejects companion `.olean` constants absent from `.olean.private`", + description="validateCompanionOleanParts rejects companion `.olean` constants absent from `.olean.private`", anchor=( - " unless privConsts.contains ci.name do\n" - ' fail (s!"target companion constant {ci.name} missing from " ++\n' - ' s!"private inventory of {m.module}")' + " unless privConsts.contains ci.name do\n" + ' fail (s!"{ctxPrefix}companion constant {ci.name} missing from " ++\n' + ' s!"private inventory of {m}")' ), - replacement=" if false then\n pure ()", + replacement=" if false then\n pure ()", fixture_id="target_companion_extra_const", ), AuditBoundaryGuard( guard_id="target_audit_reject_companion_imports_mismatch", target_file="trusted/audit/TrustedBoundary.lean", mode="target-audit", - description="targetAudit rejects companion `.olean` parts whose imports differ from `.olean.private`", + description="validateCompanionOleanParts rejects companion `.olean` parts whose imports differ from `.olean.private`", anchor=( - " unless partData.imports == privData.imports do\n" - ' fail s!"mismatched target companion imports in {m.module}"' + " unless partData.imports == privData.imports do\n" + ' fail s!"mismatched {ctxPrefix}companion imports in {m}"' ), - replacement=" let _ := privData.imports", + replacement=" let _ := privData.imports", fixture_id="target_companion_imports_mismatch", ), AuditBoundaryGuard( guard_id="target_audit_reject_companion_const_mismatch", target_file="trusted/audit/TrustedBoundary.lean", mode="target-audit", - description="targetAudit rejects companion `.olean` constants inconsistent with `.olean.private`", + description="validateCompanionOleanParts rejects companion `.olean` constants inconsistent with `.olean.private`", anchor=( - " if let some privCi := privConsts.get? ci.name then\n" - " unless isValidCompanionConstant privData.isModule privCi ci do\n" - ' fail (s!"mismatched target companion constant {ci.name} " ++\n' - ' s!"in {m.module}")' + " if let some privCi := privConsts.get? ci.name then\n" + " unless isValidCompanionConstant privData.isModule privCi ci do\n" + ' fail (s!"mismatched {ctxPrefix}companion constant {ci.name} " ++\n' + ' s!"in {m}")' ), - replacement=" let _ := privData.isModule", + replacement=" let _ := privData.isModule", fixture_id="target_companion_const_mismatch", ), AuditBoundaryGuard(
diff --git a/ci/redteam/olean_audit.lean b/ci/redteam/olean_audit.lean index 6b40762..400582b 100644 --- a/ci/redteam/olean_audit.lean +++ b/ci/redteam/olean_audit.lean
@@ -65,6 +65,7 @@ private def forbiddenSysUvPrefixes : List Name := [`Init.System, `Std.Internal.UV, `Internal.UV, `Std.Async, `Std.Http, + `Std.Sync, `Lean.LoadDynlib, `Lean.loadDynlib, `Lean.loadPlugin, `Lean.Dynlib, `Dynlib, `Lean.Syntax, `Lean.TSyntax, `Lean.TSyntaxArray, `Lean.SourceInfo, `Lean.SyntaxNodeKind, `Lean.mkAtom, `Lean.mkIdent, `Lean.mkNode, @@ -169,7 +170,7 @@ forbiddenSysRoots.contains r || m == `Std || m == `Std.Internal || [`Init.System, `Init.Meta, `Std.Internal.UV, `Internal.UV, - `Std.Async, `Std.Http].any fun pre => m == pre || pre.isPrefixOf m + `Std.Async, `Std.Http, `Std.Sync].any fun pre => m == pre || pre.isPrefixOf m private def isAllowedImportForRole (role : String) (impMod : Name) : Bool := if isForbiddenImport impMod then @@ -580,7 +581,7 @@ `Lean.LoadDynlib, `Lean.loadDynlib, `Lean.loadPlugin, `Lean.Dynlib, `Lean.getGithash, `Lean.version, `Init.System, `Std.Internal.UV, `Internal.UV, `Std.Async, - `Std.Http, `Dynlib].any + `Std.Http, `Std.Sync, `Dynlib].any (fun pre => u == pre || pre.isPrefixOf u) then true else if r == `System then !isAllowedSysPlatform u else forbiddenPureIdentifiers.contains u
diff --git a/tests/audit/tests/boundary_audit.rs b/tests/audit/tests/boundary_audit.rs index 89c995f..640a2e2 100644 --- a/tests/audit/tests/boundary_audit.rs +++ b/tests/audit/tests/boundary_audit.rs
@@ -52,6 +52,8 @@ mod forged_olean_replay; #[path = "boundary_audit/foundation_and_sysroot.rs"] mod foundation_and_sysroot; +#[path = "boundary_audit/olean_companion_hardening.rs"] +mod olean_companion_hardening; #[path = "boundary_audit/pass1_cpp_semantics.rs"] mod pass1_cpp_semantics; #[path = "boundary_audit/pass1_mir_wp_gates.rs"]
diff --git a/tests/audit/tests/boundary_audit/compiler_overrides/module_parts.rs b/tests/audit/tests/boundary_audit/compiler_overrides/module_parts.rs index 0b4e1a6..934ffa7 100644 --- a/tests/audit/tests/boundary_audit/compiler_overrides/module_parts.rs +++ b/tests/audit/tests/boundary_audit/compiler_overrides/module_parts.rs
@@ -56,6 +56,9 @@ .unwrap(); assert!(srv.exists(), "{module} missing .olean.server"); assert!(prv.exists(), "{module} missing .olean.private"); + for ext in ["ir", "ir.sig"] { + let _ = fs::remove_file(theory_lib.join(format!("{rel}.{ext}"))); + } let arts = ModuleArtifacts::from_available( &BTreeMap::from([ ("olean", olean.to_string_lossy().into_owned()),
diff --git a/tests/audit/tests/boundary_audit/compiler_overrides/module_parts/vendor_and_ir_parts.rs b/tests/audit/tests/boundary_audit/compiler_overrides/module_parts/vendor_and_ir_parts.rs index d1b9ba9..517945a 100644 --- a/tests/audit/tests/boundary_audit/compiler_overrides/module_parts/vendor_and_ir_parts.rs +++ b/tests/audit/tests/boundary_audit/compiler_overrides/module_parts/vendor_and_ir_parts.rs
@@ -81,11 +81,11 @@ "{err_vendor}" ); - // 4(e). A hook stored only in `.ir` or only in `.ir.sig`, beside clean - // `.olean*` parts, fails closed in Pass 2 `"correspondence-audit"`, - // which reads `.ir*` parts through the search path. The Pass 1 - // artifact map that `cargo-anneal` stages holds only `.olean*` - // parts, and `"target-audit"` rejects target `.ir` parts. + // 4(e). Any `.ir` or `.ir.sig` sibling beside clean `.olean*` parts of a + // non-sysroot Pass 2 module fails closed pre-import in + // `"correspondence-audit"` (matching Pass 1 and `"target-audit"`), + // preventing `.ir*`-only hooks from ever being mmapped. + let _ = cpass_clean_mod; let ir_only_dir = theory_lib.join("Anneal/CleanModIrOnly"); let ir_sig_only_dir = theory_lib.join("Anneal/CleanModIrSigOnly"); for dir in [&ir_only_dir, &ir_sig_only_dir] { @@ -146,6 +146,11 @@ (1, "correspondence-audit"), "corr-{label}: {err_ir_corr}" ); - assert!(err_ir_corr.message.contains(cpass_clean_mod), "corr-{label}: {err_ir_corr}"); + assert!( + err_ir_corr + .message + .contains("companion artifact parts unsupported in Anneal.CleanMod"), + "corr-{label}: {err_ir_corr}" + ); } }
diff --git a/tests/audit/tests/boundary_audit/olean_companion_hardening.rs b/tests/audit/tests/boundary_audit/olean_companion_hardening.rs new file mode 100644 index 0000000..6525e82 --- /dev/null +++ b/tests/audit/tests/boundary_audit/olean_companion_hardening.rs
@@ -0,0 +1,1272 @@ +// 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. + +//! Pass 1 and Pass 2 `.olean` companion parity, pre-import alignment/header +//! checks, post-replay `sameConstantShape` parity, vendor Miri companion, +//! override, alias, and alternate-cone checks, and Pass 2 `module`-mode +//! sidecar promotion. + +use super::*; + +fn compile_3part_module( + checker: &mut Checker, + stage: &Path, + out_root: &Path, + src_root: &Path, + module: &str, + src_body: &str, + edges: Vec<ImportEdge>, +) -> (PathBuf, PathBuf, PathBuf) { + let rel = module.replace('.', "/"); + let src_path = src_root.join(format!("{rel}.lean")); + fs::create_dir_all(src_path.parent().unwrap()).unwrap(); + fs::write(&src_path, src_body).unwrap(); + let setup = checker.write_setup_json(module, &edges).unwrap(); + let out_o = out_root.join(format!("{rel}.olean")); + fs::create_dir_all(out_o.parent().unwrap()).unwrap(); + let lean_path = env::join_paths([stage.join("lib"), out_root.to_path_buf()]).unwrap(); + checker + .process_with_path( + &format!("compile-3part-{module}"), + &[ + "-j1".to_string(), + "-M2048".to_string(), + "-t0".to_string(), + "-R".to_string(), + src_root.to_string_lossy().into_owned(), + "--setup".to_string(), + setup.to_string_lossy().into_owned(), + "-o".to_string(), + out_o.to_string_lossy().into_owned(), + src_path.to_string_lossy().into_owned(), + ], + Some(&lean_path), + ) + .unwrap(); + let out_s = out_root.join(format!("{rel}.olean.server")); + let out_p = out_root.join(format!("{rel}.olean.private")); + assert!(out_o.exists() && out_s.exists() && out_p.exists()); + for ext in ["ir", "ir.sig"] { + let _ = fs::remove_file(out_root.join(format!("{rel}.{ext}"))); + } + (out_o, out_s, out_p) +} + +fn register_pass1_module(checker: &mut Checker, module: &str, dir: &Path, edges: &[ImportEdge]) { + let rel = module.replace('.', "/"); + let arts = ModuleArtifacts::from_available( + &BTreeMap::from([ + ("olean", dir.join(format!("{rel}.olean")).to_string_lossy().into_owned()), + ( + "olean.server", + dir.join(format!("{rel}.olean.server")).to_string_lossy().into_owned(), + ), + ( + "olean.private", + dir.join(format!("{rel}.olean.private")).to_string_lossy().into_owned(), + ), + ]), + "test", + String::new, + ) + .unwrap(); + let adm = checker.admitted_mut().unwrap(); + adm.artifacts.insert(module.to_string(), arts); + adm.graph.insert(module.to_string(), edges.to_vec()); +} + +fn unregister_pass1_module(checker: &mut Checker, module: &str) { + let adm = checker.admitted_mut().unwrap(); + adm.artifacts.remove(module); + adm.graph.remove(module); +} + +#[test] +fn rejects_forged_companions_alignment_and_recursor_shape_across_repo_passes() { + let fix = TempFixture::new(None); + let mut checker = fix.checker(); + checker.set_require_mir_wp(false); + checker.run().unwrap(); + let stage = checker.stage().to_path_buf(); + let lib_dir = stage.join("lib"); + let work_dir = stage.join("companion-hardening"); + let src_dir = work_dir.join("src"); + let clean_dir = work_dir.join("clean"); + fs::create_dir_all(&src_dir).unwrap(); + fs::create_dir_all(&clean_dir).unwrap(); + + let init_core_edge = ImportEdge { + module: "Init.Core".to_string(), + import_all: false, + is_exported: true, + is_meta: false, + }; + let (clean_o, clean_s, clean_p) = compile_3part_module( + &mut checker, + &stage, + &clean_dir, + &src_dir, + "Anneal.CompMod", + "module\nprelude\npublic import Init.Core\n@[expose] public section\n\ + def Anneal.CompMod.ok : Nat := 1\nend\n", + vec![init_core_edge.clone()], + ); + + // Forge 3 poisoned companion variants while keeping `.olean.private` clean: + // (a) injected `axiom` in `.olean` (part 0), + // (b) extra import in `.olean.server` (part 1), + // (c) forged `extraConstNames` entry in `.olean` (part 0). + let ax_dir = work_dir.join("forged-ax"); + let imp_dir = work_dir.join("forged-imp"); + let extra_dir = work_dir.join("forged-extra"); + for d in [&ax_dir, &imp_dir, &extra_dir] { + fs::create_dir_all(d.join("Anneal")).unwrap(); + } + let forge_script = format!( + "import Lean.Elab.Import\n\ + open Lean\n\ + def main : IO Unit := do\n\ + let parts ← readModuleDataParts #[{:?}, {:?}, {:?}]\n\ + let #[(md0, _), (md1, _), (md2, _)] := parts | throw <| IO.userError \"expected 3 parts\"\n\ + let badAx : ConstantInfo := .axiomInfo {{ name := `Anneal.CompMod.forgedAx, levelParams := [], type := .const `False [], isUnsafe := false }}\n\ + saveModuleDataParts `Anneal.CompMod #[\n\ + ({:?}, {{ md0 with constNames := md0.constNames.push badAx.name, constants := md0.constants.push badAx }}),\n\ + ({:?}, md1),\n\ + ({:?}, md2)]\n\ + saveModuleDataParts `Anneal.CompMod #[\n\ + ({:?}, md0),\n\ + ({:?}, {{ md1 with imports := md1.imports.push {{ module := `Init.Prelude }} }}),\n\ + ({:?}, md2)]\n\ + saveModuleDataParts `Anneal.CompMod #[\n\ + ({:?}, {{ md0 with extraConstNames := md0.extraConstNames.push `True.intro }}),\n\ + ({:?}, md1),\n\ + ({:?}, md2)]\n", + clean_o.to_string_lossy(), + clean_s.to_string_lossy(), + clean_p.to_string_lossy(), + ax_dir.join("Anneal/CompMod.olean").to_string_lossy(), + ax_dir.join("Anneal/CompMod.olean.server").to_string_lossy(), + ax_dir.join("Anneal/CompMod.olean.private").to_string_lossy(), + imp_dir.join("Anneal/CompMod.olean").to_string_lossy(), + imp_dir.join("Anneal/CompMod.olean.server").to_string_lossy(), + imp_dir.join("Anneal/CompMod.olean.private").to_string_lossy(), + extra_dir.join("Anneal/CompMod.olean").to_string_lossy(), + extra_dir.join("Anneal/CompMod.olean.server").to_string_lossy(), + extra_dir.join("Anneal/CompMod.olean.private").to_string_lossy(), + ); + run_lean_script( + &mut checker, + "forge-repo-companions", + &work_dir.join("forge_repo_companions.lean"), + &forge_script, + ); + + let comp_cases = [ + ( + "injected-axiom", + &ax_dir, + "companion constant Anneal.CompMod.forgedAx missing from private inventory of Anneal.CompMod", + ), + ("forged-imports", &imp_dir, "mismatched companion imports in Anneal.CompMod"), + ( + "forged-extra-const", + &extra_dir, + "companion extraConstName True.intro missing from private inventory of Anneal.CompMod", + ), + ]; + + checker.set_expected_is_module_for_test(BTreeMap::from([ + ("Trusted".to_string(), false), + ("Anneal.CompMod".to_string(), true), + ])); + for (label, dir, want) in comp_cases { + register_pass1_module(&mut checker, "Anneal.CompMod", dir, &[init_core_edge.clone()]); + let err1 = checker + .inspect(InspectorRequest::Audit { + trusted: vec!["Trusted".to_string()], + theory: vec!["Anneal.CompMod".to_string()], + module_tiers: BTreeMap::from([("Trusted".to_string(), TrustTier::Vetted)]), + }) + .unwrap_err(); + assert_eq!((err1.code, err1.phase.as_str()), (1, "audit"), "p1-{label}: {err1}"); + assert!(err1.message.contains(want), "p1-{label}: {err1}"); + unregister_pass1_module(&mut checker, "Anneal.CompMod"); + + let err2 = checker + .inspect(InspectorRequest::CorrespondenceAudit { + search_path: vec![lib_dir.clone(), dir.clone()], + trusted: vec!["Trusted".to_string()], + corr_trusted: Vec::new(), + theory: Vec::new(), + corr_theory: vec!["Anneal.CompMod".to_string()], + vendor_miri: Vec::new(), + module_tiers: BTreeMap::from([("Trusted".to_string(), TrustTier::Vetted)]), + }) + .unwrap_err(); + assert_eq!( + (err2.code, err2.phase.as_str()), + (1, "correspondence-audit"), + "p2-{label}: {err2}" + ); + assert!(err2.message.contains(want), "p2-{label}: {err2}"); + } + + // Pre-import `isModule` mismatch and unaligned root pointer in Pass 1 and + // Pass 2. + checker.set_expected_is_module_for_test(BTreeMap::from([ + ("Trusted".to_string(), false), + ("Anneal.CompMod".to_string(), false), + ])); + register_pass1_module(&mut checker, "Anneal.CompMod", &clean_dir, &[init_core_edge.clone()]); + let err_ismod1 = checker + .inspect(InspectorRequest::Audit { + trusted: vec!["Trusted".to_string()], + theory: vec!["Anneal.CompMod".to_string()], + module_tiers: BTreeMap::from([("Trusted".to_string(), TrustTier::Vetted)]), + }) + .unwrap_err(); + assert_eq!((err_ismod1.code, err_ismod1.phase.as_str()), (1, "audit"), "{err_ismod1}"); + assert!( + err_ismod1.message.contains("companion artifact parts unsupported in Anneal.CompMod"), + "{err_ismod1}" + ); + unregister_pass1_module(&mut checker, "Anneal.CompMod"); + + let err_ismod2 = checker + .inspect(InspectorRequest::CorrespondenceAudit { + search_path: vec![lib_dir.clone(), clean_dir.clone()], + trusted: vec!["Trusted".to_string()], + corr_trusted: Vec::new(), + theory: Vec::new(), + corr_theory: vec!["Anneal.CompMod".to_string()], + vendor_miri: Vec::new(), + module_tiers: BTreeMap::from([("Trusted".to_string(), TrustTier::Vetted)]), + }) + .unwrap_err(); + assert_eq!( + (err_ismod2.code, err_ismod2.phase.as_str()), + (1, "correspondence-audit"), + "{err_ismod2}" + ); + assert!( + err_ismod2.message.contains("companion artifact parts unsupported in Anneal.CompMod"), + "{err_ismod2}" + ); + + let unaligned_dir = work_dir.join("unaligned"); + fs::create_dir_all(unaligned_dir.join("Anneal")).unwrap(); + let mut bad_bytes = fs::read(&clean_o).unwrap(); + let base0 = u64::from_le_bytes(bad_bytes[80..88].try_into().unwrap()); + bad_bytes[88..96].copy_from_slice(&(base0 + 88 + 9).to_le_bytes()); + fs::write(unaligned_dir.join("Anneal/CompMod.olean"), &bad_bytes).unwrap(); + fs::copy(&clean_s, unaligned_dir.join("Anneal/CompMod.olean.server")).unwrap(); + fs::copy(&clean_p, unaligned_dir.join("Anneal/CompMod.olean.private")).unwrap(); + + checker.set_expected_is_module_for_test(BTreeMap::from([ + ("Trusted".to_string(), false), + ("Anneal.CompMod".to_string(), true), + ])); + register_pass1_module( + &mut checker, + "Anneal.CompMod", + &unaligned_dir, + &[init_core_edge.clone()], + ); + let err_align1 = checker + .inspect(InspectorRequest::Audit { + trusted: vec!["Trusted".to_string()], + theory: vec!["Anneal.CompMod".to_string()], + module_tiers: BTreeMap::from([("Trusted".to_string(), TrustTier::Vetted)]), + }) + .unwrap_err(); + assert_eq!((err_align1.code, err_align1.phase.as_str()), (1, "audit"), "{err_align1}"); + assert!( + err_align1.message.contains("unaligned olean root pointer in Anneal.CompMod"), + "{err_align1}" + ); + unregister_pass1_module(&mut checker, "Anneal.CompMod"); + + let err_align2 = checker + .inspect(InspectorRequest::CorrespondenceAudit { + search_path: vec![lib_dir.clone(), unaligned_dir], + trusted: vec!["Trusted".to_string()], + corr_trusted: Vec::new(), + theory: Vec::new(), + corr_theory: vec!["Anneal.CompMod".to_string()], + vendor_miri: Vec::new(), + module_tiers: BTreeMap::from([("Trusted".to_string(), TrustTier::Vetted)]), + }) + .unwrap_err(); + assert_eq!( + (err_align2.code, err_align2.phase.as_str()), + (1, "correspondence-audit"), + "{err_align2}" + ); + assert!( + err_align2.message.contains("unaligned olean root pointer in Anneal.CompMod"), + "{err_align2}" + ); + + // Forged unaligned companion `.olean.server` root pointer fails closed + // pre-import in Pass 1 and Pass 2. + let bad_comp_root_dir = work_dir.join("bad_comp_root"); + fs::create_dir_all(bad_comp_root_dir.join("Anneal")).unwrap(); + fs::copy(&clean_o, bad_comp_root_dir.join("Anneal/CompMod.olean")).unwrap(); + let mut bad_srv = fs::read(&clean_s).unwrap(); + let srv_base = u64::from_le_bytes(bad_srv[80..88].try_into().unwrap()); + bad_srv[88..96].copy_from_slice(&(srv_base + 88 + 9).to_le_bytes()); + fs::write(bad_comp_root_dir.join("Anneal/CompMod.olean.server"), &bad_srv).unwrap(); + fs::copy(&clean_p, bad_comp_root_dir.join("Anneal/CompMod.olean.private")).unwrap(); + register_pass1_module( + &mut checker, + "Anneal.CompMod", + &bad_comp_root_dir, + &[init_core_edge.clone()], + ); + let err_comp_root1 = checker + .inspect(InspectorRequest::Audit { + trusted: vec!["Trusted".to_string()], + theory: vec!["Anneal.CompMod".to_string()], + module_tiers: BTreeMap::from([("Trusted".to_string(), TrustTier::Vetted)]), + }) + .unwrap_err(); + assert_eq!((err_comp_root1.code, err_comp_root1.phase.as_str()), (1, "audit"), "{err_comp_root1}"); + assert!( + err_comp_root1.message.contains("unaligned olean companion root pointer in Anneal.CompMod"), + "{err_comp_root1}" + ); + unregister_pass1_module(&mut checker, "Anneal.CompMod"); + let err_comp_root2 = checker + .inspect(InspectorRequest::CorrespondenceAudit { + search_path: vec![lib_dir.clone(), bad_comp_root_dir], + trusted: vec!["Trusted".to_string()], + corr_trusted: Vec::new(), + theory: Vec::new(), + corr_theory: vec!["Anneal.CompMod".to_string()], + vendor_miri: Vec::new(), + module_tiers: BTreeMap::from([("Trusted".to_string(), TrustTier::Vetted)]), + }) + .unwrap_err(); + assert_eq!( + (err_comp_root2.code, err_comp_root2.phase.as_str()), + (1, "correspondence-audit"), + "{err_comp_root2}" + ); + assert!( + err_comp_root2.message.contains("unaligned olean companion root pointer in Anneal.CompMod"), + "{err_comp_root2}" + ); + + // Forged foundation `.ir.sig` with an unaligned base address fails closed + // pre-import in Pass 1 `"audit"` before `importEnv` mmaps it. + let orig_init_core = checker + .admitted_mut() + .unwrap() + .artifacts + .get("Init.Core") + .cloned() + .expect("Init.Core must be in admitted foundation artifacts"); + { + let mut forged_ir_bytes = fs::read(&clean_o).unwrap(); + let ir_base = u64::from_le_bytes(forged_ir_bytes[80..88].try_into().unwrap()); + forged_ir_bytes[80..88].copy_from_slice(&(ir_base + 8).to_le_bytes()); + let bad_ir_sig = work_dir.join("ForInitCore.ir.sig"); + fs::write(&bad_ir_sig, &forged_ir_bytes).unwrap(); + let mut forged_arts = orig_init_core.clone(); + forged_arts.ir_parts = vec![bad_ir_sig.to_string_lossy().into_owned()]; + checker.admitted_mut().unwrap().artifacts.insert("Init.Core".to_string(), forged_arts); + let err_fnd_ir = checker + .inspect(InspectorRequest::Audit { + trusted: vec!["Trusted".to_string()], + theory: Vec::new(), + module_tiers: BTreeMap::from([("Trusted".to_string(), TrustTier::Vetted)]), + }) + .unwrap_err(); + checker.admitted_mut().unwrap().artifacts.insert("Init.Core".to_string(), orig_init_core); + assert_eq!((err_fnd_ir.code, err_fnd_ir.phase.as_str()), (1, "audit"), "{err_fnd_ir}"); + assert!( + err_fnd_ir.message.contains("unaligned olean base address in Init.Core"), + "{err_fnd_ir}" + ); + } + + // Non-sysroot `.ir.sig` or `.ir` siblings beside clean `.olean*` parts + // fail closed pre-import in Pass 2 before `importCorrEnv` mmaps them. + let bad_ir_sig_dir = work_dir.join("bad_ir_sig"); + fs::create_dir_all(bad_ir_sig_dir.join("Anneal")).unwrap(); + fs::copy(&clean_o, bad_ir_sig_dir.join("Anneal/CompMod.olean")).unwrap(); + fs::copy(&clean_s, bad_ir_sig_dir.join("Anneal/CompMod.olean.server")).unwrap(); + fs::copy(&clean_p, bad_ir_sig_dir.join("Anneal/CompMod.olean.private")).unwrap(); + fs::write(bad_ir_sig_dir.join("Anneal/CompMod.ir.sig"), &bad_bytes).unwrap(); + let err_ir_sig = checker + .inspect(InspectorRequest::CorrespondenceAudit { + search_path: vec![lib_dir.clone(), bad_ir_sig_dir], + trusted: vec!["Trusted".to_string()], + corr_trusted: Vec::new(), + theory: Vec::new(), + corr_theory: vec!["Anneal.CompMod".to_string()], + vendor_miri: Vec::new(), + module_tiers: BTreeMap::from([("Trusted".to_string(), TrustTier::Vetted)]), + }) + .unwrap_err(); + assert_eq!( + (err_ir_sig.code, err_ir_sig.phase.as_str()), + (1, "correspondence-audit"), + "{err_ir_sig}" + ); + assert!( + err_ir_sig + .message + .contains("companion artifact parts unsupported in Anneal.CompMod"), + "{err_ir_sig}" + ); + + let orphan_ir_dir = work_dir.join("orphan_ir"); + fs::create_dir_all(orphan_ir_dir.join("Anneal")).unwrap(); + fs::copy(&clean_o, orphan_ir_dir.join("Anneal/CompMod.olean")).unwrap(); + fs::copy(&clean_s, orphan_ir_dir.join("Anneal/CompMod.olean.server")).unwrap(); + fs::copy(&clean_p, orphan_ir_dir.join("Anneal/CompMod.olean.private")).unwrap(); + fs::write(orphan_ir_dir.join("Anneal/CompMod.ir"), &bad_bytes).unwrap(); + let err_orphan_ir = checker + .inspect(InspectorRequest::CorrespondenceAudit { + search_path: vec![lib_dir.clone(), orphan_ir_dir], + trusted: vec!["Trusted".to_string()], + corr_trusted: Vec::new(), + theory: Vec::new(), + corr_theory: vec!["Anneal.CompMod".to_string()], + vendor_miri: Vec::new(), + module_tiers: BTreeMap::from([("Trusted".to_string(), TrustTier::Vetted)]), + }) + .unwrap_err(); + assert_eq!( + (err_orphan_ir.code, err_orphan_ir.phase.as_str()), + (1, "correspondence-audit"), + "{err_orphan_ir}" + ); + assert!( + err_orphan_ir + .message + .contains("companion artifact parts unsupported in Anneal.CompMod"), + "{err_orphan_ir}" + ); + + // Transitively imported unlisted modules on the Pass 2 search path are also + // pre-import validated before `importCorrEnv` mmaps them. + let trans_dir = work_dir.join("trans_unlisted"); + let trans_src = work_dir.join("trans_src"); + fs::create_dir_all(&trans_dir).unwrap(); + fs::create_dir_all(&trans_src).unwrap(); + let (td_o, _, _) = compile_3part_module( + &mut checker, + &stage, + &trans_dir, + &trans_src, + "Anneal.TransDep", + "module\nprelude\npublic import Init.Core\n@[expose] public section\n\ + def Anneal.TransDep.v : Nat := 1\nend\n", + vec![init_core_edge.clone()], + ); + register_pass1_module( + &mut checker, + "Anneal.TransDep", + &trans_dir, + &[init_core_edge.clone()], + ); + compile_3part_module( + &mut checker, + &stage, + &trans_dir, + &trans_src, + "Anneal.TransRoot", + "module\nprelude\npublic import Init.Core\nimport Anneal.TransDep\n\ + @[expose] public section\ndef Anneal.TransRoot.v : Nat := 2\nend\n", + vec![ + init_core_edge.clone(), + ImportEdge { + module: "Anneal.TransDep".to_string(), + import_all: false, + is_exported: false, + is_meta: false, + }, + ], + ); + unregister_pass1_module(&mut checker, "Anneal.TransDep"); + let mut bad_td = fs::read(&td_o).unwrap(); + let td_base = u64::from_le_bytes(bad_td[80..88].try_into().unwrap()); + bad_td[88..96].copy_from_slice(&(td_base + 88 + 9).to_le_bytes()); + fs::write(&td_o, &bad_td).unwrap(); + checker.set_expected_is_module_for_test(BTreeMap::new()); + let err_trans = checker + .inspect(InspectorRequest::CorrespondenceAudit { + search_path: vec![lib_dir.clone(), trans_dir], + trusted: vec!["Trusted".to_string()], + corr_trusted: Vec::new(), + theory: Vec::new(), + corr_theory: vec!["Anneal.TransRoot".to_string()], + vendor_miri: Vec::new(), + module_tiers: BTreeMap::from([("Trusted".to_string(), TrustTier::Vetted)]), + }) + .unwrap_err(); + assert_eq!( + (err_trans.code, err_trans.phase.as_str()), + (1, "correspondence-audit"), + "{err_trans}" + ); + assert!( + err_trans.message.contains("unaligned olean root pointer in Anneal.TransDep"), + "{err_trans}" + ); + + // Shadowed transitive sysroot dependencies (`Anneal.SysDepRoot` -> + // sysroot `Lean.Meta.Tactic.Grind.VarRename` -> shadowed + // `Std.Data.HashSet`) are also pre-import validated before `importCorrEnv` + // mmaps them in both `"correspondence-audit"` and + // `"correspondence-preflight"`. + let sysdep_dir = work_dir.join("sysdep_root"); + let sysdep_src = work_dir.join("sysdep_src"); + let shadow_dir = work_dir.join("sysroot_shadow"); + fs::create_dir_all(sysdep_dir.join("Anneal")).unwrap(); + fs::create_dir_all(sysdep_src.join("Anneal")).unwrap(); + fs::create_dir_all(shadow_dir.join("Std/Data")).unwrap(); + let sysdep_lean = sysdep_src.join("Anneal/SysDepRoot.lean"); + fs::write( + &sysdep_lean, + "prelude\nimport Init.Core\nimport Lean.Meta.Tactic.Grind.VarRename\n\ + def Anneal.SysDepRoot.v : Nat := 1\n", + ) + .unwrap(); + let sysdep_olean = sysdep_dir.join("Anneal/SysDepRoot.olean"); + let sysdep_path = env::join_paths([&lib_dir, &sysdep_dir]).unwrap(); + checker + .process_with_path( + "compile-sysdep-root", + &[ + "-j1".to_string(), + "-M2048".to_string(), + "-t0".to_string(), + "-R".to_string(), + sysdep_src.to_string_lossy().into_owned(), + "-o".to_string(), + sysdep_olean.to_string_lossy().into_owned(), + sysdep_lean.to_string_lossy().into_owned(), + ], + Some(&sysdep_path), + ) + .unwrap(); + let mut shadow_bytes = fs::read(&sysdep_olean).unwrap(); + let sh_base = u64::from_le_bytes(shadow_bytes[80..88].try_into().unwrap()); + shadow_bytes[88..96].copy_from_slice(&(sh_base + 88 + 9).to_le_bytes()); + fs::write(shadow_dir.join("Std/Data/HashSet.olean"), &shadow_bytes).unwrap(); + let err_shadow_audit = checker + .inspect(InspectorRequest::CorrespondenceAudit { + search_path: vec![lib_dir.clone(), sysdep_dir.clone(), shadow_dir.clone()], + trusted: vec!["Trusted".to_string()], + corr_trusted: Vec::new(), + theory: Vec::new(), + corr_theory: vec!["Anneal.SysDepRoot".to_string()], + vendor_miri: Vec::new(), + module_tiers: BTreeMap::from([("Trusted".to_string(), TrustTier::Vetted)]), + }) + .unwrap_err(); + assert_eq!( + (err_shadow_audit.code, err_shadow_audit.phase.as_str()), + (1, "correspondence-audit"), + "{err_shadow_audit}" + ); + assert!( + err_shadow_audit + .message + .contains("unaligned olean root pointer in Std.Data.HashSet"), + "{err_shadow_audit}" + ); + + // Repository-source preflight persists `export` aliases out of `in`, + // `mutual`, `section ... end`, and `namespace ... end` wrappers (including + // nested partial closes and multi-hop chains) and bans `Std.Sync.*`. + for (label, body, want) in [ + ( + "repo-in-export", + "prelude\nimport Init.Core\nopen Nat in\nexport Std (Internal)\n\ + def Anneal.badUv : Nat := Internal.UV.Loop.alive\n", + "Internal.UV", + ), + ( + "repo-mutual-export", + "prelude\nimport Init.Core\nmutual\nexport Std (Internal)\nend\n\ + def Anneal.badMutUv : Nat := Internal.UV.Loop.alive\n", + "Internal.UV", + ), + ( + "repo-section-export", + "prelude\nimport Init.Core\nsection\nexport Std (Internal)\nend\n\ + def Anneal.badSecUv : Nat := Internal.UV.Loop.alive\n", + "Internal.UV", + ), + ( + "repo-namespace-export", + "prelude\nimport Init.Core\nnamespace Anneal.ExWrap\n\ + export Std (Internal)\nend Anneal.ExWrap\n\ + def Anneal.badNsUv : Nat := Anneal.ExWrap.Internal.UV.Loop.alive\n", + "Internal.UV", + ), + ( + "repo-namespace-reopen-export", + "prelude\nimport Init.Core\nnamespace Anneal.ExRe\n\ + export Std (Internal)\nend Anneal.ExRe\nnamespace Anneal.ExRe\n\ + def badReUv : Nat := Internal.UV.Loop.alive\nend Anneal.ExRe\n", + "Internal.UV", + ), + ( + "repo-nested-partial-close-reopen", + "prelude\nimport Init.Core\nnamespace Anneal\nnamespace ExRe\n\ + export Std (Internal)\nend ExRe\nnamespace ExRe\n\ + def badReUv : Nat := Internal.UV.Loop.alive\nend ExRe\nend Anneal\n", + "Internal.UV", + ), + ( + "repo-nested-partial-close-open", + "prelude\nimport Init.Core\nnamespace Anneal\nnamespace ExOp\n\ + export Std (Internal)\nend ExOp\nopen ExOp\n\ + def badOpUv : Nat := Internal.UV.Loop.alive\nend Anneal\n", + "Internal.UV", + ), + ( + "repo-3hop-export", + "prelude\nimport Init.Core\nnamespace Anneal.H1\nexport Std (Internal)\n\ + end Anneal.H1\nnamespace Anneal.H2\nexport Anneal.H1 (Internal)\n\ + end Anneal.H2\nnamespace Anneal.H3\nexport Anneal.H2 (Internal)\n\ + end Anneal.H3\ndef Anneal.bad3Hop : Nat := Anneal.H3.Internal.UV.Loop.alive\n", + "Internal.UV", + ), + ( + "repo-std-sync", + "prelude\nimport Init.Core\ndef Anneal.badSync : Nat := Std.Sync.Mutex\n", + "Std.Sync", + ), + ] { + let p = work_dir.join(format!("{label}.lean")); + fs::write(&p, body).unwrap(); + let err_pf = checker + .inspect(InspectorRequest::Preflight { + sources: vec![("Anneal.ExportLeak".to_string(), p)], + base_trusted_sources: Vec::new(), + allow_local_semireducible: false, + }) + .unwrap_err(); + assert_eq!((err_pf.code, err_pf.phase.as_str()), (1, "preflight"), "{label}: {err_pf}"); + assert!(err_pf.message.contains(want), "{label}: {err_pf}"); + } + + // Forged inductive metadata (`isRec := true` on a non-recursive inductive) + // passes `Environment.replay` (which re-derives `isRec` in the kernel) + // and fails closed in `replayKernelEnv` via `sameConstantShape`. + checker.set_expected_is_module_for_test(BTreeMap::new()); + let ind_out_dir = work_dir.join("ind-orig"); + fs::create_dir_all(&ind_out_dir).unwrap(); + compile_forged_module( + &mut checker, + &src_dir, + &ind_out_dir, + &[], + "Trusted.BadInd", + "prelude\nimport Init.Core\ninductive Trusted.BadInd where | mk\n", + ); + let ind_olean = ind_out_dir.join("Trusted/BadInd.olean"); + let forged_rec_olean = work_dir.join("Trusted/BadInd.olean"); + fs::create_dir_all(forged_rec_olean.parent().unwrap()).unwrap(); + let forge_rec_script = format!( + "import Lean.Elab.Import\n\ + open Lean\n\ + def main : IO Unit := do\n\ + let (d, _) ← readModuleData {:?}\n\ + let cs := d.constants.map fun ci =>\n\ + match ci with\n\ + | .inductInfo ind =>\n\ + if ind.name == `Trusted.BadInd then\n\ + .inductInfo {{ ind with isRec := true }}\n\ + else ci\n\ + | _ => ci\n\ + saveModuleData {:?} `Trusted.BadInd {{ d with constants := cs }}\n", + ind_olean.to_string_lossy(), + forged_rec_olean.to_string_lossy(), + ); + run_lean_script( + &mut checker, + "forge-bad-rec", + &work_dir.join("forge_bad_rec.lean"), + &forge_rec_script, + ); + let rec_arts = ModuleArtifacts::from_available( + &BTreeMap::from([("olean", forged_rec_olean.to_string_lossy().into_owned())]), + "test", + String::new, + ) + .unwrap(); + { + let adm = checker.admitted_mut().unwrap(); + adm.artifacts.insert("Trusted.BadInd".to_string(), rec_arts); + adm.graph.insert("Trusted.BadInd".to_string(), vec![init_core_edge]); + } + let err_rec = checker + .inspect(InspectorRequest::Audit { + trusted: vec!["Trusted".to_string(), "Trusted.BadInd".to_string()], + theory: Vec::new(), + module_tiers: BTreeMap::from([ + ("Trusted".to_string(), TrustTier::Vetted), + ("Trusted.BadInd".to_string(), TrustTier::Vetted), + ]), + }) + .unwrap_err(); + assert_eq!((err_rec.code, err_rec.phase.as_str()), (1, "audit"), "{err_rec}"); + assert!( + err_rec + .message + .contains("replayed declaration Trusted.BadInd differs from audited payload"), + "{err_rec}" + ); + unregister_pass1_module(&mut checker, "Trusted.BadInd"); + + // Run `"correspondence-preflight"` shadowed-sysroot check last because + // `InspectorRequest::CorrespondencePreflight` enables `RequireBwrap` on + // the shared `Checker` instance. + let err_shadow_pf = checker + .inspect(InspectorRequest::CorrespondencePreflight { + search_path: vec![lib_dir, sysdep_dir, shadow_dir], + trusted: vec!["Trusted".to_string()], + theory: vec!["Anneal.SysDepRoot".to_string()], + vendor_miri: Vec::new(), + base_trusted_sources: vec![( + "Trusted".to_string(), + fix.root.join("trusted/lean/Trusted.lean"), + )], + sources: Vec::new(), + }) + .unwrap_err(); + assert_eq!( + (err_shadow_pf.code, err_shadow_pf.phase.as_str()), + (1, "correspondence-preflight"), + "{err_shadow_pf}" + ); + assert!( + err_shadow_pf + .message + .contains("unaligned olean root pointer in Std.Data.HashSet"), + "{err_shadow_pf}" + ); +} + +#[test] +fn rejects_vendor_miri_companions_overrides_aliases_and_alternate_cone_and_promotes_pass2_module_sidecars() + { + let fix = TempFixture::new(Some( + "-- anneal-trust-tier: vetted\nprelude\nimport Init.NotationExtra\n\ + def Trusted.seed : Nat := 1\n", + )); + let mut checker = fix.checker(); + checker.set_require_mir_wp(false); + checker.run().unwrap(); + let stage = checker.stage().to_path_buf(); + let lib_dir = stage.join("lib"); + let work_dir = stage.join("vendor-hardening"); + let src_dir = work_dir.join("src"); + let clean_dir = work_dir.join("clean"); + fs::create_dir_all(&src_dir).unwrap(); + fs::create_dir_all(&clean_dir).unwrap(); + + let init_core_edge = ImportEdge { + module: "Init.Core".to_string(), + import_all: false, + is_exported: true, + is_meta: false, + }; + let (v_o, v_s, v_p) = compile_3part_module( + &mut checker, + &stage, + &clean_dir, + &src_dir, + "Miri.VendorMod", + "module\nprelude\npublic import Init.Core\n@[expose] public section\n\ + def Miri.VendorMod.v : Nat := 1\nend\n", + vec![init_core_edge.clone()], + ); + + let v_ax_dir = work_dir.join("vendor-ax"); + let v_ov_dir = work_dir.join("vendor-ov"); + let v_export_hook_dir = work_dir.join("vendor-export-hook"); + let v_alias_dir = work_dir.join("vendor-alias"); + let v_alias_kern_dir = work_dir.join("vendor-alias-kernel"); + let v_alias_repo_dir = work_dir.join("vendor-alias-repo"); + let v_alias_sorry_dir = work_dir.join("vendor-alias-sorry"); + let v_extra_dir = work_dir.join("vendor-extra-collision"); + for d in [ + &v_ax_dir, + &v_ov_dir, + &v_export_hook_dir, + &v_alias_dir, + &v_alias_kern_dir, + &v_alias_repo_dir, + &v_alias_sorry_dir, + &v_extra_dir, + ] { + fs::create_dir_all(d.join("Miri")).unwrap(); + } + + let forge_vendor = format!( + "import Lean.Compiler.ExportAttr\n\ + import Lean.Compiler.ImplementedByAttr\n\ + import Lean.Elab.Import\n\ + open Lean\n\ + def main : IO Unit := do\n\ + let parts ← readModuleDataParts #[{:?}, {:?}, {:?}]\n\ + let #[(md0, _), (md1, _), (md2, _)] := parts | throw <| IO.userError \"expected 3 parts\"\n\ + let badAx : ConstantInfo := .axiomInfo {{ name := `Miri.VendorMod.forgedAx, levelParams := [], type := .const `False [], isUnsafe := false }}\n\ + saveModuleDataParts `Miri.VendorMod #[\n\ + ({:?}, {{ md0 with constNames := md0.constNames.push badAx.name, constants := md0.constants.push badAx }}),\n\ + ({:?}, md1),\n\ + ({:?}, md2)]\n\ + let implEntries : Array (Name × Name) := #[(`Miri.VendorMod.v, `Miri.VendorMod.v)]\n\ + let badImplExt : Name × Array EnvExtensionEntry := (Compiler.implementedByAttr.ext.name, unsafe (unsafeCast implEntries))\n\ + saveModuleDataParts `Miri.VendorMod #[\n\ + ({:?}, {{ md0 with entries := md0.entries.push badImplExt }}),\n\ + ({:?}, md1),\n\ + ({:?}, md2)]\n\ + let expEntries : Array (Name × Name) := #[(`Miri.VendorMod.v, `c_vendor_hook)]\n\ + let badExpExt : Name × Array EnvExtensionEntry := (exportAttr.ext.name, unsafe (unsafeCast expEntries))\n\ + saveModuleDataParts `Miri.VendorMod #[\n\ + ({:?}, {{ md0 with entries := md0.entries.push badExpExt }}),\n\ + ({:?}, md1),\n\ + ({:?}, md2)]\n\ + let aliasEntries : Array (Name × Name) := #[(`Trusted.spoofed, `Miri.VendorMod.v)]\n\ + let badAliasExt : Name × Array EnvExtensionEntry := (Lean.aliasExtension.name, unsafe (unsafeCast aliasEntries))\n\ + saveModuleDataParts `Miri.VendorMod #[\n\ + ({:?}, {{ md0 with entries := md0.entries.push badAliasExt }}),\n\ + ({:?}, md1),\n\ + ({:?}, md2)]\n\ + let kernAliasEntries : Array (Name × Name) := #[(`Nat.spoofed, `Miri.VendorMod.v)]\n\ + let badKernAliasExt : Name × Array EnvExtensionEntry := (Lean.aliasExtension.name, unsafe (unsafeCast kernAliasEntries))\n\ + saveModuleDataParts `Miri.VendorMod #[\n\ + ({:?}, {{ md0 with entries := md0.entries.push badKernAliasExt }}),\n\ + ({:?}, md1),\n\ + ({:?}, md2)]\n\ + let repoAliasEntries : Array (Name × Name) := #[(`Miri.VendorMod.leak, `Trusted.seed)]\n\ + let badRepoAliasExt : Name × Array EnvExtensionEntry := (Lean.aliasExtension.name, unsafe (unsafeCast repoAliasEntries))\n\ + saveModuleDataParts `Miri.VendorMod #[\n\ + ({:?}, {{ md0 with entries := md0.entries.push badRepoAliasExt }}),\n\ + ({:?}, md1),\n\ + ({:?}, md2)]\n\ + let sorryAliasEntries : Array (Name × Name) := #[(`Miri.VendorMod.badSorry, `sorryAx)]\n\ + let badSorryAliasExt : Name × Array EnvExtensionEntry := (Lean.aliasExtension.name, unsafe (unsafeCast sorryAliasEntries))\n\ + saveModuleDataParts `Miri.VendorMod #[\n\ + ({:?}, {{ md0 with entries := md0.entries.push badSorryAliasExt }}),\n\ + ({:?}, md1),\n\ + ({:?}, md2)]\n\ + saveModuleDataParts `Miri.VendorMod #[\n\ + ({:?}, {{ md0 with extraConstNames := md0.extraConstNames.push `True.intro }}),\n\ + ({:?}, {{ md1 with extraConstNames := md1.extraConstNames.push `True.intro }}),\n\ + ({:?}, {{ md2 with extraConstNames := md2.extraConstNames.push `True.intro }})]\n", + v_o.to_string_lossy(), + v_s.to_string_lossy(), + v_p.to_string_lossy(), + v_ax_dir.join("Miri/VendorMod.olean").to_string_lossy(), + v_ax_dir.join("Miri/VendorMod.olean.server").to_string_lossy(), + v_ax_dir.join("Miri/VendorMod.olean.private").to_string_lossy(), + v_ov_dir.join("Miri/VendorMod.olean").to_string_lossy(), + v_ov_dir.join("Miri/VendorMod.olean.server").to_string_lossy(), + v_ov_dir.join("Miri/VendorMod.olean.private").to_string_lossy(), + v_export_hook_dir.join("Miri/VendorMod.olean").to_string_lossy(), + v_export_hook_dir.join("Miri/VendorMod.olean.server").to_string_lossy(), + v_export_hook_dir.join("Miri/VendorMod.olean.private").to_string_lossy(), + v_alias_dir.join("Miri/VendorMod.olean").to_string_lossy(), + v_alias_dir.join("Miri/VendorMod.olean.server").to_string_lossy(), + v_alias_dir.join("Miri/VendorMod.olean.private").to_string_lossy(), + v_alias_kern_dir.join("Miri/VendorMod.olean").to_string_lossy(), + v_alias_kern_dir.join("Miri/VendorMod.olean.server").to_string_lossy(), + v_alias_kern_dir.join("Miri/VendorMod.olean.private").to_string_lossy(), + v_alias_repo_dir.join("Miri/VendorMod.olean").to_string_lossy(), + v_alias_repo_dir.join("Miri/VendorMod.olean.server").to_string_lossy(), + v_alias_repo_dir.join("Miri/VendorMod.olean.private").to_string_lossy(), + v_alias_sorry_dir.join("Miri/VendorMod.olean").to_string_lossy(), + v_alias_sorry_dir.join("Miri/VendorMod.olean.server").to_string_lossy(), + v_alias_sorry_dir.join("Miri/VendorMod.olean.private").to_string_lossy(), + v_extra_dir.join("Miri/VendorMod.olean").to_string_lossy(), + v_extra_dir.join("Miri/VendorMod.olean.server").to_string_lossy(), + v_extra_dir.join("Miri/VendorMod.olean.private").to_string_lossy(), + ); + run_lean_script( + &mut checker, + "forge-vendor-miri", + &work_dir.join("forge_vendor_miri.lean"), + &forge_vendor, + ); + + for (label, dir, want) in [ + ( + "vendor-companion-axiom", + &v_ax_dir, + "companion constant Miri.VendorMod.forgedAx missing from private inventory of Miri.VendorMod", + ), + ( + "vendor-impl-override", + &v_ov_dir, + "unchecked compiler implemented_by override on Miri.VendorMod.v in Miri.VendorMod", + ), + ( + "vendor-non-init-export-hook", + &v_export_hook_dir, + "unchecked compiler export override on Miri.VendorMod.v in Miri.VendorMod", + ), + ( + "vendor-reserved-alias", + &v_alias_dir, + "external module Miri.VendorMod cannot declare constant Trusted.spoofed in reserved Trusted namespace", + ), + ( + "vendor-reserved-kernel-alias", + &v_alias_kern_dir, + "vendor Miri module Miri.VendorMod cannot export alias Nat.spoofed in reserved kernel namespace Nat", + ), + ( + "vendor-alias-to-repo", + &v_alias_repo_dir, + "authority violation: Miri.VendorMod.leak references Trusted.seed from Trusted", + ), + ( + "vendor-alias-sorry-target", + &v_alias_sorry_dir, + "disallowed vendor Miri export target sorryAx in Miri.VendorMod", + ), + ( + "vendor-extra-const-collision", + &v_extra_dir, + "uninventoried kernel compiler helper True.intro", + ), + ] { + let err = checker + .inspect(InspectorRequest::CorrespondenceAudit { + search_path: vec![lib_dir.clone(), dir.clone()], + trusted: vec!["Trusted".to_string()], + corr_trusted: Vec::new(), + theory: Vec::new(), + corr_theory: Vec::new(), + vendor_miri: vec!["Miri.VendorMod".to_string()], + module_tiers: BTreeMap::from([("Trusted".to_string(), TrustTier::Vetted)]), + }) + .unwrap_err(); + assert_eq!((err.code, err.phase.as_str()), (1, "correspondence-audit"), "{label}: {err}"); + assert!(err.message.contains(want), "{label}: {err}"); + } + + // Positive control: a `.vendorMiri` module using `initialize` (matching + // pinned `Miri.Input.DecoderValues`) passes vendor override scanning + // (`loadExts := false`) and proceeds to execution-machine cone checks. + let v_init_dir = work_dir.join("vendor-init"); + fs::create_dir_all(v_init_dir.join("Miri")).unwrap(); + let v_init_src = src_dir.join("Miri/VendorInit.lean"); + fs::write( + &v_init_src, + "import Init.System.IO\ninitialize Miri.VendorInit.cfg : Nat ← pure 42\n\ + def Miri.VendorInit.v : Nat := 1\n", + ) + .unwrap(); + let v_init_olean = v_init_dir.join("Miri/VendorInit.olean"); + let init_path = env::join_paths([&lib_dir, &v_init_dir]).unwrap(); + checker + .process_with_path( + "compile-vendor-init", + &[ + "-j1".to_string(), + "-M2048".to_string(), + "-t0".to_string(), + "-R".to_string(), + src_dir.to_string_lossy().into_owned(), + "-o".to_string(), + v_init_olean.to_string_lossy().into_owned(), + v_init_src.to_string_lossy().into_owned(), + ], + Some(&init_path), + ) + .unwrap(); + let err_v_init = checker + .inspect(InspectorRequest::CorrespondenceAudit { + search_path: vec![lib_dir.clone(), v_init_dir], + trusted: vec!["Trusted".to_string()], + corr_trusted: Vec::new(), + theory: Vec::new(), + corr_theory: Vec::new(), + vendor_miri: vec!["Miri.VendorInit".to_string()], + module_tiers: BTreeMap::from([("Trusted".to_string(), TrustTier::Vetted)]), + }) + .unwrap_err(); + assert_eq!( + (err_v_init.code, err_v_init.phase.as_str()), + (1, "correspondence-audit"), + "{err_v_init}" + ); + assert!( + err_v_init + .message + .contains("unknown declaration origin: Miri.Interpreter.ExecutionMachine.step"), + "{err_v_init}" + ); + + // `vendorAlternateProofs` transitive axiom cone check: two vendor modules + // export alternate proofs of the same realized theorem (`Miri.AltA.f.eq_1`) + // where the alternate proof references `propext` (omitted from allowlist), + // while `Miri.Interpreter.ExecutionMachine` does not touch `f`. + let alt_dir = work_dir.join("vendor-alt"); + fs::create_dir_all(alt_dir.join("Miri/Interpreter")).unwrap(); + let alt_path = env::join_paths([&lib_dir, &alt_dir]).unwrap(); + let compile_plain = |chk: &mut Checker, module: &str, body: &str| { + let rel = module.replace('.', "/"); + let src = src_dir.join(format!("{rel}.lean")); + fs::create_dir_all(src.parent().unwrap()).unwrap(); + fs::write(&src, body).unwrap(); + let out = alt_dir.join(format!("{rel}.olean")); + fs::create_dir_all(out.parent().unwrap()).unwrap(); + chk.process_with_path( + &format!("compile-alt-{module}"), + &[ + "-j1".to_string(), + "-M2048".to_string(), + "-t0".to_string(), + "-R".to_string(), + src_dir.to_string_lossy().into_owned(), + "-o".to_string(), + out.to_string_lossy().into_owned(), + src.to_string_lossy().into_owned(), + ], + Some(&alt_path), + ) + .unwrap(); + out + }; + let mut exec_machine_src = String::from("prelude\nimport Init.Core\n"); + for root in [ + "Miri.Interpreter.ExecutionMachine.step", + "Miri.Interpreter.ExecutionMachine.AllowedStep", + "Miri.Interpreter.ExecutionMachine.withValidation", + "Miri.Interpreter.ExecutionMachine.stepHooks", + "Miri.Interpreter.ExecutionMachine.rvalueHooks", + "Miri.Interpreter.ExecutionMachine.operandHooks", + "Miri.Interpreter.ExecutionMachine.projectionHooks", + "Miri.Interpreter.ExecutionMachine.discriminantHooks", + "Miri.Interpreter.ExecutionMachine.scalarHooks", + "Miri.Interpreter.Step.step", + "Miri.Interpreter.Step.evalStatement", + "Miri.Interpreter.ControlFlow.goToBlock", + "Miri.Interpreter.ControlFlow.evalTerminator", + "Miri.Interpreter.ControlFlow.returnFromCurrentFrame", + "Miri.Interpreter.ExecutionControl.hooks", + "Miri.Interpreter.MachineHooks.storageLiveDyn", + "Miri.Interpreter.MachineHooks.storageDead", + "Miri.Interpreter.OperandMachine.evalOperand", + "Miri.Interpreter.OperandMachine.evalPlaceToOp", + "Miri.Interpreter.PlaceMachine.readImmediate", + "Miri.Interpreter.PlaceMachine.writeMemory", + "Miri.Interpreter.ValidityVisitor.validatePlace", + "Miri.Interpreter.ValidityMemory.bind", + "Miri.Interpreter.evalRvalueIntoPlace", + "Miri.Interpreter.TerminatorMachine.beforeTerminatorWithChoice", + "Miri.Interpreter.ScalarOps.binary", + "Miri.Interpreter.ScalarOps.unary", + "Miri.Interpreter.IntegerOps.binary", + "Miri.Interpreter.IntegerOps.binaryBool", + "Miri.Interpreter.IntegerOps.unary", + "Miri.Interpreter.Discriminant.readDiscriminant", + "Miri.Interpreter.Discriminant.discriminantForVariant", + "Miri.Memory.ScalarInt.truncateFromUInt", + "Miri.Memory.ScalarInt.tryFromUInt", + "Miri.Memory.ScalarInt.tryToBool", + "Miri.Interpreter.evalOperand", + ] { + exec_machine_src.push_str(&format!("def {root} : Nat := 0\n")); + } + compile_plain(&mut checker, "Miri.Interpreter.ExecutionMachine", &exec_machine_src); + compile_plain( + &mut checker, + "Miri.AltBase", + "prelude\nimport Init.Core\n\ + def Miri.AltBase.f : Nat → Nat | 0 => 0 | n + 1 => n\n", + ); + let alt_a = compile_plain( + &mut checker, + "Miri.AltA", + "prelude\nimport Init.Core\nimport Miri.AltBase\n\ + theorem Miri.AltA.useEq1 : Miri.AltBase.f 0 = 0 := Miri.AltBase.f.eq_1\n", + ); + let alt_b = compile_plain( + &mut checker, + "Miri.AltB", + "prelude\nimport Init.Core\nimport Miri.AltBase\n\ + theorem Miri.AltB.propextHelper : (True ↔ True) → True = True := propext\n\ + theorem Miri.AltB.usePropext : Miri.AltBase.f 0 = 0 := (fun _ => rfl) (Miri.AltB.propextHelper Iff.rfl)\n", + ); + let _alt_c = compile_plain( + &mut checker, + "Miri.AltC", + "prelude\nimport Init.Core\nimport Miri.AltBase\n\ + theorem Miri.AltC.useEq1 : Miri.AltBase.f 0 = 0 := Miri.AltBase.f.eq_1\n", + ); + let splice_alt = format!( + "import Lean.Elab.Import\n\ + open Lean\n\ + def main : IO Unit := do\n\ + let (da, _) ← readModuleData {:?}\n\ + let (db, _) ← readModuleData {:?}\n\ + let some (.thmInfo ta) := da.constants.find? (·.name == `Miri.AltBase.f.eq_1)\n\ + | throw <| IO.userError \"missing AltBase.f.eq_1\"\n\ + let proofArg := Expr.app (.const `Miri.AltB.propextHelper []) (.app (.const `Iff.refl []) (.const `True []))\n\ + let eqTrue := Expr.app (.app (.app (.const `Eq [.succ .zero]) (.sort .zero)) (.const `True [])) (.const `True [])\n\ + let altVal := Expr.app (.lam `_ eqTrue ta.value .default) proofArg\n\ + let dupThm : ConstantInfo := .thmInfo {{ ta with value := altVal }}\n\ + saveModuleData {:?} `Miri.AltB {{\n\ + db with\n\ + constNames := db.constNames.push dupThm.name,\n\ + constants := db.constants.push dupThm\n\ + }}\n", + alt_a.to_string_lossy(), + alt_b.to_string_lossy(), + alt_b.to_string_lossy(), + ); + run_lean_script( + &mut checker, + "splice-vendor-alt", + &work_dir.join("splice_vendor_alt.lean"), + &splice_alt, + ); + let saved_axioms = checker.admitted().unwrap().axioms.clone(); + checker.admitted_mut().unwrap().axioms.retain(|(ax, _)| ax != "propext"); + let err_alt = checker + .inspect(InspectorRequest::CorrespondenceAudit { + search_path: vec![lib_dir, alt_dir], + trusted: vec!["Trusted".to_string()], + corr_trusted: Vec::new(), + theory: Vec::new(), + corr_theory: Vec::new(), + vendor_miri: vec![ + "Miri.Interpreter.ExecutionMachine".to_string(), + "Miri.AltBase".to_string(), + "Miri.AltA".to_string(), + "Miri.AltB".to_string(), + "Miri.AltC".to_string(), + ], + module_tiers: BTreeMap::from([("Trusted".to_string(), TrustTier::Vetted)]), + }) + .unwrap_err(); + checker.admitted_mut().unwrap().axioms = saved_axioms; + assert_eq!((err_alt.code, err_alt.phase.as_str()), (1, "correspondence-audit"), "{err_alt}"); + assert!(err_alt.message.contains("unapproved axiom propext from Init.Core"), "{err_alt}"); + + // Positive control for Pass 2 `module`-mode sidecar promotion: compiling + // `module`-mode `Trusted.Correspondence` and + // `Anneal.MirCorrespondenceProof` promotes `.olean.server` and + // `.olean.private` cleanly through Pass 2 DAG compilation and reaches + // `"correspondence-audit"` (failing only later on the synthetic fixture's + // omitted `Miri.Interpreter.ExecutionMachine` root). + let mod_fix = TempFixture::new(Some( + "-- anneal-trust-tier: vetted\n\ + module\n\ + prelude\n\ + public import Init.Core\n\ + @[expose] public section\n\ + namespace Trusted\n\ + def seed : Nat := 1\n\ + end Trusted\n\ + end\n", + )); + let mut mod_checker = mod_fix.checker(); + mod_checker.set_require_mir_wp(false); + mod_checker.run().unwrap(); + + let vendor_dir = mod_fix.root.join("vendor/lean-miri"); + fs::create_dir_all(vendor_dir.join("Miri")).unwrap(); + let vendor_src = "module\nprelude\npublic import Init.Core\n@[expose] public section\n\ + def Miri.Leaf.v : Nat := 1\nend\n"; + fs::write(vendor_dir.join("Miri/Leaf.lean"), vendor_src).unwrap(); + let corr_trusted_dir = mod_fix.root.join("trusted/correspondence/Trusted"); + fs::create_dir_all(&corr_trusted_dir).unwrap(); + fs::write( + corr_trusted_dir.join("Correspondence.lean"), + "-- anneal-trust-tier: candidate:mir_semantics\n\ + module\n\ + prelude\n\ + public import Init.Core\n\ + public import Trusted\n\ + public import Miri.Leaf\n\ + @[expose] public section\n\ + def Trusted.Correspondence.ok : Nat := Trusted.seed + Miri.Leaf.v\n\ + end\n", + ) + .unwrap(); + let corr_theory_dir = mod_fix.root.join("correspondence/Anneal"); + fs::create_dir_all(&corr_theory_dir).unwrap(); + fs::write( + corr_theory_dir.join("MirCorrespondenceProof.lean"), + "module\n\ + prelude\n\ + public import Init.Core\n\ + public import Trusted.Correspondence\n\ + @[expose] public section\n\ + theorem Anneal.MirCorrespondenceProof.ok : Trusted.Correspondence.ok = 2 := rfl\n\ + end\n", + ) + .unwrap(); + // Pre-compile `Miri.Leaf` once to obtain its deterministic SHA-256 digests + // for the synthetic `MiriClosureEntry`. + let mod_stage = mod_checker.stage().to_path_buf(); + let miri_tmp_lib = mod_stage.join("miri-digests"); + fs::create_dir_all(&miri_tmp_lib).unwrap(); + let (ml_o, ml_s, ml_p) = compile_3part_module( + &mut mod_checker, + &mod_stage, + &miri_tmp_lib, + &vendor_dir, + "Miri.Leaf", + vendor_src, + vec![init_core_edge], + ); + let closure = vec![MiriClosureEntry { + module: "Miri.Leaf".to_string(), + path: "Miri/Leaf.lean".to_string(), + olean_sha256: sha256_file(&ml_o, "test").unwrap(), + olean_server_sha256: Some(sha256_file(&ml_s, "test").unwrap()), + olean_private_sha256: Some(sha256_file(&ml_p, "test").unwrap()), + }]; + let expected_sources = + BTreeMap::from([("Miri/Leaf.lean".to_string(), sha256_bytes(vendor_src.as_bytes()))]); + let base_tiers = BTreeMap::from([("Trusted".to_string(), TrustTier::Vetted)]); + let err_p2_mod = mod_checker + .run_correspondence_with_closure( + &base_tiers, + &vendor_dir, + "0000000000000000000000000000000000000000", + &closure, + &expected_sources, + ) + .unwrap_err(); + assert_eq!( + (err_p2_mod.code, err_p2_mod.phase.as_str()), + (1, "correspondence-audit"), + "Pass 2 module-mode compilation should succeed and reach correspondence-audit: {err_p2_mod}" + ); + assert!( + err_p2_mod + .message + .contains("unknown declaration origin: Miri.Interpreter.ExecutionMachine.step"), + "{err_p2_mod}" + ); + assert!( + mod_stage.join("lib/Trusted/Correspondence.olean.private").exists() + && mod_stage.join("lib/Trusted/Correspondence.olean.server").exists() + && mod_stage.join("theory-lib/Anneal/MirCorrespondenceProof.olean.private").exists() + && mod_stage.join("theory-lib/Anneal/MirCorrespondenceProof.olean.server").exists() + && !mod_stage.join("lib/Trusted.ir").exists() + && !mod_stage.join("lib/Trusted.ir.sig").exists(), + "Pass 2 module-mode sidecars must be promoted and Pass 1 stray IR removed" + ); +}
diff --git a/tests/audit/tests/boundary_audit/pass1_preflight.rs b/tests/audit/tests/boundary_audit/pass1_preflight.rs index bb55477..dcd0d58 100644 --- a/tests/audit/tests/boundary_audit/pass1_preflight.rs +++ b/tests/audit/tests/boundary_audit/pass1_preflight.rs
@@ -644,13 +644,15 @@ /// Pass 1 `"preflight"` and `"audit"` admit Lean 4 `module`-system `Trusted` /// and `theory/` files (`public import`, `@[expose] public section`, /// `public section` + `@[expose] def`, private `import`, and narrowly scoped -/// `import all Init.Data.Nat.Bitwise.Basic` in `theory/`), thread `isModule` -/// into `lean --setup`, and fail closed when a `theory/` module attempts -/// `import all` on any non-allowlisted foundation module. +/// `import all Init.Data.Nat.Bitwise.Basic` strictly in `Anneal.NatBitwise`), +/// thread `isModule` into `lean --setup`, and fail closed when +/// `Anneal.NatBitwise` attempts `import all` on any non-allowlisted foundation +/// module or when any other `theory/` module attempts `import all`. #[test] fn admits_module_system_pass1_and_restricts_import_all() { - // Positive case: `Trusted` and `Anneal` both use Lean 4 `module` syntax, - // including `import all Init.Data.Nat.Bitwise.Basic` in `Anneal`. + // Positive case: `Trusted` and `Anneal.NatBitwise` both use Lean 4 + // `module` syntax, including `import all Init.Data.Nat.Bitwise.Basic` in + // `Anneal.NatBitwise`. { let fix = TempFixture::new(Some( "-- anneal-trust-tier: vetted\n\ @@ -663,9 +665,9 @@ end Trusted\n\ end\n", )); - fs::create_dir_all(fix.root.join("theory")).unwrap(); + fs::create_dir_all(fix.root.join("theory/Anneal")).unwrap(); fs::write( - fix.root.join("theory/Anneal.lean"), + fix.root.join("theory/Anneal/NatBitwise.lean"), "module\n\ prelude\n\ public import Init.Core\n\ @@ -673,10 +675,10 @@ public import Trusted\n\ import all Init.Data.Nat.Bitwise.Basic\n\ public section\n\ - namespace Anneal\n\ + namespace Anneal.NatBitwise\n\ @[expose] def bump : Nat := Trusted.seed\n\ theorem land_bridge (n m : Nat) : Nat.land n m = Nat.bitwise and n m := by rfl\n\ - end Anneal\n\ + end Anneal.NatBitwise\n\ end\n", ) .unwrap(); @@ -690,14 +692,37 @@ "module-compiled Trusted must emit .olean.private" ); assert!( - checker.stage().join("theory-lib/Anneal.olean.private").exists(), - "module-compiled Anneal must emit .olean.private" + checker.stage().join("theory-lib/Anneal/NatBitwise.olean.private").exists(), + "module-compiled Anneal.NatBitwise must emit .olean.private" ); } - // Negative case: `theory/` cannot `import all` outside the narrow - // `allowedTheoryImportAllModules` allowlist. - { + // Negative cases: `Anneal.NatBitwise` cannot `import all` outside the + // narrow `allowedTheoryImportAllModules` allowlist, and no other `theory/` + // module may use `import all` even on `Init.Data.Nat.Bitwise.Basic`. + for (rel_path, body) in [ + ( + "theory/Anneal/NatBitwise.lean", + "module\n\ + prelude\n\ + public import Init.Core\n\ + import all Init.Core\n\ + public section\n\ + theorem ok : True := True.intro\n\ + end\n", + ), + ( + "theory/Anneal.lean", + "module\n\ + prelude\n\ + public import Init.Core\n\ + public import Init.Data.Nat.Bitwise.Basic\n\ + import all Init.Data.Nat.Bitwise.Basic\n\ + public section\n\ + theorem ok : True := True.intro\n\ + end\n", + ), + ] { let fix = TempFixture::new(Some( "-- anneal-trust-tier: vetted\n\ module\n\ @@ -709,27 +734,18 @@ end Trusted\n\ end\n", )); - fs::create_dir_all(fix.root.join("theory")).unwrap(); - fs::write( - fix.root.join("theory/Anneal.lean"), - "module\n\ - prelude\n\ - public import Init.Core\n\ - import all Init.Core\n\ - public section\n\ - theorem ok : True := True.intro\n\ - end\n", - ) - .unwrap(); + let full = fix.root.join(rel_path); + fs::create_dir_all(full.parent().unwrap()).unwrap(); + fs::write(&full, body).unwrap(); let mut checker = fix.checker(); checker.set_require_mir_wp(false); let err = checker.run().unwrap_err(); - assert_eq!(err.code, 1, "expected policy exit 1: {err}"); - assert_eq!(err.phase, "preflight", "expected preflight rejection: {err}"); + assert_eq!(err.code, 1, "expected policy exit 1 for {rel_path}: {err}"); + assert_eq!(err.phase, "preflight", "expected preflight rejection for {rel_path}: {err}"); assert!( err.message.contains("import modifiers are unsupported"), - "unexpected error: {err}" + "unexpected error for {rel_path}: {err}" ); } }
diff --git a/tests/audit/tests/target_audit/companions_and_module_mode/module_mode/is_module_metadata.rs b/tests/audit/tests/target_audit/companions_and_module_mode/module_mode/is_module_metadata.rs index 41d13d0..4ac4680 100644 --- a/tests/audit/tests/target_audit/companions_and_module_mode/module_mode/is_module_metadata.rs +++ b/tests/audit/tests/target_audit/companions_and_module_mode/module_mode/is_module_metadata.rs
@@ -179,6 +179,15 @@ bad_layout[root_off + 7] = 1; let mut bad_flag = raw.clone(); bad_flag[root_off + 8 + 5 * 8] = 2; + let mut unaligned_root = raw.clone(); + unaligned_root[88..96].copy_from_slice(&(base0 + 88 + 9).to_le_bytes()); + let mut unaligned_base = raw.clone(); + unaligned_base[80..88].copy_from_slice(&(base0 + 8).to_le_bytes()); + let mut overflow_base = vec![0u8; 65536]; + overflow_base[..raw.len().min(65536)].copy_from_slice(&raw[..raw.len().min(65536)]); + let high_base: u64 = 0xffff_ffff_ffff_0000; + overflow_base[80..88].copy_from_slice(&high_base.to_le_bytes()); + overflow_base[88..96].copy_from_slice(&(high_base + root_off as u64).to_le_bytes()); for (name, bytes, needle) in [ ("Empty.olean", &[][..], "truncated olean header in Spec"), @@ -186,6 +195,9 @@ ("BadMagic.olean", &bad_magic[..], "invalid olean v2 header in Spec"), ("HdrOnly88.olean", &raw[..88], "truncated olean root pointer in Spec"), ("BadRootPtr.olean", &bad_ptr[..], "invalid olean root pointer in Spec"), + ("UnalignedRootPtr.olean", &unaligned_root[..], "unaligned olean root pointer in Spec"), + ("UnalignedBaseAddr.olean", &unaligned_base[..], "unaligned olean base address in Spec"), + ("OverflowBaseAddr.olean", &overflow_base[..], "olean address range overflow in Spec"), ("OobRootPtr.olean", &oob_ptr[..], "out-of-bounds olean root object in Spec"), ("LowRootPtr.olean", &low_ptr[..], "out-of-bounds olean root object in Spec"), ("BadLayout.olean", &bad_layout[..], "invalid olean ModuleData layout in Spec"), @@ -220,6 +232,37 @@ let base_msg = "mismatched olean companion base address in Spec"; assert_mod_err(&mut checker, "Spec", bad_base_arts, &modes, 1, base_msg); + let mut bad_srv_root = fs::read(&spec_parts[1]).unwrap(); + let srv_root_base = u64::from_le_bytes(bad_srv_root[80..88].try_into().unwrap()); + bad_srv_root[88..96].copy_from_slice(&(srv_root_base + 88 + 9).to_le_bytes()); + let bad_srv_root_p = write_part("Spec.bad_root.olean.server", &bad_srv_root); + let bad_srv_root_arts = + mk_arts(vec![spec_parts[0].clone(), bad_srv_root_p, spec_parts[2].clone()]); + assert_mod_err( + &mut checker, + "Spec", + bad_srv_root_arts, + &modes, + 1, + "unaligned olean companion root pointer in Spec", + ); + + let mut oob_prv_root = fs::read(&spec_parts[2]).unwrap(); + let prv_base = u64::from_le_bytes(oob_prv_root[80..88].try_into().unwrap()); + let prv_oob = prv_base + oob_prv_root.len() as u64 + 64; + oob_prv_root[88..96].copy_from_slice(&prv_oob.to_le_bytes()); + let oob_prv_root_p = write_part("Spec.oob_root.olean.private", &oob_prv_root); + let oob_prv_root_arts = + mk_arts(vec![spec_parts[0].clone(), spec_parts[1].clone(), oob_prv_root_p]); + assert_mod_err( + &mut checker, + "Spec", + oob_prv_root_arts, + &modes, + 1, + "out-of-bounds olean companion root object in Spec", + ); + for (role_mod, part0) in [("Spec", spec_parts[0].clone()), ("Proof", proof_p0)] { let mut wrong_modes = modes.clone(); wrong_modes.insert(role_mod.into(), false); @@ -227,7 +270,76 @@ assert_mod_err(&mut checker, role_mod, mk_arts(vec![part0]), &wrong_modes, 1, &msg); } - // 4. Non-module target paired with 2-part `.olean` + `.olean.server` + // 4. Forged `extraConstNames` injected strictly into companion `.olean` + // (part 0) while `.olean.private` is clean fails closed in both + // `"target-audit"` and `"target-consts"`. Run before step 5 overwrites + // `stage/lib/Spec.olean` with a non-module build. + let extra_dir = stage.join("lib/SpecCompExtra"); + fs::create_dir_all(&extra_dir).unwrap(); + let forged_o = extra_dir.join("Spec.olean"); + let forged_s = extra_dir.join("Spec.olean.server"); + let forged_p = extra_dir.join("Spec.olean.private"); + let forge_extra_script = format!( + "import Lean.Elab.Import\n\ + open Lean\n\ + def main : IO Unit := do\n\ + let parts ← readModuleDataParts #[{:?}, {:?}, {:?}]\n\ + let #[(md0, _), (md1, _), (md2, _)] := parts | throw <| IO.userError \"expected 3 parts\"\n\ + let md0' := {{ md0 with extraConstNames := md0.extraConstNames.push `True.intro }}\n\ + saveModuleDataParts `Spec #[({:?}, md0'), ({:?}, md1), ({:?}, md2)]\n", + spec_parts[0], + spec_parts[1], + spec_parts[2], + forged_o.to_string_lossy(), + forged_s.to_string_lossy(), + forged_p.to_string_lossy(), + ); + let forge_extra_lean = stage.join("forge_comp_extra.lean"); + fs::write(&forge_extra_lean, forge_extra_script).unwrap(); + checker + .process( + "forge-comp-extra", + &[ + "-j1".to_string(), + "-M4096".to_string(), + "--run".to_string(), + forge_extra_lean.to_string_lossy().into_owned(), + ], + ) + .unwrap(); + let forged_extra_arts = mk_arts(vec![ + forged_o.to_string_lossy().into_owned(), + forged_s.to_string_lossy().into_owned(), + forged_p.to_string_lossy().into_owned(), + ]); + assert_mod_err( + &mut checker, + "Spec", + forged_extra_arts.clone(), + &modes, + 1, + "target companion extraConstName True.intro missing from private inventory of Spec", + ); + checker.admitted_mut().unwrap().artifacts = orig_arts.clone(); + checker.admitted_mut().unwrap().artifacts.insert("Spec".into(), forged_extra_arts); + let tc_roles: BTreeMap<String, TargetRole> = f + .request + .modules + .iter() + .filter(|m| m.role != TargetRole::Proof) + .map(|m| (m.module.clone(), m.role)) + .collect(); + let tc_modes: BTreeMap<String, bool> = tc_roles.keys().map(|m| (m.clone(), true)).collect(); + let tc_err = checker.inspect_target_consts(&tc_roles, &tc_modes).unwrap_err(); + assert_eq!((tc_err.code, tc_err.phase.as_str()), (1, "target-consts"), "{tc_err}"); + assert!( + tc_err.message.contains( + "target companion extraConstName True.intro missing from private inventory of Spec" + ), + "{tc_err}" + ); + + // 5. Non-module target paired with 2-part `.olean` + `.olean.server` // (without `.olean.private`) is rejected pre-import on part count. let mut nonmod_modes = modes; nonmod_modes.insert("Spec".into(), false);
diff --git a/tests/audit/tests/target_audit/module_headers.rs b/tests/audit/tests/target_audit/module_headers.rs index 1c90b34..48e1db8 100644 --- a/tests/audit/tests/target_audit/module_headers.rs +++ b/tests/audit/tests/target_audit/module_headers.rs
@@ -113,6 +113,8 @@ ("std-async-sub", "prelude\nimport Std.Async.Timer\n", d), ("std-http", "prelude\nimport Std.Http\n", d), ("std-http-sub", "prelude\nimport Std.Http.Client\n", d), + ("std-sync", "prelude\nimport Std.Sync\n", d), + ("std-sync-sub", "prelude\nimport Std.Sync.Mutex\n", d), ("mod-std-http", "module\nprelude\npublic import Std.Http.Client\n", d), ("mod-pub-all", "module\nprelude\npublic import all Init.Data.Nat.Bitwise.Basic\n", p), ("mod-pub-root", "module\nprelude\npublic import _root_.Model\n", "invalid identifier"), @@ -129,6 +131,14 @@ assert_eq!((err.code, err.phase.as_str()), (1, "headers"), "{label}: {err}"); assert!(err.message.contains(want), "{label}: {err}"); } + + let non_nb_all = f.root.join("hdr_non_nb_all.lean"); + fs::write(&non_nb_all, "module\nprelude\nimport all Init.Data.Nat.Bitwise.Basic\n").unwrap(); + let err_non_nb = checker + .inspect(InspectorRequest::Headers { sources: vec![("Anneal.Foo".into(), non_nb_all)] }) + .unwrap_err(); + assert_eq!((err_non_nb.code, err_non_nb.phase.as_str()), (1, "headers"), "{err_non_nb}"); + assert!(err_non_nb.message.contains("import modifiers"), "{err_non_nb}"); } // `module` mode without `prelude` passes end-to-end in unpinned mode @@ -228,6 +238,7 @@ ("sp-meta", "prelude\nimport Init.Meta.Slicing\n", "disallowed sysroot import"), ("sp-async", "prelude\nimport Std.Async.Timer\n", "disallowed sysroot import"), ("sp-http", "prelude\nimport Std.Http\n", "disallowed sysroot import"), + ("sp-sync", "prelude\nimport Std.Sync.Mutex\n", "disallowed sysroot import"), ("sp-std", "prelude\nimport Std\n", "disallowed sysroot import"), ("sp-all", "module\nprelude\nimport all Init.Data.Nat.Bitwise.Basic\n", "import modifiers"), ("sp-root", "prelude\nimport _root_.Model\n", "invalid identifier"), @@ -243,6 +254,9 @@ "\n#eval do\n SpecPreflight.initHermeticSearchPath {sysroot_lit}\n \ let ok ← SpecPreflight.inspectHeader `Anneal.NatBitwise {ann_lit}\n \ let .ok true := ok.getObjValAs? Bool \"isModule\" | throw <| IO.userError \"sp-ok\"\n \ + let nonNbRej ← try discard <| SpecPreflight.inspectHeader `Anneal.Foo {ann_lit}; pure false catch e =>\n \ + pure (e.toString.startsWith \"policy:\" && (e.toString.splitOn \"import modifiers\").length > 1)\n \ + unless nonNbRej do throw <| IO.userError \"sp-non-natbitwise-all unexpectedly accepted\"\n \ for (t, p, w) in #[{}] do\n \ let rej ← try discard <| SpecPreflight.inspectHeader `Spec p; pure false catch e =>\n \ pure (e.toString.startsWith \"policy:\" && (e.toString.splitOn w).length > 1)\n \
diff --git a/tests/audit/tests/target_audit/spec_preflight_parse_tree/round_trip_probe.rs b/tests/audit/tests/target_audit/spec_preflight_parse_tree/round_trip_probe.rs index 04f417b..bf445f2 100644 --- a/tests/audit/tests/target_audit/spec_preflight_parse_tree/round_trip_probe.rs +++ b/tests/audit/tests/target_audit/spec_preflight_parse_tree/round_trip_probe.rs
@@ -34,6 +34,26 @@ serde_json::to_vec(&vectors_json).unwrap(), ) .unwrap(); + let struct_rec_src = "structure Spec.WithRec where\n x : Nat :=\n let rec sHelper (n : Nat) : Nat :=\n match n with\n | 0 => 0\n | k + 1 => sHelper k\n sHelper 2\n"; + let struct_rec_dir = checker.stage().join("struct-letrec-fixture"); + fs::create_dir_all(&struct_rec_dir).unwrap(); + let struct_rec_lean = struct_rec_dir.join("SpecWithRec.lean"); + let struct_rec_olean = struct_rec_dir.join("SpecWithRec.olean"); + fs::write(&struct_rec_lean, struct_rec_src).unwrap(); + checker + .process( + "compile-struct-letrec", + &[ + "-j1".to_string(), + "-M2048".to_string(), + "-R".to_string(), + struct_rec_dir.to_string_lossy().into_owned(), + "-o".to_string(), + struct_rec_olean.to_string_lossy().into_owned(), + struct_rec_lean.to_string_lossy().into_owned(), + ], + ) + .unwrap(); let mut source = fs::read_to_string(&adm.inspector).unwrap(); source.push_str(&format!( r#" @@ -121,12 +141,36 @@ let modOk := #[ "@[expose] public section\ndef Spec.specs (p : BitVec 8) : Prop := BitVec.and p p = p\nend\n", "public noncomputable section S\ndef Spec.ncHelper : Nat := 0\nend S\ndef Spec.specs (p : BitVec 8) : Prop := BitVec.and p p = p\n", - "@[expose] public def Spec.helper (n : Nat) : Nat := n\npublic theorem Spec.thm : True := trivial\nprivate theorem Spec.privThm : True := trivial\npublic section\ndef Spec.specs (p : BitVec 8) : Prop := BitVec.and p p = p\nend\n" + "@[expose] public def Spec.helper (n : Nat) : Nat := n\npublic theorem Spec.thm : True := trivial\nprivate theorem Spec.privThm : True := trivial\npublic section\ndef Spec.specs (p : BitVec 8) : Prop := BitVec.and p p = p\nend\n", + "open System.Platform renaming numBits -> nb, getNumBits -> gnb\ndef Spec.okBits : Nat := nb\ndef Spec.specs (p : BitVec 8) : Prop := BitVec.and p p = p\n", + "open Std renaming HashMap -> HM, HashSet -> HS\ndef Spec.okLocal (Async : Nat) : Nat := Async\ndef Spec.specs (p : BitVec 8) : Prop := BitVec.and p p = p\n" ] for body in modOk do let ctx := Lean.Parser.mkInputContext body "mod-ok" TrustedBoundary.parseAndInspectSpecCommands ctx cmdKinds tacKinds env [rootScope] `Spec {{}} {{}} true + -- Verify `collectCommandSpecDecls` collects `let rec` helpers inside + -- `structure` and `class` default field initializers as optional `def`s + -- matching Lean's `<StructName>.<letId>` prefix, and confirm against the + -- compiled `SpecWithRec.olean` that Lean emits `Spec.WithRec.sHelper.match_1`. + let (compiledStructMd, _) ← Lean.readModuleData (System.FilePath.mk {:?}) + unless compiledStructMd.constNames.contains `Spec.WithRec.sHelper.match_1 do + throw <| IO.userError + s!"expected SpecWithRec.olean to contain Spec.WithRec.sHelper.match_1, got: {{compiledStructMd.constNames}}" + let structRecSrc := + "structure Spec.WithRec where\n x : Nat :=\n let rec sHelper (n : Nat) : Nat :=\n match n with\n | 0 => 0\n | k + 1 => sHelper k\n sHelper 2\n" ++ + "class Spec.ClsRec where\n y : Nat :=\n let rec cHelper (n : Nat) : Nat := n\n cHelper 0\n" + let structDecls ← TrustedBoundary.parseAndInspectSpecCommandsDecls + (Lean.Parser.mkInputContext structRecSrc "struct-letrec") + cmdKinds tacKinds env [rootScope] `Spec {{}} {{}} false + let hasStructHelper := structDecls.any fun d => + (d.getObjValAs? String "name").toOption == some "Spec.WithRec.sHelper" && + (d.getObjValAs? Bool "isOptional").toOption == some true + let hasClassHelper := structDecls.any fun d => + (d.getObjValAs? String "name").toOption == some "Spec.ClsRec.cHelper" && + (d.getObjValAs? Bool "isOptional").toOption == some true + unless hasStructHelper && hasClassHelper do + throw <| IO.userError s!"missing structure/class default let rec decls: {{structDecls}}" for (label, body, want) in #[ ("mod-meta-sec", "meta section S\nend S\n", "unsupported section/namespace modifier"), ("mod-public-meta-sec", "public meta section S\nend S\n", "unsupported section/namespace modifier"), @@ -149,7 +193,8 @@ throw <| IO.userError s!"{{label}}: unexpectedly accepted" "#, adm.prefix.to_string_lossy(), - vectors_json_path.to_string_lossy() + vectors_json_path.to_string_lossy(), + struct_rec_olean.to_string_lossy() )); let probe = checker.stage().join("SpecPreflightRoundTrip.lean"); fs::write(&probe, source).unwrap();
diff --git a/tests/audit/tests/target_audit/spec_preflight_parse_tree/term_vectors/namespaces_and_macros.rs b/tests/audit/tests/target_audit/spec_preflight_parse_tree/term_vectors/namespaces_and_macros.rs index 0eb7304..379bff9 100644 --- a/tests/audit/tests/target_audit/spec_preflight_parse_tree/term_vectors/namespaces_and_macros.rs +++ b/tests/audit/tests/target_audit/spec_preflight_parse_tree/term_vectors/namespaces_and_macros.rs
@@ -238,5 +238,65 @@ "namespace TrustedBoundary\ndef bad : Nat := 0\nend TrustedBoundary\n", "cannot enter reserved namespace TrustedBoundary", ), + ( + "in-export-persists-uv", + "open Std in\nexport Std (Internal)\ndef Spec.badUv := Internal.UV.Loop.alive\n", + "Internal.UV", + ), + ( + "mutual-export-persists-uv", + "mutual\nexport Std (Internal)\nend\ndef Spec.badMutUv := Internal.UV.Loop.alive\n", + "Internal.UV", + ), + ( + "section-export-persists-uv", + "section\nexport Std (Internal)\nend\ndef Spec.badSecUv := Internal.UV.Loop.alive\n", + "Internal.UV", + ), + ( + "namespace-export-persists-uv", + "namespace Spec.ExWrap\nexport Std (Internal)\nend Spec.ExWrap\ndef Spec.badNsUv := Spec.ExWrap.Internal.UV.Loop.alive\n", + "Internal.UV", + ), + ( + "namespace-reopen-export-persists-uv", + "namespace Spec.ExRe\nexport Std (Internal)\nend Spec.ExRe\nnamespace Spec.ExRe\ndef badReUv := Internal.UV.Loop.alive\nend Spec.ExRe\n", + "Internal.UV", + ), + ( + "nested-ns-partial-close-reopen-export-uv", + "namespace Spec\nnamespace ExRe\nexport Std (Internal)\nend ExRe\nnamespace ExRe\ndef badReUv := Internal.UV.Loop.alive\nend ExRe\nend Spec\n", + "Internal.UV", + ), + ( + "nested-ns-partial-close-open-export-uv", + "namespace Spec\nnamespace ExOp\nexport Std (Internal)\nend ExOp\nopen ExOp\ndef badOpUv := Internal.UV.Loop.alive\nend Spec\n", + "Internal.UV", + ), + ( + "three-hop-export-chain-uv", + "namespace Spec.H1\nexport Std (Internal)\nend Spec.H1\nnamespace Spec.H2\nexport Spec.H1 (Internal)\nend Spec.H2\nnamespace Spec.H3\nexport Spec.H2 (Internal)\nend Spec.H3\ndef Spec.bad3Hop := Spec.H3.Internal.UV.Loop.alive\n", + "Internal.UV", + ), + ( + "open-std-sync", + "open Std (Sync)\n", + "disallowed open item Std.Sync", + ), + ( + "export-std-sync", + "export Std (Sync)\n", + "disallowed export item Std.Sync", + ), + ( + "ref-std-sync", + "def Spec.badSync := Std.Sync.Mutex\n", + "Std.Sync", + ), + ( + "open-renaming-post-comma-async", + "open Std renaming HashMap -> HM, Async -> BadAsync\n", + "disallowed open item Std.Async", + ), ] }
diff --git a/tests/audit/tests/target_audit/spec_preflight_parse_tree/term_vectors/syntax_and_panics.rs b/tests/audit/tests/target_audit/spec_preflight_parse_tree/term_vectors/syntax_and_panics.rs index 9998162..2e29a3e 100644 --- a/tests/audit/tests/target_audit/spec_preflight_parse_tree/term_vectors/syntax_and_panics.rs +++ b/tests/audit/tests/target_audit/spec_preflight_parse_tree/term_vectors/syntax_and_panics.rs
@@ -228,5 +228,20 @@ "def x := repeatM\n", "disallowed identifier repeatM", ), + ( + "direct-sorry-ax", + "def s : Nat := sorryAx Nat false\n", + "disallowed identifier sorryAx", + ), + ( + "qual-sorry-ax", + "def s : Nat := Init.Prelude.sorryAx Nat false\n", + "disallowed identifier Init.Prelude.sorryAx", + ), + ( + "computed-fields", + "inductive Spec.CompList where\n | nil\n | cons : Nat → Spec.CompList → Spec.CompList\nwith\n @[computed_field] len : Spec.CompList → Nat\n | .nil => 0\n | .cons _ t => t.len + 1\n", + "disallowed syntax Lean.Parser.Command.computedFields", + ), ] }
diff --git a/trusted/audit/SpecPreflight.lean b/trusted/audit/SpecPreflight.lean index bd5fa39..a53717c 100644 --- a/trusted/audit/SpecPreflight.lean +++ b/trusted/audit/SpecPreflight.lean
@@ -24,8 +24,9 @@ - **`"headers"` (target import discovery before elaboration):** Parses only module `prelude`/`module`/`import` headers via `Parser.parseHeader`, admitting Lean 4 `module`-system headers across target - roles (`import all` confined to `Anneal.*` on `Init.Data.Nat.Bitwise.Basic`) - and rejecting `Lean.*`/`Lake.*` and disallowed `meta` imports. + roles (`import all` confined to `Anneal.NatBitwise` on + `Init.Data.Nat.Bitwise.Basic`) and rejecting `Lean.*`/`Lake.*` and disallowed + `meta` imports. - **`"spec-preflight"` (target specification syntactic admission):** Parses every `TargetRole::Specification` source against the authenticated `Init` + `Std` parser environment (`trustLevel := 0`, `plugins := #[]`, @@ -194,15 +195,16 @@ `Lean.Parser.Tactic.«tactic_<;>_», `Lean.Parser.Tactic.unfold, `tacticFunext___] -/-- Return `true` if `id` is a valid user-written identifier with non-empty -string components, no macro scopes, and no `_root_` namespace escape. -/ +/-- Return `true` if `id` is a non-anonymous user-written identifier with +non-empty string components, no macro scopes, and no `_root_` namespace +escape. -/ def isValidSourceIdent (id : Name) : Bool := - id.isAnonymous || - (!id.hasMacroScopes && id.eraseMacroScopes == id && - !id.toString.isEmpty && - id.components.all fun - | .str .anonymous seg => !seg.isEmpty && seg != "_root_" - | _ => false) + !id.isAnonymous && + !id.hasMacroScopes && id.eraseMacroScopes == id && + !id.toString.isEmpty && + id.components.all fun + | .str .anonymous seg => !seg.isEmpty && seg != "_root_" + | _ => false /-- Validate a parsed module header syntax tree against `allowedHeaderKinds` without allowing missing recovery placeholders or malformed identifiers. -/ @@ -240,14 +242,28 @@ | .anonymous => [id.replacePrefix rootNamespace .anonymous] | ns@(.str p _) => (ns ++ id) :: scopeCandidates p | _ => [] - let openCandidates := openDecls.filterMap fun + let baseCands := scopeCandidates currNs + let simpleCands := openDecls.filterMap fun | OpenDecl.simple ns _ => some (ns ++ id) - | OpenDecl.explicit aliasId target => - if id == aliasId then some target - else if aliasId.isPrefixOf id then - some (target ++ id.replacePrefix aliasId .anonymous) - else none - (scopeCandidates currNs ++ openCandidates).eraseDups + | _ => none + let expandExplicit (inputs : List Name) : List Name := + openDecls.foldl (init := inputs) fun acc od => + match od with + | OpenDecl.explicit aliasId target => + let hits := inputs.filterMap fun cand => + if cand == aliasId then some target + else if aliasId.isPrefixOf cand then + some (target ++ cand.replacePrefix aliasId .anonymous) + else none + acc ++ hits + | _ => acc + let rec expandFixpoint : Nat → List Name → List Name + | 0, cur => cur + | fuel + 1, cur => + let next := (expandExplicit cur).eraseDups + if next.length == cur.length then cur + else expandFixpoint fuel next + expandFixpoint (openDecls.length + 1) (baseCands ++ simpleCands).eraseDups /-- Lexical scope frame tracked by `parseAndInspectCommands`, mirroring Lean's `Elab.Command.Scope` (`header`, `currNamespace`, `openDecls`) so @@ -260,6 +276,22 @@ openDecls : List OpenDecl deriving Inhabited +/-- Record `export` aliases created in namespace `exportNs` onto every frame +of `scopes` under their absolute exported name `exportNs ++ aliasId` so +`export` aliases survive `section ... end`, `namespace ... end` (including +nested partial closes followed by reopening or `open`), `... in ...`, and +`mutual ... end`. -/ +def persistExportsAcrossScopes (exportNs : Name) (exported : List OpenDecl) + (scopes : List ParseScope) : List ParseScope := + if exported.isEmpty then scopes + else + let qualified := exported.map fun + | OpenDecl.explicit aliasId target => + OpenDecl.explicit (exportNs ++ aliasId) target + | other => other + scopes.map fun s => + { s with openDecls := qualified ++ s.openDecls } + /-- Compose the names of up to the innermost `n` scopes in `ss`, truncating at an unnamed scope, matching `Lean.Elab.Command.nameOfScopes`. -/ def nameOfParseScopes : List ParseScope → Nat → Name @@ -287,8 +319,8 @@ def isAnnealModuleName (moduleName : Name) : Bool := moduleName == `Anneal || moduleName.getRoot == `Anneal -/-- Foundation modules that bundled `Anneal.*` `module`-system theory files may -open via `import all`. -/ +/-- Foundation modules that `Anneal.NatBitwise` may open via `import all` in +Lean 4 `module` mode. -/ def allowedTheoryImportAllModules : List Name := [`Init.Data.Nat.Bitwise.Basic] @@ -323,6 +355,7 @@ otherwise-admitted roots (`Init`, `Std`, `Lean`). -/ def forbiddenSysUvPrefixes : List Name := [ `Init.System, `Std.Internal.UV, `Internal.UV, `Std.Async, `Std.Http, + `Std.Sync, `Lean.LoadDynlib, `Lean.loadDynlib, `Lean.loadPlugin, `Lean.Dynlib, `Dynlib, `Lean.Syntax, `Lean.TSyntax, `Lean.TSyntaxArray, `Lean.SourceInfo, @@ -394,7 +427,7 @@ /-- Return `true` when imported module `m` belongs to `Lean.*`, `Lake.*`, `Init.System.*`, `Init.Meta.*`, `Std`, `Std.Internal`, `Std.Async.*`, -`Std.Http.*`, or `Std.Internal.UV.*`. -/ +`Std.Http.*`, `Std.Sync.*`, or `Std.Internal.UV.*`. -/ def isForbiddenPureImport (m : Name) : Bool := let r := m.getRoot r == `Lean || r == `Lake || @@ -403,13 +436,15 @@ m == `Init.Meta || (`Init.Meta).isPrefixOf m || m == `Std || m == `Std.Internal || m == `Std.Async || (`Std.Async).isPrefixOf m || - m == `Std.Http || (`Std.Http).isPrefixOf m + m == `Std.Http || (`Std.Http).isPrefixOf m || + m == `Std.Sync || (`Std.Sync).isPrefixOf m /-- Return `true` when a transitive sysroot library module `m` exposes `Lean.*`, `Lake.*`, `Std` umbrella, `Std.Internal` umbrella, `Std.Internal.UV.*`, -`Std.Async.*`, or `Std.Http.*`. (`Init.System.*` and `Init.Meta.*` are excluded -from this transitive check because `Init.Data.*` and `Std.Data.*` reach them via -pure helpers, whereas `isForbiddenPureImport` blocks direct imports.) -/ +`Std.Async.*`, `Std.Http.*`, or `Std.Sync.*`. (`Init.System.*` and `Init.Meta.*` +are excluded from this transitive check because `Init.Data.*` and `Std.Data.*` +reach them via pure helpers, whereas `isForbiddenPureImport` blocks direct +imports.) -/ def isForbiddenTransitiveLibrary (m : Name) : Bool := !(m == `Init.System || (`Init.System).isPrefixOf m || m == `Init.Meta || (`Init.Meta).isPrefixOf m) && @@ -420,8 +455,8 @@ non-exported imports unconditionally. - Lean 4 `module` targets (`allowModule = true`) allow private (non-exported) imports across target roles, and permit `import all` - strictly when `allowTheoryImportAll = true` (bundled `Anneal.*` modules) - and the imported module is in `allowedTheoryImportAllModules`. + strictly when `allowTheoryImportAll = true` (the `Anneal.NatBitwise` bridge + module) and the imported module is in `allowedTheoryImportAllModules`. - Every target rejects `Lean.*`/`Lake.*`, `Init.System.*`, and `Std.Internal.UV.*` imports, and any `isMeta` edge other than Lean 4's synthetic `!hasPrelude` `Init(isMeta = true)` paired with a non-meta @@ -447,7 +482,7 @@ /-- Read and validate a target source header (`"headers"`), admitting Lean 4 `module`-system headers across target modules while keeping `import all` -confined strictly to bundled `Anneal.*` runtime modules. -/ +confined strictly to the bundled `Anneal.NatBitwise` bridge module. -/ def inspectHeader (moduleName : Name) (path : System.FilePath) : IO Json := do let text ← IO.FS.readFile path let ctx := Parser.mkInputContext text path.toString @@ -459,7 +494,7 @@ let imports := Elab.HeaderSyntax.imports header validateTargetImports moduleName.toString imports (allowModule := isModule) - (allowTheoryImportAll := isAnnealModuleName moduleName) + (allowTheoryImportAll := moduleName == `Anneal.NatBitwise) return Json.mkObj [ ("module", toJson moduleName), ("imports", toJson imports), @@ -558,15 +593,17 @@ loops). -/ def forbiddenSpecIdentifierComponents : List String := [ "autoParam", "panic", "panicCore", "panicWithPos", "panicWithPosWithDecl", - "outOfBounds", "repeatM", "sliceOrPanic"] + "outOfBounds", "repeatM", "sliceOrPanic", "sorryAx"] /-- Root-level and extern identifiers forbidden in specifications (`autoParam` evaluates a stored `Lean.Syntax` tactic script during elaboration, bypassing syntactic tactic inspection; `panic*` constants carry runtime panic side -effects; and `forbiddenPureIdentifiers` covers debug, dynamic-library, and -`includeStr` externs). -/ +effects; `sorryAx` directly constructs an unproven term; and +`forbiddenPureIdentifiers` covers debug, dynamic-library, and `includeStr` +externs). -/ def forbiddenSpecIdentifiers : List Name := - [`autoParam, `optParam, `panic, `panicCore, `panicWithPos, `panicWithPosWithDecl] ++ + [`autoParam, `optParam, `sorryAx, + `panic, `panicCore, `panicWithPos, `panicWithPosWithDecl] ++ forbiddenPureIdentifiers /-- Exact `System.Platform` declarations admitted in target specifications. -/ @@ -684,6 +721,8 @@ `Lean.Parser.Command.contractDeclVal, `Lean.Parser.Command.requiresClause, `Lean.Parser.Command.ensuresClause, + `Lean.Parser.Command.computedFields, + `Lean.Parser.Command.computedField, `«term∎», `Std.DTreeMap.Internal.Impl.«term✓», `Lean.Parser.Term.dbgTrace, `Lean.Parser.Term.idbg, @@ -1042,7 +1081,11 @@ unless isValidSourceIdent nsId && !hasUnsafeRecComponent nsId do fail s!"invalid open namespace {nsId} in specification" let mut pairs : Array (Name × Name) := #[] - for itemStx in openDecl[2].getArgs do + for itemStx in openDecl[2].getSepArgs do + unless itemStx.isOfKind ``Parser.Command.openRenamingItem && + itemStx.getNumArgs >= 3 && + itemStx[0].isIdent && itemStx[2].isIdent do + fail "invalid open renaming item in specification" let fromId := itemStx[0].getId let toId := itemStx[2].getId unless isValidSourceIdent fromId && !hasUnsafeRecComponent fromId && @@ -1183,6 +1226,45 @@ openDecl.isOfKind ``Parser.Command.openHiding || openDecl.isOfKind ``Parser.Command.openScoped +/-- Collect `OpenDecl.explicit` alias entries introduced by `export` commands +(including inside nested `Command.in` and `Command.mutual` wrappers) under +lexical scope `(currNs, openDecls, parserEnv)`. -/ +partial def collectSpecExportDecls (currNs : Name) (openDecls : List OpenDecl) + (parserEnv : Environment) (stx : Syntax) : IO (List OpenDecl) := do + let k := stx.getKind + if k == ``Parser.Command.export then + let nsId := stx[1].getId + let itemIds := stx[3].getArgs.map Syntax.getId + let mut exported : List OpenDecl := [] + for ns in candidateOpenNamespaces currNs openDecls nsId do + for itemId in itemIds do + exported := OpenDecl.explicit itemId (ns ++ itemId) :: exported + return exported + else if k == ``Parser.Command.in then + let (tmpEnv, tmpOpen) ← + if stx[0].isOfKind ``Parser.Command.open then + validateSpecOpenDecl currNs openDecls parserEnv stx[0][1] + else + pure (parserEnv, openDecls) + collectSpecExportDecls currNs tmpOpen tmpEnv stx[2] + else if k == ``Parser.Command.mutual then + let mut mutEnv := parserEnv + let mut mutOpen := openDecls + let mut exported : List OpenDecl := [] + for child in stx[1].getArgs do + if child.isOfKind ``Parser.Command.open then + let (nextEnv, nextOpen) ← + validateSpecOpenDecl currNs mutOpen mutEnv child[1] + mutEnv := nextEnv + mutOpen := nextOpen + else + let childExports ← collectSpecExportDecls currNs mutOpen mutEnv child + mutOpen := childExports ++ mutOpen + exported := childExports ++ exported + return exported + else + return [] + /-- Recursively validate a specification AST node `s` under lexical scope `(currNs, openDecls)` and dynamic `(commandLikeKinds, tacticLikeKinds)`. -/ partial def inspectSpecSyntax (commandLikeKinds tacticLikeKinds : NameSet) @@ -1221,7 +1303,11 @@ unless allowedSpecTacticKinds.contains k do fail s!"unsupported tactic {k} in specification" -- Structural checks and scope-aware subtrees. - if k == ``Parser.Command.sectionHeader then + if k == hygieneInfoKind then + unless args.size == 1 && args[0]!.isIdent && + args[0]!.getId.isAnonymous && !args[0]!.getId.hasMacroScopes do + fail "invalid hygieneInfo syntax node in specification" + else if k == ``Parser.Command.sectionHeader then validateSpecSectionHeader args isModule else if k == ``Parser.Command.declModifiers then for child in args do @@ -1272,12 +1358,10 @@ let (nc, nt) ← collectSpecParserSets mutEnv mutCmds := nc mutTacs := nt - else if child.isOfKind ``Parser.Command.export then - let nsId := child[1].getId - let itemIds := child[3].getArgs.map Syntax.getId - for ns in candidateOpenNamespaces currNs mutOpen nsId do - for itemId in itemIds do - mutOpen := OpenDecl.explicit itemId (ns ++ itemId) :: mutOpen + else if child.isOfKind ``Parser.Command.export || + child.isOfKind ``Parser.Command.in then + let childExports ← collectSpecExportDecls currNs mutOpen mutEnv child + mutOpen := childExports ++ mutOpen else if k == ``Parser.Command.in then unless args.size == 3 do fail "unsupported command-wrapper shape in specification" @@ -1392,26 +1476,29 @@ return (nextEnv, { top with openDecls := nextOpen } :: scopes.tail!) else if k == ``Parser.Command.export then let top := scopes.head! - let nsId := stx[1].getId - let itemIds := stx[3].getArgs.map Syntax.getId - let mut ods := top.openDecls - for ns in candidateOpenNamespaces top.currNamespace top.openDecls nsId do - for itemId in itemIds do - ods := OpenDecl.explicit itemId (ns ++ itemId) :: ods - return (parserEnv, { top with openDecls := ods } :: scopes.tail!) + let exported ← + collectSpecExportDecls top.currNamespace top.openDecls parserEnv stx + return (parserEnv, + persistExportsAcrossScopes top.currNamespace exported scopes) else if k == ``Parser.Command.in then let top := scopes.head! + let exported ← + collectSpecExportDecls top.currNamespace top.openDecls parserEnv stx let tmpEnv := Parser.parserExtension.pushScope parserEnv let (tmpEnv, tmpScopes) ← applySpecScope tmpEnv (top :: scopes) stx[0] let (tmpEnv, _) ← applySpecScope tmpEnv tmpScopes stx[2] - return (Parser.parserExtension.popScope tmpEnv, scopes) + return (Parser.parserExtension.popScope tmpEnv, + persistExportsAcrossScopes top.currNamespace exported scopes) else if k == ``Parser.Command.mutual then let top := scopes.head! + let exported ← + collectSpecExportDecls top.currNamespace top.openDecls parserEnv stx let mut tmpEnv := Parser.parserExtension.pushScope parserEnv let mut tmpScopes := top :: scopes for child in stx[1].getArgs do (tmpEnv, tmpScopes) ← applySpecScope tmpEnv tmpScopes child - return (Parser.parserExtension.popScope tmpEnv, scopes) + return (Parser.parserExtension.popScope tmpEnv, + persistExportsAcrossScopes top.currNamespace exported scopes) else if k == ``Parser.Command.declaration then match declarationIdent? stx with | some id => @@ -1555,6 +1642,8 @@ if kindStr == "def" || kindStr == "abbrev" || kindStr == "theorem" || kindStr == "instance" then collectLetRecSpecDecls modStr fullUser isPriv false stx[1] acc' + else if kindStr == "structure" || kindStr == "classInductive" then + collectLetRecSpecDecls modStr fullUser isPriv true stx[1] acc' else acc' | some "instance", none => @@ -1722,7 +1811,8 @@ `Lean.Loop, `repeatM, `Lean.LoadDynlib, `Lean.loadDynlib, `Lean.loadPlugin, `Lean.Dynlib, `Lean.getGithash, `Lean.version, - `Init.System, `Std.Internal.UV, `Std.Async, `Std.Http, `Dynlib].any + `Init.System, `Std.Internal.UV, `Std.Async, `Std.Http, `Std.Sync, + `Dynlib].any (fun pre => u == pre || pre.isPrefixOf u) then true else if r == `System then @@ -1812,12 +1902,14 @@ if rootPtr < baseAddr then fail s!"invalid olean root pointer in {m}" let rootOff := rootPtr - baseAddr - if rootOff < oleanHeaderSize + 8 || rootOff + 8 > bytes.size then + if rootOff % 8 != 0 then + fail s!"unaligned olean root pointer in {m}" + if rootOff < oleanHeaderSize + 8 || rootOff + 56 > bytes.size then fail s!"out-of-bounds olean root object in {m}" let numObjs := (bytes.get! (rootOff + 6)).toNat let tag := (bytes.get! (rootOff + 7)).toNat let scalarOff := rootOff + 8 + numObjs * 8 - if tag != 0 || numObjs != 5 || scalarOff >= bytes.size then + if tag != 0 || numObjs != 5 then fail s!"invalid olean ModuleData layout in {m}" let flag := bytes.get! scalarOff if flag == 0 then @@ -1827,30 +1919,33 @@ else fail s!"invalid olean isModule flag in {m}" -/-- Validate `.olean*` / `.ir` artifact part counts for a target module `m`: -non-module targets accept a single monolithic `.olean`, while Lean 4 `module` -targets accept `.olean` plus optional `.olean.server` / `.olean.private` -sidecars (never `.ir`). -/ +/-- Validate `.olean*` / `.ir` artifact part counts for module `m`: non-module +artifacts accept a single monolithic `.olean`, while Lean 4 `module` +artifacts accept `.olean` plus optional `.olean.server` / `.olean.private` +sidecars (never `.ir` when `allowIr` is `false`). -/ def validateTargetArtifactParts (m : Name) (oleanPartCount : Nat) - (irEmpty isModuleArtifact : Bool) : IO Unit := do + (irEmpty isModuleArtifact : Bool) (allowIr : Bool := false) : IO Unit := do + let irOk := allowIr || irEmpty let partsOk := if isModuleArtifact then - oleanPartCount >= 1 && oleanPartCount <= 3 && irEmpty + oleanPartCount >= 1 && oleanPartCount <= 3 && irOk else - oleanPartCount == 1 && irEmpty + oleanPartCount == 1 && irOk unless partsOk do fail s!"companion artifact parts unsupported in {m}" -/-- Validate `.olean*` binary headers, companion base-address chaining, and -primary-part `isModule` policy before `importEnv` mmaps `.olean.server` or -`.olean.private` companion regions via `CompactedRegion.read`. -/ -def validateTargetArtifactPreImport (m : Name) (art : ImportArtifacts) - (expectedIsModule : Bool) : IO Unit := do - let parts := art.oleanParts true - validateTargetArtifactParts m parts.size art.irParts.isEmpty expectedIsModule +/-- Validate a chained sequence of `.olean*` or `.ir.sig`/`.ir` binary region +parts for module `m`: v2 magic, 64 KiB base-address alignment, 64-bit +address-range bounds, 8-byte-aligned in-bounds `ModuleData` root object for +both primary and companion parts, matching 80-byte companion headers, and +64 KiB-aligned companion base-address chaining. Returns the primary part's +`isModule` flag. -/ +def validateOleanRegionChain (m : Name) (parts : Array System.FilePath) + (expectedIsModule? : Option Bool := none) : IO Bool := do let mut prefix0 : Option ByteArray := none let mut prevEndAligned : Option Nat := none let mut primaryIsMod : Option Bool := none + let mut regions : Array (Nat × ByteArray) := #[] for partPath in parts do let bytes ← try IO.FS.readBinFile partPath @@ -1870,9 +1965,16 @@ fail s!"invalid olean v2 header in {m}" let hdrPrefix := bytes.extract 0 80 let baseAddr := readUInt64LE bytes 80 + if baseAddr % 65536 != 0 then + fail s!"unaligned olean base address in {m}" + if baseAddr + bytes.size >= UInt64.size then + fail s!"olean address range overflow in {m}" + regions := regions.push (baseAddr, bytes) match prefix0, prevEndAligned with | none, _ => let isMod ← parsePrimaryOleanIsModule m bytes baseAddr + if let some expected := expectedIsModule? then + validateTargetModuleIsModuleConsistency m isMod expected primaryIsMod := some isMod prefix0 := some hdrPrefix prevEndAligned := some (alignUp64K (baseAddr + bytes.size)) @@ -1881,13 +1983,58 @@ fail s!"mismatched olean companion header in {m}" unless baseAddr == expectedBase do fail s!"mismatched olean companion base address in {m}" + if bytes.size < oleanHeaderSize + 8 then + fail s!"truncated olean companion root pointer in {m}" + let rootPtr := readUInt64LE bytes oleanHeaderSize + let mut resolved : Option (ByteArray × Nat) := none + for (rBase, rBytes) in regions do + if rBase <= rootPtr && rootPtr < rBase + rBytes.size then + resolved := some (rBytes, rootPtr - rBase) + let some (rBytes, rootOff) := resolved + | fail s!"out-of-bounds olean companion root object in {m}" + if rootOff % 8 != 0 then + fail s!"unaligned olean companion root pointer in {m}" + if rootOff < oleanHeaderSize + 8 || rootOff + 56 > rBytes.size then + fail s!"out-of-bounds olean companion root object in {m}" + let numObjs := rBytes.get! (rootOff + 6) + let tag := rBytes.get! (rootOff + 7) + unless numObjs == 5 && tag == 0 do + fail s!"invalid olean companion ModuleData layout in {m}" + let isModByte := rBytes.get! (rootOff + 8 + 5 * 8) + unless isModByte == 0 || isModByte == 1 do + fail s!"invalid olean companion isModule flag in {m}" prevEndAligned := some (alignUp64K (baseAddr + bytes.size)) | _, _ => fail s!"inconsistent olean companion sequence in {m}" let some isMod := primaryIsMod | fail s!"missing primary olean artifact for {m}" - validateTargetModuleIsModuleConsistency m isMod expectedIsModule - validateTargetArtifactParts m parts.size art.irParts.isEmpty isMod + return isMod + +/-- Validate `.olean*` binary headers, 64 KiB base-address alignment, 64-bit +address-range bounds, 8-byte root-pointer alignment, companion base-address +chaining, and primary-part `isModule` policy before `importEnv` or +`importCorrEnv` mmaps regions via `CompactedRegion.read`. -/ +def validateOleanPartsPreImport (m : Name) (parts : Array System.FilePath) + (irEmpty : Bool) (allowIr : Bool) (expectedIsModule? : Option Bool) : + IO Bool := do + match expectedIsModule? with + | some expected => + validateTargetArtifactParts m parts.size irEmpty expected allowIr + | none => + let irOk := allowIr || irEmpty + unless parts.size >= 1 && parts.size <= 3 && irOk do + fail s!"companion artifact parts unsupported in {m}" + let isMod ← validateOleanRegionChain m parts expectedIsModule? + validateTargetArtifactParts m parts.size irEmpty isMod allowIr + return isMod + +/-- Validate target `.olean*` binary headers, companion base-address chaining, +and primary-part `isModule` policy before `importEnv` mmaps `.olean.server` or +`.olean.private` companion regions via `CompactedRegion.read`. -/ +def validateTargetArtifactPreImport (m : Name) (art : ImportArtifacts) + (expectedIsModule : Bool) : IO Unit := do + discard <| validateOleanPartsPreImport m (art.oleanParts true) + art.irParts.isEmpty (allowIr := false) (some expectedIsModule) /-- Return the human-readable kind tag for a kernel `ConstantInfo`. -/ def kind : ConstantInfo → String @@ -2198,6 +2345,10 @@ all := all.push enc if isPairedUnsafeRec env t ci then paired := paired.push enc + let privExtras : NameSet := .ofList data.extraConstNames.toList + for n in data.extraConstNames do + if !seen.contains n && (env.checked.get.find? n).isSome then + fail s!"uninventoried kernel compiler helper {n}" let (targetOv, oleanParts, irParts) ← collectModuleTargetOverrides arts t targetOverridesCache := targetOverridesCache.insert t targetOv for (partData, _) in oleanParts do @@ -2219,6 +2370,12 @@ s!"private inventory of {t}") unless isValidCompanionConstant data.isModule privCi ci do fail s!"mismatched target companion constant {ci.name} in {t}" + for n in partData.extraConstNames do + unless privExtras.contains n || privConsts.contains n do + fail (s!"target companion extraConstName {n} missing from " ++ + s!"private inventory of {t}") + if !seen.contains n && (env.checked.get.find? n).isSome then + fail s!"uninventoried kernel compiler helper {n}" let overrideNames := targetOv.implementedBy ++ targetOv.externDecls ++ targetOv.csimp let overrides :=
diff --git a/trusted/audit/TrustedBoundary.lean b/trusted/audit/TrustedBoundary.lean index 2e864e8..d5cfd3c 100644 --- a/trusted/audit/TrustedBoundary.lean +++ b/trusted/audit/TrustedBoundary.lean
@@ -61,7 +61,7 @@ Parses only module headers via `Parser.parseHeader`, reporting each module's `isModule` flag and `imports` while admitting Lean 4 module-system headers (`module`) across target roles (`Model`, `Capture`, `Specification`, - `Expected`, and `Proof`), rejecting `import all` outside `Anneal.*` + `Expected`, and `Proof`), rejecting `import all` outside `Anneal.NatBitwise` importing `Init.Data.Nat.Bitwise.Basic`, non-exported imports on non-module sources, `meta import` (except Lean 4's synthetic `!hasPrelude` `Init(isMeta = true)` paired with non-meta `Init`), and `Lean.*`/`Lake.*` @@ -951,6 +951,7 @@ otherwise-admitted roots (`Init`, `Std`, `Lean`). -/ def forbiddenSysUvPrefixes : List Name := [ `Init.System, `Std.Internal.UV, `Internal.UV, `Std.Async, `Std.Http, + `Std.Sync, `Lean.LoadDynlib, `Lean.loadDynlib, `Lean.loadPlugin, `Lean.Dynlib, `Dynlib, `Lean.Syntax, `Lean.TSyntax, `Lean.TSyntaxArray, `Lean.SourceInfo, @@ -1054,7 +1055,7 @@ /-- Return `true` when imported module `m` belongs to `Lean.*`, `Lake.*`, `Init.System.*`, `Init.Meta.*`, `Std`, `Std.Internal`, `Std.Async.*`, -`Std.Http.*`, or `Std.Internal.UV.*`. -/ +`Std.Http.*`, `Std.Sync.*`, or `Std.Internal.UV.*`. -/ def isForbiddenPureImport (m : Name) : Bool := let r := m.getRoot r == `Lean || r == `Lake || @@ -1063,13 +1064,15 @@ m == `Init.Meta || (`Init.Meta).isPrefixOf m || m == `Std || m == `Std.Internal || m == `Std.Async || (`Std.Async).isPrefixOf m || - m == `Std.Http || (`Std.Http).isPrefixOf m + m == `Std.Http || (`Std.Http).isPrefixOf m || + m == `Std.Sync || (`Std.Sync).isPrefixOf m /-- Return `true` when a transitive sysroot library module `m` exposes `Lean.*`, `Lake.*`, `Std` umbrella, `Std.Internal` umbrella, `Std.Internal.UV.*`, -`Std.Async.*`, or `Std.Http.*`. (`Init.System.*` and `Init.Meta.*` are excluded -from this transitive check because `Init.Data.*` and `Std.Data.*` reach them via -pure helpers, whereas `isForbiddenPureImport` blocks direct imports.) -/ +`Std.Async.*`, `Std.Http.*`, or `Std.Sync.*`. (`Init.System.*` and `Init.Meta.*` +are excluded from this transitive check because `Init.Data.*` and `Std.Data.*` +reach them via pure helpers, whereas `isForbiddenPureImport` blocks direct +imports.) -/ def isForbiddenTransitiveLibrary (m : Name) : Bool := !(m == `Init.System || (`Init.System).isPrefixOf m || m == `Init.Meta || (`Init.Meta).isPrefixOf m) && @@ -1107,15 +1110,16 @@ `Nat.mod, `Nat.div, `Nat.beq, `Nat.ble, `Nat.land, `Nat.lor, `Nat.xor, `Nat.shiftLeft, `Nat.shiftRight, `String.ofList] -/-- Return `true` if `id` is a valid user-written identifier with non-empty -string components, no macro scopes, and no `_root_` namespace escape. -/ +/-- Return `true` if `id` is a non-anonymous user-written identifier with +non-empty string components, no macro scopes, and no `_root_` namespace +escape. -/ def isValidSourceIdent (id : Name) : Bool := - id.isAnonymous || - (!id.hasMacroScopes && id.eraseMacroScopes == id && - !id.toString.isEmpty && - id.components.all fun - | .str .anonymous seg => !seg.isEmpty && seg != "_root_" - | _ => false) + !id.isAnonymous && + !id.hasMacroScopes && id.eraseMacroScopes == id && + !id.toString.isEmpty && + id.components.all fun + | .str .anonymous seg => !seg.isEmpty && seg != "_root_" + | _ => false /-- Return `true` iff `moduleName` belongs to the `Trusted` root namespace (`Trusted` or `Trusted.*`). -/ @@ -1248,14 +1252,28 @@ | .anonymous => [id.replacePrefix rootNamespace .anonymous] | ns@(.str p _) => (ns ++ id) :: scopeCandidates p | _ => [] - let openCandidates := openDecls.filterMap fun + let baseCands := scopeCandidates currNs + let simpleCands := openDecls.filterMap fun | OpenDecl.simple ns _ => some (ns ++ id) - | OpenDecl.explicit aliasId target => - if id == aliasId then some target - else if aliasId.isPrefixOf id then - some (target ++ id.replacePrefix aliasId .anonymous) - else none - (scopeCandidates currNs ++ openCandidates).eraseDups + | _ => none + let expandExplicit (inputs : List Name) : List Name := + openDecls.foldl (init := inputs) fun acc od => + match od with + | OpenDecl.explicit aliasId target => + let hits := inputs.filterMap fun cand => + if cand == aliasId then some target + else if aliasId.isPrefixOf cand then + some (target ++ cand.replacePrefix aliasId .anonymous) + else none + acc ++ hits + | _ => acc + let rec expandFixpoint : Nat → List Name → List Name + | 0, cur => cur + | fuel + 1, cur => + let next := (expandExplicit cur).eraseDups + if next.length == cur.length then cur + else expandFixpoint fuel next + expandFixpoint (openDecls.length + 1) (baseCands ++ simpleCands).eraseDups /-- Extend `openDecls` conservatively across an admitted `Parser.Command.open` (`openSimple`) or `Parser.Command.export` node so `Parser.Command.in` and @@ -1292,6 +1310,39 @@ else openDecls +/-- Collect `OpenDecl.explicit` aliases introduced by `export` commands within +`stx` (including nested `Command.in` and `Command.mutual` wrappers) under +`(currNs, openDecls)` for repository-source scope tracking. Because Lean 4's +`export` mutates the enclosing environment rather than the temporary `in` / +`mutual` scope, these aliases persist after the wrapper closes. -/ +partial def collectRepoExportDecls (currNs : Name) (openDecls : List OpenDecl) + (stx : Syntax) : List OpenDecl := + let k := stx.getKind + if k == ``Parser.Command.export && stx.getArgs.size == 5 then + let nsId := stx[1].getId + let itemIds := stx[3].getArgs.map Syntax.getId + Id.run do + let mut added : List OpenDecl := [] + for ns in candidateOpenNamespaces currNs openDecls nsId do + for itemId in itemIds do + added := OpenDecl.explicit itemId (ns ++ itemId) :: added + return added + else if k == ``Parser.Command.in && stx.getArgs.size >= 3 then + let innerOpen := extendOpenDeclsForOpenCmd currNs openDecls stx[0] + collectRepoExportDecls currNs innerOpen stx[2] + else if k == ``Parser.Command.mutual && stx.getArgs.size >= 2 then + Id.run do + let mut ods := openDecls + let mut added : List OpenDecl := [] + for child in stx[1].getArgs do + let childExports := collectRepoExportDecls currNs ods child + added := childExports ++ added + ods := extendOpenDeclsForOpenCmd currNs ods child + ods := childExports ++ ods + return added + else + [] + /-- Validate `export ns (id1 ...)` in repository preflight (`"preflight"` and `"correspondence-preflight"`), rejecting forbidden namespaces, resolved qualified items `ns ++ itemId`, and forbidden/reserved created alias names @@ -1426,6 +1477,11 @@ unless k == nullKind || allowedKinds.contains k do fail s!"unsupported syntax kind {k}" inspectNodeKind k args requirePrelude + if k == hygieneInfoKind then + unless args.size == 1 && args[0]!.isIdent && + args[0]!.getId.isAnonymous && !args[0]!.getId.hasMacroScopes do + fail "invalid hygieneInfo syntax node" + return if k == ``Parser.Command.in && checkPureRefs then inspectSyntax allowedKinds args[0]! requirePrelude currNs openDecls checkPureRefs isTrusted @@ -1441,7 +1497,9 @@ for child in args[1]!.getArgs do inspectSyntax allowedKinds child requirePrelude currNs mutOpen checkPureRefs isTrusted + let childExports := collectRepoExportDecls currNs mutOpen child mutOpen := extendOpenDeclsForOpenCmd currNs mutOpen child + mutOpen := childExports ++ mutOpen inspectSyntax allowedKinds args[2]! requirePrelude currNs openDecls checkPureRefs isTrusted else if (k == ``Parser.Command.open || k == ``Parser.Command.namespace) && @@ -1526,6 +1584,22 @@ openDecls : List OpenDecl deriving Inhabited +/-- Record `export` aliases created in namespace `exportNs` onto every frame +of `scopes` under their absolute exported name `exportNs ++ aliasId` so +`export` aliases survive `section ... end`, `namespace ... end` (including +nested partial closes followed by reopening or `open`), `... in ...`, and +`mutual ... end`. -/ +def persistExportsAcrossScopes (exportNs : Name) (exported : List OpenDecl) + (scopes : List ParseScope) : List ParseScope := + if exported.isEmpty then scopes + else + let qualified := exported.map fun + | OpenDecl.explicit aliasId target => + OpenDecl.explicit (exportNs ++ aliasId) target + | other => other + scopes.map fun s => + { s with openDecls := qualified ++ s.openDecls } + /-- Compose the names of up to the innermost `n` scopes in `ss`, truncating at an unnamed scope, matching `Lean.Elab.Command.nameOfScopes`. -/ def nameOfParseScopes : List ParseScope → Nat → Name @@ -1736,11 +1810,11 @@ for itemId in itemIds do let _ ← checkDeclNamespacePrefixes scopedNamespaces top.currNamespace itemId parserEnv - let mut ods := top.openDecls + let mut added : List OpenDecl := [] for ns in candidateOpenNamespaces top.currNamespace top.openDecls nsId do for itemId in itemIds do - ods := OpenDecl.explicit itemId (ns ++ itemId) :: ods - return (parserEnv, { top with openDecls := ods } :: scopes.tail!) + added := OpenDecl.explicit itemId (ns ++ itemId) :: added + return (parserEnv, persistExportsAcrossScopes top.currNamespace added scopes) else if k == ``Parser.Command.in then let top := scopes.head! let tmpEnv := Parser.parserExtension.pushScope parserEnv @@ -1749,7 +1823,9 @@ stx[0] let (tmpEnv, _) ← applyCommandScope scopedNamespaces scopedPrefixes tmpEnv tmpScopes stx[2] - return (Parser.parserExtension.popScope tmpEnv, scopes) + let exported := collectRepoExportDecls top.currNamespace top.openDecls stx + return (Parser.parserExtension.popScope tmpEnv, + persistExportsAcrossScopes top.currNamespace exported scopes) else if k == ``Parser.Command.mutual then let top := scopes.head! let mut tmpEnv := Parser.parserExtension.pushScope parserEnv @@ -1757,7 +1833,9 @@ for child in stx[1].getArgs do (tmpEnv, tmpScopes) ← applyCommandScope scopedNamespaces scopedPrefixes tmpEnv tmpScopes child - return (Parser.parserExtension.popScope tmpEnv, scopes) + let exported := collectRepoExportDecls top.currNamespace top.openDecls stx + return (Parser.parserExtension.popScope tmpEnv, + persistExportsAcrossScopes top.currNamespace exported scopes) else if k == ``Parser.Command.declaration then let currNs := scopes.head!.currNamespace let declRoot := match declarationIdent? stx with @@ -1892,7 +1970,7 @@ fail "import modifiers are unsupported" if imp.importAll then let allowImportAll := - isModule && role == .theory && + isModule && role == .theory && moduleName == `Anneal.NatBitwise && allowedTheoryImportAllModules.contains imp.module unless allowImportAll do fail "import modifiers are unsupported" @@ -1913,8 +1991,8 @@ non-exported imports unconditionally. - Lean 4 `module` targets (`allowModule = true`) allow private (non-exported) imports across target roles, and permit `import all` - strictly when `allowTheoryImportAll = true` (bundled `Anneal.*` modules) - and the imported module is in `allowedTheoryImportAllModules`. + strictly when `allowTheoryImportAll = true` (the `Anneal.NatBitwise` bridge + module) and the imported module is in `allowedTheoryImportAllModules`. - Every target rejects `Lean.*`/`Lake.*`, `Init.System.*`, and `Std.Internal.UV.*` imports, and any `isMeta` edge other than Lean 4's synthetic `!hasPrelude` `Init(isMeta = true)` paired with a non-meta @@ -1940,7 +2018,7 @@ /-- Read and validate a target source header (`"headers"`), admitting Lean 4 `module`-system headers across target modules while keeping `import all` -confined strictly to bundled `Anneal.*` runtime modules. -/ +confined strictly to the bundled `Anneal.NatBitwise` bridge module. -/ def inspectHeader (moduleName : Name) (path : System.FilePath) : IO Json := do let text ← IO.FS.readFile path let ctx := Parser.mkInputContext text path.toString @@ -1953,7 +2031,7 @@ let imports := Elab.HeaderSyntax.imports header validateTargetImports moduleName.toString imports (allowModule := isModule) - (allowTheoryImportAll := isAnnealModuleName moduleName) + (allowTheoryImportAll := moduleName == `Anneal.NatBitwise) return Json.mkObj [ ("module", toJson moduleName), ("imports", toJson imports), @@ -2070,15 +2148,17 @@ loops). -/ def forbiddenSpecIdentifierComponents : List String := [ "autoParam", "panic", "panicCore", "panicWithPos", "panicWithPosWithDecl", - "outOfBounds", "repeatM", "sliceOrPanic"] + "outOfBounds", "repeatM", "sliceOrPanic", "sorryAx"] /-- Root-level and extern identifiers forbidden in specifications (`autoParam` evaluates a stored `Lean.Syntax` tactic script during elaboration, bypassing syntactic tactic inspection; `panic*` constants carry runtime panic side -effects; and `forbiddenPureIdentifiers` covers debug, dynamic-library, and -`includeStr` externs). -/ +effects; `sorryAx` directly constructs an unproven term; and +`forbiddenPureIdentifiers` covers debug, dynamic-library, and `includeStr` +externs). -/ def forbiddenSpecIdentifiers : List Name := - [`autoParam, `optParam, `panic, `panicCore, `panicWithPos, `panicWithPosWithDecl] ++ + [`autoParam, `optParam, `sorryAx, + `panic, `panicCore, `panicWithPos, `panicWithPosWithDecl] ++ forbiddenPureIdentifiers /-- Simple attributes permitted inside `@[...]` in target specifications. -/ @@ -2190,6 +2270,8 @@ `Lean.Parser.Command.contractDeclVal, `Lean.Parser.Command.requiresClause, `Lean.Parser.Command.ensuresClause, + `Lean.Parser.Command.computedFields, + `Lean.Parser.Command.computedField, `«term∎», `Std.DTreeMap.Internal.Impl.«term✓», `Lean.Parser.Term.dbgTrace, `Lean.Parser.Term.idbg, @@ -2538,7 +2620,11 @@ unless isValidSourceIdent nsId && !hasUnsafeRecComponent nsId do fail s!"invalid open namespace {nsId} in specification" let mut pairs : Array (Name × Name) := #[] - for itemStx in openDecl[2].getArgs do + for itemStx in openDecl[2].getSepArgs do + unless itemStx.isOfKind ``Parser.Command.openRenamingItem && + itemStx.getNumArgs >= 3 && + itemStx[0].isIdent && itemStx[2].isIdent do + fail "invalid open renaming item in specification" let fromId := itemStx[0].getId let toId := itemStx[2].getId unless isValidSourceIdent fromId && !hasUnsafeRecComponent fromId && @@ -2679,6 +2765,45 @@ openDecl.isOfKind ``Parser.Command.openHiding || openDecl.isOfKind ``Parser.Command.openScoped +/-- Collect `OpenDecl.explicit` alias entries introduced by `export` commands +(including inside nested `Command.in` and `Command.mutual` wrappers) under +lexical scope `(currNs, openDecls, parserEnv)`. -/ +partial def collectSpecExportDecls (currNs : Name) (openDecls : List OpenDecl) + (parserEnv : Environment) (stx : Syntax) : IO (List OpenDecl) := do + let k := stx.getKind + if k == ``Parser.Command.export then + let nsId := stx[1].getId + let itemIds := stx[3].getArgs.map Syntax.getId + let mut exported : List OpenDecl := [] + for ns in candidateOpenNamespaces currNs openDecls nsId do + for itemId in itemIds do + exported := OpenDecl.explicit itemId (ns ++ itemId) :: exported + return exported + else if k == ``Parser.Command.in then + let (tmpEnv, tmpOpen) ← + if stx[0].isOfKind ``Parser.Command.open then + validateSpecOpenDecl currNs openDecls parserEnv stx[0][1] + else + pure (parserEnv, openDecls) + collectSpecExportDecls currNs tmpOpen tmpEnv stx[2] + else if k == ``Parser.Command.mutual then + let mut mutEnv := parserEnv + let mut mutOpen := openDecls + let mut exported : List OpenDecl := [] + for child in stx[1].getArgs do + if child.isOfKind ``Parser.Command.open then + let (nextEnv, nextOpen) ← + validateSpecOpenDecl currNs mutOpen mutEnv child[1] + mutEnv := nextEnv + mutOpen := nextOpen + else + let childExports ← collectSpecExportDecls currNs mutOpen mutEnv child + mutOpen := childExports ++ mutOpen + exported := childExports ++ exported + return exported + else + return [] + /-- Recursively validate a specification AST node `s` under lexical scope `(currNs, openDecls)` and dynamic `(commandLikeKinds, tacticLikeKinds)`. -/ partial def inspectSpecSyntax (commandLikeKinds tacticLikeKinds : NameSet) @@ -2717,7 +2842,11 @@ unless allowedSpecTacticKinds.contains k do fail s!"unsupported tactic {k} in specification" -- Structural checks and scope-aware subtrees. - if k == ``Parser.Command.sectionHeader then + if k == hygieneInfoKind then + unless args.size == 1 && args[0]!.isIdent && + args[0]!.getId.isAnonymous && !args[0]!.getId.hasMacroScopes do + fail "invalid hygieneInfo syntax node in specification" + else if k == ``Parser.Command.sectionHeader then validateSpecSectionHeader args isModule else if k == ``Parser.Command.declModifiers then for child in args do @@ -2768,12 +2897,10 @@ let (nc, nt) ← collectSpecParserSets mutEnv mutCmds := nc mutTacs := nt - else if child.isOfKind ``Parser.Command.export then - let nsId := child[1].getId - let itemIds := child[3].getArgs.map Syntax.getId - for ns in candidateOpenNamespaces currNs mutOpen nsId do - for itemId in itemIds do - mutOpen := OpenDecl.explicit itemId (ns ++ itemId) :: mutOpen + else if child.isOfKind ``Parser.Command.export || + child.isOfKind ``Parser.Command.in then + let childExports ← collectSpecExportDecls currNs mutOpen mutEnv child + mutOpen := childExports ++ mutOpen else if k == ``Parser.Command.in then unless args.size == 3 do fail "unsupported command-wrapper shape in specification" @@ -2888,26 +3015,29 @@ return (nextEnv, { top with openDecls := nextOpen } :: scopes.tail!) else if k == ``Parser.Command.export then let top := scopes.head! - let nsId := stx[1].getId - let itemIds := stx[3].getArgs.map Syntax.getId - let mut ods := top.openDecls - for ns in candidateOpenNamespaces top.currNamespace top.openDecls nsId do - for itemId in itemIds do - ods := OpenDecl.explicit itemId (ns ++ itemId) :: ods - return (parserEnv, { top with openDecls := ods } :: scopes.tail!) + let exported ← + collectSpecExportDecls top.currNamespace top.openDecls parserEnv stx + return (parserEnv, + persistExportsAcrossScopes top.currNamespace exported scopes) else if k == ``Parser.Command.in then let top := scopes.head! + let exported ← + collectSpecExportDecls top.currNamespace top.openDecls parserEnv stx let tmpEnv := Parser.parserExtension.pushScope parserEnv let (tmpEnv, tmpScopes) ← applySpecScope tmpEnv (top :: scopes) stx[0] let (tmpEnv, _) ← applySpecScope tmpEnv tmpScopes stx[2] - return (Parser.parserExtension.popScope tmpEnv, scopes) + return (Parser.parserExtension.popScope tmpEnv, + persistExportsAcrossScopes top.currNamespace exported scopes) else if k == ``Parser.Command.mutual then let top := scopes.head! + let exported ← + collectSpecExportDecls top.currNamespace top.openDecls parserEnv stx let mut tmpEnv := Parser.parserExtension.pushScope parserEnv let mut tmpScopes := top :: scopes for child in stx[1].getArgs do (tmpEnv, tmpScopes) ← applySpecScope tmpEnv tmpScopes child - return (Parser.parserExtension.popScope tmpEnv, scopes) + return (Parser.parserExtension.popScope tmpEnv, + persistExportsAcrossScopes top.currNamespace exported scopes) else if k == ``Parser.Command.declaration then match declarationIdent? stx with | some id => @@ -3092,6 +3222,8 @@ if kindStr == "def" || kindStr == "abbrev" || kindStr == "theorem" || kindStr == "instance" then collectLetRecSpecDecls modStr fullUser isPriv false stx[1] acc' + else if kindStr == "structure" || kindStr == "classInductive" then + collectLetRecSpecDecls modStr fullUser isPriv true stx[1] acc' else acc' | some "instance", none => @@ -4512,9 +4644,13 @@ `includeDeclAttrs` is `true` (repository Pass 1/Pass 2 audits), declaration-level `@[implemented_by]`, `@[extern]`, and `@[csimp]` entries fail unconditionally; `"target-audit"` passes `false` and checks those three on -logically reached dependencies authored by target source modules. -/ +logically reached dependencies authored by target source modules. When +`allowInit` is `true` (Pass 2 `.vendorMiri` modules imported with +`loadExts := false`), `[init]` declarations are permitted while all other +compiler overrides and hooks remain rejected. -/ def rejectForbiddenCompilerOverrides (ov : ProofCompilerOverrides) - (ctxSuffix : String) (includeDeclAttrs : Bool) : IO Unit := do + (ctxSuffix : String) (includeDeclAttrs : Bool) + (allowInit : Bool := false) : IO Unit := do let declAttrChecks : List (NameSet × String) := if includeDeclAttrs then [ (ov.implementedBy, "unchecked compiler implemented_by override on "), @@ -4522,10 +4658,13 @@ (ov.csimp, "authored compiler csimp replacement on ") ] else [] + let initChecks : List (NameSet × String) := + if allowInit then [] + else [ (ov.initDecls, "unchecked compiler init override on ") ] let moduleHookChecks : List (NameSet × String) := - [ (ov.exportDecls, "unchecked compiler export override on "), - (ov.initDecls, "unchecked compiler init override on "), - (ov.builtinInitDecls, "unchecked compiler builtin_init override on "), + [ (ov.exportDecls, "unchecked compiler export override on ") ] ++ + initChecks ++ + [ (ov.builtinInitDecls, "unchecked compiler builtin_init override on "), (ov.cpassDecls, "unchecked compiler cpass override "), (ov.constantFoldDecls, "unchecked compiler constant_fold override on "), (ov.postponedDecls, "unchecked postponed compilation entry for ") ] @@ -4587,6 +4726,428 @@ fail (s!"disallowed unsafe/partial/axiom export target {targetName} " ++ s!"in {m}") +/-- Fail closed when module `m`'s compiled `isModule` header flag `actual` +differs from the `"isModule"` expectation `expected` derived from the staged +source header. -/ +private def validateTargetModuleIsModuleConsistency (m : Name) + (actual expected : Bool) : IO Unit := do + if !expected && actual then + fail s!"module-system artifact unsupported in {m}" + else if expected && !actual then + fail s!"non-module artifact mismatch in {m}" + +private def oleanHeaderSize : Nat := 88 + +private def readUInt64LE (bytes : ByteArray) (off : Nat) : Nat := + (bytes.get! off).toNat + + ((bytes.get! (off + 1)).toNat <<< 8) + + ((bytes.get! (off + 2)).toNat <<< 16) + + ((bytes.get! (off + 3)).toNat <<< 24) + + ((bytes.get! (off + 4)).toNat <<< 32) + + ((bytes.get! (off + 5)).toNat <<< 40) + + ((bytes.get! (off + 6)).toNat <<< 48) + + ((bytes.get! (off + 7)).toNat <<< 56) + +private def alignUp64K (n : Nat) : Nat := + ((n + 65535) / 65536) * 65536 + +/-- Pure, bounds-checked read of `ModuleData.isModule` from the root object of +a primary `.olean` v2 file without invoking `CompactedRegion.read` or `mmap`. -/ +private def parsePrimaryOleanIsModule (m : Name) (bytes : ByteArray) + (baseAddr : Nat) : IO Bool := do + if bytes.size < oleanHeaderSize + 8 then + fail s!"truncated olean root pointer in {m}" + let rootPtr := readUInt64LE bytes oleanHeaderSize + if rootPtr < baseAddr then + fail s!"invalid olean root pointer in {m}" + let rootOff := rootPtr - baseAddr + if rootOff % 8 != 0 then + fail s!"unaligned olean root pointer in {m}" + if rootOff < oleanHeaderSize + 8 || rootOff + 56 > bytes.size then + fail s!"out-of-bounds olean root object in {m}" + let numObjs := (bytes.get! (rootOff + 6)).toNat + let tag := (bytes.get! (rootOff + 7)).toNat + let scalarOff := rootOff + 8 + numObjs * 8 + if tag != 0 || numObjs != 5 then + fail s!"invalid olean ModuleData layout in {m}" + let flag := bytes.get! scalarOff + if flag == 0 then + return false + else if flag == 1 then + return true + else + fail s!"invalid olean isModule flag in {m}" + +/-- Validate `.olean*` / `.ir` artifact part counts for a module `m`: +non-module artifacts accept a single monolithic `.olean`, while Lean 4 `module` +artifacts accept `.olean` plus optional `.olean.server` / `.olean.private` +sidecars (never `.ir` when `allowIr` is `false`). -/ +def validateTargetArtifactParts (m : Name) (oleanPartCount : Nat) + (irEmpty isModuleArtifact : Bool) (allowIr : Bool := false) : IO Unit := do + let irOk := allowIr || irEmpty + let partsOk := + if isModuleArtifact then + oleanPartCount >= 1 && oleanPartCount <= 3 && irOk + else + oleanPartCount == 1 && irOk + unless partsOk do + fail s!"companion artifact parts unsupported in {m}" + +/-- Validate a chained sequence of `.olean*` or `.ir.sig`/`.ir` binary region +parts for module `m`: v2 magic, 64 KiB base-address alignment, 64-bit +address-range bounds, 8-byte-aligned in-bounds `ModuleData` root object for +both primary and companion parts, matching 80-byte companion headers, and +64 KiB-aligned companion base-address chaining. Returns the primary part's +`isModule` flag. -/ +def validateOleanRegionChain (m : Name) (parts : Array System.FilePath) + (expectedIsModule? : Option Bool := none) : IO Bool := do + let mut prefix0 : Option ByteArray := none + let mut prevEndAligned : Option Nat := none + let mut primaryIsMod : Option Bool := none + let mut regions : Array (Nat × ByteArray) := #[] + for partPath in parts do + let bytes ← try + IO.FS.readBinFile partPath + catch e => + throw <| IO.userError + s!"missing or unreadable artifact part {partPath} for {m}: {e}" + if bytes.size < oleanHeaderSize then + fail s!"truncated olean header in {m}" + let magicOk := + bytes.get! 0 == 'o'.toNat.toUInt8 && + bytes.get! 1 == 'l'.toNat.toUInt8 && + bytes.get! 2 == 'e'.toNat.toUInt8 && + bytes.get! 3 == 'a'.toNat.toUInt8 && + bytes.get! 4 == 'n'.toNat.toUInt8 && + bytes.get! 5 == 2 + unless magicOk do + fail s!"invalid olean v2 header in {m}" + let hdrPrefix := bytes.extract 0 80 + let baseAddr := readUInt64LE bytes 80 + if baseAddr % 65536 != 0 then + fail s!"unaligned olean base address in {m}" + if baseAddr + bytes.size >= UInt64.size then + fail s!"olean address range overflow in {m}" + regions := regions.push (baseAddr, bytes) + match prefix0, prevEndAligned with + | none, _ => + let isMod ← parsePrimaryOleanIsModule m bytes baseAddr + if let some expected := expectedIsModule? then + validateTargetModuleIsModuleConsistency m isMod expected + primaryIsMod := some isMod + prefix0 := some hdrPrefix + prevEndAligned := some (alignUp64K (baseAddr + bytes.size)) + | some expectedPrefix, some expectedBase => + unless hdrPrefix == expectedPrefix do + fail s!"mismatched olean companion header in {m}" + unless baseAddr == expectedBase do + fail s!"mismatched olean companion base address in {m}" + if bytes.size < oleanHeaderSize + 8 then + fail s!"truncated olean companion root pointer in {m}" + let rootPtr := readUInt64LE bytes oleanHeaderSize + let mut resolved : Option (ByteArray × Nat) := none + for (rBase, rBytes) in regions do + if rBase <= rootPtr && rootPtr < rBase + rBytes.size then + resolved := some (rBytes, rootPtr - rBase) + let some (rBytes, rootOff) := resolved + | fail s!"out-of-bounds olean companion root object in {m}" + if rootOff % 8 != 0 then + fail s!"unaligned olean companion root pointer in {m}" + if rootOff < oleanHeaderSize + 8 || rootOff + 56 > rBytes.size then + fail s!"out-of-bounds olean companion root object in {m}" + let numObjs := rBytes.get! (rootOff + 6) + let tag := rBytes.get! (rootOff + 7) + unless numObjs == 5 && tag == 0 do + fail s!"invalid olean companion ModuleData layout in {m}" + let isModByte := rBytes.get! (rootOff + 8 + 5 * 8) + unless isModByte == 0 || isModByte == 1 do + fail s!"invalid olean companion isModule flag in {m}" + prevEndAligned := some (alignUp64K (baseAddr + bytes.size)) + | _, _ => + fail s!"inconsistent olean companion sequence in {m}" + let some isMod := primaryIsMod + | fail s!"missing primary olean artifact for {m}" + return isMod + +/-- Validate `.olean*` binary headers, 64 KiB base-address alignment, 64-bit +address-range bounds, 8-byte root-pointer alignment, companion base-address +chaining, and primary-part `isModule` policy before `importEnv` or +`importCorrEnv` mmaps regions via `CompactedRegion.read`. -/ +def validateOleanPartsPreImport (m : Name) (parts : Array System.FilePath) + (irEmpty : Bool) (allowIr : Bool) (expectedIsModule? : Option Bool) : + IO Bool := do + match expectedIsModule? with + | some expected => + validateTargetArtifactParts m parts.size irEmpty expected allowIr + | none => + let irOk := allowIr || irEmpty + unless parts.size >= 1 && parts.size <= 3 && irOk do + fail s!"companion artifact parts unsupported in {m}" + let isMod ← validateOleanRegionChain m parts expectedIsModule? + validateTargetArtifactParts m parts.size irEmpty isMod allowIr + return isMod + +/-- Validate target `.olean*` binary headers, companion base-address chaining, +and primary-part `isModule` policy before `importEnv` mmaps `.olean.server` or +`.olean.private` companion regions via `CompactedRegion.read`. -/ +def validateTargetArtifactPreImport (m : Name) (art : ImportArtifacts) + (expectedIsModule : Bool) : IO Unit := do + discard <| validateOleanPartsPreImport m (art.oleanParts true) + art.irParts.isEmpty (allowIr := false) (some expectedIsModule) + +/-- Parse optional `"moduleIsModule"` (`Array (String × Bool)`) expectations +for repository or correspondence modules, rejecting duplicates and unknown +module entries, and requiring full coverage whenever +`"requireAllModuleIsModule"` is `true`. -/ +def parseModuleIsModule (j : Json) (allowedModules : Array Name) : + IO (Std.HashMap Name Bool) := do + let allowedSet : NameSet := .ofList allowedModules.toList + let requireAll ← + match j.getObjVal? "requireAllModuleIsModule" with + | .error _ => pure false + | .ok v => + match fromJson? (α := Bool) v with + | .ok b => pure b + | .error _ => fail "invalid requireAllModuleIsModule" + match j.getObjVal? "moduleIsModule" with + | .error _ => + if requireAll && !allowedModules.isEmpty then + fail "missing required moduleIsModule expectations" + return {} + | .ok _ => + let entries ← field (α := Array (String × Bool)) j "moduleIsModule" + let mut out : Std.HashMap Name Bool := {} + for (modStr, isMod) in entries do + let m := modStr.toName + if out.contains m then + fail s!"duplicate moduleIsModule entry for {m}" + unless allowedSet.contains m do + fail s!"unexpected moduleIsModule entry for {m}" + out := out.insert m isMod + if requireAll then + for m in allowedModules do + unless out.contains m do + fail s!"missing expected isModule for {m}" + return out + +/-- Validate pre-import `.olean*` and foundation `.ir*` headers, alignment, +base-address chaining, and `isModule` expectations for every module present in +`arts` before `importEnv` mmaps any region in Pass 1 `"audit"`. Repository +modules (`mods`) forbid `.ir` parts (`allowIr := false`); sysroot foundation +artifacts permit `.ir` parts after validating their `.ir.sig`/`.ir` region +chain via `validateOleanRegionChain`. -/ +def validateRepoArtifactsPreImport (arts : NameMap ImportArtifacts) + (mods : Array Name) (expectedIsMod : Std.HashMap Name Bool) : IO Unit := do + let repoSet : NameSet := .ofList mods.toList + for (m, art) in arts.toList do + let isRepo := repoSet.contains m + discard <| validateOleanPartsPreImport m (art.oleanParts true) + art.irParts.isEmpty (allowIr := !isRepo) (expectedIsMod.get? m) + if !isRepo && !art.irParts.isEmpty then + discard <| validateOleanRegionChain m art.irParts + +/-- Validate optional `.ir.sig` / `.ir` sibling artifacts beside `mFile` before +`importCorrEnv` mmaps them via `CompactedRegion.read` (at `level := .private`, +Lean's `importModulesCore` mmaps `.ir.sig` + `.ir` whenever `.ir.sig` exists). +Returns `true` when neither `.ir.sig` nor `.ir` is present. -/ +def validateIrPartsPreImport (m : Name) (mFile : System.FilePath) : IO Bool := do + let irSigPath := mFile.withExtension "ir.sig" + let irPath := mFile.withExtension "ir" + let hasIrSig ← irSigPath.pathExists + let hasIr ← irPath.pathExists + if !hasIrSig && !hasIr then + return true + if !hasIrSig && hasIr then + fail s!"orphaned .ir artifact without .ir.sig in {m}" + let irParts := if hasIr then #[irSigPath, irPath] else #[irSigPath] + discard <| validateOleanRegionChain m irParts + return false + +/-- Resolve an 8-byte aligned pointer `ptr` inside pre-validated `.olean*` +regions `(baseAddr, bytes)` without invoking `CompactedRegion.read`. -/ +def resolveOleanPtr (m : Name) (regions : Array (Nat × ByteArray)) (ptr : Nat) : + IO (ByteArray × Nat) := do + if ptr % 2 != 0 then + fail s!"unexpected scalar pointer in olean imports of {m}" + for (base, bytes) in regions do + if base <= ptr && ptr < base + bytes.size then + let off := ptr - base + if off % 8 != 0 then + fail s!"unaligned olean import object pointer in {m}" + return (bytes, off) + fail s!"out-of-bounds olean import pointer in {m}" + +/-- Read a Lean `String` object (tag `249`) from pre-validated `.olean*` +regions. -/ +def readOleanString (m : Name) (regions : Array (Nat × ByteArray)) (ptr : Nat) : + IO String := do + let (b, off) ← resolveOleanPtr m regions ptr + unless off + 32 <= b.size && b.get! (off + 7) == 249 do + fail s!"invalid olean string object in {m}" + let sz := readUInt64LE b (off + 8) + unless sz >= 1 && sz <= b.size - (off + 32) do + fail s!"out-of-bounds olean string in {m}" + let raw := b.extract (off + 32) (off + 32 + sz - 1) + match String.fromUTF8? raw with + | some s => return s + | none => fail s!"invalid UTF-8 in olean import name of {m}" + +/-- Read a Lean `Name` object from pre-validated `.olean*` regions with bounded +recursion depth. -/ +def readOleanName (m : Name) (regions : Array (Nat × ByteArray)) (ptr : Nat) : + Nat → IO Name + | 0 => fail s!"olean import name depth limit exceeded in {m}" + | fuel + 1 => do + if ptr % 2 != 0 then + if ptr / 2 == 0 then + return .anonymous + fail s!"invalid scalar olean import name in {m}" + let (b, off) ← resolveOleanPtr m regions ptr + unless off + 24 <= b.size do + fail s!"truncated olean name object in {m}" + let tag := b.get! (off + 7) + if tag == 1 then + let pre ← readOleanName m regions (readUInt64LE b (off + 8)) fuel + let seg ← readOleanString m regions (readUInt64LE b (off + 16)) + return Name.mkStr pre seg + else if tag == 2 then + let pre ← readOleanName m regions (readUInt64LE b (off + 8)) fuel + let numPtr := readUInt64LE b (off + 16) + unless numPtr % 2 != 0 do + fail s!"unsupported boxed numeric olean import name in {m}" + return Name.mkNum pre (numPtr / 2) + else + fail s!"invalid olean name tag in {m}" + +/-- Parse `ModuleData.imports` directly from pre-validated `.olean*` part bytes +without calling `CompactedRegion.read`, avoiding duplicate region mappings +before `importCorrEnv`. -/ +def parseOleanPartImports (m : Name) (partPaths : Array System.FilePath) : + IO (Array Name) := do + let mut regions : Array (Nat × ByteArray) := #[] + let mut out : Array Name := #[] + for partPath in partPaths do + let bytes ← IO.FS.readBinFile partPath + let baseAddr := readUInt64LE bytes 80 + let rootPtr := readUInt64LE bytes 88 + regions := regions.push (baseAddr, bytes) + let (rb, roff) ← resolveOleanPtr m regions rootPtr + unless roff + 56 <= rb.size && rb.get! (roff + 6) == 5 && + rb.get! (roff + 7) == 0 do + fail s!"invalid olean ModuleData layout in {m}" + let (ab, aoff) ← resolveOleanPtr m regions (readUInt64LE rb (roff + 8)) + unless aoff + 24 <= ab.size && ab.get! (aoff + 7) == 246 do + fail s!"invalid olean imports array in {m}" + let arrSize := readUInt64LE ab (aoff + 8) + unless arrSize <= (ab.size - (aoff + 24)) / 8 do + fail s!"out-of-bounds olean imports array in {m}" + for i in [:arrSize] do + let impPtr := readUInt64LE ab (aoff + 24 + 8 * i) + let (ib, ioff) ← resolveOleanPtr m regions impPtr + unless ioff + 16 <= ib.size && ib.get! (ioff + 7) == 0 && + ib.get! (ioff + 6) == 1 do + fail s!"invalid olean Import object in {m}" + let modName ← readOleanName m regions (readUInt64LE ib (ioff + 8)) 64 + out := out.push modName + return out + +/-- Validate pre-import `.olean*` and `.ir.sig`/`.ir` headers, alignment, +base-address chaining, and `isModule` expectations for every root module and +every transitively imported module reachable from `mods` on the search path +(including transitive sysroot dependencies that a caller search-path entry +could shadow) before `importCorrEnv` mmaps any region in Pass 2 +`"correspondence-preflight"` or `"correspondence-audit"`. Non-sysroot modules +forbid `.ir`/`.ir.sig` siblings (`allowIr := false`, matching Pass 1); sysroot +modules validate any `.ir.sig` / `.ir` headers via +`validateIrPartsPreImport`. -/ +def validateCorrSearchPathPreImport (sysrootStr : String) (mods : Array Name) + (expectedIsMod : Std.HashMap Name Bool) : IO Unit := do + let sysrootReal ← + try + IO.FS.realPath (System.FilePath.mk sysrootStr) + catch _ => + pure (System.FilePath.mk sysrootStr) + let sysrootPrefix := sysrootReal.toString ++ "/" + let mut queue : List Name := mods.toList + let mut visited : NameSet := {} + while !queue.isEmpty do + let m :: rest := queue | break + queue := rest + if visited.contains m then + continue + visited := visited.insert m + let mFile? ← + try + let p ← findOLean m + if ← p.pathExists then pure (some p) else pure none + catch _ => + pure none + if let some mFile := mFile? then + let primaryIsMod ← validateOleanRegionChain m #[mFile] + let parts ← + if primaryIsMod then + pure #[mFile, OLeanLevel.server.adjustFileName mFile, + OLeanLevel.private.adjustFileName mFile] + else + pure #[mFile] + let realPath ← + try IO.FS.realPath mFile catch _ => pure mFile + let parentReal ← + match mFile.parent with + | some p => try IO.FS.realPath p catch _ => pure p + | none => pure mFile + let underSysroot := + realPath.toString.startsWith sysrootPrefix && + (parentReal.toString == sysrootReal.toString || + parentReal.toString.startsWith sysrootPrefix) + let irEmpty ← + if underSysroot then + validateIrPartsPreImport m mFile + else do + let hasIrSig ← (mFile.withExtension "ir.sig").pathExists + let hasIr ← (mFile.withExtension "ir").pathExists + pure !(hasIrSig || hasIr) + discard <| validateOleanPartsPreImport m parts irEmpty + (allowIr := underSysroot) (expectedIsMod.get? m) + let impMods ← parseOleanPartImports m parts + for impMod in impMods do + unless visited.contains impMod do + queue := impMod :: queue + +/-- Validate every companion `.olean`/`.olean.server`/`.olean.private` part of +module `m` against its authoritative private `ModuleData` (`privData` and +`privConsts`): exact `imports` parity, header inventory integrity, per-constant +compatibility (`isValidCompanionConstant`), and `extraConstNames` parity plus +checked-environment collision checks. -/ +def validateCompanionOleanParts (env : Environment) (m : Name) + (privData : ModuleData) (privConsts : Std.HashMap Name ConstantInfo) + (oleanParts : Array (ModuleData × CompactedRegion)) + (invLabel : String := "inventory") (dupLabel : String := "declaration") + (ctxPrefix : String := "") : IO Unit := do + let privModConsts : NameSet := .ofList privData.constNames.toList + let privExtras : NameSet := .ofList privData.extraConstNames.toList + for (partData, _) in oleanParts do + unless partData.imports == privData.imports do + fail s!"mismatched {ctxPrefix}companion imports in {m}" + verifyModuleHeaderInventory m partData invLabel dupLabel + for ci in partData.constants do + if ci.isUnsafe && + !(privConsts.get? ci.name).any + (isValidCompanionConstant privData.isModule · ci) then + fail s!"{ctxPrefix}module {m} declares unsafe constant {ci.name}" + unless privConsts.contains ci.name do + fail (s!"{ctxPrefix}companion constant {ci.name} missing from " ++ + s!"private inventory of {m}") + if let some privCi := privConsts.get? ci.name then + unless isValidCompanionConstant privData.isModule privCi ci do + fail (s!"mismatched {ctxPrefix}companion constant {ci.name} " ++ + s!"in {m}") + for n in partData.extraConstNames do + unless privExtras.contains n || privConsts.contains n do + fail (s!"{ctxPrefix}companion extraConstName {n} missing from " ++ + s!"private inventory of {m}") + checkExtraConstNoCheckedCollision env privModConsts n + /-! ## Explicit raw-`UInt64` cached-metadata validation -/ /-- Pointer-identity memoization sets used while validating cached `Name.hash`, @@ -4942,9 +5503,15 @@ -- and `isPartial` declarations (throwing on any rejected safe constant); all -- current callers filter those out via `ensureReplayableConstant`, -- `pairedUnsafeRecs`, and `!ci.isPartial` before calling `replayKernelEnv`. - for (k, _) in replayMap do - unless (replayed.find? k).isSome do - fail s!"{errPrefix}: declaration {k} omitted after kernel replay" + for (k, ci) in replayMap do + let some replayedCi := replayed.find? k + | fail s!"{errPrefix}: declaration {k} omitted after kernel replay" + -- FIXME: Interim guard comparing the replayed kernel `ConstantInfo` shape + -- against the audited `.olean` payload; remove once Pass 1/Pass 2 audit + -- queries run directly over a unified post-replay environment. + unless sameConstantShape replayedCi ci do + fail (s!"{errPrefix}: replayed declaration {k} differs from audited " ++ + "payload") return replayed /-- Replay `replayMap` onto `base.toKernelEnv` and check all `alternateProofs` @@ -5309,7 +5876,8 @@ /-- Execute Phase 2 (`"audit"`) on the compiled `.olean` environment `env`. -/ def audit (j : Json) (env : Environment) (foundation : Array Name) - (trusted : Array Name) (theory : Array Name) : IO Json := do + (trusted : Array Name) (theory : Array Name) + (expectedIsMod : Std.HashMap Name Bool := {}) : IO Json := do validateGraph j env let axiomPolicy ← field (α := Array (String × String)) j "axioms" let roles ← buildRepoOrigins j foundation trusted theory @@ -5317,10 +5885,17 @@ verifyAndCollectLocals env roles checkDeclarationEdges env roles locals RepoOrigin.edgeViolation? let arts ← artifacts j - for m in env.header.modules do + for m in env.header.modules, data in env.header.moduleData do if let some (modRole@(.repo srcRole)) := roles.get? m.module then + if let some expected := expectedIsMod.get? m.module then + validateTargetModuleIsModuleConsistency m.module data.isModule expected + let privConsts := data.constants.foldl + (init := ({} : Std.HashMap Name ConstantInfo)) + fun acc ci => acc.insert ci.name ci let (ov, oleanParts, irParts) ← collectModuleCompilerOverridesAndParts arts m.module + validateCompanionOleanParts env m.module data privConsts oleanParts + "inventory" "declaration" "" rejectForbiddenCompilerOverrides ov s!" in {m.module}" true validateRepoAliases env (oleanParts ++ irParts) roles RepoOrigin.edgeViolation? m.module srcRole modRole @@ -5552,6 +6127,7 @@ checkExtraConstNoCheckedCollision env modConsts n | .vendorMiri => verifyModuleHeaderInventory m.module data "inventory" "declaration" + let modConsts : NameSet := .ofList data.constNames.toList for ci in data.constants do validateExternalNamespace m.module ci.name let (orig, origRole) ← constProvenance env roles ci.name @@ -5599,6 +6175,8 @@ fail msg | none => vendorLocals := vendorLocals.insert ci.name ci + for n in data.extraConstNames do + checkExtraConstNoCheckedCollision env modConsts n | .repo srcRole => let isTrustedConst := constHasRole env roles (fun r => r matches .repo (.trusted _)) @@ -6210,12 +6788,15 @@ every prefix of `currNamespace` including root and every conservatively tracked open namespace, resisting decoy-namespace shadowing in the union environment) include—a namespace with scoped extensions is rejected before compilation. -/ -def preflightCorrespondence (j : Json) (foundation : Array Name) : IO Json := do +def preflightCorrespondence (j : Json) (sysrootStr : String) + (foundation : Array Name) : IO Json := do let trusted ← names j "trusted" let theory ← names j "theory" let vendorMiri ← names j "vendorMiri" let sources ← field (α := Array (String × String)) j "sources" let foundationSet : NameSet := .ofList foundation.toList + let expectedIsMod ← parseModuleIsModule j (trusted ++ theory ++ vendorMiri) + validateCorrSearchPathPreImport sysrootStr foundation {} let (baseTiers, reservedBaseModules) ← do let baseParserEnv ← importCorrEnv foundation true let baseScopedNs ← collectScopedExtensionNamespaces baseParserEnv @@ -6228,6 +6809,8 @@ for m in trusted do unless baseTiers.contains m do fail s!"missing base preflight source for Trusted module {m}" + validateCorrSearchPathPreImport sysrootStr + (foundation ++ trusted ++ theory ++ vendorMiri) expectedIsMod let env ← importCorrEnv (foundation ++ trusted ++ theory ++ vendorMiri) true let baseRoles ← classifyCorrModulesWithTiers j env foundation trusted theory vendorMiri baseTiers @@ -6241,16 +6824,53 @@ checkPreflightTierImports inspected foundationSet baseTiers reservedModules return Json.mkObj [("headers", .arr (inspected.map InspectedSource.renderJson))] +/-- Validate `Lean.aliasExtension` entries across all serialized `.olean*` and +`.ir*` parts of a pinned `.vendorMiri` module `m` in Pass 2. -/ +def validateVendorAliases (env : Environment) + (parts : Array (ModuleData × CompactedRegion)) + (roles : Std.HashMap Name CorrOrigin) (m : Name) : IO Unit := do + for (partData, _) in parts do + for (aliasName, targetName) in + partExtEntries Lean.aliasExtension partData do + let aliasUser := stripRootAndPrivatePrefixes aliasName + if aliasUser.hasMacroScopes || hasMalformedRootOrPrivate aliasUser then + fail s!"invalid export alias {aliasName} in {m}" + validateExternalNamespace m aliasName + let aliasRoot := aliasUser.getRoot + if kernelAcceleratedNames.contains aliasUser || + reservedKernelRoots.contains aliasRoot || + reservedRepoTargetDeclRoots.contains aliasRoot then + fail (s!"vendor Miri module {m} cannot export alias {aliasName} " ++ + s!"in reserved kernel namespace {aliasRoot}") + let (targetOrig, targetRole) ← constProvenance env roles targetName + if let some msg := CorrOrigin.edgeViolation? aliasName .vendorMiri + targetName targetOrig targetRole then + fail msg + let targetCi ← lookupConst env targetName "exported target" + let approvedAxiom := + (targetName == ``propext && targetOrig == `Init.Core) || + ((targetName == ``Classical.choice || targetName == ``Quot.sound) && + targetOrig == `Init.Prelude) + if targetName == `sorryAx || + [`Lean.ofReduceBool, `Lean.ofReduceNat, `Lean.trustCompiler, + `Lean.reduceBool, `Lean.reduceNat].contains targetName || + targetCi.isUnsafe || (targetCi.isAxiom && !approvedAxiom) then + fail (s!"disallowed vendor Miri export target {targetName} " ++ + s!"in {m}") + /-- Collect validated `.repo`, correspondence, and `.vendorMiri` inventories from the full Pass 2 environment in a dedicated scope so `env` can be released before constructing the clean sysroot replay base under `-M8192`. -/ -def collectCorrEnv (j : Json) +def collectCorrEnv (j : Json) (sysrootStr : String) (foundation allTrusted allTheory vendorMiri : Array Name) - (corrModSet : NameSet) : + (corrModSet : NameSet) + (expectedIsMod : Std.HashMap Name Bool := {}) : IO (Std.HashMap Name CorrOrigin × Std.HashMap Name ConstantInfo × Std.HashMap Name ConstantInfo × Std.HashMap Name ConstantInfo × Array ConstantInfo × Array ConstantInfo × Std.HashMap Name Name × List Name × Array Name) := do + validateCorrSearchPathPreImport sysrootStr + (foundation ++ allTrusted ++ allTheory ++ vendorMiri) expectedIsMod let env ← importCorrEnv (foundation ++ allTrusted ++ allTheory ++ vendorMiri) let roles ← classifyCorrModules j env foundation allTrusted allTheory vendorMiri @@ -6265,13 +6885,35 @@ for dep in repoAltRoots do if pairedUnsafeRecs.contains dep then fail s!"paired _unsafe_rec helper {dep} cannot be referenced logically" - for m in env.header.modules do - if let some (modRole@(.repo srcRole)) := roles.get? m.module then + for m in env.header.modules, data in env.header.moduleData do + match roles.get? m.module with + | some (modRole@(.repo srcRole)) => + if let some expected := expectedIsMod.get? m.module then + validateTargetModuleIsModuleConsistency m.module data.isModule expected + let privConsts := data.constants.foldl + (init := ({} : Std.HashMap Name ConstantInfo)) + fun acc ci => acc.insert ci.name ci let (ov, oleanParts, irParts) ← collectModuleCompilerOverridesAndParts {} m.module + validateCompanionOleanParts env m.module data privConsts oleanParts + "inventory" "declaration" "" rejectForbiddenCompilerOverrides ov s!" in {m.module}" true validateRepoAliases env (oleanParts ++ irParts) roles CorrOrigin.edgeViolation? m.module srcRole modRole + | some .vendorMiri => + if let some expected := expectedIsMod.get? m.module then + validateTargetModuleIsModuleConsistency m.module data.isModule expected + let privConsts := data.constants.foldl + (init := ({} : Std.HashMap Name ConstantInfo)) + fun acc ci => acc.insert ci.name ci + let (ov, oleanParts, irParts) ← + collectModuleCompilerOverridesAndParts {} m.module + validateCompanionOleanParts env m.module data privConsts oleanParts + "inventory" "declaration" "" + rejectForbiddenCompilerOverrides ov s!" in {m.module}" true + (allowInit := true) + validateVendorAliases env (oleanParts ++ irParts) roles m.module + | _ => pure () validateRepoAutoParamAndMeta env roles (fun r => r matches .repo _) (fun r => r == .repo .theory) (fun r => r == .foundation) @@ -6364,11 +7006,26 @@ (roles : Std.HashMap Name CorrOrigin) (corrLocals : Std.HashMap Name ConstantInfo) (corrModSet : NameSet) (repoAltRoots : List Name) (repoAlternateProofs : Array ConstantInfo) + (vendorAlternateProofs : Array ConstantInfo) (axiomPolicy : Array (String × String)) : IO (Array Name × Nat × Array Name × Nat) := do let env ← importCorrEnv (foundation ++ allTrusted ++ allTheory ++ vendorMiri) let (miriAxioms, miriVisited) ← verifyMiriExecutionMachineCone env roles axiomPolicy + let mut vendorAltRoots : List Name := [] + for ci in vendorAlternateProofs do + vendorAltRoots := ci.name :: (← declarationEdges ci).toList ++ vendorAltRoots + let (miriAxioms, miriVisited) ← + if vendorAltRoots.isEmpty then + pure (miriAxioms, miriVisited) + else do + let (altAxioms, altVisited) ← + closureCorr env roles axiomPolicy vendorAltRoots + let mergedAxioms := + (NameSet.ofList (miriAxioms.toList ++ altAxioms.toList)).toArray.qsort + Name.lt + let mergedVisited := miriVisited ++ altVisited + pure (mergedAxioms, mergedVisited) if corrModSet.isEmpty then return (miriAxioms, miriVisited.size, #[], 0) verifyCorrespondenceClaims env corrLocals @@ -6409,9 +7066,12 @@ let allTrusted := baseTrusted ++ corrTrusted let allTheory := baseTheory ++ corrTheory let corrModSet : NameSet := .ofList (corrTrusted.toList ++ corrTheory.toList) + let expectedIsMod ← + parseModuleIsModule j (allTrusted ++ allTheory ++ vendorMiri) let (roles, repoLocals, corrLocals, vendorReplayLocals, repoAlternateProofs, vendorAlternateProofs, _pairedUnsafeRecs, repoAltRoots, sysrootBaseMods) ← - collectCorrEnv j foundation allTrusted allTheory vendorMiri corrModSet + collectCorrEnv j sysrootStr foundation allTrusted allTheory vendorMiri + corrModSet expectedIsMod let (miriReplayed, corrReplayed) ← replayCorrAndVendor sysrootStr roles sysrootBaseMods vendorReplayLocals repoLocals corrLocals vendorAlternateProofs repoAlternateProofs @@ -6420,7 +7080,8 @@ initHermeticSearchPath sysrootStr (spRaw.toList.map System.FilePath.mk) let (miriAxioms, miriVisitedSize, corrAxioms, corrVisitedSize) ← verifyCorrConesAndClaims foundation allTrusted allTheory vendorMiri roles - corrLocals corrModSet repoAltRoots repoAlternateProofs axiomPolicy + corrLocals corrModSet repoAltRoots repoAlternateProofs + vendorAlternateProofs axiomPolicy return Json.mkObj [ ("miriReplay", toJson true), ("miriReplayedDeclarations", toJson miriReplayed), @@ -6475,7 +7136,8 @@ `Lean.Loop, `repeatM, `Lean.LoadDynlib, `Lean.loadDynlib, `Lean.loadPlugin, `Lean.Dynlib, `Lean.getGithash, `Lean.version, - `Init.System, `Std.Internal.UV, `Std.Async, `Std.Http, `Dynlib].any + `Init.System, `Std.Internal.UV, `Std.Async, `Std.Http, `Std.Sync, + `Dynlib].any (fun pre => u == pre || pre.isPrefixOf u) then true else if r == `System then @@ -6956,118 +7618,6 @@ (_proofMods : NameSet) (_overrides : ProofCompilerOverrides) : IO Json := throw <| IO.userError "proof exporter requires runtime implementation" -/-- Fail closed when module `m`'s compiled `isModule` header flag `actual` -differs from the `"isModule"` expectation `expected` that `cargo-anneal` -derived from the staged source header. -/ -private def validateTargetModuleIsModuleConsistency (m : Name) - (actual expected : Bool) : IO Unit := do - if !expected && actual then - fail s!"module-system artifact unsupported in {m}" - else if expected && !actual then - fail s!"non-module artifact mismatch in {m}" - -private def oleanHeaderSize : Nat := 88 - -private def readUInt64LE (bytes : ByteArray) (off : Nat) : Nat := - (bytes.get! off).toNat + - ((bytes.get! (off + 1)).toNat <<< 8) + - ((bytes.get! (off + 2)).toNat <<< 16) + - ((bytes.get! (off + 3)).toNat <<< 24) + - ((bytes.get! (off + 4)).toNat <<< 32) + - ((bytes.get! (off + 5)).toNat <<< 40) + - ((bytes.get! (off + 6)).toNat <<< 48) + - ((bytes.get! (off + 7)).toNat <<< 56) - -private def alignUp64K (n : Nat) : Nat := - ((n + 65535) / 65536) * 65536 - -/-- Pure, bounds-checked read of `ModuleData.isModule` from the root object of -a primary `.olean` v2 file without invoking `CompactedRegion.read` or `mmap`. -/ -private def parsePrimaryOleanIsModule (m : Name) (bytes : ByteArray) - (baseAddr : Nat) : IO Bool := do - if bytes.size < oleanHeaderSize + 8 then - fail s!"truncated olean root pointer in {m}" - let rootPtr := readUInt64LE bytes oleanHeaderSize - if rootPtr < baseAddr then - fail s!"invalid olean root pointer in {m}" - let rootOff := rootPtr - baseAddr - if rootOff < oleanHeaderSize + 8 || rootOff + 8 > bytes.size then - fail s!"out-of-bounds olean root object in {m}" - let numObjs := (bytes.get! (rootOff + 6)).toNat - let tag := (bytes.get! (rootOff + 7)).toNat - let scalarOff := rootOff + 8 + numObjs * 8 - if tag != 0 || numObjs != 5 || scalarOff >= bytes.size then - fail s!"invalid olean ModuleData layout in {m}" - let flag := bytes.get! scalarOff - if flag == 0 then - return false - else if flag == 1 then - return true - else - fail s!"invalid olean isModule flag in {m}" - -/-- Validate `.olean*` / `.ir` artifact part counts for a target module `m`: -non-module targets accept a single monolithic `.olean`, while Lean 4 `module` -targets accept `.olean` plus optional `.olean.server` / `.olean.private` -sidecars (never `.ir`). -/ -def validateTargetArtifactParts (m : Name) (oleanPartCount : Nat) - (irEmpty isModuleArtifact : Bool) : IO Unit := do - let partsOk := - if isModuleArtifact then - oleanPartCount >= 1 && oleanPartCount <= 3 && irEmpty - else - oleanPartCount == 1 && irEmpty - unless partsOk do - fail s!"companion artifact parts unsupported in {m}" - -/-- Validate `.olean*` binary headers, companion base-address chaining, and -primary-part `isModule` policy before `importEnv` mmaps `.olean.server` or -`.olean.private` companion regions via `CompactedRegion.read`. -/ -def validateTargetArtifactPreImport (m : Name) (art : ImportArtifacts) - (expectedIsModule : Bool) : IO Unit := do - let parts := art.oleanParts true - validateTargetArtifactParts m parts.size art.irParts.isEmpty expectedIsModule - let mut prefix0 : Option ByteArray := none - let mut prevEndAligned : Option Nat := none - let mut primaryIsMod : Option Bool := none - for partPath in parts do - let bytes ← try - IO.FS.readBinFile partPath - catch e => - throw <| IO.userError - s!"missing or unreadable artifact part {partPath} for {m}: {e}" - if bytes.size < oleanHeaderSize then - fail s!"truncated olean header in {m}" - let magicOk := - bytes.get! 0 == 'o'.toNat.toUInt8 && - bytes.get! 1 == 'l'.toNat.toUInt8 && - bytes.get! 2 == 'e'.toNat.toUInt8 && - bytes.get! 3 == 'a'.toNat.toUInt8 && - bytes.get! 4 == 'n'.toNat.toUInt8 && - bytes.get! 5 == 2 - unless magicOk do - fail s!"invalid olean v2 header in {m}" - let hdrPrefix := bytes.extract 0 80 - let baseAddr := readUInt64LE bytes 80 - match prefix0, prevEndAligned with - | none, _ => - let isMod ← parsePrimaryOleanIsModule m bytes baseAddr - primaryIsMod := some isMod - prefix0 := some hdrPrefix - prevEndAligned := some (alignUp64K (baseAddr + bytes.size)) - | some expectedPrefix, some expectedBase => - unless hdrPrefix == expectedPrefix do - fail s!"mismatched olean companion header in {m}" - unless baseAddr == expectedBase do - fail s!"mismatched olean companion base address in {m}" - prevEndAligned := some (alignUp64K (baseAddr + bytes.size)) - | _, _ => - fail s!"inconsistent olean companion sequence in {m}" - let some isMod := primaryIsMod - | fail s!"missing primary olean artifact for {m}" - validateTargetModuleIsModuleConsistency m isMod expectedIsModule - validateTargetArtifactParts m parts.size art.irParts.isEmpty isMod - /-- Execute `"target-export"` in a dedicated sandboxed child process with zero write access to `"target-audit"`'s verdict output. @@ -9851,7 +10401,7 @@ validateTargetModuleIsModuleConsistency pm.moduleName pm.isModule expected validateTargetImports pm.moduleName.toString pm.imports (allowModule := pm.isModule) - (allowTheoryImportAll := pm.isModule && isAnnealModuleName pm.moduleName) + (allowTheoryImportAll := pm.isModule && pm.moduleName == `Anneal.NatBitwise) unless pm.constNames == pm.constants.map ConstantInfo.name do fail s!"invalid target inventory {pm.moduleName}" let mut modSeen : NameSet := {} @@ -10344,24 +10894,8 @@ toJson (all.qsort (· < ·)), toJson (paired.qsort (· < ·)), toJson overrides] - for (partData, _) in oleanParts do - unless partData.imports == privData.imports do - fail s!"mismatched target companion imports in {m.module}" - verifyModuleHeaderInventory m.module partData "target inventory" - "target declaration" - for ci in partData.constants do - if ci.isUnsafe && - !(privConsts.get? ci.name).any - (isValidCompanionConstant privData.isModule · ci) then - fail (s!"target module {m.module} declares unsafe constant " ++ - s!"{ci.name}") - unless privConsts.contains ci.name do - fail (s!"target companion constant {ci.name} missing from " ++ - s!"private inventory of {m.module}") - if let some privCi := privConsts.get? ci.name then - unless isValidCompanionConstant privData.isModule privCi ci do - fail (s!"mismatched target companion constant {ci.name} " ++ - s!"in {m.module}") + validateCompanionOleanParts env m.module privData privConsts oleanParts + "target inventory" "target declaration" "target " for (partData, _) in oleanParts ++ irParts do for (aliasName, targetName) in partExtEntries Lean.aliasExtension partData do @@ -10530,14 +11064,17 @@ let foundation ← names j "foundation" let spRaw ← field (α := Array String) j "searchPath" initHermeticSearchPath sysrootStr (spRaw.toList.map System.FilePath.mk) - preflightCorrespondence j foundation + preflightCorrespondence j sysrootStr foundation | "audit" => let foundation ← names j "foundation" initHermeticSearchPath sysrootStr let trusted ← names j "trusted" let theory ← names j "theory" + let arts ← artifacts j + let expectedIsMod ← parseModuleIsModule j (trusted ++ theory) + validateRepoArtifactsPreImport arts (trusted ++ theory) expectedIsMod let env ← importEnv j (foundation ++ trusted ++ theory) - audit j env foundation trusted theory + audit j env foundation trusted theory expectedIsMod | "target-export" => let foundation ← names j "foundation" initHermeticSearchPath sysrootStr
diff --git a/trusted/audit/src/repo_audit.rs b/trusted/audit/src/repo_audit.rs index dfec9ae..27f5c4c 100644 --- a/trusted/audit/src/repo_audit.rs +++ b/trusted/audit/src/repo_audit.rs
@@ -241,6 +241,9 @@ modules: BTreeMap<String, PathBuf>, theory_modules: BTreeMap<String, PathBuf>, pass1_imports: BTreeMap<String, Vec<ImportEdge>>, + pass1_is_module: BTreeMap<String, bool>, + expected_is_module: BTreeMap<String, bool>, + require_all_is_module: bool, sysroot_foundation: Option<(PathBuf, Vec<String>)>, last_correspondence_tiers: Option<BTreeMap<String, TrustTier>>, require_correspondence: bool, @@ -264,6 +267,9 @@ modules: BTreeMap::new(), theory_modules: BTreeMap::new(), pass1_imports: BTreeMap::new(), + pass1_is_module: BTreeMap::new(), + expected_is_module: BTreeMap::new(), + require_all_is_module: false, sysroot_foundation: None, last_correspondence_tiers: None, require_correspondence: false, @@ -285,6 +291,9 @@ modules: BTreeMap::new(), theory_modules: BTreeMap::new(), pass1_imports: BTreeMap::new(), + pass1_is_module: BTreeMap::new(), + expected_is_module: BTreeMap::new(), + require_all_is_module: false, sysroot_foundation: None, last_correspondence_tiers: None, require_correspondence: false, @@ -334,6 +343,9 @@ self.modules.clear(); self.theory_modules.clear(); self.pass1_imports.clear(); + self.pass1_is_module.clear(); + self.expected_is_module.clear(); + self.require_all_is_module = false; self.sysroot_foundation = None; self.inner.reset_stage() } @@ -352,6 +364,9 @@ self.modules.clear(); self.theory_modules.clear(); self.pass1_imports.clear(); + self.pass1_is_module.clear(); + self.expected_is_module.clear(); + self.require_all_is_module = false; self.sysroot_foundation = None; self.inner .set_sandbox_mode(SandboxMode::PreferBwrapOrLandlock); @@ -433,6 +448,12 @@ Ok(()) } + #[doc(hidden)] + pub fn set_expected_is_module_for_test(&mut self, expected: BTreeMap<String, bool>) { + self.expected_is_module = expected; + self.require_all_is_module = false; + } + /// Invoke `TrustedBoundary.lean` with a typed [`InspectorRequest`]. pub fn inspect(&mut self, request: InspectorRequest) -> Result<Json, Failure> { match request { @@ -450,8 +471,10 @@ .iter() .map(|(k, parts)| json!([k, parts.to_wire()])) .collect(); - let src_pairs: Vec<(&str, std::borrow::Cow<'_, str>)> = - sources.iter().map(|(m, p)| (m.as_str(), p.to_string_lossy())).collect(); + let src_pairs: Vec<(&str, std::borrow::Cow<'_, str>)> = sources + .iter() + .map(|(m, p)| (m.as_str(), p.to_string_lossy())) + .collect(); let base_pairs: Vec<(&str, std::borrow::Cow<'_, str>)> = base_trusted_sources .iter() .map(|(m, p)| (m.as_str(), p.to_string_lossy())) @@ -522,7 +545,20 @@ .collect(); let tiers: Vec<(&str, String)> = module_tiers.iter().map(|(m, t)| (m.as_str(), t.render())).collect(); - json!({ + let mut is_mod_map: BTreeMap<&str, bool> = BTreeMap::new(); + for m in trusted.iter().chain(theory.iter()) { + if let Some(&flag) = self.expected_is_module.get(m) { + is_mod_map.insert(m.as_str(), flag); + } else if self.require_all_is_module { + return Err(Failure::policy( + "audit", + format!("missing expected isModule for {m}"), + )); + } + } + let is_mod_entries: Vec<(&str, bool)> = is_mod_map.into_iter().collect(); + let require_all_is_mod = self.require_all_is_module; + let mut req = json!({ "mode": "audit", "sysroot": adm.prefix.to_string_lossy(), "artifacts": arts_arr, @@ -533,7 +569,17 @@ "theory": theory, "moduleTiers": tiers, "requireMirWp": self.require_mir_wp, - }) + }); + if (require_all_is_mod || !is_mod_entries.is_empty()) + && let Some(obj) = req.as_object_mut() + { + obj.insert("moduleIsModule".to_string(), json!(is_mod_entries)); + obj.insert( + "requireAllModuleIsModule".to_string(), + json!(require_all_is_mod), + ); + } + req }; self.inner.invoke_inspector("audit", &req) } @@ -557,26 +603,51 @@ search_path.iter().map(|p| p.to_string_lossy()).collect(); let tiers: Vec<(&str, String)> = module_tiers.iter().map(|(m, t)| (m.as_str(), t.render())).collect(); + let mut is_mod_map: BTreeMap<&str, bool> = BTreeMap::new(); + for m in trusted + .iter() + .chain(corr_trusted.iter()) + .chain(theory.iter()) + .chain(corr_theory.iter()) + .chain(vendor_miri.iter()) + { + if let Some(&flag) = self.expected_is_module.get(m) { + is_mod_map.insert(m.as_str(), flag); + } else if self.require_all_is_module { + return Err(Failure::policy( + "correspondence-audit", + format!("missing expected isModule for {m}"), + )); + } + } + let is_mod_entries: Vec<(&str, bool)> = is_mod_map.into_iter().collect(); + let require_all_is_mod = self.require_all_is_module; let has_vendor_miri = !vendor_miri.is_empty(); let has_correspondence = !corr_trusted.is_empty() || !corr_theory.is_empty(); - ( - json!({ - "mode": "correspondence-audit", - "sysroot": adm.prefix.to_string_lossy(), - "searchPath": sp, - "foundation": adm.foundation_modules(), - "sysrootFoundation": sysroot_foundation, - "axioms": &adm.axioms, - "trusted": trusted, - "corrTrusted": corr_trusted, - "theory": theory, - "corrTheory": corr_theory, - "vendorMiri": vendor_miri, - "moduleTiers": tiers, - }), - has_vendor_miri, - has_correspondence, - ) + let mut req = json!({ + "mode": "correspondence-audit", + "sysroot": adm.prefix.to_string_lossy(), + "searchPath": sp, + "foundation": adm.foundation_modules(), + "sysrootFoundation": sysroot_foundation, + "axioms": &adm.axioms, + "trusted": trusted, + "corrTrusted": corr_trusted, + "theory": theory, + "corrTheory": corr_theory, + "vendorMiri": vendor_miri, + "moduleTiers": tiers, + }); + if (require_all_is_mod || !is_mod_entries.is_empty()) + && let Some(obj) = req.as_object_mut() + { + obj.insert("moduleIsModule".to_string(), json!(is_mod_entries)); + obj.insert( + "requireAllModuleIsModule".to_string(), + json!(require_all_is_mod), + ); + } + (req, has_vendor_miri, has_correspondence) }; let (req, has_vendor_miri, has_correspondence) = req; let report = self.inner.invoke_inspector("correspondence-audit", &req)?; @@ -768,6 +839,7 @@ )?; self.pass1_imports = preflight.imports.clone(); + self.pass1_is_module = preflight.is_module.clone(); let pass1_workers = default_compile_workers(4); self.inner.compile_lean_modules_parallel( &preflight.trusted_order, @@ -791,12 +863,42 @@ pass1_workers, )?; + // Unsandboxed Pass 1 `module`-mode compiles drop `.ir`/`.ir.sig` from + // the artifact map without unlinking them on disk; remove any stray + // `.ir*` siblings so Pass 2's search-path pre-import gate never sees + // non-sysroot IR parts. + for (subdir, mods) in + [("lib", &preflight.trusted_order), ("theory-lib", &preflight.theory_order)] + { + let dir = self.inner.stage().join(subdir); + for module in mods { + let stem = module.replace('.', "/"); + for ext in ["ir", "ir.sig"] { + let path = dir.join(format!("{stem}.{ext}")); + match fs::remove_file(&path) { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(e) => { + return Err(Failure::operational( + "compile", + format!("failed to remove stray {ext} for {module}: {e}"), + )); + } + } + } + } + } + + self.expected_is_module = preflight.is_module.clone(); + self.require_all_is_module = true; let audit_req = InspectorRequest::Audit { trusted: self.modules.keys().cloned().collect(), theory: self.theory_modules.keys().cloned().collect(), module_tiers: preflight.module_tiers.clone(), }; - let mut report = self.inspect(audit_req)?; + let audit_res = self.inspect(audit_req); + self.require_all_is_module = false; + let mut report = audit_res?; let version = self.inner.admitted()?.version.clone(); { let rep_obj = report.as_object_mut().unwrap(); @@ -1094,6 +1196,7 @@ &preflight.trusted_order, &corr_trusted_modules, &preflight.imports, + &preflight.is_module, &corr_trusted_src_root, &corr_trusted_dirs, &corr_trusted_lib, @@ -1106,6 +1209,7 @@ &preflight.theory_order, &corr_theory_modules, &preflight.imports, + &preflight.is_module, &corr_theory_src_root, &search_dirs, &corr_theory_lib, @@ -1143,6 +1247,23 @@ needed.into_iter().collect() }; + let mut corr_expected_is_module = BTreeMap::new(); + for module in self.modules.keys().chain(corr_audit_theory.iter()) { + if let Some(&flag) = self.pass1_is_module.get(module) { + corr_expected_is_module.insert(module.clone(), flag); + } + } + for (module, &flag) in &preflight.is_module { + corr_expected_is_module.insert(module.clone(), flag); + } + for entry in closure_entries { + let vendor_is_module = + entry.olean_server_sha256.is_some() || entry.olean_private_sha256.is_some(); + corr_expected_is_module.insert(entry.module.clone(), vendor_is_module); + } + self.expected_is_module = corr_expected_is_module; + self.require_all_is_module = true; + let corr_req = InspectorRequest::CorrespondenceAudit { search_path: search_dirs, trusted: self.modules.keys().cloned().collect(), @@ -1152,7 +1273,9 @@ vendor_miri: closure_entries.iter().map(|e| e.module.clone()).collect(), module_tiers: preflight.module_tiers, }; - let mut corr_report = self.inspect(corr_req)?; + let corr_res = self.inspect(corr_req); + self.require_all_is_module = false; + let mut corr_report = corr_res?; if let Some(obj) = corr_report.as_object_mut() { validate_correspondence_report( obj, @@ -1456,6 +1579,7 @@ order: &[String], staged_sources: &BTreeMap<String, PathBuf>, imports: &BTreeMap<String, Vec<ImportEdge>>, + is_module: &BTreeMap<String, bool>, src_root: &Path, lean_path_dirs: &[PathBuf], out_lib_root: &Path, @@ -1502,7 +1626,9 @@ |idx, ()| { let module = &order[idx]; let staged_src = &staged_sources[module]; - let rel_olean = format!("{}.olean", module.replace('.', "/")); + let mod_is_module = is_module.get(module).copied().unwrap_or(false); + let rel_stem = module.replace('.', "/"); + let rel_olean = format!("{rel_stem}.olean"); let mut out_builder = tempfile::Builder::new(); out_builder.prefix("anneal-pass2-out-"); #[cfg(unix)] @@ -1515,6 +1641,12 @@ fs::create_dir_all(parent) .map_err(|e| Failure::operational("compile", e.to_string()))?; } + let (allowed_extra_parts, discarded_extra_parts): (&[&str], &[&str]) = + if mod_is_module { + (&["olean.server", "olean.private"], &["ir", "ir.sig"]) + } else { + (&[], &[]) + }; cargo_anneal::Checker::compile_lean_module_with_root_in_runtime( &runtime, &stage, @@ -1527,23 +1659,32 @@ lean_path_dirs, 4096, warning_as_error, - &[], - &[], + allowed_extra_parts, + discarded_extra_parts, )?; - Ok((rel_olean, module_out_dir)) + Ok((rel_stem, mod_is_module, module_out_dir)) }, - |_, _idx, (rel_olean, module_out_dir)| { + |_, _idx, (rel_stem, mod_is_module, module_out_dir)| { // Stage under the mutex so downstream Pass 2 workers only ever - // observe complete `.olean` files. - let worker_olean = module_out_dir.path().join(&rel_olean); - let staged_olean = out_lib_root.join(&rel_olean); - if let Some(parent) = staged_olean.parent() { - fs::create_dir_all(parent) + // observe complete `.olean` (and module-mode sidecar) files. + let promote_part = |ext: &str| -> Result<(), Failure> { + let rel_part = format!("{rel_stem}.{ext}"); + let worker_part = module_out_dir.path().join(&rel_part); + let staged_part = out_lib_root.join(&rel_part); + if let Some(parent) = staged_part.parent() { + fs::create_dir_all(parent) + .map_err(|e| Failure::operational("compile", e.to_string()))?; + } + fs::rename(&worker_part, &staged_part) .map_err(|e| Failure::operational("compile", e.to_string()))?; + regular(&staged_part, "compile")?; + Ok(()) + }; + promote_part("olean")?; + if mod_is_module { + promote_part("olean.server")?; + promote_part("olean.private")?; } - fs::rename(&worker_olean, &staged_olean) - .map_err(|e| Failure::operational("compile", e.to_string()))?; - regular(&staged_olean, "compile")?; Ok(()) }, )
diff --git a/trusted/cargo-anneal/src/ndjson_comparator.rs b/trusted/cargo-anneal/src/ndjson_comparator.rs index c43b0dc..0e15949 100644 --- a/trusted/cargo-anneal/src/ndjson_comparator.rs +++ b/trusted/cargo-anneal/src/ndjson_comparator.rs
@@ -906,6 +906,7 @@ || has_prefix3("Std", "Internal", "UV") || has_prefix2("Std", "Async") || has_prefix2("Std", "Http") + || has_prefix2("Std", "Sync") || matches!(u.first(), Some(NamePart::Str("repeatM"))) { return true; @@ -5576,9 +5577,10 @@ "{err}" ); - // 5. Transitive `Std.Async` and `Std.Http` constants in specification - // closures fail closed (parity with `TrustedBoundary.lean`). - for (ns, leaf) in [("Async", "getAddrInfo"), ("Http", "get")] { + // 5. Transitive `Std.Async`, `Std.Http`, and `Std.Sync` constants in + // specification closures fail closed (parity with + // `TrustedBoundary.lean`). + for (ns, leaf) in [("Async", "getAddrInfo"), ("Http", "get"), ("Sync", "Mutex")] { let fq = format!("Std.{ns}.{leaf}"); let mut sysroot_net = sysroot.clone(); sysroot_net.insert(fq.clone(), format!("Std.{ns}.Client"));
diff --git a/trusted/cargo-anneal/src/target.rs b/trusted/cargo-anneal/src/target.rs index 2222a29..8050a49 100644 --- a/trusted/cargo-anneal/src/target.rs +++ b/trusted/cargo-anneal/src/target.rs
@@ -225,8 +225,8 @@ module == "Anneal" || module.starts_with("Anneal.") } -/// Foundation modules that bundled `Anneal.*` `module`-system theory files may -/// open via `import all` (mirroring `TrustedBoundary.allowedTheoryImportAllModules`). +/// Foundation modules that `Anneal.NatBitwise` may open via `import all` +/// (mirroring `TrustedBoundary.allowedTheoryImportAllModules`). const ALLOWED_THEORY_IMPORT_ALL_MODULES: &[&str] = &["Init.Data.Nat.Bitwise.Basic"]; /// Compute the deterministic BFS set of target modules to retain for @@ -1489,7 +1489,7 @@ let mod_is_module = is_module.get(module).copied().unwrap_or(false); let allow_theory_import_all = mod_is_module && roles[module] == TargetRole::Proof - && is_bundled_theory_module(module); + && module == "Anneal.NatBitwise"; let has_non_meta_init = edges.iter().any(|e| e.module == "Init" && !e.is_meta); for edge in edges { if edge.import_all
diff --git a/trusted/cargo-anneal/src/toolchain.rs b/trusted/cargo-anneal/src/toolchain.rs index 34e8119..e376ebc 100644 --- a/trusted/cargo-anneal/src/toolchain.rs +++ b/trusted/cargo-anneal/src/toolchain.rs
@@ -823,8 +823,8 @@ } /// Return `true` when `module` exposes unsafe/system-level `Lean.*`, `Lake.*`, -/// umbrella `Std`/`Std.Internal`, `Std.Internal.UV.*`, `Std.Async.*`, or -/// `Std.Http.*` libraries. +/// umbrella `Std`/`Std.Internal`, `Std.Internal.UV.*`, `Std.Async.*`, +/// `Std.Http.*`, or `Std.Sync.*` libraries. pub(crate) fn is_forbidden_transitive_library(module: &str) -> bool { let root = module.split('.').next().unwrap_or(""); matches!(root, "Lean" | "Lake") @@ -836,6 +836,8 @@ || module.starts_with("Std.Async.") || module == "Std.Http" || module.starts_with("Std.Http.") + || module == "Std.Sync" + || module.starts_with("Std.Sync.") } fn validate_sysroot_graph_with( @@ -3378,8 +3380,8 @@ assert!(err.message.contains("exceeded Init.*"), "{err}"); // Forbidden transitive sysroot libraries (`Std`, `Std.Internal`, - // `Std.Internal.UV.*`, `Std.Async.*`, `Std.Http.*`) are rejected in - // both direct graph nodes and transitive edges. + // `Std.Internal.UV.*`, `Std.Async.*`, `Std.Http.*`, `Std.Sync.*`) are + // rejected in both direct graph nodes and transitive edges. assert!(!is_forbidden_transitive_library("Std.Data.HashMap")); for forbidden_lib in [ "Std", @@ -3390,6 +3392,8 @@ "Std.Async.DNS", "Std.Http", "Std.Http.Client", + "Std.Sync", + "Std.Sync.Mutex", ] { assert!(is_forbidden_transitive_library(forbidden_lib), "{forbidden_lib}"); let mut direct_graph = six_module_graph();