creusot.py

verification/tools/creusot.py

creusot.py691 lines← SDK documentation
1#!/usr/bin/env python32"""Build isolated pinned Creusot and verify erasure-linked page-pool operations."""3from pathlib import Path4import argparse5import datetime6import fcntl7import hashlib8import json9import os10import re11import subprocess12import sys13import tomllib14import uuid15from contextlib import contextmanager16from threading import get_ident17import creusot_report18import run_receipt19import checkpoint_seal20import equality_bridge21import standard_contracts2223ROOT = Path(__file__).resolve().parents[2]24VERIFY = ROOT / 'verification'25TEMP = VERIFY / 'tmp'26INSTALL = TEMP / 'creusot-install'27SOURCE = INSTALL / 'source'28TOOL = INSTALL / 'nix-result'29PIN = tomllib.loads(Path(__file__).with_suffix('.toml').read_text())30FRONTEND_PATCHES = tuple(Path(__file__).parent / entry['path'] for entry in PIN['frontend_patches'])31NIX_EXPRESSION = Path(__file__).with_suffix('.nix')3233_CACHE_OWNER = None343536@contextmanager37def cache_lease():38    """One process/thread owns this checkout's shared verifier cache at a time."""39    global _CACHE_OWNER40    owner = (os.getpid(), get_ident(), INSTALL.resolve())41    if _CACHE_OWNER is not None:42        require(_CACHE_OWNER == owner, 'Creusot cache has another owner in this process')43        yield44        return45    INSTALL.mkdir(parents=True, exist_ok=True)46    with (INSTALL / '.cache-owner.lock').open('a') as lock:47        try:48            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)49        except BlockingIOError as error:50            raise RuntimeError('Creusot shared cache already has an owner') from error51        _CACHE_OWNER = owner52        try:53            yield54        finally:55            _CACHE_OWNER = None56            fcntl.flock(lock, fcntl.LOCK_UN)57PRODUCT = ROOT / 'cdk-rsx/crates/cdk-rsx-platform/src/memory/page_pool.rs'58PROOF = VERIFY / 'proofs/page-pool/creusot/control.rs'59PROOF_DIR = PROOF.parent60PROOF_FILES = tuple(PROOF_DIR / name for name in (61    'control.rs', 'queries.rs', 'bit_queries.rs', 'updates.rs',62    'partition.rs', 'free_bits.rs', 'free_queries.rs', 'provider.rs',63    'boundary_bits.rs', 'lookup.rs', 'equality.rs',64    'validation_helpers.rs', 'validation.rs', 'option_equality.rs', 'release.rs', 'initialize.rs',65    'lifecycle.rs', 'recovery.rs', 'counting.rs', 'claim.rs', 'claim_completeness.rs', 'resource_admission.rs', 'borrowed_zero.rs',66)) + (ROOT / 'verification/proofs/provider/creusot/copy_fill.rs',)67ERASURE_TARGETS = tuple(PROOF_DIR / n for n in ('equality_targets.rs', 'option_equality_targets.rs')) + (PROOF_DIR.parent / 'shared/count_model.rs', ROOT / 'verification/proofs/provider/creusot/borrowed_backing.rs')68PROOF_SCOPES = {69    'all': ('',),70    'initializer': ('initialize/',),71    'handoff': ('claim/', 'provider/'),72    'claim': ('claim/impl_Pool_B/claim_proof/',),73    'claim-completeness': ('claim/',),74    'claim-committed-view': ('claim/completeness/',),75    'claim-physical-witness': ('provider/resource_admission/committed_claim_borrowed_image/',76        'provider/resource_admission/actual_committed_owner_witness/'),77    'claim-completeness-support': ('claim/search/', 'claim/prefix_choice/',78        'claim/unbase_candidate/', 'claim/search_progress/', 'claim/completeness/',79        'claim/claim_committed_without_growth/', 'claim/claim_positive_witness/',80        'provider/resource_admission/committed_claim_borrowed_image/',81        'provider/resource_admission/actual_committed_owner_witness/'),82    'claim-chain': ('claim/search/', 'claim/prefix_choice/', 'claim/unbase_candidate/',83        'claim/search_progress/', 'claim/marked_valid/', 'claim/completeness/',84        'claim/chain_alignment_one/', 'claim/chain_singleton_run/',85        'claim/claim_committed_without_growth/', 'claim/fresh_store_admitted/',86        'release/impl_Pool_B/release_proof/',87        'provider/resource_admission/committed_claim_borrowed_image/',88        'provider/resource_admission/actual_committed_owner_witness/'),89    'claim-search-lemmas': tuple('claim/search/' + name + '/' for name in (90        'committed_admit', 'committed_request', 'committed_free_choice', 'aligned_ceiling_bound',91        'committed_rounding_safe', 'committed_rounding_keeps_candidate',92        'committed_cursor_bound', 'committed_skip_occupied')),93}94# The private config generated by this pinned tool on the qualified host.95WHY3_MAIN_DEFAULTS = {'magic': 14, 'running_provers_max': 32, 'memlimit': 1000, 'timelimit': 5.0}96# Generated original-source bodies are erasure targets, not proof callees or proved traits.97ORIGINAL_SOURCE_GOALS = {98    **{f'page_pool/impl_Clone_for_{ty}/clone.coma': frozenset(('vc_clone_' + ty,))99       for ty in ('Config', 'Owner', 'PoolError', 'Run')},100    **{f'page_pool/impl_Debug_for_{ty}/fmt.coma': frozenset((helper, 'vc_fmt_' + ty))101       for ty, helper in (('Config', 'vc_debug_struct_field4_finish'), ('Owner', 'vc_write_str'),102                          ('PoolError', 'vc_write_str'), ('Run', 'vc_debug_struct_field2_finish'))},103    **{f'page_pool/impl_Eq_for_{ty}/assert_fields_are_eq.coma': frozenset(('vc_assert_fields_are_eq_' + ty,))104       for ty in ('Config', 'Owner', 'PoolError', 'Run')},105    **{f'page_pool/impl_PartialEq_for_{ty}/eq.coma': frozenset(('vc_eq_' + ty,))106       for ty in ('Owner', 'PoolError', 'Run')},107    'page_pool/impl_PartialEq_for_Config/eq.coma': frozenset(('vc_eq_Option_Run', 'vc_eq_Config')),108    **{f'page_pool/impl_PartialEq_for_{ty}/eq__refines.coma': frozenset(('refines',))109       for ty in ('Config', 'Owner', 'PoolError', 'Run')},110}111MODEL_CONTROLS = {112    'claim-chain-first-one-model': ('resource_admission.rs',113        'drop(whole);\n    Ok(second)',114        'drop(whole);\n    proof_assert!(first.start != 1usize || first.start == second.start);\n    Ok(second)',115        'provider/resource_admission/committed_claim_borrowed_image'),116    'claim-chain-first-two-model': ('resource_admission.rs',117        'drop(whole);\n    Ok(second)',118        'drop(whole);\n    proof_assert!(first.start != 2usize || first.start == second.start);\n    Ok(second)',119        'provider/resource_admission/committed_claim_borrowed_image'),120    'claim-chain-internal-model': ('resource_admission.rs',121        'drop(whole);\n    Ok(second)',122        'drop(whole);\n    proof_assert!(first.start == second.start);\n    Ok(second)',123        'provider/resource_admission/committed_claim_borrowed_image'),124    'claim-chain-run-model': ('resource_admission.rs',125        'Ok(run) => run.count == 1usize && run.start + run.count <= 3usize,',126        'Ok(run) => run.count == 2usize && run.start + run.count <= 3usize,',127        'provider/resource_admission/actual_committed_owner_witness'),128    'claim-chain-free-model': ('claim.rs',129        'else { owner_bits(physical_words(**state), q) }, _ => false })]',130        'else { owner_bits(physical_words(**state), q) ^ 1u64 }, _ => false })]',131        'claim/claim_committed_without_growth'),132    'claim-chain-success-model': ('resource_admission.rs',133        'Ok(run) => run.count == 1usize && run.start + run.count <= 3usize,',134        'Err(PoolError::Exhausted) => true,',135        'provider/resource_admission/actual_committed_owner_witness'),136    'claim-root-frame-model': ('resource_admission.rs',137        '// Committed fit preserves the independently retained root loan.\n    assert!(image[0] == 0xa5u8);',138        '// Committed fit preserves the independently retained root loan.\n    assert!(image[0] == 0u8);',139        'provider/resource_admission/actual_committed_owner_witness'),140    'claim-skip-model': ('claim.rs',141        '#[ensures(no_fit_before(*image, config, count, alignment, *pages, used + 1usize))]\n    pub(in super::super) fn committed_skip_occupied',142        '#[ensures(no_fit_before(*image, config, count, alignment, *pages, used + 2usize))]\n    pub(in super::super) fn committed_skip_occupied',143        'claim/search/committed_skip_occupied'),144    'claim-exhaustion-model': ('claim.rs',145        '#[ensures(match result { Ok(run) => run.count == count, _ => false })]',146        '#[ensures(match result { Err(PoolError::Exhausted) => true, _ => false })]',147        'claim/claim_committed_without_growth'),148    'payload-bound-model': ('provider.rs',149        '\n        && (run.start@ + run.count@ - 1) * PAGE_BYTES@ <= backing_payload(backing).len()',150        '', 'provider/initialized_byte'),151    'dirty-handoff': ('provider.rs',152        'proof_assert!(!initialized_run(**state, run));',153        'proof_assert!(initialized_run(**state, run));', 'provider/handed_out_payload_is_dirty'),154    'count-model': ('counting.rs', 'if bits <= 0 || 64 < bits { 0 }',155                    'if bits <= 0 || 64 < bits { 1 }', 'counting/bit_population_anchor'),156    'ceil-model': ('counting.rs',157        '#[erasure(super::super::count_model::ceil32_model)]\n#[ensures(result@ == (value@ + 31) / 32)]',158        '#[erasure(super::super::count_model::ceil32_model)]\n#[ensures(result@ == value@ / 32)]',159        'counting/ceil32_model_checked'),160    'equality-model': ('equality.rs', 'left.count == right.count',161                       'left.count != right.count', 'equality/run_model_matches_oracle'),162    'option-equality-model': ('option_equality.rs', '(None, None) => true',163                              '(None, None) => false', 'option_equality/option_model_matches_oracle'),164}165# These confirmed false anchors can have one open leaf and no closed leaves.166# Prove this existing independent producer in the same invocation; keep both167# complete report inventories and the shared nonzero-closed-leaf requirement.168MODEL_CONTROL_SUPPORT = {169    'claim-chain-run-model': ('claim/search/committed_request',),170    'claim-chain-free-model': ('claim/search/committed_request',),171    'claim-chain-success-model': ('claim/search/committed_request',),172    'claim-root-frame-model': ('claim/search/committed_request',),173    'claim-skip-model': ('claim/search/committed_cursor_bound',),174    'claim-exhaustion-model': ('claim/search/committed_request',),175    'count-model': ('counting/ceil32_model_checked',),176    'equality-model': ('counting/ceil32_model_checked',),177}178179180ERASURE_CONTROLS = {181    'claim-completeness-erasure': (182        'claim_completeness.rs', 'let run = Run { start: p, count };',183        'let run = Run { start: p, count: count + 1 };',184        'page_pool::proof::claim::completeness::<impl page_pool::Pool<B>>::claim_committed_proof',185    ),186    'claim-zero-omission': (187        'claim.rs',188        '''unsafe {189                    zero_payload(&mut self.backing, p * PAGE_BYTES..end.min(committed) * PAGE_BYTES,190                        ghost!(&mut **state));191                }''',192        '{}',193        'page_pool::proof::claim::<impl page_pool::Pool<B>>::claim_proof',194    ),195    'claim-zero-erasure': (196        'claim.rs', 'p * PAGE_BYTES..end.min(committed) * PAGE_BYTES',197        'p * PAGE_BYTES..p * PAGE_BYTES',198        'page_pool::proof::claim::<impl page_pool::Pool<B>>::claim_proof',199    ),200    'erasure': (201        'control.rs',202        '((self.word_proof(OWNER_OFFSET, page / 32, words) >> ((page % 32) * 2)) & 3) as u8',203        '((self.word_proof(OWNER_OFFSET, page / 32, words) >> ((page % 32) * 2)) & 1) as u8',204        'page_pool::proof::<impl page_pool::Pool<B>>::owner_proof',205    ),206    'claim-erasure': (207        'claim.rs', 'let run = Run { start: p, count };',208        'let run = Run { start: p, count: count + 1 };',209        'page_pool::proof::claim::<impl page_pool::Pool<B>>::claim_proof',210    ),211}212213214def require(condition, message):215    if not condition:216        raise RuntimeError(message)217218219def one_error_compiler_summary(line):220    return re.fullmatch(r'error: could not compile .+ due to 1 previous error'221                        r'(?:; [1-9][0-9]* warnings? emitted)?', line) is not None222223224def diagnostic_text(log):225    return re.sub(r'\x1b\[[0-?]*[ -/]*[@-~]', '', log)226227228def require_no_fatal_diagnostics(log, allowed_errors):229    """Ordinary error lines must already pass the caller's exact context check."""230    allowed = set(allowed_errors)231    fatal = re.compile(r'^[ \t]*(?:'232        r'(?:[A-Za-z0-9_./-]+:[ \t]+)?(?:error(?:\[[^]]+\])?|fatal(?: runtime error| error| exception)?|(?:rustc-)?llvm error|cbmc error):'233        r'|thread\b.*\bpanicked at\b|panicked at\b|internal compiler error\b'234        r'|terminate called\b|segmentation fault\b|bus error\b|aborted(?:\s|$)|killed(?:\s|$)'235        r'|process didn.t exit successfully:.*(?:\bSIG[A-Z0-9]+\b|\(signal:\s*\d+)'236        r'|thread\b.*\bhas overflowed its stack\b'237        r'|\[(?:ERROR|FATAL)(?:\s|\]))', re.I)238    for line in diagnostic_text(log).splitlines():239        if line.strip() in allowed or line.lstrip().lower().startswith('warning:'):240            continue241        require(not fatal.search(line), 'Fatal compiler/prover diagnostic: ' + line.strip())242        if line.lstrip().startswith('{'):243            try:244                message = json.loads(line)245            except (ValueError, TypeError):246                continue247            if isinstance(message, dict) and message.get('reason') == 'compiler-message':248                message = message.get('message')249            level = message.get('level') if isinstance(message, dict) else None250            require(not isinstance(level, str) or not (level.startswith('error') or level in ('fatal', 'ice')),251                    'Fatal JSON compiler diagnostic')252253254def require_logical_rejection(log, exit_code, main_goal):255    log = diagnostic_text(log)256    errors = re.findall(r'^[ \t]*(?:Error:|error:|error\[[^]]+\]:).*$', log, re.MULTILINE)257    errors = [line.strip() for line in errors]258    require(type(exit_code) is int and exit_code == 1,259            'Logical control requires exit code 1')260    require(re.findall(r'^Goal Coma\.([^:\s]+):', log, re.MULTILINE) == [main_goal]261            and errors == ['Error: 1 unproved file', "Error: 'why3find prove' failed"],262            'Unexpected logical control diagnostics')263    require_no_fatal_diagnostics(log, errors)264265266def require_erasure_rejection(log, exit_code, target):267    log = diagnostic_text(log)268    designated = 'error: failed #[erasure] check for ' + target269    errors = [line for line in log.splitlines() if line.startswith(('error', 'Error:'))]270    require(type(exit_code) is int and exit_code == 1 and errors and errors[0] == designated271            and errors.count(designated) == 1 and log.count('error: failed #[erasure] check') == 1,272            'Altered executable body was not rejected by its designated erasure check')273    require(all(line == designated or line == 'error: aborting due to 1 previous error'274                or one_error_compiler_summary(line) or line == 'Error: Compilation failed'275                for line in errors), 'Unrelated erasure-control compiler/tool failure')276    require_no_fatal_diagnostics(log, errors)277278279def command(argv, **kwargs):280    return subprocess.run([str(x) for x in argv], check=True, **kwargs)281282283def sha(path):284    return hashlib.sha256(path.read_bytes()).hexdigest()285286287def git(repo, *args):288    return subprocess.check_output(['git', '-C', str(repo), *args], text=True).strip()289290291def validate_source():292    require(git(SOURCE, 'rev-parse', '--show-toplevel') == str(SOURCE), 'Wrong tool source root')293    require(git(SOURCE, 'rev-parse', 'HEAD') == PIN['revision'], 'Unexpected Creusot source')294    require(not git(SOURCE, 'status', '--porcelain'), 'Creusot source checkout has changes')295    require(sha(SOURCE / 'flake.lock') == PIN['flake_lock_sha256'], 'Unexpected Nix lock')296    require(sha(SOURCE / 'Cargo.lock') == PIN['cargo_lock_sha256'], 'Unexpected Cargo lock')297    require(len(FRONTEND_PATCHES) == len(set(FRONTEND_PATCHES)), 'Duplicate verifier frontend patch')298    for patch, entry in zip(FRONTEND_PATCHES, PIN['frontend_patches']):299        require(set(entry) == {'path', 'sha256'} and sha(patch) == entry['sha256'],300                'Unexpected verifier frontend patch: ' + str(patch))301302303def effective_why3_configuration():304    config = INSTALL / 'config/creusot/why3.conf'305    require(not config.is_symlink(), 'Symlinked local Why3 configuration')306    if config.exists():307        require(config.is_file(), 'Local Why3 configuration is not a regular file')308        try:309            settings = tomllib.loads(config.read_text())310        except (OSError, tomllib.TOMLDecodeError) as error:311            raise RuntimeError('Malformed local Why3 configuration') from error312        require(set(settings) == {'main'} and type(settings['main']) is dict313                and set(settings['main']) == set(WHY3_MAIN_DEFAULTS)314                and all(type(settings['main'][key]) is int for key in ('magic', 'running_provers_max', 'memlimit'))315                and type(settings['main']['timelimit']) in (int, float)316                and settings['main'] == WHY3_MAIN_DEFAULTS,317                'Local Why3 configuration overrides the pinned prover setup or budgets')318    # Absence and subsequent normal auto-generation have the same effective identity.319    return {'base_sha256': sha(TOOL / 'creusot_why3.conf'), 'main': dict(WHY3_MAIN_DEFAULTS)}320321322def validate_binaries():323    binaries = {name: TOOL / 'bin' / name for name in PIN['binary_sha256']324                if not name.endswith('-payload')}325    compiler_dir = (TOOL / 'bin/creusot-rustc').resolve().parent326    for name in ('cargo-creusot', 'creusot-rustc'):327        binaries[name + '-payload'] = compiler_dir / ('.' + name + '-wrapped')328    for name, expected in PIN['binary_sha256'].items():329        require(binaries[name].is_file() and sha(binaries[name]) == expected,330                'Unexpected pinned binary: ' + name)331    require((TOOL / 'creusot_why3.conf').read_bytes() ==332            (SOURCE / 'creusot-install/creusot_why3.conf').read_bytes(),333            'Unexpected prover command configuration')334    return {**{name: str(path.resolve()) for name, path in binaries.items()},335            'why3_configuration': effective_why3_configuration()}336337338def setup():339    INSTALL.mkdir(parents=True, exist_ok=True)340    if not SOURCE.exists():341        command(['git', 'clone', '--depth', '1', '--branch', 'v' + PIN['version'],342                 PIN['source_url'], SOURCE])343    validate_source()344    command(['nix', '--extra-experimental-features', 'nix-command flakes',345             'build', '--impure', '--file', NIX_EXPRESSION, '--argstr', 'source', SOURCE,346             '--argstr', 'revision', PIN['revision'], '--argstr', 'patches_json',347             json.dumps([str(path) for path in FRONTEND_PATCHES]),348             '--out-link', TOOL], cwd=ROOT)349    validate_binaries()350    command([TOOL / 'bin/cargo-creusot', 'creusot', 'version'])351    print('Pinned Creusot installed; production compiler and sources unchanged')352353354def environment(output):355    env = dict(os.environ)356    for key in ('RUSTC_WRAPPER', 'RUSTC_WORKSPACE_WRAPPER', 'CARGO_ENCODED_RUSTFLAGS',357                'RUSTFLAGS', 'RUSTUP_TOOLCHAIN', 'RUSTC', 'CARGO_BUILD_TARGET',358                'CREUSOT_DATA_HOME', 'LD_LIBRARY_PATH', 'WHY3CONFIG', 'WHY3_CONFIG',359                'WHY3FIND_CONFIG', 'WHY3LIB', 'WHY3DATA', 'WHY3LOADPATH'):360        env.pop(key, None)361    tool_identity = TOOL.resolve().name362    env.update(PATH=str(TOOL / 'bin') + ':' + env['PATH'],363               CARGO_HOME=str(INSTALL / 'cargo-home'),364               CARGO_TARGET_DIR=str(INSTALL / 'targets' / tool_identity),365               XDG_CACHE_HOME=str(INSTALL / 'cache' / tool_identity),366               XDG_CONFIG_HOME=str(INSTALL / 'config'))367    return env368369370def function_body(source, name):371    found = re.search(r'\bfn ' + re.escape(name) + r'\b', source)372    require(found is not None, 'Missing function: ' + name)373    start = source.index('{', found.end())374    cursor, depth = start + 1, 1375    while depth:376        require(cursor < len(source), 'Unclosed function: ' + name)377        depth += (source[cursor] == '{') - (source[cursor] == '}')378        cursor += 1379    return source[start:cursor]380381382def audit_oracle_calls(source):383    # Shared ordinary Rust oracles are erasure targets, never assumed callees.384    code = re.sub(r'//[^\n]*', '', source)385    require(not re.search(r'\b(?:bit_count|ceil32_model)\s*\(', code),386            'Call to an unchecked oracle erasure target')387    code = re.sub(r'#\[erasure\(super::super::count_model::(?:bit_count|ceil32_model)\)\]', '', code)388    require(not re.search(r'\bcount_model\b', code),389            'Unchecked oracle namespace/import/alias outside erasure attributes')390391392def audit_proof():393    source = '\n'.join(path.read_text() for path in PROOF_FILES)394    audit_oracle_calls(source)395    admission = (PROOF_DIR / 'resource_admission.rs').read_text()396    ordinary = re.sub(r'#\[erasure\([^\n]*\)\]\n', '', admission)397    require(not re.search(r'(?:\.\s*(?:pages|control_ptr|grow_to|zero)\s*\(|'398                          r'\bBacking\s*::\s*(?:pages|control_ptr|grow_to|zero)\b)', ordinary),399            'Original borrowed receiver primitive used as an assumed proof callee')400    require('Perm<*const [u64]>' not in source,401            'Control resources must use byte permissions, not an aligned u64 surrogate')402    names = set(re.findall(r'\bfn (\w+_proof)\b', source))403    require(names == {name + '_proof' for name in creusot_report.METHODS} |404            {'read_proof', 'write_proof', 'claim_committed_proof'}, 'Unexpected checked-method set')405    trusted = [re.search(r'\bfn (\w+)\b', source[m.end():]).group(1)406               for m in re.finditer(r'#\[\s*(?:[A-Za-z_]\w*\s*::\s*)*trusted\s*\]', source)]407    require(trusted == ['read_proof', 'write_proof', 'observed_pages',408                        'grow_pages', 'observed_control_ptr', 'control_add', 'zero_metadata', 'zero_payload',409                        *equality_bridge.LEAVES, *equality_bridge.OPTION_LEAVES, *equality_bridge.COUNT_LEAVES],410            'Unexpected trusted proof function')411    equality_bridge.audit_wrappers((PROOF_DIR / 'equality.rs').read_text())412    equality_bridge.audit_option_wrappers((PROOF_DIR / 'option_equality.rs').read_text())413    equality_bridge.audit_count_wrapper((PROOF_DIR / 'counting.rs').read_text())414    require(source.count('extern_spec!') == 2, 'Unexpected external contract declaration')415    fill = ROOT / 'verification/proofs/provider/creusot/copy_fill.rs'416    standard_contracts.audit_copy_fill(fill.read_text())417    std_contract = function_body('fn std_tcb ' + source.split('extern_spec!', 1)[1], 'std_tcb')418    expected_std_contract = """{419        impl<T> Option<T> {420            #[requires(match self { None => true, Some(t) => f.precondition((t,)) })]421            #[ensures(match self {422                None => resolve(f) && result == true,423                Some(t) => f.postcondition_once((t,), result),424            })]425            fn is_none_or(self, f: impl FnOnce(T) -> bool + Destruct) -> bool;426        }427    }"""428    require(re.sub(r'\s+', '', std_contract) == re.sub(r'\s+', '', expected_std_contract),429            'Unreviewed standard-library primitive contract')430    require(not re.search(r'\b(?:assume|admit|conjure)\s*!?\s*\(', source),431            'Unchecked proof assumption')432    require(not re.search(r'#\[requires\(\s*false\s*\)\]', source),433            'Vacuous proof precondition')434    calls = set(re.findall(r'\b(?:self|pool)\.(\w+)\s*\(', source))435    require(calls <= names, 'Call to an unchecked original Pool method: ' + str(calls - names))436    static_calls = set(re.findall(r'\b(?:Pool(?:::[^\n]*?)?|Self)::(\w+)\s*\(', source))437    require(static_calls <= names, 'Unchecked static Pool call: ' + str(static_calls - names))438    # Two additional standard slice constructors belong to the owned committed-fit seed.439    require(source.count('.backing.') == 2 and source.count('ptr::') == 9,440            'Raw backing access outside the declared bridge')441    require(re.sub(r'\s+', '', function_body(source, 'observed_pages')) == '{backing.pages()}',442            'Page observer differs from the Backing primitive')443    primitives = {444        'grow_pages': '{backing.grow_to(pages)}',445        'observed_control_ptr': '{backing.control_ptr()}',446        'control_add': '{unsafe{pointer.add(offset)}}',447        'zero_metadata': '{unsafe{ptr::write_bytes(pointer,value,count)}}',448        'zero_payload': '{unsafe{backing.zero(bytes)}}',449    }450    for name, body in primitives.items():451        require(re.sub(r'\s+', '', function_body(source, name)) == body,452                'Physical primitive body differs: ' + name)453    for name in ('read', 'write'):454        actual = re.sub(r'\s+', '', function_body(PRODUCT.read_text(), name))455        checked = re.sub(r'\s+', '', function_body(source, name + '_proof'))456        require(actual == checked, 'Raw bridge body differs from production: ' + name)457458459def stage(output):460    # Original methods carry no specifications and are not used as proof callees.461    # Mark them unverified only to retain their full THIR as erasure targets.462    # Remove exactly these inserted attributes to recover byte-identical source.463    original = PRODUCT.read_text()464    marker = '#[creusot_std::prelude::trusted]'465    require(marker not in original, 'Unexpected proof annotation in production source')466    staged = re.sub(r'(?m)^([ \t]*)((?:pub(?:\([^)]*\))? )?(?:unsafe )?fn )',467                    lambda m: m[1] + marker + '\n' + m[1] + m[2], original)468    staged = re.sub(r'(?m)^([ \t]*)((?:pub )?const )',469                    lambda m: m[1] + marker + '\n' + m[1] + '#[creusot_std::prelude::constant(eval)]\n' + m[1] + m[2], staged)470    staged = staged.replace('#[derive(Clone, Copy, Debug, PartialEq, Eq)]',471                            '#[derive(creusot_std::prelude::DeepModel)]\n#[derive(Clone, Copy, Debug, PartialEq, Eq)]')472    recovered = re.sub(r'(?m)^[ \t]*#\[(?:creusot_std::prelude::trusted|creusot_std::prelude::constant\(eval\)|derive\(creusot_std::prelude::DeepModel\))\]\n', '', staged)473    # Compare while retaining the original indentation of the fn line.474    require(recovered == original, 'Production-body staging changed source')475    (output / 'src').mkdir()476    (output / 'src/page_pool.rs').write_text(staged + '\n#[path="control.rs"] mod proof;\n')477    for path in PROOF_FILES:478        (output / 'src' / path.name).write_bytes(path.read_bytes())479    for path in ERASURE_TARGETS:480        (output / 'src' / path.name).write_bytes(path.read_bytes())481        staged_product = output / 'src/page_pool.rs'482        staged_product.write_text(staged_product.read_text() + f'\n#[path="{path.name}"] mod {path.stem};\n')483    for name in ('Cargo.toml', 'Cargo.lock', 'why3find.json'):484        (output / name).write_bytes((PROOF_DIR / name).read_bytes())485    (output / 'src/lib.rs').write_text('#![feature(const_destruct)]\n#![allow(dead_code, unexpected_cfgs)]\n#![recursion_limit="512"]\nmod page_pool;\n')486    return len(original.encode())487488489def proof_inputs(extra=()):490    return [PRODUCT, *PROOF_FILES, *ERASURE_TARGETS, *FRONTEND_PATCHES, NIX_EXPRESSION,491            Path(__file__), Path(__file__).with_suffix('.toml'), *run_receipt.INPUTS, Path(checkpoint_seal.__file__),492            Path(creusot_report.__file__), Path(standard_contracts.__file__), *[PROOF_DIR / name for name in493               ('Cargo.toml', 'Cargo.lock', 'why3find.json')], *extra]494495496def scope_paths(scope):497    return tuple(('page_pool/proof/' + prefix).rstrip('/') for prefix in PROOF_SCOPES[scope])498499500def scope_reports(scope):501    return {name: main for name, main in creusot_report.EXPECTED.items()502            if name.startswith(PROOF_SCOPES[scope])}503504505def model_control_paths(control):506    names = (MODEL_CONTROLS[control][3], *MODEL_CONTROL_SUPPORT.get(control, ()))507    return tuple('page_pool/proof/' + name for name in names)508509510def validate_model_control(output, control, inventory, exit_code):511    name = MODEL_CONTROLS[control][3]512    relative = name + '/proof.json'513    goal = creusot_report.EXPECTED[relative]514    proof_root = output / 'verif/page_pool_creusot_rlib/page_pool/proof'515    report_path = proof_root / relative516    require(exit_code != 0 and report_path.is_file(),517            'False equality-model mapping did not produce a failed proof')518    if control in MODEL_CONTROL_SUPPORT:519        require(type(exit_code) is int and exit_code == 1,520                'Paired model control did not fail with exit code 1')521        expected = {path + '/proof.json': creusot_report.EXPECTED[path + '/proof.json']522                    for path in (name, *MODEL_CONTROL_SUPPORT[control])}523        result = creusot_report.validate_negative_directory(proof_root, inventory, expected, relative)524    else:525        report = creusot_report.parse_report(report_path.read_text())526        result = creusot_report.validate_expected_rejection(report, goal, inventory.goals[relative])527    log = (output / 'run.log').read_text()528    require_logical_rejection(log, exit_code, goal)529    return result530531532def run(translate_only, control=None, *, extra_inputs=(), scope='all'):533    require(scope in PROOF_SCOPES and (control is None or scope == 'all'),534            'Invalid proof scope/control combination')535    validate_source()536    audit_proof()537    require((TOOL / 'bin/cargo-creusot').exists(), 'Run creusot.py setup first')538    binaries = validate_binaries()539    stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')540    output = TEMP / ('creusot-' + stamp + '-' + uuid.uuid4().hex[:8])541    output.mkdir(parents=True, exist_ok=False)542    paths = proof_inputs(extra_inputs)543    before = {str(p.relative_to(ROOT)): sha(p) for p in paths}544    require(PIN['target'] == equality_bridge.TARGET, 'Equality consumer target mismatch')545    bridge, bridge_paths = equality_bridge.qualify(output, TOOL / 'bin/rustc', paths)546    stage(output)547    staged_proof = output / 'src/control.rs'548    if control in ERASURE_CONTROLS:549        filename, old, new, _ = ERASURE_CONTROLS[control]550        staged_proof = output / 'src' / filename551        source = staged_proof.read_text()552        require(source.count(old) == 1, 'Missing erasure-control mutation target')553        staged_proof.write_text(source.replace(old, new))554        translate_only = True555    elif control == 'semantic':556        source = staged_proof.read_text()557        require(source.count('fn owner_chunk(') == 1, 'Missing semantic-control mutation target')558        staged_proof.write_text(source.replace('fn owner_chunk(', '#[ensures(result == 0u64)]\nfn owner_chunk('))559    elif control in MODEL_CONTROLS:560        filename, old, new, _ = MODEL_CONTROLS[control]561        staged_proof = output / 'src' / filename562        source = staged_proof.read_text()563        require(source.count(old) == 1, 'Missing comparison-model control target')564        staged_proof.write_text(source.replace(old, new))565    staged_paths = sorted((output / 'src').rglob('*.rs')) + [output / name for name in566                         ('Cargo.toml', 'Cargo.lock', 'why3find.json')]567    staged_before = {str(path.relative_to(output)): sha(path) for path in staged_paths}568    receipt = run_receipt.write(ROOT, output, {569        'factory': git(ROOT, 'rev-parse', 'HEAD'),570        'sdk': git(ROOT / 'cdk-rsx', 'rev-parse', 'HEAD'),571        'sdk_status': git(ROOT / 'cdk-rsx', 'status', '--porcelain'),572        'sources': before, 'staged': staged_before, 'creusot_revision': PIN['revision'],573        'creusot_frontend_patches': PIN['frontend_patches'],574        'unproved_original_source_goals': {name: sorted(goals) for name, goals in ORIGINAL_SOURCE_GOALS.items()},575        'nix_store': str(TOOL.resolve()), 'binaries': binaries, 'negative_control': control, 'scope': scope,576    })577    print('Creusot output: ' + str(output), flush=True)578    selected = (('page_pool/proof/owner_chunk',) if control == 'semantic' else579                model_control_paths(control) if control in MODEL_CONTROLS else580                scope_paths(scope))581    # Leave room for other isolated worktrees on the shared 64-core host.582    args = [TOOL / 'bin/cargo-creusot', 'creusot', '--erasure-check=error', '-j', '8', *selected,583            '--only=coma', '--', '--locked']584    equality_bridge.verify(bridge, output, bridge_paths)585    with (output / 'run.log').open('w') as log:586        result = subprocess.run([str(a) for a in args], cwd=output, env=environment(output),587                                stdout=log, stderr=subprocess.STDOUT)588    receipt.verify()589    require(before == {str(p.relative_to(ROOT)): sha(p) for p in paths}, 'Proof inputs changed during run')590    require(staged_before == {str(path.relative_to(output)): sha(path) for path in staged_paths},591            'Staged proof changed during translation')592    require(validate_binaries() == binaries, 'Pinned verifier/configuration changed during translation')593    equality_bridge.verify(bridge, output, bridge_paths)594    if control in ERASURE_CONTROLS:595        require_erasure_rejection((output / 'run.log').read_text(), result.returncode,596                                  ERASURE_CONTROLS[control][3])597        print('EXPECTED_' + control.upper().replace('-', '_') + '_REJECTION: ' + str(output))598        return599    require(result.returncode == 0, 'Creusot translation failed; see ' + str(output / 'run.log'))600    proof_root = output / 'verif/page_pool_creusot_rlib/page_pool/proof'601    inventory = creusot_report.goal_inventory(602        proof_root, creusot_report.EXPECTED, TOOL / 'bin/why3',603        translation_root=output / 'verif/page_pool_creusot_rlib', original_source_goals=ORIGINAL_SOURCE_GOALS,604        load_paths=[TOOL / 'share/why3find/packages/creusot'],605        config=TOOL / 'creusot_why3.conf', cwd=output, env=environment(output),606        output_dir=output / 'goal-inventory')607    print('UNPROVED_ORIGINAL_SOURCE: ' + json.dumps({'files': len(inventory.original_source_goals),608          'goals': sum(map(len, inventory.original_source_goals.values()))}), flush=True)609    if translate_only:610        print('TRANSLATED (not proved): ' + str(output))611        return612    # Prove exactly the already-enumerated translation. Recompiling here would613    # sever the link between the independent goal inventory and proof.json.614    args = [TOOL / 'bin/cargo-creusot', 'creusot', '--only=prove', '-j', '8', *selected,615            '--', '--locked']616    with (output / 'run.log').open('a') as log:617        result = subprocess.run([str(a) for a in args], cwd=output, env=environment(output),618                                stdout=log, stderr=subprocess.STDOUT)619    receipt.verify()620    require(before == {str(p.relative_to(ROOT)): sha(p) for p in paths}, 'Proof inputs changed during run')621    require(staged_before == {str(path.relative_to(output)): sha(path) for path in staged_paths},622            'Staged proof changed during verification')623    require(validate_binaries() == binaries, 'Pinned verifier identity changed during run')624    inventory.verify()625    equality_bridge.verify(bridge, output, bridge_paths)626    if control == 'semantic':627        report_path = output / 'verif/page_pool_creusot_rlib/page_pool/proof/owner_chunk/proof.json'628        require(result.returncode != 0 and report_path.is_file(),629                'False semantic postcondition did not produce a failed proof')630        report = creusot_report.parse_report(report_path.read_text())631        creusot_report.validate_expected_rejection(report, 'vc_owner_chunk',632                                                 inventory.goals['owner_chunk/proof.json'])633        log = (output / 'run.log').read_text()634        require_logical_rejection(log, result.returncode, 'vc_owner_chunk')635        print('EXPECTED_SEMANTIC_REJECTION: ' + str(output))636        return637    if control in MODEL_CONTROLS:638        validate_model_control(output, control, inventory, result.returncode)639        print('EXPECTED_' + control.upper().replace('-', '_') + '_REJECTION: ' + str(output))640        return641    require(result.returncode == 0, 'Creusot failed; see ' + str(output / 'run.log'))642    if scope != 'all':643        expected = scope_reports(scope)644        require(expected, 'Missing selected proof scope')645        summary = creusot_report.validate_directory(proof_root,646            {name: inventory.goals[name] for name in expected}, expected=expected)647    else:648        summary = creusot_report.validate_directory(proof_root, inventory)649    seal = checkpoint_seal.capture(output, kind='ordinary-positive',650        qualification={'scope': scope, 'summary': summary},651        external={**inventory.hashes, **checkpoint_seal.bridge_artifacts(bridge)})652    print('CHECKPOINT_SEAL_SHA256 ' + seal, flush=True)653    print(json.dumps({'status': 'PASS', 'scope': scope, 'summary': summary, 'output': str(output)}, indent=2))654655656def run_controls():657    for control in (*ERASURE_CONTROLS, 'semantic', *MODEL_CONTROLS):658        run(False, control)659660661def main(argv=None):662    parser = argparse.ArgumentParser(description=__doc__)663    parser.add_argument('action', choices=['setup', 'run', 'controls'])664    parser.add_argument('--translate-only', action='store_true')665    parser.add_argument('--scope', choices=tuple(PROOF_SCOPES), default='all')666    parser.add_argument('--control', choices=(*ERASURE_CONTROLS, 'semantic', *MODEL_CONTROLS))667    args = parser.parse_args(argv)668    require(not args.control or args.action == 'run' and not args.translate_only and args.scope == 'all',669            '--control requires run without --translate-only')670    TEMP.mkdir(exist_ok=True)671    with (TEMP / '.creusot-runner.lock').open('w') as lock:672        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)673        if args.action == 'setup':674            setup()675        elif args.control:676            run(False, args.control)677        elif args.action == 'controls':678            run_controls()679        else:680            run(args.translate_only, scope=args.scope)681            if not args.translate_only and args.scope == 'all':682                run_controls()683684685if __name__ == '__main__':686    try:687        with cache_lease():688            main()689    except (RuntimeError, subprocess.CalledProcessError, BlockingIOError) as error:690        print('Verification refused: ' + str(error), file=sys.stderr)691        sys.exit(1)