diff --git a/crates/metal2vulkan-validation/src/replay/mod.rs b/crates/metal2vulkan-validation/src/replay/mod.rs index a8e8a253b..3ced92c35 100644 --- a/crates/metal2vulkan-validation/src/replay/mod.rs +++ b/crates/metal2vulkan-validation/src/replay/mod.rs @@ -9,7 +9,7 @@ mod value; pub use old_runtime::OldRuntime; pub use player::WAIT_COMPLETED; -pub use player::{Backend, Check, Counters, Counts, Made, PlayError, Player, Report}; +pub use player::{Backend, Check, Counters, Counts, IdDiffers, Made, PlayError, Player, Report}; pub use stream::{segments, Call, StreamError, StreamReader, StreamWriter}; pub use value::{Hash, Name, Value}; diff --git a/crates/metal2vulkan-validation/src/replay/old_runtime/args.rs b/crates/metal2vulkan-validation/src/replay/old_runtime/args.rs index b55b4b1b4..aaee37db3 100644 --- a/crates/metal2vulkan-validation/src/replay/old_runtime/args.rs +++ b/crates/metal2vulkan-validation/src/replay/old_runtime/args.rs @@ -135,6 +135,13 @@ impl<'c> Fields<'c> { self.typed(key, "an object", Value::as_object) } + /// An object property a setter record sets: none where it is left as it was (nil), `Some(None)` + /// where it is set to nil (object 0), else the object. + pub(super) fn set_object(&self, key: &str) -> Result>, PlayError> { + let set = self.object(key)?; + Ok(set.map(|id| Some(id).filter(|&id| id != 0))) + } + pub(super) fn str(&self, key: &str) -> Result, PlayError> { self.typed(key, "a string", Value::as_str) } diff --git a/crates/metal2vulkan-validation/src/replay/old_runtime/descriptors.rs b/crates/metal2vulkan-validation/src/replay/old_runtime/descriptors.rs index 8146a0f7f..0b24172aa 100644 --- a/crates/metal2vulkan-validation/src/replay/old_runtime/descriptors.rs +++ b/crates/metal2vulkan-validation/src/replay/old_runtime/descriptors.rs @@ -122,11 +122,12 @@ fn option_sets(call: &Call, initial: u64, sets: &[Value]) -> Result Result<(u64, ResourceOptions), PlayError> { let f = Fields::arg( call, @@ -142,7 +143,7 @@ pub(super) fn buffer(call: &Call) -> Result<(u64, ResourceOptions), PlayError> { ], )?; if f.get("contents").is_some() { - return Err(refuse(call, "contents other than host memory")); + return Err(refuse(call, "contents that are no bytes")); } let sets = f.list("options")?.unwrap_or_default(); let mut raw = option_sets(call, 0, sets)?; @@ -580,10 +581,11 @@ fn attachment_keys(own: &[&'static str]) -> Vec<&'static str> { ATTACHMENT_KEYS.iter().chain(own).copied().collect() } -/// What an attachment's setter record sets of the properties every attachment has, resolved. +/// What an attachment's setter record sets of the properties every attachment has, resolved: an +/// object property `Some(None)` where it is set to nil. struct AttachmentSet { - texture: Option, - resolve_texture: Option, + texture: Option>, + resolve_texture: Option>, level: Option, slice: Option, depth_plane: Option, @@ -601,10 +603,10 @@ macro_rules! set_attachment { let set = $set; let a = $a; if let Some(texture) = set.texture { - a.texture = Some(texture); + a.texture = texture; } if let Some(texture) = set.resolve_texture { - a.resolve_texture = Some(texture); + a.resolve_texture = texture; } let numbers = [ (set.level, &mut a.level), @@ -795,8 +797,9 @@ impl OldRuntime { /// What an attachment's map sets of the properties every attachment has. fn attachment_set(&self, call: &Call, f: &Fields) -> Result { - let texture = |key: &str| match f.object(key)? { - Some(id) => self.texture_of(call, id).map(Some), + let texture = |key: &str| match f.set_object(key)? { + Some(Some(id)) => self.texture_of(call, id).map(|texture| Some(Some(texture))), + Some(None) => Ok(Some(None)), None => Ok(None), }; Ok(AttachmentSet { @@ -831,19 +834,22 @@ impl OldRuntime { } /// A setter record of the render pass descriptor `call` is sent to: each property its map - /// sets. A nil property is left as it is; `defaultColorSampleCount`, which changes nothing a - /// pass shows, is not played; a rate map and accumulated visibility results are refused. + /// sets. A nil property is left as it is, and an object property of object 0 set to nil; + /// `defaultColorSampleCount`, which changes nothing a pass shows, is not played; a rate map + /// and accumulated visibility results are refused. pub(super) fn pass_call(&mut self, call: &Call) -> Result<(), PlayError> { let failed = super::args::failed(call); match &*call.selector { "m2v.setPass" => { let f = Fields::arg(call, 0, &PASS_KEYS)?; - if f.get("rasterizationRateMap").is_some() { + // The pass never holds a rate map, so one set to nil changes nothing. + if let Some(Some(_)) = f.set_object("rasterizationRateMap")? { return Err(refuse(call, "a rasterization rate map")); } f.only("visibilityResultType", Fields::uint, 0)?; - let visibility = match f.object("visibilityResultBuffer")? { - Some(id) => Some(self.buffer_of(call, id)?), + let visibility = match f.set_object("visibilityResultBuffer")? { + Some(Some(id)) => Some(Some(self.buffer_of(call, id)?)), + Some(None) => Some(None), None => None, }; let numbers = [ @@ -858,7 +864,7 @@ impl OldRuntime { ] .map(|key| f.uint(key)); let pass = self.pass(call.receiver); - if visibility.is_some() { + if let Some(visibility) = visibility { pass.visibility_result_buffer = visibility; } let fields = [ diff --git a/crates/metal2vulkan-validation/src/replay/old_runtime/mod.rs b/crates/metal2vulkan-validation/src/replay/old_runtime/mod.rs index 7e8be441c..8558d63b9 100644 --- a/crates/metal2vulkan-validation/src/replay/old_runtime/mod.rs +++ b/crates/metal2vulkan-validation/src/replay/old_runtime/mod.rs @@ -735,6 +735,26 @@ impl Backend for OldRuntime { } } + fn resource_id(&mut self, object: u64) -> Result, PlayError> { + let id = match self.objects.get(&object) { + Some(Object::Texture(texture)) => texture.gpu_resource_id(), + Some(Object::Sampler(sampler)) => sampler.gpu_resource_id(), + Some(Object::ComputePipeline(state)) => state.gpu_resource_id(), + Some(Object::RenderPipeline(state)) => state.gpu_resource_id(), + // Refused on a device that claims Apple10, where Metal's getter raises. + Some(Object::DepthStencil(state)) => match state.gpu_resource_id() { + Ok(id) => id, + Err(_) => return Ok(None), + }, + _ => { + return Err(PlayError::Invalid(format!( + "gpuResourceID of #{object}, which has none" + ))) + } + }; + Ok(Some(id.0)) + } + fn counters(&mut self) -> Counters { let counts = self.device.work_counts(); let c = &counts.commands_recorded; diff --git a/crates/metal2vulkan-validation/src/replay/player.rs b/crates/metal2vulkan-validation/src/replay/player.rs index 114e55d3c..3d7093ebe 100644 --- a/crates/metal2vulkan-validation/src/replay/player.rs +++ b/crates/metal2vulkan-validation/src/replay/player.rs @@ -47,9 +47,11 @@ pub struct Made { /// One runtime behind the player. Objects are named by their stream ids; the player resolves blobs /// and relocates before a call reaches the backend, and handles `m2v.write`, `m2v.check`, -/// `m2v.present`, `release` of a device, and the program's waits itself. A copy from the guest's -/// RAM reaches it with its data relocated ([`upload`] says where the data lands), and a record of -/// the host's own plumbing as the plain Metal call it stands for ([`plain`]). +/// `m2v.present`, `m2v.commitPart`, `gpuResourceID`, `release` of a device, and the program's +/// waits itself. A copy from the guest's RAM reaches it with its data relocated ([`upload`] says +/// where the data lands), a record of the host's own plumbing as the plain Metal call it stands +/// for ([`plain`]), and a copied buffer's descriptor without its `contents`, which reach it as a +/// write once the buffer is made ([`copied`]). pub trait Backend { /// Run `call`: make its result, or run its receiver's method, or drop the object `release` /// names. @@ -60,6 +62,8 @@ pub trait Backend { fn wait(&mut self, command_buffer: u64) -> Result<(), PlayError>; /// The bytes of buffer or texture `object`, for a checksum. fn read(&mut self, object: u64) -> Result, PlayError>; + /// The `gpuResourceID` the runtime gives `object`; none where its getter raises. + fn resource_id(&mut self, object: u64) -> Result, PlayError>; /// The runtime's counters now. fn counters(&mut self) -> Counters; } @@ -108,6 +112,16 @@ pub struct Check { pub recorded: Option, } +/// An object whose `gpuResourceID` in the runtime is not the one the program saw: the bytes that +/// hold the program's ID name no object of the play. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct IdDiffers { + pub object: u64, + pub recorded: u64, + /// None where the runtime's getter raises. + pub played: Option, +} + /// What one span of a play counted. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Counts { @@ -135,6 +149,7 @@ pub struct Report { /// Each frame's counts: the groups completed since the present before. pub frames: Vec, pub checks: Vec, + pub ids: Vec, /// The whole play's counts, the player's readbacks left out. Its calls are the calls played: /// where a play stopped, the stopping call is the next. pub total: Counts, @@ -171,6 +186,12 @@ impl Report { let sha = super::value::hex(&check.sha256); lines.push(format!("check #{} {sha} {verdict}", check.object)); } + for id in &self.ids { + let played = id + .played + .map_or("none".to_owned(), |played| format!("{played:#x}")); + lines.push(format!("id #{} {:#x} {played}", id.object, id.recorded)); + } lines.push(format!("total{}", counted(&self.total))); lines } @@ -211,6 +232,8 @@ pub struct Player<'b, B: Backend> { committed: Vec, /// Each event's value as far as the stream has set or completed it. events: HashMap, + /// The live objects whose `gpuResourceID` the player compared. + compared: HashSet, baseline: Counters, /// The counts the stream fixes, since the last group. fixed: Counters, @@ -326,6 +349,39 @@ fn plain(mut call: Call) -> Option { Some(call) } +/// Whether the host committed the command buffer of `m2v.commitPart` `call`: where its answer `cut` +/// is `"Cut"`, or absent; not where it is `"Fails"` or `{Whole: reason}`. +fn cut(call: &Call) -> Result { + let Some(cut) = call.answer("cut") else { + return Ok(true); + }; + match cut { + Value::Str(cut) if cut == "Cut" => Ok(true), + Value::Str(cut) if cut == "Fails" => Ok(false), + Value::Map(whole) if whole.len() == 1 && &*whole[0].0 == "Whole" => Ok(false), + _ => Err(invalid(format!("m2v.commitPart's cut {cut}"))), + } +} + +/// `descriptor`, a `newBufferWithDescriptor:` map, with its `contents` nil, and the bytes they +/// held: what a buffer made as a copy of host memory starts with, which the player writes once the +/// buffer is made (`docs/REPLAY-STREAM.md`, section 5). +fn copied(descriptor: Value) -> (Value, Option>) { + let Value::Map(fields) = descriptor else { + return (descriptor, None); + }; + let mut contents = None; + let fields = fields.into_iter().map(|(key, value)| match value { + Value::Bytes(bytes) if &*key == "contents" => { + contents = Some(bytes); + (key, Value::Nil) + } + value => (key, value), + }); + let fields = fields.collect(); + (Value::Map(fields), contents) +} + /// The program's waits for a command buffer, as a stream records them: names of records, not /// waits (the player's own waits are its backend's, under `gpu::wait`). Spelled in pieces so the /// check that every device wait is bounded (`gpu::tests`) finds none here. @@ -350,6 +406,7 @@ impl<'b, B: Backend> Player<'b, B> { pending: HashMap::new(), committed: Vec::new(), events: HashMap::new(), + compared: HashSet::new(), baseline, fixed, frame: Counts::default(), @@ -430,7 +487,12 @@ impl<'b, B: Backend> Player<'b, B> { self.frame = Counts::default(); Ok(()) } - "commit" | "m2v.commitPart" => self.commit(call.receiver), + "commit" => self.commit(call.receiver), + "m2v.commitPart" => match cut(&call)? { + true => self.commit(call.receiver), + false => Ok(()), + }, + "gpuResourceID" => self.resource_id(&call), // A split or part of result 0 is one the host did not cut. "m2v.split" | "m2v.part" if call.result == 0 => Ok(()), "m2v.split" => { @@ -531,15 +593,56 @@ impl<'b, B: Backend> Player<'b, B> { Ok(()) } - /// A call the backend runs, its blobs and addresses resolved, and what it made recorded. + /// Compare the ID the program saw of `call`'s receiver, where it saw one, with the runtime's, + /// once per object, and report the object where they differ. + fn resource_id(&mut self, call: &Call) -> Result<(), PlayError> { + let object = call.receiver; + if !self.kinds.contains_key(&object) { + return Err(invalid(format!( + "gpuResourceID of #{object}, made by no call" + ))); + } + // A getter that raised answers nothing. + let Some(recorded) = call.answer("gpuResourceID") else { + return Ok(()); + }; + let recorded = recorded.as_uint(); + let recorded = recorded.ok_or_else(|| invalid("gpuResourceID answers no uint"))?; + if !self.compared.insert(object) { + return Ok(()); + } + let played = self.backend.resource_id(object)?; + if played != Some(recorded) { + let differs = IdDiffers { + object, + recorded, + played, + }; + self.report.ids.push(differs); + } + Ok(()) + } + + /// A call the backend runs, its blobs and addresses resolved, and what it made recorded; a + /// copied buffer's `contents` written once it is made. fn make(&mut self, stream: &mut StreamReader, call: Call) -> Result<(), PlayError> { let Some(call) = plain(call) else { return Ok(()); }; let mut relocated = 0; let mut args = Vec::with_capacity(call.args.len()); - for arg in &call.args { - args.push(self.resolve(stream, arg, &mut relocated)?); + let mut contents = None; + for (at, arg) in call.args.iter().enumerate() { + let arg = self.resolve(stream, arg, &mut relocated)?; + let arg = match (at, &*call.selector) { + (0, "newBufferWithDescriptor:") => { + let (descriptor, bytes) = copied(arg); + contents = bytes; + descriptor + } + _ => arg, + }; + args.push(arg); } *self.fixed.entry(RELOCATED_WORDS).or_default() += relocated; if sets_bytes(&call.selector) { @@ -574,7 +677,10 @@ impl<'b, B: Backend> Player<'b, B> { .insert(object, address, length, base) .map_err(PlayError::Invalid)?; } - Ok(()) + match contents { + Some(bytes) => self.put(object, 0, bytes), + None => Ok(()), + } } /// `call` with the data of the upload it is, if any, relocated where its target answered a @@ -683,20 +789,26 @@ impl<'b, B: Backend> Player<'b, B> { for [offset, data] in pairs { let offset = offset.as_uint(); let offset = offset.ok_or_else(|| invalid("m2v.write of no offset"))?; - let mut data = match data { + let data = match data { Value::Bytes(data) => data.clone(), Value::Blob(hash) => stream.blob(hash)?, _ => return Err(invalid("m2v.write of no data")), }; - if self.addresses.holds(target) { - self.relocate(&mut data, offset); - } - *self.fixed.entry(WRITTEN_BYTES).or_default() += data.len() as u64; - self.backend.write(target, offset, &data)?; + self.put(target, offset, data)?; } Ok(()) } + /// Put `data` at `offset` of `target`, relocated where the target answered a `gpuAddress`, and + /// count it. + fn put(&mut self, target: u64, offset: u64, mut data: Vec) -> Result<(), PlayError> { + if self.addresses.holds(target) { + self.relocate(&mut data, offset); + } + *self.fixed.entry(WRITTEN_BYTES).or_default() += data.len() as u64; + self.backend.write(target, offset, &data) + } + /// Relocate `data`, which starts `offset` bytes into its target, and count what it found. fn relocate(&mut self, data: &mut [u8], offset: u64) { let (moved, misaligned) = self.addresses.relocate(data, offset); @@ -747,6 +859,7 @@ impl<'b, B: Backend> Player<'b, B> { fn drop_object(&mut self, object: u64) -> Result<(), PlayError> { self.addresses.remove(object); self.owner.remove(&object); + self.compared.remove(&object); if let Some(pending) = self.pending.get_mut(&object) { if pending.committed { pending.released = true; diff --git a/crates/metal2vulkan-validation/src/replay/tests.rs b/crates/metal2vulkan-validation/src/replay/tests.rs index 903920347..e5cc1383b 100644 --- a/crates/metal2vulkan-validation/src/replay/tests.rs +++ b/crates/metal2vulkan-validation/src/replay/tests.rs @@ -2,7 +2,9 @@ //! is asked (no device). The runtime backends' tests are device tests (`runtime_lane`). use super::addresses::AddressMap; -use super::player::{Backend, Counters, Counts, Made, PlayError, Player, Report, WAIT_COMPLETED}; +use super::player::{ + Backend, Counters, Counts, IdDiffers, Made, PlayError, Player, Report, WAIT_COMPLETED, +}; use super::stream::{segments, Call, StreamError, StreamReader, StreamWriter}; use super::value::{hex, Value}; use crate::ScratchDir; @@ -250,8 +252,9 @@ fn the_address_map_relocates_by_the_innermost_live_range() { ); } -/// A backend that keeps what it is asked: the calls, the waits, the bytes written. It places -/// blocks and buffers apart from the recorded addresses, and a buffer in a block at its offset. +/// A backend that keeps what it is asked: the calls, the waits, the bytes written, the objects +/// whose resource IDs it gave. It places blocks and buffers apart from the recorded addresses, and +/// a buffer in a block at its offset. #[derive(Default)] struct Kept { calls: Vec, @@ -262,6 +265,9 @@ struct Kept { bases: HashMap, next: u64, commits: u64, + /// The resource IDs it gives; an object not here has none (its getter raises). + ids: HashMap, + asked: Vec, } impl Backend for Kept { @@ -270,7 +276,9 @@ impl Backend for Kept { self.args.push(call.args.clone()); let mut made = Made::default(); match &*call.selector { - "m2v.newBlockWithLength:storageMode:" | "newBufferWithLength:options:" => { + "m2v.newBlockWithLength:storageMode:" + | "newBufferWithLength:options:" + | "newBufferWithDescriptor:" => { self.next += 0x1000_0000; made.address = Some(self.next); } @@ -307,6 +315,11 @@ impl Backend for Kept { Ok(object.to_le_bytes().to_vec()) } + fn resource_id(&mut self, object: u64) -> Result, PlayError> { + self.asked.push(object); + Ok(self.ids.get(&object).copied()) + } + fn counters(&mut self) -> Counters { Counters::from([("submissions", self.commits)]) } @@ -730,3 +743,123 @@ fn the_stream_fixes_its_calls_commits_encoders_draws_and_dispatches() { misaligned_address_words=0 relocated_words=0 written_bytes=0 executed submissions=1" ); } + +/// `m2v.commitPart` commits its command buffer where its answer `cut` is "Cut" or absent, and +/// nothing where the host committed nothing ("Fails", `{Whole: reason}`); a command buffer kept +/// whole commits at its own `commit`. Any other answer stops the play. +#[test] +fn a_part_commits_only_where_the_host_cut_it() { + let mut kept = Kept::default(); + let cut = |cut: &str| [("cut", Value::Str(cut.to_owned()))]; + let whole = [("cut", map(&[("Whole", Value::Str("Committed".to_owned()))]))]; + let (report, ended) = played(&mut kept, |w| { + w.call("MTLCreateSystemDefaultDevice", 0, 1, &[], &[])?; + w.call("newCommandQueue", 1, 2, &[], &[])?; + for command_buffer in 3..=6 { + w.call("commandBuffer", 2, command_buffer, &[], &[])?; + } + w.call("m2v.commitPart", 3, 0, &[], &cut("Cut"))?; + w.call("m2v.commitPart", 4, 0, &[], &[])?; + w.call("m2v.commitPart", 5, 0, &[], &cut("Fails"))?; + w.call("m2v.commitPart", 6, 0, &[], &whole)?; + w.call("commit", 6, 0, &[], &[])?; + w.call("m2v.commitPart", 5, 0, &[], &[("cut", Value::Uint(1))]) + }); + match ended { + Err(PlayError::Invalid(why)) => assert!(why.contains("m2v.commitPart's cut"), "{why}"), + other => panic!("the play went on past an unknown cut: {other:?}"), + } + assert_eq!(kept.waits, [3, 4, 6]); + assert_eq!(kept.commits, 3); + assert_eq!(report.total.stream["commits"], 3); +} + +/// A buffer made as a copy of host memory starts with its descriptor's `contents`, a blob or +/// inline bytes: the backend makes it with the contents nil, and the player writes them from its +/// first byte, relocated where it answered a `gpuAddress` (here a pointer into itself) and +/// counted; a buffer of no address is written as it is, and a no-copy buffer's nil contents +/// write nothing. +#[test] +fn a_copied_buffer_starts_with_its_contents() { + let mut kept = Kept::default(); + let pointer = (BLOCK + 0x40).to_le_bytes(); + let mut long = vec![5u8; 128]; + long[8..16].copy_from_slice(&pointer); + let descriptor = |length: u64, contents: Value, no_copy: bool| { + let options = Value::List(Vec::new()); + let fields = [ + ("length", Value::Uint(length)), + ("options", options), + ("contents", contents), + ("noCopy", Value::Bool(no_copy)), + ]; + [map(&fields)] + }; + let selector = "newBufferWithDescriptor:"; + let (report, ended) = played(&mut kept, |w| { + w.call("MTLCreateSystemDefaultDevice", 0, 1, &[], &[])?; + let blob = Value::Blob(w.blob(&long)?); + let at = addressed(BLOCK, 128); + w.call(selector, 1, 2, &descriptor(128, blob, false), &at)?; + let short = Value::Bytes(pointer.to_vec()); + w.call(selector, 1, 3, &descriptor(8, short, false), &[])?; + w.call(selector, 1, 4, &descriptor(8, Value::Nil, true), &[]) + }); + ended.unwrap(); + for args in &kept.args[1..] { + let contents = args[0] + .as_map() + .unwrap() + .iter() + .find(|(k, _)| &**k == "contents"); + assert_eq!(contents.map(|(_, v)| v), Some(&Value::Nil)); + } + let mut moved = long.clone(); + moved[8..16].copy_from_slice(&(0x1000_0000u64 + 0x40).to_le_bytes()); + let untouched = (3, 0, pointer.to_vec()); + assert_eq!(kept.writes, [(2, 0, moved), untouched]); + assert_eq!(report.total.stream["written_bytes"], 128 + 8); + assert_eq!(report.total.stream["relocated_words"], 1); +} + +/// A `gpuResourceID` record compares the ID the program saw with the runtime's, once per object: +/// an object the runtime gives another ID, or none, is reported; one whose getter raised (no +/// answer) is not asked; one the stream never made stops the play. +#[test] +fn a_resource_id_the_runtime_gives_otherwise_is_reported() { + let mut kept = Kept { + ids: HashMap::from([(2, 0x4d), (3, 0x99)]), + ..Kept::default() + }; + let id = |id: u64| [("gpuResourceID", Value::Uint(id))]; + let (report, ended) = played(&mut kept, |w| { + w.call("MTLCreateSystemDefaultDevice", 0, 1, &[], &[])?; + for object in 2..=5 { + w.call("newSamplerStateWithDescriptor:", 1, object, &[], &[])?; + } + w.call("gpuResourceID", 2, 0, &[], &id(0x4d))?; + w.call("gpuResourceID", 3, 0, &[], &id(0x1_0000_0005))?; + w.call("gpuResourceID", 3, 0, &[], &id(0x1_0000_0005))?; + w.call("gpuResourceID", 4, 0, &[], &id(7))?; + w.call("gpuResourceID", 5, 0, &[], &[])?; + w.call("gpuResourceID", 9, 0, &[], &id(1)) + }); + match ended { + Err(PlayError::Invalid(why)) => assert!(why.contains("#9, made by no call"), "{why}"), + other => panic!("the play went on past an unmade object: {other:?}"), + } + assert_eq!(kept.asked, [2, 3, 4]); + let differs = |object, recorded, played| IdDiffers { + object, + recorded, + played, + }; + let ids = [differs(3, 0x1_0000_0005, Some(0x99)), differs(4, 7, None)]; + assert_eq!(report.ids, ids); + let lines = report.lines(); + assert!( + lines.contains(&"id #3 0x100000005 0x99".to_owned()), + "{lines:?}" + ); + assert!(lines.contains(&"id #4 0x7 none".to_owned()), "{lines:?}"); +} diff --git a/crates/metal2vulkan-validation/src/runtime_lane/replay_streams.rs b/crates/metal2vulkan-validation/src/runtime_lane/replay_streams.rs index 3a00ec692..79f00bf6c 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/replay_streams.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/replay_streams.rs @@ -9,6 +9,9 @@ //! - Textures made from descriptor records read back as written. //! - A render pass its setter records describe clears a drawable the stream never saw made. //! - The copies from the guest's RAM and a device copy's fill land where their pieces say. +//! - A pass setter's object 0 clears the attachment's texture it sets to nil. +//! - A buffer made as a copy of host memory starts with its contents, and the IDs the program saw +//! are compared with the runtime's. //! //! Each device takes its queue plan ([`at_plan`]): the player's readbacks take a command queue of //! their own beside the stream's. @@ -461,3 +464,179 @@ fn guest_ram_copies_land_where_their_pieces_say() { assert_eq!(report.total.stream["relocated_words"], 0); }); } + +/// A 4 by 4 RGBA8Unorm texture descriptor record's map, shader-read and render-target, Shared, +/// with `extra` fields. +fn render_target(extra: Vec<(&str, Value)>) -> Value { + let Value::Map(mut fields) = uints(&[ + ("pixelFormat", 70), + ("width", 4), + ("height", 4), + ("usage", 5), + ("resourceOptions", 0), + ]) else { + unreachable!("a map"); + }; + fields.extend(extra.into_iter().map(|(key, value)| (key.into(), value))); + Value::Map(fields) +} + +/// The whole of a 4 by 4 texture. +fn whole() -> Value { + Value::Map(vec![ + ("origin".into(), uints(&[("x", 0), ("y", 0), ("z", 0)])), + ( + "size".into(), + uints(&[("width", 4), ("height", 4), ("depth", 1)]), + ), + ]) +} + +/// A pass whose setter records set attachment 1's texture and then set it to nil (object 0) +/// clears attachment 0's texture to green and leaves the other's blue, as Metal leaves a texture +/// no attachment holds; object 0 for the visibility result buffer, the rate map and a resolve +/// texture plays too. +#[test] +fn a_pass_setter_clears_an_attachment_set_to_nil() { + let dir = ScratchDir::new("replay-pass-nil").unwrap(); + let [red, blue] = [[255u8, 0, 0, 255], [0, 0, 255, 255]].map(|texel| texel.repeat(16)); + let green: Vec = [0u8, 255, 0, 255].repeat(16); + let path = written(&dir, |w| { + w.call("MTLCreateSystemDefaultDevice", 0, 1, &[], &[])?; + w.call("newCommandQueue", 1, 2, &[], &[])?; + w.call("m2v.textureDescriptor", 0, 3, &[render_target(vec![])], &[])?; + for (texture, texels) in [(4, &red), (5, &blue)] { + w.call( + "newTextureWithDescriptor:", + 1, + texture, + &[Value::Object(3)], + &[], + )?; + let args = [ + whole(), + Value::Uint(0), + Value::Bytes(texels.clone()), + Value::Uint(16), + ]; + let selector = "replaceRegion:mipmapLevel:withBytes:bytesPerRow:"; + w.call(selector, texture, 0, &args, &[])?; + } + let shared = [Value::Uint(64), Value::Uint(0)]; + w.call("newBufferWithLength:options:", 1, 6, &shared, &[])?; + w.call("MTLRenderPassDescriptor.new", 0, 7, &[], &[])?; + let pass = |visibility: u64, rate_map: Value| { + Value::Map(vec![ + ("visibilityResultBuffer".into(), Value::Object(visibility)), + ("rasterizationRateMap".into(), rate_map), + ("renderTargetWidth".into(), Value::Uint(4)), + ("renderTargetHeight".into(), Value::Uint(4)), + ]) + }; + w.call("m2v.setPass", 7, 0, &[pass(6, Value::Nil)], &[])?; + w.call("m2v.setPass", 7, 0, &[pass(0, Value::Object(0))], &[])?; + let clear = |color: [f64; 4]| { + let channels = ["red", "green", "blue", "alpha"].into_iter().zip(color); + Value::Map( + channels + .map(|(key, value)| (key.into(), Value::F64(value))) + .collect(), + ) + }; + let attachment = |texture: u64, color: [f64; 4]| { + let Value::Map(mut fields) = + uints(&[("level", 0), ("loadAction", 2), ("storeAction", 1)]) + else { + unreachable!("a map"); + }; + fields.push(("texture".into(), Value::Object(texture))); + fields.push(("resolveTexture".into(), Value::Object(0))); + fields.push(("clearColor".into(), clear(color))); + Value::Map(fields) + }; + let set = [Value::Uint(0), attachment(4, [0.0, 1.0, 0.0, 1.0])]; + w.call("m2v.setColorAttachment", 7, 0, &set, &[])?; + let set = [Value::Uint(1), attachment(5, [1.0, 0.0, 0.0, 1.0])]; + w.call("m2v.setColorAttachment", 7, 0, &set, &[])?; + let nil = Value::Map(vec![("texture".into(), Value::Object(0))]); + w.call("m2v.setColorAttachment", 7, 0, &[Value::Uint(1), nil], &[])?; + w.call("commandBuffer", 2, 8, &[], &[])?; + let pass = [Value::Object(7)]; + w.call("renderCommandEncoderWithDescriptor:", 8, 9, &pass, &[])?; + w.call("endEncoding", 9, 0, &[], &[])?; + w.call("commit", 8, 0, &[], &[])?; + let sums = [&green, &blue].map(|texels| Value::Bytes(Sha256::digest(texels).to_vec())); + let answer = [("sha256", Value::List(sums.to_vec()))]; + w.call( + "m2v.check", + 0, + 0, + &[Value::Object(4), Value::Object(5)], + &answer, + ) + }); + on_device_with(at_plan, |device| { + let report = play("pass-nil", device, &path); + assert_eq!(report.checks.len(), 2); + for check in &report.checks { + assert_eq!(Some(check.sha256), check.recorded, "#{}", check.object); + } + }); +} + +/// A buffer `newBufferWithDescriptor:` made as a copy of host memory reads back as its +/// `contents`, a blob and inline bytes; a texture placed at its resource index gives the ID the +/// program saw, and one the runtime placed where it had room another, which the report names. +#[test] +fn a_copied_buffer_starts_with_its_contents_and_ids_are_compared() { + let dir = ScratchDir::new("replay-contents-ids").unwrap(); + let long: Vec = (0..=255).collect(); + let short = [9u8; 8]; + let recorded = 0xdead_0000_0001; + let path = written(&dir, |w| { + w.call("MTLCreateSystemDefaultDevice", 0, 1, &[], &[])?; + let blob = Value::Blob(w.blob(&long)?); + for (buffer, length, contents) in [(2, 256, blob), (3, 8, Value::Bytes(short.to_vec()))] { + let descriptor = Value::Map(vec![ + ("length".into(), Value::Uint(length)), + ("options".into(), Value::List(Vec::new())), + ("contents".into(), contents), + ("noCopy".into(), Value::Bool(false)), + ]); + w.call("newBufferWithDescriptor:", 1, buffer, &[descriptor], &[])?; + } + let placed = Value::List(vec![Value::Uint(77), Value::Bool(true)]); + let at_77 = render_target(vec![("resourceIndex", placed)]); + w.call("m2v.textureDescriptor", 0, 4, &[at_77], &[])?; + w.call("m2v.textureDescriptor", 0, 5, &[render_target(vec![])], &[])?; + for (texture, descriptor, id) in [(6, 4, 77), (7, 5, recorded)] { + let args = [Value::Object(descriptor)]; + w.call("newTextureWithDescriptor:", 1, texture, &args, &[])?; + let answer = [("gpuResourceID", Value::Uint(id))]; + w.call("gpuResourceID", texture, 0, &[], &answer)?; + } + let sums = + [&long[..], &short[..]].map(|bytes| Value::Bytes(Sha256::digest(bytes).to_vec())); + let answer = [("sha256", Value::List(sums.to_vec()))]; + w.call( + "m2v.check", + 0, + 0, + &[Value::Object(2), Value::Object(3)], + &answer, + ) + }); + on_device_with(at_plan, |device| { + let report = play("contents-ids", device, &path); + for check in &report.checks { + assert_eq!(Some(check.sha256), check.recorded, "#{}", check.object); + } + assert_eq!(report.total.stream["written_bytes"], 256 + 8); + assert_eq!(report.ids.len(), 1, "{:?}", report.ids); + assert_eq!( + (report.ids[0].object, report.ids[0].recorded), + (7, recorded) + ); + assert!(report.ids[0].played.is_some_and(|id| id != recorded)); + }); +} diff --git a/docs/REPLAY-STREAM.md b/docs/REPLAY-STREAM.md index bc0c69499..471dc83f1 100644 --- a/docs/REPLAY-STREAM.md +++ b/docs/REPLAY-STREAM.md @@ -48,7 +48,7 @@ Each value starts with a one-byte tag. | 4 | sint | zigzag varint | signed integers | | 5 | f32 | 4 bytes | read as a number; the recorder writes `float` as f64 | | 6 | f64 | 8 bytes | `float`, `double`, `CGFloat` | -| 7 | object | varint id | Metal objects | +| 7 | object | varint id | Metal objects; object 0, which no object is, a property set to nil (section 9) | | 8 | address | varint | a GPU address: relocated (section 5) | | 9 | string | varint length, UTF-8 | `NSString`, names | | 10 | bytes | varint length, data | data, inline | @@ -61,8 +61,9 @@ Each value starts with a one-byte tag. `MTLSize` `{width, height, depth}`, `MTLRegion` `{origin, size}`, `NSRange` `{location, length}`, `MTLScissorRect` `{x, y, width, height}`, `MTLViewport` `{originX, originY, width, height, znear, zfar}`, `MTLClearColor` and `MTLTextureSwizzleChannels` `{red, green, blue, alpha}`. -- **An optional field** is nil where it is unset. One set to nil reads the same: a player leaves - the property as it was either way. +- **An optional field** is nil where it is unset, and a player leaves the property as it was. One + set to nil reads the same, but for the object properties of the pass descriptor's setters + (section 9): one of those set to nil is object 0, which a player clears. - **Other shapes:** a range of host addresses is the list `[start, end]`; a tuple is a list; an enum value without data is its name as a string (`"Itu709"`); one with data is a map of one pair, `{Name: value}` (a resource `{Buffer: object}` or `{Texture: object}`, an option setter @@ -87,7 +88,7 @@ and the (name id, value) answer pairs. later calls and writes. - **Answers:** what the call returned that the program could see (section 5). A player ignores answer keys it does not use. -- Getters are not recorded. +- Getters are not recorded, but for `gpuResourceID` (section 5). ## 4. Objects @@ -124,14 +125,18 @@ and the (name id, value) answer pairs. without a pinned address answers none. `newBufferWithBytesNoCopy:length:options:deallocator:` is `[nil, length, options, nil]`, and a no-copy descriptor's `contents` nil; their bytes arrive as writes. +- **Copied buffers.** A buffer `newBufferWithDescriptor:` made as a copy of host memory (`contents` + set, `noCopy` not) carries the bytes it starts with as its descriptor's `contents`: a blob where + they are 64 bytes or longer, bytes otherwise. The player makes the buffer, then puts them at its + first byte as a write's bytes (section 6). - **Textures over memory:** a buffer's `newTextureWithDescriptor:offset:bytesPerRow:` and `newTiledTextureWithDescriptor:offset:bytesPerRow:`, a heap's `newTextureWithDescriptor:offset:`, each taking a texture descriptor object (section 9). - **The address map** is the ranges `[gpuAddress, gpuAddress + gpuLength)` of the live objects that answered them; `release` removes an object's range. - **Relocation.** The player makes each object where its runtime has room. In the bytes it puts - into an object that answered a `gpuAddress` (`m2v.write` and the copies from the guest's RAM), in - the data of every `set*Bytes:length:atIndex:` and in every address value, each 8-byte word at an + into an object that answered a `gpuAddress` (`m2v.write`, a copied buffer's `contents` and the + copies from the guest's RAM), in the data of every `set*Bytes:length:atIndex:` and in every address value, each 8-byte word at an offset that is a multiple of 8 from the target's start, whose value lies in a live range, becomes the player's address of that range's object plus the word's offset into the range. The innermost range wins: a buffer in a block moves with its own new address. Words outside every live range @@ -139,10 +144,17 @@ and the (name id, value) answer pairs. library bytes and function constants are never rewritten. The player counts the words it rewrote; a data word that is no address but lies in a live range is rewritten too, and the count shows it. -- **Resource IDs** are not answered. A descriptor's resource index places its object at that ID, as - Metal places it whether or not the index is forced: a texture descriptor's and a render - pipeline's `resourceIndex` (`[index, forced]`), a sampler's (an index), and a view's - `resourceIndex:` argument. Every other object takes the ID its runtime gives it. +- **Resource IDs.** A descriptor's resource index places its object at that ID, as Metal places it + whether or not the index is forced: a texture descriptor's and a render pipeline's + `resourceIndex` (`[index, forced]`), a sampler's (an index), and a view's `resourceIndex:` + argument. Every other object takes the ID its runtime gives it. +- **The IDs the program saw.** Each `gpuResourceID` the platform answered of a texture, sampler, + depth-stencil state, compute or render pipeline, indirect command buffer or visible function + table is a `gpuResourceID` record: the object its receiver, no arguments, result 0, and the ID + under the answer `gpuResourceID`. A getter that raised answers nothing. The player compares the + first answer of each object with the ID its runtime gives the object, and reports each object + where they differ (section 10): the bytes in which the program wrote that ID name no object of + the play. ## 6. CPU writes @@ -208,8 +220,9 @@ and the (name id, value) answer pairs. - **The host's own commit splits** (no Metal counterpart): `m2v.split` commits its command buffer as a part and makes the command buffer of the same queue that goes on from it (its result); `m2v.part` makes a command buffer of the same queue for a later range (its result), and - `m2v.commitPart` commits its receiver as a part. A split or part of result 0 is one the host did - not cut: it commits nothing and makes nothing. + `m2v.commitPart` commits its receiver as a part where its answer `cut` is `"Cut"`. Where it is + `"Fails"` or `{Whole: reason}`, the host committed nothing; a record without the answer commits. + A split or part of result 0 is one the host did not cut: it commits nothing and makes nothing. - **The host's scheduling records** change nothing a program sees, and a player plays none of them: `m2v.setCompletionJoinsNext` (`[joins]`: the host groups the command buffer's completion with the next ones of its queue), `m2v.holdsNoPredication` (`[]`), `m2v.fold` (`[later]`: the @@ -243,7 +256,8 @@ and the (name id, value) answer pairs. `level`, `slice`, `depthPlane`, `resolveLevel`, `resolveSlice`, `resolveDepthPlane`, `loadAction`, `storeAction`, `storeActionOptions`, then `clearColor`, `clearDepth` and `depthResolveFilter`, or `clearStencil` and `stencilResolveFilter`. A nil property takes - nothing: the descriptor keeps what it had. + nothing: the descriptor keeps what it had. An object property (`visibilityResultBuffer`, + `rasterizationRateMap`, `texture`, `resolveTexture`) set to nil is object 0, which clears it. - `m2v.rateMapDescriptor` (`[{screenSize, mutability, minFactor}]`) makes an `MTLRasterizationRateMapDescriptor`; its layers are set on it afterwards. - **Drawables.** A `newTextureWithDescriptor:` of receiver 0 whose argument is a map @@ -294,7 +308,7 @@ and the (name id, value) answer pairs. | `front`, `back` | `frontFaceStencil`, `backFaceStencil` | | `heapType` | `type` | | `options` | the setters of `resourceOptions`, `storageMode` and `hazardTrackingMode` | -| `pinnedGpuAddress`, `contents`, `noCopy`, `deallocator`, `zeroFrom` | the host's buffer creation: a pin, no-copy host memory and its deallocator, and the bytes known zero from an offset | +| `pinnedGpuAddress`, `contents`, `noCopy`, `deallocator`, `zeroFrom` | the host's buffer creation: a pin, the bytes a copied buffer starts with (section 5), no-copy host memory and its deallocator, and the bytes known zero from an offset | | `openGlModeEnabled`, `openClMode` | `openGLModeEnabled`, `openCLModeEnabled` | | `znear`, `zfar` | `MTLViewport`'s `znear` and `zfar` | | `rotation`, `isDrawable`, `framebufferOnly`, `protectionOptions`, `writeSwizzleEnabled` | Apple's texture descriptor properties of those names | @@ -330,8 +344,8 @@ and the (name id, value) answer pairs. and dispatches their calls issued (`draws` and `dispatches`: an encoder's calls whose selectors begin `draw` and `dispatch`), the words it relocated (`relocated_words`), the 8-byte values at offsets 4 past a multiple of 8 that lie in a live range, left as they are - (`misaligned_address_words`), and the bytes it wrote or copied in, `m2v.write` and the copies - from the guest's RAM (`written_bytes`). A group's calls are those played before it completed: + (`misaligned_address_words`), and the bytes it wrote or copied in, `m2v.write`, the copied + buffers' `contents` and the copies from the guest's RAM (`written_bytes`). A group's calls are those played before it completed: the call that waited for it counts in the next. - **As executed** (`executed`): the counters the runtime exposes. The old runtime's are the Vulkan commands it recorded (submissions, render passes, barriers, dispatches, draws, copies) @@ -353,7 +367,9 @@ and the (name id, value) answer pairs. read-only option (bit 24) is made without it and keeps the GPU writes Metal drops. `report.txt` holds one line per item: `device NAME`, `completed IDS COUNTS`, `frame N COUNTS`, -`check ID SHA256 match|differs|unrecorded`, `total COUNTS` (its `calls` the calls played: where +`check ID SHA256 match|differs|unrecorded`, `id ID RECORDED PLAYED` for each object whose runtime +gives another `gpuResourceID` than the program saw (both in hex, `PLAYED` `none` where the +runtime's getter raises), `total COUNTS` (its `calls` the calls played: where the play stopped, the stopping call is the next), `cut SEGMENT OFFSET` where the last segment ends in a record cut short, then `ok` or `error WHAT`. `COUNTS` is `stream KEY=VALUE ... executed KEY=VALUE ...`. The exit status is 0 for `ok`, 1 for a run that stopped and 2 for a harness