kani.py

verification/tools/kani.py

1#!/usr/bin/env python32"""Read-only admission of corrected pinned Kani and source-linked proof suites."""3from pathlib import Path4import argparse5import datetime6import fcntl7import hashlib8import json9import os10import re11import subprocess12import sys13import tomllib14import uuid15import buddy_fragments16import kani_obligations17import kani_install1819ROOT = Path(__file__).resolve().parents[2]20VERIFY = ROOT / 'verification'21TEMP = VERIFY / 'tmp'22PIN = tomllib.loads(Path(__file__).with_suffix('.toml').read_text())23PLATFORM = ROOT / 'cdk-rsx/crates/cdk-rsx-platform/src'24LAUNCHER = TEMP / 'kani-launcher/bin'25KANI = TEMP / PIN['home_dir'] / ('kani-' + PIN['version'])26SUITES = {27    'geometry': ('geometry.rs', 4),28    'pointer-fit': ('pointer_fit.rs', 1),29    'negative': ('negative.rs', 1),30    'contracts': ('contracts.rs', 2),31    'equality': ('equality.rs', 2),32    'equality-negative': ('equality_negative.rs', 1),33    'option-equality': ('option_equality.rs', 1),34    'buddy': ('buddy.rs', 4),35    'buddy-ceil64': ('buddy_ceil64.rs', 1),36    'buddy-minimum': ('buddy_minimum.rs', 1),37    'buddy-minimum-negative': ('buddy_minimum_negative.rs', 1),38    'buddy-ceil64-negative': ('buddy_ceil64_negative.rs', 1),39    'buddy-step': ('buddy_step.rs', 1),40    'buddy-split': ('buddy_split.rs', 2),41    'buddy-split-negative': ('buddy_split_negative.rs', 1),42    'buddy-coalesce-research': ('buddy_coalesce.rs', 2),43    'buddy-coalesce-witness': ('buddy_coalesce_witness.rs', 1),44    'buddy-coalesce-negative': ('buddy_coalesce_negative.rs', 1),45    'buddy-negative': ('buddy_negative.rs', 1),46    'buddy-bins': ('buddy_bins.rs', 6),47    'buddy-bins-negative': ('buddy_bins_negative.rs', 1),48    'buddy-bins-heap-negative': ('buddy_bins_heap_negative.rs', 1),49    'slab-links': ('slab_links.rs', 6),50    'slab-links-negative': ('slab_links_negative.rs', 1),51    'slab-slots': ('slab_slots.rs', 2),52    'slab-slots-negative': ('slab_slots_negative.rs', 1),53    'slab-hinted-slots-research': ('slab_hinted_slots_research.rs', 2),54    'buddy-acquire-research': ('buddy_acquire_probe.rs', 1),55    'buddy-spans-research': ('buddy_spans.rs', 6),56    'count-ones': ('count_ones.rs', 1),57    'count-ones-negative': ('count_ones_negative.rs', 1),58    'ceil32': ('ceil32.rs', 1),59    'ceil32-negative': ('ceil32_negative.rs', 1),60}6162NEGATIVE_CONTROLS = {63    'buddy-ceil64-negative': 'NEGATIVE_CONTROL_BUDDY_CEIL64_TRUNCATES',64    'buddy-minimum-negative': 'NEGATIVE_CONTROL_BUDDY_MINIMUM_LARGER',65    'negative': 'NEGATIVE_CONTROL_EXACT_STRIDE',66    'equality-negative': 'NEGATIVE_CONTROL_RUN_COUNT',67    'buddy-negative': 'NEGATIVE_CONTROL_BUDDY_SHARED_WORD',68    'buddy-bins-negative': 'NEGATIVE_CONTROL_BIN_PREDECESSOR',69    'buddy-bins-heap-negative': 'NEGATIVE_CONTROL_BIN_PREDECESSOR',70    'buddy-split-negative': 'NEGATIVE_CONTROL_ACQUIRED_CELL_FREE',71    'slab-links-negative': 'NEGATIVE_CONTROL_SLAB_PREDECESSOR',72    'buddy-coalesce-negative': 'NEGATIVE_CONTROL_COALESCED_LEAF_FREE',73    'slab-slots-negative': 'NEGATIVE_CONTROL_SLAB_NEXT_SLOT',74    'count-ones-negative': 'NEGATIVE_CONTROL_COUNT_ONES',75    'ceil32-negative': 'NEGATIVE_CONTROL_CEIL32',76}777879EXPECTED_HARNESSES = {80    'buddy-ceil64': {'transient::proofs::ceil64_matches_wide_rounding'},81    'buddy-minimum': {'transient::proofs::minimum_matches_branch'},82    'buddy-minimum-negative': {'transient::proofs::negative_minimum_uses_larger_operand'},83    'buddy-ceil64-negative': {'transient::proofs::negative_ceil64_truncates_partial_word'},84    'geometry': {85        'transient::proofs::small_layout_geometry',86        'transient::proofs::classifier_covers_valid_layouts',87        'transient::proofs::direct_run_geometry',88        'transient::proofs::priority_band_roundtrip',89    },90    'pointer-fit': {'transient::proofs::real_arena_header_recovery'},91    'buddy-step': {'transient::proofs::exhausted_source_keeps_empty_heap'},92    'buddy-split': {'transient::proofs::acquire_metadata_exact',93                    'transient::proofs::acquire_pointwise_free_conservation'},94    'buddy-split-negative': {'transient::proofs::negative_acquired_cell_stays_free'},95    'buddy-coalesce-research': {'transient::proofs::release_metadata_exact',96                                'transient::proofs::release_pointwise_free_conservation'},97    'buddy-coalesce-witness': {'transient::proofs::upper_half_seven_level_coalesce_witness'},98    'buddy-coalesce-negative': {'transient::proofs::negative_coalesced_leaf_stays_free'},99    'buddy': {100        'transient::proofs::buddy_geometry',101        'transient::proofs::buddy_set_exact',102        'transient::proofs::buddy_clear_exact',103        'transient::proofs::buddy_roundtrip',104    },105    'buddy-negative': {'transient::proofs::negative_clearing_one_order_empties_shared_word'},106    'buddy-bins': {107        'transient::proofs::page_link_exact_local_contract',108        'transient::proofs::page_link_heap',109        'transient::proofs::page_unlink_heap',110        'transient::proofs::page_rebin_heap',111        'transient::proofs::page_unlink_exact_local_contract',112        'transient::proofs::page_rebin_exact_local_contract',113    },114    'buddy-bins-negative': {'transient::proofs::negative_link_preserves_old_head_predecessor'},115    'buddy-bins-heap-negative': {'transient::proofs::negative_heap_link_preserves_old_head_predecessor'},116    'slab-links': {117        'transient::proofs::slab_link_heap', 'transient::proofs::slab_link_hinted',118        'transient::proofs::slab_unlink_heap', 'transient::proofs::slab_unlink_hinted',119        'transient::proofs::slab_roundtrip_heap', 'transient::proofs::slab_roundtrip_hinted',120    },121    'slab-links-negative': {'transient::proofs::negative_link_preserves_old_slab_predecessor'},122    'slab-slots': {123        'transient::proofs::slab_bump_heap', 'transient::proofs::slab_reuse_heap',124    },125    'slab-slots-negative': {'transient::proofs::negative_bump_returns_following_slot'},126    'slab-hinted-slots-research': {127        'transient::proofs::slab_bump_hinted', 'transient::proofs::slab_reuse_hinted',128    },129    'buddy-acquire-research': {'transient::proofs::fresh_minimum_exact_header'},130    'buddy-spans-research': {131        'transient::proofs::two_minimum_spans',132        'transient::proofs::minimum_then_maximum',133        'transient::proofs::maximum_then_minimum',134        'transient::proofs::split_next_order',135        'transient::proofs::second_maximum_fails',136        'transient::proofs::full_depth_split_and_coalesce',137    },138    'negative': {'transient::proofs::negative_exact_size_class'},139    'contracts': {140        'transient::proofs::prove_span_contract',141        'transient::proofs::span_contract_composes_into_placement',142    },143    'equality': {144        'page_pool::proofs::owner_eq_ne_contract',145        'page_pool::proofs::run_eq_ne_contract',146    },147    'equality-negative': {'page_pool::proofs::negative_run_identity_drops_count'},148    'option-equality': {'page_pool::proofs::option_run_eq_ne_contract'},149    'count-ones': {'page_pool::proofs::count_ones_matches_bit_count'},150    'count-ones-negative': {'page_pool::proofs::negative_count_ones_drops_low_bit'},151    'ceil32': {'page_pool::proofs::ceil32_matches_wide_arithmetic'},152    'ceil32-negative': {'page_pool::proofs::negative_ceil32_rounds_down'},153    'page-pool': {154        'proofs::bounded_claim_release_history_preserves_partition',155        'proofs::word_boundaries_preserve_exact_runs_and_protected_pages',156        'proofs::growth_failure_preserves_control_and_distinguished_live_run',157        'proofs::rejected_claims_and_releases_do_not_change_control',158        'proofs::recycled_store_zero_request_is_exactly_the_previously_committed_prefix',159        'proofs::corrupt_header_recovery_rejects_before_any_write',160    },161}162163164def require(condition, message):165    if not condition:166        raise RuntimeError(message)167168169def sha(path):170    return hashlib.sha256(path.read_bytes()).hexdigest()171172173def command(argv, **kwargs):174    return subprocess.run([str(x) for x in argv], check=True, **kwargs)175176177def git(repo, *args):178    return subprocess.check_output(['git', '-C', str(repo), *args], text=True).strip()179180181def environment():182    home = TEMP / 'rustup'183    require(not home.is_symlink(), 'Kani needs a private proof Rustup home')184    require((home / 'toolchains' / PIN['rust_toolchain'] / 'bin/rustc').is_file(),185            'Required existing Kani toolchain is absent; implicit installation forbidden')186    env = dict(os.environ)187    # Proof tools never select or modify the SDK's retention compiler.188    for key in ('RUSTC_WRAPPER', 'RUSTC_WORKSPACE_WRAPPER', 'CARGO_ENCODED_RUSTFLAGS',189                'RUSTFLAGS', 'RUSTUP_TOOLCHAIN', 'RUSTC', 'CARGO_BUILD_TARGET',190                'CARGO', 'LD_LIBRARY_PATH', 'LD_PRELOAD', 'LD_AUDIT'):191        env.pop(key, None)192    env.update(KANI_HOME=str(TEMP / PIN['home_dir']), RUSTUP_HOME=str(TEMP / 'rustup'),193               RUSTUP_AUTO_INSTALL='0',194               RUSTC=str(KANI / 'toolchain/bin/rustc'), CARGO=str(KANI / 'toolchain/bin/cargo'),195               RUSTUP_TOOLCHAIN=PIN['rust_toolchain'],196               PATH=str(KANI / 'toolchain/bin') + ':' + env['PATH'],197               PYTHONDONTWRITEBYTECODE='1')198    return env199200201def validate_diagnostics(text):202    # This backend warning admits an altered call with an invented argument.203    # Other ordinary compiler warnings are not a qualification failure.204    require('not enough arguments, inserting non-deterministic value'205            not in ' '.join(text.split()), 'Unqualified backend argument warning')206    plain = re.sub(r'\x1b\[[0-?]*[ -/]*[@-~]', '', text)207    fatal = re.compile(r'^[ \t]*(?:'208        r'(?:[A-Za-z0-9_./-]+:[ \t]+)?(?:error(?:\[[^]]+\])?|fatal(?: runtime error| error| exception)?|(?:rustc-)?llvm error|cbmc error):'209        r'|thread\b.*\bpanicked at\b|panicked at\b|internal compiler error\b'210        r'|terminate called\b|segmentation fault\b|bus error\b|aborted(?:\s|$)|killed(?:\s|$)'211        r'|process didn.t exit successfully:.*(?:\bSIG[A-Z0-9]+\b|\(signal:\s*\d+)'212        r'|thread\b.*\bhas overflowed its stack\b'213        r'|\[(?:ERROR|FATAL)(?:\s|\]))', re.I)214    for line in plain.splitlines():215        if line.lstrip().lower().startswith('warning:'):216            continue217        require(not fatal.search(line), 'Fatal verifier diagnostic: ' + line.strip())218        if line.lstrip().startswith('{'):219            try:220                message = json.loads(line)221            except (ValueError, TypeError):222                continue223            if isinstance(message, dict) and message.get('reason') == 'compiler-message':224                message = message.get('message')225            level = message.get('level') if isinstance(message, dict) else None226            require(not isinstance(level, str) or not (level.startswith('error') or level in ('fatal', 'ice')),227                    'Fatal JSON compiler diagnostic')228229230def result_status(suite):231    if (suite.endswith(('-research', '-experimental'))232            or suite in PIN['experimental_suites']):233        return 'EXPERIMENTAL_UNQUALIFIED'234    return 'EXPECTED_COUNTEREXAMPLE' if suite in NEGATIVE_CONTROLS else 'PASS'235236237def validate_run(output, suite, exit_code, *, expected_report_sha256=None, expected_log_sha256=None,238                 manifest=None):239    """Consume a complete report together with its backend diagnostics."""240    output = Path(output)241    result, log = output / 'result.json', output / 'run.log'242    require(all(path.is_file() and not path.is_symlink() for path in (result, log)),243            'Missing or symlinked verifier report/diagnostic log')244    if expected_report_sha256 is not None:245        require(sha(result) == expected_report_sha256, 'Changed producer report')246    if expected_log_sha256 is not None:247        require(sha(log) == expected_log_sha256, 'Changed producer diagnostic log')248    validate_diagnostics(log.read_text())249    return validate_report(json.loads(result.read_text()), suite, exit_code, manifest=manifest)250251252def validate_report(report, suite, exit_code, *, manifest=None):253    require(report['tools']['kani'] == PIN['version'], 'Unexpected Kani result version')254    require(report['metadata']['target'] == PIN['target'], 'Unexpected proof target')255    require(report['tools']['rustc'] == PIN['rustc_version'], 'Unexpected proof rustc')256    require(report['tools']['cbmc'].startswith(PIN['cbmc_version'] + ' '), 'Unexpected CBMC')257    summary = report['verification_results']['summary']258    expected = EXPECTED_HARNESSES[suite]259    obligations = kani_obligations.required(suite, expected, manifest=manifest)260    count = len(expected)261    require(summary['status'] == 'completed' and summary['executed'] == count262            and summary['total_harnesses'] == count, 'Incomplete or unexpected harness set')263    results = report['verification_results']['results']264    require(isinstance(results, list) and len(results) == count,265            'Missing or unexpected per-harness results')266    require(all(isinstance(result, dict) for result in results), 'Invalid harness result')267    require({result['harness_id'] for result in results} == expected,268            'Missing, duplicate or unexpected harness identity')269    is_negative = suite in NEGATIVE_CONTROLS270    expected_status = 'Failure' if is_negative else 'Success'271    for result in results:272        require(result['status'] == expected_status,273                'Unexpected harness result status: ' + str(result['status']))274        checks = result['checks']275        require(isinstance(checks, list) and len(checks) > 0,276                'Harness has no property checks: ' + result['harness_id'])277        require(all(isinstance(check, dict) for check in checks), 'Invalid property check')278        kani_obligations.validate(checks, obligations[result['harness_id']], result['harness_id'],279                                 negative=is_negative)280        for check in checks:281            if check['category'] == 'cover':282                # An unreachable cover does not establish its nonvacuity claim.283                require(check['status'] == 'Satisfied', 'Mandatory cover was not satisfied')284            else:285                allowed = ('Success', 'Unreachable', 'Failure') if is_negative else (286                    'Success', 'Unreachable')287                require(check['status'] in allowed,288                        'Failed, unsupported or undetermined property check')289        if not is_negative:290            require(any(check['category'] == 'assertion' and check['status'] == 'Success'291                        for check in checks),292                    'Harness has no reachable successful assertion: ' + result['harness_id'])293    checks = [check for result in results for check in result['checks']]294    if is_negative:295        failures = [check for check in checks if check['status'] == 'Failure']296        require(exit_code == 1 and summary['successful'] == 0 and summary['failed'] == count297                and len(failures) == 1 and failures[0]['category'] == 'assertion'298                and failures[0]['description'].strip('"') == NEGATIVE_CONTROLS[suite],299                'Negative control must fail only its designated false assertion')300        designated = [item for rows in obligations.values() for item in rows301                      if item.category == 'assertion' and item.description ==302                      kani_obligations.normalized(json.dumps(NEGATIVE_CONTROLS[suite]))]303        # A selected SDK assertion can be the deliberate failure; its component304        # checks that exact canonical SDK location. When an authored marker is305        # declared, the shared inventory additionally binds its precise site.306        if designated:307            require(len(designated) == 1 and308                    kani_obligations.check_identity(failures[0]) == designated[0],309                    'Negative control must fail at its designated source assertion')310    else:311        require(exit_code == 0 and summary['failed'] == 0312                and summary['successful'] == count, 'Verification did not pass')313    return summary314315316def run(suite, timeout):317    kani_obligations.required(suite, EXPECTED_HARNESSES[suite])318    require(not git(ROOT, 'status', '--porcelain'), 'Commit factory source before qualification')319    require((LAUNCHER / 'kani').is_file() and (KANI / 'toolchain/bin/rustc').is_file(),320            'Required corrected Kani installation is absent; integration owner must provision it')321    tool_identity = kani_install.capture(TEMP)322    suffix = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')323    output = TEMP / 'runs' / (suffix + '-' + suite + '-' + uuid.uuid4().hex[:8])324    output.mkdir(parents=True, exist_ok=False)325    env = environment()326    result_path = output / 'result.json'327    args = ['-Z', 'unstable-options', '--harness-timeout', str(timeout) + 's',328            '--export-json', str(result_path)]329    if suite == 'page-pool':330        sources = [PLATFORM / 'memory/page_pool.rs',331                   VERIFY / 'proofs/page-pool/kani/src/lib.rs',332                   VERIFY / 'proofs/page-pool/kani/Cargo.toml']333        env['CARGO_TARGET_DIR'] = str(output / 'target')334        argv = [LAUNCHER / 'cargo-kani', '--manifest-path', sources[-1], *args]335    elif suite in ('equality', 'equality-negative', 'option-equality', 'count-ones', 'count-ones-negative', 'ceil32', 'ceil32-negative'):336        proof = VERIFY / 'proofs/page-pool/kani' / SUITES[suite][0]337        sources = [PLATFORM / 'memory/page_pool.rs', proof]338        if suite in ('count-ones', 'count-ones-negative', 'ceil32', 'ceil32-negative'):339            sources.append(VERIFY / 'proofs/page-pool/shared/count_model.rs')340        production_source = sources[0]341        original = production_source.read_bytes()342        tail = ('\n#[cfg(kani)] mod proofs { include!(' + json.dumps(str(proof)) + '); }\n').encode()343        staged = output / 'page_pool.rs'344        staged.write_bytes(original + tail)345        require(staged.read_bytes() == original + tail, 'Source staging differs')346        main = output / 'main.rs'347        main.write_text('extern crate core;\nmod page_pool;\nfn main() {}\n')348        env['RUSTFLAGS'] = '--edition=2024 -A dead_code --check-cfg=cfg(test)'349        argv = [LAUNCHER / 'kani', main, '--target-dir', output / 'target', *args]350    else:351        proof = VERIFY / 'proofs/allocator/kani' / SUITES[suite][0]352        sources = [PLATFORM / 'allocation.rs', PLATFORM / 'transient.rs', proof]353        if suite in ('buddy', 'buddy-step', 'buddy-split', 'buddy-split-negative',354                     'buddy-coalesce-research', 'buddy-coalesce-witness', 'buddy-coalesce-negative',355                     'buddy-negative', 'buddy-bins', 'buddy-bins-negative', 'buddy-bins-heap-negative',356                     'buddy-acquire-research', 'buddy-spans-research'):357            sources.append(VERIFY / 'proofs/allocator/kani/buddy_support.rs')358        if suite in ('buddy-acquire-research', 'buddy-spans-research'):359            sources.append(VERIFY / 'proofs/allocator/kani/buddy_span_support.rs')360        if suite in ('buddy-bins-negative', 'buddy-bins-heap-negative'):361            sources.append(VERIFY / 'proofs/allocator/kani/buddy_bins_negative_support.rs')362        if suite in ('slab-links', 'slab-links-negative'):363            sources.append(VERIFY / 'proofs/allocator/kani/slab_support.rs')364        if suite in ('buddy-ceil64', 'buddy-ceil64-negative'):365            sources.append(VERIFY / 'proofs/allocator/shared/ceil64.rs')366        if suite in ('slab-slots', 'slab-slots-negative', 'slab-hinted-slots-research'):367            sources.append(VERIFY / 'proofs/allocator/kani/slab_slot_support.rs')368        production_source = sources[1]369        original = sources[1].read_bytes()370        tail = ('\n#[cfg(kani)] mod proofs { include!(' + json.dumps(str(proof)) + '); }\n').encode()371        fragments = None372        if suite in ('buddy-split', 'buddy-split-negative', 'buddy-coalesce-research',373                     'buddy-coalesce-witness', 'buddy-coalesce-negative'):374            sources.append(VERIFY / 'tools/buddy_fragments.py')375            wrapper, fragments = buddy_fragments.stage(original,376                'coalesce' if suite.startswith('buddy-coalesce') else 'split')377            tail = wrapper + tail378        staged = output / 'transient.rs'379        staged.write_bytes(original + tail)380        require(staged.read_bytes() == original + tail, 'Source staging differs')381        # Append a child module to access private helpers; do not edit SDK source.382        main = output / 'main.rs'383        main.write_text('extern crate core;\n#[path=' + json.dumps(str(sources[0]))384                        + '] mod allocation;\nmod transient;\nfn main() {}\n')385        env['RUSTFLAGS'] = '--edition=2024 -A dead_code --check-cfg=cfg(test)'386        argv = [LAUNCHER / 'kani', main, '--target-dir', output / 'target', *args]387        if suite == 'contracts':388            argv += ['-Z', 'function-contracts', '-Z', 'stubbing']389    sources += [Path(__file__), Path(__file__).with_suffix('.toml'), *kani_obligations.INPUTS, *kani_install.INPUTS]390    before = {str(p.relative_to(ROOT)): sha(p) for p in sources}391    if suite != 'page-pool':392        require(hashlib.sha256(original).hexdigest() == before[str(production_source.relative_to(ROOT))],393                'Production source changed during staging')394    identities = {'factory': git(ROOT, 'rev-parse', 'HEAD'),395                  'sdk': git(ROOT / 'cdk-rsx', 'rev-parse', 'HEAD'),396                  'sdkStatus': git(ROOT / 'cdk-rsx', 'status', '--porcelain'),397                  'sources': before, 'toolIdentity': tool_identity}398    require(not git(ROOT, 'status', '--porcelain') and not identities['sdkStatus'],399            'Factory and SDK must be clean')400    staged_hashes = {}401    if suite != 'page-pool':402        staged_hashes = {path.name: sha(path) for path in (main, staged)}403        identities['staged'] = staged_hashes404        identities['exactProductionPrefixBytes'] = len(original)405        if suite in ('buddy-split', 'buddy-split-negative', 'buddy-coalesce-research',406                     'buddy-coalesce-witness', 'buddy-coalesce-negative'):407            identities['sourceFragments'] = fragments408    (output / 'inputs.json').write_text(json.dumps(identities, indent=2) + '\n')409    metadata_sha = sha(output / 'inputs.json')410    print('Running ' + suite + '; local output: ' + str(output), flush=True)411    with (output / 'run.log').open('w') as log:412        proc = subprocess.run([str(x) for x in argv], cwd=ROOT, env=env,413                              stdout=log, stderr=subprocess.STDOUT)414    require(before == {str(p.relative_to(ROOT)): sha(p) for p in sources},415            'Source changed while verification was running')416    require(all((output / name).is_file() and not (output / name).is_symlink()417                for name in ('inputs.json', *staged_hashes)),418            'Missing or symlinked producer metadata/staged file')419    require(sha(output / 'inputs.json') == metadata_sha, 'Producer metadata changed during verification')420    require(staged_hashes == {name: sha(output / name) for name in staged_hashes},421            'Staged compilation files changed during verification')422    if suite != 'page-pool':423        require(staged.read_bytes() == original + tail, 'Staged source changed during verification')424    require(identities['factory'] == git(ROOT, 'rev-parse', 'HEAD')425            and identities['sdk'] == git(ROOT / 'cdk-rsx', 'rev-parse', 'HEAD')426            and not git(ROOT, 'status', '--porcelain')427            and not git(ROOT / 'cdk-rsx', 'status', '--porcelain'),428            'Producer checkout identity changed during verification')429    require(result_path.is_file(), 'Verifier produced no result; inspect run.log')430    kani_install.verify(tool_identity, TEMP)431    summary = validate_run(output, suite, proc.returncode)432    print(json.dumps({'suite': suite, 'status': result_status(suite),433                      'summary': summary, 'output': str(output)}, indent=2))434    return {'output': str(output), 'exit_code': proc.returncode,435            'result_sha256': sha(result_path), 'log_sha256': sha(output / 'run.log'),436            'inputs_sha256': metadata_sha, 'staged_sha256': staged_hashes}437438439def main():440    parser = argparse.ArgumentParser(description=__doc__)441    sub = parser.add_subparsers(dest='action', required=True)442    sub.add_parser('tool-help', help='Show Kani options using the isolated installation')443    p = sub.add_parser('run')444    p.add_argument('suite', choices=[*SUITES, 'page-pool'])445    p.add_argument('--timeout', type=int, default=180)446    options = parser.parse_args()447    TEMP.mkdir(exist_ok=True)448    with (TEMP / '.kani-runner.lock').open('w') as lock:449        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)450        if options.action == 'tool-help':451            require((LAUNCHER / 'kani').is_file() and (KANI / 'toolchain/bin/rustc').is_file(),452                    'Required corrected Kani installation is absent; integration owner must provision it')453            kani_install.capture(TEMP)454            command([LAUNCHER / 'kani', '--help'], env=environment())455        else:456            run(options.suite, options.timeout)457            if options.suite == 'equality':458                run('equality-negative', options.timeout)459            elif options.suite == 'count-ones':460                run('count-ones-negative', options.timeout)461            elif options.suite == 'ceil32':462                run('ceil32-negative', options.timeout)463464465if __name__ == '__main__':466    try:467        main()468    except (RuntimeError, subprocess.CalledProcessError, BlockingIOError) as error:469        print('Verification refused: ' + str(error), file=sys.stderr)470        sys.exit(1)