Compare commits

...
Author SHA1 Message Date
Ranveer Soni 9d83e09aa6 feat(qa): tighten RDNA2 planning filters, manifests and claim exclusion.
Add family/status filters, compact output, Codex manifests, path-only vs family claim scoping, and coverage reconcile without inflating counts.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:56:13 +05:30
Ranveer Soni 3bdc43d3ad Merge pull request #281 from Swastickc/task/66-movsx-movzx
loader: implement MOVZX and MOVSX in the interpreter (#66)
2026-11-24 17:47:21 +05:30
Ranveer Soni fa434d7174 Merge pull request #282 from Swastickc/task/279-native-app-gate5
app: persistent GPU resources, dynamic texture updates, and resource retirement (#279)
2026-11-24 17:46:43 +05:30
Ranveer Soni ed657ad802 Merge pull request #280 from Swastickc/task/72-segment-override
loader: add the FS and GS segment base to RIP-relative operands in the DBT (#72)
2026-11-24 17:46:25 +05:30
Ranveer Soni b49ec43ddc Merge branch 'main' into task/72-segment-override 2026-11-24 17:46:11 +05:30
Ranveer Soni d00c787544 Merge pull request #283 from Swastickc/task/65-movsx-dest-width
loader: clear the upper half of a 32-bit MOVSX destination (#65)
2026-11-24 17:45:40 +05:30
Swastick Chowdhury f6dfe58695 loader: implement MOVZX and MOVSX in the interpreter (#66)
The native DBT translator implements the four extension opcodes MOVZX r32/r64,
r/m8 (0F B6), MOVZX r32/r64, r/m16 (0F B7), MOVSX r32/r64, r/m8 (0F BE) and
MOVSX r32/r64, r/m16 (0F BF), with both register and memory source operands.
The interpreter implemented none of them: its 0x0F handler covered only SYSCALL
(0F 05) and BSWAP (0F C8..CF), so any of the four opcodes exited with
IllegalInstruction and the two execution paths accepted different instruction
sets for the same bytes.

Implement them in the interpreter:

- The source width follows the opcode, so 0F B6 and 0F BE read one byte and
  0F B7 and 0F BF read one word.
- The destination width follows REX.W. Without REX.W the destination is 32
  bits and its upper half is cleared; with REX.W it is 64 bits.
- MOVZX zero-extends, so both destination widths hold the same value.
- MOVSX sign-extends to the destination width, so a 32-bit destination keeps
  the sign in bits 31:0 with the upper half cleared, while a 64-bit
  destination keeps the sign extension across all 64 bits.

The effective-address computation shared by the memory forms of MOV,
MOVZX and MOVSX is extracted into an `effective_address` method so both
instruction families use one implementation. That is a pure refactor: the
address computation itself is unchanged.

Add six regression tests in crates/loader/tests/bootstrap.rs covering the
register and the memory source forms independently, both destination widths,
and the sign-extension boundary values. Every encoding was produced by LLVM
23.1.6 llvm-mc -show-encoding and the expected values follow the Intel SDM
rules for MOVZX and MOVSX.

All six tests fail against the unmodified interpreter and pass with this
change.

A related defect in the native DBT translator was found while writing these
tests: its MOVSX paths sign-extend to 64 bits unconditionally, so a 32-bit
destination keeps the sign extension in bits 63:32 instead of having them
cleared. That belongs to #65, which permits the translator files, and is
reported there rather than fixed here.

Closes #66

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 17:37:02 +05:30
Swastick Chowdhury b12aa502a2 loader: add the FS and GS segment base to RIP-relative operands in the DBT (#72)
The native DBT translator computed the RIP-relative address and passed it
straight to the memory helper, without adding the FS or GS segment base. The
non-RIP-relative path went through emit_effective_address, which does add it,
so the two paths in the same translator disagreed with each other, and the
interpreter in crates/loader/src/cpu.rs disagreed with both.

Per the Intel SDM Volume 3A, section 3.4.4, "When FS and GS segment overrides
are used in 64-bit mode, their respective base addresses are used in the
linear address calculation: (FS or GS).base + index + displacement", and the
AMD64 Architecture Programmer's Manual Volume 1, section 2.2.3.3, "Use of the
FS or GS prefix causes their respective segment bases to be added to the
effective address calculation." The base is added for every addressing form,
so the RIP-relative form needs it too.

The segment base is a runtime guest value, so it cannot be folded into the
translation-time immediate. The addition is factored into emit_segment_base,
which reads the base from the guest CPU state at run time, and is now called
from the RIP-relative MOV paths as well as from emit_effective_address.

Add six regression tests in the dbt test module:

- fs_segment_override_adds_the_fs_base_to_the_address: a segment-relative
  store and load land at the FS base plus the displacement, not at the bare
  displacement.
- gs_segment_override_adds_the_gs_base_to_the_address: the GS base is used,
  and a distinct FS base is left untouched.
- rip_relative_segment_override_adds_the_segment_base: the RIP-relative form
  adds the segment base. This test fails without the fix.
- segment_relative_access_to_an_unmapped_address_faults: a segment-relative
  access outside the mapped regions faults and reports the segment-adjusted
  address.
- interpreter_and_native_dbt_agree_on_segment_relative_addressing: the same
  program runs through the interpreter and the native DBT and produces the same
  state and the same memory writes.
- redundant_fs_and_gs_overrides_are_handled_the_same_by_both_paths: an
  instruction carrying both an FS and a GS override is architecturally
  undefined, so this pins the local rule that both paths prefer GS and that
  they agree with each other.

Every encoding was produced by LLVM 23.1.6 llvm-mc -show-encoding, and the
expected addresses were derived from the SDM rule above.

Closes #72

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 17:36:38 +05:30
Swastick Chowdhury 20780eab24 loader: clear the upper half of a 32-bit MOVSX destination (#65)
The native DBT translator sign-extended to 64 bits unconditionally and stored
the full 64-bit result, so a 32-bit MOVSX destination kept the sign extension
in bits 63:32 instead of having them cleared.

Before, both MOVSX paths did this:

    asm.sxtb_64(X9, X9);   // or sxth_64
    asm.str_uoff_64(X9, X19, (reg_idx as u32) * 8);

`sxtb_64` is `SBFM Xd, Xn, #0, #7`, which sign-extends the byte to 64 bits,
and `str_uoff_64` writes all 64 bits of the destination register.

That is correct for the REX.W form `movsbq rax, bl`, but the Intel SDM
requires a 32-bit result for the 32-bit destination form `movsbl eax, bl`. The
translator therefore left `rax = 0xFFFFFFFFFFFFFFFF` where the architecture
requires `rax = 0x00000000FFFFFFFF`.

Select the sign-extension width from REX.W:

- REX.W set: keep the 64-bit extension, which is already correct.
- REX.W clear: sign-extend to 32 bits, which also clears bits 63:32 of the
  destination because the 32-bit form writes a W register.

This needs two new assembler instructions, `sxtb_32` and `sxth_32`, which are
the 32-bit forms of the existing `sxtb_64` and `sxth_64`:

    sxtb_32: SBFM Wd, Wn, #0, #7   (0x13001c00)
    sxth_32: SBFM Wd, Wn, #0, #15  (0x13003c00)

Both encodings were confirmed against LLVM 23.1.6 `llvm-mc -triple=aarch64
-show-encoding`.

The MOVZX paths are unchanged: a zero extension produces the same value at
both destination widths, because the 32-bit form already clears the upper half.

Add three regression tests in the dbt test module covering the register and
memory source forms and the byte and word sources, each at both destination
widths. Every encoding was produced by LLVM 23.1.6 llvm-mc -show-encoding and
the expected values follow the Intel SDM rules for MOVSX.

All three tests fail against the unmodified translator and pass with this
change.

Closes #65

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 17:35:49 +05:30
10 changed files with 1016 additions and 84 deletions

No files matched your search

+3
View File
@@ -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.
+16
View File
@@ -183,11 +183,27 @@ impl Arm64Assembler {
self.emit(0x93401c00 | ((wn as u32 & 0x1f) << 5) | (xd as u32 & 0x1f));
}
/// SXTB (32-bit/sign-extended): SXTB Wd, Wn (SBFM Wd, Wn, #0, #7)
///
/// Writing the 32-bit destination form clears bits 63:32 of the
/// destination register, which is what a 32-bit x86 destination requires.
pub fn sxtb_32(&mut self, wd: u8, wn: u8) {
self.emit(0x13001c00 | ((wn as u32 & 0x1f) << 5) | (wd as u32 & 0x1f));
}
/// SXTH (64-bit/sign-extended): SXTH Xd, Wn (SBFM Xd, Xn, #0, #15)
pub fn sxth_64(&mut self, xd: u8, wn: u8) {
self.emit(0x93403c00 | ((wn as u32 & 0x1f) << 5) | (xd as u32 & 0x1f));
}
/// SXTH (32-bit/sign-extended): SXTH Wd, Wn (SBFM Wd, Wn, #0, #15)
///
/// Writing the 32-bit destination form clears bits 63:32 of the
/// destination register, which is what a 32-bit x86 destination requires.
pub fn sxth_32(&mut self, wd: u8, wn: u8) {
self.emit(0x13003c00 | ((wn as u32 & 0x1f) << 5) | (wd as u32 & 0x1f));
}
/// ADD (extended/shifted register, 32-bit): ADD Wd, Wn, Wm
pub fn add_reg_32(&mut self, wd: u8, wn: u8, wm: u8) {
self.emit(
+116 -30
View File
@@ -466,6 +466,12 @@ impl<'a> Interpreter<'a> {
0x0F => match self.fetch_u8()? {
0x05 => Ok(Some(ExitReason::Syscall(self.cpu.get(Register::Rax)))),
// MOVZX r32/r64, r/m8 (0xB6), MOVZX r32/r64, r/m16 (0xB7),
// MOVSX r32/r64, r/m8 (0xBE), MOVSX r32/r64, r/m16 (0xBF).
op @ (0xB6 | 0xB7 | 0xBE | 0xBF) => {
let modrm = self.fetch_u8()?;
self.execute_mov_ext(modrm, &prefixes, op)
}
op @ 0xC8..=0xCF => {
let reg = Register::from_index((op & 7) | (u8::from(prefixes.rex_b) << 3));
let value = self.cpu.get(reg);
@@ -722,6 +728,72 @@ impl<'a> Interpreter<'a> {
Ok((Register::from_index(reg_idx), Register::from_index(rm_idx)))
}
/// Execute a MOVZX or MOVSX extension instruction.
///
/// `op` is the second opcode byte: `0xB6` extends a byte, `0xB7` extends
/// a word, `0xBE` sign-extends a byte and `0xBF` sign-extends a word.
///
/// The source width follows the opcode and the destination width follows
/// REX.W: without REX.W the destination is 32 bits and its upper half is
/// cleared, and with REX.W it is 64 bits. MOVSX sign-extends to the
/// destination width, so a 32-bit destination keeps the sign in bits
/// 31:0 and a zeroed upper half, while a 64-bit destination keeps the
/// sign extension across all 64 bits.
fn execute_mov_ext(
&mut self,
modrm: u8,
prefixes: &Prefixes,
op: u8,
) -> Result<Option<ExitReason>, ExitReason> {
let mode = (modrm >> 6) & 3;
let reg_idx = ((modrm >> 3) & 7) + if prefixes.rex_r { 8 } else { 0 };
let rm_idx = (modrm & 7) + if prefixes.rex_b { 8 } else { 0 };
let reg = Register::from_index(reg_idx);
let is_word = op == 0xB7 || op == 0xBF;
let is_signed = op == 0xBE || op == 0xBF;
let source = if mode == 3 {
// Register source: only the low 8 or 16 bits are read.
let value = self.cpu.get(Register::from_index(rm_idx));
if is_word {
value as u16 as u64
} else {
value as u8 as u64
}
} else {
let address = self.effective_address(modrm, prefixes)?;
if is_word {
self.memory
.read_u16(address)
.map_err(ExitReason::MemoryFault)? as u64
} else {
self.memory
.read_u8(address)
.map_err(ExitReason::MemoryFault)? as u64
}
};
let extended = if is_signed {
if is_word {
source as u16 as i16 as i64 as u64
} else {
source as u8 as i8 as i64 as u64
}
} else {
source
};
// A 32-bit destination holds a 32-bit result, so its upper half is
// cleared; a 64-bit destination keeps the full extension.
let result = if prefixes.rex_w {
extended
} else {
extended as u32 as u64
};
self.cpu.set(reg, result);
Ok(None)
}
fn execute_mov_rm(
&mut self,
modrm: u8,
@@ -761,6 +833,49 @@ impl<'a> Interpreter<'a> {
}
// Memory operand [rm + disp] or SIB
let effective_addr = self.effective_address(modrm, prefixes)?;
if is_load {
// Load from memory to reg
if prefixes.rex_w {
let val = self
.memory
.read_u64(effective_addr)
.map_err(ExitReason::MemoryFault)?;
self.cpu.set(reg, val);
} else {
let val = self
.memory
.read_u32(effective_addr)
.map_err(ExitReason::MemoryFault)?;
self.cpu.set(reg, val as u64);
}
} else {
// Store from reg to memory
let val = self.cpu.get(reg);
if prefixes.rex_w {
self.memory
.write_u64(effective_addr, val)
.map_err(ExitReason::MemoryFault)?;
} else {
self.memory
.write_u32(effective_addr, val as u32)
.map_err(ExitReason::MemoryFault)?;
}
}
Ok(None)
}
/// Compute the effective address of a memory operand.
///
/// Consumes the SIB byte and the displacement from the instruction
/// stream. The FS or GS segment base is added when the corresponding
/// segment override prefix is present.
fn effective_address(&mut self, modrm: u8, prefixes: &Prefixes) -> Result<u64, ExitReason> {
let mode = (modrm >> 6) & 3;
let rm_idx = (modrm & 7) + if prefixes.rex_b { 8 } else { 0 };
let (base_val, disp): (u64, i64) = if (rm_idx & 7) == 4 {
// SIB byte follows ModR/M
let sib = self.fetch_u8()?;
@@ -832,36 +947,7 @@ impl<'a> Interpreter<'a> {
effective_addr = effective_addr.wrapping_add(self.cpu.fs_base);
}
if is_load {
// Load from memory to reg
if prefixes.rex_w {
let val = self
.memory
.read_u64(effective_addr)
.map_err(ExitReason::MemoryFault)?;
self.cpu.set(reg, val);
} else {
let val = self
.memory
.read_u32(effective_addr)
.map_err(ExitReason::MemoryFault)?;
self.cpu.set(reg, val as u64);
}
} else {
// Store from reg to memory
let val = self.cpu.get(reg);
if prefixes.rex_w {
self.memory
.write_u64(effective_addr, val)
.map_err(ExitReason::MemoryFault)?;
} else {
self.memory
.write_u32(effective_addr, val as u32)
.map_err(ExitReason::MemoryFault)?;
}
}
Ok(None)
Ok(effective_addr)
}
fn update_flags_logic(&mut self, val: u64, is_64: bool) {
+139 -8
View File
@@ -765,6 +765,7 @@ impl DbtEngine {
// MOV reg, [RIP + disp32]
asm.mov_reg_64(X0, X20);
asm.load_imm_64(X1, target_ea);
Self::emit_segment_base(asm, seg_gs, seg_fs);
let helper_fn = read_u64_helper as *const () as u64;
asm.load_imm_64(X4, helper_fn);
asm.blr(X4);
@@ -778,6 +779,7 @@ impl DbtEngine {
asm.ldr_uoff_64(X2, X19, (reg_idx as u32) * 8);
asm.mov_reg_64(X0, X20);
asm.load_imm_64(X1, target_ea);
Self::emit_segment_base(asm, seg_gs, seg_fs);
let helper_fn = write_u64_helper as *const () as u64;
asm.load_imm_64(X4, helper_fn);
asm.blr(X4);
@@ -1245,7 +1247,13 @@ impl DbtEngine {
if mode == 3 {
asm.ldr_uoff_64(X9, X19, (rm_idx as u32) * 8);
asm.sxtb_64(X9, X9);
if rex_w {
asm.sxtb_64(X9, X9);
} else {
// A 32-bit destination holds a 32-bit
// result, so the upper half is cleared.
asm.sxtb_32(X9, X9);
}
asm.str_uoff_64(X9, X19, (reg_idx as u32) * 8);
} else {
Self::emit_effective_address(
@@ -1265,7 +1273,13 @@ impl DbtEngine {
asm.load_imm_64(X4, helper_fn);
asm.blr(X4);
emit_fault_guard(asm, &mut fault_guards, insn_count - 1, insn_rip);
asm.sxtb_64(X0, X0);
if rex_w {
asm.sxtb_64(X0, X0);
} else {
// A 32-bit destination holds a 32-bit
// result, so the upper half is cleared.
asm.sxtb_32(X0, X0);
}
asm.str_uoff_64(X0, X19, (reg_idx as u32) * 8);
}
}
@@ -1283,7 +1297,13 @@ impl DbtEngine {
if mode == 3 {
asm.ldr_uoff_64(X9, X19, (rm_idx as u32) * 8);
asm.sxth_64(X9, X9);
if rex_w {
asm.sxth_64(X9, X9);
} else {
// A 32-bit destination holds a 32-bit
// result, so the upper half is cleared.
asm.sxth_32(X9, X9);
}
asm.str_uoff_64(X9, X19, (reg_idx as u32) * 8);
} else {
Self::emit_effective_address(
@@ -1303,7 +1323,13 @@ impl DbtEngine {
asm.load_imm_64(X4, helper_fn);
asm.blr(X4);
emit_fault_guard(asm, &mut fault_guards, insn_count - 1, insn_rip);
asm.sxth_64(X0, X0);
if rex_w {
asm.sxth_64(X0, X0);
} else {
// A 32-bit destination holds a 32-bit
// result, so the upper half is cleared.
asm.sxth_32(X0, X0);
}
asm.str_uoff_64(X0, X19, (reg_idx as u32) * 8);
}
}
@@ -1453,17 +1479,36 @@ impl DbtEngine {
}
}
Self::emit_segment_base(asm, seg_gs, seg_fs);
Ok(())
}
/// Add the FS or GS segment base to the effective address held in X1.
///
/// In 64-bit mode an FS or GS segment override adds the segment base to
/// the effective address, so the linear address is
/// `(FS or GS).base + base + (scale * index) + displacement`
/// (Intel SDM Volume 3A, section 3.4.4; AMD64 Architecture Programmer's
/// Manual Volume 1, section 2.2.3.3).
///
/// The base is a runtime guest value, so it is read from the guest CPU
/// state rather than folded into the translated address.
///
/// When both FS and GS overrides are present the encoding is
/// architecturally undefined (Intel SDM Volume 2: "The effect of redundant
/// prefixes ... is undefined"), so this uses a fixed local rule of
/// preferring GS. The interpreter applies the same rule.
fn emit_segment_base(asm: &mut Arm64Assembler, seg_gs: bool, seg_fs: bool) {
if seg_gs {
// Add CpuState.gs_base (offset 16*8 + 8 + 8 = 144) to X1
// CpuState.gs_base (offset 16*8 + 8 + 8 = 144) to X1
asm.ldr_uoff_64(X9, X19, 144);
asm.add_reg_64(X1, X1, X9);
} else if seg_fs {
// Add CpuState.fs_base (offset 16*8 + 8 + 8 + 8 = 152) to X1
// CpuState.fs_base (offset 16*8 + 8 + 8 + 8 = 152) to X1
asm.ldr_uoff_64(X9, X19, 152);
asm.add_reg_64(X1, X1, X9);
}
Ok(())
}
fn emit_set_exit_reason(asm: &mut Arm64Assembler, code: u32, next_rip: u64) {
@@ -1781,6 +1826,92 @@ mod tests {
assert_eq!(memory.read_u64(STORED_ADDR).unwrap(), STORED_VALUE);
}
/// A 32-bit MOVSX destination holds a 32-bit result, so the upper half of
/// the register must be cleared.
///
/// The encodings are `movsbl eax, bl` (0F BE C3) and
/// `movsbq rdx, bl` (48 0F BE D3), as produced by LLVM 23.1.6
/// `llvm-mc -show-encoding`. With `bl = 0xFF` the 32-bit destination holds
/// 0x00000000ffffffff while the 64-bit destination holds the sign
/// extension across all 64 bits.
///
/// Per Intel SDM Volume 1, "Address Calculations in 64-Bit Mode": "32-bit
/// operands generate a 32-bit result, zero-extended to a 64-bit result in
/// the destination general-purpose register."
#[test]
fn movsx_to_a_32_bit_destination_clears_the_upper_half() {
// mov rbx, 0xffffffffffffffff (48 BB <imm64>)
// movsbl eax, bl (0F BE C3)
// movsbq rdx, bl (48 0F BE D3)
let mut code = vec![0x48, 0xBB];
code.extend_from_slice(&u64::MAX.to_le_bytes());
code.extend_from_slice(&[0x0F, 0xBE, 0xC3]);
code.extend_from_slice(&[0x48, 0x0F, 0xBE, 0xD3]);
code.push(0xF4); // hlt
let (mut engine, mut cpu, mut memory) = fixture(&code);
cpu.set(Register::Rbx, u64::MAX);
let result = engine.run(&mut cpu, &mut memory, 16);
assert_eq!(result.exit_reason, ExitReason::Halt);
assert_eq!(result.final_state.get(Register::Rax), 0x0000_0000_ffff_ffff);
assert_eq!(result.final_state.get(Register::Rdx), 0xffff_ffff_ffff_ffff);
}
/// A 32-bit MOVSX destination from a 16-bit source also holds a 32-bit
/// result.
///
/// The encodings are `movswl eax, bx` (0F BF C3) and
/// `movswq rdx, bx` (48 0F BF D3), as produced by LLVM 23.1.6
/// `llvm-mc -show-encoding`.
#[test]
fn movsx_from_a_word_to_a_32_bit_destination_clears_the_upper_half() {
// mov rbx, 0xffffffffffffffff (48 BB <imm64>)
// movswl eax, bx (0F BF C3)
// movswq rdx, bx (48 0F BF D3)
let mut code = vec![0x48, 0xBB];
code.extend_from_slice(&u64::MAX.to_le_bytes());
code.extend_from_slice(&[0x0F, 0xBF, 0xC3]);
code.extend_from_slice(&[0x48, 0x0F, 0xBF, 0xD3]);
code.push(0xF4); // hlt
let (mut engine, mut cpu, mut memory) = fixture(&code);
cpu.set(Register::Rbx, u64::MAX);
let result = engine.run(&mut cpu, &mut memory, 16);
assert_eq!(result.exit_reason, ExitReason::Halt);
assert_eq!(result.final_state.get(Register::Rax), 0x0000_0000_ffff_ffff);
assert_eq!(result.final_state.get(Register::Rdx), 0xffff_ffff_ffff_ffff);
}
/// The same 32-bit destination rule applies to the memory source forms.
///
/// The encodings are `movsbl eax, byte [rdi]` (0F BE 07) and
/// `movsbq rdx, byte [rdi]` (48 0F BE 17), as produced by LLVM 23.1.6
/// `llvm-mc -show-encoding`.
#[test]
fn movsx_from_memory_to_a_32_bit_destination_clears_the_upper_half() {
// mov rdi, 0x4000 (48 BF <imm64>)
// movsbl eax, byte [rdi] (0F BE 07)
// movsbq rdx, byte [rdi] (48 0F BE 17)
let mut code = vec![0x48, 0xBF];
code.extend_from_slice(&0x4000u64.to_le_bytes());
code.extend_from_slice(&[0x0F, 0xBE, 0x07]);
code.extend_from_slice(&[0x48, 0x0F, 0xBE, 0x17]);
code.push(0xF4); // hlt
let (mut engine, mut cpu, mut memory) = fixture(&code);
memory
.map_region(0x4000, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
memory.write_u8(0x4000, 0xFF).unwrap();
let result = engine.run(&mut cpu, &mut memory, 16);
assert_eq!(result.exit_reason, ExitReason::Halt);
assert_eq!(result.final_state.get(Register::Rax), 0x0000_0000_ffff_ffff);
assert_eq!(result.final_state.get(Register::Rdx), 0xffff_ffff_ffff_ffff);
}
#[test]
fn indirect_call_target_fault_leaves_guest_stack_unchanged() {
// call qword ptr [rip + 0x1000]; hlt. The IAT slot is outside the
+247
View File
@@ -462,3 +462,250 @@ fn test_sib_index_field_100b_without_rex_x_means_no_index() {
0x1234_5678_9abc_def0
);
}
/// Build a guest program that loads `value` into `rdi` and then runs `body`.
///
/// `mov rdi, imm64` is 48 BF <imm64>.
fn program_with_rdi(value: u64, body: &[u8]) -> Vec<u8> {
let mut code = vec![0x48, 0xBF];
code.extend_from_slice(&value.to_le_bytes());
code.extend_from_slice(body);
code.push(0xF4); // hlt
code
}
/// Run `code` on the interpreter and return the final state and exit reason.
fn run_interpreter(code: &[u8]) -> (CpuState, ExitReason) {
let pe_bytes = build_synthetic_pe32_plus(code);
let parsed = ParsedPe::parse(&pe_bytes).expect("parse");
let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load");
loaded
.memory
.map_region(STACK_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("stack mapping should succeed");
loaded
.memory
.map_region(DATA_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("data mapping should succeed");
let cpu = CpuState::new(loaded.entry_point, STACK_BASE + 0x8000);
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 100);
let result = interp.run();
(result.final_state, result.exit_reason)
}
/// MOVZX with a register source, for both destination widths.
///
/// The encodings are `movzbl eax, bl` (0F B6 C3) and
/// `movzbq rdx, bl` (48 0F B6 D3), as produced by LLVM 23.1.6
/// `llvm-mc -show-encoding`. A zero extension always produces a zero-extended
/// value, so the 32-bit form clears the upper half of rax while the 64-bit
/// form produces the same 64-bit value.
#[test]
fn test_movzx_register_source_zero_extends() {
// mov rbx, 0xffffffffffffffff (48 BB <imm64>)
let mut code = vec![0x48, 0xBB];
code.extend_from_slice(&u64::MAX.to_le_bytes());
code.extend_from_slice(&[0x0F, 0xB6, 0xC3]); // movzbl eax, bl
code.extend_from_slice(&[0x48, 0x0F, 0xB6, 0xD3]); // movzbq rdx, bl
code.push(0xF4); // hlt
let (state, reason) = run_interpreter(&code);
assert_eq!(reason, ExitReason::Halt);
// The 32-bit destination holds a zero-extended byte: 0x00000000000000ff.
assert_eq!(state.get(Register::Rax), 0x0000_0000_0000_00ff);
// The 64-bit destination holds the same zero-extended value.
assert_eq!(state.get(Register::Rdx), 0x0000_0000_0000_00ff);
}
/// MOVSX with a register source, for both destination widths.
///
/// The encodings are `movsbl eax, bl` (0F BE C3) and
/// `movsbq rdx, bl` (48 0F BE D3), as produced by LLVM 23.1.6
/// `llvm-mc -show-encoding`. A sign extension reaches the destination width,
/// so the 32-bit form keeps the sign in bits 31:0 and clears the upper half,
/// while the 64-bit form sign-extends across all 64 bits.
#[test]
fn test_movsx_register_source_sign_extends_to_the_destination_width() {
// mov rbx, 0xffffffffffffffff (48 BB <imm64>)
let mut code = vec![0x48, 0xBB];
code.extend_from_slice(&u64::MAX.to_le_bytes());
code.extend_from_slice(&[0x0F, 0xBE, 0xC3]); // movsbl eax, bl
code.extend_from_slice(&[0x48, 0x0F, 0xBE, 0xD3]); // movsbq rdx, bl
code.push(0xF4); // hlt
let (state, reason) = run_interpreter(&code);
assert_eq!(reason, ExitReason::Halt);
// The 32-bit destination holds 0xffffffff and its upper half is cleared.
assert_eq!(state.get(Register::Rax), 0x0000_0000_ffff_ffff);
// The 64-bit destination keeps the sign extension across all 64 bits.
assert_eq!(state.get(Register::Rdx), 0xffff_ffff_ffff_ffff);
}
/// MOVSX from a 16-bit source sign-extends to the destination width.
///
/// The encodings are `movswl eax, bx` (0F BF C3) and
/// `movswq rdx, bx` (48 0F BF D3), as produced by LLVM 23.1.6
/// `llvm-mc -show-encoding`.
#[test]
fn test_movsx_word_register_source_sign_extends() {
// mov rbx, 0xffffffffffffffff (48 BB <imm64>)
let mut code = vec![0x48, 0xBB];
code.extend_from_slice(&u64::MAX.to_le_bytes());
code.extend_from_slice(&[0x0F, 0xBF, 0xC3]); // movswl eax, bx
code.extend_from_slice(&[0x48, 0x0F, 0xBF, 0xD3]); // movswq rdx, bx
code.push(0xF4); // hlt
let (state, reason) = run_interpreter(&code);
assert_eq!(reason, ExitReason::Halt);
assert_eq!(state.get(Register::Rax), 0x0000_0000_ffff_ffff);
assert_eq!(state.get(Register::Rdx), 0xffff_ffff_ffff_ffff);
}
/// MOVZX with a memory source reads only the low byte of the operand.
///
/// The encodings are `movzbl eax, byte [rdi]` (0F B6 07) and
/// `movzbq rdx, byte [rdi]` (48 0F B6 17), as produced by LLVM 23.1.6
/// `llvm-mc -show-encoding`.
#[test]
fn test_movzx_memory_source_reads_one_byte() {
// mov rdi, DATA_BASE (48 BF <imm64>)
// movzbl eax, byte [rdi] (0F B6 07)
// movzbq rdx, byte [rdi] (48 0F B6 17)
let code = program_with_rdi(DATA_BASE, &[0x0F, 0xB6, 0x07, 0x48, 0x0F, 0xB6, 0x17]);
let pe_bytes = build_synthetic_pe32_plus(&code);
let parsed = ParsedPe::parse(&pe_bytes).expect("parse");
let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load");
loaded
.memory
.map_region(STACK_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("stack mapping should succeed");
loaded
.memory
.map_region(DATA_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("data mapping should succeed");
// The byte at the source address has the high bit set, so a sign
// extension would produce a negative value and a zero extension must not.
loaded
.memory
.write_u8(DATA_BASE, 0xFF)
.expect("source byte");
let cpu = CpuState::new(loaded.entry_point, STACK_BASE + 0x8000);
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 100);
let result = interp.run();
assert_eq!(result.exit_reason, ExitReason::Halt);
assert_eq!(result.final_state.get(Register::Rax), 0x0000_0000_0000_00ff);
assert_eq!(result.final_state.get(Register::Rdx), 0x0000_0000_0000_00ff);
}
/// MOVSX with a memory source sign-extends the byte that was read.
///
/// The encodings are `movsbl eax, byte [rdi]` (0F BE 07) and
/// `movsbq rdx, byte [rdi]` (48 0F BE 17), as produced by LLVM 23.1.6
/// `llvm-mc -show-encoding`.
#[test]
fn test_movsx_memory_source_sign_extends() {
// mov rdi, DATA_BASE (48 BF <imm64>)
// movsbl eax, byte [rdi] (0F BE 07)
// movsbq rdx, byte [rdi] (48 0F BE 17)
let code = program_with_rdi(DATA_BASE, &[0x0F, 0xBE, 0x07, 0x48, 0x0F, 0xBE, 0x17]);
let pe_bytes = build_synthetic_pe32_plus(&code);
let parsed = ParsedPe::parse(&pe_bytes).expect("parse");
let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load");
loaded
.memory
.map_region(STACK_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("stack mapping should succeed");
loaded
.memory
.map_region(DATA_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("data mapping should succeed");
loaded
.memory
.write_u8(DATA_BASE, 0xFF)
.expect("source byte");
let cpu = CpuState::new(loaded.entry_point, STACK_BASE + 0x8000);
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 100);
let result = interp.run();
assert_eq!(result.exit_reason, ExitReason::Halt);
// The 32-bit destination holds 0xffffffff with the upper half cleared.
assert_eq!(result.final_state.get(Register::Rax), 0x0000_0000_ffff_ffff);
// The 64-bit destination keeps the sign extension across all 64 bits.
assert_eq!(result.final_state.get(Register::Rdx), 0xffff_ffff_ffff_ffff);
}
/// The interpreter must implement the same extension opcodes as the native
/// DBT translator.
///
/// The program exercises all four opcodes with both a register and a memory
/// source, and both destination widths:
///
/// - `movzbl eax, bl` (0F B6 C3), `movzbq rdx, bl` (48 0F B6 D3)
/// - `movswl eax, bx` (0F BF C3), `movswq rdx, bx` (48 0F BF D3)
/// - `movzbl eax, byte [rdi]` (0F B6 07), `movzbq rdx, byte [rdi]`
/// (48 0F B6 17)
/// - `movsbl eax, byte [rdi]` (0F BE 07), `movsbq rdx, byte [rdi]`
/// (48 0F BE 17)
///
/// All encodings were produced by LLVM 23.1.6 `llvm-mc -show-encoding`.
///
/// The expected values follow the Intel SDM rules for MOVZX and MOVSX: MOVZX
/// always zero-extends, and MOVSX sign-extends to the destination width, so a
/// 32-bit destination keeps the sign in bits 31:0 and clears the upper half
/// while a 64-bit destination keeps the sign extension across all 64 bits.
#[test]
fn test_interpreter_implements_the_extension_opcodes() {
let code = program_with_rdi(
DATA_BASE,
&[
0x0F, 0xB6, 0xC3, // movzbl eax, bl
0x48, 0x0F, 0xB6, 0xD3, // movzbq rdx, bl
0x0F, 0xBF, 0xC3, // movswl eax, bx
0x48, 0x0F, 0xBF, 0xD3, // movswq rdx, bx
0x0F, 0xB6, 0x07, // movzbl eax, byte [rdi]
0x48, 0x0F, 0xB6, 0x17, // movzbq rdx, byte [rdi]
0x0F, 0xBE, 0x07, // movsbl eax, byte [rdi]
0x48, 0x0F, 0xBE, 0x17, // movsbq rdx, byte [rdi]
],
);
let pe_bytes = build_synthetic_pe32_plus(&code);
let parsed = ParsedPe::parse(&pe_bytes).expect("parse");
let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load");
loaded
.memory
.map_region(STACK_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("stack mapping should succeed");
loaded
.memory
.map_region(DATA_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("data mapping should succeed");
// The bytes at the source address have the high bit set and clear, so a
// sign extension and a zero extension give different results.
loaded
.memory
.write_u8(DATA_BASE, 0xFF)
.expect("source byte");
loaded
.memory
.write_u8(DATA_BASE + 1, 0x7F)
.expect("source byte");
let mut cpu = CpuState::new(loaded.entry_point, STACK_BASE + 0x8000);
// rbx and rsi hold the register-source values.
cpu.set(Register::Rbx, u64::MAX);
cpu.set(Register::Rsi, 0x0000_0000_0000_7FFF);
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 100);
let result = interp.run();
assert_eq!(result.exit_reason, ExitReason::Halt);
// The last write to rax is the 32-bit sign extension of the byte 0xFF.
assert_eq!(result.final_state.get(Register::Rax), 0x0000_0000_ffff_ffff);
// The last write to rdx is the 64-bit sign extension of the same byte.
assert_eq!(result.final_state.get(Register::Rdx), 0xffff_ffff_ffff_ffff);
}
+9 -4
View File
@@ -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
View File
@@ -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
View File
@@ -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")
+21
View File
@@ -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",
+86 -3
View File
@@ -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__":