stable_bytes.py

verification/tools/stable_bytes.py

stable_bytes.py117 lines← SDK documentation
1#!/usr/bin/env python32"""Check actual stable I/O bounds, import operands and an explicit byte window."""3from pathlib import Path4import argparse5import datetime6import fcntl7import json8import subprocess9import sys10import uuid1112import kani13import run_receipt14from platform_providers import item1516ROOT = kani.ROOT17PROOFS = ROOT / 'verification/proofs/stable/kani'18NAMES = ('checked_full_domain', 'stable64_scalar_operands', 'actual_read_window',19         'actual_write_window', 'actual_invalid_io_frames', 'actual_empty_zero_capacity')20SUITES = {21    'positive': ('bytes.rs', {'adapter::proofs::' + name for name in NAMES}),22    'negative': ('bytes_negative.rs', {'adapter::proofs::negative_write_changes_neighbor'}),23}242526def register():27    for name, (_, harnesses) in SUITES.items():28        kani.EXPECTED_HARNESSES['stable-bytes-' + name] = harnesses29    kani.NEGATIVE_CONTROLS['stable-bytes-negative'] = 'NEGATIVE_CONTROL_STABLE_NEIGHBOR_CHANGED'303132def source_parts(source):33    return '\n'.join(item(source, anchor) for anchor in (34        'fn checked(offset: u64, size: usize, limit: u64)',35        'pub struct StableMemory {', 'impl StableMemory {',36        'unsafe impl Memory for StableMemory {'))373839def stage(output, suite):40    original = (kani.PLATFORM / 'stable_capacity.rs').read_bytes()41    wasm = (kani.PLATFORM / 'wasm.rs').read_text()42    profile = (kani.PLATFORM / 'profile.rs').read_text()43    constant = 'pub const WASM_PAGE: usize = 65536;'44    kani.require(profile.count(constant) == 1, 'Production stable page constant changed')45    (output / 'stable_capacity.rs').write_bytes(original)46    (output / 'adapter.rs').write_text('include!(' + json.dumps(str(PROOFS / 'byte_support.rs'))47        + ');\n' + source_parts(wasm)48        + '\n#[cfg(kani)] mod proofs { use super::*; include!('49        + json.dumps(str(PROOFS / SUITES[suite][0])) + '); }\n')50    (output / 'main.rs').write_text(constant + '\nmod stable_capacity;\n'51        '#[path=' + json.dumps(str(kani.PLATFORM / 'memory/error.rs')) + '] mod error;\n'52        'mod adapter;\nfn main() {}\n')53    return {name: kani.sha(output / name) for name in ('main.rs', 'stable_capacity.rs', 'adapter.rs')}545556def run(suite, timeout):57    checkout = run_receipt.checkout(ROOT)58    register()59    key = 'stable-bytes-' + suite60    kani.kani_obligations.required(key, SUITES[suite][1])61    identity = kani.kani_install.capture(kani.TEMP)62    sources = [kani.PLATFORM / name for name in ('stable_capacity.rs', 'wasm.rs', 'profile.rs', 'memory/error.rs')]63    sources += [PROOFS / name for name in ('byte_support.rs', SUITES[suite][0])]64    sources += [Path(__file__), *run_receipt.INPUTS, Path(kani.__file__), Path(kani.__file__).with_suffix('.toml'),65                Path(__file__).with_name('platform_providers.py'),66                *kani.kani_obligations.INPUTS, *kani.kani_install.INPUTS]67    before = {str(path.relative_to(ROOT)): kani.sha(path) for path in sources}68    stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')69    output = kani.TEMP / 'runs' / (stamp + '-' + key + '-' + uuid.uuid4().hex[:8])70    output.mkdir(parents=True)71    staged = stage(output, suite)72    receipt = run_receipt.write(ROOT, output, {73        **checkout,74        'sources': before, 'staged': staged, 'toolIdentity': identity,75        'scope': 'native64 full-domain bounds/scalar casts; exact actual adapter bodies; '76                 'independent symbolic 16-byte stable image/0..8-byte requests under explicit VM semantics; '77                 'not physical authority construction, unbounded byte I/O, Wasm ABI or VM proof',78    })79    env = kani.environment()80    env['CARGO_HOME'] = str(kani.TEMP / 'stable-bytes-cargo-home')81    env['RUSTFLAGS'] = '--edition=2024 -A dead_code --check-cfg=cfg(test)'82    result = output / 'result.json'83    command = [kani.LAUNCHER / 'kani', output / 'main.rs', '--target-dir', output / 'target',84               '-Z', 'unstable-options', '--harness-timeout', str(timeout) + 's', '--export-json', result]85    print('Stable bytes ' + suite + ': ' + str(output), flush=True)86    with (output / 'run.log').open('w') as log:87        process = subprocess.run([str(arg) for arg in command], cwd=ROOT, env=env,88                                 stdout=log, stderr=subprocess.STDOUT)89    receipt.verify()90    kani.require(before == {str(path.relative_to(ROOT)): kani.sha(path) for path in sources},91                 'Stable byte source changed during proof')92    kani.kani_install.verify(identity, kani.TEMP)93    kani.require(result.is_file(), 'No stable byte report; inspect ' + str(output / 'run.log'))94    summary = kani.validate_run(output, key, process.returncode)95    print(json.dumps({'suite': key, 'status': kani.result_status(key), 'summary': summary,96                      'output': str(output)}, indent=2), flush=True)97    return output9899100def main():101    parser = argparse.ArgumentParser(description=__doc__)102    parser.add_argument('suite', choices=('all', *SUITES), nargs='?', default='all')103    parser.add_argument('--timeout', type=int, default=90)104    args = parser.parse_args()105    kani.TEMP.mkdir(exist_ok=True)106    with (kani.TEMP / '.kani-runner.lock').open('w') as lock:107        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)108        for suite in SUITES if args.suite == 'all' else (args.suite,):109            run(suite, args.timeout)110111112if __name__ == '__main__':113    try:114        main()115    except (RuntimeError, subprocess.CalledProcessError, BlockingIOError) as error:116        print('Stable byte proof refused: ' + str(error), file=sys.stderr)117        sys.exit(1)