From 326fef0dc221fc782d4dd7cc54639afe2dcc346a Mon Sep 17 00:00:00 2001 From: Tyler Smith <74526874+tylertms@users.noreply.github.com> Date: Fri, 16 Oct 2026 07:24:25 +0000 Subject: [PATCH] build: replace dev shell and Python VM tooling with cargo xtask --- .cargo/config.toml | 2 + .github/workflows/ci.yml.disabled | 17 +- Cargo.lock | 12 + Cargo.toml | 10 +- {dev/boot => crates/stela-boot}/Cargo.lock | 2 +- {dev/boot => crates/stela-boot}/Cargo.toml | 8 +- {dev/boot => crates/stela-boot}/build.rs | 0 {dev/boot => crates/stela-boot}/link.ld | 0 {dev/boot => crates/stela-boot}/src/entry.S | 0 {dev/boot => crates/stela-boot}/src/heap.rs | 0 {dev/boot => crates/stela-boot}/src/main.rs | 0 .../stela-boot}/src/multiboot.rs | 0 {dev/boot => crates/stela-boot}/src/paging.rs | 0 {dev/boot => crates/stela-boot}/src/serial.rs | 0 dev/boot/package.py | 89 ---- dev/boot/run.py | 94 ----- dev/check | 40 -- dev/stela | 4 - dev/system_vm.py | 388 ------------------ dev/vm-memory.py | 67 --- dev/vm.py | 325 --------------- dev/vm/boot.S | 119 ------ dev/vm/debug.gdb | 10 - dev/vm/x86_64_boot.S | 269 ------------ xtask/Cargo.toml | 17 + xtask/src/boot.rs | 334 +++++++++++++++ xtask/src/check.rs | 48 +++ xtask/src/main.rs | 38 ++ xtask/src/tools.rs | 83 ++++ 29 files changed, 550 insertions(+), 1426 deletions(-) create mode 100644 .cargo/config.toml rename {dev/boot => crates/stela-boot}/Cargo.lock (99%) rename {dev/boot => crates/stela-boot}/Cargo.toml (67%) rename {dev/boot => crates/stela-boot}/build.rs (100%) rename {dev/boot => crates/stela-boot}/link.ld (100%) rename {dev/boot => crates/stela-boot}/src/entry.S (100%) rename {dev/boot => crates/stela-boot}/src/heap.rs (100%) rename {dev/boot => crates/stela-boot}/src/main.rs (100%) rename {dev/boot => crates/stela-boot}/src/multiboot.rs (100%) rename {dev/boot => crates/stela-boot}/src/paging.rs (100%) rename {dev/boot => crates/stela-boot}/src/serial.rs (100%) delete mode 100644 dev/boot/package.py delete mode 100644 dev/boot/run.py delete mode 100755 dev/check delete mode 100755 dev/stela delete mode 100644 dev/system_vm.py delete mode 100644 dev/vm-memory.py delete mode 100755 dev/vm.py delete mode 100644 dev/vm/boot.S delete mode 100644 dev/vm/debug.gdb delete mode 100644 dev/vm/x86_64_boot.S create mode 100644 xtask/Cargo.toml create mode 100644 xtask/src/boot.rs create mode 100644 xtask/src/check.rs create mode 100644 xtask/src/main.rs create mode 100644 xtask/src/tools.rs diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000000..75daa33ca4 --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,2 @@ +[alias] +xtask = "run --quiet --locked --package xtask --" diff --git a/.github/workflows/ci.yml.disabled b/.github/workflows/ci.yml.disabled index a55bf22636..a8788a1716 100644 --- a/.github/workflows/ci.yml.disabled +++ b/.github/workflows/ci.yml.disabled @@ -8,23 +8,10 @@ jobs: - uses: dtolnay/rust-toolchain@stable with: components: rustfmt, clippy - - run: ./dev/check + - run: rustup target add x86_64-unknown-none + - run: cargo xtask check - run: python3 -m pip install -r dev/requirements-test.txt - run: python3 -m unittest discover -s dev -p 'test_*.py' - - run: sudo apt-get update && sudo apt-get install -y qemu-system-x86 clang - - run: python3 dev/vm.py smoke - - run: | - python3 -c 'import struct; from pathlib import Path; Path(".stela/leaf.arm64").write_bytes(struct.pack(" load['memory_bytes'] or load['offset'] + load['file_bytes'] > len(raw): - raise ValueError('invalid actual LOAD extent') - if load['file_bytes'] and load['physical'] - load['offset'] != bias: - raise ValueError('LOADs are not one linear initialized file mapping') - if load['file_bytes'] and load['physical'] + load['file_bytes'] > end: - raise ValueError('initialized LOAD outside declared address-fields extent') - previous = load['physical'] + load['memory_bytes'] - if not (start < end <= bss_end < 0x10000000) or previous != bss_end: - raise ValueError('invalid linked image/BSS reservation') - image = raw[start - bias:end - bias] - header_offset = found['stela_multiboot_header'] - start - if header_offset < 0 or header_offset + 32 > min(len(image), 8192) or header_offset % 4: - raise ValueError('Multiboot header not in first aligned 8KiB') - header = struct.unpack_from('<8I', image, header_offset) - expected = (found['stela_multiboot_header'], start, end, bss_end, found['stela_start32']) - if header[0] != 0x1badb002 or header[1] != 0x10003 or sum(header[:3]) & 0xffffffff or header[3:] != expected: - raise ValueError('linked Multiboot address-fields/checksum mismatch') - output.mkdir(parents=True, exist_ok=True) - flat = output / 'stela-multiboot.bin' - flat.write_bytes(image) - (output / 'llvm-program-headers.txt').write_text(headers) - (output / 'llvm-image-symbols.json').write_text(json.dumps(found, indent=2) + '\n') - report = dict(elf=dict(path=str(elf), sha256=sha(raw), bytes=len(raw)), - flat=dict(path=str(flat.resolve()), sha256=sha(image), bytes=len(image)), - linked_symbols=found, multiboot_header=list(header), loads=loads, - bss_zero_bytes=bss_end - end, - claim='Exact host packaging; no QEMU execution or OS boot claim.') - (output / 'image-binding.json').write_text(json.dumps(report, indent=2) + '\n') - print(json.dumps(report, indent=2)) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--elf', required=True, type=Path) - parser.add_argument('--output', required=True, type=Path) - parser.add_argument('--llvm-bin', type=Path, default=Path('/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin')) - args = parser.parse_args() - package(args.elf.resolve(), args.output.resolve(), args.llvm_bin) diff --git a/dev/boot/run.py b/dev/boot/run.py deleted file mode 100644 index 640e2279f8..0000000000 --- a/dev/boot/run.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/env python3 -"""Execute a packaged shared-runtime diagnostic in bounded single-BSP x86 QEMU. - -The module is passed unchanged to QEMU. Its ARM placement and initial state are -ordinary explicit machine data. All target compilation and native execution are -inside the real freestanding shared runtime; this host tool only launches QEMU. -""" -import hashlib -import json -from pathlib import Path -import subprocess -import time -import tempfile - - -def binding(path): - raw = path.read_bytes() - return dict(path=str(path), bytes=len(raw), sha256=hashlib.sha256(raw).hexdigest()) - - -def run(args, monitor_type): - args.output.mkdir(parents=True, exist_ok=False) - serial = args.output / 'serial.txt' - command = [str(args.qemu), '-machine', - 'q35,smm=off,sata=off,usb=off,smbus=off,hpet=off,i8042=off,vmport=off', - '-accel', 'tcg,thread=single', '-cpu', 'qemu64', '-smp', '1', '-m', '1G', - '-nodefaults', '-no-reboot', '-display', args.display, '-monitor', 'none', - '-device', 'isa-debug-exit,iobase=0xf4,iosize=4', - '-kernel', str(args.image), '-initrd', str(args.module), '-append', args.append] - if args.display == 'cocoa': - command.extend(['-chardev', 'vc,id=uart,cols=132,rows=50,logfile=' + str(serial), '-serial', 'chardev:uart']) - else: - command.extend(['-serial', 'file:' + str(serial)]) - qmp_directory = tempfile.TemporaryDirectory(prefix="stela-qmp-", dir="/tmp") if args.capture_console else None - qmp_socket = Path(qmp_directory.name) / "q" if qmp_directory else None - if qmp_socket: - command.extend(["-qmp", f"unix:{qmp_socket},server=on,wait=off"]) - start = time.monotonic() - report = dict(command=command, runner=binding(Path(__file__).resolve()), qemu=binding(args.qemu), image=binding(args.image), - original_module=binding(args.module), timeout_seconds=args.timeout, - platform='One BSP; TCG single; SMM off; no optional/default DMA devices; IF must actually be clear; terminal assembly NMI handlers.', - claim='Bounded component diagnostic; intact macOS boot/installation unverified.') - (args.output / 'start.json').write_text(json.dumps(report, indent=2) + '\n') - with (args.output / 'stdout.txt').open('wb') as out, (args.output / 'stderr.txt').open('wb') as err: - process = subprocess.Popen(command, stdout=out, stderr=err) - if qmp_socket: - try: - deadline = time.monotonic() + min(2, args.timeout / 2) - while not qmp_socket.exists() and process.poll() is None and time.monotonic() < deadline: - time.sleep(0.05) - # Capture the actual text-console surface once after initial UART. - time.sleep(min(1, max(0, deadline - time.monotonic()))) - monitor = monitor_type(socket_path=qmp_socket) - try: - image = args.output / "console.ppm" - report["qmp_screendump"] = monitor.execute("screendump", {"filename": str(image)}) - report["console_image"] = binding(image) - finally: - monitor.close() - except (OSError, RuntimeError, ValueError) as error: - report["console_capture_failure"] = str(error) - try: - report['returncode'] = process.wait(timeout=max(0.01, args.timeout - (time.monotonic() - start))) - report['timed_out'] = False - except subprocess.TimeoutExpired: - process.terminate() - try: - process.wait(timeout=5) - except subprocess.TimeoutExpired: - process.kill() - process.wait() - report['returncode'] = process.returncode - report['timed_out'] = True - report['wall_seconds'] = time.monotonic() - start - if qmp_directory: - qmp_directory.cleanup() - report['outputs'] = [binding(p) for p in [serial, args.output / 'stdout.txt', args.output / 'stderr.txt'] if p.exists()] - (args.output / 'completion.json').write_text(json.dumps(report, indent=2) + '\n') - print(json.dumps(report, indent=2)) - # Preserve actual debug-exit carrier; 33 means requested component stop only. - return report['returncode'] if not report['timed_out'] else 124 - - -def configure_parser(parser): - parser.add_argument('--qemu', required=True, type=lambda v: Path(v).resolve()) - parser.add_argument('--image', required=True, type=lambda v: Path(v).resolve()) - parser.add_argument('--module', required=True, type=lambda v: Path(v).resolve()) - parser.add_argument('--output', required=True, type=lambda v: Path(v).resolve()) - parser.add_argument('--display', choices=['none', 'cocoa'], default='none', - help='Optional visible host UART console; creates no guest VGA/display device.') - parser.add_argument('--capture-console', action='store_true', - help='One actual QMP screendump attempt using the existing VM monitor.') - parser.add_argument('--append', default='') - parser.add_argument('--timeout', type=float, default=60) diff --git a/dev/check b/dev/check deleted file mode 100755 index 3e14c1bcbe..0000000000 --- a/dev/check +++ /dev/null @@ -1,40 +0,0 @@ -#!/bin/sh -# Shared local/CI Rust checks. Formatting is read-only unless --fix is explicit. -set -eu -root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) -usage() { - cat <<'USAGE' -Usage: ./dev/check [--fix] - -Run Rust formatting checks, strict workspace and freestanding Clippy, then -workspace tests. Default checks do not format source files. --fix formats Rust -sources first. -USAGE -} -fix=false -case "$#" in - 0) ;; - 1) - case "$1" in - --fix) fix=true ;; - --help|-h) usage; exit 0 ;; - *) usage >&2; exit 2 ;; - esac - ;; - *) usage >&2; exit 2 ;; -esac -cd "$root" -# The freestanding mount has its own manifest outside the workspace. -boot=dev/boot/Cargo.toml -if [ "$fix" = true ]; then - ./dev/cargo fmt --all - ./dev/cargo fmt --manifest-path "$boot" --all -fi -./dev/cargo fmt --all -- --check -./dev/cargo fmt --manifest-path "$boot" --all -- --check -./dev/cargo clippy --workspace --all-targets --locked -- -D warnings -# RUSTFLAGS also denies warnings in the runtime crates the mount builds without -# std; registry dependencies stay lint-capped. Output stays under ignored target/. -RUSTFLAGS="-D warnings" ./dev/cargo clippy --manifest-path "$boot" --locked \ - --target x86_64-unknown-none --target-dir target/boot -- -D warnings -./dev/cargo test --workspace --locked diff --git a/dev/stela b/dev/stela deleted file mode 100755 index 6bd077aba6..0000000000 --- a/dev/stela +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/sh -set -eu -root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) -exec "$root/dev/cargo" run --quiet --locked -p stela-cli -- "$@" diff --git a/dev/system_vm.py b/dev/system_vm.py deleted file mode 100644 index d3ef5cfc02..0000000000 --- a/dev/system_vm.py +++ /dev/null @@ -1,388 +0,0 @@ -#!/usr/bin/env python3 -"""Execute original Stela ARM tasks on the freestanding x86 QEMU debug machine. - -Host page-fault retry and PIT delivery are exercised inside actual translated -code. This does not implement ARM EL1 exception delivery or an ARM MMU. -""" -import argparse -import hashlib -import json -import os -import re -from pathlib import Path -import shutil -import socket -import struct -import subprocess -import time - -import vm -from evidence import write_evidence - -ROOT = Path(__file__).resolve().parents[1] -GUEST_BASE = 0x100000 -STATE_BYTES = 784 -STATE_A = 0x6000 -STATE_B = 0x6400 -TASK_DATA = (0x8000, 0x8010) -TIMER_TICKS = 0x8040 -TRACE = 0x9000 -FAULT_STATE = 0xB000 -FAULT_RAM = 0xB400 -FAULT_ADDRESS = 0x200000 -NATIVE_BASE = 0x10000 -MINIMUM_NATIVE_IRQS = 4 -INITIAL_X3 = 0xDEADBEEF -PAGE_FAULT_WORD_INDEX = 5 -LOOP_WORDS = 12 -INITIAL_NZCV = 0xB0000000 -NZCV_OFFSET = 256 -GPR_COUNT = 32 -BLOCK_ABI = "x86_64-sysv-guest-state-v2-block-exit-direct-ram" - - -def sha256(data): - return hashlib.sha256(data).hexdigest() - - -def task_words(): - """Named A64 encodings for an original two-task polling/fault fixture.""" - mov_register = 0xAA0003E0 - ldr_unsigned_x = 0xF9400000 - str_unsigned_x = 0xF9000000 - add_immediate_x = 0x91000000 - movz_x = 0xD2800000 - cmp_immediate_x = 0xF100001F - branch_condition = 0x54000000 - condition_carry_clear = 3 - brk = 0xD4200000 - branch_word_index = LOOP_WORDS - 1 - backward_word_offset = (-branch_word_index) & ((1 << 19) - 1) - return [ - mov_register | (5 << 16), # MOV X0,X5 - ldr_unsigned_x | 1, # LDR X1,[X0] - add_immediate_x | (1 << 10) | (1 << 5) | 1, # ADD X1,X1,#1 - str_unsigned_x | 1, # STR X1,[X0] - movz_x | (1 << 21) | (0x20 << 5) | 2, # MOV X2,#0x200000 - ldr_unsigned_x | (2 << 5) | 3, # LDR X3,[X2] - add_immediate_x | (7 << 10) | (3 << 5) | 3, # ADD X3,X3,#7 - str_unsigned_x | (1 << 10) | 3, # STR X3,[X0,#8] - movz_x | (TIMER_TICKS << 5) | 4, # MOV X4,#timer - ldr_unsigned_x | (4 << 5) | 4, # LDR X4,[X4] - cmp_immediate_x | (MINIMUM_NATIVE_IRQS << 10) | (4 << 5), - branch_condition | (backward_word_offset << 5) | condition_carry_clear, - brk | (0x10 << 5), - ] - - -def initial_state(task): - registers = [0x0123456700000000 + task * 0x10000 + index for index in range(GPR_COUNT)] - registers[3] = INITIAL_X3 - registers[5] = TASK_DATA[task] - registers[31] = 0x700000 + task * 0x1000 - vectors = bytes((index * 13 + task * 7 + 1) & 0xFF for index in range(512)) - return struct.pack("<32QII", *registers, INITIAL_NZCV, 0x11223344) + vectors + struct.pack(" ticks: - raise RuntimeError("Fault snapshot RAM prefix differs") - return {"dispatches": dispatches, "tasks": states, "fault": { - "count": faults, "address": address, "error": error, "native_rip": rip, - "native_offset": fault_offset, "source_pc": fault_pc, - "snapshot_sha256": sha256(fault_state), "destination_before": before_x3, - "ticks_at_fault": fault_ram[8], - "retry": "unchanged native RIP; #PF handler installs identity page then IRETQ", - }, "pit": {"total_interrupts": all_irqs, "translated_interrupts": ticks, - "native_rip": irq_rip, "native_offset": irq_offset, "source_pc": irq_pc}} - - -def run(stela, directory, assembly, qmp_port, gdb_port): - owned_sources = (Path(__file__), assembly, ROOT / "dev/vm.py", ROOT / "dev/vm/boot.S") - source_hashes = {str(path.relative_to(ROOT)): sha256(path.read_bytes()) for path in owned_sources} - cli_sha256 = sha256(stela.read_bytes()) - source, manifests = compile_tasks(stela, directory) - native, symbols = build_payload(directory, assembly) - vm.STATE = directory / "vm" - vm.QMP_PORT, vm.GDB_PORT = qmp_port, gdb_port - args = vm.command(paused=True, native=native) - for port in (qmp_port, gdb_port): - with socket.socket() as probe: - probe.bind(("127.0.0.1", port)) - (vm.STATE / "debug.log").write_text("") - monitor = None - with (directory / "qemu.stderr").open("w") as log: - process = subprocess.Popen(args, stdout=log, stderr=log) - launch = {"pid": process.pid, "started_unix_ns": time.time_ns(), "command": args} - (directory / "launch.json").write_text(json.dumps(launch, indent=2) + "\n") - print(json.dumps({"qemu_pid": process.pid, "output_dir": str(directory)}), flush=True) - try: - deadline = time.monotonic() + 30 - while time.monotonic() < deadline: - if process.poll() is not None: - raise RuntimeError("QEMU exited before monitor connection") - try: - monitor = vm.Monitor() - break - except OSError: - time.sleep(0.05) - if monitor is None: - raise RuntimeError("QMP did not start") - with socket.create_connection(("127.0.0.1", gdb_port), timeout=5) as debug: - debug.sendall(b"$?#3f") - reply = b"" - while b"#" not in reply: - chunk = debug.recv(4096) - if not chunk: - raise RuntimeError("GDB stub disconnected") - reply += chunk - if b"$T" not in reply and b"$S" not in reply: - raise RuntimeError("GDB stub did not report stopped CPU") - debug.sendall(b"+") - monitor.execute("cont") - while time.monotonic() < deadline: - output = (vm.STATE / "debug.log").read_text() - if "OK\n" in output or "E" in output: - break - if process.poll() is not None: - raise RuntimeError("QEMU stopped while executing fixture") - time.sleep(0.01) - monitor.execute("stop") - registers = monitor.human("info registers") - (directory / "registers.txt").write_text(registers) - inspect_memory(monitor, directory) - if "OK\n" not in (vm.STATE / "debug.log").read_text(): - raise RuntimeError("Translated system fixture did not complete") - match = re.search(r"RIP=([0-9a-fA-F]+)", registers) - if match is None or not symbols["completed"] <= int(match.group(1), 16) < symbols["completed"] + 3: - raise RuntimeError("Stopped native RIP is outside the completion halt loop") - observations = verify(monitor, directory, manifests, symbols) - if source_hashes != {str(path.relative_to(ROOT)): sha256(path.read_bytes()) for path in owned_sources} or cli_sha256 != sha256(stela.read_bytes()): - raise RuntimeError("Sources or frozen compiler changed during execution") - report = { - "schema_version": 1, "kind": "translated_x86_platform_boundaries", "passed": True, - "original_arm_sha256": sha256(source), - "original_inspection_sha256": sha256((directory / "original-inspection.json").read_bytes()), "stela_sha256": cli_sha256, - "compiler_source_sha256": manifests[0]["compiler_source_sha256"], - "native_payload_sha256": sha256(native.read_bytes()), "block_manifests": manifests, - "native_inspection_sha256": {name: sha256((directory / f"{name}-native-inspection.json").read_bytes()) for name in ("loop", "trap")}, - "boot_image_sha256": sha256((vm.STATE / "boot.img").read_bytes()), - "boot_elf_sha256": sha256((vm.STATE / "boot.elf").read_bytes()), - "source_sha256": source_hashes, - "initial_state_sha256": [sha256(initial_state(task)) for task in (0, 1)], - "qemu_sha256": sha256(Path(vm.qemu_binary()).read_bytes()), - "symbols": {key: symbols[key] for key in ("_start", "page_fault", "timer_irq", "loop_native", "loop_native_end", "trap_native", "completed")}, - "qemu": subprocess.check_output([vm.qemu_binary(), "--version"], text=True).splitlines()[0], - "qemu_command": args, "gdb_stub": "initial stopped-state handshake passed", - "observations": observations, - "limits": ["Host x86 page-fault retry and PIT IRQ; no ARM architectural exception delivery", - "Fixed identity direct-RAM profile; no ARM MMU, TLB or device emulation", - "Two serialized guest states, not ARM preemptive task scheduling", - "AOT block execution only; runtime compilation/cache not linked in freestanding image", - "No macOS boot or application acceptance; QEMU TCG timing is not native performance"], - } - monitor.execute("quit") - process.wait(timeout=5) - report["process"] = {**launch, "returncode": process.returncode, "finished_unix_ns": time.time_ns()} - if process.returncode != 0: - raise RuntimeError("QEMU did not exit cleanly after successful observations") - write_evidence(directory / "receipt.json", report) - return report - finally: - if monitor: - monitor.close() - if process.poll() is None: - process.terminate() - try: - process.wait(timeout=5) - except subprocess.TimeoutExpired: - process.kill() - process.wait() - launch.update({"returncode": process.returncode, "finished_unix_ns": time.time_ns()}) - (directory / "launch.json").write_text(json.dumps(launch, indent=2) + "\n") - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--stela", type=Path, required=True, help="Existing frozen Stela compiler executable") - parser.add_argument("--output-dir", type=Path, required=True, help="Fresh ignored evidence directory") - parser.add_argument("--qmp-port", type=int, default=4447) - parser.add_argument("--gdb-port", type=int, default=1237) - arguments = parser.parse_args() - directory = arguments.output_dir.resolve() - ignored_root = (ROOT / ".stela").resolve() - if not directory.is_relative_to(ignored_root): - parser.error("output directory must be under ignored .stela/") - if not all(1 <= port <= 65535 for port in (arguments.qmp_port, arguments.gdb_port)) or arguments.qmp_port == arguments.gdb_port: - parser.error("QMP/GDB ports must be distinct and in 1..65535") - directory.mkdir(parents=True, exist_ok=False) - assembly = ROOT / "dev/vm/x86_64_boot.S" - report = run(arguments.stela.resolve(), directory, assembly, arguments.qmp_port, arguments.gdb_port) - print(json.dumps({"passed": report["passed"], "receipt": str(directory / "receipt.json"), - "observations": report["observations"]}, indent=2)) - - -if __name__ == "__main__": - main() diff --git a/dev/vm-memory.py b/dev/vm-memory.py deleted file mode 100644 index ac9c2e45e3..0000000000 --- a/dev/vm-memory.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python3 -"""Assemble our original ARM memory fixture, AOT compile, then check RAM in QEMU.""" -import argparse -import hashlib -import json -from pathlib import Path -import subprocess -import sys -import tempfile - -from evidence import ROOT, write_evidence - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--fixture", choices=("scalar", "pair", "simd"), default="scalar") - parser.add_argument("--no-build", action="store_true", help="Use the already built, frozen CLI") - args = parser.parse_args() - if not args.no_build: - subprocess.run([str(ROOT / "dev/cargo"), "build", "--locked", "-p", "stela-cli"], check=True) - cli = ROOT / "target/debug/stela" - assembly = ROOT / "tests/fixtures" / {"scalar": "memory.S", "pair": "pair.S", "simd": "simd-memory.S"}[args.fixture] - with tempfile.TemporaryDirectory(prefix="stela-vm-memory-") as temporary: - directory = Path(temporary) - object_path = directory / "memory.o" - subprocess.run(["clang", "--target=arm64-apple-macos", "-c", str(assembly), "-o", str(object_path)], check=True) - rows = json.loads(subprocess.check_output([str(cli), "binary-text", str(object_path)])) - if len(rows) != 1 or len(rows[0]["slice"]["sections"]) != 1: - raise AssertionError("Unexpected original fixture layout") - section = rows[0]["slice"]["sections"][0] - if section["name"] != "__text": - raise AssertionError("Expected fixture text section") - source = bytes.fromhex(section["data_hex"]) - input_path = directory / "memory.arm64" - input_path.write_bytes(source) - prepared = json.loads(subprocess.check_output([str(cli), "prepare-leaf", str(input_path)])) - native_path = Path(prepared["directory"]) / "native.bin" - checks = ["0x8000=40", "0x8008=42", "0x8010=42", "0x8ff0=42", "0x60f8=0x9000"] - if args.fixture == "pair": - checks = ["0x8000=40", "0x8008=2", "0x8010=0x0000000200000028", "0x8018=0x7fffffff80000000", - "0x8020=0xffffffff80000000", "0x8028=0x7fffffff", "0x8ff0=40", "0x8ff8=2", "0x60f8=0x9000"] - if args.fixture == "simd": - mask = "0xff00ff0000ff00ff" - checks = [f"0x8000={mask}", f"0x8008={mask}", "0x8010=255", "0x8018=0", - "0x8020=255", "0x8028=0", f"0x8ff0={mask}", f"0x8ff8={mask}", - "0x60f8=0x9000", "0x6108=255", "0x6110=0", "0x62f8=255", "0x6300=0", - "0x6308=0", "0x8030=255", "0x8038=0", "0x8040=255", "0x8048=0", - "0x6148=255", "0x6150=0", "0x6158=255", "0x6160=0", - f"0x6168={mask}", f"0x6170={mask}", f"0x6178={mask}", f"0x6180={mask}", - f"0x8fe0={mask}", f"0x8fe8={mask}"] - arguments = [sys.executable, str(ROOT / "dev/vm.py"), "smoke", "--native", str(native_path)] - for check in checks: - arguments.extend(["--expect-memory", check]) - observed = json.loads(subprocess.check_output(arguments)) - report = {"kind": "assembled_arm_memory_fixture_in_x86_vm", "fixture": args.fixture, "passed": True, - "assembly_sha256": hashlib.sha256(assembly.read_bytes()).hexdigest(), - "arm_source_sha256": hashlib.sha256(source).hexdigest(), "aot_cache_key": prepared["key"], - "translation_manifest": prepared["manifest"], "native_artifact": str(native_path), "vm": observed, - "limits": "Original Stela fixture and identity-mapped RAM only. QEMU debug evidence, not macOS boot or a native performance benchmark."} - destination = ROOT / ".stela/vm" / {"scalar": "memory-smoke-report.json", "pair": "pair-smoke-report.json", "simd": "simd-smoke-report.json"}[args.fixture] - write_evidence(destination, report) - print(json.dumps({"report": str(destination), "passed": True, "guest_x0": observed["expected_result"], - "checked_memory_locations": len(observed["memory_checks"]), "native_artifact": str(native_path)}, indent=2)) - - -if __name__ == "__main__": - main() diff --git a/dev/vm.py b/dev/vm.py deleted file mode 100755 index ae69a9ee89..0000000000 --- a/dev/vm.py +++ /dev/null @@ -1,325 +0,0 @@ -#!/usr/bin/env python3 -"""Build, launch, inspect, and smoke-test the x86 native-code development VM.""" -import argparse -import hashlib -import json -import os -import re -from pathlib import Path -import shutil -import socket -import struct -import subprocess -import time -from evidence import write_evidence - -ROOT = Path(__file__).resolve().parents[1] -STATE = ROOT / ".stela" / "vm" -# Keep UNIX socket paths below macOS's 104-byte limit even in deep checkouts. -QMP_PORT = 4444 -GDB_PORT = 1234 - - -def fixture_symbols(path): - """Read symbols from our locally generated ELF32 fixture (no extra tools).""" - data = path.read_bytes() - if data[:6] != b"\x7fELF\x01\x01": - raise RuntimeError("Expected a little-endian ELF32 fixture") - table = struct.unpack_from(" x86-64 long mode -> test payload. - * Link at 0x7c00. No Apple code, filesystem, or operating system required. - * PML4=0x1000, PDPT=0x2000, PD=0x3000; identity maps the first 2 MiB. - */ -.section .text -.global _start, long_mode, payload, completed -.code16 -_start: - cli - xorw %ax, %ax - movw %ax, %ds - movw %ax, %es - movw %ax, %ss - movw $0x7c00, %sp - cld -#ifdef STELA_TRANSLATED - /* BIOS overwrites low RAM during startup. Read native code from LBA 1 - * into 0x1000:0000 after BIOS has handed us the boot sector. */ - movw $disk_packet, %si - movb $0x42, %ah - sti - int $0x13 - cli - jc disk_failure -#endif - inb $0x92, %al - orb $2, %al - outb %al, $0x92 - - xorw %ax, %ax - movw $0x1000, %di - movw $0x1800, %cx - rep stosw - movl $0x2003, 0x1000 - movl $0x3003, 0x2000 - movl $0x0083, 0x3000 - lgdt gdt_pointer - movl %cr4, %eax - /* PAE, OSFXSR and OSXMMEXCPT: native x86-64/SSE2 baseline. */ - orl $0x620, %eax - movl %eax, %cr4 - movl $0x1000, %eax - movl %eax, %cr3 - movl $0xc0000080, %ecx - rdmsr - orl $0x100, %eax - wrmsr - movl %cr0, %eax - andl $0xfffffff3, %eax /* clear EM/TS before native SIMD data moves */ - orl $0x80000003, %eax /* PG/PE/MP */ - movl %eax, %cr0 - ljmpl $8, $long_mode - -.code64 -long_mode: - movw $16, %ax - movw %ax, %ds - movw %ax, %es - movw %ax, %ss - movq $0x7000, %rsp -payload: -#ifdef STELA_TRANSLATED - /* Leaf ABI v3/block ABI v2: zero all784 state bytes, including V/FP. */ - xorq %rax, %rax - movq $0x6000, %rdi - movq $98, %rcx - rep stosq - movq $0x6000, %rdi - movq $0x10000, %rax - call *%rax - /* Block ABI: preserve the RAX/RDX next-PC/kind tuple before leaf-result - * handling or debug-port writes clobber either return register. */ - movq %rax, 0x5010 - movq %rdx, 0x5018 - movq 0x6000, %rax -#else - movq $40, %rax - addq $2, %rax -#endif - movq %rax, 0x5000 - movw $0xe9, %dx - movb $'O', %al - outb %al, %dx - movb $'K', %al - outb %al, %dx - movb $10, %al - outb %al, %dx - movq 0x5000, %rax -completed: - hlt - jmp completed - -#ifdef STELA_TRANSLATED -.code16 -disk_failure: - movw $0xe9, %dx - movb $'E', %al - outb %al, %dx - hlt - jmp disk_failure -.balign 4 -disk_packet: - .byte 0x10, 0 - .word STELA_NATIVE_SECTORS - .word 0, 0x1000 - .quad 1 -#endif - -.balign 8 -gdt: - .quad 0 - .quad 0x00af9a000000ffff - .quad 0x00cf92000000ffff -gdt_end: -gdt_pointer: - .word gdt_end - gdt - 1 - .long gdt -.org 510 -.word 0xaa55 diff --git a/dev/vm/debug.gdb b/dev/vm/debug.gdb deleted file mode 100644 index 1e05fb4b1c..0000000000 --- a/dev/vm/debug.gdb +++ /dev/null @@ -1,10 +0,0 @@ -set pagination off -target remote 127.0.0.1:1234 -# ELF is 32-bit because BIOS enters in real mode; payload runs in long mode. -symbol-file .stela/vm/boot.elf -hbreak payload -continue -monitor info registers -monitor xp /8gx 0x1000 -# Use stepi / info registers / x to inspect execution. After completed: -# monitor xp /1gx 0x5000 diff --git a/dev/vm/x86_64_boot.S b/dev/vm/x86_64_boot.S deleted file mode 100644 index eda5ec2e90..0000000000 --- a/dev/vm/x86_64_boot.S +++ /dev/null @@ -1,269 +0,0 @@ -/* Freestanding x86 debug substrate. This is a host platform test, not an ARM - * exception/MMU implementation. Actual compiler blocks use the ordinary ABI. - * Entry is called by dev/vm/boot.S at 0x10000 with State A at 0x6000. */ -.set STATE_A, 0x6000 -.set STATE_B, 0x6400 -.set STATE_BYTES, 784 -.set STATE_X3, 3 * 8 -.set TASK_RAM_QWORDS, 9 -.set TRACE_QWORDS, 15 -.set TASK_A_DATA, 0x8000 -.set TIMER_TICKS, 0x8040 -.set TRACE, 0x9000 -.set DISPATCHES, TRACE -.set TASK_A_DONE, TRACE + 8 -.set TASK_B_DONE, TRACE + 16 -.set PAGE_FAULTS, TRACE + 24 -.set FAULT_ADDRESS, TRACE + 32 -.set FAULT_ERROR, TRACE + 40 -.set FAULT_RIP, TRACE + 48 -.set IRQ_RIP, TRACE + 56 -.set LAST_GUEST_PC, TRACE + 64 -.set ACTIVE_TASK, TRACE + 72 -.set FAULT_GUEST_PC, TRACE + 80 -.set FAULT_DESTINATION_BEFORE, TRACE + 88 -.set TASK_A_PC, TRACE + 96 -.set TASK_B_PC, TRACE + 104 -.set ALL_IRQS, TRACE + 112 -.set FAULT_STATE, 0xb000 -.set FAULT_RAM, 0xb400 -.set DISPATCH_LIMIT, 10000000 -.set PAGE_DIRECTORY_SECOND, 0x3008 -.set RETRY_ADDRESS, 0x200000 -.set PAGE_PRESENT_WRITE_LARGE, 0x83 -.set RETRY_PAGE_FLAGS, RETRY_ADDRESS | PAGE_PRESENT_WRITE_LARGE -.set PAGE_FAULT_ERROR_OFFSET, 4 * 8 -.set PAGE_FAULT_RIP_OFFSET, PAGE_FAULT_ERROR_OFFSET + 8 -.set IRQ_RIP_OFFSET, 8 -.set X86_STACK_SLOT_BYTES, 8 -.set DEBUG_PORT, 0xe9 -.set PIC_MASTER_COMMAND, 0x20 -.set PIC_MASTER_DATA, 0x21 -.set PIC_SLAVE_COMMAND, 0xa0 -.set PIC_SLAVE_DATA, 0xa1 -.set PIC_INIT, 0x11 -.set PIC_TIMER_VECTOR, 0x20 -.set PIC_SLAVE_VECTOR, 0x28 -.set PIC_MASTER_CASCADE, 4 -.set PIC_SLAVE_CASCADE, 2 -.set PIC_8086, 1 -.set PIC_TIMER_ONLY_MASK, 0xfe -.set PIC_ALL_MASK, 0xff -.set PIC_EOI, 0x20 -.set PIT_COMMAND, 0x43 -.set PIT_CHANNEL_ZERO, 0x40 -.set PIT_RATE_GENERATOR, 0x34 -.set PIT_DIVISOR, 11932 -.set IDT_GATE_BYTES, 16 -.set IDT_GATE_SHIFT, 4 -.set IDT_OFFSET_HIGH_SHIFT, 16 -.set IDT_INTERRUPT_GATE, 0x8e -.set CODE_SELECTOR, 8 -.set PAGE_FAULT_VECTOR, 14 -.set BLOCK_TRAP, 5 -.set TASK_B_OFFSET, 0x400 - -.section .text -.global _start, page_fault, timer_irq, loop_native, trap_native, loop_native_end, completed -.code64 -_start: - cli - sub $X86_STACK_SLOT_BYTES, %rsp /* nested SysV CALL sites require RSP%16=0 */ - cld - lea initial_state_a(%rip), %rsi - mov $STATE_A, %edi - mov $(STATE_BYTES / 8), %ecx - rep movsq - lea initial_state_b(%rip), %rsi - mov $STATE_B, %edi - mov $(STATE_BYTES / 8), %ecx - rep movsq - xor %eax, %eax - mov $TASK_A_DATA, %edi - mov $TASK_RAM_QWORDS, %ecx - rep stosq - mov $TRACE, %edi - mov $TRACE_QWORDS, %ecx - rep stosq - movabs $GUEST_LOOP_PC, %rax - mov %rax, TASK_A_PC - mov %rax, TASK_B_PC - lea page_fault(%rip), %rax - mov $PAGE_FAULT_VECTOR, %ecx - call install_gate - lea timer_irq(%rip), %rax - mov $PIC_TIMER_VECTOR, %ecx - call install_gate - lidt idt_pointer(%rip) - /* Remap and mask both 8259s before enabling only PIT IRQ0. */ - mov $PIC_INIT, %al - outb %al, $PIC_MASTER_COMMAND - outb %al, $PIC_SLAVE_COMMAND - mov $PIC_TIMER_VECTOR, %al - outb %al, $PIC_MASTER_DATA - mov $PIC_SLAVE_VECTOR, %al - outb %al, $PIC_SLAVE_DATA - mov $PIC_MASTER_CASCADE, %al - outb %al, $PIC_MASTER_DATA - mov $PIC_SLAVE_CASCADE, %al - outb %al, $PIC_SLAVE_DATA - mov $PIC_8086, %al - outb %al, $PIC_MASTER_DATA - outb %al, $PIC_SLAVE_DATA - mov $PIC_ALL_MASK, %al - outb %al, $PIC_SLAVE_DATA - mov $PIT_RATE_GENERATOR, %al - outb %al, $PIT_COMMAND - mov $PIT_DIVISOR, %ax - outb %al, $PIT_CHANNEL_ZERO - mov %ah, %al - outb %al, $PIT_CHANNEL_ZERO - mov $PIC_TIMER_ONLY_MASK, %al - outb %al, $PIC_MASTER_DATA - sti -schedule: - mov ACTIVE_TASK, %r12 - mov $STATE_A, %edi - mov TASK_A_PC(,%r12,8), %rax - test %r12, %r12 - jz dispatch - add $TASK_B_OFFSET, %rdi -dispatch: - mov %rax, LAST_GUEST_PC - incq DISPATCHES - cmpq $DISPATCH_LIMIT, DISPATCHES - ja failed - movabs $GUEST_LOOP_PC, %rcx - cmp %rcx, %rax - je run_loop - movabs $GUEST_TRAP_PC, %rcx - cmp %rcx, %rax - jne failed - lea trap_native(%rip), %rax - jmp execute -run_loop: - lea loop_native(%rip), %rax -execute: - call *%rax - mov %rax, TASK_A_PC(,%r12,8) - cmp $BLOCK_TRAP, %rdx - jne switch_task - movq $1, TASK_A_DONE(,%r12,8) -switch_task: - xorq $1, ACTIVE_TASK - cmpq $1, TASK_A_DONE - jne schedule - cmpq $1, TASK_B_DONE - jne schedule - cli - mov $DEBUG_PORT, %dx - mov $'O', %al - outb %al, %dx - mov $'K', %al - outb %al, %dx - mov $10, %al - outb %al, %dx -completed: - hlt - jmp completed -failed: - cli - mov $DEBUG_PORT, %dx - mov $'E', %al - outb %al, %dx - jmp completed - -/* RAX handler, ECX vector. Only these two explicitly supported vectors exist. */ -install_gate: - shl $IDT_GATE_SHIFT, %ecx - lea idt(%rip), %rdx - add %rcx, %rdx - mov %ax, 0(%rdx) - movw $CODE_SELECTOR, 2(%rdx) - movb $0, 4(%rdx) - movb $IDT_INTERRUPT_GATE, 5(%rdx) - shr $IDT_OFFSET_HIGH_SHIFT, %rax - mov %ax, 6(%rdx) - shr $IDT_OFFSET_HIGH_SHIFT, %rax - mov %eax, 8(%rdx) - movl $0, 12(%rdx) - ret - -page_fault: - push %rax - push %rcx - push %rsi - push %rdi - incq PAGE_FAULTS - mov %cr2, %rax - mov %rax, FAULT_ADDRESS - mov PAGE_FAULT_ERROR_OFFSET(%rsp), %rax - mov %rax, FAULT_ERROR - mov PAGE_FAULT_RIP_OFFSET(%rsp), %rax - mov %rax, FAULT_RIP - movabs $GUEST_FAULT_PC, %rax - mov %rax, FAULT_GUEST_PC - mov STATE_X3(%rdi), %rax - mov %rax, FAULT_DESTINATION_BEFORE - mov %rdi, %rsi - mov $FAULT_STATE, %edi - mov $(STATE_BYTES / 8), %ecx - rep movsq - mov $TASK_A_DATA, %esi - mov $FAULT_RAM, %edi - mov $TASK_RAM_QWORDS, %ecx - rep movsq - /* Exactly one unmapped read of the dedicated identity page is permitted. - * Retrying the unchanged host RIP demonstrates recovery, not ARM MMU entry. */ - cmpq $RETRY_ADDRESS, FAULT_ADDRESS - jne fault_failed - cmpq $0, FAULT_ERROR - jne fault_failed - movq $RETRY_PAGE_FLAGS, PAGE_DIRECTORY_SECOND - mov $RETRY_ADDRESS, %eax - invlpg (%rax) - movq $0, (%rax) /* initialize the sole fixture-owned word before retry */ - pop %rdi - pop %rsi - pop %rcx - pop %rax - add $X86_STACK_SLOT_BYTES, %rsp - iretq -fault_failed: - jmp failed - -timer_irq: - push %rax - mov IRQ_RIP_OFFSET(%rsp), %rax - incq ALL_IRQS - cmp $loop_native, %rax - jb irq_acknowledge - cmp $loop_native_end, %rax - jae irq_acknowledge - mov %rax, IRQ_RIP - incq TIMER_TICKS -irq_acknowledge: - mov $PIC_EOI, %al - outb %al, $PIC_MASTER_COMMAND - pop %rax - iretq - -.balign 16 -loop_native: -.incbin "LOOP_NATIVE_PATH" -loop_native_end: -.balign 16 -trap_native: -.incbin "TRAP_NATIVE_PATH" -.balign 16 -initial_state_a: -.incbin "STATE_A_PATH" -initial_state_b: -.incbin "STATE_B_PATH" -.balign 16 -idt: -.zero (PIC_TIMER_VECTOR + 1) * IDT_GATE_BYTES -idt_end: -idt_pointer: -.word idt_end - idt - 1 -.quad idt diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml new file mode 100644 index 0000000000..c736f15879 --- /dev/null +++ b/xtask/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "xtask" +version.workspace = true +edition.workspace = true +license.workspace = true +publish = false + +[dependencies] +anyhow.workspace = true +clap.workspace = true +serde_json.workspace = true +sha2.workspace = true +hex.workspace = true +object = { version = "0.37", features = ["read"] } + +[lints] +workspace = true diff --git a/xtask/src/boot.rs b/xtask/src/boot.rs new file mode 100644 index 0000000000..362e1884ed --- /dev/null +++ b/xtask/src/boot.rs @@ -0,0 +1,334 @@ +//! Freestanding Multiboot mount: build, package and run in x86 QEMU. +//! +//! The image is the real shared runtime linked for `x86_64-unknown-none`. The +//! ARM module (firmware or test code) is passed to QEMU unchanged as the +//! Multiboot module; placement and initial state travel on the command line. +use crate::{ + check::{BOOT_MANIFEST, BOOT_TARGET, BOOT_TARGET_DIR}, + tools::{binding, cargo, exec, qemu, root, sha256, stop, wait}, +}; +use anyhow::{Context, Result, bail, ensure}; +use clap::{Args, Subcommand, ValueEnum}; +use object::{ + Endianness, Object, ObjectSymbol, + elf::PT_LOAD, + read::elf::{ElfFile64, ProgramHeader}, +}; +use serde_json::{Value, json}; +use std::{ + collections::BTreeMap, + fs, + path::{Path, PathBuf}, + process::{Command as Process, ExitCode, Stdio}, + time::{Duration, Instant}, +}; + +const IMAGE: &str = "stela-multiboot.bin"; +const MULTIBOOT_MAGIC: u32 = 0x1bad_b002; +/// Page-aligned modules, memory map and address fields. +const MULTIBOOT_FLAGS: u32 = 0x0001_0003; +const MULTIBOOT_HEADER_WORDS: usize = 8; +const MULTIBOOT_SEARCH_BYTES: usize = 8192; +/// The image and its heap must stay inside the loader's identity window. +const IDENTITY_LIMIT: u64 = 0x1000_0000; +/// `isa-debug-exit` reports `(code << 1) | 1`; a timeout reports 124. +const TIMEOUT_EXIT: u8 = 124; +const MAX_TIMEOUT_SECONDS: f64 = 120.0; + +#[derive(Subcommand)] +pub enum Command { + /// Build the runtime image and package it for Multiboot. + Build { + #[arg(long)] + release: bool, + }, + /// Run a packaged image with an ARM module in single-CPU x86 QEMU. + Run(Run), +} + +#[derive(Args)] +pub struct Run { + /// Packaged image; defaults to the latest release build. + #[arg(long)] + image: Option, + /// Original ARM bytes loaded as the Multiboot module. + #[arg(long)] + module: PathBuf, + /// Fresh directory for the serial log and run report. + #[arg(long)] + output: PathBuf, + /// Mount options, for example `--entry 0x100000 --budget 1000`. + #[arg(long, default_value = "", allow_hyphen_values = true)] + append: String, + #[arg(long, default_value_t = 60.0)] + timeout: f64, + #[arg(long, value_enum, default_value_t = Display::None)] + display: Display, + /// Pause at reset with a GDB stub on this loopback port. + #[arg(long)] + gdb: Option, + /// Serve the QEMU monitor over telnet on this loopback port. + #[arg(long)] + monitor: Option, +} + +#[derive(Clone, Copy, ValueEnum)] +enum Display { + None, + /// Show the UART in a host window; adds no guest display device. + Cocoa, +} + +pub fn run(command: Command) -> Result { + match command { + Command::Build { release } => { + let image = build(release)?; + println!("{}", image.display()); + Ok(ExitCode::SUCCESS) + } + Command::Run(arguments) => launch(arguments), + } +} + +fn profile_directory(release: bool) -> PathBuf { + let profile = if release { "release" } else { "debug" }; + root().join(BOOT_TARGET_DIR).join(BOOT_TARGET).join(profile) +} + +fn build(release: bool) -> Result { + let mut command = cargo(); + command.args(["build", "--locked", "--manifest-path", BOOT_MANIFEST]); + command.args(["--target", BOOT_TARGET, "--target-dir", BOOT_TARGET_DIR]); + if release { + command.arg("--release"); + } + exec(&mut command)?; + let directory = profile_directory(release); + package(&directory.join("stela-boot"), &directory) +} + +/// Copy the initialized bytes of the linked ELF into a flat Multiboot image. +/// +/// QEMU's Multiboot loader uses the header's address fields, so the loadable +/// segments must form one identity-mapped file range followed only by BSS. +fn package(elf: &Path, output: &Path) -> Result { + let raw = fs::read(elf).with_context(|| format!("cannot read {}", elf.display()))?; + let file = ElfFile64::::parse(&*raw)?; + let endian = file.endian(); + let symbol = |name: &str| { + file.symbols() + .find(|symbol| symbol.name() == Ok(name)) + .map(|symbol| symbol.address()) + .with_context(|| format!("missing linker symbol {name}")) + }; + let start = symbol("__image_start")?; + let load_end = symbol("__load_end")?; + let image_end = symbol("__image_end")?; + let header_address = symbol("stela_multiboot_header")?; + let entry = symbol("stela_start32")?; + + let loads: Vec<_> = file + .elf_program_headers() + .iter() + .filter(|header| header.p_type(endian) == PT_LOAD) + .map(|header| { + ( + header.p_offset(endian), + header.p_vaddr(endian), + header.p_paddr(endian), + header.p_filesz(endian), + header.p_memsz(endian), + ) + }) + .collect(); + let (first_offset, ..) = *loads.first().context("ELF has no loadable segment")?; + let bias = start - first_offset; + let mut previous = start; + for &(offset, virtual_address, physical, file_bytes, memory_bytes) in &loads { + ensure!( + virtual_address == physical && physical >= previous, + "segments must be identity-mapped and ordered" + ); + ensure!( + file_bytes <= memory_bytes && offset + file_bytes <= raw.len() as u64, + "segment exceeds its file" + ); + if file_bytes != 0 { + ensure!( + physical - offset == bias, + "initialized segments are not one file range" + ); + ensure!( + physical + file_bytes <= load_end, + "initialized segment past __load_end" + ); + } + previous = physical + memory_bytes; + } + ensure!( + start < load_end && load_end <= image_end && image_end < IDENTITY_LIMIT, + "image does not fit the identity window" + ); + ensure!(previous == image_end, "BSS does not end at __image_end"); + + let image = &raw[(start - bias) as usize..(load_end - bias) as usize]; + let header_offset = (header_address - start) as usize; + ensure!( + header_offset.is_multiple_of(4) + && header_offset + MULTIBOOT_HEADER_WORDS * 4 + <= image.len().min(MULTIBOOT_SEARCH_BYTES), + "Multiboot header must be aligned within the first 8 KiB" + ); + let header: Vec = image[header_offset..][..MULTIBOOT_HEADER_WORDS * 4] + .as_chunks::<4>() + .0 + .iter() + .map(|&word| u32::from_le_bytes(word)) + .collect(); + let address_fields: Vec = header[3..].iter().map(|&word| word.into()).collect(); + ensure!( + header[0] == MULTIBOOT_MAGIC + && header[1] == MULTIBOOT_FLAGS + && header[..3] + .iter() + .fold(0u32, |sum, &word| sum.wrapping_add(word)) + == 0 + && address_fields == [header_address, start, load_end, image_end, entry], + "Multiboot header does not match the linked layout" + ); + + let flat = output.join(IMAGE); + fs::write(&flat, image)?; + let report = json!({ + "elf": { "path": elf, "bytes": raw.len(), "sha256": sha256(&raw) }, + "image": { "path": flat, "bytes": image.len(), "sha256": sha256(image) }, + "symbols": BTreeMap::from([ + ("__image_start", start), ("__load_end", load_end), ("__image_end", image_end), + ("stela_multiboot_header", header_address), ("stela_start32", entry), + ]), + "bss_bytes": image_end - load_end, + }); + fs::write(output.join("image.json"), format!("{report:#}\n"))?; + Ok(flat) +} + +fn launch(arguments: Run) -> Result { + ensure!( + arguments.timeout > 0.0 && arguments.timeout <= MAX_TIMEOUT_SECONDS, + "timeout must be in (0, {MAX_TIMEOUT_SECONDS}] seconds" + ); + let image = arguments + .image + .unwrap_or_else(|| profile_directory(true).join(IMAGE)); + let output = arguments.output; + if output.exists() { + bail!("{} already exists", output.display()); + } + fs::create_dir_all(&output)?; + let serial = output.join("serial.txt"); + let qemu = qemu()?; + + let mut command = Process::new(&qemu); + command + .args([ + "-machine", + "q35,smm=off,sata=off,usb=off,smbus=off,hpet=off,i8042=off,vmport=off", + ]) + .args([ + "-accel", + "tcg,thread=single", + "-cpu", + "qemu64", + "-smp", + "1", + "-m", + "1G", + ]) + .args([ + "-nodefaults", + "-no-reboot", + "-device", + "isa-debug-exit,iobase=0xf4,iosize=4", + ]) + .arg("-kernel") + .arg(&image) + .arg("-initrd") + .arg(&arguments.module) + .args(["-append", &arguments.append]); + match arguments.display { + Display::None => command + .args(["-display", "none"]) + .arg("-serial") + .arg(format!("file:{}", serial.display())), + Display::Cocoa => command + .args(["-display", "cocoa", "-chardev"]) + .arg(format!( + "vc,id=uart,cols=132,rows=50,logfile={}", + serial.display() + )) + .args(["-serial", "chardev:uart"]), + }; + match arguments.monitor { + Some(port) => command + .arg("-monitor") + .arg(format!("telnet:127.0.0.1:{port},server=on,wait=off")), + None => command.args(["-monitor", "none"]), + }; + if let Some(port) = arguments.gdb { + command + .arg("-gdb") + .arg(format!("tcp:127.0.0.1:{port}")) + .arg("-S"); + eprintln!( + "paused: gdb {} -ex 'target remote 127.0.0.1:{port}'", + image.with_file_name("stela-boot").display() + ); + } + let command_line: Vec = std::iter::once(command.get_program()) + .chain(command.get_args()) + .map(|argument| argument.to_string_lossy().into_owned()) + .collect(); + + let started = Instant::now(); + let mut child = command + .stdout(fs::File::create(output.join("stdout.txt"))?) + .stderr(fs::File::create(output.join("stderr.txt"))?) + .stdin(Stdio::null()) + .spawn()?; + // A paused debugging session has no deadline. + let limit = match arguments.gdb { + Some(_) => Duration::MAX, + None => Duration::from_secs_f64(arguments.timeout), + }; + let status = match wait(&mut child, limit) { + Ok(status) => status, + Err(error) => { + stop(&mut child); + return Err(error); + } + }; + let code = match status { + Some(status) => status.code().map_or(TIMEOUT_EXIT, |code| code as u8), + None => TIMEOUT_EXIT, + }; + + let outputs: Vec = ["serial.txt", "stdout.txt", "stderr.txt"] + .into_iter() + .map(|name| output.join(name)) + .filter(|path| path.exists()) + .map(|path| binding(&path)) + .collect::>()?; + let report = json!({ + "command": command_line, + "qemu": binding(&qemu)?, + "image": binding(&image)?, + "module": binding(&arguments.module)?, + "returncode": code, + "timed_out": status.is_none(), + "wall_seconds": started.elapsed().as_secs_f64(), + "outputs": outputs, + }); + fs::write(output.join("run.json"), format!("{report:#}\n"))?; + println!("{report:#}"); + Ok(ExitCode::from(code)) +} diff --git a/xtask/src/check.rs b/xtask/src/check.rs new file mode 100644 index 0000000000..74d0146462 --- /dev/null +++ b/xtask/src/check.rs @@ -0,0 +1,48 @@ +//! The shared local and CI gate. +use crate::tools::{cargo, exec}; +use anyhow::Result; + +pub const BOOT_MANIFEST: &str = "crates/stela-boot/Cargo.toml"; +pub const BOOT_TARGET: &str = "x86_64-unknown-none"; +pub const BOOT_TARGET_DIR: &str = "target/boot"; + +pub fn run(fix: bool) -> Result<()> { + let boot = ["--manifest-path", BOOT_MANIFEST]; + if fix { + exec(cargo().args(["fmt", "--all"]))?; + exec(cargo().arg("fmt").args(boot).arg("--all"))?; + } + exec(cargo().args(["fmt", "--all", "--", "--check"]))?; + exec( + cargo() + .arg("fmt") + .args(boot) + .args(["--all", "--", "--check"]), + )?; + exec(cargo().args([ + "clippy", + "--workspace", + "--all-targets", + "--locked", + "--", + "-D", + "warnings", + ]))?; + // RUSTFLAGS also denies warnings in the runtime crates the mount builds + // without std; registry dependencies stay lint-capped. + exec( + cargo() + .env("RUSTFLAGS", "-D warnings") + .arg("clippy") + .args(boot) + .args([ + "--locked", + "--target", + BOOT_TARGET, + "--target-dir", + BOOT_TARGET_DIR, + ]) + .args(["--", "-D", "warnings"]), + )?; + exec(cargo().args(["test", "--workspace", "--locked"])) +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs new file mode 100644 index 0000000000..87b0400ab2 --- /dev/null +++ b/xtask/src/main.rs @@ -0,0 +1,38 @@ +//! Repository development tasks: `cargo xtask `. +use clap::{Parser, Subcommand}; +use std::process::ExitCode; + +mod boot; +mod check; +mod tools; + +#[derive(Parser)] +#[command(about = "Stela development tasks")] +struct Cli { + #[command(subcommand)] + task: Task, +} + +#[derive(Subcommand)] +enum Task { + /// Check formatting, run strict hosted and freestanding Clippy, then test. + Check { + /// Format sources before checking. + #[arg(long)] + fix: bool, + }, + /// Build, run and debug the freestanding Multiboot mount in x86 QEMU. + #[command(subcommand)] + Boot(boot::Command), +} + +fn main() -> ExitCode { + let result = match Cli::parse().task { + Task::Check { fix } => check::run(fix).map(|()| ExitCode::SUCCESS), + Task::Boot(command) => boot::run(command), + }; + result.unwrap_or_else(|error| { + eprintln!("error: {error:#}"); + ExitCode::FAILURE + }) +} diff --git a/xtask/src/tools.rs b/xtask/src/tools.rs new file mode 100644 index 0000000000..ab74884558 --- /dev/null +++ b/xtask/src/tools.rs @@ -0,0 +1,83 @@ +//! Process, path and hashing helpers shared by tasks. +use anyhow::{Context, Result, bail}; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use std::{ + env, + ffi::OsStr, + fs, + path::{Path, PathBuf}, + process::{Child, Command, ExitStatus}, + thread, + time::{Duration, Instant}, +}; + +pub fn root() -> &'static Path { + Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .expect("xtask lives in the repository root") +} + +/// The cargo that launched this task, so nested builds share its toolchain. +pub fn cargo() -> Command { + let mut command = Command::new(env::var_os("CARGO").unwrap_or_else(|| "cargo".into())); + command.current_dir(root()); + command +} + +pub fn exec(command: &mut Command) -> Result<()> { + let status = command + .status() + .with_context(|| format!("cannot start {:?}", command.get_program()))?; + if !status.success() { + bail!("{command:?} failed with {status}"); + } + Ok(()) +} + +pub fn which(name: impl AsRef) -> Option { + let name = name.as_ref(); + env::split_paths(&env::var_os("PATH")?) + .map(|directory| directory.join(name)) + .find(|path| path.is_file()) +} + +pub fn qemu() -> Result { + let local = root().join(".tools/qemu/bin/qemu-system-x86_64"); + if local.exists() { + return Ok(local); + } + which("qemu-system-x86_64").context("install QEMU or bootstrap .tools/qemu") +} + +pub fn sha256(data: &[u8]) -> String { + hex::encode(Sha256::digest(data)) +} + +/// Path, size and digest of one input or output file. +pub fn binding(path: &Path) -> Result { + let data = fs::read(path).with_context(|| format!("cannot read {}", path.display()))?; + Ok(json!({ "path": path, "bytes": data.len(), "sha256": sha256(&data) })) +} + +/// Wait for `child` until `timeout`, then terminate it. Returns `None` on timeout. +pub fn wait(child: &mut Child, timeout: Duration) -> Result> { + let Some(deadline) = Instant::now().checked_add(timeout) else { + return Ok(Some(child.wait()?)); + }; + while Instant::now() < deadline { + if let Some(status) = child.try_wait()? { + return Ok(Some(status)); + } + thread::sleep(Duration::from_millis(20)); + } + stop(child); + Ok(None) +} + +pub fn stop(child: &mut Child) { + if matches!(child.try_wait(), Ok(None)) { + let _ = child.kill(); + } + let _ = child.wait(); +}