Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/startup_stubs/d3d12_compute_dispatch.inl
Original file line number Diff line number Diff line change
Expand Up @@ -560,6 +560,7 @@ bool translate_compute_natively(ComputeTranslation& tr, ID3D12Device* device)
tr.srvs.clear();
tr.uavs.clear();
tr.samplers = {}; // a published manifest read next numbers its sampler lines from 0
tr.sampler_heap_bytes = 0;
tr.root.Reset();
tr.pipeline.Reset();
count_native_compute_refusal(reason);
Expand Down Expand Up @@ -600,6 +601,22 @@ bool translate_compute_natively(ComputeTranslation& tr, ID3D12Device* device)
slot.source = ComputeTranslation::input_stride;
tr.uds.push_back(slot);
}
// Directly indexed sampler heap (#3076): one heap_sampler binding records the span in bytes
// the program reads (whole 16-byte title entries below the fallback entry 2047) and is not a
// view register. Extract it before sorting and checking SRV/UAV registers.
for (auto at = program.bindings.begin(); at != program.bindings.end();) {
if (at->kind != x2w::ComputeViewKind::heap_sampler) {
++at;
continue;
}
if (tr.sampler_heap_bytes || at->root_parameter != x2w::compute_sampler_heap ||
at->shader_register != 0 || at->array_count != 1 || !at->required_bytes ||
at->required_bytes % x2w_startup::title_sampler_stride ||
at->required_bytes > x2w_startup::title_sampler_stride * x2w_startup::translated_sampler_fallback)
throw std::runtime_error("a sampler heap span that is not 16-byte entries below the fallback");
tr.sampler_heap_bytes = at->required_bytes;
at = program.bindings.erase(at);
}
std::sort(program.bindings.begin(), program.bindings.end(),
[](const auto& a, const auto& b) { return a.shader_register < b.shader_register; });
for (const auto& view : program.bindings) {
Expand Down
10 changes: 10 additions & 0 deletions tests/cmake/startup_compute_sampler_heap.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,13 @@ if(TARGET startup_stream_consumer AND TARGET compile_dxil AND EXISTS "${INTAKE_P
set_tests_properties(startup_compute_dispatch_sampler_heap_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77)
endforeach()
endif()
# The same program translated in-process (X2W_NATIVE_SHADERS, X2W_NATIVE_SHADERS_ONLY=1), as a default run does (#3076).
if(TARGET startup_stream_consumer AND TARGET compile_dxil AND TARGET x2w_shader_compiler AND EXISTS "${INTAKE_PYTHON}"
AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll" AND EXISTS "${DXC_BIN_DIR}/dxc.exe")
foreach(adapter IN ITEMS warp hardware)
add_test(NAME startup_compute_dispatch_sampler_heap_native_${adapter} COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_sampler_heap_check.py" "$<TARGET_FILE:startup_stream_consumer>"
"$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" ${adapter} native)
set_tests_properties(startup_compute_dispatch_sampler_heap_native_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77)
endforeach()
endif()
17 changes: 15 additions & 2 deletions tests/standin_exports_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,15 @@ def patch_root(module, root):

# ---------------------------------------------------------------- real repo

def _direct_export_source(rel_path, symbol):
for lineno, line in enumerate(
(ROOT / rel_path).read_text(encoding="utf-8").splitlines(), 1
):
if "__declspec(dllexport)" in line and symbol in line:
return f"{rel_path}:{lineno}"
raise AssertionError(f"{symbol} export not found in {rel_path}")


def test_real_catalogs():
modules = [stem + ".dll" for stem in DEFAULT_DEFS]
modules += ["xgameruntime.dll", "unknown.dll", "XMem.DLL", "xmem.dll"]
Expand Down Expand Up @@ -221,7 +230,9 @@ def test_real_catalogs():
check(d3d12.lookup("x2w_d3d12_compute_census").status == "unmeasured",
"d3d12_xs direct export is unmeasured")
check(d3d12.lookup("x2w_d3d12_compute_census").source
== "src/startup_stubs/d3d12_compute_dispatch.inl:1744",
== _direct_export_source(
"src/startup_stubs/d3d12_compute_dispatch.inl",
"x2w_d3d12_compute_census"),
"d3d12_xs direct export source is the included file")
check(d3d12.lookup("NoSuchExport").status == "absent",
"d3d12_xs absent name")
Expand Down Expand Up @@ -270,7 +281,9 @@ def test_export_coverage():
"src/xmem_shim.def:15", None),
("d3d12_xs.dll", "x2w_d3d12_compute_census", "unmeasured",
"d3d12_xs.dll", "shim",
"src/startup_stubs/d3d12_compute_dispatch.inl:1744", None),
_direct_export_source(
"src/startup_stubs/d3d12_compute_dispatch.inl",
"x2w_d3d12_compute_census"), None),
("d3d12_xs.dll", "IID_ID3D12Device", "implemented", "d3d12_xs.dll",
"shim", "src/d3d12_xs_shim.def:13", "src/d3d12_xs_iids.cpp:1"),
("xgameruntime.dll", "XUserAddAsync", "implemented",
Expand Down
168 changes: 159 additions & 9 deletions tests/startup_compute_sampler_heap_check.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""A native compute program that reads the directly indexed sampler heap runs with the title's sampler heap (#3076, stage 2a).
"""A native compute program that reads the directly indexed sampler heap runs with the title's sampler heap (#3076).

usage: startup_compute_sampler_heap_check.py <startup_stream_consumer> <compile_dxil> <sdk bin dir> <warp|hardware>
usage: startup_compute_sampler_heap_check.py <startup_stream_consumer> <compile_dxil> <sdk bin dir> <warp|hardware> [native]

The program is SAMPLE of native_sampler_heap_check.py: it loads the sampler at heap byte 0x430 (entry 67) and samples a
4x4 RGBA32F texture at (1.375, -0.375), outside [0, 1]; one thread group of 32 lanes stores one float4 per lane. The
Expand All @@ -9,6 +9,7 @@
sampler heap of 128 title entries (the descriptor words the title writes, 16 bytes each, entry 67 a wrap/point sampler,
every other entry a decoy), sets it on the list with the view heap and records Dispatch(1, 1, 1). Steps:

Published route (default):
1. before translation: refused with "no translation", every output word keeps its sentinel;
2. `compile_dxil --requests` publishes <key>.cs.cso and a <key>.txt whose last line before `native` is `smpidx 1088`;
3. reader refusals (no GPU needed), each with its text and an untouched output: `smpidx` 0, 20, 32768, -16, twice, and
Expand All @@ -20,9 +21,19 @@
smaller than the program reads"; a heap of exactly 68 entries runs; a manifest span of 1104 on 68 entries is refused;
the manifest without its `smpidx` line -> "pipeline creation failed" (the root then lacks the sampler heap flag).

Exit 77 when the adapter has no 32-lane waves (WARP): the program is then not translated, steps 1 to 3 have run.
In-process native route (`native` argument, X2W_NATIVE_SHADERS + X2W_NATIVE_SHADERS_ONLY=1, no published manifest):
1. `translate_compute_natively` translates SAMPLE live with no `<key>.cs.cso` or `<key>.txt` in the cache, runs the
dispatch and matches the CPU model in all 32 lanes;
2. each decoy in slot 67 changes the output and matches the CPU model for point samplers;
3. controls: view heap alone -> "no sampler heap is set on the list"; 67 entries -> "the sampler heap is smaller than
the program reads"; 68 entries runs; a second program sampling entry 68 (span 1104) is refused on 68 entries and runs
on 69 entries; entry 2047 (the fallback slot) is refused natively with an untouched output.

Exit 77 when the adapter has no 32-lane waves (WARP): on the published route steps 1 to 3 have run; on the native route
the refusal is verified and the test skips.
"""
from pathlib import Path
import hashlib
import struct
import subprocess
import sys
Expand Down Expand Up @@ -82,10 +93,10 @@ def model(words):
assert all(model(d) != WANTED for d in DECOYS)


def heap_bytes(count, entry=WRAP_POINT):
def heap_bytes(count, entry=WRAP_POINT, slot=ENTRY):
words = []
for i in range(count):
words.extend(entry if i == ENTRY else DECOYS[i % len(DECOYS)])
words.extend(entry if i == slot else DECOYS[i % len(DECOYS)])
return struct.pack('<%dI' % len(words), *words)


Expand All @@ -98,15 +109,151 @@ def refusal(result):
return [line for line in D.lines(result, 'Dispatch(1, 1, 1) refused: ')]


def main(consumer, compile_dxil, sdk, adapter):
def patch_sampler_heap_pack(pack_path, dest_path, *, shader_register=0, array_count=1, required_bytes=SPAN):
"""Patch the single heap_sampler binding inside a prepared compute pack and refresh its digest."""
raw = bytearray(pack_path.read_bytes())
assert len(raw) > 128, len(raw)
payload = bytearray(raw[128:])
# ComputeViewBinding layout in encode(): kind(20), root_parameter(0xfffffffe), byte_offset(0),
# shader_register(0), required_bytes(SPAN), array_count(1), array_position(0).
needle = struct.pack('<7I', 20, 0xfffffffe, 0, 0, SPAN, 1, 0)
pos = payload.find(needle)
assert pos >= 0 and payload.find(needle, pos + 1) < 0, (pos, len(payload))
payload[pos:pos + len(needle)] = struct.pack('<7I', 20, 0xfffffffe, 0, shader_register, required_bytes, array_count, 0)
digest = hashlib.sha256(payload).hexdigest().encode('ascii')
assert len(digest) == 64
dest_path.write_bytes(bytes(raw[:64]) + digest + bytes(payload))


def run_native(directory, cache, consumer, compile_dxil, env, adapter, dispatch):
untouched = [SENTINEL] * (LANES * 4)

# 0. capability probe before create_slot67 so an adapter lacking SM 6.6 or Tier 3 skips (77)
# instead of failing CreateRootSignature(SAMPLER_HEAP_DIRECTLY_INDEXED).
probe = subprocess.run(
[consumer, str(directory / 'vertex'), str(directory / 'pixel'), str(directory / 'root'),
'slot67', str(directory / 'program'), str(directory / 'data'), str(directory / 'state'),
'sampler-heap-probe'],
env=env, capture_output=True, text=True)
if probe.returncode == 77:
print(probe.stdout, end='')
print('sampler heap (native): skipped (adapter lacks SM 6.6 or resource binding tier 3)')
return 77
assert probe.returncode == 0, (probe.returncode, probe.stdout, probe.stderr[-3000:])

# 1. live in-process native translation with no published .cs.cso or .txt
got, result = dispatch('sampler-heap')
print(result.stdout, end='')
skipped_capability = None
for capability in ('the adapter has no 32-lane waves', 'the adapter reports shader model below 6.6',
'the device does not take a directly indexed sampler heap'):
if D.lines(result, f'not translated natively: {capability}'):
assert got == untouched, 'a dispatch without a pipeline wrote the output'
skipped_capability = capability
break

# 1b. runtime span guard controls (run even on WARP because they execute before the wave32 check):
# prepare a compute frontend pack from the published request and patch its heap_sampler binding
# metadata to out-of-range values so translate_compute_natively's own guard is exercised directly.
key = int(D.lines(result, 'x2w-draw compute request')[-1].split()[3], 16)
pack_reqs = directory / 'pack_reqs'
pack_reqs.mkdir(exist_ok=True)
for part in cache.glob(f'req_{key:016x}.*'):
(pack_reqs / part.name).write_bytes(part.read_bytes())
pack_cache = directory / 'pack_cache'
pack_cache.mkdir(exist_ok=True)
pack_run = subprocess.run([compile_dxil, '--prepare-compute-pack', str(pack_reqs), str(pack_cache), '0'],
capture_output=True, text=True)
assert pack_run.returncode == 0 and 'prepared=1' in pack_run.stdout, (pack_run.stdout, pack_run.stderr)
pack_base = pack_cache / 'compute-0.pack'
span_reason = 'a sampler heap span that is not 16-byte entries below the fallback'
for label, patch_kwargs in (
('span 0', dict(required_bytes=0)),
('span 20 (not 16-byte aligned)', dict(required_bytes=20)),
('span 32768 (fallback entry)', dict(required_bytes=32768)),
('nonzero shader register', dict(shader_register=1))):
bad_pack = directory / f'bad_pack_{label.split()[0]}.bin'
patch_sampler_heap_pack(pack_base, bad_pack, **patch_kwargs)
bad_env = dict(env, X2W_NATIVE_COMPUTE_PACK=str(bad_pack))
(directory / 'sampler_heap').write_bytes(heap_bytes(ENTRIES))
bad_got, bad_res = run(directory, consumer, bad_env, 'sampler-heap', LAYOUT)
assert bad_got == untouched, (label, bad_res.stderr[-3000:])
assert D.lines(bad_res, f'not translated natively: {span_reason}'), (label, bad_res.stderr[-3000:])
assert refusal(bad_res), (label, bad_res.stderr[-3000:])

if skipped_capability is not None:
print(f'sampler heap (native): 4 runtime span guard controls verified; dispatch skipped ({skipped_capability})')
return 77

assert not [p for p in cache.glob('*.txt') if p.name != 'revision.txt'] and not list(cache.glob('*.cs.cso')), list(cache.iterdir())
assert D.lines(result, 'translated natively: 0 entry values, 1 inputs, 1 outputs (frontend live)'), result.stderr[-3000:]
assert len(D.lines(result, 'Dispatch(1, 1, 1) translated')) == 1 and not refusal(result), result.stderr[-3000:]
assert all(lane == WANTED for lane in lanes(got)), (lanes(got)[:2], WANTED, result.stderr[-3000:])
layer = clean(result)

# 2. each decoy in slot 67 changes the output
for decoy in DECOYS:
got, result = dispatch('sampler-heap', heap_bytes(ENTRIES, decoy))
assert len(D.lines(result, 'Dispatch(1, 1, 1) translated')) == 1 and not refusal(result), result.stderr[-3000:]
seen = lanes(got)
assert all(lane == seen[0] for lane in seen) and seen[0] != WANTED and got != untouched, (decoy, seen[0])
if (decoy[2] >> 20) & 3 == 0:
assert seen[0] == model(decoy), (decoy, seen[0], model(decoy))
clean(result)

# 3. controls: views-only, undersized heap, exact 68-entry boundary
got, result = run(directory, consumer, env, 'sampler-heap-views-only', LAYOUT)
refused = refusal(result)
assert got == untouched and len(refused) == 1 and refused[0].endswith(
'refused: no sampler heap is set on the list'), (refused, result.stderr[-3000:])

got, result = dispatch('sampler-heap', heap_bytes(ENTRY))
refused = refusal(result)
assert got == untouched and len(refused) == 1 and refused[0].endswith(
'refused: the sampler heap is smaller than the program reads'), (refused, result.stderr[-3000:])

got, result = dispatch('sampler-heap', heap_bytes(ENTRY + 1))
assert len(D.lines(result, 'Dispatch(1, 1, 1) translated')) == 1 and not refusal(result), result.stderr[-3000:]
assert all(lane == WANTED for lane in lanes(got)), (lanes(got)[0], WANTED)
clean(result)

# 4. a second program sampling entry 68 (span 1104): refused on 68 entries, succeeds on 69 entries
sample68 = [0xfa000440 if w == 0xfa000430 else w for w in N.PROGRAMS['sample']]
assert sample68 != N.PROGRAMS['sample']
(directory / 'program').write_bytes(struct.pack('<%dI' % len(sample68), *sample68))
got, result = dispatch('sampler-heap', heap_bytes(ENTRY + 1, slot=ENTRY + 1))
refused = refusal(result)
assert got == untouched and len(refused) == 1 and refused[0].endswith(
'refused: the sampler heap is smaller than the program reads'), (refused, result.stderr[-3000:])

got, result = dispatch('sampler-heap', heap_bytes(ENTRY + 2, slot=ENTRY + 1))
assert len(D.lines(result, 'Dispatch(1, 1, 1) translated')) == 1 and not refusal(result), result.stderr[-3000:]
assert all(lane == WANTED for lane in lanes(got)), (lanes(got)[0], WANTED)
clean(result)

# 5. negative control: entry 2047 (reserved fallback) stays refused natively
(directory / 'program').write_bytes(struct.pack('<%dI' % len(N.PROGRAMS['idx2047']), *N.PROGRAMS['idx2047']))
got, result = dispatch('sampler-heap')
assert got == untouched and D.lines(result, 'not translated natively:') and refusal(result), result.stderr[-3000:]

print(f'startup_compute_sampler_heap (native): PASS on {adapter}: entry {ENTRY} and {ENTRY + 1} sampled live in all '
f'{LANES} lanes, {len(DECOYS)} decoys change it, 4 runtime span guard controls and views-only / span / '
f'fallback controls verified; debug layer: {layer}')
return 0


def main(consumer, compile_dxil, sdk, adapter, native=False):
env = dict(X2W_D3D12_LIST_NOOP='1', X2W_D3D12_DEBUG='1') # guest lists; debug-layer messages go to the log
if adapter == 'hardware':
env['X2W_TEST_DISPATCH_HARDWARE'] = '1'
with tempfile.TemporaryDirectory() as temporary:
directory = Path(temporary)
cache, base = prepare(directory)
env = dict(base, **env)
env.pop('X2W_NATIVE_SHADERS', None) # the published route
env.pop('X2W_NATIVE_SHADERS', None)
env.pop('X2W_NATIVE_SHADERS_ONLY', None)
if native:
env.update(X2W_NATIVE_SHADERS=str(sdk), X2W_NATIVE_SHADERS_ONLY='1')
root_source = directory / 'root.hlsl'
root_source.write_text(f'#define RS "{N.ROOT_RW}"')
subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'RS', '-Fo', directory / 'compute_root', root_source],
Expand All @@ -124,6 +271,9 @@ def dispatch(mode, heap=None):
(directory / 'sampler_heap').write_bytes(heap_bytes(ENTRIES) if heap is None else heap)
return run(directory, consumer, env, mode, LAYOUT)

if native:
return run_native(directory, cache, consumer, compile_dxil, env, adapter, dispatch)

untouched = [SENTINEL] * (LANES * 4)

# 1. no translation yet
Expand Down Expand Up @@ -221,6 +371,6 @@ def dispatch(mode, heap=None):


if __name__ == '__main__':
if len(sys.argv) != 5 or sys.argv[4] not in ('warp', 'hardware'):
if len(sys.argv) not in (5, 6) or sys.argv[4] not in ('warp', 'hardware') or (len(sys.argv) == 6 and sys.argv[5] != 'native'):
sys.exit(__doc__)
sys.exit(main(*sys.argv[1:]))
sys.exit(main(*sys.argv[1:5], native=len(sys.argv) == 6))
15 changes: 15 additions & 0 deletions tests/startup_stream_consumer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1606,6 +1606,21 @@ int main(int argc, char** argv)
}
if (argc == 9 && std::strcmp(argv[4], "slot67") == 0 && std::strncmp(argv[8], "texture", 7) == 0)
return create_slot67(device, argv[5], argv[6], argv[7], argv[8]) ? texture_slot67(adapter.Get(), device, argv[8]) : 10;
if (argc == 9 && std::strcmp(argv[4], "slot67") == 0 && std::strcmp(argv[8], "sampler-heap-probe") == 0) {
Microsoft::WRL::ComPtr<ID3D12Device> desktop;
if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&desktop)))) return 77;
D3D12_FEATURE_DATA_SHADER_MODEL model{D3D_SHADER_MODEL_6_6};
D3D12_FEATURE_DATA_D3D12_OPTIONS options{};
if (FAILED(desktop->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &model, sizeof(model))) ||
model.HighestShaderModel < D3D_SHADER_MODEL_6_6 ||
FAILED(desktop->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options))) ||
options.ResourceBindingTier < D3D12_RESOURCE_BINDING_TIER_3) {
std::printf("adapter lacks shader model 6.6 or resource binding tier 3 (tier %d)\n",
static_cast<int>(options.ResourceBindingTier));
return 77;
}
return 0;
}
if (argc == 9 && std::strcmp(argv[4], "slot67") == 0 && std::strncmp(argv[8], "sampler-heap", 12) == 0)
return create_slot67(device, argv[5], argv[6], argv[7], argv[8]) ? sampler_heap_slot67(device, argv[8]) : 10;
if ((argc == 8 || argc == 9) && std::strcmp(argv[4], "slot67") == 0)
Expand Down
Loading