Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/victory-loader/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand Down
60 changes: 55 additions & 5 deletions crates/victory-loader/src/prepare.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -106,6 +107,15 @@ pub fn prepare(original: &[u8]) -> Result<PreparedImage, PrepareError> {
}
}

// 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,
Expand All @@ -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 {
Expand All @@ -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;
Expand Down Expand Up @@ -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: "<module basename>:<rva hex>:<hex bytes>"
/// 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<u8>)> {
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<u8>)]) -> 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::<Vec<_>>().join("");
let new_hex = new_bytes.iter().map(|b| format!("{:02x}", b)).collect::<Vec<_>>().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::*;
Expand Down Expand Up @@ -280,4 +330,4 @@ mod tests {
let b = prepare(&original).unwrap();
assert_eq!(a.file_name(), b.file_name());
}
}
}
50 changes: 35 additions & 15 deletions crates/victory-shader/src/emit/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<V, Why> {
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<V, Why> {
self.half_src_with(inst, k, false)
}

fn half_src_with(&mut self, inst: &Inst, k: usize, opsel: bool) -> Result<V, Why> {
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 => {}
Expand All @@ -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<V, Why> {
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<V, Why> {
self.half_fsrc_with(inst, k, false)
}

fn half_fsrc_with(&mut self, inst: &Inst, k: usize, opsel: bool) -> Result<V, Why> {
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
Expand Down Expand Up @@ -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)?)
};
Expand Down Expand Up @@ -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] {
Expand Down Expand Up @@ -7099,9 +7119,7 @@ mod tests {
S_ENDPGM,
];

let code: Vec<u8> = words.iter()
.flat_map(|w| w.to_le_bytes())
.collect();
let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();

let native = NativeProgram {
stage: HwStage::Cs,
Expand All @@ -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();
Expand All @@ -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())
}
Expand Down
60 changes: 60 additions & 0 deletions crates/victory-shader/src/emit/valu_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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],
);
});
}
Loading