buddy_owned.py
verification/tools/buddy_owned.py
1#!/usr/bin/env python32"""Native owned-page seed and explicitly unqualified formal feasibility probes."""3from pathlib import Path4import argparse5import datetime6import fcntl7import json8import subprocess9import sys10import uuid1112import kani13import creusot14import native_witness15import run_receipt1617ROOT = kani.ROOT18PROOFS = ROOT / 'verification/proofs/allocator/kani'19EXPECTED = {20 'buddy-owned': {'transient::proofs::' + name for name in (21 'owned_split_heap', 'owned_split_hinted', 'owned_exhaust_heap', 'owned_exhaust_hinted')},22 'buddy-owned-negative': {'transient::proofs::negative_owned_split_loses_bin'},23}24NEGATIVE = 'NEGATIVE_CONTROL_OWNED_BUDDY_LOST_FREE_BIN'252627def inputs():28 return list(dict.fromkeys([kani.PLATFORM / 'allocation.rs', kani.PLATFORM / 'transient.rs',29 *[PROOFS / ('buddy_owned' + suffix + '.rs') for suffix in ('', '_negative', '_support', '_native')],30 Path(__file__), *run_receipt.INPUTS, Path(creusot.__file__), Path(kani.__file__), Path(kani.__file__).with_suffix('.toml'),31 *kani.kani_obligations.INPUTS, *kani.kani_install.INPUTS, *native_witness.INPUTS]))323334def stage(output, mode):35 original = (kani.PLATFORM / 'transient.rs').read_bytes()36 proof = PROOFS / ('buddy_owned_negative.rs' if mode == 'negative' else 'buddy_owned.rs')37 tail = ('\npub mod proofs { include!(' + json.dumps(str(proof)) + ');\n'38 + ('include!(' + json.dumps(str(PROOFS / 'buddy_owned_native.rs')) + ');\n' if mode != 'negative' else '')39 + '}\n').encode()40 (output / 'transient.rs').write_bytes(original + tail)41 call = ('transient::proofs::negative_owned_split_loses_bin();' if mode == 'negative'42 else 'transient::proofs::native_main();')43 (output / 'main.rs').write_text('#![allow(dead_code,unexpected_cfgs,unused_variables)]\n'44 '#[cfg(not(all(target_pointer_width="64",target_endian="little")))]\n'45 'compile_error!("owned buddy seed requires native64 little-endian");\n'46 '#[path=' + json.dumps(str(kani.PLATFORM / 'allocation.rs')) + '] mod allocation;\n'47 'mod transient;\nfn main() { #[cfg(not(kani))] { ' + call + ' } }\n')48 kani.require((output / 'transient.rs').read_bytes() == original + tail, 'Actual buddy source prefix changed')49 return {name: kani.sha(output / name) for name in ('transient.rs', 'main.rs')}505152def verify(paths, before, tool, receipt):53 receipt.verify()54 kani.require(before == {str(p.relative_to(ROOT)): kani.sha(p) for p in paths}, 'Owned buddy source changed')55 kani.kani_install.verify(tool, kani.TEMP)565758def native_compiler(kind):59 if kind == 'production':60 return native_witness.compiler_identity()61 path = (kani.KANI / 'toolchain/bin/rustc').resolve()62 result = subprocess.run([str(path), '--version'], env=native_witness.environment(path),63 text=True, capture_output=True, timeout=30)64 kani.require(result.returncode == 0 and result.stdout.strip() == kani.PIN['rustc_version'],65 'Wrong Kani native compiler version')66 return {'path': str(path), 'sha256': kani.sha(path), 'version': result.stdout.strip()}676869def validate_compile(log, code, retirement):70 if not retirement:71 kani.require(type(code) is int and code == 0, 'Owned buddy native compilation failed')72 creusot.require_no_fatal_diagnostics(log, [])73 return74 errors = [line for line in log.splitlines() if line.startswith('error')]75 expected = 'error[E0505]: cannot move out of `owned` because it is borrowed'76 kani.require(type(code) is int and code == 1 and errors == [expected,77 'error: aborting due to 1 previous error'],78 'Live owning span did not reject page retirement at its designated borrow')79 creusot.require_no_fatal_diagnostics(log, errors)808182def validate_native(log, code, negative):83 kani.require(type(code) is int and code == (101 if negative else 0)84 and (log.count(NEGATIVE) == 1 and log.count('panicked at') == 185 if negative else log == 'OWNED_BUDDY_NATIVE_PASS\n'), 'Wrong native owned-buddy result')86 expected_panic = [line.strip() for line in log.splitlines() if 'panicked at' in line] if negative else []87 creusot.require_no_fatal_diagnostics(log, expected_panic)888990def run(mode, timeout=90, compiler_kind=None):91 checkout = run_receipt.checkout(ROOT)92 suite = 'buddy-owned' + ('-negative' if mode == 'negative' else '')93 kani.kani_obligations.required(suite, EXPECTED[suite])94 tool = kani.kani_install.capture(kani.TEMP)95 paths = inputs()96 before = {str(p.relative_to(ROOT)): kani.sha(p) for p in paths}97 output = kani.TEMP / 'runs' / (datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')98 + '-buddy-owned-' + (compiler_kind or 'kani') + '-' + mode + '-' + uuid.uuid4().hex[:8])99 output.mkdir(parents=True)100 staged = stage(output, mode)101 compiler = native_compiler(compiler_kind) if compiler_kind else None102 window = 'finite native first/last cell-byte checks' if compiler else 'first256-byte symbolic windows'103 receipt = run_receipt.write(ROOT, output, {**checkout, 'sources': before, 'staged': staged,104 'toolIdentity': tool, 'compiler': compiler, 'mode': mode,105 'scope': 'complete native single-page existing-bin acquisition, orders6/7, six pre-owned spans; '106 'actual source, std-allocated page object and typed header, operation-specific native/opposite controls, '107 'safe disjoint loans, ' + window + '; not provider construction, arbitrary histories, Wasm, '108 'final release or a deductive reusable allocator contract'})109 print('Owned buddy ' + (compiler_kind or 'kani') + ' ' + mode + ': ' + str(output), flush=True)110 if compiler:111 executable = Path(compiler['path'])112 env = native_witness.environment(executable)113 command = [executable, '--edition=2024', '-Awarnings', output / 'main.rs', '-o', output / 'witness']114 if mode == 'retirement':115 command += ['--cfg', 'buddy_owned_retirement']116 with (output / 'compile.log').open('w') as log:117 result = subprocess.run([str(x) for x in command], cwd=ROOT, env=env,118 stdout=log, stderr=subprocess.STDOUT, timeout=90)119 verify(paths, before, tool, receipt)120 kani.require(compiler == native_compiler(compiler_kind), 'Native compiler identity changed')121 log = (output / 'compile.log').read_text()122 validate_compile(log, result.returncode, mode == 'retirement')123 if mode == 'retirement':124 print('EXPECTED_RETIREMENT_BORROW_REJECTION', flush=True)125 else:126 witness = output / 'witness'127 witness_hash = native_witness.executable_hash(witness)128 with (output / 'run.log').open('w') as log:129 result = subprocess.run([str(witness)], cwd=ROOT, env=env,130 stdout=log, stderr=subprocess.STDOUT, timeout=90)131 native_witness.executable_hash(witness, witness_hash)132 verify(paths, before, tool, receipt)133 kani.require(compiler == native_compiler(compiler_kind), 'Native compiler identity changed')134 log = (output / 'run.log').read_text()135 validate_native(log, result.returncode, mode == 'negative')136 (output / 'native.json').write_text(json.dumps({'witness_sha256': witness_hash,137 'compile_log_sha256': kani.sha(output / 'compile.log'),138 'run_log_sha256': kani.sha(output / 'run.log'), 'exit_code': result.returncode}, indent=2) + '\n')139 print('EXPECTED_NATIVE_REJECTION' if mode == 'negative' else 'EXECUTED_NATIVE_PASS', flush=True)140 else:141 env = kani.environment()142 env['CARGO_HOME'] = str(kani.TEMP / 'buddy-owned-cargo-home')143 env['RUSTFLAGS'] = '--edition=2024 -A dead_code -A unexpected_cfgs -A unused_variables'144 command = [kani.LAUNCHER / 'kani', output / 'main.rs', '--target-dir', output / 'target',145 '-Z', 'unstable-options', '--harness-timeout', str(timeout) + 's', '--export-json', output / 'result.json',146 '--jobs', '2', '--output-format', 'terse']147 with (output / 'run.log').open('w') as log:148 result = subprocess.run([str(x) for x in command], cwd=ROOT, env=env,149 stdout=log, stderr=subprocess.STDOUT)150 verify(paths, before, tool, receipt)151 kani.EXPECTED_HARNESSES.update(EXPECTED)152 kani.NEGATIVE_CONTROLS['buddy-owned-negative'] = NEGATIVE153 summary = kani.validate_run(output, suite, result.returncode)154 print(json.dumps({'suite': suite, 'status': 'EXPERIMENTAL_UNQUALIFIED', 'summary': summary}), flush=True)155 return output156157158def main():159 parser = argparse.ArgumentParser(description=__doc__)160 parser.add_argument('action', choices=('positive', 'negative', 'native', 'all'), nargs='?', default='native')161 parser.add_argument('--timeout', type=int, default=90)162 args = parser.parse_args()163 with (kani.TEMP / '.kani-runner.lock').open('w') as lock:164 fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)165 # Every feasibility action retains this exact representation's native166 # true/false/borrow controls. There is no formal producer ticket yet.167 for compiler in ('production', 'kani-rust'):168 for mode in ('positive', 'negative', 'retirement'):169 run(mode, args.timeout, compiler)170 if args.action != 'native':171 for mode in ('positive', 'negative') if args.action in ('all', 'positive') else ('negative',):172 run(mode, args.timeout)173174175if __name__ == '__main__':176 try:177 with creusot.cache_lease():178 main()179 except (RuntimeError, subprocess.CalledProcessError, BlockingIOError) as error:180 print('Owned buddy verification refused: ' + str(error), file=sys.stderr)181 sys.exit(1)