resize_success.py
verification/tools/resize_success.py
1#!/usr/bin/env python32"""Qualify source-selected direct Heap resize; no slab/whole-Heap theorem."""3from pathlib import Path4import argparse5import datetime6import fcntl7import json8import re9import subprocess10import sys11import uuid1213import creusot14import creusot_report15import native_witness16import provider_resource17import run_receipt1819ROOT = creusot.ROOT20PROOF = ROOT / 'verification/proofs/allocator/creusot/resize_success.rs'21SDK = ROOT / 'cdk-rsx/crates/cdk-rsx-platform/src/transient.rs'22ALLOCATION = SDK.with_name('allocation.rs')23FIXTURE = ROOT / 'verification/proofs/allocator/shared/resize_source.rs'24NATIVE = ROOT / 'verification/proofs/allocator/native/resize_success.rs'25EXPECTED = {name + '/proof.json': 'vc_' + name for name in (26 'run_geometry_proof', 'retire', 'geometry_owning_witness',27 'copy_owning_witness', 'retirement_owning_witness')}28EXPECTED.update({29 **{'impl_ResizeSource/' + name + '_proof/proof.json': 'vc_' + name + '_proof'30 for name in ('allocate_pages', 'release_pages')},31 **{'impl_AllocatorHeap/' + name + '_proof/proof.json': 'vc_' + name + '_proof'32 for name in ('allocate', 'release', 'resize')},33})34RESIZE_REPORT = 'impl_AllocatorHeap/resize_proof/proof.json'35# These two original impl-generated trait invariants are classified, not proved.36# Checked clients call the checked inherent shadows, never these trait targets.37ORIGINAL_GOALS = {'impl_PageSource_for_ResizeSource/' + name + '__refines.coma': ('refines',)38 for name in ('allocate_pages', 'release_pages')}39CONTROLS = ('wrong-prefix', 'wrong-retirement', 'erasure')40SCOPE = ('Native64 ordinary Heap; fixed Layout(37,65536) to Layout(65537,65536); '41 'source-selected direct arms and resize suffix with explicit owned-run/provider premises; '42 'no whole Heap/slab/hinted/zero-growth theorem')434445def audit(source, proof):46 creusot.require(re.findall(r'#\[trusted\]\s*fn (\w+)', proof) == ['layout_size', 'layout_align'],47 'Unexpected trusted model')48 creusot.require(proof.count('#[trusted]') == 4 and 'Ghost::conjure' not in proof49 and not re.search(r'\b(?:assume|admit)\s*!?\(', proof), 'Unexpected assumption')50 original = provider_resource.complete_item(source, 'fn run_geometry(')51 creusot.require(creusot.function_body(original, 'run_geometry')52 == creusot.function_body(proof, 'run_geometry_proof'), 'Geometry source mismatch')53 for name, body in (54 ('copy_bytes', '{\n unsafe { core::ptr::copy_nonoverlapping(source, destination, count) }\n}'),55 ('overwrite_returned', '{\n unsafe { core::ptr::write_bytes(pointer, value, count) }\n}'),56 ):57 creusot.require(creusot.function_body(proof, name) == body, 'Raw primitive body changed: ' + name)58 # Pin source-level path selection. This audit is not a proof of full-method59 # correspondence: the checked entry explicitly starts at these direct arms.60 classify = provider_resource.complete_item(source, 'fn small_class(')61 creusot.require(classify.startswith('fn small_class(layout: Layout) -> Option<usize> {\n'62 ' let size = layout.size().max(1);\n'63 ' if size > SMALL_MAX || layout.align() > 32 {\n return None;\n }'),64 'Direct-path class guard changed')65 creusot.require('pub type Heap = AllocatorHeap<2, 1>;' in source, 'Ordinary Heap specialization changed')66 ordinary = re.sub(r'#\[erasure\([^\n]+\)\]', '', proof)67 creusot.require(not re.search(r'\b(?:run_geometry|allocate|release|resize|allocate_pages|release_pages)\s*\(', ordinary),68 'Checked code called an unchecked target')69 return original707172def mutate(proof, control):73 if control is None:74 return proof75 creusot.require(control in CONTROLS, 'Unknown resize control')76 start = proof.index(' #[erasure(super::DirectPath::resize)]')77 before, main = proof[:start], proof[start:]78 anchors = {79 'wrong-prefix': ('if i < 37 { bytes((**caps).old_live)[i] }',80 'if i < 36 { bytes((**caps).old_live)[i] }'),81 'wrong-retirement': ('#[ensures(key((^*caps).returned_old) == key((**caps).old_live))]',82 '#[ensures(key((^*caps).returned_old) == None)]'),83 'erasure': ('copy_bytes(pointer, result, old.size().min(new.size()),',84 'copy_bytes(pointer, result, old.size().min(new.size()) - 1,'),85 }86 old, new = anchors[control]87 creusot.require(main.count(old) == 1, 'Resize control anchor changed: ' + control)88 return before + main.replace(old, new)899091def stage(output, control=None):92 source, proof = SDK.read_text(), PROOF.read_text()93 geometry = audit(source, proof)94 allocate = provider_resource.complete_item(source, 'pub unsafe fn allocate(')95 release = provider_resource.complete_item(source, 'pub unsafe fn release(')96 resize = provider_resource.complete_item(source, 'pub unsafe fn resize_layout(')97 start = allocate.index(' let Some((count, alignment)) = run_geometry(layout) else {')98 direct_allocate = allocate[start:allocate.rindex(' }\n }')]99 start = release.index(' let (count, _) = run_geometry(layout).expect(')100 direct_release = release[start:release.rindex(' }\n }')]101 start = resize.index(' let result = unsafe { self.allocate(source, new, priority) };')102 move = resize[start:resize.rindex(' }')]103 trait = provider_resource.complete_item(source, 'pub unsafe trait PageSource')104 fixture = FIXTURE.read_text()105 staged_fixture = re.sub(r'(?m)^( )((?:unsafe )?fn )',106 lambda match: match[1] + '#[creusot_std::prelude::trusted]\n' + match[1] + match[2], fixture)107 creusot.require(re.sub(r'(?m)^ #\[creusot_std::prelude::trusted\]\n', '', staged_fixture) == fixture,108 'Fixture source changed')109 creusot.require(staged_fixture.count('#[creusot_std::prelude::trusted]') == 2,110 'Unexpected fixture trusted target inventory')111 (output / 'src').mkdir()112 (output / 'src/resize_success.rs').write_text(mutate(proof, control))113 page = next(line for line in source.splitlines() if line.startswith('pub const PAGE:'))114 creusot.require(page == 'pub const PAGE: usize = 65_536;', 'Resize scope requires 64KiB pages')115 root = ('#![allow(dead_code,unexpected_cfgs)]\n#![deny(creusot::contractless_external_function)]\n'116 'use creusot_std::prelude::*;\nuse core::{alloc::Layout,ptr::{self,NonNull}};\n'117 '#[trusted]\n#[constant(eval)]\n' + page + '\n#[trusted]\n' + geometry + '\n' + trait + '\n' + staged_fixture)118 constants = []119 for name in ('MIN_BLOCK', 'ORDERS', 'CLASSES', 'CELLS', 'TREE_BITS', 'TREE_WORDS', 'SLAB_RESERVED'):120 matches = re.findall(r'(?m)^const ' + name + r':[^;]+;', source)121 creusot.require(len(matches) == 1, 'Heap constant changed: ' + name)122 constants.append('#[trusted]\n#[constant(eval)]\n' + matches[0])123 types = [provider_resource.complete_item(source, signature) for signature in (124 '#[repr(C)]\nstruct PageHeader', '#[repr(C, align(16))]\nstruct Slab', 'pub struct AllocatorHeap<')]125 # Pinned frontend emits unescaped Why3 record label `partial`, a keyword.126 # Only this proof-context identifier is renamed; byte-for-byte reverse audit.127 heap = types[-1]128 creusot.require(heap.count(' partial:') == 1 and 'partial_heads' not in heap, 'Receiver alpha anchor changed')129 types[-1] = heap.replace(' partial:', ' partial_heads:')130 creusot.require(types[-1].replace(' partial_heads:', ' partial:') == heap,131 'Receiver alpha-renaming changed representation')132 root += '\n' + '\n'.join(constants + types)133 priority = re.findall(r'#\[repr\(transparent\)\]\npub struct WritePriority\([^;]+;', ALLOCATION.read_text())134 creusot.require(priority == ['#[repr(transparent)]\npub struct WritePriority(pub u8);'], 'Priority representation changed')135 root += '\n' + priority[0] + '\ntype DirectPath=AllocatorHeap<2,1>;\nimpl DirectPath {\n'136 root += '#[trusted]\nunsafe fn allocate(&mut self, source: &mut ResizeSource, layout: Layout, priority: WritePriority) -> *mut u8 {\n' + direct_allocate + '}\n'137 root += '#[trusted]\nunsafe fn release(&mut self, source: &mut ResizeSource, pointer: *mut u8, layout: Layout) {\n' + direct_release + '}\n'138 root += '#[trusted]\nunsafe fn resize(&mut self, source: &mut ResizeSource, pointer: *mut u8, old: Layout, new: Layout, priority: WritePriority) -> *mut u8 {\n' + move + '}\n}\n'139 root += '#[path="resize_success.rs"] mod resize;\n'140 (output / 'src/lib.rs').write_text(root)141 for name in ('Cargo.toml', 'Cargo.lock', 'why3find.json'):142 (output / name).write_bytes((creusot.PROOF_DIR / name).read_bytes())143 return {str(path.relative_to(output)): creusot.sha(path) for path in output.rglob('*') if path.is_file()}144145146def run(translate=False, control=None):147 creusot.validate_source()148 binaries = creusot.validate_binaries()149 paths = list(dict.fromkeys([PROOF, SDK, ALLOCATION, FIXTURE, Path(__file__), Path(creusot.__file__),150 Path(creusot.__file__).with_suffix('.toml'), Path(creusot.__file__).with_suffix('.nix'),151 Path(creusot_report.__file__), *run_receipt.INPUTS, Path(provider_resource.__file__),152 *creusot.FRONTEND_PATCHES, *[creusot.PROOF_DIR / name for name in ('Cargo.toml', 'Cargo.lock', 'why3find.json')]]))153 before = {str(path.relative_to(ROOT)): creusot.sha(path) for path in paths}154 output = creusot.TEMP / ('resize-success-' + datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')155 + '-' + (control or 'positive') + '-' + uuid.uuid4().hex[:8])156 output.mkdir()157 staged = stage(output, control)158 receipt = run_receipt.write(ROOT, output, {'sources': before, 'staged': staged, 'binaries': binaries,159 'scope': SCOPE, 'control': control})160161 def verify():162 receipt.verify()163 creusot.require(before == {str(path.relative_to(ROOT)): creusot.sha(path) for path in paths}, 'Source changed')164 creusot.require(binaries == creusot.validate_binaries(), 'Tool changed')165166 env = creusot.environment(output)167 command = [str(creusot.TOOL / 'bin/cargo-creusot'), 'creusot', '--erasure-check=error',168 '--only=coma', '-j', '4', '--', '--locked', '--offline']169 print('Resize scope:', SCOPE, '\nResize checkpoint:', output, flush=True)170 with (output / 'run.log').open('w') as log:171 result = subprocess.run(command, cwd=output, env=env, stdout=log, stderr=subprocess.STDOUT)172 verify()173 log = (output / 'run.log').read_text()174 if control == 'erasure':175 creusot.require_erasure_rejection(log, result.returncode, 'resize::<impl AllocatorHeap<2, 1>>::resize_proof')176 print('EXPECTED_ERASURE_REJECTION', output, flush=True)177 return178 creusot.require_no_fatal_diagnostics(log, ())179 creusot.require(result.returncode == 0, 'Strict translation failed: ' + str(output / 'run.log'))180 root = output / 'verif/page_pool_creusot_rlib/resize'181 inventory = creusot_report.goal_inventory(root, EXPECTED, creusot.TOOL / 'bin/why3',182 load_paths=[creusot.TOOL / 'share/why3find/packages/creusot'], config=creusot.TOOL / 'creusot_why3.conf',183 cwd=output, env=env, output_dir=output / 'goal-inventory', translation_root=root.parent,184 original_source_goals=ORIGINAL_GOALS)185 verify()186 if translate:187 print('TRANSLATION_ONLY', {name: len(goals) for name, goals in inventory.goals.items()})188 return189 command = [str(creusot.TOOL / 'bin/cargo-creusot'), 'creusot', '--only=prove', '-j', '8',190 'resize', '--', '--locked', '--offline']191 with (output / 'run.log').open('a') as log:192 result = subprocess.run(command, cwd=output, env=env, stdout=log, stderr=subprocess.STDOUT)193 verify()194 inventory.verify()195 log = (output / 'run.log').read_text()196 if control:197 creusot.require_logical_rejection(log, result.returncode, 'vc_resize_proof')198 creusot_report.validate_negative_directory(root, inventory, EXPECTED, RESIZE_REPORT)199 print('EXPECTED_' + control.upper().replace('-', '_') + '_REJECTION', output, flush=True)200 else:201 creusot.require_no_fatal_diagnostics(log, ())202 creusot.require(result.returncode == 0, 'Proof failed: ' + str(output / 'run.log'))203 print(json.dumps(creusot_report.validate_directory(root, inventory, expected=EXPECTED)), flush=True)204205206def native():207 checkout = run_receipt.checkout(ROOT)208 paths = tuple(dict.fromkeys([NATIVE, FIXTURE, SDK, SDK.with_name('allocation.rs'), Path(__file__),209 Path(creusot.__file__), *run_receipt.INPUTS, *native_witness.INPUTS]))210 before = native_witness.snapshot(paths)211 output = creusot.TEMP / ('resize-native-' + datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')212 + '-' + uuid.uuid4().hex[:8])213 ticket = native_witness.qualify(output, ((NATIVE, 'RESIZE_SUCCESS_NATIVE_OK'),), paths, before)214 creusot.require(checkout == run_receipt.checkout(ROOT), 'Native checkout changed')215 native_witness.verify(ticket, ((NATIVE, 'RESIZE_SUCCESS_NATIVE_OK'),), paths, before)216 print('NATIVE_PASS', output)217218219if __name__ == '__main__':220 parser = argparse.ArgumentParser(description=__doc__)221 parser.add_argument('action', choices=('positive', *CONTROLS, 'native', 'all'), nargs='?', default='all')222 parser.add_argument('--translate-only', action='store_true')223 args = parser.parse_args()224 try:225 with creusot.cache_lease():226 creusot.require(not args.translate_only or args.action == 'positive', 'Translation-only requires positive')227 with (creusot.TEMP / '.resize-success.lock').open('w') as lease:228 fcntl.flock(lease, fcntl.LOCK_EX | fcntl.LOCK_NB)229 if args.action == 'native':230 native()231 else:232 for control in (None, *CONTROLS) if args.action == 'all' else (None if args.action == 'positive' else args.action,):233 run(args.translate_only, control)234 except (RuntimeError, subprocess.CalledProcessError, BlockingIOError) as error:235 print('Resize scope refused: ' + str(error), file=sys.stderr)236 sys.exit(1)