From 4c438ca2c6668674b9f9442508a3f6b6be4ea81e Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 23 Nov 2026 00:39:04 -0800 Subject: [PATCH] Translator: under the identity domains a command buffer's field is plain data An argument buffer's command_buffer member holds, under the identity domains, its word: the gpuResourceID the program or the host wrote there, the device address of the records (lower::access::icb). The byte rule of memory::provenance::objects treated it as an opaque object, so any access other than the exact handle load that might reach its 8 bytes was Unsupported{ArgumentBufferObjects}: an index past the structure by a signed run-time index, whose offsets run back to 0, and, once such a buffer's address escaped, every run-time dereference. Metal lays a Tier 2 argument buffer out as the equivalent C structure (macOS 13 and later), into whose member the host writes gpuResourceID ("Handle of the GPU resource suitable for storing in an Argument Buffer", MTLIndirectCommandBuffer.h), and whose contents the GPU and the CPU may both modify. A plain access of those bytes reads or writes that word, which is all Metal defines of them. So under the identity domains a command buffer's field is not opaque for either rule (ObjectLayouts::of takes `words`, from the profile's pointer domain); a pipeline state's field stays opaque, and under the resident-table domains, the validation executor's, nothing changes. Tests: the objects rule's unit test (a command buffer's field is opaque only without its word), and engine_identity_icb's an_access_past_an_encoder_is_a_plain_access_of_its_command_buffers_word over the owned fixture icb_encoder_tail: both entries compile and validate under the identity domains on lavapipe and moltenvk-m3, and the resident tables still refuse them. --- crates/metal2vulkan/src/memory/plan.rs | 5 +- crates/metal2vulkan/src/memory/plan/tests.rs | 2 +- crates/metal2vulkan/src/memory/provenance.rs | 15 ++++-- .../src/memory/provenance/objects.rs | 54 ++++++++++++++----- .../src/memory/provenance/objects/tests.rs | 47 ++++++++++++++-- .../src/tests/engine_identity_icb.rs | 33 ++++++++++++ docs/API.md | 6 ++- 7 files changed, 135 insertions(+), 27 deletions(-) diff --git a/crates/metal2vulkan/src/memory/plan.rs b/crates/metal2vulkan/src/memory/plan.rs index 76a006212..6f78f26e8 100644 --- a/crates/metal2vulkan/src/memory/plan.rs +++ b/crates/metal2vulkan/src/memory/plan.rs @@ -60,7 +60,7 @@ use crate::air::ir::{ }; use crate::air::Entry; use crate::budget::{tree_bytes, vec_bytes, Meter}; -use crate::device::profile::BufferAccess; +use crate::device::profile::{BufferAccess, PointerDomain}; use crate::device::DeviceProfile; use crate::error::{Error, Feature, InternalError, InternalKind, Limit, LowerFamily, Unsupported}; use crate::pipeline::interface::{AccessSet, Window}; @@ -680,7 +680,8 @@ pub fn analyze_memory(e: &Entry, p: &DeviceProfile, m: &mut Meter) -> Result Result { let layouts = TypeLayouts::new(&e.layout, e.module.types(), m)?; - let prov = provenance::analyze(e, &layouts, m)?; + let words = p.fields().pointer_domain == PointerDomain::Identity; + let prov = provenance::analyze(e, &layouts, words, m)?; if let (Some((b, id)), BufferAccess::Floor) = (prov.dynamic_deref, p.fields().buffer_access) { let err: Error = Unsupported::needs_any_of(Feature::DereferenceLoadedPointer, vec![p.addressed_needs()]) diff --git a/crates/metal2vulkan/src/memory/plan/tests.rs b/crates/metal2vulkan/src/memory/plan/tests.rs index 936af85f7..91fab4fbc 100644 --- a/crates/metal2vulkan/src/memory/plan/tests.rs +++ b/crates/metal2vulkan/src/memory/plan/tests.rs @@ -1467,7 +1467,7 @@ fn verifying_the_cells_returns_its_tables_to_the_ledger() { let mut m = meter(); let layouts = TypeLayouts::new(&e.layout, e.module.types(), &mut m).expect("layouts"); let before = m.ledger(); - let prov = provenance::analyze(&e, &layouts, &mut m).expect("provenance"); + let prov = provenance::analyze(&e, &layouts, true, &mut m).expect("provenance"); assert!( prov.dynamic_deref.is_none(), "the cell forwards its pointer" diff --git a/crates/metal2vulkan/src/memory/provenance.rs b/crates/metal2vulkan/src/memory/provenance.rs index 9e38a2e75..7c95219e7 100644 --- a/crates/metal2vulkan/src/memory/provenance.rs +++ b/crates/metal2vulkan/src/memory/provenance.rs @@ -1959,8 +1959,14 @@ fn uf_len(i: usize) -> Result { u32::try_from(i).map_err(|_| invariant("more pointer values than u32")) } -/// Run the provenance analysis over `e`. -pub fn analyze(e: &Entry, layouts: &TypeLayouts, m: &mut Meter) -> Result { +/// Run the provenance analysis over `e`; `words` says an argument buffer's command-buffer field +/// holds its word, plain data (the identity domains, `objects`). +pub fn analyze( + e: &Entry, + layouts: &TypeLayouts, + words: bool, + m: &mut Meter, +) -> Result { let func = e .module .func(e.func) @@ -2244,7 +2250,7 @@ pub fn analyze(e: &Entry, layouts: &TypeLayouts, m: &mut Meter) -> Result, classes: &mut Classes, + words: bool, m: &mut Meter, ) -> Result { let (values, n) = (cx.values, cx.ptr_values.len()); @@ -2288,7 +2295,7 @@ fn classify( .iter() .any(|b| matches!(&b.role, ParamRole::ArgumentBuffer(arg) if arg.layout.is_some())) { - ObjectLayouts::of(&e.structs, m)? + ObjectLayouts::of(&e.structs, words, m)? } else { ObjectLayouts::default() }; diff --git a/crates/metal2vulkan/src/memory/provenance/objects.rs b/crates/metal2vulkan/src/memory/provenance/objects.rs index a9329e1d0..ad4088cfb 100644 --- a/crates/metal2vulkan/src/memory/provenance/objects.rs +++ b/crates/metal2vulkan/src/memory/provenance/objects.rs @@ -1,12 +1,16 @@ //! The bytes of an argument buffer's indirect-command objects. //! //! Metal's encoder writes an object's resource id into a command-buffer or compute or render -//! pipeline-state member of an argument buffer, and the binder has no class for these objects, so -//! the field holds no value a translation defines. Only the handle load reads it: a pointer load -//! of exactly one such field, at a translation-time constant offset in the buffer's first element, -//! which `Walk::seed_loaded` classes as the object's handle and whose every use its family -//! refuses. Any other access that may reach an object's bytes is `ArgumentBufferObjects`, not -//! implemented: +//! pipeline-state member of an argument buffer. Under the identity domains a command buffer's +//! field holds its word, the `gpuResourceID` the program or the host wrote there: the device +//! address of its records (`lower::access::icb`). Metal lays a Tier 2 argument buffer out as the +//! equivalent C structure, whose contents the GPU and the CPU may both modify, so an access to +//! those bytes is a plain access of the buffer's memory, as an access to any other member's is. +//! Any other object's field, and a command buffer's under the resident-table domains, holds no +//! value a translation defines. Only the handle load reads it: a pointer load of exactly one such +//! field, at a translation-time constant offset in the buffer's first element, which +//! `Walk::seed_loaded` classes as the object's handle (`lower::access::object`). Any other access +//! that may reach such an object's bytes is `ArgumentBufferObjects`, not implemented: //! //! - **The offsets an access may take** are its shape's (a constant, or a constant plus multiples //! of its strides) within its range. An access at least as wide as its step touches one @@ -50,6 +54,13 @@ pub(super) fn is_object(h: AbiHandle) -> bool { ) } +/// Whether the field of an object of handle `h` holds no value a translation defines, so that +/// only its handle load reads it: a pipeline state's, and a command buffer's unless its field +/// holds its word (`words`, the identity domains). +fn opaque(h: AbiHandle, words: bool) -> bool { + is_object(h) && !(words && matches!(h, AbiHandle::CommandBuffer)) +} + /// The most offsets (or residues) one access is checked at; an access that may take more is /// refused. const OBJECT_OFFSETS: u32 = 4096; @@ -82,9 +93,11 @@ fn edge(mem: &Member, n: usize) -> Option<(u32, bool)> { .filter(|(t, _)| (*t as usize) < n) } -/// Which layouts hold an indirect-command object. +/// Which layouts hold an indirect-command object whose field is opaque. #[derive(Debug, Default)] pub(super) struct ObjectLayouts { + /// A command buffer's field holds its word, plain data (the identity domains). + words: bool, /// By value, at any nesting depth. holds: Vec, /// Behind a pointer member at any nesting depth, whose pointee holds an object or is itself @@ -93,10 +106,14 @@ pub(super) struct ObjectLayouts { } impl ObjectLayouts { - /// Both tables for `structs`: one pass up the reverse nesting and pointer edges from the - /// layouts that hold an object directly. Each member and edge is a unit of work, and the - /// edge table is charged to the ledger. - pub(super) fn of(structs: &[StructInfo], m: &mut Meter) -> Result { + /// Both tables for `structs`, with a command buffer's field its word where `words`: one pass + /// up the reverse nesting and pointer edges from the layouts that hold an object directly. + /// Each member and edge is a unit of work, and the edge table is charged to the ledger. + pub(super) fn of( + structs: &[StructInfo], + words: bool, + m: &mut Meter, + ) -> Result { let n = structs.len(); let work = |units: usize, m: &mut Meter| m.tick(u32::try_from(units).unwrap_or(u32::MAX)); // Reverse edges, sorted by the layout they lead to: `(child or pointee, the layout that @@ -133,7 +150,7 @@ impl ObjectLayouts { holds.extend(structs.iter().map(|info| { info.members .iter() - .any(|mem| mem.handle().is_some_and(is_object)) + .any(|mem| mem.handle().is_some_and(|h| opaque(h, words))) })); let mut queue: Vec = Vec::new(); m.reserve(&mut queue, n)?; @@ -174,7 +191,11 @@ impl ObjectLayouts { } // The edge table and the worklist are dropped here; the two tables stay charged. m.release(count * std::mem::size_of::<(u32, u32, bool)>() + n * std::mem::size_of::()); - Ok(ObjectLayouts { holds, behind }) + Ok(ObjectLayouts { + words, + holds, + behind, + }) } fn holds(&self, s: StructRef) -> bool { @@ -185,6 +206,11 @@ impl ObjectLayouts { self.behind.get(s.0 as usize).copied().unwrap_or(false) } + /// Whether member `mem` is an object whose field is opaque. + fn opaque(&self, mem: &Member) -> bool { + mem.handle().is_some_and(|h| opaque(h, self.words)) + } + /// Whether a pointer member loads the address of an object's memory. fn object_pointer(&self, mem: &Member) -> bool { pointee(mem).is_some_and(|t| self.holds(t) || self.behind(t)) @@ -357,7 +383,7 @@ impl ObjectBuffer { if !self.holds { return Ok(false); } - let leaf = |mem: &Member| mem.handle().is_some_and(is_object); + let leaf = |mem: &Member| layouts.opaque(mem); self.touches(structs, &|s| layouts.holds(s), &leaf, fact, reach, m) } diff --git a/crates/metal2vulkan/src/memory/provenance/objects/tests.rs b/crates/metal2vulkan/src/memory/provenance/objects/tests.rs index 7bee22cfe..c5392652b 100644 --- a/crates/metal2vulkan/src/memory/provenance/objects/tests.rs +++ b/crates/metal2vulkan/src/memory/provenance/objects/tests.rs @@ -89,7 +89,7 @@ fn a_shared_layout_is_classified_once() { for object in [true, false] { let structs = shared_graph(60, |_| 0, object); let mut m = meter(u64::MAX); - let layouts = ObjectLayouts::of(&structs, &mut m).expect("layouts"); + let layouts = ObjectLayouts::of(&structs, false, &mut m).expect("layouts"); assert!((0..=60).all(|s| layouts.holds(StructRef(s)) == object)); assert!((0..=60).all(|s| !layouts.behind(StructRef(s)))); assert!(m.work() <= 4 * 121, "work {}", m.work()); @@ -102,7 +102,7 @@ fn an_access_descends_only_into_the_elements_it_covers_partly() { let depth = 27; let structs = shared_graph(depth, |size| size, true); let mut m = meter(u64::MAX); - let layouts = ObjectLayouts::of(&structs, &mut m).expect("layouts"); + let layouts = ObjectLayouts::of(&structs, false, &mut m).expect("layouts"); let contains = |s: StructRef| layouts.holds(s); let leaf = |mem: &Member| mem.handle().is_some_and(is_object); let size = 16u64 << depth; @@ -127,13 +127,50 @@ fn overlapping_members_end_at_the_work_cap() { // partly covered paths per level. The meter ends the search instead of 2^60 visits. let structs = shared_graph(60, |_| 0, true); let mut m = meter(1 << 20); - let layouts = ObjectLayouts::of(&structs, &mut m).expect("layouts"); + let layouts = ObjectLayouts::of(&structs, false, &mut m).expect("layouts"); let contains = |s: StructRef| layouts.holds(s); let leaf = |mem: &Member| mem.handle().is_some_and(is_object); let found = overlaps(&structs, &contains, &leaf, StructRef(0), (4, 8), 0, &mut m); assert!(matches!(found, Err(Error::LimitExceeded(Limit::WorkUnits)))); } +fn command(offset: u32) -> Member { + member( + offset, + 8, + None, + indirect(ParamRole::CommandBuffer(ObjectArg { + location: slot(), + access: None, + })), + ) +} + +/// A command buffer's field is opaque only where it does not hold its word: `{ command_buffer c; +/// uint w[2]; }` holds an object outside the identity domains and none under them, where an +/// access of its first eight bytes is plain data; a pipeline state's field is opaque under both. +#[test] +fn a_command_buffers_field_is_opaque_only_without_its_word() { + let structs = vec![ + StructInfo { + members: vec![command(0), word(8), word(12)], + }, + StructInfo { + members: vec![pipeline(0), word(8)], + }, + ]; + for words in [false, true] { + let mut m = meter(u64::MAX); + let layouts = ObjectLayouts::of(&structs, words, &mut m).expect("layouts"); + let holds: Vec = (0..2).map(|s| layouts.holds(StructRef(s))).collect(); + assert_eq!(holds, [!words, true], "words {words}"); + let leaf = |mem: &Member| layouts.opaque(mem); + let contains = |s: StructRef| layouts.holds(s); + let found = overlaps(&structs, &contains, &leaf, StructRef(0), (0, 8), 0, &mut m); + assert_eq!(found.expect("overlap"), !words, "words {words}"); + } +} + #[test] fn an_object_behind_a_pointer_member_is_behind() { // Outer { Pipelines* inner; uint x; } -> Pipelines { compute_pipeline_state p; uint s; }, @@ -163,7 +200,7 @@ fn an_object_behind_a_pointer_member_is_behind() { }, ]; let mut m = meter(u64::MAX); - let layouts = ObjectLayouts::of(&structs, &mut m).expect("layouts"); + let layouts = ObjectLayouts::of(&structs, false, &mut m).expect("layouts"); let holds: Vec = (0..3).map(|s| layouts.holds(StructRef(s))).collect(); let behind: Vec = (0..3).map(|s| layouts.behind(StructRef(s))).collect(); assert_eq!(holds, [false, true, false]); @@ -199,7 +236,7 @@ fn an_access_as_wide_as_its_step_is_one_test() { let n = 8192; let (structs, buffer) = data_then_object(n); let mut m = meter(u64::MAX); - let layouts = ObjectLayouts::of(&structs, &mut m).expect("layouts"); + let layouts = ObjectLayouts::of(&structs, false, &mut m).expect("layouts"); let words = crate::memory::alloca::Strides::one(4).expect("stride"); let data_end = 4 * i64::from(n); for shape in [ diff --git a/crates/metal2vulkan/src/tests/engine_identity_icb.rs b/crates/metal2vulkan/src/tests/engine_identity_icb.rs index 0bfbd7214..e1f24a8aa 100644 --- a/crates/metal2vulkan/src/tests/engine_identity_icb.rs +++ b/crates/metal2vulkan/src/tests/engine_identity_icb.rs @@ -7,6 +7,10 @@ //! validate on every profile with device addresses. //! - A kernel's plain draw (`engine/icb_merged_draws.ll`'s `icb_merged_triangles`) is refused, //! `Unsupported{GpuEncodedIndirectCommands, NotImplemented}`. +//! - An access past an argument buffer whose first member is a command buffer, by a signed +//! run-time index that may reach the command buffer's field (`engine/icb_encoder_tail.ll`), is a +//! plain access of the field's word: it compiles and validates; under the resident-table domains +//! it is refused, `Unsupported{ArgumentBufferObjects, NotImplemented}`. //! - The vertex function of a state made with `supportIndirectCommandBuffers` pushes the execution //! range's address and its command (`PushField::IndirectRange`, `PushField::IndirectSequence`, //! `PushField::IndirectBase`) @@ -93,6 +97,35 @@ fn a_kernels_plain_draw_into_commands_is_refused_under_the_identity_domains() { } } +/// The words past an argument buffer whose first member is a command buffer, indexed by a signed +/// run-time index, which a negative index takes back into the command buffer's field: a vertex +/// function binds each command's buffers from the addresses there, and a kernel reads and writes +/// words there. Under the identity domains the field holds the command buffer's word, so each +/// access is a plain access and both compile and validate; under the resident-table domains, +/// where the field holds no value a translation defines, both are refused. +#[test] +fn an_access_past_an_encoder_is_a_plain_access_of_its_command_buffers_word() { + let Some(bc) = assemble("icb_encoder_tail") else { + return; + }; + for entry in ["tail_bind", "tail_count"] { + for stem in PROFILES { + let p = profile(stem, identity()).unwrap_or_else(|e| panic!("{e}")); + let a = compile(&bc, entry, &p).unwrap_or_else(|e| panic!("{stem}: {entry}: {e:?}")); + link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: {entry}: {e}")); + let p = profile(stem, DevicePolicy::RESIDENT_TABLES).unwrap_or_else(|e| panic!("{e}")); + match compile(&bc, entry, &p) { + Err(Error::Unsupported(u)) => assert_eq!( + (u.feature, u.needs), + (Feature::ArgumentBufferObjects, Needs::NotImplemented), + "{stem}: {entry}" + ), + other => panic!("{stem}: {entry}: {other:?}"), + } + } + } +} + /// The vertex function of a state for indirect command buffers pushes the execution range's /// address and its command; the same state without the flag pushes neither. #[test] diff --git a/docs/API.md b/docs/API.md index 24f202b95..a1f020bc6 100644 --- a/docs/API.md +++ b/docs/API.md @@ -267,7 +267,11 @@ and so do the command line, the compile worker and every validation tool. It hol first lowers an argument buffer's sampler masks its index the same way. A function writes an indirect command buffer's render commands, under the identity domains alone, through the `gpuResourceID` an argument buffer's `command_buffer` member holds: the - device address of the buffer's records, laid out as `pipeline::IndirectDrawLayout` states. A + device address of the buffer's records, laid out as `pipeline::IndirectDrawLayout` states. Any + other access that may reach the member's 8 bytes, such as an index past the structure that + runs back into it, is a plain access of the argument buffer's memory there, reading or writing + that word, as Metal's Tier 2 argument buffer is laid out as the equivalent C structure; under + the resident-table domains it is `Unsupported{ArgumentBufferObjects}`. A command's `set_vertex_buffer` and `set_fragment_buffer`, its `draw_indexed_primitives` of triangles and its `reset` write them, each only where the command's index is below the buffer's capacity; any other indirect-command operation is