Merge upstream main (42361b0) into shader/per-lane-phi
main moved under #307 and this branch. One conflict, in the test module of emit/lower.rs: the imports take both sides' names (#117's `half_shift` beside `Lowered`), and #117's `scalar_bit_tests_lower` sits after this branch's waterfall tests. No code outside the test module was touched by hand. A merge rather than a rebase so #307's commits keep their ids. Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
commit
a7e60cfac0
24 files changed
+1363
-191
No files matched your search
@@ -80,10 +80,10 @@ impl Config {
|
||||
) -> Result<Self> {
|
||||
let env_path = |k: &str| env(k).filter(|v| !v.is_empty()).map(PathBuf::from);
|
||||
let test_titles = match env("VICTORY_TEST_TITLES") {
|
||||
Some(v) => std::env::split_paths(&v)
|
||||
Some(v) if !v.is_empty() => std::env::split_paths(&v)
|
||||
.filter(|p| !p.as_os_str().is_empty())
|
||||
.collect(),
|
||||
None => file.test_titles,
|
||||
_ => file.test_titles,
|
||||
};
|
||||
let cache_dir = env_path("VICTORY_CACHE_DIR")
|
||||
.or(file.cache_dir)
|
||||
@@ -165,6 +165,29 @@ mod tests {
|
||||
assert_eq!(cfg.game_dir.unwrap(), PathBuf::from("from-file"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_test_titles_env_is_ignored() {
|
||||
let file = FilePaths {
|
||||
test_titles: vec!["from-file".into()],
|
||||
..Default::default()
|
||||
};
|
||||
let env = |k: &str| (k == "VICTORY_TEST_TITLES").then(OsString::new);
|
||||
let cfg = Config::resolve(file, None, env).unwrap();
|
||||
assert_eq!(cfg.test_titles, vec![PathBuf::from("from-file")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_titles_env_splits_paths() {
|
||||
let value = std::env::join_paths(["first", "second"]).unwrap();
|
||||
let file = FilePaths::default();
|
||||
let env = |k: &str| (k == "VICTORY_TEST_TITLES").then(|| value.clone());
|
||||
let cfg = Config::resolve(file, None, env).unwrap();
|
||||
assert_eq!(
|
||||
cfg.test_titles,
|
||||
vec![PathBuf::from("first"), PathBuf::from("second")]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn example_config_parses() {
|
||||
let text = include_str!("../../../victory.example.toml");
|
||||
|
||||
@@ -17,8 +17,11 @@ pub(crate) struct HostHeap {
|
||||
pub(crate) heap: ID3D12DescriptorHeap,
|
||||
cpu: usize,
|
||||
step: u32,
|
||||
/// Slots mirroring the title's; view heaps have [`DYNAMIC`] more.
|
||||
/// Slots mirroring the title's; view heaps have `dynamic` more.
|
||||
count: u32,
|
||||
/// Dynamic slots past `count` (none in sampler heaps): [`DYNAMIC`]
|
||||
/// where the host takes them, else [`MIN_DYNAMIC`].
|
||||
dynamic: u32,
|
||||
sampler: bool,
|
||||
/// The record (view index and generation) each slot was last made from.
|
||||
made: Mutex<Vec<u64>>,
|
||||
@@ -62,7 +65,13 @@ const PORTABLE_VIEWS: u32 = 1_000_000;
|
||||
/// Slots past the title's in a view heap, for tables a draw needs made
|
||||
/// afresh (constant buffers copied per draw). A list holds the slots it
|
||||
/// took until it is reset (its submissions have run) or released.
|
||||
const DYNAMIC: u32 = 1 << 16;
|
||||
/// 2^16 ran out seconds into the world (every world run on an RX 9070 XT,
|
||||
/// each a device removal shortly after; #59).
|
||||
const DYNAMIC: u32 = 1 << 18;
|
||||
|
||||
/// The dynamic slots of a heap whose host would not take [`DYNAMIC`] more
|
||||
/// (a capped heap, NVIDIA): the title's slots keep their room first.
|
||||
const MIN_DYNAMIC: u32 = 1 << 16;
|
||||
|
||||
impl HostHeap {
|
||||
pub(crate) fn new(sampler: bool, count: u32) -> Option<Self> {
|
||||
@@ -84,18 +93,31 @@ impl HostHeap {
|
||||
})
|
||||
}
|
||||
};
|
||||
let extra = if sampler { 0 } else { DYNAMIC };
|
||||
let (heap, count) = match make(count + extra) {
|
||||
Ok(heap) => (heap, count),
|
||||
Err(e) if !sampler && count + extra > PORTABLE_VIEWS => {
|
||||
// shortcut: descriptors past the host's limit are left out;
|
||||
// a title that reaches them needs remapping.
|
||||
tracing::warn!(error = %e, count, "host view heap capped at {PORTABLE_VIEWS}");
|
||||
(make(PORTABLE_VIEWS).ok()?, PORTABLE_VIEWS - extra)
|
||||
// The larger dynamic range only where the host takes it on top of
|
||||
// every title slot; else the smaller one, and the cap after that.
|
||||
let (heap, count, extra) = if sampler {
|
||||
match make(count) {
|
||||
Ok(heap) => (heap, count, 0),
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, count, sampler, "no host descriptor heap");
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, count, sampler, "no host descriptor heap");
|
||||
return None;
|
||||
} else if let Ok(heap) = make(count + DYNAMIC) {
|
||||
(heap, count, DYNAMIC)
|
||||
} else {
|
||||
match make(count + MIN_DYNAMIC) {
|
||||
Ok(heap) => (heap, count, MIN_DYNAMIC),
|
||||
Err(e) if count + MIN_DYNAMIC > PORTABLE_VIEWS => {
|
||||
// shortcut: descriptors past the host's limit are left
|
||||
// out; a title that reaches them needs remapping.
|
||||
tracing::warn!(error = %e, count, "host view heap capped at {PORTABLE_VIEWS}");
|
||||
(make(PORTABLE_VIEWS).ok()?, PORTABLE_VIEWS - MIN_DYNAMIC, MIN_DYNAMIC)
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, count, sampler, "no host descriptor heap");
|
||||
return None;
|
||||
}
|
||||
}
|
||||
};
|
||||
// SAFETY: a live heap.
|
||||
@@ -119,10 +141,11 @@ impl HostHeap {
|
||||
cpu,
|
||||
step,
|
||||
count,
|
||||
dynamic: extra,
|
||||
sampler,
|
||||
made: Mutex::new(vec![0; count as usize]),
|
||||
kept: Mutex::new(vec![None; (count + extra) as usize]),
|
||||
next: Mutex::new((0, vec![false; DYNAMIC as usize])),
|
||||
next: Mutex::new((0, vec![false; extra as usize])),
|
||||
};
|
||||
// A slot never written is undefined: shaders reading one (a slot
|
||||
// the title wrote in a way we do not know, or a table entry no
|
||||
@@ -201,14 +224,14 @@ impl HostHeap {
|
||||
/// `n` consecutive free dynamic slots (view heaps only), taken until
|
||||
/// [`HostHeap::release`]: the first's index.
|
||||
pub(crate) fn dynamic(&self, n: u32) -> Option<u32> {
|
||||
if self.sampler || n == 0 || n > DYNAMIC {
|
||||
if self.sampler || n == 0 || n > self.dynamic {
|
||||
return None;
|
||||
}
|
||||
let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (next, taken) = &mut *guard;
|
||||
let n = n as usize;
|
||||
// Search from `next` on, then from the start.
|
||||
let starts = (*next as usize..DYNAMIC as usize).chain(0..*next as usize);
|
||||
let starts = (*next as usize..self.dynamic as usize).chain(0..*next as usize);
|
||||
let mut run = 0;
|
||||
let mut found = None;
|
||||
let mut last = usize::MAX;
|
||||
@@ -230,7 +253,7 @@ impl HostHeap {
|
||||
return None;
|
||||
};
|
||||
taken[first..first + n].fill(true);
|
||||
*next = ((first + n) % DYNAMIC as usize) as u32;
|
||||
*next = ((first + n) % self.dynamic as usize) as u32;
|
||||
Some(self.count + first as u32)
|
||||
}
|
||||
|
||||
@@ -249,7 +272,7 @@ impl HostHeap {
|
||||
return;
|
||||
};
|
||||
let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let end = (at + n).min(DYNAMIC) as usize;
|
||||
let end = (at + n).min(self.dynamic) as usize;
|
||||
if let Some(slots) = guard.1.get_mut(at as usize..end) {
|
||||
slots.fill(false);
|
||||
}
|
||||
@@ -734,9 +757,13 @@ pub(crate) fn placed_texture(view: &View) -> Option<View> {
|
||||
fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) {
|
||||
let Some(host) = host() else { return };
|
||||
let is_buffer = |r: &usize| crate::resource::buffer_bytes(*r as crate::object::This).is_some();
|
||||
let buffer = match view {
|
||||
View::Unordered(r, _, desc) => is_buffer(r) || desc.is_some_and(|d| d[1] == 1),
|
||||
View::Placed(true, resource, _) => resource[0] == 1,
|
||||
// Unordered views: whether a buffer, and the title's view dimension.
|
||||
let (buffer, dimension) = match view {
|
||||
View::Unordered(r, _, desc) => (
|
||||
is_buffer(r) || desc.is_some_and(|d| d[1] == 1),
|
||||
desc.map(|d| d[1]),
|
||||
),
|
||||
View::Placed(true, resource, desc) => (resource[0] == 1, Some(desc[1])),
|
||||
// Shader views of buffers read nothing through a null buffer view:
|
||||
// a null 2D view where the shader expects a buffer is a mismatch
|
||||
// the hardware does not survive in general (GPU-based validation
|
||||
@@ -758,14 +785,14 @@ fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) {
|
||||
}
|
||||
_ => return null_view(at),
|
||||
};
|
||||
let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC {
|
||||
Format: DXGI_FORMAT_R32_UINT,
|
||||
ViewDimension: if buffer {
|
||||
D3D12_UAV_DIMENSION_BUFFER
|
||||
} else {
|
||||
D3D12_UAV_DIMENSION_TEXTURE2D
|
||||
},
|
||||
..Default::default()
|
||||
let desc = if buffer {
|
||||
D3D12_UNORDERED_ACCESS_VIEW_DESC {
|
||||
Format: DXGI_FORMAT_R32_UINT,
|
||||
ViewDimension: D3D12_UAV_DIMENSION_BUFFER,
|
||||
..Default::default()
|
||||
}
|
||||
} else {
|
||||
null_uav_desc(dimension)
|
||||
};
|
||||
// SAFETY: a slot of our heap; a null resource is allowed with a desc.
|
||||
unsafe {
|
||||
@@ -778,6 +805,46 @@ fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) {
|
||||
};
|
||||
}
|
||||
|
||||
/// A null texture UAV of the title's view dimension (1D, 1D or 2D arrays,
|
||||
/// 3D), 2D if it names none: a 2D null view where the shader writes a 3D
|
||||
/// texture is a mismatch GPU-based validation reports (the world's wind
|
||||
/// field, CS_CopyWindFieldBeforeUpdateWithSmooth, 2026-11-24).
|
||||
fn null_uav_desc(dimension: Option<u32>) -> D3D12_UNORDERED_ACCESS_VIEW_DESC {
|
||||
let mut desc = D3D12_UNORDERED_ACCESS_VIEW_DESC {
|
||||
Format: DXGI_FORMAT_R32_UINT,
|
||||
ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D,
|
||||
..Default::default()
|
||||
};
|
||||
match dimension.map(|d| D3D12_UAV_DIMENSION(d as i32)) {
|
||||
Some(D3D12_UAV_DIMENSION_TEXTURE1D) => {
|
||||
desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D;
|
||||
}
|
||||
Some(D3D12_UAV_DIMENSION_TEXTURE1DARRAY) => {
|
||||
desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1DARRAY;
|
||||
desc.Anonymous.Texture1DArray = D3D12_TEX1D_ARRAY_UAV {
|
||||
ArraySize: 1,
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
Some(D3D12_UAV_DIMENSION_TEXTURE2DARRAY) => {
|
||||
desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY;
|
||||
desc.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_UAV {
|
||||
ArraySize: 1,
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
Some(D3D12_UAV_DIMENSION_TEXTURE3D) => {
|
||||
desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D;
|
||||
desc.Anonymous.Texture3D = D3D12_TEX3D_UAV {
|
||||
WSize: u32::MAX,
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
desc
|
||||
}
|
||||
|
||||
/// A buffer view that reads zeros (raw, as translated shaders mostly read
|
||||
/// buffers).
|
||||
fn null_buffer_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) {
|
||||
@@ -856,19 +923,54 @@ fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A null texture UAV keeps the title's dimension (3D for the world's
|
||||
/// wind field), and is 2D when the title names none.
|
||||
#[test]
|
||||
fn null_uavs_keep_the_titles_dimension() {
|
||||
let d = null_uav_desc(Some(8));
|
||||
assert_eq!(d.ViewDimension, D3D12_UAV_DIMENSION_TEXTURE3D);
|
||||
// SAFETY: the member the dimension names.
|
||||
assert_eq!(unsafe { d.Anonymous.Texture3D.WSize }, u32::MAX);
|
||||
let d = null_uav_desc(Some(5));
|
||||
assert_eq!(d.ViewDimension, D3D12_UAV_DIMENSION_TEXTURE2DARRAY);
|
||||
// SAFETY: the member the dimension names.
|
||||
assert_eq!(unsafe { d.Anonymous.Texture2DArray.ArraySize }, 1);
|
||||
let dimension = |d| null_uav_desc(d).ViewDimension;
|
||||
assert_eq!(dimension(Some(2)), D3D12_UAV_DIMENSION_TEXTURE1D);
|
||||
assert_eq!(dimension(Some(4)), D3D12_UAV_DIMENSION_TEXTURE2D);
|
||||
assert_eq!(dimension(None), D3D12_UAV_DIMENSION_TEXTURE2D);
|
||||
// Multisampled UAVs need a cap; they stay 2D.
|
||||
assert_eq!(dimension(Some(6)), D3D12_UAV_DIMENSION_TEXTURE2D);
|
||||
}
|
||||
|
||||
/// A null 3D UAV made on the real device leaves it alive.
|
||||
#[test]
|
||||
fn null_3d_uav_is_accepted_by_the_device() {
|
||||
let Some(host) = host() else {
|
||||
return; // no host GPU
|
||||
};
|
||||
let Some(heap) = HostHeap::new(false, 4) else {
|
||||
return;
|
||||
};
|
||||
let view = View::Unordered(0, 0, Some([28, 8, 0, 0, 0, 0, 0, 0, 0, 0]));
|
||||
null_for(&view, heap.cpu(0));
|
||||
// SAFETY: a plain device query.
|
||||
assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok());
|
||||
}
|
||||
|
||||
/// Dynamic slots stay taken until given back, and runs do not wrap.
|
||||
#[test]
|
||||
fn dynamic_slots_are_held_until_released() {
|
||||
let Some(heap) = HostHeap::new(false, 4) else {
|
||||
return; // no host GPU
|
||||
};
|
||||
let a = heap.dynamic(DYNAMIC - 100).unwrap();
|
||||
let a = heap.dynamic(heap.dynamic - 100).unwrap();
|
||||
let b = heap.dynamic(60).unwrap();
|
||||
assert_eq!((a, b), (4, 4 + DYNAMIC - 100));
|
||||
assert_eq!((a, b), (4, 4 + heap.dynamic - 100));
|
||||
// 40 left at the end: 50 do not fit until something is given back.
|
||||
assert_eq!(heap.dynamic(50), None);
|
||||
heap.release(a, 50);
|
||||
assert_eq!(heap.dynamic(50), Some(4));
|
||||
assert_eq!(heap.dynamic(40), Some(4 + DYNAMIC - 40));
|
||||
assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic - 40));
|
||||
}
|
||||
}
|
||||
@@ -88,7 +88,8 @@ const LEVEL_IIDS: [Iid; 9] = [
|
||||
),
|
||||
];
|
||||
|
||||
fn is_device(iid: *const Iid) -> bool {
|
||||
/// Whether `iid` names the device: its first interface or a newer level.
|
||||
pub(crate) fn is_device(iid: *const Iid) -> bool {
|
||||
object::is(iid, &[IID]) || object::is(iid, &LEVEL_IIDS)
|
||||
}
|
||||
|
||||
@@ -445,6 +446,54 @@ mod tests {
|
||||
assert_eq!(missing(), E_NOTIMPL);
|
||||
}
|
||||
|
||||
/// A device child, and the DXGI device, hand out the device as any
|
||||
/// interface the device itself answers to.
|
||||
#[test]
|
||||
fn the_device_is_found_at_every_level_through_others() {
|
||||
type Get = extern "system" fn(This, *const Iid, *mut This) -> HRESULT;
|
||||
let fence_iid = &crate::fence::FENCE_IIDS[0];
|
||||
let mut fence = std::ptr::null();
|
||||
assert_eq!(
|
||||
crate::fence::create(std::ptr::null(), 0, 0, fence_iid, &mut fence),
|
||||
S_OK
|
||||
);
|
||||
let get_device = slot::<Get>(fence, 0x38);
|
||||
let dxgi = dxgi::device();
|
||||
let query = slot::<Get>(dxgi, 0);
|
||||
for iid in std::iter::once(&IID).chain(&LEVEL_IIDS) {
|
||||
let mut found = std::ptr::null();
|
||||
assert_eq!(get_device(fence, iid, &mut found), S_OK, "{iid:02x?}");
|
||||
assert_eq!(found, device());
|
||||
let mut found = std::ptr::null();
|
||||
assert_eq!(query(dxgi, iid, &mut found), S_OK, "{iid:02x?}");
|
||||
assert_eq!(found, device());
|
||||
}
|
||||
// What the device is not, it is not through them either.
|
||||
let mut found = device();
|
||||
assert_eq!(get_device(fence, fence_iid, &mut found), E_NOINTERFACE);
|
||||
assert!(found.is_null());
|
||||
slot::<extern "system" fn(This) -> u32>(fence, 0x10)(fence);
|
||||
}
|
||||
|
||||
/// The host's: a fence's `GetDevice` for `ID3D12Device5`.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn the_hosts_children_hand_out_newer_device_levels() {
|
||||
use windows::Win32::Graphics::Direct3D12::{
|
||||
D3D12_FENCE_FLAG_NONE, ID3D12Device5, ID3D12Fence,
|
||||
};
|
||||
let Some(host) = crate::host::host() else {
|
||||
return; // no host GPU here
|
||||
};
|
||||
// SAFETY: plain calls on the host device and its fence.
|
||||
unsafe {
|
||||
let fence: ID3D12Fence = host.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
|
||||
let mut device: Option<ID3D12Device5> = None;
|
||||
assert!(fence.GetDevice(&mut device).is_ok());
|
||||
assert!(device.is_some());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn virtual_memory_configuration_reports_user_space() {
|
||||
let mut config = VirtualMemory {
|
||||
|
||||
@@ -77,6 +77,8 @@ pub(crate) struct State {
|
||||
/// The dynamic slots the list holds: title heap, first, count; given
|
||||
/// back when the list is reset or released.
|
||||
dynamic: Vec<(usize, u32, u32)>,
|
||||
/// A fresh table of the stage being bound could not be made.
|
||||
table_failed: bool,
|
||||
}
|
||||
|
||||
impl Drop for State {
|
||||
@@ -344,7 +346,9 @@ impl State {
|
||||
once!(mesh, "a draw or mesh dispatch with another kind of pipeline");
|
||||
return false;
|
||||
}
|
||||
self.bind(list, p, false);
|
||||
if !self.bind(list, p, false) {
|
||||
return false;
|
||||
}
|
||||
let l = &list.list;
|
||||
// Vertex buffers the input layout reads.
|
||||
let mut views = [D3D12_VERTEX_BUFFER_VIEW::default(); 32];
|
||||
@@ -403,7 +407,9 @@ impl State {
|
||||
/// What draws and dispatches share: heaps, our root signature, the
|
||||
/// pipeline, and per stage the user data, root views and the
|
||||
/// descriptors its tables hold.
|
||||
fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) {
|
||||
/// False if the draw or dispatch must not run: a table it reads could
|
||||
/// not be made.
|
||||
fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) -> bool {
|
||||
let l = &list.list;
|
||||
// Heaps first: a root signature with directly indexed heaps must be
|
||||
// set after them.
|
||||
@@ -446,7 +452,19 @@ impl State {
|
||||
}
|
||||
for stage in &p.stages {
|
||||
let t = stage.translated();
|
||||
self.table_failed = false;
|
||||
let made = self.tables(list, &t.used, compute);
|
||||
if self.table_failed {
|
||||
static DROPPED_TABLES: AtomicU64 = AtomicU64::new(0);
|
||||
let n = DROPPED_TABLES.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
if n.is_power_of_two() {
|
||||
tracing::warn!(
|
||||
dropped = n,
|
||||
"a draw or dispatch dropped: no dynamic slots for its tables"
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if let Some((param, dwords)) = stage.user_data {
|
||||
let mut values = vec![0u32; dwords as usize];
|
||||
for u in &t.host.user_data {
|
||||
@@ -489,6 +507,7 @@ impl State {
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Runs a dispatch on the host.
|
||||
@@ -513,7 +532,10 @@ impl State {
|
||||
once!("a dispatch with a graphics pipeline");
|
||||
return;
|
||||
}
|
||||
self.bind(list, p, true);
|
||||
if !self.bind(list, p, true) {
|
||||
DROPPED.fetch_add(1, Ordering::Relaxed);
|
||||
return;
|
||||
}
|
||||
#[cfg(feature = "diagnostics")]
|
||||
list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true));
|
||||
// SAFETY: an open list with everything set.
|
||||
@@ -696,6 +718,12 @@ impl State {
|
||||
continue;
|
||||
}
|
||||
let Some(first) = host.dynamic(n) else {
|
||||
// Without its fresh table the shader would read the title's
|
||||
// slots, which for constant buffer tables hold no constant
|
||||
// view: a texture or null descriptor read as a buffer gives
|
||||
// a wild address on AMD and the device is removed (#59).
|
||||
// The draw or dispatch is dropped instead.
|
||||
self.table_failed = true;
|
||||
continue;
|
||||
};
|
||||
self.fresh_tables.insert(key, first);
|
||||
@@ -988,10 +1016,7 @@ impl State {
|
||||
DRAW | INDEXED => self.topology != RECTANGLES && self.prepare(list, kind == INDEXED),
|
||||
MESH => self.prepare_for(list, false, true),
|
||||
DISPATCH => match crate::pipeline::host_pipeline(self.pipeline as This) {
|
||||
Some(p) if p.compute => {
|
||||
self.bind(list, p, true);
|
||||
true
|
||||
}
|
||||
Some(p) if p.compute => self.bind(list, p, true),
|
||||
_ => false,
|
||||
},
|
||||
_ => false,
|
||||
|
||||
@@ -92,7 +92,7 @@ fn query(kind: usize, iid: *const Iid, known: &[Iid], found: This, out: *mut Thi
|
||||
|
||||
/// The DXGI device also answers for the D3D12 device.
|
||||
extern "system" fn device_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
if object::is(iid, &[crate::device::IID]) {
|
||||
if crate::device::is_device(iid) {
|
||||
return object::answer(DXGI_DEVICE, iid, Some(crate::device::device()), out);
|
||||
}
|
||||
query(DXGI_DEVICE, iid, &DEVICE_IIDS, this, out)
|
||||
|
||||
@@ -264,6 +264,8 @@ mod tests {
|
||||
factory.EnumWarpAdapter::<IDXGIAdapter>()
|
||||
};
|
||||
let Ok(raw) = raw else { return };
|
||||
// SAFETY: EnumWarpAdapter returns a DXGI adapter, which implements
|
||||
// IDXGIAdapter1; `raw` owns that interface.
|
||||
let desc = unsafe { raw.cast::<IDXGIAdapter1>().unwrap().GetDesc1().unwrap() };
|
||||
eprintln!(
|
||||
"EnumWarpAdapter: vendor={:#x}, flags={:#x}",
|
||||
@@ -1466,6 +1468,8 @@ struct Presenter {
|
||||
struct Meter {
|
||||
since: std::time::Instant,
|
||||
frames: u32,
|
||||
#[cfg(feature = "diagnostics")]
|
||||
copy_stats_frames: u64,
|
||||
drawn: u64,
|
||||
logged: std::time::Instant,
|
||||
/// The caption the window had, once read.
|
||||
@@ -1478,6 +1482,8 @@ impl Meter {
|
||||
Meter {
|
||||
since: now,
|
||||
frames: 0,
|
||||
#[cfg(feature = "diagnostics")]
|
||||
copy_stats_frames: 0,
|
||||
drawn: crate::draw::drawn(),
|
||||
logged: now,
|
||||
caption: None,
|
||||
@@ -1489,6 +1495,10 @@ impl Meter {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
tracing::debug!(target: "victory_gpu::frame", token = crate::frame::current(), "present");
|
||||
self.frames += 1;
|
||||
#[cfg(feature = "diagnostics")]
|
||||
{
|
||||
self.copy_stats_frames += 1;
|
||||
}
|
||||
let elapsed = self.since.elapsed();
|
||||
if elapsed < std::time::Duration::from_secs(1) {
|
||||
return;
|
||||
@@ -1527,7 +1537,7 @@ impl Meter {
|
||||
);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
{
|
||||
crate::copystat::log(frames);
|
||||
crate::copystat::log(std::mem::take(&mut self.copy_stats_frames) as f64);
|
||||
for (why, n) in drops.iter().take(40) {
|
||||
tracing::info!(
|
||||
"dropped {:.1}/frame without a host pipeline: {why}",
|
||||
|
||||
@@ -223,13 +223,14 @@ pub(crate) extern "system" fn set_name(this: This, name: *const u16) -> HRESULT
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// The device-child method: the device that made the object.
|
||||
/// The device-child method: the device that made the object, as any of
|
||||
/// the interfaces the device itself answers to.
|
||||
pub(crate) extern "system" fn parent_device(_: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
let device = crate::device::device();
|
||||
answer(
|
||||
DEVICE,
|
||||
iid,
|
||||
is(iid, &[crate::device::IID]).then_some(device),
|
||||
crate::device::is_device(iid).then_some(device),
|
||||
out,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -283,7 +283,9 @@ pub(crate) fn note_why(why: String) {
|
||||
pub(crate) fn take_drops() -> Vec<(String, u64)> {
|
||||
let drops = DROPS.lock().unwrap_or_else(|e| e.into_inner()).take();
|
||||
let mut drops: Vec<(String, u64)> = drops.into_iter().flatten().collect();
|
||||
drops.sort_by_key(|d| std::cmp::Reverse(d.1));
|
||||
// Frame reports only show the first 40 reasons. Keep ties ordered so
|
||||
// a HashMap iteration order change cannot change which reasons appear.
|
||||
drops.sort_unstable_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
|
||||
drops
|
||||
}
|
||||
|
||||
|
||||
@@ -129,7 +129,10 @@ fn f32_to_half(v: f32) -> u16 {
|
||||
if exp <= 0 {
|
||||
return sign; // too small: zero
|
||||
}
|
||||
sign | (exp as u16) << 10 | ((man + 0x1000) >> 13) as u16
|
||||
// Rounded to nearest: a carry out of the mantissa is added into the
|
||||
// exponent (`2 - 2^-12` is 2.0); at most it reaches infinity, 0x7c00.
|
||||
let half = (exp as u32) << 10;
|
||||
sign | (half + ((man + 0x1000) >> 13)) as u16
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -165,6 +168,24 @@ mod tests {
|
||||
assert_eq!(half_to_f32(0xc000), -2.0);
|
||||
}
|
||||
|
||||
/// A rounding that carries out of the mantissa raises the exponent
|
||||
/// (the carry used to be or-ed into an odd exponent, halving the value).
|
||||
#[test]
|
||||
fn halves_round_up_into_the_next_power_of_two() {
|
||||
assert_eq!(f32_to_half(2.0 - 2f32.powi(-12)), 0x4000);
|
||||
assert_eq!(f32_to_half(0.5 - 2f32.powi(-13)), 0x3800);
|
||||
assert_eq!(f32_to_half(65520.0), 0x7c00, "past the largest half");
|
||||
// An R16_FLOAT element at 1.0, 2^-12 and 1.0: the fourth corner is
|
||||
// 2 - 2^-12, which rounds to 2.0.
|
||||
let src: Vec<u8> = [0x3c00_u16, 0x0c00, 0x3c00]
|
||||
.iter()
|
||||
.flat_map(|h| h.to_le_bytes())
|
||||
.collect();
|
||||
let mut dst = vec![0u8; 6 * 2];
|
||||
expand_rects(&src, &mut dst, 2, &[(0, 54)]);
|
||||
assert_eq!(dst[10..], 0x4000_u16.to_le_bytes());
|
||||
}
|
||||
|
||||
/// An element that reaches past the stride (float4 at 4 in 8-byte
|
||||
/// vertices, RGBA8 at the stride itself): the components inside get
|
||||
/// the fourth corner, the rest keep the first vertex's bytes. The old
|
||||
|
||||
@@ -4,9 +4,11 @@
|
||||
//! Every title import that takes a path is bound here. A path on a virtual
|
||||
//! drive (`X:\..`, `X:/..`, `X:`, `\\?\X:\..`) is rewritten to the host
|
||||
//! folder behind it and handed to the host's own function; any other path
|
||||
//! goes to the host unchanged. A rewritten narrow path goes to the wide
|
||||
//! twin, so host folders outside the ANSI code page work. Letters are
|
||||
//! chosen among those the host does not use, so no host drive is hidden.
|
||||
//! goes to the host unchanged. A rewritten narrow path goes to the host's
|
||||
//! wide twin, so host folders outside the ANSI code page work; never to our
|
||||
//! wide wrapper, which would rewrite the host path a second time when its
|
||||
//! drive letter is mounted too. Letters are chosen among those the host
|
||||
//! does not use, so no host drive is hidden.
|
||||
#![allow(non_snake_case)]
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
#![allow(clippy::too_many_arguments)]
|
||||
@@ -282,15 +284,17 @@ pub extern "system" fn CreateFileA(
|
||||
template: Handle,
|
||||
) -> Handle {
|
||||
match narrow(path) {
|
||||
Some(p) => CreateFileW(
|
||||
p.as_ptr(),
|
||||
access,
|
||||
share,
|
||||
security,
|
||||
disposition,
|
||||
flags,
|
||||
template,
|
||||
),
|
||||
Some(p) => {
|
||||
host!("kernel32.dll", "CreateFileW": extern "system" fn(*const u16, u32, u32, *const c_void, u32, u32, Handle) -> Handle)(
|
||||
p.as_ptr(),
|
||||
access,
|
||||
share,
|
||||
security,
|
||||
disposition,
|
||||
flags,
|
||||
template,
|
||||
)
|
||||
}
|
||||
None => {
|
||||
host!("kernel32.dll", "CreateFileA": extern "system" fn(*const c_char, u32, u32, *const c_void, u32, u32, Handle) -> Handle)(
|
||||
path,
|
||||
@@ -354,7 +358,11 @@ pub extern "system" fn SetFileAttributesW(path: *const u16, attributes: u32) ->
|
||||
|
||||
pub extern "system" fn GetFileAttributesA(path: *const c_char) -> u32 {
|
||||
match narrow(path) {
|
||||
Some(p) => GetFileAttributesW(p.as_ptr()),
|
||||
Some(p) => {
|
||||
host!("kernel32.dll", "GetFileAttributesW": extern "system" fn(*const u16) -> u32)(
|
||||
p.as_ptr(),
|
||||
)
|
||||
}
|
||||
None => {
|
||||
host!("kernel32.dll", "GetFileAttributesA": extern "system" fn(*const c_char) -> u32)(
|
||||
path,
|
||||
@@ -536,7 +544,10 @@ pub extern "C" fn fread(buffer: *mut u8, size: usize, count: usize, stream: File
|
||||
|
||||
pub extern "C" fn fopen(path: *const c_char, mode: *const c_char) -> File {
|
||||
match narrow(path) {
|
||||
Some(p) => _wfopen(p.as_ptr(), widen(mode).as_ptr()),
|
||||
Some(p) => host!("ucrtbase.dll", "_wfopen": extern "C" fn(*const u16, *const u16) -> File)(
|
||||
p.as_ptr(),
|
||||
widen(mode).as_ptr(),
|
||||
),
|
||||
None => {
|
||||
host!("ucrtbase.dll", "fopen": extern "C" fn(*const c_char, *const c_char) -> File)(
|
||||
path, mode,
|
||||
@@ -547,7 +558,13 @@ pub extern "C" fn fopen(path: *const c_char, mode: *const c_char) -> File {
|
||||
|
||||
pub extern "C" fn fopen_s(out: *mut File, path: *const c_char, mode: *const c_char) -> i32 {
|
||||
match narrow(path) {
|
||||
Some(p) => _wfopen_s(out, p.as_ptr(), widen(mode).as_ptr()),
|
||||
Some(p) => {
|
||||
host!("ucrtbase.dll", "_wfopen_s": extern "C" fn(*mut File, *const u16, *const u16) -> i32)(
|
||||
out,
|
||||
p.as_ptr(),
|
||||
widen(mode).as_ptr(),
|
||||
)
|
||||
}
|
||||
None => {
|
||||
host!("ucrtbase.dll", "fopen_s": extern "C" fn(*mut File, *const c_char, *const c_char) -> i32)(
|
||||
out, path, mode,
|
||||
@@ -640,7 +657,13 @@ extern "C" fn fiopen_wide(path: *const u16, mode: i32, protection: i32) -> File
|
||||
/// `_Fiopen(const char* path, ios_base::openmode, int protection)`.
|
||||
extern "C" fn fiopen(path: *const c_char, mode: i32, protection: i32) -> File {
|
||||
match narrow(path) {
|
||||
Some(p) => fiopen_wide(p.as_ptr(), mode, protection),
|
||||
Some(p) => {
|
||||
host!("msvcp140.dll", "?_Fiopen@std@@YAPEAU_iobuf@@PEB_WHH@Z": extern "C" fn(*const u16, i32, i32) -> File)(
|
||||
p.as_ptr(),
|
||||
mode,
|
||||
protection,
|
||||
)
|
||||
}
|
||||
None => {
|
||||
host!("msvcp140.dll", "?_Fiopen@std@@YAPEAU_iobuf@@PEBDHH@Z": extern "C" fn(*const c_char, i32, i32) -> File)(
|
||||
path, mode, protection,
|
||||
@@ -866,4 +889,53 @@ mod tests {
|
||||
fclose(f);
|
||||
assert!(dir.path().join("plain.txt").is_file());
|
||||
}
|
||||
|
||||
/// A narrow path is rewritten once, as its wide twin is. The inner
|
||||
/// drive's folder lies on the outer virtual drive, as the title folder
|
||||
/// does when it sits on a host `G:` drive and is mounted as `G:`. The
|
||||
/// outer letter is no host drive, so the host finds nothing there; a
|
||||
/// narrow call that reaches the outer folder rewrote the path twice.
|
||||
#[test]
|
||||
fn narrow_paths_are_rewritten_once() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let folder = dir.path().join("inner");
|
||||
std::fs::create_dir(&folder).unwrap();
|
||||
std::fs::write(folder.join("present.txt"), b"").unwrap();
|
||||
let outer = mount(dir.path()).unwrap();
|
||||
let inner = mount(Path::new(&format!(r"{outer}:\inner"))).unwrap();
|
||||
let path = |name: &str| format!("{inner}:/{name}\0");
|
||||
|
||||
const INVALID_FILE_ATTRIBUTES: u32 = u32::MAX;
|
||||
let wide = GetFileAttributesW(w(&format!("{inner}:/present.txt")).as_ptr());
|
||||
assert_eq!(wide, INVALID_FILE_ATTRIBUTES);
|
||||
let narrow = GetFileAttributesA(path("present.txt").as_ptr().cast());
|
||||
assert_eq!(narrow, wide, "GetFileAttributesA agrees with its wide twin");
|
||||
|
||||
const GENERIC_WRITE: u32 = 0x4000_0000;
|
||||
const CREATE_ALWAYS: u32 = 2;
|
||||
let null = std::ptr::null_mut();
|
||||
let h = CreateFileA(
|
||||
path("a.bin").as_ptr().cast(),
|
||||
GENERIC_WRITE,
|
||||
0,
|
||||
null,
|
||||
CREATE_ALWAYS,
|
||||
0,
|
||||
null,
|
||||
);
|
||||
assert_eq!(h as isize, -1);
|
||||
assert!(fopen(path("b.txt").as_ptr().cast(), c"wb".as_ptr()).is_null());
|
||||
let mut f: File = std::ptr::null_mut();
|
||||
let error = fopen_s(&mut f, path("c.txt").as_ptr().cast(), c"wb".as_ptr());
|
||||
assert_ne!(error, 0);
|
||||
const OUT: i32 = 2;
|
||||
assert!(fiopen(path("d.txt").as_ptr().cast(), OUT, 0x40).is_null());
|
||||
|
||||
// Nothing was made behind a path rewritten twice.
|
||||
let names: Vec<_> = std::fs::read_dir(&folder)
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().file_name())
|
||||
.collect();
|
||||
assert_eq!(names, ["present.txt"]);
|
||||
}
|
||||
}
|
||||
@@ -1048,18 +1048,22 @@ mod tests {
|
||||
named.name
|
||||
);
|
||||
}
|
||||
// Every override names a real export of its DLL.
|
||||
// Every override names a real export of its DLL. Some exports only
|
||||
// exist on newer Windows (WinHttpGetProxySettingsEx is absent from
|
||||
// Windows 10's winhttp.dll); the HLE supplies those itself, so skip
|
||||
// them only when the host really lacks them.
|
||||
const NEWER_WINDOWS_ONLY: &[&str] = &["WinHttpGetProxySettingsEx"];
|
||||
for e in m.exports.iter().filter(|e| !e.name.starts_with('#')) {
|
||||
let dll = if e.name.starts_with("WinHttp") {
|
||||
"winhttp.dll"
|
||||
} else {
|
||||
"ws2_32.dll"
|
||||
};
|
||||
assert!(
|
||||
crate::host::function(dll, e.name).is_some(),
|
||||
"{dll} lacks {}",
|
||||
e.name
|
||||
);
|
||||
let present = crate::host::function(dll, e.name).is_some();
|
||||
if !present && NEWER_WINDOWS_ONLY.contains(&e.name) {
|
||||
continue;
|
||||
}
|
||||
assert!(present, "{dll} lacks {}", e.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -105,7 +105,7 @@ impl Port {
|
||||
let worker = port.clone();
|
||||
std::thread::spawn(move || {
|
||||
loop {
|
||||
match worker.take(1000) {
|
||||
match worker.take(1000, || false) {
|
||||
Some(task) => task.run(false),
|
||||
None if Arc::strong_count(&worker) == 1 => break,
|
||||
None => {}
|
||||
@@ -127,17 +127,19 @@ impl Port {
|
||||
}
|
||||
}
|
||||
|
||||
/// The next queued task, waiting up to `timeout_ms`.
|
||||
fn take(&self, timeout_ms: u32) -> Option<Task> {
|
||||
/// The next queued task, waiting up to `timeout_ms`, or until `ended`
|
||||
/// (checked whenever the port is woken) says no task will come.
|
||||
fn take(&self, timeout_ms: u32, ended: impl Fn() -> bool) -> Option<Task> {
|
||||
let waiting = |t: &mut VecDeque<Task>| t.is_empty() && !ended();
|
||||
let tasks = lock(&self.tasks);
|
||||
let mut tasks = if timeout_ms == INFINITE {
|
||||
self.ready
|
||||
.wait_while(tasks, |t| t.is_empty())
|
||||
.wait_while(tasks, waiting)
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
} else {
|
||||
let timeout = Duration::from_millis(timeout_ms.into());
|
||||
self.ready
|
||||
.wait_timeout_while(tasks, timeout, |t| t.is_empty())
|
||||
.wait_timeout_while(tasks, timeout, waiting)
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.0
|
||||
};
|
||||
@@ -332,7 +334,9 @@ pub fn XTaskQueueCloseHandle(handle: *const Queue) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs one queued callback of a manual port; false if none came in time.
|
||||
/// Runs one queued callback of a manual port; false if none came in time,
|
||||
/// or none can come: the queue was terminated (which ends a wait under way,
|
||||
/// as a dispatcher thread's loop expects).
|
||||
pub fn XTaskQueueDispatch(handle: *const Queue, port: u32, timeout_ms: u32) -> bool {
|
||||
let Some(queue) = queue(handle) else {
|
||||
return false;
|
||||
@@ -343,7 +347,7 @@ pub fn XTaskQueueDispatch(handle: *const Queue, port: u32, timeout_ms: u32) -> b
|
||||
if port.mode != Mode::Manual {
|
||||
return false;
|
||||
}
|
||||
match port.take(timeout_ms) {
|
||||
match port.take(timeout_ms, || queue.terminated.load(Ordering::Acquire)) {
|
||||
Some(task) => {
|
||||
task.run(false);
|
||||
true
|
||||
@@ -379,6 +383,10 @@ pub fn XTaskQueueTerminate(
|
||||
queue.terminated.store(true, Ordering::Release);
|
||||
for port in &queue.ports {
|
||||
let pending: Vec<Task> = lock(&port.tasks).drain(..).collect();
|
||||
// Dispatches waiting on this queue end: nothing more will come.
|
||||
// (Those of other queues on the port see theirs is open and wait
|
||||
// on.) After the lock above, so none misses both flag and wake.
|
||||
port.ready.notify_all();
|
||||
for task in pending {
|
||||
task.run(true);
|
||||
}
|
||||
@@ -1179,6 +1187,73 @@ mod tests {
|
||||
XTaskQueueCloseHandle(q);
|
||||
}
|
||||
|
||||
/// A dispatcher thread's loop, `while (XTaskQueueDispatch(queue, port,
|
||||
/// INFINITE));`, ends when its queue is terminated: nothing can be
|
||||
/// submitted to it any more, so nothing else would ever wake it.
|
||||
#[test]
|
||||
fn terminate_ends_a_waiting_dispatch() {
|
||||
static RAN: AtomicU32 = AtomicU32::new(0);
|
||||
extern "system" fn ran(_: *mut c_void, _: bool) {
|
||||
RAN.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
/// Dispatches `queue`'s work until a dispatch returns false, then
|
||||
/// says so.
|
||||
fn dispatcher(queue: *const Queue) -> std::sync::mpsc::Receiver<()> {
|
||||
let (done, ended) = std::sync::mpsc::channel();
|
||||
let queue = queue as usize;
|
||||
std::thread::spawn(move || {
|
||||
while XTaskQueueDispatch(queue as *const Queue, WORK, INFINITE) {}
|
||||
let _ = done.send(());
|
||||
});
|
||||
ended
|
||||
}
|
||||
let run_one = |queue, total| {
|
||||
let none = std::ptr::null_mut();
|
||||
assert_eq!(
|
||||
XTaskQueueSubmitDelayedCallback(queue, WORK, 0, none, Some(ran)),
|
||||
S_OK
|
||||
);
|
||||
for _ in 0..500 {
|
||||
if RAN.load(Ordering::SeqCst) == total {
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
panic!("callback {total} did not run");
|
||||
};
|
||||
let (long, short) = (Duration::from_secs(5), Duration::from_millis(200));
|
||||
let none = std::ptr::null_mut();
|
||||
|
||||
// Two queues on the same manual ports.
|
||||
let (mut a, mut b) = (std::ptr::null(), std::ptr::null());
|
||||
assert_eq!(XTaskQueueCreate(0, 0, &mut a), S_OK);
|
||||
let (mut work, mut completion) = (std::ptr::null(), std::ptr::null());
|
||||
assert_eq!(XTaskQueueGetPort(a, WORK, &mut work), S_OK);
|
||||
assert_eq!(XTaskQueueGetPort(a, COMPLETION, &mut completion), S_OK);
|
||||
assert_eq!(XTaskQueueCreateComposite(work, completion, &mut b), S_OK);
|
||||
|
||||
let ended = dispatcher(a);
|
||||
run_one(a, 1);
|
||||
// The other queue's end is not this one's: the wait goes on and
|
||||
// still runs what comes in.
|
||||
assert_eq!(XTaskQueueTerminate(b, false, none, None), S_OK);
|
||||
assert!(
|
||||
ended.recv_timeout(short).is_err(),
|
||||
"ended with another queue"
|
||||
);
|
||||
run_one(a, 2);
|
||||
// Its own queue's end is.
|
||||
assert_eq!(XTaskQueueTerminate(a, false, none, None), S_OK);
|
||||
assert!(
|
||||
ended.recv_timeout(long).is_ok(),
|
||||
"still waiting on a terminated queue"
|
||||
);
|
||||
// And a dispatch that starts after the end returns at once.
|
||||
assert!(!XTaskQueueDispatch(a, WORK, INFINITE));
|
||||
XTaskQueueCloseHandle(a);
|
||||
XTaskQueueCloseHandle(b);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminate_cancels_what_is_queued() {
|
||||
static TERMINATED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
@@ -362,11 +362,14 @@ fn take<T>(handle: *mut T) {
|
||||
|
||||
impl Provider {
|
||||
/// The provider for the only user and `config` (the service
|
||||
/// configuration id), under `saves`.
|
||||
/// configuration id), under `saves`. An empty id names no
|
||||
/// configuration, like none: as a folder name it would be the user's
|
||||
/// folder itself, where the other configurations' folders are.
|
||||
fn open(saves: &Path, config: Option<&str>) -> Result<Provider, HRESULT> {
|
||||
let config = config.filter(|c| !c.is_empty()).unwrap_or("default");
|
||||
let root = saves
|
||||
.join(format!("{:016X}", xuser::XUID))
|
||||
.join(file_name(config.unwrap_or("default")));
|
||||
.join(file_name(config));
|
||||
std::fs::create_dir_all(&root).map_err(|_| NO_ACCESS)?;
|
||||
let _saves = saves_lock();
|
||||
containers(&root); // converts old containers now
|
||||
@@ -1108,6 +1111,31 @@ mod tests {
|
||||
assert_eq!((v.number, v.display.as_str()), (1, "Chapter 1"));
|
||||
}
|
||||
|
||||
/// An empty configuration id names none. As a folder name it would be
|
||||
/// the folder every configuration lives in, whose folders then look
|
||||
/// like containers of the old layout and are converted away.
|
||||
#[test]
|
||||
fn an_empty_configuration_id_is_the_default_one() {
|
||||
let saves = tempfile::tempdir().unwrap();
|
||||
let scid = Provider::open(saves.path(), Some("scid")).unwrap();
|
||||
assert_eq!(update(&scid.root, "one", &[("a", Some("kept"))]), S_OK);
|
||||
let kept = Some(("one".into(), vec![("a".into(), "kept".into())]));
|
||||
assert_eq!(state(&scid.root), kept);
|
||||
|
||||
let empty = Provider::open(saves.path(), Some("")).unwrap();
|
||||
assert!(scid.root.is_dir(), "another configuration's saves are gone");
|
||||
assert_eq!(state(&scid.root), kept);
|
||||
let default = Provider::open(saves.path(), None).unwrap();
|
||||
assert_eq!(empty.root, default.root);
|
||||
|
||||
// Named configurations stay apart, from it and from each other.
|
||||
assert_ne!(empty.root, scid.root);
|
||||
assert_eq!(state(&empty.root), None);
|
||||
let other = Provider::open(saves.path(), Some("other")).unwrap();
|
||||
assert_eq!(state(&other.root), None);
|
||||
assert_eq!(state(&scid.root), kept);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saves_persist_across_providers() {
|
||||
let this: This = &OBJECT;
|
||||
|
||||
@@ -743,8 +743,10 @@ fn commit(base: usize, len: usize) -> bool {
|
||||
}
|
||||
let error = std::io::Error::last_os_error();
|
||||
if error.raw_os_error() == Some(ERROR_COMMITMENT_LIMIT as i32) {
|
||||
let mut info = PERFORMANCE_INFORMATION::default();
|
||||
info.cb = size_of::<PERFORMANCE_INFORMATION>() as u32;
|
||||
let mut info = PERFORMANCE_INFORMATION {
|
||||
cb: size_of::<PERFORMANCE_INFORMATION>() as u32,
|
||||
..Default::default()
|
||||
};
|
||||
// SAFETY: the buffer and size describe a writable PERFORMANCE_INFORMATION.
|
||||
let queried = unsafe { K32GetPerformanceInfo(&mut info, info.cb) } != 0;
|
||||
victory_loader::log_crash(&commit_limit_message(len, &error, queried.then_some(&info)));
|
||||
@@ -781,6 +783,12 @@ fn commit_limit_message(
|
||||
/// Returns `[base, base + len)` to placeholders; views reaching past it
|
||||
/// are mapped again outside it.
|
||||
fn unmap(physical: &mut Physical, base: usize, len: usize) {
|
||||
// No bytes: no view to return. The search below would still find the
|
||||
// view holding `base` and cut it in two there, and its range of views
|
||||
// starting inside would run backwards (which `BTreeMap` panics on).
|
||||
if len == 0 {
|
||||
return;
|
||||
}
|
||||
let end = base + len;
|
||||
// Views do not overlap: the one holding `base`, then those starting
|
||||
// inside (the GPU's page mappings make one view per page).
|
||||
@@ -1103,6 +1111,48 @@ mod tests {
|
||||
assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1);
|
||||
assert_eq!(XMemIsToolsMemAvailable(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mapping_no_pages_changes_nothing() {
|
||||
let pages = allocate(2);
|
||||
let a = XMemVirtualAlloc(
|
||||
std::ptr::null_mut(),
|
||||
2 * PAGE,
|
||||
MEM_RESERVE | PAGES_64K,
|
||||
0,
|
||||
PAGE_READWRITE,
|
||||
);
|
||||
assert!(!a.is_null());
|
||||
assert_eq!(XMemMapPhysicalPages(a, 2, pages.as_ptr()), a);
|
||||
// SAFETY: both pages are mapped read-write.
|
||||
unsafe { a.cast::<u8>().write(5) };
|
||||
let second = a.wrapping_byte_add(PAGE);
|
||||
|
||||
// A count of 0 at the start of a view, inside it and past it: with
|
||||
// pages, without (an unmap), and as the GPU's page-mapping copy.
|
||||
for at in [a, second, a.wrapping_byte_add(2 * PAGE)] {
|
||||
assert_eq!(XMemMapPhysicalPages(at, 0, pages.as_ptr()), at);
|
||||
assert_eq!(XMemMapPhysicalPages(at, 0, std::ptr::null()), at);
|
||||
assert!(map_alias(at as u64, a as u64, 0));
|
||||
assert!(map_alias(at as u64, 0, 0));
|
||||
}
|
||||
|
||||
// The view is still the one view it was.
|
||||
let view = physical().views.get(&(a as usize)).map(|v| v.0);
|
||||
assert_eq!(view, Some(2 * PAGE));
|
||||
assert_eq!(query(a).host.State, MEM_COMMIT);
|
||||
assert_eq!(query(second).host.State, MEM_COMMIT);
|
||||
// SAFETY: still mapped.
|
||||
assert_eq!(unsafe { a.cast::<u8>().read() }, 5);
|
||||
|
||||
// A count of 1 still unmaps that page alone.
|
||||
assert_eq!(XMemMapPhysicalPages(second, 1, std::ptr::null()), second);
|
||||
assert_eq!(query(second).host.State, MEM_RESERVE);
|
||||
assert_eq!(query(a).host.State, MEM_COMMIT);
|
||||
assert_eq!(XMemMapPhysicalPages(a, 1, std::ptr::null()), a);
|
||||
assert_eq!(XMemFreePhysicalPages(2, pages.as_ptr()), 1);
|
||||
}
|
||||
|
||||
/// `n` pages of one new allocation.
|
||||
fn allocate(n: usize) -> Vec<usize> {
|
||||
let (mut pages, mut given) = (vec![0; n], n);
|
||||
|
||||
@@ -154,16 +154,23 @@ extern "system" fn get_is_guest(_: This, _: Handle, out: *mut bool) -> HRESULT {
|
||||
extern "system" fn get_state(_: This, _: Handle, out: *mut u32) -> HRESULT {
|
||||
put(out, 0)
|
||||
}
|
||||
/// The same name for every component (classic, modern, suffix, unique).
|
||||
/// The user's gamertag as the component asked for (`XUserGamertagComponent`):
|
||||
/// it has no suffix, so the modern suffix is empty and every other component
|
||||
/// (classic, modern, unique modern) is the name itself.
|
||||
extern "system" fn get_gamertag(
|
||||
_: This,
|
||||
_: Handle,
|
||||
_component: u32,
|
||||
component: u32,
|
||||
size: usize,
|
||||
buffer: *mut u8,
|
||||
used: *mut usize,
|
||||
) -> HRESULT {
|
||||
put_string(GAMERTAG, size, buffer, used)
|
||||
const MODERN_SUFFIX: u32 = 2;
|
||||
let text = match component {
|
||||
MODERN_SUFFIX => "",
|
||||
_ => GAMERTAG,
|
||||
};
|
||||
put_string(text, size, buffer, used)
|
||||
}
|
||||
/// Granted; deny reason 0 (none).
|
||||
extern "system" fn check_privilege(
|
||||
@@ -322,6 +329,25 @@ mod tests {
|
||||
use crate::modules::xasync::E_NOT_SUFFICIENT_BUFFER;
|
||||
use crate::modules::xgameruntime::method as slot;
|
||||
|
||||
#[test]
|
||||
fn a_gamertag_without_a_suffix_has_an_empty_modern_suffix() {
|
||||
type Gamertag =
|
||||
extern "system" fn(This, Handle, u32, usize, *mut u8, *mut usize) -> HRESULT;
|
||||
let this: This = &OBJECT;
|
||||
let user = std::ptr::null();
|
||||
// Classic, modern, modern suffix, unique modern; through both slots.
|
||||
let expected: [&[u8]; 4] = [b"Player\0", b"Player\0", b"\0", b"Player\0"];
|
||||
for (object, at) in [(&GAMERTAG_OBJECT, 0x18), (&OBJECT, 0x78)] {
|
||||
let get = slot::<Gamertag>(object, at);
|
||||
for (component, expected) in (0..).zip(expected) {
|
||||
let (mut name, mut used) = ([0xff_u8; 16], 0);
|
||||
let hr = get(this, user, component, 16, name.as_mut_ptr(), &mut used);
|
||||
assert_eq!(hr, S_OK);
|
||||
assert_eq!(&name[..used], expected, "component {component}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_adds_the_user_and_reads_its_id() {
|
||||
type Add = extern "system" fn(This, u32, *mut AsyncBlock) -> HRESULT;
|
||||
|
||||
@@ -379,6 +379,22 @@ pub unsafe fn report_unhandled(info: *const EXCEPTION_POINTERS) {
|
||||
unsafe { report("unhandled exception", info, true) };
|
||||
}
|
||||
|
||||
/// The bytes at `at` as hex, as many as the longest x86 instruction (15),
|
||||
/// but none past the end of `at`'s page: the next page may not be mapped.
|
||||
/// For an instruction the CPU refused, they name it (`0f 01 fd` is
|
||||
/// `rdpru`), which the address alone does not.
|
||||
///
|
||||
/// # Safety
|
||||
/// `at`'s page is readable.
|
||||
unsafe fn instruction_bytes(at: usize) -> String {
|
||||
let n = (0x1000 - (at & 0xfff)).min(15);
|
||||
// SAFETY: `n` bytes from `at` stay inside its page, which the caller
|
||||
// says is readable.
|
||||
let bytes = unsafe { std::slice::from_raw_parts(at as *const u8, n) };
|
||||
let hex: Vec<_> = bytes.iter().map(|b| format!("{b:02x}")).collect();
|
||||
hex.join(" ")
|
||||
}
|
||||
|
||||
/// MSVC's code for a C++ `throw`, and its magic first parameter.
|
||||
const CPP_EXCEPTION: i32 = 0xE06D_7363_u32 as i32;
|
||||
const CPP_MAGIC: usize = 0x1993_0520;
|
||||
@@ -436,10 +452,13 @@ unsafe fn report(what: &str, info: *const EXCEPTION_POINTERS, to_file: bool) {
|
||||
1 => "write",
|
||||
_ => "execute",
|
||||
};
|
||||
format!(" ({kind} {:#x})", p[1])
|
||||
format!(" ({kind} {:#x}: {})", p[1], memory_at(p[1]))
|
||||
} else if code == CPP_EXCEPTION && record.NumberParameters >= 4 && p[0] == CPP_MAGIC {
|
||||
// SAFETY: a live MSVC throw.
|
||||
format!(" (C++ {} thrown)", unsafe { thrown(&p) })
|
||||
} else if code == EXCEPTION_ILLEGAL_INSTRUCTION || code == EXCEPTION_PRIV_INSTRUCTION {
|
||||
// SAFETY: the CPU refused the instruction at `at`, so it fetched it.
|
||||
format!(" (code {})", unsafe { instruction_bytes(at) })
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
@@ -512,10 +531,19 @@ fn unwind(context: CONTEXT) -> Vec<u64> {
|
||||
frames
|
||||
}
|
||||
|
||||
/// A `CONTEXT` at the 16-byte alignment the unwind and capture functions need.
|
||||
#[repr(C, align(16))]
|
||||
pub(crate) struct Aligned16(pub(crate) CONTEXT);
|
||||
|
||||
/// [`unwind`] for any thread of the process, its stack being `low..high`;
|
||||
/// pushes no more than `MAX_FRAMES`, so it does not allocate when `frames`
|
||||
/// has that capacity (another thread may be suspended holding the heap).
|
||||
pub(crate) fn unwind_into(mut context: CONTEXT, low: usize, high: usize, frames: &mut Vec<u64>) {
|
||||
pub(crate) fn unwind_into(context: CONTEXT, low: usize, high: usize, frames: &mut Vec<u64>) {
|
||||
// `RtlVirtualUnwind` writes the context with 16-byte aligned stores, and
|
||||
// windows-sys declares `CONTEXT` without that alignment: a by-value copy on
|
||||
// the stack can land 8 bytes off and fault (seen in a debug build).
|
||||
let mut aligned = Aligned16(context);
|
||||
let context = &mut aligned.0;
|
||||
frames.push(context.Rip);
|
||||
while frames.len() < MAX_FRAMES {
|
||||
// Stop where reading the stack would fault inside this handler.
|
||||
@@ -539,7 +567,7 @@ pub(crate) fn unwind_into(mut context: CONTEXT, low: usize, high: usize, frames:
|
||||
image,
|
||||
context.Rip,
|
||||
entry,
|
||||
&mut context,
|
||||
context,
|
||||
&mut data,
|
||||
&mut frame,
|
||||
null_mut(),
|
||||
@@ -579,6 +607,48 @@ fn module_of(address: usize) -> Option<String> {
|
||||
Some(format!("{name}+{:#x}", address - module as usize))
|
||||
}
|
||||
|
||||
/// What is at `address`, for an access violation there: nothing, memory
|
||||
/// reserved but never committed, a guard page, or the protection the access
|
||||
/// broke (with the module, for an image's pages). Each points at a different
|
||||
/// cause: a wild pointer, an allocation whose commit failed, a stack
|
||||
/// overrun, a write to code or constants.
|
||||
fn memory_at(address: usize) -> String {
|
||||
use windows_sys::Win32::System::Memory::{
|
||||
MEM_FREE, MEM_IMAGE, MEM_RESERVE, MEMORY_BASIC_INFORMATION, PAGE_EXECUTE,
|
||||
PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_EXECUTE_WRITECOPY, PAGE_GUARD,
|
||||
PAGE_NOACCESS, PAGE_READONLY, PAGE_READWRITE, PAGE_WRITECOPY, VirtualQuery,
|
||||
};
|
||||
// SAFETY: a zeroed MEMORY_BASIC_INFORMATION is valid.
|
||||
let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
|
||||
// SAFETY: reads the address space's bookkeeping, not `address` itself.
|
||||
let n = unsafe { VirtualQuery(address as *const _, &mut info, size_of_val(&info)) };
|
||||
if n == 0 {
|
||||
// Above the process's address space: Windows reports a
|
||||
// non-canonical address as all ones.
|
||||
return "outside the address space".into();
|
||||
}
|
||||
let protect = match info.State {
|
||||
MEM_FREE => return "nothing mapped there".into(),
|
||||
MEM_RESERVE => return "reserved, never committed".into(),
|
||||
_ if info.Protect & PAGE_GUARD != 0 => return "a guard page".into(),
|
||||
_ => match info.Protect & 0xff {
|
||||
PAGE_NOACCESS => "no access".into(),
|
||||
PAGE_READONLY => "read-only".into(),
|
||||
PAGE_READWRITE => "read-write".into(),
|
||||
PAGE_WRITECOPY => "copy-on-write".into(),
|
||||
PAGE_EXECUTE => "execute-only".into(),
|
||||
PAGE_EXECUTE_READ => "read-execute".into(),
|
||||
PAGE_EXECUTE_READWRITE => "read-write-execute".into(),
|
||||
PAGE_EXECUTE_WRITECOPY => "copy-on-write, executable".into(),
|
||||
_ => format!("protection {:#x}", info.Protect),
|
||||
},
|
||||
};
|
||||
match module_of(address) {
|
||||
Some(module) if info.Type == MEM_IMAGE => format!("{protect}, in {module}"),
|
||||
_ => protect,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -591,11 +661,12 @@ mod tests {
|
||||
fn unwinds_like_the_system_walk() {
|
||||
// SAFETY: zeroed CONTEXT is valid; both calls write our buffers.
|
||||
let (frames, walked) = unsafe {
|
||||
let mut context: CONTEXT = std::mem::zeroed();
|
||||
RtlCaptureContext(&mut context);
|
||||
// `RtlCaptureContext` wants it 16-byte aligned too.
|
||||
let mut context = Aligned16(std::mem::zeroed());
|
||||
RtlCaptureContext(&mut context.0);
|
||||
let mut walked = [null_mut(); 8];
|
||||
let n = RtlCaptureStackBackTrace(0, 8, walked.as_mut_ptr(), null_mut());
|
||||
(unwind(context), walked[..usize::from(n)].to_vec())
|
||||
(unwind(context.0), walked[..usize::from(n)].to_vec())
|
||||
};
|
||||
// Frame 0 differs (two call sites in this function); callers agree.
|
||||
assert!(walked.len() >= 4, "{walked:?}");
|
||||
@@ -607,6 +678,41 @@ mod tests {
|
||||
assert_eq!(ours, system);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memory_at_names_what_an_access_hit() {
|
||||
use windows_sys::Win32::System::Memory::{
|
||||
MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_GUARD, PAGE_NOACCESS, PAGE_READONLY,
|
||||
PAGE_READWRITE, VirtualAlloc, VirtualFree,
|
||||
};
|
||||
// SAFETY: reserves four pages of ours and commits three of them;
|
||||
// nothing reads or writes them.
|
||||
let base = unsafe {
|
||||
let base = VirtualAlloc(std::ptr::null(), 0x4000, MEM_RESERVE, PAGE_NOACCESS);
|
||||
assert!(!base.is_null());
|
||||
let page = |i: usize, protect| {
|
||||
let at = base.cast::<u8>().add(i * 0x1000).cast();
|
||||
assert!(!VirtualAlloc(at, 0x1000, MEM_COMMIT, protect).is_null());
|
||||
};
|
||||
page(1, PAGE_READONLY);
|
||||
page(2, PAGE_READWRITE | PAGE_GUARD);
|
||||
page(3, PAGE_NOACCESS);
|
||||
base as usize
|
||||
};
|
||||
assert_eq!(memory_at(base + 8), "reserved, never committed");
|
||||
assert_eq!(memory_at(base + 0x1008), "read-only");
|
||||
assert_eq!(memory_at(base + 0x2008), "a guard page");
|
||||
assert_eq!(memory_at(base + 0x3008), "no access");
|
||||
// SAFETY: releases the reservation made above.
|
||||
unsafe { VirtualFree(base as *mut _, 0, MEM_RELEASE) };
|
||||
assert_eq!(memory_at(base + 8), "nothing mapped there");
|
||||
assert_eq!(memory_at(0), "nothing mapped there");
|
||||
assert_eq!(memory_at(usize::MAX), "outside the address space");
|
||||
// This test's own code: an image page, named by its module.
|
||||
let code = memory_at(memory_at_names_what_an_access_hit as *const () as usize);
|
||||
let named = code.starts_with("read-execute, in victory_loader-");
|
||||
assert!(named, "{code}");
|
||||
}
|
||||
|
||||
/// On an Intel CPU, the real instructions go through the vectored
|
||||
/// handler. On an AMD CPU they run natively, and the tests below test
|
||||
/// the emulation.
|
||||
@@ -848,4 +954,38 @@ mod tests {
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instruction_bytes_stop_at_the_end_of_their_page() {
|
||||
use windows_sys::Win32::System::Memory::{
|
||||
MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE, VirtualAlloc,
|
||||
VirtualFree, VirtualProtect,
|
||||
};
|
||||
// rdpru, then the next instruction (mov rcx, rax) and padding.
|
||||
let mut code = [0x90_u8; 16];
|
||||
code[..6].copy_from_slice(&[0x0f, 0x01, 0xfd, 0x48, 0x89, 0xc1]);
|
||||
// SAFETY: two fresh pages of ours, the second made unreadable, so a
|
||||
// read past the end of the first faults.
|
||||
unsafe {
|
||||
let page = VirtualAlloc(
|
||||
std::ptr::null(),
|
||||
0x2000,
|
||||
MEM_RESERVE | MEM_COMMIT,
|
||||
PAGE_READWRITE,
|
||||
)
|
||||
.cast::<u8>();
|
||||
assert!(!page.is_null());
|
||||
let mut old = 0;
|
||||
let guard = page.add(0x1000).cast();
|
||||
assert_ne!(VirtualProtect(guard, 0x1000, PAGE_NOACCESS, &mut old), 0);
|
||||
page.copy_from_nonoverlapping(code.as_ptr(), code.len());
|
||||
let whole = "0f 01 fd 48 89 c1 90 90 90 90 90 90 90 90 90";
|
||||
assert_eq!(instruction_bytes(page as usize), whole);
|
||||
// The page's last three bytes: rdpru, and nothing read after it.
|
||||
let end = page.add(0x1000 - 3);
|
||||
end.copy_from_nonoverlapping(code.as_ptr(), 3);
|
||||
assert_eq!(instruction_bytes(end as usize), "0f 01 fd");
|
||||
VirtualFree(page.cast(), 0, MEM_RELEASE);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -62,10 +62,11 @@ extern "system" fn unimplemented_import(site: &'static ImportSite) -> u64 {
|
||||
}
|
||||
UnimplementedPolicy::Trap => {
|
||||
tracing::error!(dll = %site.dll, symbol = %site.symbol, "unimplemented import called");
|
||||
eprintln!(
|
||||
"VIctory: unimplemented import {}!{} called",
|
||||
site.dll, site.symbol
|
||||
);
|
||||
// Into the crash log too: `abort` ends the process without
|
||||
// running the handlers that write it.
|
||||
let (dll, symbol) = (&site.dll, &site.symbol);
|
||||
let text = format!("VIctory: unimplemented import {dll}!{symbol} called");
|
||||
crate::log_crash(&text);
|
||||
// SAFETY: plain Win32 calls without preconditions.
|
||||
unsafe {
|
||||
if IsDebuggerPresent() != 0 {
|
||||
@@ -147,3 +148,40 @@ impl ThunkBlock {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// In a child process of the next test: calls an unimplemented import
|
||||
/// that traps, with the crash log where `VICTORY_TRAP_LOG` says.
|
||||
#[test]
|
||||
fn trap_child() {
|
||||
let Some(log) = std::env::var_os("VICTORY_TRAP_LOG") else {
|
||||
return;
|
||||
};
|
||||
crate::log_crashes_to(log.into());
|
||||
let site = Box::leak(Box::new(ImportSite {
|
||||
dll: "probe.dll".into(),
|
||||
symbol: "Missing".into(),
|
||||
policy: UnimplementedPolicy::Trap,
|
||||
calls: AtomicU64::new(0),
|
||||
}));
|
||||
unimplemented_import(site);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_trapped_import_is_in_the_crash_log() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let log = dir.path().join("crashes.log");
|
||||
let out = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", "thunks::tests::trap_child", "--nocapture"])
|
||||
.env("VICTORY_TRAP_LOG", &log)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!out.status.success(), "the trap ends the process");
|
||||
let text = std::fs::read_to_string(&log).unwrap_or_default();
|
||||
let named = text.contains("VIctory: unimplemented import probe.dll!Missing called");
|
||||
assert!(named, "crash log: {text:?}");
|
||||
}
|
||||
}
|
||||
@@ -152,8 +152,8 @@ fn map_dll(
|
||||
return Ok(());
|
||||
}
|
||||
let original = std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?;
|
||||
let image = load(&prepare(&original)?, dirs.1)
|
||||
.with_context(|| format!("loading {}", path.display()))?;
|
||||
let prepared = prepare(&original).with_context(|| format!("preparing {}", path.display()))?;
|
||||
let image = load(&prepared, dirs.1).with_context(|| format!("loading {}", path.display()))?;
|
||||
map_imports(&image.info, dirs, wanted, seen, loaded)?;
|
||||
loaded.push((name, image));
|
||||
Ok(())
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
//! A title DLL that cannot be loaded is named in the error.
|
||||
#![cfg(windows)]
|
||||
|
||||
#[test]
|
||||
fn a_title_dll_that_does_not_prepare_is_named() {
|
||||
let title = tempfile::tempdir().unwrap();
|
||||
let cache = tempfile::tempdir().unwrap();
|
||||
std::fs::write(title.path().join("broken.dll"), b"MZ not a PE").unwrap();
|
||||
let wanted = |_: &str| true;
|
||||
let loaded = victory_loader::load_title_dll("broken.dll", title.path(), cache.path(), &wanted);
|
||||
let Err(error) = loaded else {
|
||||
panic!("a DLL that is not a PE loaded");
|
||||
};
|
||||
let text = format!("{error:#}");
|
||||
assert!(text.contains("broken.dll"), "{text}");
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
@@ -58,8 +59,17 @@ impl Cache {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
// Write-then-rename so readers never see partial output.
|
||||
let tmp = tempfile_in(dir);
|
||||
std::fs::write(&tmp, &output)?;
|
||||
std::fs::rename(&tmp, &path)?;
|
||||
let mut file = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&tmp)?;
|
||||
let written = file.write_all(&output);
|
||||
drop(file);
|
||||
let published = written.and_then(|()| std::fs::rename(&tmp, &path));
|
||||
if published.is_err() {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
}
|
||||
published?;
|
||||
Ok(path)
|
||||
}
|
||||
}
|
||||
@@ -109,6 +119,25 @@ mod tests {
|
||||
assert_eq!(conv.runs.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_publication_removes_the_staging_file() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let cache = Cache::open(tmp.path().join("cache")).unwrap();
|
||||
let conv = Upper {
|
||||
version: 1,
|
||||
runs: AtomicUsize::new(0),
|
||||
};
|
||||
let path = cache.path_for(&CacheKey::new(&conv, b"abc"));
|
||||
std::fs::create_dir_all(&path).unwrap();
|
||||
|
||||
assert!(cache.get_or_convert(&conv, b"abc").is_err());
|
||||
assert!(path.is_dir());
|
||||
assert_eq!(
|
||||
std::fs::read_dir(path.parent().unwrap()).unwrap().count(),
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_bump_invalidates() {
|
||||
let v1 = Upper {
|
||||
|
||||
@@ -473,6 +473,37 @@ impl Module {
|
||||
}
|
||||
|
||||
/// The module as bitcode.
|
||||
/// Which instructions are written: every body instruction, the branch
|
||||
/// conditions, and whatever they read, transitively (a phi nothing reads
|
||||
/// is dropped). A worklist visits each instruction once, so a long chain
|
||||
/// of merges costs one pass, not one pass per merge.
|
||||
fn live(&self) -> Vec<bool> {
|
||||
let mut live = vec![false; self.insts.len()];
|
||||
let mut work: Vec<u32> = Vec::new();
|
||||
let mark = |live: &mut [bool], work: &mut Vec<u32>, v: V| {
|
||||
if let V::Inst(i) = v
|
||||
&& !live[i as usize]
|
||||
{
|
||||
live[i as usize] = true;
|
||||
work.push(i);
|
||||
}
|
||||
};
|
||||
for b in &self.blocks {
|
||||
for &i in &b.body {
|
||||
mark(&mut live, &mut work, V::Inst(i));
|
||||
}
|
||||
if let Some(Term::CondBr(c, ..)) = b.term {
|
||||
mark(&mut live, &mut work, c);
|
||||
}
|
||||
}
|
||||
while let Some(i) = work.pop() {
|
||||
for_each_operand(&self.insts[i as usize].op, |v| {
|
||||
mark(&mut live, &mut work, v)
|
||||
});
|
||||
}
|
||||
live
|
||||
}
|
||||
|
||||
pub fn write(&self) -> Vec<u8> {
|
||||
let mut w = Writer::default();
|
||||
w.bytes(b"BC\xC0\xDE");
|
||||
@@ -606,56 +637,12 @@ impl Module {
|
||||
w.exit();
|
||||
|
||||
// Phis nothing reads are left out (one register per phi makes many).
|
||||
let mut live = vec![false; self.insts.len()];
|
||||
let mark = |live: &mut Vec<bool>, v: V| {
|
||||
if let V::Inst(i) = v
|
||||
&& !live[i as usize]
|
||||
{
|
||||
live[i as usize] = true;
|
||||
return true;
|
||||
}
|
||||
false
|
||||
};
|
||||
let operands = |op: &Op| -> Vec<V> {
|
||||
match op {
|
||||
Op::Bin(_, a, b) | Op::Cmp(_, a, b) | Op::Store(a, b) | Op::AtomicRmw(_, a, b) => {
|
||||
vec![*a, *b]
|
||||
}
|
||||
Op::Cast(_, v) | Op::Extract(v, _) | Op::Load(v) => vec![*v],
|
||||
Op::Select(a, b, c) | Op::CmpXchg(a, b, c) => vec![*a, *b, *c],
|
||||
Op::Call(_, args) => args.clone(),
|
||||
Op::Phi(inc) => inc.iter().map(|x| x.0).collect(),
|
||||
Op::Gep(_, p, idx) => std::iter::once(*p).chain(idx.iter().copied()).collect(),
|
||||
}
|
||||
};
|
||||
for b in &self.blocks {
|
||||
for &i in &b.body {
|
||||
live[i as usize] = true;
|
||||
}
|
||||
if let Some(Term::CondBr(c, ..)) = b.term {
|
||||
mark(&mut live, c);
|
||||
}
|
||||
}
|
||||
let mut changed = true;
|
||||
while changed {
|
||||
changed = false;
|
||||
for (i, inst) in self.insts.iter().enumerate() {
|
||||
if live[i] {
|
||||
for v in operands(&inst.op) {
|
||||
changed |= mark(&mut live, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let live = self.live();
|
||||
|
||||
// Blocks are laid out in reverse postorder, so every block follows
|
||||
// its forward predecessors (drivers take a branch to an earlier
|
||||
// block for a loop's back edge).
|
||||
let succs = |b: usize| match self.blocks[b].term {
|
||||
Some(Term::Br(t)) => vec![t],
|
||||
Some(Term::CondBr(_, t, f)) => vec![t, f],
|
||||
_ => vec![],
|
||||
};
|
||||
let succs = |b: usize| successors(self.blocks[b].term);
|
||||
let mut seen = vec![false; self.blocks.len()];
|
||||
let mut post = Vec::new();
|
||||
let mut stack = vec![(0usize, 0usize)];
|
||||
@@ -685,7 +672,7 @@ impl Module {
|
||||
// DXC's loops; the AMD driver hangs on divergent loops otherwise.
|
||||
let mut preds = vec![Vec::new(); self.blocks.len()];
|
||||
for &b in &post {
|
||||
for s in succs(b) {
|
||||
for &s in succs(b).iter() {
|
||||
preds[s].push(b);
|
||||
}
|
||||
}
|
||||
@@ -795,6 +782,8 @@ impl Module {
|
||||
w.enter(FUNCTION_BLOCK, 4);
|
||||
w.record(1, &[layout.len() as u64]);
|
||||
let mut inst_id = base;
|
||||
// The operands of variable-length records, reused across them.
|
||||
let mut r: Vec<u64> = Vec::new();
|
||||
for b in layout.iter().map(|&b| &self.blocks[b]) {
|
||||
for &i in b.phis.iter().filter(|&&i| live[i as usize]).chain(&b.body) {
|
||||
let inst = &self.insts[i as usize];
|
||||
@@ -810,13 +799,15 @@ impl Module {
|
||||
Op::Select(c, t, f) => w.record(29, &[rel(*t), rel(*f), rel(*c)]),
|
||||
Op::Extract(a, idx) => w.record(26, &[rel(*a), u64::from(*idx)]),
|
||||
Op::Call(f, args) => {
|
||||
let mut r = vec![0, 1 << 15, u64::from(self.funcs[*f as usize].ty.0)];
|
||||
r.clear();
|
||||
r.extend([0, 1 << 15, u64::from(self.funcs[*f as usize].ty.0)]);
|
||||
r.push(rel(V::Func(*f)));
|
||||
r.extend(args.iter().map(|&a| rel(a)));
|
||||
w.record(34, &r);
|
||||
}
|
||||
Op::Phi(incoming) => {
|
||||
let mut r = vec![u64::from(inst.ty.0)];
|
||||
r.clear();
|
||||
r.push(u64::from(inst.ty.0));
|
||||
for &(v, b) in incoming {
|
||||
r.push(signed(i64::from(inst_id) - i64::from(abs(v))));
|
||||
r.push(from(b));
|
||||
@@ -824,7 +815,8 @@ impl Module {
|
||||
w.record(16, &r);
|
||||
}
|
||||
Op::Gep(ty, p, idx) => {
|
||||
let mut r = vec![0, u64::from(ty.0), rel(*p)];
|
||||
r.clear();
|
||||
r.extend([0, u64::from(ty.0), rel(*p)]);
|
||||
r.extend(idx.iter().map(|&i| rel(i)));
|
||||
w.record(43, &r);
|
||||
}
|
||||
@@ -868,6 +860,49 @@ const VALUE_SYMTAB_BLOCK: u64 = 14;
|
||||
const METADATA_BLOCK: u64 = 15;
|
||||
const TYPE_BLOCK: u64 = 17;
|
||||
|
||||
/// Calls `f` with every value `op` reads, in operand order.
|
||||
fn for_each_operand(op: &Op, mut f: impl FnMut(V)) {
|
||||
match op {
|
||||
Op::Bin(_, a, b) | Op::Cmp(_, a, b) | Op::Store(a, b) | Op::AtomicRmw(_, a, b) => {
|
||||
f(*a);
|
||||
f(*b);
|
||||
}
|
||||
Op::Cast(_, v) | Op::Extract(v, _) | Op::Load(v) => f(*v),
|
||||
Op::Select(a, b, c) | Op::CmpXchg(a, b, c) => {
|
||||
f(*a);
|
||||
f(*b);
|
||||
f(*c);
|
||||
}
|
||||
Op::Call(_, args) => args.iter().copied().for_each(f),
|
||||
Op::Phi(inc) => inc.iter().for_each(|x| f(x.0)),
|
||||
Op::Gep(_, p, idx) => {
|
||||
f(*p);
|
||||
idx.iter().copied().for_each(f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A block's successors (at most two), without allocating.
|
||||
struct Succs {
|
||||
to: [usize; 2],
|
||||
len: usize,
|
||||
}
|
||||
|
||||
impl std::ops::Deref for Succs {
|
||||
type Target = [usize];
|
||||
fn deref(&self) -> &[usize] {
|
||||
&self.to[..self.len]
|
||||
}
|
||||
}
|
||||
|
||||
fn successors(term: Option<Term>) -> Succs {
|
||||
match term {
|
||||
Some(Term::Br(t)) => Succs { to: [t, 0], len: 1 },
|
||||
Some(Term::CondBr(_, t, f)) => Succs { to: [t, f], len: 2 },
|
||||
_ => Succs { to: [0, 0], len: 0 },
|
||||
}
|
||||
}
|
||||
|
||||
fn chars(s: &str) -> Vec<u64> {
|
||||
s.bytes().map(u64::from).collect()
|
||||
}
|
||||
@@ -983,4 +1018,177 @@ mod tests {
|
||||
assert_eq!(signed(-3), 7);
|
||||
assert_eq!(signed(2), 4);
|
||||
}
|
||||
|
||||
/// A structured shader's shape: `stages` if/else diamonds in a row, each
|
||||
/// merge with one phi per register (as the lowering makes them), then a
|
||||
/// loop, and a tail that reads only the first `read` registers.
|
||||
fn synthetic(regs: usize, stages: usize, read: usize) -> Module {
|
||||
let mut m = Module::default();
|
||||
let i32t = m.int(32);
|
||||
let void = m.void();
|
||||
let fty = m.func_ty(i32t, vec![i32t, i32t]);
|
||||
let f = m.function("dx.op.synthetic", fty, Some(Attr::ReadNone), false);
|
||||
let main_ty = m.func_ty(void, vec![]);
|
||||
m.function("main", main_ty, None, true);
|
||||
let mut b = m.new_block();
|
||||
let mut cur: Vec<V> = (0..regs).map(|r| m.i32(r as u32)).collect();
|
||||
for s in 0..stages {
|
||||
let c = m.cmp(b, pred::EQ, cur[0], cur[s % regs]);
|
||||
let (t, e, j) = (m.new_block(), m.new_block(), m.new_block());
|
||||
m.terminate(b, Term::CondBr(c, t, e));
|
||||
let x = m.call(t, f, vec![cur[s % regs], cur[(s + 1) % regs]]);
|
||||
m.terminate(t, Term::Br(j));
|
||||
m.terminate(e, Term::Br(j));
|
||||
cur = (0..regs)
|
||||
.map(|r| {
|
||||
let p = m.phi(j, i32t);
|
||||
let tv = if r == s % regs { x } else { cur[r] };
|
||||
m.set_phi(p, vec![(tv, t), (cur[r], e)]);
|
||||
p
|
||||
})
|
||||
.collect();
|
||||
b = j;
|
||||
}
|
||||
// A loop: header phis fed back from an empty latch (which is folded).
|
||||
let (head, body, latch, exit) =
|
||||
(m.new_block(), m.new_block(), m.new_block(), m.new_block());
|
||||
m.terminate(b, Term::Br(head));
|
||||
let phis: Vec<V> = (0..regs).map(|_| m.phi(head, i32t)).collect();
|
||||
let one = m.i32(1);
|
||||
let stepped: Vec<V> = phis
|
||||
.iter()
|
||||
.map(|&p| m.bin(body, Bin::Add, p, one))
|
||||
.collect();
|
||||
let c = m.cmp(body, pred::IULT, stepped[0], cur[0]);
|
||||
m.terminate(head, Term::Br(body));
|
||||
m.terminate(body, Term::CondBr(c, latch, exit));
|
||||
m.terminate(latch, Term::Br(head));
|
||||
for r in 0..regs {
|
||||
m.set_phi(phis[r], vec![(cur[r], b), (stepped[r], latch)]);
|
||||
}
|
||||
let mut acc = stepped[0];
|
||||
for &v in &stepped[1..read.max(1)] {
|
||||
acc = m.bin(exit, Bin::Add, acc, v);
|
||||
}
|
||||
let _ = m.call(exit, f, vec![acc, cur[0]]);
|
||||
m.terminate(exit, Term::Ret);
|
||||
m
|
||||
}
|
||||
|
||||
/// FNV-1a, to pin a written module's exact bytes.
|
||||
fn fnv(bytes: &[u8]) -> u64 {
|
||||
bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, &b| {
|
||||
(h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)
|
||||
})
|
||||
}
|
||||
|
||||
/// Liveness as `write` computed it before the worklist: whole passes over
|
||||
/// the instructions until one changes nothing.
|
||||
fn live_by_passes(m: &Module) -> Vec<bool> {
|
||||
let mut live = vec![false; m.insts.len()];
|
||||
for b in &m.blocks {
|
||||
for &i in &b.body {
|
||||
live[i as usize] = true;
|
||||
}
|
||||
if let Some(Term::CondBr(V::Inst(c), ..)) = b.term {
|
||||
live[c as usize] = true;
|
||||
}
|
||||
}
|
||||
let mut changed = true;
|
||||
while changed {
|
||||
changed = false;
|
||||
for (i, inst) in m.insts.iter().enumerate() {
|
||||
if live[i] {
|
||||
for_each_operand(&inst.op, |v| {
|
||||
if let V::Inst(j) = v
|
||||
&& !live[j as usize]
|
||||
{
|
||||
live[j as usize] = true;
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
live
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worklist_liveness_matches_passes() {
|
||||
for (regs, stages, read) in [(1, 0, 1), (1, 1, 1), (4, 3, 1), (8, 17, 3), (16, 40, 16)] {
|
||||
let m = synthetic(regs, stages, read);
|
||||
let live = m.live();
|
||||
assert_eq!(live, live_by_passes(&m), "{regs} regs x {stages} stages");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unread_phis_are_dropped() {
|
||||
let mut m = Module::default();
|
||||
let i32t = m.int(32);
|
||||
let (entry, join) = (m.new_block(), m.new_block());
|
||||
let (a, b) = (m.i32(1), m.i32(2));
|
||||
m.terminate(entry, Term::Br(join));
|
||||
let read = m.phi(join, i32t);
|
||||
let unread = m.phi(join, i32t);
|
||||
// A cycle of phis that only feed each other stays dead.
|
||||
let cyc_a = m.phi(join, i32t);
|
||||
let cyc_b = m.phi(join, i32t);
|
||||
m.set_phi(read, vec![(a, entry)]);
|
||||
m.set_phi(unread, vec![(b, entry)]);
|
||||
m.set_phi(cyc_a, vec![(cyc_b, entry)]);
|
||||
m.set_phi(cyc_b, vec![(cyc_a, entry)]);
|
||||
let sum = m.bin(join, Bin::Add, read, b);
|
||||
m.terminate(join, Term::Ret);
|
||||
let ids = |v: V| match v {
|
||||
V::Inst(i) => i as usize,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let live = m.live();
|
||||
assert!(live[ids(read)] && live[ids(sum)]);
|
||||
assert!(!live[ids(unread)] && !live[ids(cyc_a)] && !live[ids(cyc_b)]);
|
||||
assert_eq!(live, live_by_passes(&m));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successors_of_each_terminator() {
|
||||
assert!(successors(None).is_empty());
|
||||
assert!(successors(Some(Term::Ret)).is_empty());
|
||||
assert_eq!(&*successors(Some(Term::Br(7))), &[7]);
|
||||
assert_eq!(&*successors(Some(Term::CondBr(V::Const(0), 3, 5))), &[3, 5]);
|
||||
}
|
||||
|
||||
/// The written bytes are pinned to what the writer produced before the
|
||||
/// worklist and the reused record buffers.
|
||||
#[test]
|
||||
fn written_bytes_unchanged() {
|
||||
for ((regs, stages, read), len, hash) in [
|
||||
((64, 64, 64), 38_916, 0x9586_730c_f953_4a45),
|
||||
((128, 256, 32), 295_952, 0x89e5_de2d_64f0_8785),
|
||||
] {
|
||||
let bytes = synthetic(regs, stages, read).write();
|
||||
assert_eq!((bytes.len(), fnv(&bytes)), (len, hash), "{regs}x{stages}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "benchmark: cargo test --release -p victory-shader bitcode -- --ignored --nocapture"]
|
||||
fn bench_write() {
|
||||
for (regs, stages, read) in [(64, 64, 64), (128, 256, 32), (256, 512, 256)] {
|
||||
let m = synthetic(regs, stages, read);
|
||||
let bytes = m.write();
|
||||
let runs = 5;
|
||||
let t = std::time::Instant::now();
|
||||
for _ in 0..runs {
|
||||
std::hint::black_box(m.write());
|
||||
}
|
||||
let per = t.elapsed() / runs;
|
||||
println!(
|
||||
"write {regs} regs x {stages} stages ({} insts): {per:?}, {} bytes, fnv {:#018x}",
|
||||
m.insts.len(),
|
||||
bytes.len(),
|
||||
fnv(&bytes)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -107,33 +107,46 @@ fn buffer_format(format: u8) -> Option<(&'static [u32], Numeric)> {
|
||||
const NORM: &[Numeric] = &[Unorm, Snorm, Uscaled, Sscaled, Uint, Sint];
|
||||
const ALL: &[Numeric] = &[Unorm, Snorm, Uscaled, Sscaled, Uint, Sint, Float];
|
||||
const WIDE: &[Numeric] = &[Uint, Sint, Float];
|
||||
// `None`: a family not decoded (packed floats, 10_10_10_2).
|
||||
const FAMILIES: [(Option<&[u32]>, &[Numeric]); 14] = [
|
||||
(Some(&[8]), NORM),
|
||||
(Some(&[16]), ALL),
|
||||
(Some(&[8, 8]), NORM),
|
||||
(Some(&[32]), WIDE),
|
||||
(Some(&[16, 16]), ALL),
|
||||
(None, ALL), // 10_11_11
|
||||
(None, ALL), // 11_11_10
|
||||
(None, NORM), // 10_10_10_2
|
||||
(Some(&[10, 10, 10, 2]), NORM), // 2_10_10_10
|
||||
(Some(&[8, 8, 8, 8]), NORM),
|
||||
(Some(&[32, 32]), WIDE),
|
||||
(Some(&[16, 16, 16, 16]), ALL),
|
||||
(Some(&[32, 32, 32]), WIDE),
|
||||
(Some(&[32, 32, 32, 32]), WIDE),
|
||||
// Numbers and order from LLVM's `UfmtGFX10` (`SIDefines.h`); the GFX10
|
||||
// buffer formats have no 5_9_9_9. Channel order from Mesa
|
||||
// (`ac_formats.c`): R11G11B10_FLOAT is 10_11_11, and 10_10_10_2 has
|
||||
// its 2-bit channel in the lowest bits.
|
||||
const FAMILIES: [(&[u32], &[Numeric]); 14] = [
|
||||
(&[8], NORM),
|
||||
(&[16], ALL),
|
||||
(&[8, 8], NORM),
|
||||
(&[32], WIDE),
|
||||
(&[16, 16], ALL),
|
||||
(&[11, 11, 10], ALL), // 10_11_11
|
||||
(&[10, 11, 11], ALL), // 11_11_10
|
||||
(&[2, 10, 10, 10], NORM), // 10_10_10_2
|
||||
(&[10, 10, 10, 2], NORM), // 2_10_10_10
|
||||
(&[8, 8, 8, 8], NORM),
|
||||
(&[32, 32], WIDE),
|
||||
(&[16, 16, 16, 16], ALL),
|
||||
(&[32, 32, 32], WIDE),
|
||||
(&[32, 32, 32, 32], WIDE),
|
||||
];
|
||||
let mut n = usize::from(format.checked_sub(1)?);
|
||||
for (bits, numerics) in FAMILIES {
|
||||
if n < numerics.len() {
|
||||
return Some((bits?, numerics[n]));
|
||||
return Some((bits, numerics[n]));
|
||||
}
|
||||
n -= numerics.len();
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// How far a float channel of `width` bits (16, or the unsigned 11- and
|
||||
/// 10-bit floats of the packed formats) shifts up to be a half:
|
||||
/// the small floats are a half's exponent (5 bits, biased 15) and the top
|
||||
/// of its mantissa, without the sign, so `legacyF16ToF32` widens them
|
||||
/// exactly, denormals, infinities and NaNs included.
|
||||
fn half_shift(width: u32) -> u32 {
|
||||
debug_assert!(matches!(width, 10 | 11 | 16), "{width}-bit float");
|
||||
if width == 16 { 0 } else { 15 - width }
|
||||
}
|
||||
|
||||
struct Lower<'a> {
|
||||
s: Shader,
|
||||
x: &'a Parts<'a>,
|
||||
@@ -2314,6 +2327,29 @@ impl<'a> Lower<'a> {
|
||||
_ => Ok(l.s.m.i32(0)),
|
||||
}
|
||||
};
|
||||
if let Some(op) = name.strip_prefix("s_bitcmp") {
|
||||
// SCC is whether bit src1 (mod 32, or mod 64 for the 64-bit form)
|
||||
// of src0 is clear (bitcmp0) or set (bitcmp1).
|
||||
let (bit, k31) = (src32(self, 1)?, self.s.m.i32(31));
|
||||
let idx = self.s.m.bin(c, Bin::And, bit, k31);
|
||||
let word = if op.ends_with("_b64") {
|
||||
let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?);
|
||||
let k32 = self.s.m.i32(32);
|
||||
let upper = self.s.m.bin(c, Bin::And, bit, k32);
|
||||
let z = self.s.m.i32(0);
|
||||
let upper = self.s.m.cmp(c, pred::NE, upper, z);
|
||||
self.s.m.select(c, upper, b, a)
|
||||
} else {
|
||||
src32(self, 0)?
|
||||
};
|
||||
let shifted = self.s.m.bin(c, Bin::LShr, word, idx);
|
||||
let one = self.s.m.i32(1);
|
||||
let tested = self.s.m.bin(c, Bin::And, shifted, one);
|
||||
let want = self.s.m.i32(u32::from(op.starts_with('1')));
|
||||
let r = self.s.m.cmp(c, pred::EQ, tested, want);
|
||||
self.set(scc, Val::Bit(r));
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(op) = name.strip_prefix("s_cmp_").filter(|o| o.ends_with("_u64")) {
|
||||
// eq and lg only: both dwords.
|
||||
let mut r = None;
|
||||
@@ -3051,11 +3087,10 @@ impl<'a> Lower<'a> {
|
||||
/// typed loads do (channels past the format's read 0, 0, 0, 1).
|
||||
// shortcut: the descriptor's channel swizzle is taken as the identity
|
||||
// (it is for raw views and the descriptors code builds), elements of 4
|
||||
// bytes or more as dword-aligned, and the packed float and 10_10_10_2
|
||||
// layouts are refused; decode them when a program needs them. Norm
|
||||
// formats divide, which the AMD driver does 1 ULP off the hardware's
|
||||
// correctly rounded conversion for some values; correct it with an
|
||||
// integer check if a title compares converted values exactly.
|
||||
// bytes or more as dword-aligned. Norm formats divide, which the AMD
|
||||
// driver does 1 ULP off the hardware's correctly rounded conversion for
|
||||
// some values; correct it with an integer check if a title compares
|
||||
// converted values exactly.
|
||||
fn format_load(&mut self, h: V, off: V, format: u8, channels: u32) -> Result<Vec<V>, Why> {
|
||||
let (bits, numeric) = buffer_format(format).ok_or("a buffer format")?;
|
||||
let c = self.cur;
|
||||
@@ -3142,9 +3177,16 @@ impl<'a> Lower<'a> {
|
||||
Numeric::Sint => signed(self),
|
||||
Numeric::Float if w == 32 => field,
|
||||
Numeric::Float => {
|
||||
let h = match half_shift(w) {
|
||||
0 => field,
|
||||
k => {
|
||||
let sh = self.s.m.i32(k);
|
||||
self.s.m.bin(c, Bin::Shl, field, sh)
|
||||
}
|
||||
};
|
||||
let f = self
|
||||
.s
|
||||
.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[field]);
|
||||
.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
|
||||
float(self, f)
|
||||
}
|
||||
};
|
||||
@@ -5098,28 +5140,50 @@ impl<'a> Lower<'a> {
|
||||
let (op, ty) = rest.rsplit_once('_').ok_or("a compare")?;
|
||||
let c = self.cur;
|
||||
let r = match ty {
|
||||
"f32" if op == "class" => {
|
||||
"f32" | "f16" if op == "class" => {
|
||||
// Bit k of src1 tests class k: signalling NaN, quiet NaN,
|
||||
// -inf, -normal, -denormal, -0, +0, +denormal, +normal, +inf.
|
||||
let x = self.fsrc(inst, 0)?;
|
||||
let x = self.as_int(x);
|
||||
let f16 = ty == "f16";
|
||||
let x = if f16 {
|
||||
let Fields::Valu(v) = &inst.fields else {
|
||||
unreachable!()
|
||||
};
|
||||
let mut h = self.half_src(inst, 0)?;
|
||||
if v.abs & 1 != 0 {
|
||||
let m = self.s.m.i32(0x7FFF);
|
||||
h = self.s.m.bin(c, Bin::And, h, m);
|
||||
}
|
||||
if v.neg & 1 != 0 {
|
||||
let s = self.s.m.i32(0x8000);
|
||||
h = self.s.m.bin(c, Bin::Xor, h, s);
|
||||
}
|
||||
h
|
||||
} else {
|
||||
let x = self.fsrc(inst, 0)?;
|
||||
self.as_int(x)
|
||||
};
|
||||
let mask = self.src(inst, 1)?;
|
||||
let k = |l: &mut Self, v: u32| l.s.m.i32(v);
|
||||
let (k23, k31, kff, mant, quiet) = (
|
||||
k(self, 23),
|
||||
k(self, 31),
|
||||
k(self, 0xFF),
|
||||
k(self, 0x7F_FFFF),
|
||||
k(self, 0x40_0000),
|
||||
let (exp_sh, sign_sh, exp_mask, mant_mask, quiet_bit) = if f16 {
|
||||
(10, 15, 0x1F, 0x03FF, 0x0200)
|
||||
} else {
|
||||
(23, 31, 0xFF, 0x7F_FFFF, 0x40_0000)
|
||||
};
|
||||
let (k_exp, k_sign, k_emax, mant, quiet) = (
|
||||
k(self, exp_sh),
|
||||
k(self, sign_sh),
|
||||
k(self, exp_mask),
|
||||
k(self, mant_mask),
|
||||
k(self, quiet_bit),
|
||||
);
|
||||
let e = self.s.m.bin(c, Bin::LShr, x, k23);
|
||||
let e = self.s.m.bin(c, Bin::And, e, kff);
|
||||
let e = self.s.m.bin(c, Bin::LShr, x, k_exp);
|
||||
let e = self.s.m.bin(c, Bin::And, e, k_emax);
|
||||
let m = self.s.m.bin(c, Bin::And, x, mant);
|
||||
let neg = self.s.m.bin(c, Bin::LShr, x, k31);
|
||||
let neg = self.s.m.bin(c, Bin::LShr, x, k_sign);
|
||||
let zero = k(self, 0);
|
||||
let (e0, e255) = (
|
||||
let (e0, emax) = (
|
||||
self.s.m.cmp(c, pred::EQ, e, zero),
|
||||
self.s.m.cmp(c, pred::EQ, e, kff),
|
||||
self.s.m.cmp(c, pred::EQ, e, k_emax),
|
||||
);
|
||||
let m0 = self.s.m.cmp(c, pred::EQ, m, zero);
|
||||
let q = self.s.m.bin(c, Bin::And, x, quiet);
|
||||
@@ -5129,7 +5193,7 @@ impl<'a> Lower<'a> {
|
||||
(k(self, 8), k(self, 9), k(self, 6), k(self, 7));
|
||||
let t = self.s.m.select(c, m0, zero_c, denorm);
|
||||
let t = self.s.m.select(c, e0, t, normal);
|
||||
let t = self.s.m.select(c, e255, inf, t);
|
||||
let t = self.s.m.select(c, emax, inf, t);
|
||||
let eleven = k(self, 11);
|
||||
let mirrored = self.s.m.bin(c, Bin::Sub, eleven, t);
|
||||
let is_neg = self.s.m.cmp(c, pred::NE, neg, zero);
|
||||
@@ -5138,7 +5202,7 @@ impl<'a> Lower<'a> {
|
||||
let nan_class = self.s.m.select(c, q, one, snan);
|
||||
let yes = self.s.m.bool(true);
|
||||
let nan = self.s.m.bin(c, Bin::Xor, m0, yes);
|
||||
let nan = self.s.m.bin(c, Bin::And, nan, e255);
|
||||
let nan = self.s.m.bin(c, Bin::And, nan, emax);
|
||||
let t = self.s.m.select(c, nan, nan_class, t);
|
||||
let bit = self.s.m.bin(c, Bin::LShr, mask, t);
|
||||
let bit = self.s.m.bin(c, Bin::And, bit, one);
|
||||
@@ -6720,7 +6784,7 @@ impl<'a> Lower<'a> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Lowered, Numeric, Parts, buffer_format, lower};
|
||||
use super::{Lowered, Numeric, Parts, buffer_format, half_shift, lower};
|
||||
use crate::native::{
|
||||
ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
|
||||
};
|
||||
@@ -6960,6 +7024,35 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_bit_tests_lower() {
|
||||
// Each tests one bit of a constant into SCC and branches on it (only
|
||||
// code with an effect needs its operands).
|
||||
let tail = [
|
||||
0xBF85_0001, // s_cbranch_scc1 -> s_endpgm
|
||||
0xBE84_0380, // s_mov_b32 s4, 0
|
||||
S_ENDPGM,
|
||||
];
|
||||
let bit_tests: [&[u32]; 4] = [
|
||||
&[0xBE81_0387, 0xBF0C_8301], // s_mov_b32 s1, 7; s_bitcmp0_b32 s1, 3
|
||||
&[0xBE81_0387, 0xBF0D_8301], // s_mov_b32 s1, 7; s_bitcmp1_b32 s1, 3
|
||||
&[
|
||||
0xBE80_0387, // s_mov_b32 s0, 7
|
||||
0xBE81_0380, // s_mov_b32 s1, 0
|
||||
0xBF0E_8300, // s_bitcmp0_b64 s[0:1], 3
|
||||
],
|
||||
&[
|
||||
0xBE80_0387, // s_mov_b32 s0, 7
|
||||
0xBE81_0380, // s_mov_b32 s1, 0
|
||||
0xBF0F_8300, // s_bitcmp1_b64 s[0:1], 3
|
||||
],
|
||||
];
|
||||
for head in bit_tests {
|
||||
let words: Vec<u32> = head.iter().chain(&tail).copied().collect();
|
||||
lowers(&words).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn buffer_formats_by_number() {
|
||||
// The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM,
|
||||
@@ -6975,9 +7068,81 @@ mod tests {
|
||||
buffer_format(77),
|
||||
Some((&[32, 32, 32, 32][..], Numeric::Float))
|
||||
);
|
||||
// Invalid, a packed float, past the table.
|
||||
// Invalid, past the table.
|
||||
assert_eq!(buffer_format(0), None);
|
||||
assert_eq!(buffer_format(36), None);
|
||||
assert_eq!(buffer_format(78), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packed_buffer_formats_by_number() {
|
||||
// LLVM's `UfmtGFX10`: 10_11_11 is 30-36, 11_11_10 37-43,
|
||||
// 10_10_10_2 44-49. Channels from the lowest bits: R11G11B10_FLOAT
|
||||
// is 10_11_11 (Mesa), 10_10_10_2 has the 2-bit channel first.
|
||||
assert_eq!(buffer_format(30), Some((&[11, 11, 10][..], Numeric::Unorm)));
|
||||
assert_eq!(buffer_format(36), Some((&[11, 11, 10][..], Numeric::Float)));
|
||||
assert_eq!(buffer_format(37), Some((&[10, 11, 11][..], Numeric::Unorm)));
|
||||
assert_eq!(buffer_format(43), Some((&[10, 11, 11][..], Numeric::Float)));
|
||||
assert_eq!(
|
||||
buffer_format(44),
|
||||
Some((&[2, 10, 10, 10][..], Numeric::Unorm))
|
||||
);
|
||||
assert_eq!(
|
||||
buffer_format(45),
|
||||
Some((&[2, 10, 10, 10][..], Numeric::Snorm))
|
||||
);
|
||||
assert_eq!(
|
||||
buffer_format(46),
|
||||
Some((&[2, 10, 10, 10][..], Numeric::Uscaled))
|
||||
);
|
||||
assert_eq!(
|
||||
buffer_format(47),
|
||||
Some((&[2, 10, 10, 10][..], Numeric::Sscaled))
|
||||
);
|
||||
assert_eq!(
|
||||
buffer_format(48),
|
||||
Some((&[2, 10, 10, 10][..], Numeric::Uint))
|
||||
);
|
||||
assert_eq!(
|
||||
buffer_format(49),
|
||||
Some((&[2, 10, 10, 10][..], Numeric::Sint))
|
||||
);
|
||||
}
|
||||
|
||||
/// A half's value (sign, 5-bit exponent biased 15, 10-bit mantissa), as
|
||||
/// `legacyF16ToF32` widens it.
|
||||
fn half(h: u32) -> f32 {
|
||||
let (s, e, m) = ((h >> 15) & 1, (h >> 10) & 31, h & 1023);
|
||||
let v = match e {
|
||||
0 => m as f32 * 2f32.powi(-24),
|
||||
31 if m == 0 => f32::INFINITY,
|
||||
31 => f32::NAN,
|
||||
_ => (1024 + m) as f32 * 2f32.powi(e as i32 - 25),
|
||||
};
|
||||
if s == 1 { -v } else { v }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_floats_widen_as_halves() {
|
||||
// Unsigned 11- and 10-bit floats: a 5-bit exponent biased 15 over a
|
||||
// 6- or 5-bit mantissa, no sign; values from the D3D/GL spec.
|
||||
let f11 = |x: u32| half(x << half_shift(11));
|
||||
let f10 = |x: u32| half(x << half_shift(10));
|
||||
assert_eq!(f11(0), 0.0);
|
||||
assert_eq!(f11(0x001), 2f32.powi(-20)); // smallest denormal
|
||||
assert_eq!(f11(0x03F), 63.0 * 2f32.powi(-20)); // largest denormal
|
||||
assert_eq!(f11(0x040), 2f32.powi(-14)); // smallest normal
|
||||
assert_eq!(f11(0x3C0), 1.0);
|
||||
assert_eq!(f11(0x3E0), 1.5);
|
||||
assert_eq!(f11(0x7BF), 65024.0); // largest
|
||||
assert_eq!(f11(0x7C0), f32::INFINITY);
|
||||
assert!(f11(0x7C1).is_nan());
|
||||
assert_eq!(f10(0x001), 2f32.powi(-19));
|
||||
assert_eq!(f10(0x020), 2f32.powi(-14));
|
||||
assert_eq!(f10(0x1E0), 1.0);
|
||||
assert_eq!(f10(0x3DF), 64512.0);
|
||||
assert_eq!(f10(0x3E0), f32::INFINITY);
|
||||
assert!(f10(0x3FF).is_nan());
|
||||
// A 16-bit float is a half already, sign included.
|
||||
assert_eq!(half(0xBC00 << half_shift(16)), -1.0);
|
||||
}
|
||||
}
|
||||
@@ -674,3 +674,73 @@ fn bfe_signed_and_unsigned_match_rdna2() {
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn v_cmp_class_f16_matches_rdna2() {
|
||||
// v_cmp_class_f16_e64 s6, v1, v2 (VOP3 opcode 0x08f); v_cndmask_b32_e64 v0, 0, 1, s6
|
||||
let cmp_lo = build_valu_cs(&[
|
||||
vop3(0x08f, 6, vgpr(1), vgpr(2), 0)[0],
|
||||
vop3(0x08f, 6, vgpr(1), vgpr(2), 0)[1],
|
||||
vop3(0x101, 0, 0x80, 0x81, sgpr(6))[0],
|
||||
vop3(0x101, 0, 0x80, 0x81, sgpr(6))[1],
|
||||
]);
|
||||
// Same with op_sel:[1,0] (high half of v1) + neg on src0 (bit 29 of w1).
|
||||
let [mut w0, mut w1] = vop3(0x08f, 6, vgpr(1), vgpr(2), 0);
|
||||
w0 |= 1 << 11; // opsel[0] = 1 (high half)
|
||||
w1 |= 1 << 29; // neg[0] = 1
|
||||
let cmp_hi_neg = build_valu_cs(&[
|
||||
w0,
|
||||
w1,
|
||||
vop3(0x101, 0, 0x80, 0x81, sgpr(6))[0],
|
||||
vop3(0x101, 0, 0x80, 0x81, sgpr(6))[1],
|
||||
]);
|
||||
|
||||
// All 10 IEEE-754 binary16 classes: bit k corresponds to class k.
|
||||
let classes: &[(u32, u32)] = &[
|
||||
(0x7C01, 0), // sNaN (+sNaN, quiet bit 0x0200 clear)
|
||||
(0xFDFF, 0), // -sNaN (sign ignored for NaNs)
|
||||
(0x7E00, 1), // +qNaN
|
||||
(0xFE01, 1), // -qNaN
|
||||
(0xFC00, 2), // -inf
|
||||
(0xBC00, 3), // -normal (-1.0)
|
||||
(0x8001, 4), // -denormal
|
||||
(0x8000, 5), // -0.0
|
||||
(0x0000, 6), // +0.0
|
||||
(0x0001, 7), // +denormal
|
||||
(0x3C00, 8), // +normal (+1.0)
|
||||
(0x7C00, 9), // +inf
|
||||
];
|
||||
let mut cases = Vec::new();
|
||||
for &(bits, cls) in classes {
|
||||
// Exact class bit -> true; complement of class bit across all 10 bits -> false.
|
||||
cases.push(([bits, 1u32 << cls, 0, 0], 1u32));
|
||||
cases.push(([bits, 0x3FF & !(1u32 << cls), 0, 0], 0u32));
|
||||
}
|
||||
let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect();
|
||||
run_cases(&cmp_lo, &inputs, |backend, i, inp, got| {
|
||||
let want = cases[i].1;
|
||||
assert_eq!(
|
||||
got, want,
|
||||
"{backend}: v_cmp_class_f16({:#06x}, {:#05x}) = {got}, want {want}",
|
||||
inp[0], inp[1],
|
||||
);
|
||||
});
|
||||
|
||||
// High half with neg: high half 0x3C00 (+1.0) negated -> -normal (class 3);
|
||||
// high half 0x7C01 (+sNaN) negated -> still sNaN (class 0, not quieted).
|
||||
let hi_cases: &[([u32; 4], u32)] = &[
|
||||
([0x3C00_0000, 1 << 3, 0, 0], 1),
|
||||
([0x3C00_0000, 1 << 8, 0, 0], 0),
|
||||
([0x7C01_FFFF, 1 << 0, 0, 0], 1),
|
||||
([0x7C01_FFFF, 1 << 1, 0, 0], 0),
|
||||
];
|
||||
let hi_in: Vec<[u32; 4]> = hi_cases.iter().map(|c| c.0).collect();
|
||||
run_cases(&cmp_hi_neg, &hi_in, |backend, i, inp, got| {
|
||||
let want = hi_cases[i].1;
|
||||
assert_eq!(
|
||||
got, want,
|
||||
"{backend}: v_cmp_class_f16(-hi({:#010x}), {:#05x}) = {got}, want {want}",
|
||||
inp[0], inp[1],
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -236,7 +236,7 @@ pub(super) const SOPP: &[(u16, &str)] = &[
|
||||
(0x023, "s_waitcnt_depctr"),
|
||||
(0x024, "s_round_mode"),
|
||||
(0x025, "s_denorm_mode"),
|
||||
(0x026, "s_ttracedata_imm"),
|
||||
(0x028, "s_ttracedata_imm"),
|
||||
];
|
||||
|
||||
pub(super) const SMEM: &[(u16, &str)] = &[
|
||||
@@ -1313,3 +1313,21 @@ pub(super) const SCRATCH: &[(u16, &str)] = &[
|
||||
(0x024, "scratch_load_short_d16"),
|
||||
(0x025, "scratch_load_short_d16_hi"),
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
fn bytes(words: &[u32]) -> Vec<u8> {
|
||||
words.iter().flat_map(|w| w.to_le_bytes()).collect()
|
||||
}
|
||||
|
||||
/// `s_ttracedata_imm 0x1234` as LLVM's GFX10 disassembler tests have it
|
||||
/// (`gfx10_sopp.txt`: `0x34,0x12,0xa8,0xbf`), SOPP opcode 0x28 as in
|
||||
/// AMD's RDNA2 ISA. A thread-trace marker, which translation drops.
|
||||
#[test]
|
||||
fn s_ttracedata_imm_is_sopp_0x28() {
|
||||
let code = bytes(&[0xBFA8_1234, 0xBF81_0000]);
|
||||
let decoded = super::super::decode(&code).unwrap();
|
||||
assert_eq!(decoded[0].name(), Some("s_ttracedata_imm"));
|
||||
assert!(crate::ir::build(&code, false, 1).is_ok());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user