physical.py

verification/tools/physical.py

physical.py115 lines← SDK documentation
1#!/usr/bin/env python32"""Check verbatim private read/write bodies in a native owned byte-window context."""3from pathlib import Path4import argparse5import datetime6import fcntl7import json8import subprocess9import sys10import uuid1112import kani13import run_receipt14from rust_source import complete_item1516ROOT = kani.ROOT17PROOFS = ROOT / 'verification/proofs/physical'18PRODUCT = kani.PLATFORM / 'memory/page_pool.rs'19EXPECTED = {20    'physical': {'proofs::' + name for name in (21        'window_read_is_exact_and_preserves_bytes',22        'window_write_has_exact_value_and_frame', 'oracle_byte_word_bijection',23        'aligned_write_refines_three_word_image')},24    'physical-negative': {'proofs::negative_big_endian_word'},25}262728def source_item(text, anchor):29    kani.require(anchor.endswith('{'), 'Raw-access item anchor must end at opening brace')30    kani.require(text.count(anchor) == 1, 'Raw-access item anchor is not unique: ' + anchor)31    return complete_item(text, anchor)323334def raw_methods(text):35    # These private items contain no strings/comments with braces. Reject such36    # syntax rather than silently applying a brace counter to a changed grammar.37    result = []38    for anchor in ('    fn read(&self, offset: usize) -> u64 {',39                   '    fn write(&mut self, offset: usize, value: u64) {'):40        selected = source_item(text, anchor)41        kani.require(not any(token in selected for token in ('"', '//', '/*', "'")),42                     'Raw-access source item needs a reviewed parser update')43        result.append(selected)44    return '\n'.join(result)454647def run(suite, timeout):48    checkout = run_receipt.checkout(ROOT)49    tool_identity = kani.kani_install.capture(kani.TEMP)50    kani.kani_obligations.required(suite, EXPECTED[suite])51    stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')52    output = kani.TEMP / 'runs' / (stamp + '-' + suite + '-' + uuid.uuid4().hex[:8])53    output.mkdir(parents=True)54    inputs = [PRODUCT, PROOFS / 'kani/window_fixture.rs', PROOFS / 'kani/windows.rs',55              PROOFS / 'kani/negative.rs', PROOFS / 'shared/byte_word.rs',56              Path(__file__), *run_receipt.INPUTS, Path(kani.__file__), Path(kani.__file__).with_suffix('.toml'),57              *kani.kani_obligations.INPUTS, *kani.kani_install.INPUTS]58    before = {str(path.relative_to(ROOT)): kani.sha(path) for path in inputs}59    # The receiver context changes deliberately: no page count, unsafe Backing60    # implementation, Pool constructor, saved-format admission or provider claim.61    selected = raw_methods(PRODUCT.read_text())62    wrapper = ('include!(' + json.dumps(str(PROOFS / 'kani/window_fixture.rs'))63               + ');\nimpl Window<\'_> {\n' + selected + '\n}\n')64    proof = PROOFS / ('kani/negative.rs' if suite.endswith('negative') else 'kani/windows.rs')65    main = ('#![allow(dead_code, unexpected_cfgs)]\nextern crate core;\n'66            + wrapper67            + '#[cfg(kani)] mod proofs { include!(' + json.dumps(str(proof)) + '); }\nfn main() {}\n')68    (output / 'main.rs').write_text(main)69    staged = {path.name: kani.sha(path) for path in output.iterdir() if path.is_file()}70    identities = {**checkout,71                  'sources': before, 'toolIdentity': tool_identity, 'staged': staged,72                  'exactSelectedItemBytes': len(selected.encode()),73                  'scope': 'native64 little-endian; selected raw bodies, different receiver, 24-byte windows'}74    receipt = run_receipt.write(ROOT, output, identities)75    env = kani.environment()76    env['CARGO_HOME'] = str(kani.TEMP / 'physical-cargo-home')77    env['RUSTFLAGS'] = '--edition=2024 -A dead_code -A unexpected_cfgs'78    result = output / 'result.json'79    argv = [kani.LAUNCHER / 'kani', output / 'main.rs', '--target-dir', output / 'target',80            '-Z', 'unstable-options', '--harness-timeout', str(timeout) + 's',81            '--export-json', result, '--jobs', '2', '--output-format', 'terse']82    print('Running ' + suite + ': ' + str(output), flush=True)83    with (output / 'run.log').open('w') as log:84        process = subprocess.run([str(x) for x in argv], cwd=ROOT, env=env,85                                 stdout=log, stderr=subprocess.STDOUT)86    receipt.verify()87    kani.require(before == {str(path.relative_to(ROOT)): kani.sha(path) for path in inputs},88                 'Source changed during physical verification')89    kani.require(result.is_file(), 'No complete result: inspect ' + str(output / 'run.log'))90    kani.EXPECTED_HARNESSES.update(EXPECTED)91    kani.NEGATIVE_CONTROLS['physical-negative'] = 'NEGATIVE_CONTROL_BIG_ENDIAN_MATCHES_NATIVE_LITTLE_ENDIAN'92    kani.kani_install.verify(tool_identity, kani.TEMP)93    summary = kani.validate_run(output, suite, process.returncode)94    print(json.dumps({'suite': suite, 'status': kani.result_status(suite),95                      'summary': summary, 'output': str(output)}, indent=2))96    return output979899def main():100    parser = argparse.ArgumentParser(description=__doc__)101    parser.add_argument('--timeout', type=int, default=30)102    args = parser.parse_args()103    kani.TEMP.mkdir(exist_ok=True)104    with (kani.TEMP / '.kani-runner.lock').open('w') as lock:105        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)106        run('physical', args.timeout)107        run('physical-negative', args.timeout)108109110if __name__ == '__main__':111    try:112        main()113    except (RuntimeError, subprocess.CalledProcessError, BlockingIOError) as error:114        print('Physical verification refused: ' + str(error), file=sys.stderr)115        sys.exit(1)