From 0d918ce72ebdce5cd1785fa5680d4c833e531b8d Mon Sep 17 00:00:00 2001 From: Hugo VIAUD Date: Tue, 24 Nov 2026 13:23:25 +0100 Subject: [PATCH 1/2] Shaders: 16-bit compares ignore VOP3 op_sel RDNA2 reads only the low half in v_cmp_*/v_cmpx_* over f16, u16 and i16, whatever op_sel says; VIctory honoured it and compared the wrong half. The arithmetic paths still honour op_sel. Adds a test for the f16 and u16 compares with op_sel set and clear (#833). --- crates/victory-shader/src/emit/lower.rs | 50 +++++++++++----- crates/victory-shader/src/emit/valu_tests.rs | 60 ++++++++++++++++++++ 2 files changed, 95 insertions(+), 15 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c5fbd804b0..e6d5a564f7 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -4313,11 +4313,22 @@ impl<'a> Lower<'a> { /// op_sel (or an SDWA word select) picks the high half; inline float /// constants are f16 values here. fn half_src(&mut self, inst: &Inst, k: usize) -> Result { + self.half_src_with(inst, k, true) + } + + /// [`Self::half_src`] for a 16-bit compare: RDNA2 ignores VOP3 `op_sel` + /// on `v_cmp_*`/`v_cmpx_*` over f16, u16 and i16, and reads the low half; + /// an SDWA word select still picks the half it names. + fn half_cmp_src(&mut self, inst: &Inst, k: usize) -> Result { + self.half_src_with(inst, k, false) + } + + fn half_src_with(&mut self, inst: &Inst, k: usize, opsel: bool) -> Result { let Fields::Valu(v) = &inst.fields else { unreachable!() }; let op = *v.src.get(k).ok_or("a missing operand")?; - let mut high = v.opsel >> k & 1 != 0; + let mut high = opsel && v.opsel >> k & 1 != 0; if let Some(sd) = v.sdwa { match sd.src_sel.get(k).copied().unwrap_or(6) { 4 => {} @@ -4343,10 +4354,19 @@ impl<'a> Lower<'a> { /// An f16 source as an f32 (exact), with its abs/neg modifiers. fn half_fsrc(&mut self, inst: &Inst, k: usize) -> Result { + self.half_fsrc_with(inst, k, true) + } + + /// [`Self::half_fsrc`] for a 16-bit compare, which ignores `op_sel`. + fn half_cmp_fsrc(&mut self, inst: &Inst, k: usize) -> Result { + self.half_fsrc_with(inst, k, false) + } + + fn half_fsrc_with(&mut self, inst: &Inst, k: usize, opsel: bool) -> Result { let Fields::Valu(v) = &inst.fields else { unreachable!() }; - let h = self.half_src(inst, k)?; + let h = self.half_src_with(inst, k, opsel)?; let f32t = self.s.t.f32; let mut f = self .s @@ -5331,7 +5351,7 @@ impl<'a> Lower<'a> { } "f32" | "f16" => { let (a, b) = if ty == "f16" { - (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?) + (self.half_cmp_fsrc(inst, 0)?, self.half_cmp_fsrc(inst, 1)?) } else { (self.fsrc(inst, 0)?, self.fsrc(inst, 1)?) }; @@ -5385,7 +5405,7 @@ impl<'a> Lower<'a> { } "u32" | "i32" | "u16" | "i16" => { let (a, b) = if ty.ends_with("16") { - let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?); + let (mut a, mut b) = (self.half_cmp_src(inst, 0)?, self.half_cmp_src(inst, 1)?); if ty == "i16" { let k16 = self.s.m.i32(16); for x in [&mut a, &mut b] { @@ -7099,9 +7119,7 @@ mod tests { S_ENDPGM, ]; - let code: Vec = words.iter() - .flat_map(|w| w.to_le_bytes()) - .collect(); + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); let native = NativeProgram { stage: HwStage::Cs, @@ -7118,9 +7136,12 @@ mod tests { let p = ir::build(&native.code, false, 256).unwrap(); - assert!(p.blocks.iter() - .flat_map(|b| &b.insts) - .any(|i| i.name() == "v_perm_b32")); + assert!( + p.blocks + .iter() + .flat_map(|b| &b.insts) + .any(|i| i.name() == "v_perm_b32") + ); let st = structure::structure(&p).unwrap(); let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); @@ -7137,13 +7158,12 @@ mod tests { outputs: vec![], prims: vec![], mesh_stride: 0, - }).unwrap(); + }) + .unwrap(); - let container = - crate::Container::parse(&emitted.dxil).unwrap(); + let container = crate::Container::parse(&emitted.dxil).unwrap(); - let features = - container.part(crate::FourCC::SFI0).unwrap(); + let features = container.part(crate::FourCC::SFI0).unwrap(); u64::from_le_bytes(features.data.try_into().unwrap()) } diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index b4ee77d778..0c983b553a 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -937,3 +937,63 @@ fn v_cmp_class_f16_matches_rdna2() { ); }); } + +#[test] +fn v_cmp_16bit_ignores_vop3_op_sel() { + // v_cmp_lt_f16_e64 s6, v1, v2 (VOP3 encoding of VOPC 0x0c9), op_sel:[1,0]; + // then v_cndmask_b32_e64 v0, 0, 1, s6. + let [mut hi0, hi1] = vop3(0x0c9, 6, vgpr(1), vgpr(2), 0); + hi0 |= 1 << 11; // op_sel[0] = high half, which RDNA2 ignores here + let f16_hi = build_valu_cs(&[ + hi0, + hi1, + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[0], + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[1], + ]); + // The same compare with op_sel clear, as a control. + let f16_lo = build_valu_cs(&[ + vop3(0x0c9, 6, vgpr(1), vgpr(2), 0)[0], + vop3(0x0c9, 6, vgpr(1), vgpr(2), 0)[1], + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[0], + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[1], + ]); + // v_cmp_lt_u16_e64 with op_sel:[1,0] (VOPC 0x0a9). + let [mut hi0, hi1] = vop3(0x0a9, 6, vgpr(1), vgpr(2), 0); + hi0 |= 1 << 11; + let u16_hi = build_valu_cs(&[ + hi0, + hi1, + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[0], + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[1], + ]); + + // Low halves decide: 1.0 < 1.5 true; 2.0 < 1.5 false. In the second + // case honouring op_sel (high half 1.0) would wrongly say true. + let f16_inputs = [ + [0x4000_3C00, 0x0000_3E00, 0, 0], + [0x3C00_4000, 0x0000_3E00, 0, 0], + ]; + let f16_wants = [1u32, 0u32]; + for (name, shader) in [("op_sel high", &f16_hi), ("op_sel low", &f16_lo)] { + run_cases(shader, &f16_inputs, |backend, i, inp, got| { + let want = f16_wants[i]; + assert_eq!( + got, want, + "{backend}: v_cmp_lt_f16({name}) ({:#010x}, {:#010x}) = {got}, want {want}", + inp[0], inp[1], + ); + }); + } + + // u16: low 9 < 5 is false; honouring op_sel (high half 1) would say true. + let u16_inputs = [[0x0001_0009, 0x0000_0005, 0, 0]]; + let u16_wants = [0u32]; + run_cases(&u16_hi, &u16_inputs, |backend, i, inp, got| { + let want = u16_wants[i]; + assert_eq!( + got, want, + "{backend}: v_cmp_lt_u16(op_sel high) ({:#010x}, {:#010x}) = {got}, want {want}", + inp[0], inp[1], + ); + }); +} From f23c49321bb3c0be7384b0f1ff37c01d26cd7198 Mon Sep 17 00:00:00 2001 From: Hugo VIAUD Date: Tue, 24 Nov 2026 15:28:51 +0100 Subject: [PATCH 2/2] VICTORY_PATCH: refine hex crate support for full hex decoding - Add hex = "0.4" crate dependency to victory-loader - Replace custom hexDecode() with hex::decode() - Add parse_victory_patch() and apply_victory_patches() functions - Support format: :: - Log patch applications via tracing::info! --- Cargo.lock | 7 ++++ crates/victory-loader/Cargo.toml | 1 + crates/victory-loader/src/prepare.rs | 60 +++++++++++++++++++++++++--- 3 files changed, 63 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bab4a7e1a6..aaee366189 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -226,6 +226,12 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + [[package]] name = "indexmap" version = "2.14.2" @@ -723,6 +729,7 @@ version = "0.1.0" dependencies = [ "anyhow", "blake3", + "hex", "tempfile", "thiserror", "tracing", diff --git a/crates/victory-loader/Cargo.toml b/crates/victory-loader/Cargo.toml index 637253a8c4..4b0e0986a8 100644 --- a/crates/victory-loader/Cargo.toml +++ b/crates/victory-loader/Cargo.toml @@ -14,6 +14,7 @@ anyhow.workspace = true thiserror.workspace = true tracing.workspace = true blake3.workspace = true +hex = "0.4" [target.'cfg(windows)'.dependencies] windows-sys = { workspace = true, features = [ diff --git a/crates/victory-loader/src/prepare.rs b/crates/victory-loader/src/prepare.rs index c8935081bf..7ce27184df 100644 --- a/crates/victory-loader/src/prepare.rs +++ b/crates/victory-loader/src/prepare.rs @@ -3,6 +3,7 @@ use victory_pe::layout::{self, dir, dll_flags, file_flags}; use victory_pe::{ImageInfo, PeError}; +use tracing; #[derive(Debug, thiserror::Error)] pub enum PrepareError { @@ -106,6 +107,15 @@ pub fn prepare(original: &[u8]) -> Result { } } + // Apply VICTORY_PATCH if set + if let Some(patch_env) = std::env::var_os("VICTORY_PATCH") { + let patch_env = patch_env.to_string_lossy().into_owned(); + let patches = parse_victory_patch(&patch_env); + if let Err(e) = apply_victory_patches(&mut bytes, &patches) { + tracing::warn!(target: "victory-loader", "VICTORY_PATCH application failed: {e}"); + } + } + Ok(PreparedImage { info, bytes, @@ -124,8 +134,7 @@ fn dir64_relocations(bytes: &[u8], info: &ImageInfo) -> Vec<(usize, u32)> { let Some(d) = layout::data_directory_offset(bytes, dir::BASERELOC) else { return out; }; - let (Some(rva), Some(size)) = (layout::read_u32(bytes, d), layout::read_u32(bytes, d + 4)) - else { + let (Some(rva), Some(size)) = (layout::read_u32(bytes, d), layout::read_u32(bytes, d + 4)) else { return out; }; let Some(start) = info.rva_to_file_offset(rva).filter(|_| size != 0) else { @@ -134,8 +143,7 @@ fn dir64_relocations(bytes: &[u8], info: &ImageInfo) -> Vec<(usize, u32)> { let (mut at, end) = (start as usize, start as usize + size as usize); while at + 8 <= end { let (Some(page), Some(block)) = - (layout::read_u32(bytes, at), layout::read_u32(bytes, at + 4)) - else { + (layout::read_u32(bytes, at), layout::read_u32(bytes, at + 4)) else { break; }; let block = block as usize; @@ -173,6 +181,48 @@ fn write(bytes: &mut [u8], at: usize, v: &[u8]) -> Result<(), PrepareError> { Ok(()) } +/// Simple hex decoder for VICTORY_PATCH bytes (no external `hex` crate needed). +/// Parses a VICTORY_PATCH environment variable value. +/// Format: "::" +/// Multiple patches can be specified by setting the env var multiple times +/// or using a separator (here we support space-separated multiple entries). +fn parse_victory_patch(env_val: &str) -> Vec<(String, u32, Vec)> { + let mut patches = Vec::new(); + for part in env_val.split_whitespace() { + let parts: Vec<&str> = part.split(':').collect(); + if parts.len() != 3 { + tracing::warn!(target: "victory-loader", "invalid VICTORY_PATCH format: {part}"); + continue; + } + let module = parts[0].to_string(); + let rva = u32::from_str_radix(parts[1], 16).unwrap_or(0); + let bytes = hex::decode(parts[2].trim()).unwrap_or_else(|_| Vec::new()); + patches.push((module, rva, bytes)); + } + patches +} + +/// Applies a list of VICTORY_PATCH entries to the image bytes. +/// Each patch is logged via `tracing::info!` with module, rva, old bytes, new bytes. +fn apply_victory_patches(bytes: &mut [u8], patches: &[(String, u32, Vec)]) -> Result<(), PrepareError> { + for (module, rva, new_bytes) in patches { + // Verify the RVA is within the file bounds + if *rva as usize >= bytes.len() { + tracing::warn!(target: "victory-loader", "VICTORY_PATCH rva {:#x} outside file size {}", rva, bytes.len()); + continue; + } + // Save the old bytes for logging + let old_bytes = bytes[*rva as usize..*rva as usize + new_bytes.len()].to_vec(); + // Apply the patch + let _ = bytes[*rva as usize..*rva as usize + new_bytes.len()].copy_from_slice(new_bytes); + // Log the patch application + let old_hex = old_bytes.iter().map(|b| format!("{:02x}", b)).collect::>().join(""); + let new_hex = new_bytes.iter().map(|b| format!("{:02x}", b)).collect::>().join(""); + tracing::info!(target: "victory-loader", "VICTORY_PATCH: module={}, rva={:#x}, old_bytes=[{}], new_bytes=[{}]", module, rva, old_hex, new_hex); + } + Ok(()) +} + #[cfg(test)] mod tests { use super::*; @@ -280,4 +330,4 @@ mod tests { let b = prepare(&original).unwrap(); assert_eq!(a.file_name(), b.file_name()); } -} +} \ No newline at end of file