ZZZ Digital Lab

Back to WaitLens

scripts/build_qnx.py

"""Owner-invoked local SDP build. No login, downloads, activation, or upload.

Run after the owner initializes an already licensed SDP environment. The qcc
path is explicit. Compiler output stays in the terminal; it is not copied to a
public log. No environment dump or credential-file discovery is performed.
"""
import argparse
from datetime import datetime, timezone
import hashlib
import json
from pathlib import Path
import struct
import subprocess
import sys

ROOT = Path(__file__).resolve().parents[1]

def sha(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()

def elf_machine(data):
    if len(data) < 64 or data[:6] != b'\x7fELF\x02\x01':
        raise ValueError('expected a 64-bit little-endian ELF')
    return struct.unpack_from('<H', data, 18)[0]

def main(argv=None, *, runner=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--qcc', type=Path, required=True)
    parser.add_argument('--variant', choices=['gcc_ntox86_64', 'gcc_ntoaarch64le'], default='gcc_ntox86_64')
    parser.add_argument('--out-dir', type=Path, default=ROOT / 'build/qnx')
    args = parser.parse_args(argv)
    qcc = args.qcc.resolve()
    if not qcc.is_file():
        parser.error('qcc executable not found at the owner-supplied path')
    out = args.out_dir.resolve()
    out.mkdir(parents=True, exist_ok=True)
    receipt_path = out / 'build-receipt.json'
    source = ROOT / 'target' / 'waitlens_probe.c'
    binary = out / 'waitlens_probe'
    temporary = out / 'waitlens_probe.pending'
    receipt = {'schema_version': 1, 'status': 'started',
               'time_utc': datetime.now(timezone.utc).isoformat(),
               'source': 'target/waitlens_probe.c', 'source_sha256': sha(source),
               'variant': args.variant, 'toolchain': 'owner-installed QNX SDP 8.0 qcc',
               'runtime_verified': False,
               'command': ['qcc', '-V' + args.variant, '-nopipe', '-D_QNX_SOURCE',
                           '-std=c11', '-Wall', '-Wextra', '-Werror',
                           'target/waitlens_probe.c', '-o', 'build/qnx/waitlens_probe.pending']}
    display_out = out.relative_to(ROOT).as_posix() if out.is_relative_to(ROOT) else str(out)
    receipt['command'][-1] = display_out + '/waitlens_probe.pending'
    receipt_path.write_text(json.dumps(receipt, indent=2) + '\n', encoding='utf-8')
    try:
        # A stale temporary file must never become evidence for a later failed build.
        if temporary.exists():
            temporary.unlink()
        command = [str(qcc)] + receipt['command'][1:-1] + [str(temporary)]
        completed = (runner or subprocess.run)(command, cwd=ROOT, timeout=120, check=False)
        receipt['compiler_exit'] = completed.returncode
        if completed.returncode:
            raise ValueError('compiler failed; owner must resolve the terminal diagnostic')
        machine = elf_machine(temporary.read_bytes())
        expected = 62 if args.variant == 'gcc_ntox86_64' else 183
        if machine != expected:
            raise ValueError('ELF architecture does not match the requested variant')
        temporary.replace(binary)
        receipt.update(status='built', binary=display_out + '/waitlens_probe',
                       binary_sha256=sha(binary), elf_machine=machine,
                       note='Local build receipt, not independent attestation or a runtime test. Source has a QNX 8.0 compiler guard.')
    except (OSError, ValueError, subprocess.TimeoutExpired) as error:
        receipt['status'] = 'failed'
        receipt['reason'] = type(error).__name__
        print('QNX build did not complete. Inspect the local terminal; do not claim QNX verification.', file=sys.stderr)
    receipt_path.write_text(json.dumps(receipt, indent=2) + '\n', encoding='utf-8')
    print('Build receipt:', receipt_path.relative_to(ROOT), 'status=' + receipt['status'])
    return 0 if receipt['status'] == 'built' else 2

if __name__ == '__main__':
    raise SystemExit(main())