mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 12:20:42 +00:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8cae9772b6 | ||
|
|
c6a354bca5 | ||
|
|
9d83e09aa6 |
No files matched your search
@@ -9,6 +9,9 @@ exact revision and known limitations.
|
||||
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
|
||||
remains unsupported.
|
||||
|
||||
### Changed
|
||||
- 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 Phase II infrastructure CLIs under `scripts/qa` and `scripts/release` (#277): read-only RDNA2 expansion planning over live inventories, unified verification profiles with stale-evidence detection, CPU/runtime coverage scans, benchmark regression comparisons that reject incompatible identities, git rename/delete scope collision reports, and release-readiness reports with SBOM/checksum/bundle checks. Covered by `tests/qa` and `tests/release`; advisory until reviewed.
|
||||
- Added advisory infrastructure QA helpers under `scripts/qa/` and `scripts/release/` (issue #277): exit-status-preserving orchestration with JSON reports, PR scope/DCO/artifact checks, benchmark percentile analysis over existing samples, environment and repository health diagnostics, ARM64 Mach-O/bundle/codesign helpers, and checksum manifests. Covered by `tests/qa/` and `tests/release/`; checks stay advisory until reviewed.
|
||||
|
||||
@@ -2061,4 +2061,423 @@ mod tests {
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
// FS/GS segment override regression tests from #280 (#72), restored after a
|
||||
// merge-conflict resolution dropped them.
|
||||
/// A segment-relative store and load through the FS base.
|
||||
///
|
||||
/// The encodings are `mov [fs:0x8], rbx` (64 48 89 1C 25 08 00 00 00)
|
||||
/// and `mov rdx, [fs:0x8]` (64 48 8B 14 25 08 00 00 00), as produced by
|
||||
/// LLVM 23.1.6 `llvm-mc -show-encoding`. The SIB byte 0x25 selects "no
|
||||
/// index" and "no base", so the address is the FS base plus the
|
||||
/// displacement 8.
|
||||
///
|
||||
/// Per Intel SDM Volume 3A section 3.4.4 the linear address is
|
||||
/// `(FS or GS).base + index + displacement`, so the store must land at
|
||||
/// `FS_BASE + 8`.
|
||||
#[test]
|
||||
fn fs_segment_override_adds_the_fs_base_to_the_address() {
|
||||
let code = [
|
||||
0x64, 0x48, 0x89, 0x1C, 0x25, 0x08, 0x00, 0x00, 0x00, // mov [fs:0x8], rbx
|
||||
0x64, 0x48, 0x8B, 0x14, 0x25, 0x08, 0x00, 0x00, 0x00, // mov rdx, [fs:0x8]
|
||||
0xF4, // hlt
|
||||
];
|
||||
let (mut engine, mut cpu, mut memory) = fixture(&code);
|
||||
const FS_BASE: u64 = 0x7000;
|
||||
const GS_BASE: u64 = 0x8000;
|
||||
const STORED_VALUE: u64 = 0x1122_3344_5566_7788;
|
||||
cpu.fs_base = FS_BASE;
|
||||
cpu.gs_base = GS_BASE;
|
||||
cpu.set(Register::Rbx, STORED_VALUE);
|
||||
memory
|
||||
.map_region(FS_BASE, 0x100, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region(GS_BASE, 0x100, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
|
||||
let result = engine.run(&mut cpu, &mut memory, 16);
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
// The store landed at the FS base plus the displacement, not at the
|
||||
// bare displacement and not at the GS base. The bare displacement
|
||||
// address 8 is not mapped at all, so reaching it would have faulted.
|
||||
assert_eq!(memory.read_u64(FS_BASE + 8).unwrap(), STORED_VALUE);
|
||||
assert_eq!(memory.read_u64(GS_BASE + 8).unwrap(), 0);
|
||||
// The load read back the same location.
|
||||
assert_eq!(result.final_state.get(Register::Rdx), STORED_VALUE);
|
||||
}
|
||||
|
||||
/// A RIP-relative segment-relative store adds the segment base too.
|
||||
///
|
||||
/// The encoding is `mov [fs:(%rip)], rbx` (64 48 89 1D 00 00 00 00), as
|
||||
/// produced by LLVM 23.1.6 `llvm-mc -show-encoding`. The displacement is
|
||||
/// zero, so the address is the address of the next instruction plus the
|
||||
/// FS base.
|
||||
///
|
||||
/// The segment base is added to the effective address for every addressing
|
||||
/// form, so this must land at `FS_BASE + ENTRY + 8` and not at the bare
|
||||
/// RIP-relative address.
|
||||
#[test]
|
||||
fn rip_relative_segment_override_adds_the_segment_base() {
|
||||
let code = [
|
||||
0x64, 0x48, 0x89, 0x1D, 0x00, 0x00, 0x00, 0x00, // mov [fs:(%rip)], rbx
|
||||
0xF4, // hlt
|
||||
];
|
||||
let (mut engine, mut cpu, mut memory) = fixture(&code);
|
||||
const FS_BASE: u64 = 0x7000;
|
||||
const STORED_VALUE: u64 = 0x1122_3344_5566_7788;
|
||||
cpu.fs_base = FS_BASE;
|
||||
cpu.set(Register::Rbx, STORED_VALUE);
|
||||
// The segment-adjusted address is FS_BASE + ENTRY + 8, so the region
|
||||
// has to reach that far.
|
||||
memory
|
||||
.map_region(FS_BASE, 0x2000, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
|
||||
let result = engine.run(&mut cpu, &mut memory, 16);
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
// The instruction is 8 bytes long, so the next instruction is at
|
||||
// ENTRY + 8 and the displacement of zero makes that the offset.
|
||||
assert_eq!(memory.read_u64(FS_BASE + ENTRY + 8).unwrap(), STORED_VALUE);
|
||||
}
|
||||
|
||||
/// The two execution paths must agree on segment-relative addressing.
|
||||
///
|
||||
/// The native DBT translator and the software interpreter are separate
|
||||
/// implementations of the same guest semantics, so a program that uses a
|
||||
/// segment override must produce the same result and the same memory
|
||||
/// writes under both.
|
||||
///
|
||||
/// The encodings are `mov [fs:0x8], rbx` (64 48 89 1C 25 08 00 00 00),
|
||||
/// `mov [gs:0x10], rbx` (65 48 89 1C 25 10 00 00 00),
|
||||
/// `mov rdx, [fs:0x8]` (64 48 8B 14 25 08 00 00 00) and
|
||||
/// `mov rsi, [gs:0x10]` (65 48 8B 34 25 10 00 00 00), as produced by
|
||||
/// LLVM 23.1.6 `llvm-mc -show-encoding`.
|
||||
#[test]
|
||||
fn interpreter_and_native_dbt_agree_on_segment_relative_addressing() {
|
||||
const CODE: [u8; 37] = [
|
||||
0x64, 0x48, 0x89, 0x1C, 0x25, 0x08, 0x00, 0x00, 0x00, // mov [fs:0x8], rbx
|
||||
0x65, 0x48, 0x89, 0x1C, 0x25, 0x10, 0x00, 0x00, 0x00, // mov [gs:0x10], rbx
|
||||
0x64, 0x48, 0x8B, 0x14, 0x25, 0x08, 0x00, 0x00, 0x00, // mov rdx, [fs:0x8]
|
||||
0x65, 0x48, 0x8B, 0x34, 0x25, 0x10, 0x00, 0x00, 0x00, // mov rsi, [gs:0x10]
|
||||
0xF4, // hlt
|
||||
];
|
||||
const FS_BASE: u64 = 0x7000;
|
||||
const GS_BASE: u64 = 0x8000;
|
||||
const STORED_VALUE: u64 = 0x1122_3344_5566_7788;
|
||||
|
||||
// The native DBT path.
|
||||
let (mut engine, mut cpu, mut memory) = fixture(&CODE);
|
||||
cpu.fs_base = FS_BASE;
|
||||
cpu.gs_base = GS_BASE;
|
||||
cpu.set(Register::Rbx, STORED_VALUE);
|
||||
memory
|
||||
.map_region(FS_BASE, 0x100, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region(GS_BASE, 0x100, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
let native = engine.run(&mut cpu, &mut memory, 16);
|
||||
assert_eq!(native.exit_reason, ExitReason::Halt);
|
||||
let native_memory = memory;
|
||||
|
||||
// The software interpreter path over the same program.
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(ENTRY, CODE.len(), MemoryPermissions::READ_EXECUTE, &CODE)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region(FS_BASE, 0x100, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region(GS_BASE, 0x100, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.fs_base = FS_BASE;
|
||||
cpu.gs_base = GS_BASE;
|
||||
cpu.set(Register::Rbx, STORED_VALUE);
|
||||
let mut interp = crate::cpu::Interpreter::new(cpu, &mut memory, 16);
|
||||
let interpreted = interp.run();
|
||||
|
||||
assert_eq!(interpreted.exit_reason, native.exit_reason);
|
||||
assert_eq!(interpreted.final_state, native.final_state);
|
||||
assert_eq!(
|
||||
memory.read_u64(FS_BASE + 8).unwrap(),
|
||||
native.final_state.get(Register::Rbx)
|
||||
);
|
||||
assert_eq!(
|
||||
memory.read_u64(GS_BASE + 0x10).unwrap(),
|
||||
native.final_state.get(Register::Rbx)
|
||||
);
|
||||
// The bytes each path left in guest memory must be identical, not only the
|
||||
// two words checked above.
|
||||
for base in [FS_BASE, GS_BASE] {
|
||||
assert_eq!(
|
||||
region_bytes(&native_memory, base, 0x100),
|
||||
region_bytes(&memory, base, 0x100),
|
||||
"segment region at {base:#x}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn region_bytes(memory: &GuestMemory, base: u64, len: usize) -> Vec<u8> {
|
||||
let mut bytes = vec![0; len];
|
||||
memory.read_bytes(base, &mut bytes).unwrap();
|
||||
bytes
|
||||
}
|
||||
|
||||
/// FS and GS RIP-relative loads and stores with positive and negative
|
||||
/// displacements. The effective address is the segment base plus the address of
|
||||
/// the next instruction plus the signed disp32 (AMD64 APM vol. 1, RIP-relative
|
||||
/// addressing; FS/GS overrides still apply in 64-bit mode). Each expected address
|
||||
/// below is worked out by hand from that rule.
|
||||
const RIP_CODE: [u8; 33] = [
|
||||
// 0x1000: mov fs:[rip - 0x100], rbx -> FS + 0x1008 - 0x100 = FS + 0x0F08
|
||||
0x64, 0x48, 0x89, 0x1D, 0x00, 0xFF, 0xFF, 0xFF,
|
||||
// 0x1008: mov gs:[rip + 0x40], rbx -> GS + 0x1010 + 0x40 = GS + 0x1050
|
||||
0x65, 0x48, 0x89, 0x1D, 0x40, 0x00, 0x00, 0x00,
|
||||
// 0x1010: mov rdx, fs:[rip - 0x28] -> FS + 0x1018 - 0x28 = FS + 0x0FF0
|
||||
0x64, 0x48, 0x8B, 0x15, 0xD8, 0xFF, 0xFF, 0xFF,
|
||||
// 0x1018: mov rsi, gs:[rip + 0x20] -> GS + 0x1020 + 0x20 = GS + 0x1040
|
||||
0x65, 0x48, 0x8B, 0x35, 0x20, 0x00, 0x00, 0x00, // 0x1020: hlt
|
||||
0xF4,
|
||||
];
|
||||
const RIP_FS: u64 = 0x10_0000;
|
||||
const RIP_GS: u64 = 0x20_0000;
|
||||
const RIP_STORED: u64 = 0x0102_0304_0506_0708;
|
||||
const RIP_FS_SEED: u64 = 0xA1A2_A3A4_A5A6_A7A8;
|
||||
const RIP_GS_SEED: u64 = 0xB1B2_B3B4_B5B6_B7B8;
|
||||
|
||||
fn rip_setup(cpu: &mut CpuState, memory: &mut GuestMemory) {
|
||||
cpu.fs_base = RIP_FS;
|
||||
cpu.gs_base = RIP_GS;
|
||||
cpu.set(Register::Rbx, RIP_STORED);
|
||||
for base in [RIP_FS, RIP_GS] {
|
||||
memory
|
||||
.map_region(base, 0x2000, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
}
|
||||
memory.write_u64(RIP_FS + 0x0FF0, RIP_FS_SEED).unwrap();
|
||||
memory.write_u64(RIP_GS + 0x1040, RIP_GS_SEED).unwrap();
|
||||
}
|
||||
|
||||
fn check_rip_results(state: &CpuState, memory: &GuestMemory, path: &str) {
|
||||
assert_eq!(
|
||||
memory.read_u64(RIP_FS + 0x0F08).unwrap(),
|
||||
RIP_STORED,
|
||||
"{path}: FS store, negative disp"
|
||||
);
|
||||
assert_eq!(
|
||||
memory.read_u64(RIP_GS + 0x1050).unwrap(),
|
||||
RIP_STORED,
|
||||
"{path}: GS store, positive disp"
|
||||
);
|
||||
assert_eq!(
|
||||
state.get(Register::Rdx),
|
||||
RIP_FS_SEED,
|
||||
"{path}: FS load, negative disp"
|
||||
);
|
||||
assert_eq!(
|
||||
state.get(Register::Rsi),
|
||||
RIP_GS_SEED,
|
||||
"{path}: GS load, positive disp"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fs_and_gs_rip_relative_loads_and_stores_use_the_segment_base() {
|
||||
let (mut engine, mut cpu, mut memory) = fixture(&RIP_CODE);
|
||||
rip_setup(&mut cpu, &mut memory);
|
||||
let native = engine.run(&mut cpu, &mut memory, 16);
|
||||
assert_eq!(native.exit_reason, ExitReason::Halt);
|
||||
check_rip_results(&native.final_state, &memory, "native DBT");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interpreter_and_native_dbt_agree_on_rip_relative_segment_accesses() {
|
||||
let (mut engine, mut cpu, mut native_memory) = fixture(&RIP_CODE);
|
||||
rip_setup(&mut cpu, &mut native_memory);
|
||||
let native = engine.run(&mut cpu, &mut native_memory, 16);
|
||||
|
||||
let (_, mut cpu, mut memory) = fixture(&RIP_CODE);
|
||||
rip_setup(&mut cpu, &mut memory);
|
||||
let interpreted = crate::cpu::Interpreter::new(cpu, &mut memory, 16).run();
|
||||
|
||||
assert_eq!(interpreted.exit_reason, native.exit_reason);
|
||||
assert_eq!(interpreted.final_state, native.final_state);
|
||||
check_rip_results(&interpreted.final_state, &memory, "interpreter");
|
||||
for base in [RIP_FS, RIP_GS] {
|
||||
assert_eq!(
|
||||
region_bytes(&native_memory, base, 0x2000),
|
||||
region_bytes(&memory, base, 0x2000),
|
||||
"segment region at {base:#x}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rip_relative_segment_faults_report_the_segment_adjusted_address() {
|
||||
// One instruction per case, with nothing mapped at either segment base.
|
||||
let cases: [(&[u8], u64); 4] = [
|
||||
// mov fs:[rip - 0x10], rbx -> FS + 0x1008 - 0x10
|
||||
(
|
||||
&[0x64, 0x48, 0x89, 0x1D, 0xF0, 0xFF, 0xFF, 0xFF, 0xF4],
|
||||
RIP_FS + 0x0FF8,
|
||||
),
|
||||
// mov gs:[rip + 0x30], rbx -> GS + 0x1008 + 0x30
|
||||
(
|
||||
&[0x65, 0x48, 0x89, 0x1D, 0x30, 0x00, 0x00, 0x00, 0xF4],
|
||||
RIP_GS + 0x1038,
|
||||
),
|
||||
// mov rdx, fs:[rip - 0x800] -> FS + 0x1008 - 0x800
|
||||
(
|
||||
&[0x64, 0x48, 0x8B, 0x15, 0x00, 0xF8, 0xFF, 0xFF, 0xF4],
|
||||
RIP_FS + 0x0808,
|
||||
),
|
||||
// mov rsi, gs:[rip + 0x8] -> GS + 0x1008 + 0x8
|
||||
(
|
||||
&[0x65, 0x48, 0x8B, 0x35, 0x08, 0x00, 0x00, 0x00, 0xF4],
|
||||
RIP_GS + 0x1010,
|
||||
),
|
||||
];
|
||||
for (code, fault) in cases {
|
||||
let expected = ExitReason::MemoryFault(MemoryError::UnmappedAddress(fault));
|
||||
let (mut engine, mut cpu, mut memory) = fixture(code);
|
||||
cpu.fs_base = RIP_FS;
|
||||
cpu.gs_base = RIP_GS;
|
||||
let native = engine.run(&mut cpu, &mut memory, 16);
|
||||
assert_eq!(
|
||||
native.exit_reason, expected,
|
||||
"native DBT, fault at {fault:#x}"
|
||||
);
|
||||
|
||||
let (_, mut cpu, mut memory) = fixture(code);
|
||||
cpu.fs_base = RIP_FS;
|
||||
cpu.gs_base = RIP_GS;
|
||||
let interpreted = crate::cpu::Interpreter::new(cpu, &mut memory, 16).run();
|
||||
assert_eq!(
|
||||
interpreted.exit_reason, expected,
|
||||
"interpreter, fault at {fault:#x}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Both execution paths must agree when an instruction carries an FS and
|
||||
/// a GS override together.
|
||||
///
|
||||
/// The Intel SDM states that "the effect of redundant prefixes (more than
|
||||
/// one prefix from a group) is undefined", and FS and GS are in the same
|
||||
/// prefix group. The architecture therefore does not define which base
|
||||
/// applies, so this test pins the local rule instead: both paths prefer
|
||||
/// GS, and they must agree with each other.
|
||||
///
|
||||
/// The encoding is `mov [fs:0x8], rbx` preceded by a GS override
|
||||
/// (65 64 48 89 1C 25 08 00 00 00).
|
||||
#[test]
|
||||
fn redundant_fs_and_gs_overrides_are_handled_the_same_by_both_paths() {
|
||||
const CODE: [u8; 11] = [
|
||||
0x65, 0x64, 0x48, 0x89, 0x1C, 0x25, 0x08, 0x00, 0x00, 0x00, // mov [fs:0x8], rbx
|
||||
0xF4, // hlt
|
||||
];
|
||||
const FS_BASE: u64 = 0x7000;
|
||||
const GS_BASE: u64 = 0x8000;
|
||||
const STORED_VALUE: u64 = 0x1122_3344_5566_7788;
|
||||
|
||||
let (mut engine, mut cpu, mut memory) = fixture(&CODE);
|
||||
cpu.fs_base = FS_BASE;
|
||||
cpu.gs_base = GS_BASE;
|
||||
cpu.set(Register::Rbx, STORED_VALUE);
|
||||
memory
|
||||
.map_region(FS_BASE, 0x100, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region(GS_BASE, 0x100, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
let native = engine.run(&mut cpu, &mut memory, 16);
|
||||
assert_eq!(native.exit_reason, ExitReason::Halt);
|
||||
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(ENTRY, CODE.len(), MemoryPermissions::READ_EXECUTE, &CODE)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region(FS_BASE, 0x100, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region(GS_BASE, 0x100, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.fs_base = FS_BASE;
|
||||
cpu.gs_base = GS_BASE;
|
||||
cpu.set(Register::Rbx, STORED_VALUE);
|
||||
let mut interp = crate::cpu::Interpreter::new(cpu, &mut memory, 16);
|
||||
let interpreted = interp.run();
|
||||
|
||||
assert_eq!(interpreted.exit_reason, native.exit_reason);
|
||||
assert_eq!(interpreted.final_state, native.final_state);
|
||||
// The local rule prefers GS, so the store landed at the GS base.
|
||||
assert_eq!(memory.read_u64(GS_BASE + 8).unwrap(), STORED_VALUE);
|
||||
assert_eq!(memory.read_u64(FS_BASE + 8).unwrap(), 0);
|
||||
}
|
||||
|
||||
/// The GS segment override adds the GS base, and distinct FS and GS bases
|
||||
/// must not be confused with each other.
|
||||
///
|
||||
/// The encodings are `mov [gs:0x8], rbx` (65 48 89 1C 25 08 00 00 00)
|
||||
/// and `mov rdx, [gs:0x8]` (65 48 8B 14 25 08 00 00 00), as produced by
|
||||
/// LLVM 23.1.6 `llvm-mc -show-encoding`.
|
||||
#[test]
|
||||
fn gs_segment_override_adds_the_gs_base_to_the_address() {
|
||||
let code = [
|
||||
0x65, 0x48, 0x89, 0x1C, 0x25, 0x08, 0x00, 0x00, 0x00, // mov [gs:0x8], rbx
|
||||
0x65, 0x48, 0x8B, 0x14, 0x25, 0x08, 0x00, 0x00, 0x00, // mov rdx, [gs:0x8]
|
||||
0xF4, // hlt
|
||||
];
|
||||
let (mut engine, mut cpu, mut memory) = fixture(&code);
|
||||
const FS_BASE: u64 = 0x7000;
|
||||
const GS_BASE: u64 = 0x8000;
|
||||
const STORED_VALUE: u64 = 0x1122_3344_5566_7788;
|
||||
cpu.fs_base = FS_BASE;
|
||||
cpu.gs_base = GS_BASE;
|
||||
cpu.set(Register::Rbx, STORED_VALUE);
|
||||
memory
|
||||
.map_region(FS_BASE, 0x100, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region(GS_BASE, 0x100, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
|
||||
let result = engine.run(&mut cpu, &mut memory, 16);
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
assert_eq!(memory.read_u64(GS_BASE + 8).unwrap(), STORED_VALUE);
|
||||
// The FS base must be untouched.
|
||||
assert_eq!(memory.read_u64(FS_BASE + 8).unwrap(), 0);
|
||||
assert_eq!(result.final_state.get(Register::Rdx), STORED_VALUE);
|
||||
}
|
||||
|
||||
/// A segment-relative access to an unmapped address must fault, and the
|
||||
/// fault must report the segment-adjusted address.
|
||||
///
|
||||
/// The encoding is `mov [fs:0x8], rbx` (64 48 89 1C 25 08 00 00 00).
|
||||
/// The FS base points outside every mapped region, so the store faults at
|
||||
/// `FS_BASE + 8`.
|
||||
#[test]
|
||||
fn segment_relative_access_to_an_unmapped_address_faults() {
|
||||
let code = [
|
||||
0x64, 0x48, 0x89, 0x1C, 0x25, 0x08, 0x00, 0x00, 0x00, // mov [fs:0x8], rbx
|
||||
0xF4, // hlt
|
||||
];
|
||||
let (mut engine, mut cpu, mut memory) = fixture(&code);
|
||||
const FS_BASE: u64 = 0x7000;
|
||||
cpu.fs_base = FS_BASE;
|
||||
cpu.set(Register::Rbx, 0x1122_3344_5566_7788);
|
||||
// No region is mapped at FS_BASE, so the segment-adjusted address
|
||||
// FS_BASE + 8 is unmapped.
|
||||
|
||||
let result = engine.run(&mut cpu, &mut memory, 16);
|
||||
assert_eq!(
|
||||
result.exit_reason,
|
||||
ExitReason::MemoryFault(MemoryError::UnmappedAddress(FS_BASE + 8))
|
||||
);
|
||||
}
|
||||
}
|
||||
+18
-38
@@ -791,42 +791,17 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
|
||||
});
|
||||
}
|
||||
|
||||
// Map an RVA to a file offset.
|
||||
//
|
||||
// The offset is derived from the section header, so on a truncated file it
|
||||
// can point past the end of the buffer. Such an offset is not readable, so
|
||||
// it is reported as unmapped rather than returned and sliced later.
|
||||
let rva_to_offset = |rva: u32| -> Option<usize> {
|
||||
for sec in §ions {
|
||||
let max_span = std::cmp::max(sec.virtual_size, sec.raw_data_size);
|
||||
if rva >= sec.virtual_address && rva < sec.virtual_address.saturating_add(max_span) {
|
||||
let off_in_sec = (rva - sec.virtual_address) as usize;
|
||||
let off = sec.raw_data_ptr as usize + off_in_sec;
|
||||
if off >= bytes.len() {
|
||||
return None;
|
||||
}
|
||||
return Some(off);
|
||||
return Some(sec.raw_data_ptr as usize + off_in_sec);
|
||||
}
|
||||
}
|
||||
None
|
||||
};
|
||||
|
||||
// Read a NUL-terminated string that starts at `start`.
|
||||
//
|
||||
// Returns `None` when the string starts outside the buffer or is not
|
||||
// terminated, so a truncated file yields an unreadable name instead of a
|
||||
// slice that panics.
|
||||
let read_c_string = |start: usize| -> Option<String> {
|
||||
if start >= bytes.len() {
|
||||
return None;
|
||||
}
|
||||
let mut end = start;
|
||||
while end < bytes.len() && bytes[end] != 0 {
|
||||
end += 1;
|
||||
}
|
||||
Some(String::from_utf8_lossy(&bytes[start..end]).into_owned())
|
||||
};
|
||||
|
||||
// 1. Relocations Census
|
||||
let mut relocations = RelocationCensus {
|
||||
total_entries: 0,
|
||||
@@ -920,11 +895,14 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
|
||||
}
|
||||
desc_off += 20;
|
||||
|
||||
let dll_name = match rva_to_offset(name_rva).and_then(read_c_string) {
|
||||
Some(name) => name,
|
||||
// The name is outside the file or is not NUL-terminated
|
||||
// within it, which a truncated file can cause.
|
||||
None => "UNKNOWN.dll".to_string(),
|
||||
let dll_name = if let Some(no) = rva_to_offset(name_rva) {
|
||||
let mut end = no;
|
||||
while end < bytes.len() && bytes[end] != 0 {
|
||||
end += 1;
|
||||
}
|
||||
String::from_utf8_lossy(&bytes[no..end]).into_owned()
|
||||
} else {
|
||||
"UNKNOWN.dll".to_string()
|
||||
};
|
||||
|
||||
let category = ProbeReport::categorize_dll(&dll_name);
|
||||
@@ -947,13 +925,15 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
|
||||
format!("Ordinal#{}", val & 0xFFFF)
|
||||
} else {
|
||||
let hint_rva = (val & 0x7FFF_FFFF) as u32;
|
||||
// The hint is two bytes, so the name starts after it.
|
||||
match rva_to_offset(hint_rva)
|
||||
.and_then(|ho| ho.checked_add(2))
|
||||
.and_then(read_c_string)
|
||||
{
|
||||
Some(name) => name,
|
||||
None => "UNKNOWN_SYM".to_string(),
|
||||
if let Some(ho) = rva_to_offset(hint_rva) {
|
||||
let str_start = ho + 2;
|
||||
let mut str_end = str_start;
|
||||
while str_end < bytes.len() && bytes[str_end] != 0 {
|
||||
str_end += 1;
|
||||
}
|
||||
String::from_utf8_lossy(&bytes[str_start..str_end]).into_owned()
|
||||
} else {
|
||||
"UNKNOWN_SYM".to_string()
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
use xenora_loader::probe::{ProbeConfig, probe_pe_bytes};
|
||||
|
||||
/// The static probe must never panic on a truncated PE.
|
||||
///
|
||||
/// The fixture is truncated across its whole length, which covers the range
|
||||
/// where the import directory and the import names overlap the end of the
|
||||
/// file, and every other range where a name or thunk read computed from the
|
||||
/// section header can run past the buffer.
|
||||
#[test]
|
||||
fn probe_never_panics_on_truncated_input() {
|
||||
let pe = include_bytes!("../../../fixtures/pe/trusted-runner.exe");
|
||||
for len in 1..=pe.len() {
|
||||
let truncated = &pe[..len];
|
||||
// The probe may reject the file or report it with unreadable
|
||||
// imports, but it must not panic.
|
||||
let _ = probe_pe_bytes(truncated, &ProbeConfig::default());
|
||||
}
|
||||
}
|
||||
@@ -29,10 +29,13 @@ PYTHONPATH=scripts python3 -m unittest discover -s tests/release
|
||||
## Phase II CLIs
|
||||
|
||||
```sh
|
||||
PYTHONPATH=scripts python3 -m qa rdna2 inventory
|
||||
PYTHONPATH=scripts python3 -m qa rdna2 candidates --limit 50
|
||||
PYTHONPATH=scripts python3 -m qa rdna2 plan
|
||||
PYTHONPATH=scripts python3 -m qa rdna2 inventory --compact
|
||||
PYTHONPATH=scripts python3 -m qa rdna2 candidates --family SOP2 --status reuse-primitives --limit 50
|
||||
PYTHONPATH=scripts python3 -m qa rdna2 plan --limit 20 --compact
|
||||
PYTHONPATH=scripts python3 -m qa rdna2 manifests --status reuse-primitives --limit 10 --claims claims.json
|
||||
PYTHONPATH=scripts python3 -m qa rdna2 reconcile --compact
|
||||
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 bench-compare --baseline b.json --current c.json
|
||||
@@ -40,4 +43,6 @@ PYTHONPATH=scripts python3 -m release readiness --revision HEAD --live --binary
|
||||
```
|
||||
|
||||
RDNA2 planning is read-only over the AMD snapshot, semantic registry, decoder tables and
|
||||
`docs/status.toml`. Candidates are never counted as implemented forms.
|
||||
`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.
|
||||
+101
-11
@@ -8,6 +8,7 @@ import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from .bench_regress import IncompatibleComparison, compare_records, dumps_comparison, load_record
|
||||
from .bench_stats import export_json, human_report, summarize
|
||||
@@ -35,14 +36,21 @@ from .pr_validate import (
|
||||
merge_reports,
|
||||
)
|
||||
from .rdna2_plan import (
|
||||
build_manifests,
|
||||
classify_unsupported,
|
||||
compact_candidates,
|
||||
compact_inventory,
|
||||
compact_manifests,
|
||||
coverage_diff,
|
||||
discrepancies,
|
||||
dumps_candidates,
|
||||
dumps_inventory,
|
||||
load_inventories,
|
||||
parse_claims_file,
|
||||
plan_batches,
|
||||
reconcile_with_coverage_report,
|
||||
summarize_inventory,
|
||||
write_json,
|
||||
)
|
||||
from .coverage_history import historical_report, snapshot_inventory, write_snapshot
|
||||
from .stale_branch import classify_sync, format_sync_reports
|
||||
@@ -91,8 +99,21 @@ def main(argv: list[str] | None = None) -> int:
|
||||
v.add_argument("--allowed", action="append", default=[])
|
||||
|
||||
r = sub.add_parser("rdna2", help="read-only RDNA2 expansion planning")
|
||||
r.add_argument("action", choices=("inventory", "candidates", "plan", "discrepancies", "diff"))
|
||||
r.add_argument(
|
||||
"action",
|
||||
choices=("inventory", "candidates", "plan", "discrepancies", "diff", "manifests", "reconcile"),
|
||||
)
|
||||
r.add_argument("--limit", type=int, default=0)
|
||||
r.add_argument("--family", action="append", default=[], help="filter by encoding family")
|
||||
r.add_argument(
|
||||
"--status",
|
||||
action="append",
|
||||
default=[],
|
||||
help="filter: reuse-primitives|needs-primitives|needs-operand-rules",
|
||||
)
|
||||
r.add_argument("--claims", default="", help="JSON claims file to exclude overlapping work")
|
||||
r.add_argument("--compact", action="store_true", help="print compact summary to stdout")
|
||||
r.add_argument("--out", default="", help="write full JSON under this path (prefer artifacts/)")
|
||||
r.add_argument("--before", default="", help="JSON inventory for diff")
|
||||
r.add_argument("--after", default="", help="JSON inventory for diff")
|
||||
|
||||
@@ -199,24 +220,93 @@ def main(argv: list[str] | None = None) -> int:
|
||||
return Inventory(**{k: d[k] for k in (
|
||||
"identified", "declared", "decoder_supported", "reference_verified",
|
||||
"metal_verified", "unsupported", "by_family")})
|
||||
print(json.dumps(coverage_diff(inv(before), inv(after)), indent=2, sort_keys=True))
|
||||
payload = coverage_diff(inv(before), inv(after))
|
||||
if args.out:
|
||||
write_json(Path(args.out), payload)
|
||||
if args.compact or args.out:
|
||||
print(
|
||||
f"declared_delta={payload['declared_delta']} "
|
||||
f"unsupported_delta={payload['unsupported_delta']}"
|
||||
)
|
||||
else:
|
||||
print(json.dumps(payload, indent=2, sort_keys=True))
|
||||
return 0
|
||||
data = load_inventories(root)
|
||||
inv = summarize_inventory(data)
|
||||
exclude_families: list[str] = []
|
||||
claimed_paths: list[str] = []
|
||||
if args.claims:
|
||||
fams, paths = parse_claims_file(Path(args.claims))
|
||||
exclude_families = sorted(fams)
|
||||
claimed_paths = sorted(paths)
|
||||
limit = args.limit or None
|
||||
|
||||
def emit(payload: Any, compact_text: str, full_text: str | None = None) -> int:
|
||||
if args.out:
|
||||
write_json(Path(args.out), payload)
|
||||
if args.compact or args.out:
|
||||
print(compact_text, end="")
|
||||
elif full_text is not None:
|
||||
print(full_text, end="")
|
||||
else:
|
||||
print(json.dumps(payload, indent=2, sort_keys=True) + "\n", end="")
|
||||
return 0
|
||||
|
||||
if args.action == "inventory":
|
||||
print(dumps_inventory(inv), end="")
|
||||
return 0
|
||||
return emit(json.loads(dumps_inventory(inv)), compact_inventory(inv), dumps_inventory(inv))
|
||||
if args.action == "candidates":
|
||||
limit = args.limit or None
|
||||
print(dumps_candidates(classify_unsupported(data, limit=limit)), end="")
|
||||
return 0
|
||||
cands = classify_unsupported(
|
||||
data,
|
||||
limit=limit,
|
||||
families=args.family or None,
|
||||
statuses=args.status or None,
|
||||
exclude_families=exclude_families,
|
||||
)
|
||||
payload = json.loads(dumps_candidates(cands))
|
||||
return emit(payload, compact_candidates(cands), dumps_candidates(cands))
|
||||
if args.action == "plan":
|
||||
cands = classify_unsupported(data, limit=(args.limit or None))
|
||||
print(json.dumps(plan_batches(cands), indent=2, sort_keys=True))
|
||||
cands = classify_unsupported(
|
||||
data,
|
||||
limit=limit,
|
||||
families=args.family or None,
|
||||
statuses=args.status or None,
|
||||
exclude_families=exclude_families,
|
||||
)
|
||||
payload = plan_batches(cands)
|
||||
return emit(payload, compact_candidates(cands))
|
||||
if args.action == "manifests":
|
||||
cands = classify_unsupported(
|
||||
data,
|
||||
limit=None,
|
||||
families=args.family or None,
|
||||
statuses=args.status or ["reuse-primitives"],
|
||||
exclude_families=exclude_families,
|
||||
)
|
||||
manifests = build_manifests(
|
||||
cands,
|
||||
exclude_families=exclude_families,
|
||||
claimed_paths=claimed_paths,
|
||||
limit=limit,
|
||||
)
|
||||
payload = {
|
||||
"note": "Codex-ready planning manifests only; forms are not implemented.",
|
||||
"count": len(manifests),
|
||||
"manifests": manifests,
|
||||
}
|
||||
out = args.out or "artifacts/rdna2-manifests.json"
|
||||
write_json(Path(out), payload)
|
||||
print(compact_manifests(manifests), end="")
|
||||
print(f"wrote {out}")
|
||||
return 0
|
||||
if args.action == "discrepancies":
|
||||
print(json.dumps(discrepancies(data), indent=2, sort_keys=True))
|
||||
return 0
|
||||
payload = discrepancies(data)
|
||||
return emit(payload, f"discrepancies={len(payload)}\n")
|
||||
if args.action == "reconcile":
|
||||
payload = reconcile_with_coverage_report(root, data)
|
||||
return emit(
|
||||
payload,
|
||||
f"reconcile_ok={payload['ok']} mismatches={len(payload['mismatches'])}\n",
|
||||
)
|
||||
|
||||
if args.command == "cpu-coverage":
|
||||
report = build_cpu_report(root)
|
||||
|
||||
+278
-28
@@ -9,12 +9,13 @@ implemented forms.
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import runpy
|
||||
import tomllib
|
||||
from collections import defaultdict
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from typing import Any, Iterable, Sequence
|
||||
|
||||
|
||||
def _load_coverage_module(root: Path):
|
||||
@@ -46,6 +47,8 @@ class Candidate:
|
||||
missing_effects: list[str] = field(default_factory=list)
|
||||
spec_refs: list[dict[str, Any]] = field(default_factory=list)
|
||||
priority_batch: str = "unclassified"
|
||||
priority_rank: int = 99
|
||||
status: str = "unsupported"
|
||||
notes: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@@ -60,6 +63,27 @@ class Inventory:
|
||||
by_family: dict[str, dict[str, int]]
|
||||
|
||||
|
||||
# Conventional GPU semantic-expansion file set for Codex manifests only.
|
||||
# Planning does not claim or edit these paths.
|
||||
DEFAULT_PERMITTED_FILES = (
|
||||
"crates/isa/semantics/rdna2.toml",
|
||||
"crates/isa/src/semantics_gen.rs",
|
||||
"crates/decoder/src/lib.rs",
|
||||
"crates/shader/",
|
||||
"crates/ref/",
|
||||
"tests/validation/",
|
||||
"docs/status.toml",
|
||||
"CHANGELOG.md",
|
||||
)
|
||||
|
||||
DEFAULT_ACCEPTANCE = (
|
||||
"cargo test --locked -p xenora-ref",
|
||||
"cargo test --locked -p xenora-semantic-review",
|
||||
"scripts/test-gpu.sh",
|
||||
"python3 scripts/audit/semantic_coverage.py --check",
|
||||
)
|
||||
|
||||
|
||||
def load_inventories(root: Path) -> dict[str, Any]:
|
||||
sc = _load_coverage_module(root)
|
||||
identified = sc["load_snapshot"](root)
|
||||
@@ -146,52 +170,65 @@ def _declared_ops(registry: dict[str, Any]) -> set[str]:
|
||||
return {form.get("operation") for form in registry.get("form", []) if form.get("operation")}
|
||||
|
||||
|
||||
def _declared_rules(registry: dict[str, Any]) -> set[str]:
|
||||
return set(registry.get("operand_rules", {}))
|
||||
def _batch_for(family: str, family_rule_names: list[str], ops: set[str]) -> tuple[str, int, str]:
|
||||
"""Return (batch_id, priority_rank, status). Lower rank is higher priority."""
|
||||
if family_rule_names and ops:
|
||||
return f"batch-{family.lower()}-reuse-primitives", 0, "reuse-primitives"
|
||||
if family_rule_names:
|
||||
return f"batch-{family.lower()}-needs-primitives", 1, "needs-primitives"
|
||||
return f"batch-{family.lower()}-needs-operand-rules", 2, "needs-operand-rules"
|
||||
|
||||
|
||||
def classify_unsupported(data: dict[str, Any], *, limit: int | None = None) -> list[Candidate]:
|
||||
def classify_unsupported(
|
||||
data: dict[str, Any],
|
||||
*,
|
||||
limit: int | None = None,
|
||||
families: Sequence[str] | None = None,
|
||||
statuses: Sequence[str] | None = None,
|
||||
exclude_families: Sequence[str] | None = None,
|
||||
) -> list[Candidate]:
|
||||
"""Build candidates for identified forms that are not registry-declared.
|
||||
|
||||
Does not infer behaviour from the mnemonic. Width/type/layout are filled
|
||||
only when already present on related declared forms in the same family, or
|
||||
left null.
|
||||
left null. Results are sorted by priority_rank then family/name.
|
||||
"""
|
||||
identified = data["identified"]
|
||||
declared = data["declared"]
|
||||
registry = data["registry"]
|
||||
rules = data["rules"]
|
||||
ops = _declared_ops(registry)
|
||||
rule_names = _declared_rules(registry)
|
||||
family_rules = defaultdict(list)
|
||||
family_widths = defaultdict(set)
|
||||
family_types = defaultdict(set)
|
||||
family_widths: dict[str, set[int]] = defaultdict(set)
|
||||
family_types: dict[str, set[str]] = defaultdict(set)
|
||||
for form in registry.get("form", []):
|
||||
family_rules[form["family"]].append(form.get("operands"))
|
||||
if "width" in form:
|
||||
family_widths[form["family"]].add(form["width"])
|
||||
if "signedness" in form:
|
||||
family_types[form["family"]].add(form["signedness"])
|
||||
|
||||
family_filter = {f.upper() for f in families} if families else None
|
||||
status_filter = {s for s in statuses} if statuses else None
|
||||
excluded = {f.upper() for f in (exclude_families or ())}
|
||||
|
||||
candidates: list[Candidate] = []
|
||||
unsupported = sorted(set(identified) - set(declared))
|
||||
if limit is not None:
|
||||
unsupported = unsupported[:limit]
|
||||
for family, name in unsupported:
|
||||
if family_filter is not None and family.upper() not in family_filter:
|
||||
continue
|
||||
if family.upper() in excluded:
|
||||
continue
|
||||
opcode = identified[(family, name)]
|
||||
reusable = sorted(op for op in ops if op) # available primitives, not guessed mapping
|
||||
missing_rules = []
|
||||
# If the family has no operand rule yet, record that gap.
|
||||
reusable = sorted(op for op in ops if op)
|
||||
family_rule_names = [n for n, (fam, _) in rules.items() if fam == family]
|
||||
missing_rules = []
|
||||
if not family_rule_names:
|
||||
missing_rules.append(f"no operand_rules for family {family}")
|
||||
missing_effects = []
|
||||
# Architectural effects are unknown until specified; flag absence.
|
||||
missing_effects.append("scc/vcc/exec effects unspecified until registry declaration")
|
||||
widths = sorted(family_widths.get(family, []))
|
||||
types = sorted(family_types.get(family, []))
|
||||
layout = family_rule_names[0] if len(family_rule_names) == 1 else None
|
||||
batch = _batch_for(family, family_rule_names, ops)
|
||||
batch, rank, status = _batch_for(family, family_rule_names, ops)
|
||||
if status_filter is not None and status not in status_filter:
|
||||
continue
|
||||
candidates.append(Candidate(
|
||||
family=family,
|
||||
name=name,
|
||||
@@ -201,25 +238,22 @@ def classify_unsupported(data: dict[str, Any], *, limit: int | None = None) -> l
|
||||
operand_layout=layout,
|
||||
reusable_primitives=reusable[:20],
|
||||
missing_operand_rules=missing_rules,
|
||||
missing_effects=missing_effects,
|
||||
missing_effects=["scc/vcc/exec effects unspecified until registry declaration"],
|
||||
spec_refs=[{"document": "xml", "note": "identity from pinned AMD snapshot only"}],
|
||||
priority_batch=batch,
|
||||
priority_rank=rank,
|
||||
status=status,
|
||||
notes=[
|
||||
"behaviour must come from the public AMD guide, never the mnemonic",
|
||||
"candidate is not implemented",
|
||||
],
|
||||
))
|
||||
candidates.sort(key=lambda c: (c.priority_rank, c.family, c.name, c.opcode))
|
||||
if limit is not None:
|
||||
candidates = candidates[:limit]
|
||||
return candidates
|
||||
|
||||
|
||||
def _batch_for(family: str, family_rule_names: list[str], ops: set[str]) -> str:
|
||||
if family_rule_names and ops:
|
||||
return f"batch-{family.lower()}-reuse-primitives"
|
||||
if family_rule_names:
|
||||
return f"batch-{family.lower()}-needs-primitives"
|
||||
return f"batch-{family.lower()}-needs-operand-rules"
|
||||
|
||||
|
||||
def plan_batches(candidates: list[Candidate]) -> dict[str, list[dict[str, Any]]]:
|
||||
batches: dict[str, list[dict[str, Any]]] = defaultdict(list)
|
||||
for cand in candidates:
|
||||
@@ -227,6 +261,7 @@ def plan_batches(candidates: list[Candidate]) -> dict[str, list[dict[str, Any]]]
|
||||
"family": cand.family,
|
||||
"name": cand.name,
|
||||
"opcode": cand.opcode,
|
||||
"status": cand.status,
|
||||
"missing_operand_rules": cand.missing_operand_rules,
|
||||
"reusable_primitives": cand.reusable_primitives[:5],
|
||||
})
|
||||
@@ -275,6 +310,179 @@ def discrepancies(data: dict[str, Any]) -> list[dict[str, str]]:
|
||||
return issues
|
||||
|
||||
|
||||
def reconcile_with_coverage_report(root: Path, data: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Compare planner inventory to canonical semantic_coverage collect_coverage.
|
||||
|
||||
Does not inflate planner counts. Reports per-family deltas only.
|
||||
"""
|
||||
sc = data["sc"]
|
||||
identified = data["identified"]
|
||||
registry = data["registry"]
|
||||
decoder = data["decoder"]
|
||||
status = data["status"]
|
||||
counts, _rules = sc["collect_coverage"](identified, registry, decoder, status)
|
||||
# collect_coverage tuple per family:
|
||||
# Identified, Encoding-validated, Declared, Decoder-supported, IR, MSL,
|
||||
# Reference-verified, Metal-verified, Unsupported operand variants
|
||||
inv = summarize_inventory(data)
|
||||
mismatches: list[dict[str, Any]] = []
|
||||
for family, values in sorted(counts.items()):
|
||||
canon_identified, _enc, canon_declared, canon_decoder, _ir, _msl, canon_ref, canon_metal, _u = values
|
||||
bucket = inv.by_family.get(family, {})
|
||||
pairs = (
|
||||
("identified", canon_identified, bucket.get("identified", 0)),
|
||||
("declared", canon_declared, bucket.get("declared", 0)),
|
||||
("decoder", canon_decoder, bucket.get("decoder", 0)),
|
||||
("reference", canon_ref, bucket.get("reference", 0)),
|
||||
("metal", canon_metal, bucket.get("metal", 0)),
|
||||
)
|
||||
for field_name, canon, plan in pairs:
|
||||
if canon != plan:
|
||||
mismatches.append({
|
||||
"family": family,
|
||||
"field": field_name,
|
||||
"canonical": canon,
|
||||
"planner": plan,
|
||||
"delta": plan - canon,
|
||||
})
|
||||
return {
|
||||
"ok": not mismatches,
|
||||
"canonical_totals": {
|
||||
"identified": sum(v[0] for v in counts.values()),
|
||||
"declared": sum(v[2] for v in counts.values()),
|
||||
"decoder_supported": sum(v[3] for v in counts.values()),
|
||||
"reference_verified": sum(v[6] for v in counts.values()),
|
||||
"metal_verified": sum(v[7] for v in counts.values()),
|
||||
},
|
||||
"planner_totals": {
|
||||
"identified": inv.identified,
|
||||
"declared": inv.declared,
|
||||
"decoder_supported": inv.decoder_supported,
|
||||
"reference_verified": inv.reference_verified,
|
||||
"metal_verified": inv.metal_verified,
|
||||
},
|
||||
"mismatches": mismatches,
|
||||
"note": "Planner counts are not adjusted to match; mismatches must be investigated.",
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ClaimScope:
|
||||
"""One active claim. Families exclude those families; path-only claims
|
||||
block candidates whose default permitted files overlap the claimed paths.
|
||||
A claim that lists both families and paths excludes only the families —
|
||||
the paths document the claim and do not blanket-block other families.
|
||||
"""
|
||||
families: frozenset[str] = frozenset()
|
||||
paths: frozenset[str] = frozenset()
|
||||
|
||||
|
||||
def parse_claims_file(path: Path) -> tuple[set[str], set[str]]:
|
||||
"""Load excluded families and path-only claim prefixes.
|
||||
|
||||
Expected shape: {"claims":[{"families":["VOP2"], "paths":["crates/isa/**"]}, ...]}
|
||||
or a bare list of such objects.
|
||||
|
||||
Returns (exclude_families, path_only_claimed_paths). Path prefixes from
|
||||
claims that also name families are ignored for blocking so a SOP2+isa
|
||||
claim does not suppress every other family's manifests.
|
||||
"""
|
||||
scopes = load_claim_scopes(path)
|
||||
families: set[str] = set()
|
||||
path_only: set[str] = set()
|
||||
for scope in scopes:
|
||||
families.update(scope.families)
|
||||
if scope.families:
|
||||
continue
|
||||
path_only.update(scope.paths)
|
||||
return families, path_only
|
||||
|
||||
|
||||
def load_claim_scopes(path: Path) -> list[ClaimScope]:
|
||||
raw = json.loads(path.read_text(encoding="utf-8"))
|
||||
items = raw["claims"] if isinstance(raw, dict) and "claims" in raw else raw
|
||||
if not isinstance(items, list):
|
||||
raise ValueError("claims file must be a list or {\"claims\": [...]}")
|
||||
scopes: list[ClaimScope] = []
|
||||
for item in items:
|
||||
fams = frozenset(str(f).upper() for f in (item.get("families") or []))
|
||||
paths = frozenset(str(p) for p in (item.get("paths") or []))
|
||||
if not fams and not paths:
|
||||
continue
|
||||
scopes.append(ClaimScope(families=fams, paths=paths))
|
||||
return scopes
|
||||
|
||||
|
||||
def claims_block_candidate(cand: Candidate, claimed_paths: set[str]) -> bool:
|
||||
"""True if a path-only claim overlaps the default GPU expansion files."""
|
||||
if not claimed_paths:
|
||||
return False
|
||||
for permitted in DEFAULT_PERMITTED_FILES:
|
||||
for claimed in claimed_paths:
|
||||
if _path_overlap(permitted, claimed):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _path_overlap(a: str, b: str) -> bool:
|
||||
a = a.rstrip("/")
|
||||
b = b.rstrip("/")
|
||||
if a.endswith("/**"):
|
||||
a = a[:-3].rstrip("/")
|
||||
if b.endswith("/**"):
|
||||
b = b[:-3].rstrip("/")
|
||||
return a == b or a.startswith(b + "/") or b.startswith(a + "/")
|
||||
|
||||
|
||||
def build_manifests(
|
||||
candidates: list[Candidate],
|
||||
*,
|
||||
exclude_families: Sequence[str] | None = None,
|
||||
claimed_paths: Sequence[str] | None = None,
|
||||
limit: int | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Deterministic Codex-ready implementation manifests.
|
||||
|
||||
Prioritises reuse-primitives, then needs-primitives, then needs-operand-rules.
|
||||
Excludes active claim families and path-only claims. Does not invent semantics.
|
||||
"""
|
||||
excluded = {f.upper() for f in (exclude_families or ())}
|
||||
claimed = set(claimed_paths or ())
|
||||
manifests: list[dict[str, Any]] = []
|
||||
for cand in candidates:
|
||||
if cand.family.upper() in excluded:
|
||||
continue
|
||||
if claims_block_candidate(cand, claimed):
|
||||
continue
|
||||
deps: list[str] = []
|
||||
if cand.status == "needs-operand-rules":
|
||||
deps.append(f"define operand_rules for family {cand.family}")
|
||||
if cand.status == "needs-primitives":
|
||||
deps.append("add registry operation primitive before declaring this form")
|
||||
if cand.status == "reuse-primitives":
|
||||
deps.append("reuse existing registry primitives/operand rules; declare form from AMD guide")
|
||||
deps.append("do not infer behaviour from the mnemonic")
|
||||
manifest = {
|
||||
"id": f"{cand.family}:{cand.name}",
|
||||
"instruction": {
|
||||
"family": cand.family,
|
||||
"name": cand.name,
|
||||
"opcode": cand.opcode,
|
||||
},
|
||||
"priority_rank": cand.priority_rank,
|
||||
"status": cand.status,
|
||||
"dependencies": deps,
|
||||
"specification_references": cand.spec_refs,
|
||||
"permitted_files": list(DEFAULT_PERMITTED_FILES),
|
||||
"acceptance_tests": list(DEFAULT_ACCEPTANCE),
|
||||
"notes": list(cand.notes),
|
||||
}
|
||||
manifests.append(manifest)
|
||||
if limit is not None and len(manifests) >= limit:
|
||||
break
|
||||
return manifests
|
||||
|
||||
|
||||
def coverage_diff(before: Inventory, after: Inventory) -> dict[str, Any]:
|
||||
return {
|
||||
"identified_delta": after.identified - before.identified,
|
||||
@@ -299,3 +507,45 @@ def dumps_candidates(candidates: list[Candidate]) -> str:
|
||||
|
||||
def dumps_inventory(inv: Inventory) -> str:
|
||||
return json.dumps(asdict(inv), indent=2, sort_keys=True) + "\n"
|
||||
|
||||
|
||||
def compact_inventory(inv: Inventory) -> str:
|
||||
lines = [
|
||||
f"identified={inv.identified} declared={inv.declared} "
|
||||
f"decoder={inv.decoder_supported} unsupported={inv.unsupported} "
|
||||
f"ref={inv.reference_verified} metal={inv.metal_verified}",
|
||||
]
|
||||
for family, bucket in inv.by_family.items():
|
||||
if bucket.get("unsupported", 0) == 0 and bucket.get("declared", 0) == 0:
|
||||
continue
|
||||
lines.append(
|
||||
f" {family}: id={bucket['identified']} decl={bucket['declared']} "
|
||||
f"dec={bucket['decoder']} unsup={bucket['unsupported']}"
|
||||
)
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def compact_candidates(candidates: Sequence[Candidate]) -> str:
|
||||
lines = [f"candidates={len(candidates)}"]
|
||||
for cand in candidates:
|
||||
lines.append(
|
||||
f" [{cand.priority_rank}:{cand.status}] {cand.family}:{cand.name} "
|
||||
f"op=0x{cand.opcode:x} batch={cand.priority_batch}"
|
||||
)
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def compact_manifests(manifests: Sequence[dict[str, Any]]) -> str:
|
||||
lines = [f"manifests={len(manifests)}"]
|
||||
for item in manifests:
|
||||
inst = item["instruction"]
|
||||
lines.append(
|
||||
f" [{item['priority_rank']}:{item['status']}] {inst['family']}:{inst['name']} "
|
||||
f"deps={len(item['dependencies'])}"
|
||||
)
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def write_json(path: Path, payload: Any) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
||||
@@ -32,6 +32,27 @@ class CliSmoke(unittest.TestCase):
|
||||
data = json.loads(inv.stdout)
|
||||
self.assertGreater(data["identified"], data["declared"])
|
||||
|
||||
compact = run("qa", "rdna2", "candidates", "--status", "reuse-primitives", "--limit", "2", "--compact")
|
||||
self.assertEqual(compact.returncode, 0, compact.stderr)
|
||||
self.assertIn("candidates=2", compact.stdout)
|
||||
|
||||
recon = run("qa", "rdna2", "reconcile", "--compact")
|
||||
self.assertEqual(recon.returncode, 0, recon.stderr)
|
||||
self.assertIn("reconcile_ok=", recon.stdout)
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
out = Path(tmp) / "manifests.json"
|
||||
man = run(
|
||||
"qa", "rdna2", "manifests",
|
||||
"--status", "reuse-primitives",
|
||||
"--limit", "2",
|
||||
"--out", str(out),
|
||||
)
|
||||
self.assertEqual(man.returncode, 0, man.stderr)
|
||||
payload = json.loads(out.read_text(encoding="utf-8"))
|
||||
self.assertEqual(payload["count"], 2)
|
||||
self.assertIn("not implemented", payload["note"].lower())
|
||||
|
||||
def test_release_readiness_cli_negative(self):
|
||||
r = run(
|
||||
"release", "readiness",
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from qa.rdna2_plan import (
|
||||
Inventory,
|
||||
build_manifests,
|
||||
classify_unsupported,
|
||||
compact_candidates,
|
||||
compact_inventory,
|
||||
coverage_diff,
|
||||
discrepancies,
|
||||
dumps_candidates,
|
||||
load_inventories,
|
||||
parse_claims_file,
|
||||
plan_batches,
|
||||
reconcile_with_coverage_report,
|
||||
summarize_inventory,
|
||||
)
|
||||
|
||||
@@ -40,9 +46,85 @@ class Rdna2Plan(unittest.TestCase):
|
||||
batches = plan_batches(cands)
|
||||
self.assertTrue(batches)
|
||||
|
||||
def test_discrepancies_and_diff(self):
|
||||
issues = discrepancies(self.data)
|
||||
self.assertIsInstance(issues, list)
|
||||
def test_family_status_limit_and_priority(self):
|
||||
reuse = classify_unsupported(
|
||||
self.data, families=["SOP2"], statuses=["reuse-primitives"], limit=5
|
||||
)
|
||||
self.assertLessEqual(len(reuse), 5)
|
||||
for cand in reuse:
|
||||
self.assertEqual(cand.family, "SOP2")
|
||||
self.assertEqual(cand.status, "reuse-primitives")
|
||||
self.assertEqual(cand.priority_rank, 0)
|
||||
needs_rules = classify_unsupported(
|
||||
self.data, statuses=["needs-operand-rules"], limit=3
|
||||
)
|
||||
for cand in needs_rules:
|
||||
self.assertEqual(cand.status, "needs-operand-rules")
|
||||
self.assertEqual(cand.priority_rank, 2)
|
||||
# Priority ordering: reuse before needs-operand-rules when unfiltered.
|
||||
mixed = classify_unsupported(self.data, limit=20)
|
||||
ranks = [c.priority_rank for c in mixed]
|
||||
self.assertEqual(ranks, sorted(ranks))
|
||||
|
||||
def test_manifests_exclude_claims_and_stay_deterministic(self):
|
||||
cands = classify_unsupported(self.data, statuses=["reuse-primitives"], limit=50)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
claims = Path(tmp) / "claims.json"
|
||||
claims.write_text(
|
||||
json.dumps({"claims": [{"families": ["SOP2"], "paths": ["crates/isa/**"]}]}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
fams, paths = parse_claims_file(claims)
|
||||
self.assertIn("SOP2", fams)
|
||||
# Family+path claims must not path-block every other family.
|
||||
self.assertEqual(paths, set())
|
||||
manifests = build_manifests(
|
||||
cands, exclude_families=sorted(fams), claimed_paths=sorted(paths), limit=5
|
||||
)
|
||||
self.assertGreater(len(manifests), 0)
|
||||
for item in manifests:
|
||||
self.assertNotEqual(item["instruction"]["family"], "SOP2")
|
||||
self.assertIn("permitted_files", item)
|
||||
self.assertIn("acceptance_tests", item)
|
||||
self.assertIn("specification_references", item)
|
||||
self.assertIn("dependencies", item)
|
||||
again = build_manifests(
|
||||
cands, exclude_families=sorted(fams), claimed_paths=sorted(paths), limit=5
|
||||
)
|
||||
self.assertEqual(manifests, again)
|
||||
|
||||
path_only = Path(tmp) / "path_only.json"
|
||||
path_only.write_text(
|
||||
json.dumps({"claims": [{"paths": ["crates/isa/**"]}]}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
_, path_claims = parse_claims_file(path_only)
|
||||
self.assertIn("crates/isa/**", path_claims)
|
||||
blocked = build_manifests(
|
||||
cands, claimed_paths=sorted(path_claims), limit=5
|
||||
)
|
||||
self.assertEqual(blocked, [])
|
||||
|
||||
def test_reconcile_does_not_inflate_coverage(self):
|
||||
report = reconcile_with_coverage_report(ROOT, self.data)
|
||||
self.assertIn("mismatches", report)
|
||||
self.assertEqual(
|
||||
report["planner_totals"]["identified"],
|
||||
report["canonical_totals"]["identified"],
|
||||
)
|
||||
# Declared/decoder may differ in representation but planner must not
|
||||
# silently bump counts to hide mismatches.
|
||||
before = self.inv.declared
|
||||
_ = reconcile_with_coverage_report(ROOT, self.data)
|
||||
after = summarize_inventory(self.data).declared
|
||||
self.assertEqual(before, after)
|
||||
self.assertTrue(report["ok"] or isinstance(report["mismatches"], list))
|
||||
|
||||
def test_compact_helpers_and_diff(self):
|
||||
text = compact_inventory(self.inv)
|
||||
self.assertIn("identified=", text)
|
||||
cands = classify_unsupported(self.data, limit=2)
|
||||
self.assertIn("candidates=2", compact_candidates(cands))
|
||||
before = Inventory(
|
||||
identified=self.inv.identified,
|
||||
declared=self.inv.declared - 1 if self.inv.declared else 0,
|
||||
@@ -54,6 +136,7 @@ class Rdna2Plan(unittest.TestCase):
|
||||
)
|
||||
delta = coverage_diff(before, self.inv)
|
||||
self.assertEqual(delta["declared_delta"], self.inv.declared - before.declared)
|
||||
self.assertIsInstance(discrepancies(self.data), list)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in new issue
Block a user