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
4 changes: 3 additions & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1500,9 +1500,11 @@ add_dependencies(d3d12_xs_shim_check pso_compute_headers)
target_link_libraries(d3d12_xs_shim_check PRIVATE d3d12_xs_shim dxgi)
target_include_directories(d3d12_xs_shim_check PRIVATE "${CMAKE_CURRENT_BINARY_DIR}")
target_compile_features(d3d12_xs_shim_check PRIVATE cxx_std_17)
foreach(scenario IN ITEMS exports serialize deserialize iids warp_root)
foreach(scenario IN ITEMS exports serialize deserialize iids warp_root heap_indexing)
add_test(NAME d3d12_xs_shim_${scenario} COMMAND d3d12_xs_shim_check ${scenario})
endforeach()
# 77: the desktop runtime accepts the heap-indexing flags (shader model 6.6), so the retry is unreachable.
set_tests_properties(d3d12_xs_shim_heap_indexing PROPERTIES SKIP_RETURN_CODE 77)
# D3D12XboxCreateDevice device-slot inventory and source-built creation fixture (#XCL-08).
set(d3d12x_pso_header "${CMAKE_CURRENT_BINARY_DIR}/d3d12x_pso_cs.h")
add_custom_command(OUTPUT "${d3d12x_pso_header}"
Expand Down
2 changes: 1 addition & 1 deletion docs/startup-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -597,7 +597,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr
| `X2W_XMEM_PERMISSIVE=1` | accepts the reservation, mapping and allocation shapes a startup run uses |
| `X2W_XMEM_STARTUP_BELOW_40=1` (`run.ps1 -StartupBelow40`) | startup compatibility configuration ([#1758](https://github.com/R0Y00/Xbox2Windows/issues/1758)): the large-page startup blocks with attribute `0x283` (null address, type `0x20003000`, protection `0x2004` or `0x2404`) are placed so that the whole block, last byte included, lies below 2^40. A block that does not fit there returns NULL with the Windows error and logs `x2w-xmem startup block below 2^40 refused:`; nothing is truncated or placed higher. Other shapes and explicit addresses keep their placement. See [Startup blocks below 2^40](experiments.md#startup-blocks-below-240) |
| `X2W_XMEM_GPU_MIRROR=1` | pairs a no-access graphics reservation with the read-write reservation of the same size made just before it, and maps every physical page into both (same section) |
| `X2W_D3D12_PERMISSIVE=1` | wraps the device: recording command lists, console present, view tracking |
| `X2W_D3D12_PERMISSIVE=1` | wraps the device: recording command lists, console present, view tracking; on a runtime without shader model 6.6 (in-box Windows 10), root signatures with the heap-indexing flags (`0xC00`) are serialized again without them, and the copy kept for shader translation gets that call's bits back when `CreateRootSignature` receives the returned blob's own buffer (a copy of the bytes keeps the desktop flags; `d3d12_xs_shim_heap_indexing`). The retry runs only on runtimes that refuse the flags (before shader model 6.6); where the runtime accepts them, `d3d12_xs_shim_heap_indexing` reports a capability skip (77) |
| `X2W_D3D12_RENDER=1` | draws through translated pipelines from `X2W_SHADER_CACHE` and forwards [single-record indirect Dispatch](experiments.md#gpu-written-indirect-dispatch-arguments), [DrawIndexed](experiments.md#gpu-written-indirect-indexed-draw-arguments), [Draw](experiments.md#gpu-written-indirect-draw-arguments), and [DispatchMesh](experiments.md#gpu-written-indirect-mesh-dispatch-arguments) for supported desktop pipelines and tracked placed buffers |
| `X2W_SHADER_CACHE=<dir>` | translation cache: the runtime writes source requests `req_<key>.{a,b,root}` and, when needed, RTV variants `req_<key>.rtv`. Run `tools/startup/gfx2hlsl.py --pending <dir>` while the process is running. Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\<version>\x64`, else `PATH`. When none exists it writes `<key>.fail` naming `X2W_FXC` and no manifest; `X2W_FXC=` (empty) skips compilation and publishes the manifest alone. |
| `X2W_DRAW_NULL_IDENTITY=1` | null descriptors read as identity values instead of zero |
Expand Down
156 changes: 152 additions & 4 deletions src/d3d12_xs_shim.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <new>
#include <vector>

#include "d3d12x_device_slots.h"

Expand All @@ -39,6 +41,152 @@ struct VmState {
bool device_created = false;
};
VmState vm_state;

// Desktop root-signature flags for direct heap indexing (CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED and
// SAMPLER_HEAP_DIRECTLY_INDEXED). A desktop runtime older than shader model 6.6 does not know them
// and answers E_INVALIDARG; the in-box Windows 10 runtime is one. With X2W_D3D12_PERMISSIVE=1 the
// serialization is then repeated without them, so that a caller that sets them on every root
// signature still gets a blob. The result no longer declares direct heap indexing.
constexpr std::uint32_t heap_indexing_flags = 0x00000C00u;

// The serialized bytes do not say which input produced them: the legal baseline and inputs with only
// 0x400, only 0x800 or both serialize to the same blob once the bits are removed. The removed bits are
// therefore tied to the blob object a retry returns. That object registers its buffer while it lives
// and unregisters it before the buffer can be freed and reused, so x2w_stripped_root_flags answers
// for that exact buffer only. A copy of the bytes, or a blob from any other call, reports 0.
struct StrippedBlob { const void* data; std::size_t bytes; std::uint32_t bits; };
SRWLOCK stripped_lock = SRWLOCK_INIT;
std::vector<StrippedBlob> stripped_blobs;

class RetriedBlob final : public ID3DBlob {
public:
// Take ownership only after the wrapper and its provenance record have both been allocated.
static ID3DBlob* wrap(ID3DBlob* inner, std::uint32_t bits) noexcept
{
RetriedBlob* wrapper = new (std::nothrow) RetriedBlob(inner);
if (!wrapper) return nullptr;
bool registered = true;
AcquireSRWLockExclusive(&stripped_lock);
try {
stripped_blobs.push_back({inner->GetBufferPointer(), inner->GetBufferSize(), bits});
} catch (...) {
registered = false;
}
ReleaseSRWLockExclusive(&stripped_lock);
if (registered) return wrapper;
wrapper->inner_ = nullptr; // inner stays with the caller
delete wrapper;
return nullptr;
}
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void** out) override
{
if (!out) return E_POINTER;
*out = nullptr;
if (iid != __uuidof(IUnknown) && iid != __uuidof(ID3D10Blob)) return E_NOINTERFACE;
*out = static_cast<ID3DBlob*>(this);
AddRef();
return S_OK;
}
ULONG STDMETHODCALLTYPE AddRef() override { return static_cast<ULONG>(InterlockedIncrement(&refs_)); }
ULONG STDMETHODCALLTYPE Release() override
{
const LONG left = InterlockedDecrement(&refs_);
if (!left) delete this;
return static_cast<ULONG>(left);
}
LPVOID STDMETHODCALLTYPE GetBufferPointer() override { return inner_->GetBufferPointer(); }
SIZE_T STDMETHODCALLTYPE GetBufferSize() override { return inner_->GetBufferSize(); }

private:
explicit RetriedBlob(ID3DBlob* inner) : inner_(inner) {}
~RetriedBlob()
{
if (!inner_) return;
const void* data = inner_->GetBufferPointer();
AcquireSRWLockExclusive(&stripped_lock);
for (std::size_t i = 0; i < stripped_blobs.size(); ++i)
if (stripped_blobs[i].data == data) {
stripped_blobs[i] = stripped_blobs.back();
stripped_blobs.pop_back();
break;
}
ReleaseSRWLockExclusive(&stripped_lock);
inner_->Release(); // only now may the buffer be reused
}
ID3DBlob* inner_;
LONG refs_ = 1;
};

bool permissive_switch()
{
const DWORD saved = GetLastError();
char value[4] = {};
const bool on = GetEnvironmentVariableA("X2W_D3D12_PERMISSIVE", value, sizeof(value)) > 0 && value[0] == '1';
SetLastError(saved);
return on;
}

HRESULT serialize_for_runtime(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* desc, ID3DBlob** blob, ID3DBlob** error_blob)
{
const HRESULT hr = D3D12SerializeVersionedRootSignature(desc, blob, error_blob);
if (hr != E_INVALIDARG || !desc || !blob) return hr;
if (desc->Version != D3D_ROOT_SIGNATURE_VERSION_1_0 && desc->Version != D3D_ROOT_SIGNATURE_VERSION_1_1) return hr;
const bool version_1_0 = desc->Version == D3D_ROOT_SIGNATURE_VERSION_1_0;
const auto flags = static_cast<std::uint32_t>(version_1_0 ? desc->Desc_1_0.Flags : desc->Desc_1_1.Flags);
if (!(flags & heap_indexing_flags) || !permissive_switch()) return hr;
D3D12_VERSIONED_ROOT_SIGNATURE_DESC copy = *desc;
auto& retry_flags = version_1_0 ? copy.Desc_1_0.Flags : copy.Desc_1_1.Flags;
retry_flags = static_cast<D3D12_ROOT_SIGNATURE_FLAGS>(flags & ~heap_indexing_flags);
ID3DBlob* retry_blob = nullptr;
ID3DBlob* retry_error = nullptr;
const HRESULT retry = D3D12SerializeVersionedRootSignature(&copy, &retry_blob, &retry_error);
if (retry_error) retry_error->Release();
if (FAILED(retry) || !retry_blob) {
if (retry_blob) retry_blob->Release();
return hr; // something else is wrong: keep the first answer and its error blob
}
*blob = RetriedBlob::wrap(retry_blob, flags & heap_indexing_flags);
if (error_blob && *error_blob) {
(*error_blob)->Release();
*error_blob = nullptr;
}
if (!*blob) {
retry_blob->Release();
return E_OUTOFMEMORY;
}
static LONG logged;
if (InterlockedIncrement(&logged) == 1)
std::fprintf(stderr, "x2w-d3d12 root signature flags 0x%x: this desktop runtime refuses the heap-indexing bits 0x%x; "
"serialized without them (X2W_D3D12_PERMISSIVE)\n", flags, flags & heap_indexing_flags);
return retry;
}
}

// The heap-indexing bits serialize_for_runtime removed for the live blob whose buffer is exactly
// (blob, bytes), 0 for any other pointer or size.
extern "C" std::uint32_t x2w_stripped_root_flags(const void* blob, std::size_t bytes)
{
if (!blob || !bytes) return 0;
std::uint32_t bits = 0;
bool same_bytes_elsewhere = false;
// The byte comparison below only feeds a once-only line; it stops once that line is logged.
static LONG logged;
AcquireSRWLockShared(&stripped_lock);
for (const StrippedBlob& entry : stripped_blobs)
if (entry.data == blob && entry.bytes == bytes) bits = entry.bits;
// Live entries' buffers stay valid while the lock is held (the destructor unregisters first).
if (!bits && !InterlockedCompareExchange(&logged, 0, 0))
for (const StrippedBlob& entry : stripped_blobs)
if (entry.bytes == bytes && std::memcmp(entry.data, blob, bytes) == 0) {
same_bytes_elsewhere = true;
break;
}
ReleaseSRWLockShared(&stripped_lock);
// The bytes alone cannot say which it is, so the answer stays 0; the line says why bits may be missing.
if (same_bytes_elsewhere && InterlockedExchange(&logged, 1) == 0)
std::fprintf(stderr, "x2w-d3d12 root signature blob %p has the bytes of a retried blob at another address: a copy "
"(its heap-indexing bits are not restored for translation) or a call without them\n", blob);
return bits;
}

extern "C" HRESULT WINAPI d3d12_xs_SerializeVersionedRootSignature(
Expand All @@ -47,24 +195,24 @@ extern "C" HRESULT WINAPI d3d12_xs_SerializeVersionedRootSignature(
ID3DBlob** error_blob)
{
if (!root_signature) {
return D3D12SerializeVersionedRootSignature(root_signature, blob, error_blob);
return serialize_for_runtime(root_signature, blob, error_blob);
}
if (root_signature->Version == D3D_ROOT_SIGNATURE_VERSION_1_1) {
const auto flags = static_cast<std::uint32_t>(root_signature->Desc_1_1.Flags);
if (flags & observed_console_flags) {
D3D12_VERSIONED_ROOT_SIGNATURE_DESC copy = *root_signature;
copy.Desc_1_1.Flags = static_cast<D3D12_ROOT_SIGNATURE_FLAGS>(flags & ~observed_console_flags);
return D3D12SerializeVersionedRootSignature(&copy, blob, error_blob);
return serialize_for_runtime(&copy, blob, error_blob);
}
} else if (root_signature->Version == D3D_ROOT_SIGNATURE_VERSION_1_0) {
const auto flags = static_cast<std::uint32_t>(root_signature->Desc_1_0.Flags);
if (flags & observed_console_flags) {
D3D12_VERSIONED_ROOT_SIGNATURE_DESC copy = *root_signature;
copy.Desc_1_0.Flags = static_cast<D3D12_ROOT_SIGNATURE_FLAGS>(flags & ~observed_console_flags);
return D3D12SerializeVersionedRootSignature(&copy, blob, error_blob);
return serialize_for_runtime(&copy, blob, error_blob);
}
}
return D3D12SerializeVersionedRootSignature(root_signature, blob, error_blob);
return serialize_for_runtime(root_signature, blob, error_blob);
}

extern "C" HRESULT WINAPI d3d12_xs_CreateRootSignatureDeserializer(
Expand Down
1 change: 1 addition & 0 deletions src/d3d12_xs_shim.def
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ EXPORTS
D3D12CreateRootSignatureDeserializer=d3d12_xs_CreateRootSignatureDeserializer
D3D12XboxCreateDevice=d3d12_xs_XboxCreateDevice
D3D12ConfigureVirtualMemoryX=d3d12_xs_ConfigureVirtualMemoryX
x2w_stripped_root_flags
IID_ID3D12CommandAllocator DATA
IID_ID3D12CommandList DATA
IID_ID3D12CommandQueue DATA
Expand Down
20 changes: 19 additions & 1 deletion src/startup_stubs/d3d12_capture.inl
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,26 @@ const PipelineInfo* pipeline_info(const Wrapper* w)
void note_root_blob(Wrapper* w, const void* blob, std::size_t bytes)
{
if (!blob || !bytes || bytes > (1u << 20)) return;
std::vector<unsigned char> copy(static_cast<const unsigned char*>(blob), static_cast<const unsigned char*>(blob) + bytes);
// The blob the d3d12_xs serializer returned after removing the title's heap-indexing flags (see
// serialize_for_runtime in src/d3d12_xs_shim.cpp): the copy kept for shader translation gets that
// call's bits back, because the title's shaders take the heap pointers in the registers they add.
if (const std::uint32_t stripped = x2w_stripped_root_flags(blob, bytes); stripped && bytes >= 32 && !std::memcmp(copy.data(), "DXBC", 4)) {
std::uint32_t parts = 0;
std::memcpy(&parts, copy.data() + 28, 4);
for (std::uint32_t i = 0; i < parts && 32 + 4 * (i + 1) <= bytes; ++i) {
std::uint32_t at = 0;
std::memcpy(&at, copy.data() + 32 + 4 * i, 4);
if (std::size_t{at} + 8 + 24 <= bytes && !std::memcmp(copy.data() + at, "RTS0", 4)) {
std::uint32_t flags = 0;
std::memcpy(&flags, copy.data() + at + 8 + 20, 4);
flags |= stripped;
std::memcpy(copy.data() + at + 8 + 20, &flags, 4);
}
}
}
AcquireSRWLockExclusive(&note_lock);
root_blobs()[w].assign(static_cast<const unsigned char*>(blob), static_cast<const unsigned char*>(blob) + bytes);
root_blobs()[w] = std::move(copy);
ReleaseSRWLockExclusive(&note_lock);
}
// This index only lists active slot-133 wrappers. The existing resource record
Expand Down
22 changes: 22 additions & 0 deletions src/startup_stubs/d3d12_xs_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,12 @@
#include <utility>
#include <vector>

// The heap-indexing bits src/d3d12_xs_shim.cpp removed for the blob it returned at exactly this
// buffer. A build that compiles this file without the shim (offscreen_check) links the fallback, 0.
extern "C" std::uint32_t x2w_stripped_root_flags(const void* blob, std::size_t bytes);
extern "C" std::uint32_t x2w_no_stripped_root_flags(const void*, std::size_t) { return 0; }
#pragma comment(linker, "/alternatename:x2w_stripped_root_flags=x2w_no_stripped_root_flags")

namespace {

using u64 = std::uint64_t;
Expand Down Expand Up @@ -1586,6 +1592,22 @@ HRESULT __stdcall device_create_root_signature(Wrapper* self, UINT node, const v
return S_OK;
}

// Fixtures: the copy of a root signature's blob kept for shader translation (the .root request and the
// translation key). Returns its size and copies up to capacity bytes to out; 0 for anything else. The
// heap-indexing flags slot 34 acts on (root_heap_flags, read from the desktop blob) go to heap_flags.
extern "C" __declspec(dllexport) std::size_t x2w_d3d12_root_translation_blob(void* root, void* out, std::size_t capacity, UINT* heap_flags)
{
Wrapper* w = as_wrapper(root);
if (!w || w->own().kind != root_signature_kind) return 0;
if (heap_flags) *heap_flags = root_heap_flags(w);
AcquireSRWLockShared(&note_lock);
const auto found = root_blobs().find(w);
const std::size_t bytes = found == root_blobs().end() ? 0 : found->second.size();
if (bytes && out) std::memcpy(out, found->second.data(), bytes < capacity ? bytes : capacity);
ReleaseSRWLockShared(&note_lock);
return bytes;
}

bool readable_shader_container(const D3D12_SHADER_BYTECODE& code)
{
return code.BytecodeLength >= 32 && code.BytecodeLength <= (1u << 20) &&
Expand Down
Loading
Loading