diff --git a/CHANGELOG.md b/CHANGELOG.md index ddc149a74..74fd2d520 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -88,6 +88,10 @@ Bottom level categories: - Validate that the arguments are within the indirect buffer when encoding an indirect draw to a render bundle. Moves some indirect draw errors from `RenderPassErrorInner` to `RenderCommandError`. By @andyleiserson in [#9871](https://github.com/gfx-rs/wgpu/pull/9871). +#### Naga + +- Replace embedded NUL characters with `?` when writing debug strings to SPIR-V. By @andyleiserson in [#9904](https://github.com/gfx-rs/wgpu/pull/9904). + #### Vulkan - Stop passing an un-waited fence to `vkAcquireNextImageKHR` on non-Windows platforms, which triggered `VUID-vkAcquireNextImageKHR-fence-10066` validation errors every frame since v30.0.0. By @ErichDonGubler in [#9855](https://github.com/gfx-rs/wgpu/issues/9855). diff --git a/naga/src/back/spv/helpers.rs b/naga/src/back/spv/helpers.rs index d3de25491..05d5c1ecc 100644 --- a/naga/src/back/spv/helpers.rs +++ b/naga/src/back/spv/helpers.rs @@ -15,10 +15,26 @@ pub(super) fn bytes_to_words(bytes: &[u8]) -> Vec { pub(super) fn string_to_words(input: &str) -> Vec { let bytes = input.as_bytes(); - str_bytes_to_words(bytes) + debug_str_bytes_to_words(bytes) } -pub(super) fn str_bytes_to_words(bytes: &[u8]) -> Vec { +/// Convert bytes to a vector of SPIR-V words, replacing NUL bytes with `?`. +/// +/// (Using the replacement character or NUL symbol would require changing +/// the length of the string, which would complicate chunking of the +/// program source.) +pub(super) fn debug_str_bytes_to_words(bytes: &[u8]) -> Vec { + let sanitized; + let bytes = if bytes.contains(&0) { + sanitized = bytes + .iter() + .map(|&b| if b == 0 { b'?' } else { b }) + .collect::>(); + &sanitized[..] + } else { + bytes + }; + let mut words = bytes_to_words(bytes); if bytes.len().is_multiple_of(4) { // nul-termination diff --git a/naga/src/back/spv/instructions.rs b/naga/src/back/spv/instructions.rs index 0a22bc3db..ffeea715b 100644 --- a/naga/src/back/spv/instructions.rs +++ b/naga/src/back/spv/instructions.rs @@ -48,7 +48,7 @@ impl super::Instruction { pub(super) fn source_continued(source: &[u8]) -> Self { let mut instruction = Self::new(Op::SourceContinued); - instruction.add_operands(helpers::str_bytes_to_words(source)); + instruction.add_operands(helpers::debug_str_bytes_to_words(source)); instruction } @@ -69,7 +69,7 @@ impl super::Instruction { let words = helpers::string_to_byte_chunks(debug_info.source_code, u16::MAX as usize); instruction.add_operand(debug_info.source_file_id); - instruction.add_operands(helpers::str_bytes_to_words(words[0])); + instruction.add_operands(helpers::debug_str_bytes_to_words(words[0])); instructions.push(instruction); for word_bytes in words[1..].iter() { let instruction_continue = Self::source_continued(word_bytes); diff --git a/naga/tests/naga/main.rs b/naga/tests/naga/main.rs index d7a930948..7253e3cdf 100644 --- a/naga/tests/naga/main.rs +++ b/naga/tests/naga/main.rs @@ -1,6 +1,7 @@ mod example_wgsl; mod snapshots; mod spirv_capabilities; +mod spirv_debug_info; mod spirv_roundtrip; mod validation; mod wgsl_errors; diff --git a/naga/tests/naga/spirv_debug_info.rs b/naga/tests/naga/spirv_debug_info.rs new file mode 100644 index 000000000..e2d71dffb --- /dev/null +++ b/naga/tests/naga/spirv_debug_info.rs @@ -0,0 +1,108 @@ +//! Regression test for https://github.com/gfx-rs/wgpu/issues/8082: a shader-module label +//! (or source) that contains embedded NUL characters caused Naga's SPIR-V backend to emit +//! invalid SPIR-V. SPIR-V literal strings are NUL-terminated, but Naga's string encoder +//! packed the raw UTF-8 bytes without any interior-NUL handling, so the emitted instruction +//! word count disagreed with where a parser stops the string. + +use std::io::Write as _; +use std::process::{Command, Stdio}; + +fn words_to_bytes(words: &[u32]) -> Vec { + let mut bytes = Vec::with_capacity(words.len() * 4); + for word in words { + bytes.extend_from_slice(&word.to_le_bytes()); + } + bytes +} + +/// Emit SPIR-V for a trivial compute shader with debug info forced on, then run +/// the result through `spirv-val`. Panics if `spirv-val` rejects the module. +fn write_and_validate(file_name: &str, source_code: &str) { + let module = naga::front::wgsl::parse_str("@compute @workgroup_size(1) fn main() {}").unwrap(); + + let mut validator = naga::valid::Validator::new( + naga::valid::ValidationFlags::all(), + naga::valid::Capabilities::empty(), + ); + let info = validator.validate(&module).unwrap(); + + let mut options = naga::back::spv::Options::default(); + // `Options::default()` only sets `DEBUG` under `debug_assertions`, so force it + // on to guarantee the debug-info strings are emitted regardless of build mode. + options.flags |= naga::back::spv::WriterFlags::DEBUG; + options.debug_info = Some(naga::back::spv::DebugInfo { + source_code, + file_name, + language: naga::back::spv::SourceLanguage::Unknown, + }); + + let pipeline_options = naga::back::spv::PipelineOptions { + entry_point: "main".to_string(), + shader_stage: naga::ShaderStage::Compute, + }; + + let words = + naga::back::spv::write_vec(&module, &info, &options, Some(&pipeline_options)).unwrap(); + let bytes = words_to_bytes(&words); + + let mut child = Command::new("spirv-val") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect( + "Failed to execute spirv-val. It can be installed \ + by installing the Vulkan SDK and adding it to your path.", + ); + + child + .stdin + .as_mut() + .unwrap() + .write_all(&bytes) + .expect("failed to write SPIR-V module to spirv-val stdin"); + + let output = child + .wait_with_output() + .expect("failed to wait for spirv-val"); + + assert!( + output.status.success(), + "spirv-val rejected naga output:\n{}", + String::from_utf8_lossy(&output.stderr) + ); +} + +/// Sanity check: a trivial shader with clean strings must validate, proving the +/// harness itself is sound. +#[cfg_attr(miri, ignore)] +#[test] +fn clean_label_validates() { + write_and_validate("shader.wgsl", "@compute @workgroup_size(1) fn main() {}"); +} + +/// The exact label from the issue #8082 trace, exercising the `OpString` +/// (debug source file name) path. +#[cfg_attr(miri, ignore)] +#[test] +fn embedded_nul_in_file_name() { + write_and_validate( + "\0)@\u{1}\u{1}ompute\n@workgroup_size(1)\nfn main() {\n}\u{15}\0\0\u{1}\0\u{1}\u{1}\u{1})@compute\n@workgroup_size(1)\nfn main() {\n}\u{15}\0\0\u{1}\0", + "@compute @workgroup_size(1) fn main() {}", + ); +} + +/// An embedded NUL in the source code, exercising the `OpSource` path. +#[cfg_attr(miri, ignore)] +#[test] +fn embedded_nul_in_source_code() { + write_and_validate("shader.wgsl", "before\0after"); +} + +/// A NUL that lands exactly on a 4-byte boundary, exercising the trailing-NUL +/// branch of `debug_str_bytes_to_words`. +#[cfg_attr(miri, ignore)] +#[test] +fn embedded_nul_at_word_boundary() { + write_and_validate("abcd\0efgh", "@compute @workgroup_size(1) fn main() {}"); +}