From a3ff94f510c62865f9b30019b3044cfc01ab2277 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Wed, 18 Nov 2026 21:55:18 -0800 Subject: [PATCH] replay: the escape note (m2v.bufferEscaped) and a stop on a written word into a noted buffer The recorder will note a buffer whose address may escape into the program's memory: once in the buffer's life, at the first gpuAddress read (kind 0), argument-encoder write (1), gpuResourceID read of a texture over it (2) or residency-set add (3); the whole buffer escapes. No stream carries the note yet. The player now reads m2v.bufferEscaped: the receiver must be a made object and the one argument a kind from 0 to 3, else the stream is invalid. Once a buffer's note is read, a written word that looks like an address (the census's aligned words) whose value lies in that buffer's recorded range stops the play with PlayError::NotedWord {target, offset, value, buffer, kind}. Moving such a word is not built: no stream exercises it, and the move gets built with the first stream that does. AddressMap::noted_word finds the word at any nesting level. The lookup runs only once a note was read, so a stream without notes pays nothing for it. The report counts the notes (Report::escape_notes); the addresses line ends "the stream predates the escape note" where there are none, "escape notes N" otherwise. Test (unit, a synthetic stream): a note, then a write of a word into the noted buffer stops, naming the word; the same kind of word into a buffer with no note played as written before it; a kind past 3 and a note of an unmade object are invalid streams. docs/REPLAY-STREAM.md section 5 holds the record and the stop, section 10 the line. Verification: the replay checks run as a potluck job on this commit. --- .../src/bin/command-replay.rs | 7 +- .../src/replay/addresses.rs | 33 ++++++++ .../src/replay/player.rs | 81 +++++++++++++++++-- .../src/replay/tests.rs | 55 +++++++++++++ docs/REPLAY-STREAM.md | 21 ++++- 5 files changed, 185 insertions(+), 12 deletions(-) diff --git a/crates/metal2vulkan-validation/src/bin/command-replay.rs b/crates/metal2vulkan-validation/src/bin/command-replay.rs index 259a895bf..1ee80fc4c 100644 --- a/crates/metal2vulkan-validation/src/bin/command-replay.rs +++ b/crates/metal2vulkan-validation/src/bin/command-replay.rs @@ -477,10 +477,13 @@ fn run( let differing_ids = (played.ids.len() as u64).saturating_sub(unread_ids); let stream = &played.total.stream; let fixed = |key: &str| stream.get(key).copied().unwrap_or(0); + let notes = match played.escape_notes { + 0 => "the stream predates the escape note".to_owned(), + notes => format!("escape notes {notes}"), + }; report.line(&format!( "addresses address_looking_words={} misaligned_address_words={} address_arguments={} \ - relocated_words={} differing_ids={differing_ids}: written words play as recorded; the \ - stream predates the escape note", + relocated_words={} differing_ids={differing_ids}: written words play as recorded; {notes}", fixed("address_looking_words"), fixed("misaligned_address_words"), fixed("address_arguments"), diff --git a/crates/metal2vulkan-validation/src/replay/addresses.rs b/crates/metal2vulkan-validation/src/replay/addresses.rs index 490aa2cb0..eda66fbd8 100644 --- a/crates/metal2vulkan-validation/src/replay/addresses.rs +++ b/crates/metal2vulkan-validation/src/replay/addresses.rs @@ -152,6 +152,39 @@ impl AddressMap { counted((12 - offset % 8) % 8), ) } + + /// The first 8-byte word of `bytes` at a multiple of 8 from the target's start (`bytes` starts + /// `offset` bytes into the target) whose value lies in the live range of an object `noted` + /// holds, at any level: the word's offset in the target, its value and that object. + pub fn noted_word( + &self, + bytes: &[u8], + offset: u64, + noted: impl Fn(u64) -> bool, + ) -> Option<(u64, u64, u64)> { + let first = ((8 - offset % 8) % 8) as usize; + (first..bytes.len().saturating_sub(7)) + .step_by(8) + .find_map(|at| { + let value = u64::from_le_bytes(bytes[at..at + 8].try_into().expect("8 bytes")); + let object = self.holders(value).find(|&object| noted(object))?; + Some((offset + at as u64, value, object)) + }) + } + + /// The objects whose live ranges hold `value`, outermost first. + fn holders(&self, value: u64) -> impl Iterator + '_ { + let mut level = Some(&self.top); + std::iter::from_fn(move || { + let (_, range) = level?.range(..=value).next_back()?; + if value >= range.end { + level = None; + return None; + } + level = Some(&range.inner); + Some(range.object) + }) + } } /// The start of the range of `level` that holds `[start, end)` whole, if one does. diff --git a/crates/metal2vulkan-validation/src/replay/player.rs b/crates/metal2vulkan-validation/src/replay/player.rs index 0598a496b..7dc76ba1a 100644 --- a/crates/metal2vulkan-validation/src/replay/player.rs +++ b/crates/metal2vulkan-validation/src/replay/player.rs @@ -186,6 +186,17 @@ pub enum PlayError { }, /// The stream contradicts itself (an object it never made, a wait nothing can meet). Invalid(String), + /// A written word at byte `offset` of `target` (an object, or the encoder of `set*Bytes` data) + /// whose value lies in the recorded range of `buffer`, which the stream noted escaped + /// (`m2v.bufferEscaped`, its `kind`): the word may be the buffer's address, and moving it is not + /// built. + NotedWord { + target: u64, + offset: u64, + value: u64, + buffer: u64, + kind: u64, + }, /// Object `object` has a recorded range at `recorded`, and the backend, which makes such /// objects at their recorded addresses (`Backend::places_at_recorded`), could not: its runtime /// refused the address (`why`), or made it at `made`. No other placement is tried. @@ -204,6 +215,17 @@ impl fmt::Display for PlayError { PlayError::Refused { selector, why } => write!(f, "refused {selector}: {why}"), PlayError::Runtime { selector, error } => write!(f, "{selector}: {error}"), PlayError::Invalid(why) => write!(f, "invalid stream: {why}"), + PlayError::NotedWord { + target, + offset, + value, + buffer, + kind, + } => write!( + f, + "#{target} +{offset}: the word {value:#x} lies in #{buffer}'s recorded range, \ + which the stream noted escaped (kind {kind}); moving it is not built" + ), PlayError::Unpinned { object, recorded, @@ -304,6 +326,9 @@ pub struct Report { /// The live recorded ranges a newer one met in part, which the address map ended /// (`AddressMap::insert`). pub parted: u64, + /// The escape notes the stream holds (`m2v.bufferEscaped`): none in a stream recorded before + /// the recorder wrote them. + pub escape_notes: u64, /// On a backend that makes objects at their recorded addresses /// (`Backend::places_at_recorded`), the objects with a recorded range it made there, every /// one of them (another stops the play); `None` on a backend the address map moves address @@ -858,6 +883,9 @@ fn placement_offset(selector: &str) -> Option { pub struct Player<'b, B: Backend> { backend: &'b mut B, addresses: AddressMap, + /// The live buffers the stream noted escaped (`m2v.bufferEscaped`), with the note's kind: a + /// written word whose value lies in one's range stops the play (section 5). + escaped: HashMap, kinds: HashMap, /// Each live object's device and the number of objects made before it. owner: HashMap, @@ -1091,6 +1119,7 @@ impl<'b, B: Backend> Player<'b, B> { Player { backend, addresses: AddressMap::default(), + escaped: HashMap::new(), kinds: HashMap::new(), owner: HashMap::new(), made_count: 0, @@ -1360,6 +1389,7 @@ impl<'b, B: Backend> Player<'b, B> { } match &*call.selector { "m2v.write" => self.write(stream, &call), + "m2v.bufferEscaped" => self.escape(&call), "m2v.check" => { let recorded = call.answer("sha256").and_then(Value::as_list); let objects = call.args.iter().enumerate().map(|(at, object)| { @@ -1601,7 +1631,7 @@ impl<'b, B: Backend> Player<'b, B> { args.iter().map(addresses).sum::(); if sets_bytes(&call.selector) { if let Some(Value::Bytes(data)) = args.first() { - self.census(data, 0); + self.census(call.receiver, data, 0)?; } } let resolved = self.placed(Call { args, ..call }); @@ -1678,7 +1708,7 @@ impl<'b, B: Backend> Player<'b, B> { unreachable!("a piece's bytes"); }; if censused { - self.census(data, at); + self.census(upload.target, data, at)?; } *self.fixed.entry(WRITTEN_BYTES).or_default() += data.len() as u64; } @@ -1792,18 +1822,54 @@ impl<'b, B: Backend> Player<'b, B> { /// where the target answered a `gpuAddress`, and its bytes. fn put(&mut self, target: u64, offset: u64, data: Vec) -> Result<(), PlayError> { if self.addresses.holds(target) { - self.census(&data, offset); + self.census(target, &data, offset)?; } *self.fixed.entry(WRITTEN_BYTES).or_default() += data.len() as u64; self.write_bytes(target, offset, &data) } - /// Count the address-looking words of `data`, which starts `offset` bytes into its target - /// (`AddressMap::census`), and move none. - fn census(&mut self, data: &[u8], offset: u64) { + /// Count the address-looking words of `data`, which starts `offset` bytes into `target` + /// (`AddressMap::census`), and move none; one whose value lies in the range of a buffer the + /// stream noted escaped stops the play (`PlayError::NotedWord`). + fn census(&mut self, target: u64, data: &[u8], offset: u64) -> Result<(), PlayError> { let (aligned, misaligned) = self.addresses.census(data, offset); *self.fixed.entry(ADDRESS_LOOKING_WORDS).or_default() += aligned; *self.fixed.entry(MISALIGNED_WORDS).or_default() += misaligned; + if aligned == 0 || self.escaped.is_empty() { + return Ok(()); + } + let noted = |object| self.escaped.contains_key(&object); + match self.addresses.noted_word(data, offset, noted) { + Some((offset, value, buffer)) => Err(PlayError::NotedWord { + target, + offset, + value, + buffer, + kind: self.escaped[&buffer], + }), + None => Ok(()), + } + } + + /// `m2v.bufferEscaped`: the program may hold its receiver's address in memory, from then on + /// (`docs/REPLAY-STREAM.md`, section 5). Its one argument is the kind of escape, 0 to 3. + fn escape(&mut self, call: &Call) -> Result<(), PlayError> { + let buffer = call.receiver; + if !self.kinds.contains_key(&buffer) { + return Err(invalid(format!( + "m2v.bufferEscaped of #{buffer}, made by no call" + ))); + } + match call.args.as_slice() { + [kind] if kind.as_uint().is_some_and(|kind| kind <= 3) => { + self.escaped.insert(buffer, kind.as_uint().expect("a kind")); + self.report.escape_notes += 1; + Ok(()) + } + _ => Err(invalid(format!( + "m2v.bufferEscaped of #{buffer}: its argument is a kind from 0 to 3" + ))), + } } /// Read `object` and record its checksum; the readback's own work is no command buffer's. @@ -1925,7 +1991,7 @@ impl<'b, B: Backend> Player<'b, B> { let before = self.blob(stream, &around.before)?; sized(&around, &before)?; if self.addresses.holds(around.buffer) { - self.census(&before, around.location); + self.census(around.buffer, &before, around.location)?; } *self.fixed.entry(WRITTEN_BYTES).or_default() += around.length; self.write_bytes(staging, at, &before)?; @@ -2056,6 +2122,7 @@ impl<'b, B: Backend> Player<'b, B> { fn drop_object(&mut self, object: u64) -> Result<(), PlayError> { self.encoders.remove(&object); self.addresses.remove(object); + self.escaped.remove(&object); self.owner.remove(&object); self.compared.remove(&object); self.outside.remove(&object); diff --git a/crates/metal2vulkan-validation/src/replay/tests.rs b/crates/metal2vulkan-validation/src/replay/tests.rs index c565f8272..1132a3da8 100644 --- a/crates/metal2vulkan-validation/src/replay/tests.rs +++ b/crates/metal2vulkan-validation/src/replay/tests.rs @@ -781,6 +781,61 @@ fn a_typed_address_argument_moves_with_its_object() { assert_eq!(report.total.stream["address_looking_words"], 0); } +/// Once the stream notes a buffer escaped (`m2v.bufferEscaped`), a written word whose value lies in +/// its recorded range stops the play, naming the word, its target, the buffer and the note's kind; +/// the same word into a buffer with no note played as written before it. A note of a kind past 3, +/// or of an object no call made, is an invalid stream. +#[test] +fn a_word_into_a_buffer_noted_escaped_stops_the_play() { + let mut kept = Kept::default(); + let noted = BLOCK; + let plain = BLOCK + 0x1_0000; + let (report, ended) = played(&mut kept, |w| { + w.call("MTLCreateSystemDefaultDevice", 0, 1, &[], &[])?; + let length = [Value::Uint(0x100), Value::Uint(0)]; + let made = "newBufferWithLength:options:"; + w.call(made, 1, 2, &length, &addressed(noted, 0x100))?; + w.call(made, 1, 3, &length, &addressed(plain, 0x100))?; + w.call(made, 1, 4, &length, &addressed(BLOCK + 0x2_0000, 0x100))?; + let into = |target: u64, offset: u64, word: u64| { + let pair = [ + Value::Uint(offset), + Value::Bytes(word.to_le_bytes().to_vec()), + ]; + (target, pair) + }; + let (target, pair) = into(4, 8, plain + 8); + w.call("m2v.write", target, 0, &pair, &[])?; + w.call("m2v.bufferEscaped", 2, 0, &[Value::Uint(1)], &[])?; + let (target, pair) = into(4, 16, noted + 0x10); + w.call("m2v.write", target, 0, &pair, &[]) + }); + match ended { + Err(PlayError::NotedWord { + target: 4, + offset: 16, + value, + buffer: 2, + kind: 1, + }) if value == noted + 0x10 => {} + other => panic!("the play went on past a word into a noted buffer: {other:?}"), + } + assert_eq!(kept.writes, [(4, 8, (plain + 8).to_le_bytes().to_vec())]); + assert_eq!(report.escape_notes, 1); + + for (receiver, kind) in [(2, 4), (9, 0)] { + let (_, ended) = played(&mut Kept::default(), |w| { + w.call("MTLCreateSystemDefaultDevice", 0, 1, &[], &[])?; + let length = [Value::Uint(0x100), Value::Uint(0)]; + let made = "newBufferWithLength:options:"; + w.call(made, 1, 2, &length, &addressed(noted, 0x100))?; + let note = [Value::Uint(kind)]; + w.call("m2v.bufferEscaped", receiver, 0, ¬e, &[]) + }); + assert!(matches!(ended, Err(PlayError::Invalid(_))), "{ended:?}"); + } +} + /// A copy from the guest's RAM lands each piece at its byte, as recorded: into a block, a word that /// looks like an address is counted at a multiple of 8 and apart 4 past one; into a buffer of no /// address, it is not counted. A copy of another form (one the platform refused, recorded before diff --git a/docs/REPLAY-STREAM.md b/docs/REPLAY-STREAM.md index 02adfdb4f..f9b80ff80 100644 --- a/docs/REPLAY-STREAM.md +++ b/docs/REPLAY-STREAM.md @@ -207,6 +207,20 @@ and the (name id, value) answer pairs. lies in a live range (`address_looking_words`), and apart from them the 8-byte values at 4 past a multiple of 8 that do (`misaligned_address_words`). Both are the stream's, the same on every play on either runtime. +- **The escape note.** `m2v.bufferEscaped` (receiver: a buffer; arguments: `[kind]`) says the + program may hold the buffer's address in memory from then on; the whole buffer escapes. Its + kind is 0 for a `gpuAddress` read of the buffer or of a texture over it, 1 for an argument + encoder's write of its address or of a texture-over-it's resource ID, 2 for a `gpuResourceID` + read of a texture or view over it, and 3 for a residency set's add. The recorder writes it once + in the buffer's life, at the first escape, in stream order: after the `m2v.write` records of + the commits before it and before those of every commit after it. The buffer is a no-copy one, + never Managed. Once a buffer's note is read, a written word that looks like an address (above) + whose value lies in that buffer's recorded range stops the play, naming its target and offset, + its value, the buffer and the note's kind (`PlayError::NotedWord`): the word may be the + buffer's address, which the play would have to move, and that move is not built. A note of a + kind past 3, or of an object no call made, is an invalid stream. A stream recorded before the + recorder wrote the note holds none, and the report's `addresses` line says it predates the note + (section 10). - **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:` @@ -704,9 +718,10 @@ stream may differ from what the program did` first where the stream's header lac sidecar`, `the player's table, stream LABEL` or `no sidecar and no table row`, then `device NAME runtime old|rt snapshots yes|no`, then `addresses address_looking_words=N misaligned_address_words=N address_arguments=N -relocated_words=N differing_ids=N: written words play as recorded; the stream predates the escape -note` (the census of the written words that look like addresses, at a multiple of 8 and 4 past -one, which play as the stream holds them; the address arguments and those moved; and the objects +relocated_words=N differing_ids=N: written words play as recorded; NOTES` (the census of the +written words that look like addresses, at a multiple of 8 and 4 past one, which play as the +stream holds them; the address arguments and those moved; `NOTES` `the stream predates the escape +note` where it holds no `m2v.bufferEscaped` record, else `escape notes N`; and the objects whose ID differs from the recording's, those of the compute pipeline states' typed gap and of the skipped objects aside: any such object makes the play an error, as a word that names it names something else in the play),