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
38 changes: 33 additions & 5 deletions apps/victory/src/shader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,14 @@ pub(crate) fn sources(data: &[u8]) -> Vec<Source<'_>> {
if sgd5::is_sgd5(data) {
out.extend(sgd5::records(data).map(Source::Packed));
}
let raw = memchr::memmem::find_iter(data, b"DXBC")
.filter(|&offset| Container::parse(&data[offset..]).is_ok())
.map(|offset| Source::Raw {
let raw = memchr::memmem::find_iter(data, b"DXBC").filter_map(|offset| {
let tail = &data[offset..];
let container = Container::parse(tail).ok()?;
Some(Source::Raw {
offset,
data: &data[offset..],
});
data: &tail[..container.byte_len],
})
});
out.extend(raw);
out
}
Expand Down Expand Up @@ -225,3 +227,29 @@ fn format_instruction(i: &Instruction, wave64: bool) -> String {
};
format!(" {:06x}: {:<44} {text}", i.offset, words.join(" "))
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn embedded_raw_sources_end_at_the_declared_container_size() {
let mut container = [0u8; 32];
container[..4].copy_from_slice(b"DXBC");
container[24..28].copy_from_slice(&32u32.to_le_bytes());
let file = [
b"prefix".as_slice(),
&container,
b"gap",
&container,
b"suffix",
]
.concat();
let sources = sources(&file);
assert_eq!(sources.len(), 2);
for (source, offset) in sources.iter().zip([6, 41]) {
assert_eq!(source.label(), format!("@{offset:#x}"));
assert_eq!(source.bytes().unwrap().as_ref(), &container);
}
}
}
53 changes: 46 additions & 7 deletions apps/victory/src/translate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -333,9 +333,7 @@ pub fn warm(paths: Vec<PathBuf>, jobs: Option<usize>, pipelines: bool, rays: cra
let Some(bytes) = job.bytes() else { continue };
let Ok(container) = Container::parse(&bytes) else { continue };
// As the title passes it: no more than the container.
let Some(total) = bytes.get(0x18..0x1c).and_then(|b| b.try_into().ok()) else { continue };
let total = u32::from_le_bytes(total) as usize;
let bytes = &bytes[..total.min(bytes.len())];
let bytes = &bytes[..container.byte_len];
let Some(dxil) = container.part(FourCC::DXIL).map(|p| p.data) else { continue };
if !lock(&seen).insert(blake3::hash(bytes)) {
continue;
Expand Down Expand Up @@ -396,7 +394,11 @@ fn translate(
};
// The hash a run's log names the shader by (`hash=` in "first bind",
// "shader does not translate", "host pipeline refused").
let hash = blake3::hash(&bytes).to_hex()[..16].to_owned();
let parsed = Container::parse(&bytes);
// Packed records can include padding after the container. Use the same
// bytes as warm-up, retaining the full payload for malformed-record diagnostics.
let bytes = parsed.as_ref().map_or(bytes.as_ref(), |c| &bytes[..c.byte_len]);
let hash = blake3::hash(bytes).to_hex()[..16].to_owned();
// Diagnostics: `VICTORY_TRANSLATE_ONLY=<hash prefix>,...` translates
// those containers alone.
static ONLY: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
Expand All @@ -413,7 +415,7 @@ fn translate(
}
let example = || format!("{}{} #{hash}", path.display(), source.label());
t.containers += 1;
let Ok(container) = Container::parse(&bytes) else {
let Ok(container) = parsed else {
return t.fail("no DXIL part (SM5 or older)".into(), example);
};
let Some(dxil) = container.part(FourCC::DXIL).map(|p| p.data) else {
Expand All @@ -439,7 +441,7 @@ fn translate(
.take(70)
.collect();
let _ = std::fs::create_dir_all(dir);
let _ = std::fs::write(std::path::Path::new(dir).join(format!("{name}.{hash}.cdxil")), &bytes[..]);
let _ = std::fs::write(std::path::Path::new(dir).join(format!("{name}.{hash}.cdxil")), bytes);
}
}
if !lock(seen).insert(code) {
Expand All @@ -464,7 +466,7 @@ fn translate(
if *n > was && was < 3 {
let stem: String = reason.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).take(60).collect();
let _ = std::fs::create_dir_all(&dir);
let _ = std::fs::write(std::path::Path::new(&dir).join(format!("{stem}_{was}.cdxil")), &bytes[..]);
let _ = std::fs::write(std::path::Path::new(&dir).join(format!("{stem}_{was}.cdxil")), bytes);
}
}
}
Expand Down Expand Up @@ -860,3 +862,40 @@ fn tally_structured(program: &ir::Program, s: &structure::Structured, t: &mut Ta
fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
m.lock().unwrap_or_else(|e| e.into_inner())
}

#[cfg(test)]
mod packed_source_tests {
use super::*;

#[test]
fn packed_translation_hashes_the_container_and_preserves_invalid_payloads() {
let mut container = [0u8; 32];
container[..4].copy_from_slice(b"DXBC");
container[24..28].copy_from_slice(&32u32.to_le_bytes());
let padded = [&container[..], b"record padding"].concat();
for (payload, expected) in [
(padded.as_slice(), container.as_slice()),
(b"not a container".as_slice(), b"not a container".as_slice()),
(&container[..28], &container[..28]),
] {
// An SGD5 record containing one uncompressed DEFLATE block.
let len = u16::try_from(payload.len()).unwrap();
let record_size = u32::from(len) + 17;
let mut file = vec![0, 0x32];
for word in [record_size, 0x000d_dce7, record_size, u32::from(len)] {
file.extend_from_slice(&word.to_le_bytes());
}
file.push(1);
file.extend_from_slice(&len.to_le_bytes());
file.extend_from_slice(&(!len).to_le_bytes());
file.extend_from_slice(payload);
let record = victory_game::sgd5::records(&file).next().unwrap();
let mut tally = Tally::default();
let mut checks = Checks { keep: None, validator: None, host: None };
translate(&Source::Packed(record), Path::new("test"), &Mutex::default(), &mut tally, &mut checks);
let (count, example) = &tally.failed["no DXIL part (SM5 or older)"];
assert_eq!(*count, 1);
assert!(example.ends_with(&format!("#{}", &blake3::hash(expected).to_hex()[..16])));
}
}
}
3 changes: 3 additions & 0 deletions crates/victory-shader/src/dxbc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ pub struct Part<'a> {

#[derive(Debug, Clone)]
pub struct Container<'a> {
/// Declared container size, including its header and excluding any following file data.
pub byte_len: usize,
pub digest: [u8; 16],
pub version: (u16, u16),
pub parts: Vec<Part<'a>>,
Expand Down Expand Up @@ -100,6 +102,7 @@ impl<'a> Container<'a> {
});
}
Ok(Container {
byte_len: total,
digest,
version,
parts,
Expand Down