mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 13:30:43 +00:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
60bfaff97e | ||
|
|
b29a504506 | ||
|
|
b2a36e9c16 |
No files matched your search
@@ -13,6 +13,9 @@ remains unsupported.
|
||||
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
|
||||
|
||||
### Added
|
||||
- Added authoritative read-only x86-64 CPU inventory CLI (`python3 -m qa cpu-inventory`) over `crates/loader/x86/instructions.toml` via `generate_x86.load`, with opcode-map/prefix/operand summaries, native vs shared-semantic operation partitions from `dbt.rs`, fixture mnemonic evidence and a separate unsupported catalog. Does not count candidates as implemented. Covered by `tests/qa/test_cpu_inventory.py`.
|
||||
- Added typed runtime inventory CLI (`python3 -m qa runtime-inventory`) over `crates/loader/runtime/services.txt`, reporting implemented/partial/stub services separately from API-set aliases and leaving independently-verified empty unless recorded. Covered by `tests/qa/test_runtime_inventory.py`.
|
||||
|
||||
- Added a typed runtime service registry (`crates/loader/runtime/services.txt`) and `xenora-runtime-gen`, which generates Win64 argument and result adapters, static metadata and a coverage report. It covers 20 services: 16 existing kernel32 services moved to typed handlers, and `sqrt`, `sqrtf`, `fabs` and `fabsf` with arguments and results in XMM registers. Conflicting keys, unlisted API sets, unsupported types and behaviour without an existing test are rejected. See `docs/runtime/registry.md`.
|
||||
- Added SSE and SSE2 floating point in scalar and packed, binary32 and binary64 forms: add, subtract, multiply, divide, minimum, maximum, square root, compares, COMI/UCOMI and the conversions between formats and integers (parts of #127 and #128; awaiting independent review). `crates/loader/src/softfloat.rs` computes every result exactly and rounds once, with MXCSR rounding modes, sticky flags, denormals-are-zero, flush-to-zero, tininess after rounding and x86 NaN rules; host floating point is not used because ARM64 differs. An unmasked exception exits with `SimdException` and leaves everything but MXCSR unchanged. RCP, RSQRT and MMX conversions are rejected, and no floating-point form is translated to NEON yet.
|
||||
- Added 6,824 floating-point vectors computed with exact fractions by `tests/x86/float_reference.py`, run through both engines from registers and memory and through the packed forms, and more than two million round-to-nearest results compared with the host's IEEE 754 hardware.
|
||||
|
||||
@@ -306,26 +306,6 @@ impl Arm64Assembler {
|
||||
);
|
||||
}
|
||||
|
||||
/// RBIT Xd, Xn: reverse the bit order of the source.
|
||||
pub fn rbit_64(&mut self, xd: u8, xn: u8) {
|
||||
self.emit(0xdac0_0000 | ((u32::from(xn) & 0x1f) << 5) | (u32::from(xd) & 0x1f));
|
||||
}
|
||||
|
||||
/// CLZ Xd, Xn: count the leading zero bits of the source.
|
||||
pub fn clz_64(&mut self, xd: u8, xn: u8) {
|
||||
self.emit(0xdac0_1000 | ((u32::from(xn) & 0x1f) << 5) | (u32::from(xd) & 0x1f));
|
||||
}
|
||||
|
||||
/// LSLV Xd, Xn, Xm: shift the source left by the amount in Xm.
|
||||
pub fn lslv_64(&mut self, xd: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
0x9ac2_2000
|
||||
| ((u32::from(xm) & 0x1f) << 16)
|
||||
| ((u32::from(xn) & 0x1f) << 5)
|
||||
| (u32::from(xd) & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// LDR Qt, [Xn, #offset] (offset a multiple of 16)
|
||||
pub fn ldr_q_uoff(&mut self, qt: u8, xn: u8, offset: u32) {
|
||||
self.emit(
|
||||
|
||||
@@ -330,18 +330,10 @@ pub fn is_translatable(insn: &Insn) -> bool {
|
||||
/// [`DbtMetrics::interpreter_fallbacks`].
|
||||
pub fn is_native(insn: &Insn) -> bool {
|
||||
let wide = matches!(insn.size, 4 | 8);
|
||||
// The bit scans work on any register or memory source, and the bit test
|
||||
// needs the index in a register.
|
||||
let scanned = matches!(insn.size, 2 | 4 | 8);
|
||||
match insn.op {
|
||||
Op::Add | Op::Sub | Op::Cmp | Op::And | Op::Or | Op::Xor | Op::Test => wide,
|
||||
Op::Inc | Op::Dec | Op::Neg | Op::Not => wide,
|
||||
Op::Cmov => wide,
|
||||
Op::Bsf | Op::Bsr => scanned,
|
||||
// Only the `0F A3` form has the bit index in a register. The `0F BA`
|
||||
// group form takes an immediate index and may write memory, so it
|
||||
// stays on the shared semantics.
|
||||
Op::Bt => scanned && insn.encoding == Encoding::RmReg,
|
||||
Op::Pop => insn.encoding == Encoding::OpReg,
|
||||
Op::Mov
|
||||
| Op::Movzx
|
||||
@@ -508,18 +500,6 @@ impl Emitter<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Zero-extend the low `size` bytes of `xd` to the full 64-bit register.
|
||||
///
|
||||
/// An operation narrower than the register reads only the low bytes of its
|
||||
/// source, so the bits above them must not take part in a bit scan.
|
||||
fn zero_extend(&mut self, xd: u8, size: u8) {
|
||||
match size {
|
||||
8 => {}
|
||||
4 => self.asm.mov_reg_32(xd, xd),
|
||||
_ => self.asm.uxth_32(xd, xd),
|
||||
}
|
||||
}
|
||||
|
||||
/// Effective address into X1, clobbering X9.
|
||||
fn effective_address(&mut self, operand: &MemOperand, with_segment: bool) {
|
||||
let asm = &mut *self.asm;
|
||||
@@ -1052,71 +1032,6 @@ impl Emitter<'_> {
|
||||
self.load_condition(insn.condition);
|
||||
self.store_rm(insn, X12, completed);
|
||||
}
|
||||
Op::Bsf | Op::Bsr => {
|
||||
// BSF and BSR write the index of the lowest or the highest set
|
||||
// bit of the source into the destination and set the zero flag
|
||||
// when the source is zero (Intel SDM Volume 2B, "BSF" and
|
||||
// "BSR"). A zero source leaves the destination undefined, so
|
||||
// the destination keeps its value, which is the same rule the
|
||||
// interpreter and the reference apply.
|
||||
self.load_rm(X9, insn, completed);
|
||||
self.zero_extend(X9, insn.size);
|
||||
match insn.op {
|
||||
// The lowest set bit is the highest set bit of the
|
||||
// reversed value, so its index is the leading zero count
|
||||
// of the reversed value.
|
||||
Op::Bsf => {
|
||||
self.asm.rbit_64(X10, X9);
|
||||
self.asm.clz_64(X10, X10);
|
||||
}
|
||||
// The highest set bit sits at 63 minus the leading zero
|
||||
// count.
|
||||
_ => {
|
||||
self.asm.clz_64(X10, X9);
|
||||
self.asm.movz_64(X13, 63, 0);
|
||||
self.asm.sub_reg_64(X10, X13, X10);
|
||||
}
|
||||
}
|
||||
self.load_reg(X11, insn.reg);
|
||||
self.asm.tst_reg_64(X9, X9);
|
||||
// CSEL takes the first operand when the condition holds, so
|
||||
// the index is the value that replaces the destination.
|
||||
self.asm.csel_64(X11, X10, X11, Condition::Ne);
|
||||
match insn.size {
|
||||
// A 16-bit destination keeps the bits above it, so the
|
||||
// register is merged rather than replaced.
|
||||
2 => self.store_reg(insn.reg, insn.size, X11),
|
||||
// A 32-bit or 64-bit destination is written in full. The
|
||||
// index has no bits above the operand width, so this
|
||||
// matches the interpreter's 32-bit write, and a zero
|
||||
// source keeps the whole register unchanged.
|
||||
_ => self.asm.str_uoff_64(X11, X19, reg_offset(insn.reg.index)),
|
||||
}
|
||||
if flags {
|
||||
// The zero flag is set when the source is zero. The other
|
||||
// flags are undefined and keep their value.
|
||||
self.asm.cset_32(X12, Condition::Eq);
|
||||
self.asm.strb_uoff(X12, X19, ZF);
|
||||
}
|
||||
}
|
||||
Op::Bt => {
|
||||
// BT sets the carry flag from the tested bit and leaves the
|
||||
// other flags undefined (Intel SDM Volume 2B, "BT"). The bit
|
||||
// index comes from the register operand and is masked to the
|
||||
// operand width.
|
||||
self.load_rm(X9, insn, completed);
|
||||
self.zero_extend(X9, insn.size);
|
||||
self.load_reg(X10, insn.reg);
|
||||
self.asm.load_imm_64(X13, u64::from(8 * insn.size - 1));
|
||||
self.asm.and_reg_64(X10, X10, X13);
|
||||
self.asm.load_imm_64(X11, 1);
|
||||
self.asm.lslv_64(X11, X11, X10);
|
||||
self.asm.tst_reg_64(X9, X11);
|
||||
if flags {
|
||||
self.asm.cset_32(X12, Condition::Ne);
|
||||
self.asm.strb_uoff(X12, X19, CF);
|
||||
}
|
||||
}
|
||||
Op::Cmov => {
|
||||
self.load_rm(X10, insn, completed);
|
||||
self.load_reg(X9, insn.reg);
|
||||
|
||||
@@ -1298,107 +1298,6 @@ fn division_accepts_exactly_the_representable_quotients() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The bit scans and the bit test keep the destination and the flags where
|
||||
/// the architecture puts them.
|
||||
///
|
||||
/// The expectations come from the Intel SDM Volume 2B, "BSF", "BSR" and "BT":
|
||||
/// BSF writes the index of the lowest set bit of the source and BSR the index
|
||||
/// of the highest set bit, and both set the zero flag when the source is
|
||||
/// zero, in which case the destination is undefined and keeps its value. BT
|
||||
/// sets the carry flag from the tested bit, leaves the other flags alone and
|
||||
/// masks the bit index to the operand width.
|
||||
///
|
||||
/// The encodings are `bsf rbx, r9` (49 0F BC D9), `bsr rbx, r9` (49 0F BD
|
||||
/// D9), `bt rbx, r9` (4C 0F A3 CB), `bsf ebx, r9d` (41 0F BC D9),
|
||||
/// `bsr ebx, r9d` (41 0F BD D9), `bt ebx, r9d` (44 0F A3 CB), `bsf bx, r9w`
|
||||
/// (66 41 0F BC D9) and `bt bx, r9w` (66 44 0F A3 CB), as produced by LLVM
|
||||
/// 23.1.6 `llvm-mc -show-encoding`.
|
||||
#[test]
|
||||
fn bit_scans_and_bit_tests_follow_the_architecture() {
|
||||
const BSF64: &[u8] = &[0x49, 0x0F, 0xBC, 0xD9]; // bsf rbx, r9
|
||||
const BSR64: &[u8] = &[0x49, 0x0F, 0xBD, 0xD9]; // bsr rbx, r9
|
||||
const BT64: &[u8] = &[0x4C, 0x0F, 0xA3, 0xCB]; // bt rbx, r9
|
||||
const BSF32: &[u8] = &[0x41, 0x0F, 0xBC, 0xD9]; // bsf ebx, r9d
|
||||
const BSR32: &[u8] = &[0x41, 0x0F, 0xBD, 0xD9]; // bsr ebx, r9d
|
||||
const BT32: &[u8] = &[0x44, 0x0F, 0xA3, 0xCB]; // bt ebx, r9d
|
||||
const BSF16: &[u8] = &[0x66, 0x41, 0x0F, 0xBC, 0xD9]; // bsf bx, r9w
|
||||
const BT16: &[u8] = &[0x66, 0x44, 0x0F, 0xA3, 0xCB]; // bt bx, r9w
|
||||
|
||||
/// A machine with R9 and RBX set and every other register zero.
|
||||
fn machine(source: u64, destination: u64) -> Machine {
|
||||
let mut gpr = [0; 16];
|
||||
gpr[3] = destination;
|
||||
gpr[9] = source;
|
||||
Machine {
|
||||
gpr,
|
||||
flags: Flags::default(),
|
||||
operand: 0,
|
||||
pushed: 0,
|
||||
top: STACK_TOP,
|
||||
}
|
||||
}
|
||||
|
||||
// The lowest set bit of the source is the index BSF writes.
|
||||
let (state, _, _) = run_both(&machine(0x0000_0000_0000_0028, 0xFFFF), BSF64, 1);
|
||||
assert_eq!(state.gpr[3], 3);
|
||||
assert!(!state.flags.zf);
|
||||
|
||||
// The highest set bit of the source is the index BSR writes.
|
||||
let (state, _, _) = run_both(&machine(0x8000_0000_0000_0028, 0xFFFF), BSR64, 1);
|
||||
assert_eq!(state.gpr[3], 63);
|
||||
assert!(!state.flags.zf);
|
||||
|
||||
// A zero source sets the zero flag and leaves the destination alone.
|
||||
let (state, _, _) = run_both(&machine(0, 0xFFFF_FFFF_FFFF_FFFF), BSF64, 1);
|
||||
assert_eq!(state.gpr[3], 0xFFFF_FFFF_FFFF_FFFF);
|
||||
assert!(state.flags.zf);
|
||||
let (state, _, _) = run_both(&machine(0, 0xFFFF_FFFF_FFFF_FFFF), BSR64, 1);
|
||||
assert_eq!(state.gpr[3], 0xFFFF_FFFF_FFFF_FFFF);
|
||||
assert!(state.flags.zf);
|
||||
|
||||
// A 32-bit destination holds a 32-bit index and clears the half above it.
|
||||
let (state, _, _) = run_both(&machine(0x0000_0028, 0xFFFF_FFFF_FFFF_FFFF), BSF32, 1);
|
||||
assert_eq!(state.gpr[3], 3);
|
||||
let (state, _, _) = run_both(&machine(0x8000_0000, 0xFFFF_FFFF_FFFF_FFFF), BSR32, 1);
|
||||
assert_eq!(state.gpr[3], 31);
|
||||
|
||||
// A 16-bit destination keeps the bits above it.
|
||||
let (state, _, _) = run_both(&machine(0x0100, 0xFFFF_FFFF_FFFF_FFFF), BSF16, 1);
|
||||
assert_eq!(state.gpr[3], 0xFFFF_FFFF_FFFF_0008);
|
||||
|
||||
// BT reports the tested bit in the carry flag and leaves the bit string
|
||||
// alone.
|
||||
let (state, _, _) = run_both(&machine(1, 0b1010), BT64, 1);
|
||||
assert!(state.flags.cf);
|
||||
assert_eq!(state.gpr[3], 0b1010);
|
||||
let (state, _, _) = run_both(&machine(0, 0b1010), BT64, 1);
|
||||
assert!(!state.flags.cf);
|
||||
assert_eq!(state.gpr[3], 0b1010);
|
||||
|
||||
// The bit index is masked to the operand width, so 64 selects bit 0 of a
|
||||
// 64-bit bit string and 32 selects bit 0 of a 32-bit one.
|
||||
let (state, _, _) = run_both(&machine(64, 0b1), BT64, 1);
|
||||
assert!(state.flags.cf);
|
||||
let (state, _, _) = run_both(&machine(32, 0b1), BT32, 1);
|
||||
assert!(state.flags.cf);
|
||||
let (state, _, _) = run_both(&machine(16, 0b1), BT16, 1);
|
||||
assert!(state.flags.cf);
|
||||
|
||||
// The bit scans and the register form of the bit test are lowered to
|
||||
// ARM64 instead of falling back to the shared semantics.
|
||||
for code in [BSF64, BSR64, BT64, BSF32, BSR32, BT32, BSF16, BT16] {
|
||||
let insn = decode(ENTRY, |address| {
|
||||
code.get((address - ENTRY) as usize).copied().ok_or(())
|
||||
})
|
||||
.expect("decode");
|
||||
assert!(is_native(&insn), "{code:02X?} is not native");
|
||||
let mut engine = DbtEngine::new(64 * 1024).unwrap();
|
||||
let (mut cpu, mut memory) = load(&machine(0x28, 0), code);
|
||||
engine.run(&mut cpu, &mut memory, 1);
|
||||
assert_eq!(engine.metrics.interpreter_fallbacks, 0, "{code:02X?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pop_rsp_and_push_rsp_use_the_architectural_stack_pointer() {
|
||||
let machine = Random(17).machine();
|
||||
|
||||
@@ -38,6 +38,7 @@ PYTHONPATH=scripts python3 -m qa rdna2 discrepancies
|
||||
PYTHONPATH=scripts python3 -m qa rdna2 diff --before before.json --after after.json --compact
|
||||
PYTHONPATH=scripts python3 -m qa verify quick
|
||||
PYTHONPATH=scripts python3 -m qa cpu-coverage --blockers
|
||||
PYTHONPATH=scripts python3 -m qa cpu-inventory --compact
|
||||
PYTHONPATH=scripts python3 -m qa bench-compare --baseline b.json --current c.json
|
||||
PYTHONPATH=scripts python3 -m release readiness --revision HEAD --live --binary path --app path.app
|
||||
```
|
||||
@@ -46,3 +47,12 @@ RDNA2 planning is read-only over the AMD snapshot, semantic registry, decoder ta
|
||||
`docs/status.toml`. Candidates and manifests are never counted as implemented forms.
|
||||
Family claims exclude those families; path-only claims block candidates whose default
|
||||
permitted files overlap. Reconcile reports mismatches without adjusting planner counts.
|
||||
|
||||
## Phase III — compatibility intelligence
|
||||
|
||||
Checkpoint ledger: [phase3-compat-ledger.md](phase3-compat-ledger.md).
|
||||
|
||||
`cpu-inventory` consumes the x86 instruction registry (not heuristic opcode scans).
|
||||
Declared forms are decodable only; native vs shared-semantic partitions come from
|
||||
read-only `dbt.rs` analysis. Unsupported intentional rejections stay in a separate catalog.
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
# Phase III compatibility-intelligence checkpoint ledger
|
||||
|
||||
Branch: `feat/infra-phase3-compat`. Issue #277.
|
||||
Approved paths only. No push without separate authorization.
|
||||
|
||||
| Milestone | Status | Commit | Tests | Next |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| M1 CPU inventory | done | `b2a36e9` | test_cpu_inventory 5 OK; cpu-inventory compact | M2 runtime inventory |
|
||||
| M2 Runtime intelligence | done | `da92995` | test_runtime_inventory 2 OK; runtime-inventory compact | M3 compat gaps |
|
||||
| M3 Compat gaps | pending | — | — | — |
|
||||
| M4 Performance intel | pending | — | — | — |
|
||||
| M5 Regression detection | pending | — | — | — |
|
||||
| M6 Task planning | pending | — | — | — |
|
||||
| M7 Unified diagnostics | pending | — | — | — |
|
||||
| M8 Verify profiles | pending | — | — | — |
|
||||
|
||||
## Notes
|
||||
|
||||
- Do not inflate coverage. Declared ≠ implemented.
|
||||
- Prefer focused `tests/qa` unit tests between milestones.
|
||||
+66
-1
@@ -53,6 +53,17 @@ from .rdna2_plan import (
|
||||
write_json,
|
||||
)
|
||||
from .coverage_history import historical_report, snapshot_inventory, write_snapshot
|
||||
from .cpu_inventory import (
|
||||
build_inventory as build_cpu_inventory,
|
||||
compact_inventory as compact_cpu_inventory,
|
||||
dumps_inventory as dumps_cpu_inventory,
|
||||
)
|
||||
from .runtime_inventory import (
|
||||
build_runtime_inventory,
|
||||
compact_runtime,
|
||||
dumps_runtime,
|
||||
)
|
||||
from .compat_gaps import analyze_gaps, compact_gaps, dumps_gaps, load_dependency_report
|
||||
from .stale_branch import classify_sync, format_sync_reports
|
||||
from .verify import dumps_evidence, evidence_is_stale, load_evidence, run_profile
|
||||
|
||||
@@ -117,10 +128,24 @@ def main(argv: list[str] | None = None) -> int:
|
||||
r.add_argument("--before", default="", help="JSON inventory for diff")
|
||||
r.add_argument("--after", default="", help="JSON inventory for diff")
|
||||
|
||||
cpu = sub.add_parser("cpu-coverage", help="read-only CPU/runtime coverage scan")
|
||||
cpu = sub.add_parser("cpu-coverage", help="legacy heuristic CPU/runtime coverage scan")
|
||||
cpu.add_argument("--blockers", action="store_true")
|
||||
cpu.add_argument("--compare", default="", help="previous JSON report path")
|
||||
|
||||
cinv = sub.add_parser("cpu-inventory", help="authoritative x86 inventory from instructions.toml")
|
||||
cinv.add_argument("--compact", action="store_true")
|
||||
cinv.add_argument("--forms", action="store_true", help="include expanded form records in JSON")
|
||||
cinv.add_argument("--out", default="", help="write JSON (prefer artifacts/)")
|
||||
|
||||
rinv = sub.add_parser("runtime-inventory", help="typed runtime services from services.txt")
|
||||
rinv.add_argument("--compact", action="store_true")
|
||||
rinv.add_argument("--out", default="")
|
||||
|
||||
gaps = sub.add_parser("compat-gaps", help="read-only dependency gap analysis (no binary exec)")
|
||||
gaps.add_argument("--deps", required=True, help="JSON dependency report path")
|
||||
gaps.add_argument("--compact", action="store_true")
|
||||
gaps.add_argument("--out", default="")
|
||||
|
||||
ver = sub.add_parser("verify", help="run a verification profile")
|
||||
ver.add_argument("profile", choices=("quick", "cpu", "gpu", "app", "full", "release"))
|
||||
ver.add_argument("--revision", default="")
|
||||
@@ -320,6 +345,46 @@ def main(argv: list[str] | None = None) -> int:
|
||||
print(dumps_cpu(report), end="")
|
||||
return 0
|
||||
|
||||
if args.command == "cpu-inventory":
|
||||
inv = build_cpu_inventory(root)
|
||||
payload = inv.to_dict()
|
||||
if not args.forms:
|
||||
payload.pop("forms", None)
|
||||
if args.out:
|
||||
Path(args.out).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(args.out).write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
||||
if args.compact or args.out:
|
||||
print(compact_cpu_inventory(inv), end="")
|
||||
else:
|
||||
print(dumps_cpu_inventory(inv, include_forms=args.forms), end="")
|
||||
return 0
|
||||
|
||||
if args.command == "runtime-inventory":
|
||||
inv = build_runtime_inventory(root)
|
||||
payload = inv.to_dict()
|
||||
if args.out:
|
||||
Path(args.out).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(args.out).write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
||||
if args.compact or args.out:
|
||||
print(compact_runtime(inv), end="")
|
||||
else:
|
||||
print(dumps_runtime(inv), end="")
|
||||
return 0
|
||||
|
||||
if args.command == "compat-gaps":
|
||||
deps = load_dependency_report(Path(args.deps))
|
||||
rt = build_runtime_inventory(root)
|
||||
report = analyze_gaps(deps, implemented=rt.implemented, partial=rt.partial)
|
||||
payload = report.to_dict()
|
||||
if args.out:
|
||||
Path(args.out).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(args.out).write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
||||
if args.compact or args.out:
|
||||
print(compact_gaps(report), end="")
|
||||
else:
|
||||
print(dumps_gaps(report), end="")
|
||||
return 0
|
||||
|
||||
if args.command == "verify":
|
||||
if args.check_stale:
|
||||
evidence = load_evidence(Path(args.check_stale).read_text(encoding="utf-8"))
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Compatibility gap analysis over read-only dependency reports.
|
||||
|
||||
Consumes JSON describing imports required by authorized workloads. Never
|
||||
executes input binaries. Groups missing symbols by reusable subsystem.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from collections import defaultdict
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterable
|
||||
|
||||
|
||||
# Heuristic subsystem buckets for missing Win64/CRT symbols (planning only).
|
||||
SUBSYSTEM_RULES: tuple[tuple[str, tuple[str, ...]], ...] = (
|
||||
("memory", ("VirtualAlloc", "VirtualFree", "HeapAlloc", "HeapFree", "LocalAlloc", "GlobalAlloc")),
|
||||
("threading", ("CreateThread", "OpenThread", "WaitFor", "Sleep", "Tls", "CriticalSection")),
|
||||
("process", ("GetCurrentProcess", "GetProcess", "TerminateProcess", "ExitProcess", "CreateProcess")),
|
||||
("error", ("GetLastError", "SetLastError", "FormatMessage")),
|
||||
("time", ("GetSystemTime", "QueryPerformance", "GetTickCount", "Sleep")),
|
||||
("crt-math", ("sqrt", "fabs", "sin", "cos", "pow", "exp", "log", "floor", "ceil")),
|
||||
("crt-string", ("strlen", "strcmp", "strcpy", "memcpy", "memmove", "memset", "sprintf", "snprintf")),
|
||||
("file-io", ("CreateFile", "ReadFile", "WriteFile", "CloseHandle", "GetFileSize")),
|
||||
("sync", ("WaitForSingleObject", "WaitForMultipleObjects", "CreateEvent", "CreateMutex", "ReleaseMutex")),
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class GapItem:
|
||||
module: str
|
||||
symbol: str
|
||||
subsystem: str
|
||||
status: str # missing | partial | present
|
||||
note: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class GapReport:
|
||||
workload: str
|
||||
total_imports: int
|
||||
missing: list[dict[str, Any]] = field(default_factory=list)
|
||||
partial: list[dict[str, Any]] = field(default_factory=list)
|
||||
present: list[dict[str, Any]] = field(default_factory=list)
|
||||
by_subsystem: dict[str, list[str]] = field(default_factory=dict)
|
||||
shared_primitives: list[str] = field(default_factory=list)
|
||||
notes: list[str] = field(default_factory=list)
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
def classify_subsystem(symbol: str) -> str:
|
||||
for name, needles in SUBSYSTEM_RULES:
|
||||
for needle in needles:
|
||||
if needle.lower() in symbol.lower():
|
||||
return name
|
||||
return "other"
|
||||
|
||||
|
||||
def _normalize_imports(payload: dict[str, Any]) -> list[tuple[str, str]]:
|
||||
"""Accept {workload, imports:[{module,symbol}| "mod!sym"]} or flat list."""
|
||||
items = payload.get("imports", payload if isinstance(payload, list) else [])
|
||||
out: list[tuple[str, str]] = []
|
||||
for item in items:
|
||||
if isinstance(item, str):
|
||||
if "!" in item:
|
||||
mod, sym = item.split("!", 1)
|
||||
else:
|
||||
mod, sym = "unknown", item
|
||||
out.append((mod, sym))
|
||||
elif isinstance(item, dict):
|
||||
mod = str(item.get("module") or item.get("dll") or "unknown")
|
||||
sym = str(item.get("symbol") or item.get("name") or "")
|
||||
if sym:
|
||||
out.append((mod, sym))
|
||||
return out
|
||||
|
||||
|
||||
def analyze_gaps(
|
||||
dependency_report: dict[str, Any],
|
||||
*,
|
||||
implemented: Iterable[str],
|
||||
partial: Iterable[str],
|
||||
) -> GapReport:
|
||||
"""Compare required imports to runtime inventory keys (`dll!symbol`)."""
|
||||
impl = {k.lower() for k in implemented}
|
||||
part = {k.lower() for k in partial}
|
||||
workload = str(dependency_report.get("workload", "unspecified"))
|
||||
imports = _normalize_imports(dependency_report)
|
||||
missing: list[GapItem] = []
|
||||
partial_hits: list[GapItem] = []
|
||||
present: list[GapItem] = []
|
||||
for module, symbol in imports:
|
||||
key = f"{module}!{symbol}".lower()
|
||||
# Also try basename match on symbol alone against inventory keys.
|
||||
symbol_keys = {k for k in impl | part if k.endswith("!" + symbol.lower())}
|
||||
if key in impl or any(k in impl for k in symbol_keys):
|
||||
present.append(GapItem(module, symbol, classify_subsystem(symbol), "present"))
|
||||
elif key in part or any(k in part for k in symbol_keys):
|
||||
partial_hits.append(GapItem(module, symbol, classify_subsystem(symbol), "partial",
|
||||
"registry status is partial"))
|
||||
else:
|
||||
missing.append(GapItem(module, symbol, classify_subsystem(symbol), "missing"))
|
||||
|
||||
by_sub: dict[str, list[str]] = defaultdict(list)
|
||||
for item in missing + partial_hits:
|
||||
by_sub[item.subsystem].append(f"{item.module}!{item.symbol}")
|
||||
# Shared primitives: subsystems with more than one missing/partial entry.
|
||||
shared = sorted(sub for sub, items in by_sub.items() if len(items) > 1 and sub != "other")
|
||||
return GapReport(
|
||||
workload=workload,
|
||||
total_imports=len(imports),
|
||||
missing=[asdict(i) for i in missing],
|
||||
partial=[asdict(i) for i in partial_hits],
|
||||
present=[asdict(i) for i in present],
|
||||
by_subsystem={k: sorted(v) for k, v in sorted(by_sub.items())},
|
||||
shared_primitives=shared,
|
||||
notes=[
|
||||
"Read-only analysis of a dependency JSON report; binaries are not executed.",
|
||||
"Subsystem grouping is advisory for prioritising shared primitives.",
|
||||
"Does not claim Xbox or commercial workload compatibility.",
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def load_dependency_report(path: Path) -> dict[str, Any]:
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def compact_gaps(report: GapReport) -> str:
|
||||
return (
|
||||
f"workload={report.workload} imports={report.total_imports} "
|
||||
f"missing={len(report.missing)} partial={len(report.partial)} "
|
||||
f"present={len(report.present)} shared_subsystems={len(report.shared_primitives)}\n"
|
||||
)
|
||||
|
||||
|
||||
def dumps_gaps(report: GapReport) -> str:
|
||||
return json.dumps(report.to_dict(), indent=2, sort_keys=True) + "\n"
|
||||
@@ -0,0 +1,258 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Authoritative x86-64 inventory from the instruction registry.
|
||||
|
||||
Consumes `crates/loader/x86/instructions.toml` via `generate_x86.load`.
|
||||
Classifies native lowering from read-only `is_native`/`neon_operation` arms in
|
||||
`dbt.rs`. Does not modify CPU crates or invent support percentages.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import runpy
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
REGISTRY_REL = Path("crates/loader/x86/instructions.toml")
|
||||
GENERATOR_REL = Path("crates/loader/generate_x86.py")
|
||||
DBT_REL = Path("crates/loader/src/dbt.rs")
|
||||
FIXTURE_RELS = (
|
||||
Path("crates/loader/tests/x86/integer.txt"),
|
||||
Path("crates/loader/tests/x86/vector.txt"),
|
||||
Path("crates/loader/tests/x86/float.txt"),
|
||||
)
|
||||
|
||||
# Documented intentional rejections (docs/cpu/instruction-registry.md).
|
||||
# Not registry forms; tracked separately so they are never counted as declared.
|
||||
UNSUPPORTED_CATALOG = (
|
||||
"LOCK",
|
||||
"F2/F3-as-rep (except PAUSE / declared forms)",
|
||||
"F2+F3 combined",
|
||||
"address-size override",
|
||||
"ignored segment after FS/GS",
|
||||
"16-bit stack/branch",
|
||||
"16-bit BSWAP/MOVSXD",
|
||||
"BT memory by register index",
|
||||
"RCL/RCR/SHLD/SHRD",
|
||||
"string instructions",
|
||||
"MMX",
|
||||
"RCP/RSQRT approximations",
|
||||
"SSE3+",
|
||||
"VEX",
|
||||
"atomics/fences",
|
||||
"raw SYSCALL in DBT",
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FormRecord:
|
||||
op: str
|
||||
map: str
|
||||
prefix: str
|
||||
opcode: int
|
||||
digit: int | None
|
||||
enc: str
|
||||
size: str
|
||||
imm: str
|
||||
src: str
|
||||
expanded_from_count: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class CpuInventory:
|
||||
schema: int
|
||||
architecture: str
|
||||
form_count: int
|
||||
operation_count: int
|
||||
by_map: dict[str, int] = field(default_factory=dict)
|
||||
by_prefix: dict[str, int] = field(default_factory=dict)
|
||||
by_size: dict[str, int] = field(default_factory=dict)
|
||||
by_enc: dict[str, int] = field(default_factory=dict)
|
||||
operations: list[str] = field(default_factory=list)
|
||||
native_ops: list[str] = field(default_factory=list)
|
||||
shared_semantic_ops: list[str] = field(default_factory=list)
|
||||
fixture_mnemonics: list[str] = field(default_factory=list)
|
||||
ops_missing_fixture_evidence: list[str] = field(default_factory=list)
|
||||
unsupported_catalog: list[str] = field(default_factory=list)
|
||||
forms: list[dict[str, Any]] = field(default_factory=list)
|
||||
notes: list[str] = field(default_factory=list)
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
def _load_generator(root: Path):
|
||||
path = root / GENERATOR_REL
|
||||
if not path.is_file():
|
||||
raise FileNotFoundError(f"missing generator {path}")
|
||||
# Keep generate_x86 importable without installing the package.
|
||||
sys.path.insert(0, str(path.parent))
|
||||
try:
|
||||
return runpy.run_path(str(path))
|
||||
finally:
|
||||
if sys.path and sys.path[0] == str(path.parent):
|
||||
sys.path.pop(0)
|
||||
|
||||
|
||||
def expand_forms(raw_forms: list[dict[str, Any]]) -> list[FormRecord]:
|
||||
"""Expand count>1 encodings into per-opcode records (matches generator slots)."""
|
||||
out: list[FormRecord] = []
|
||||
for form in raw_forms:
|
||||
count = int(form.get("count", 1))
|
||||
base = int(form["opcode"])
|
||||
for offset in range(count):
|
||||
out.append(
|
||||
FormRecord(
|
||||
op=str(form["op"]),
|
||||
map=str(form.get("map", "1")),
|
||||
prefix=str(form.get("prefix", "") or ""),
|
||||
opcode=base + offset,
|
||||
digit=form.get("digit"),
|
||||
enc=str(form["enc"]),
|
||||
size=str(form["size"]),
|
||||
imm=str(form.get("imm", "") or ""),
|
||||
src=str(form.get("src", "") or ""),
|
||||
expanded_from_count=count > 1,
|
||||
)
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def parse_native_ops(dbt_text: str) -> set[str]:
|
||||
"""Collect Op::* names that appear as unconditional native arms or NEON table keys.
|
||||
|
||||
Conditional native (wide-only, encoding-gated) still counts the op as having
|
||||
a native lowering path; shared-semantic remains available for other widths.
|
||||
"""
|
||||
native: set[str] = set()
|
||||
# Arms of is_native before the final `_ => false`
|
||||
fn = re.search(r"pub fn is_native\(.*?\{(.*?)\n\}", dbt_text, re.S)
|
||||
body = fn.group(1) if fn else dbt_text
|
||||
for match in re.finditer(r"Op::([A-Za-z0-9_]+)", body):
|
||||
# Stop once we hit neon_operation definition if we grabbed too much.
|
||||
native.add(_rust_op_to_registry(match.group(1)))
|
||||
neon = re.search(r"fn neon_operation\(.*?\{(.*?)\n\}", dbt_text, re.S)
|
||||
if neon:
|
||||
for match in re.finditer(r"Op::([A-Za-z0-9_]+)", neon.group(1)):
|
||||
native.add(_rust_op_to_registry(match.group(1)))
|
||||
native.discard("syscall") # is_translatable rejects; not a native lower
|
||||
return native
|
||||
|
||||
|
||||
def _rust_op_to_registry(name: str) -> str:
|
||||
# Op::Movsxd -> movsxd, Op::Add -> add
|
||||
out = []
|
||||
for i, ch in enumerate(name):
|
||||
if ch.isupper() and i:
|
||||
out.append("_")
|
||||
out.append(ch.lower())
|
||||
return "".join(out).replace("__", "_")
|
||||
|
||||
|
||||
def parse_fixture_mnemonics(texts: list[str]) -> set[str]:
|
||||
"""First token after `|` in `hex | asm` fixture lines."""
|
||||
found: set[str] = set()
|
||||
for text in texts:
|
||||
for line in text.splitlines():
|
||||
if " | " not in line:
|
||||
continue
|
||||
asm = line.split(" | ", 1)[1].strip()
|
||||
if not asm:
|
||||
continue
|
||||
token = asm.split()[0].lower()
|
||||
# strip width suffixes used in intel syntax occasionally
|
||||
found.add(token)
|
||||
return found
|
||||
|
||||
|
||||
def mnemonic_covers_op(mnemonic: str, op: str) -> bool:
|
||||
if mnemonic == op:
|
||||
return True
|
||||
# Common aliases: jcc conditions, cmovcc, setcc, imul2 -> imul
|
||||
if op == "jcc" and mnemonic.startswith("j") and mnemonic not in {"jmp", "jecxz", "jrcxz"}:
|
||||
return True
|
||||
if op == "cmov" and mnemonic.startswith("cmov"):
|
||||
return True
|
||||
if op == "setcc" and mnemonic.startswith("set"):
|
||||
return True
|
||||
if op == "imul2" and mnemonic == "imul":
|
||||
return True
|
||||
if op in {"cwde", "cdq"} and mnemonic in {"cwde", "cdqe", "cdq", "cqo", "cbw", "cwd"}:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def build_inventory(root: Path) -> CpuInventory:
|
||||
gen = _load_generator(root)
|
||||
text = (root / REGISTRY_REL).read_text(encoding="utf-8")
|
||||
operations, forms = gen["load"](text)
|
||||
records = expand_forms(forms)
|
||||
by_map: dict[str, int] = defaultdict(int)
|
||||
by_prefix: dict[str, int] = defaultdict(int)
|
||||
by_size: dict[str, int] = defaultdict(int)
|
||||
by_enc: dict[str, int] = defaultdict(int)
|
||||
for rec in records:
|
||||
by_map[rec.map] += 1
|
||||
by_prefix[rec.prefix or "none"] += 1
|
||||
by_size[rec.size] += 1
|
||||
by_enc[rec.enc] += 1
|
||||
|
||||
dbt = (root / DBT_REL).read_text(encoding="utf-8") if (root / DBT_REL).is_file() else ""
|
||||
native_ops = sorted(parse_native_ops(dbt) & set(operations))
|
||||
shared = sorted(set(operations) - set(native_ops))
|
||||
|
||||
fixture_texts = []
|
||||
for rel in FIXTURE_RELS:
|
||||
path = root / rel
|
||||
if path.is_file():
|
||||
fixture_texts.append(path.read_text(encoding="utf-8"))
|
||||
mnemonics = parse_fixture_mnemonics(fixture_texts)
|
||||
missing = sorted(
|
||||
op for op in operations
|
||||
if not any(mnemonic_covers_op(m, op) for m in mnemonics)
|
||||
and op not in {"ldmxcsr", "stmxcsr", "jcc", "jmp", "call", "ret", "hlt", "syscall"}
|
||||
)
|
||||
|
||||
notes = [
|
||||
"Declared forms are decodable; support requires semantics + fixtures (docs/cpu/instruction-registry.md).",
|
||||
"Native ops are read from dbt.rs is_native/neon_operation; conditional width/encoding gates still use shared semantics for other cases.",
|
||||
"Unsupported catalog is documentation of intentional rejections, not missing registry rows.",
|
||||
"Does not inflate coverage: fixture evidence is mnemonic-level, not form-index proof.",
|
||||
]
|
||||
return CpuInventory(
|
||||
schema=1,
|
||||
architecture="x86-64",
|
||||
form_count=len(records),
|
||||
operation_count=len(operations),
|
||||
by_map=dict(sorted(by_map.items())),
|
||||
by_prefix=dict(sorted(by_prefix.items())),
|
||||
by_size=dict(sorted(by_size.items())),
|
||||
by_enc=dict(sorted(by_enc.items())),
|
||||
operations=sorted(operations),
|
||||
native_ops=native_ops,
|
||||
shared_semantic_ops=shared,
|
||||
fixture_mnemonics=sorted(mnemonics),
|
||||
ops_missing_fixture_evidence=missing,
|
||||
unsupported_catalog=list(UNSUPPORTED_CATALOG),
|
||||
forms=[asdict(r) for r in records],
|
||||
notes=notes,
|
||||
)
|
||||
|
||||
|
||||
def compact_inventory(inv: CpuInventory) -> str:
|
||||
return (
|
||||
f"forms={inv.form_count} ops={inv.operation_count} "
|
||||
f"native={len(inv.native_ops)} shared={len(inv.shared_semantic_ops)} "
|
||||
f"maps={inv.by_map} unsupported_catalog={len(inv.unsupported_catalog)}\n"
|
||||
)
|
||||
|
||||
|
||||
def dumps_inventory(inv: CpuInventory, *, include_forms: bool = False) -> str:
|
||||
data = inv.to_dict()
|
||||
if not include_forms:
|
||||
data.pop("forms", None)
|
||||
return json.dumps(data, indent=2, sort_keys=True) + "\n"
|
||||
@@ -0,0 +1,163 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Typed runtime service inventory from crates/loader/runtime/services.txt.
|
||||
|
||||
Separates canonical services from API-set aliases. Does not execute guests or
|
||||
modify runtime crates.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from collections import defaultdict
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
SERVICES_REL = Path("crates/loader/runtime/services.txt")
|
||||
STATUS_VALUES = frozenset({"implemented", "partial", "stub"})
|
||||
|
||||
|
||||
@dataclass
|
||||
class ServiceRecord:
|
||||
library: str
|
||||
symbol: str
|
||||
signature: str
|
||||
handler: str
|
||||
status: str
|
||||
aliases: list[str] = field(default_factory=list)
|
||||
fails: str = ""
|
||||
ref: str = ""
|
||||
tests: list[str] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def key(self) -> str:
|
||||
return f"{self.library}!{self.symbol}"
|
||||
|
||||
|
||||
@dataclass
|
||||
class RuntimeInventory:
|
||||
service_count: int
|
||||
by_status: dict[str, int]
|
||||
implemented: list[str]
|
||||
partial: list[str]
|
||||
stub: list[str]
|
||||
independently_verified: list[str]
|
||||
aliases: list[dict[str, str]]
|
||||
alias_count: int
|
||||
libraries: dict[str, int]
|
||||
services: list[dict[str, Any]]
|
||||
notes: list[str]
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
_SERVICE_HEAD = re.compile(
|
||||
r"^service\s+(\S+)\s+(\S+)\((.*)\)\s*->\s*(\S+)\s*$"
|
||||
)
|
||||
|
||||
|
||||
def parse_services_text(text: str) -> list[ServiceRecord]:
|
||||
services: list[ServiceRecord] = []
|
||||
current: ServiceRecord | None = None
|
||||
for raw in text.splitlines():
|
||||
line = raw.strip()
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
if line.startswith("service "):
|
||||
match = _SERVICE_HEAD.match(line)
|
||||
if not match:
|
||||
raise ValueError(f"bad service header: {line}")
|
||||
library, symbol, params, result = match.groups()
|
||||
current = ServiceRecord(
|
||||
library=library,
|
||||
symbol=symbol,
|
||||
signature=f"({params}) -> {result}",
|
||||
handler="",
|
||||
status="",
|
||||
)
|
||||
services.append(current)
|
||||
continue
|
||||
if current is None:
|
||||
raise ValueError(f"field outside service: {line}")
|
||||
if " " not in line:
|
||||
raise ValueError(f"missing field value: {line}")
|
||||
key, value = line.split(None, 1)
|
||||
if key == "handler":
|
||||
current.handler = value
|
||||
elif key == "status":
|
||||
if value not in STATUS_VALUES:
|
||||
raise ValueError(f"unknown status {value!r}")
|
||||
current.status = value
|
||||
elif key == "alias":
|
||||
current.aliases.append(value)
|
||||
elif key == "fails":
|
||||
current.fails = value
|
||||
elif key == "ref":
|
||||
current.ref = value
|
||||
elif key == "test":
|
||||
current.tests.append(value)
|
||||
else:
|
||||
raise ValueError(f"unknown field {key!r}")
|
||||
for svc in services:
|
||||
if not svc.handler or not svc.status:
|
||||
raise ValueError(f"incomplete service {svc.key}")
|
||||
return services
|
||||
|
||||
|
||||
def build_runtime_inventory(root: Path) -> RuntimeInventory:
|
||||
path = root / SERVICES_REL
|
||||
services = parse_services_text(path.read_text(encoding="utf-8"))
|
||||
by_status: dict[str, int] = defaultdict(int)
|
||||
libraries: dict[str, int] = defaultdict(int)
|
||||
aliases: list[dict[str, str]] = []
|
||||
for svc in services:
|
||||
by_status[svc.status] += 1
|
||||
libraries[svc.library] += 1
|
||||
for alias in svc.aliases:
|
||||
aliases.append({
|
||||
"alias": alias,
|
||||
"canonical": svc.key,
|
||||
"symbol": svc.symbol,
|
||||
})
|
||||
# Independently verified: registry documents zero acceptance unless a future
|
||||
# field appears; do not invent. Track explicit empty list.
|
||||
independently_verified: list[str] = []
|
||||
notes = [
|
||||
"Status values are registry contracts for synthetic guests, not Xbox compatibility.",
|
||||
"API-set aliases are counted separately from canonical services.",
|
||||
"Independently verified remains empty until an acceptance process records it; not inferred.",
|
||||
"docs/runtime/services.md counts are generated; this tool re-parses services.txt.",
|
||||
]
|
||||
return RuntimeInventory(
|
||||
service_count=len(services),
|
||||
by_status=dict(sorted(by_status.items())),
|
||||
implemented=sorted(s.key for s in services if s.status == "implemented"),
|
||||
partial=sorted(s.key for s in services if s.status == "partial"),
|
||||
stub=sorted(s.key for s in services if s.status == "stub"),
|
||||
independently_verified=independently_verified,
|
||||
aliases=sorted(aliases, key=lambda a: (a["alias"], a["canonical"])),
|
||||
alias_count=len(aliases),
|
||||
libraries=dict(sorted(libraries.items())),
|
||||
services=[asdict(s) for s in services],
|
||||
notes=notes,
|
||||
)
|
||||
|
||||
|
||||
def compact_runtime(inv: RuntimeInventory) -> str:
|
||||
return (
|
||||
f"services={inv.service_count} "
|
||||
f"implemented={inv.by_status.get('implemented', 0)} "
|
||||
f"partial={inv.by_status.get('partial', 0)} "
|
||||
f"stub={inv.by_status.get('stub', 0)} "
|
||||
f"aliases={inv.alias_count} "
|
||||
f"verified={len(inv.independently_verified)}\n"
|
||||
)
|
||||
|
||||
|
||||
def dumps_runtime(inv: RuntimeInventory, *, include_services: bool = True) -> str:
|
||||
data = inv.to_dict()
|
||||
if not include_services:
|
||||
data.pop("services", None)
|
||||
return json.dumps(data, indent=2, sort_keys=True) + "\n"
|
||||
@@ -0,0 +1,39 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import unittest
|
||||
|
||||
from qa.compat_gaps import analyze_gaps, classify_subsystem, compact_gaps
|
||||
|
||||
|
||||
class CompatGaps(unittest.TestCase):
|
||||
def test_groups_missing_by_subsystem(self):
|
||||
report = analyze_gaps(
|
||||
{
|
||||
"workload": "synthetic-a",
|
||||
"imports": [
|
||||
{"module": "kernel32.dll", "symbol": "VirtualAlloc"},
|
||||
{"module": "kernel32.dll", "symbol": "VirtualFree"},
|
||||
{"module": "kernel32.dll", "symbol": "GetCurrentProcess"},
|
||||
{"module": "ucrtbase.dll", "symbol": "sqrt"},
|
||||
{"module": "kernel32.dll", "symbol": "CreateFileW"},
|
||||
],
|
||||
},
|
||||
implemented=["kernel32.dll!GetCurrentProcess"],
|
||||
partial=["kernel32.dll!VirtualAlloc", "ucrtbase.dll!sqrt"],
|
||||
)
|
||||
self.assertEqual(report.workload, "synthetic-a")
|
||||
self.assertEqual(len(report.present), 1)
|
||||
self.assertEqual(len(report.partial), 2)
|
||||
self.assertEqual(len(report.missing), 2) # VirtualFree, CreateFileW
|
||||
self.assertIn("memory", report.by_subsystem)
|
||||
self.assertIn("memory", report.shared_primitives)
|
||||
self.assertIn("binaries are not executed", " ".join(report.notes).lower())
|
||||
self.assertIn("missing=2", compact_gaps(report))
|
||||
|
||||
def test_subsystem_rules(self):
|
||||
self.assertEqual(classify_subsystem("VirtualAlloc"), "memory")
|
||||
self.assertEqual(classify_subsystem("sqrtf"), "crt-math")
|
||||
self.assertEqual(classify_subsystem("NoSuchThing"), "other")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,71 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from qa.cpu_inventory import (
|
||||
build_inventory,
|
||||
compact_inventory,
|
||||
expand_forms,
|
||||
mnemonic_covers_op,
|
||||
parse_fixture_mnemonics,
|
||||
parse_native_ops,
|
||||
)
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class CpuInventory(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.inv = build_inventory(ROOT)
|
||||
|
||||
def test_registry_forms_not_heuristic(self):
|
||||
self.assertEqual(self.inv.schema, 1)
|
||||
self.assertEqual(self.inv.architecture, "x86-64")
|
||||
self.assertGreater(self.inv.form_count, 200)
|
||||
self.assertGreater(self.inv.operation_count, 100)
|
||||
self.assertIn("1", self.inv.by_map)
|
||||
self.assertIn("0f", self.inv.by_map)
|
||||
self.assertEqual(
|
||||
self.inv.form_count,
|
||||
sum(self.inv.by_map.values()),
|
||||
)
|
||||
|
||||
def test_native_and_shared_partition(self):
|
||||
native = set(self.inv.native_ops)
|
||||
shared = set(self.inv.shared_semantic_ops)
|
||||
ops = set(self.inv.operations)
|
||||
self.assertTrue(native)
|
||||
self.assertTrue(shared)
|
||||
self.assertTrue(native.issubset(ops))
|
||||
self.assertTrue(shared.issubset(ops))
|
||||
self.assertEqual(native | shared, ops)
|
||||
self.assertEqual(native & shared, set())
|
||||
|
||||
def test_unsupported_catalog_separate(self):
|
||||
self.assertIn("MMX", self.inv.unsupported_catalog)
|
||||
for name in self.inv.unsupported_catalog:
|
||||
self.assertNotIn(name.lower(), self.inv.operations)
|
||||
|
||||
def test_expand_count_and_fixtures(self):
|
||||
expanded = expand_forms(
|
||||
[{"op": "push", "opcode": 0x50, "count": 8, "enc": "op_reg", "size": "q"}]
|
||||
)
|
||||
self.assertEqual(len(expanded), 8)
|
||||
self.assertEqual(expanded[0].opcode, 0x50)
|
||||
self.assertEqual(expanded[7].opcode, 0x57)
|
||||
mnems = parse_fixture_mnemonics(["00 cb | add bl, cl\n66 01 cb | add bx, cx\n"])
|
||||
self.assertEqual(mnems, {"add"})
|
||||
self.assertTrue(mnemonic_covers_op("je", "jcc"))
|
||||
self.assertTrue(mnemonic_covers_op("imul", "imul2"))
|
||||
|
||||
def test_compact_and_no_coverage_inflation(self):
|
||||
text = compact_inventory(self.inv)
|
||||
self.assertIn(f"forms={self.inv.form_count}", text)
|
||||
# Notes must deny inflation.
|
||||
joined = " ".join(self.inv.notes).lower()
|
||||
self.assertIn("does not inflate", joined)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,56 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from qa.runtime_inventory import build_runtime_inventory, compact_runtime, parse_services_text
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
SAMPLE = """
|
||||
# comment
|
||||
service kernel32.dll GetCurrentProcess() -> handle
|
||||
handler get_current_process
|
||||
status implemented
|
||||
alias api-ms-win-core-processthreads-l1-1-0.dll
|
||||
fails never
|
||||
ref processthreadsapi.h GetCurrentProcess
|
||||
test identity_services_return_documented_pseudo_handles_and_ids
|
||||
|
||||
service ucrtbase.dll sqrt(x: f64) -> f64
|
||||
handler crt_sqrt
|
||||
status partial
|
||||
fails NaN for a negative argument
|
||||
ref math.h sqrt
|
||||
test crt_math_guest_dispatch
|
||||
"""
|
||||
|
||||
|
||||
class RuntimeInventory(unittest.TestCase):
|
||||
def test_parse_separates_aliases(self):
|
||||
services = parse_services_text(SAMPLE)
|
||||
self.assertEqual(len(services), 2)
|
||||
self.assertEqual(services[0].status, "implemented")
|
||||
self.assertEqual(services[0].aliases, ["api-ms-win-core-processthreads-l1-1-0.dll"])
|
||||
self.assertEqual(services[1].library, "ucrtbase.dll")
|
||||
|
||||
def test_live_registry(self):
|
||||
inv = build_runtime_inventory(ROOT)
|
||||
self.assertGreaterEqual(inv.service_count, 20)
|
||||
self.assertEqual(
|
||||
inv.service_count,
|
||||
inv.by_status.get("implemented", 0)
|
||||
+ inv.by_status.get("partial", 0)
|
||||
+ inv.by_status.get("stub", 0),
|
||||
)
|
||||
self.assertEqual(inv.independently_verified, [])
|
||||
self.assertGreater(inv.alias_count, 0)
|
||||
# Aliases are separate records pointing at canonical services.
|
||||
self.assertTrue(all("canonical" in a and "alias" in a for a in inv.aliases))
|
||||
self.assertTrue(all("!" in a["canonical"] for a in inv.aliases))
|
||||
text = compact_runtime(inv)
|
||||
self.assertIn(f"services={inv.service_count}", text)
|
||||
self.assertIn("verified=0", text)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user