From cae19cc850f7dd71378c88b6aac44658b5209469 Mon Sep 17 00:00:00 2001 From: lewisalex86 Date: Wed, 25 Nov 2026 19:41:23 +0000 Subject: [PATCH] runtime: add a console profile and composite presented planes X2W_DEVICE_TYPE (with X2W_RUNTIME_PROXY) answers the OEM ConsoleMode registry reads: 6 = Series S, 7 = Series X, 1 = PC; unset, the real registry answers. The Series S profile's start-up path hit these desktop refusals, now avoided by the stand-in (shared-exponent UAVs are already covered by the packed-target stand-in on main): - Device::slot76 is CreateCommittedResource and shares the slot-127 path. - Views with ViewDimension 0 get the resource's default view where desktop allows one; other dimension mismatches are skipped. - A present can carry several planes; the output window composites them bottom to top instead of showing plane 0 alone (black on Series S). X2W_PRESENT_PLANE= shows one plane for diagnosis. New fixtures with negative controls: startup_console_mode, startup_view_dimension, startup_present_planes. --- CMakeLists.txt | 20 ++ docs/startup-runtime.md | 52 +++++ src/startup_stubs/console_mode.h | 96 +++++++++ src/startup_stubs/d3d12_present.inl | 88 +++++--- src/startup_stubs/d3d12_xs_device.cpp | 187 +++++++++++++--- src/startup_stubs/present_planes.h | 61 ++++++ src/startup_stubs/registry_console_mode.inl | 227 ++++++++++++++++++++ src/startup_stubs/runtime_gpa_patch.h | 28 ++- src/startup_stubs/runtime_proxy.cpp | 11 + src/startup_stubs/view_dimension.h | 80 +++++++ tests/startup_console_mode_check.cpp | 221 +++++++++++++++++++ tests/startup_present_planes_check.cpp | 89 ++++++++ tests/startup_view_dimension_check.cpp | 88 ++++++++ 13 files changed, 1184 insertions(+), 64 deletions(-) create mode 100644 src/startup_stubs/console_mode.h create mode 100644 src/startup_stubs/present_planes.h create mode 100644 src/startup_stubs/registry_console_mode.inl create mode 100644 src/startup_stubs/view_dimension.h create mode 100644 tests/startup_console_mode_check.cpp create mode 100644 tests/startup_present_planes_check.cpp create mode 100644 tests/startup_view_dimension_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 2cc5fbcf76..1575f30e42 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1050,6 +1050,20 @@ target_compile_features(startup_runtime_gpa_patch PRIVATE cxx_std_17) add_test(NAME startup_runtime_gpa_patch COMMAND startup_runtime_gpa_patch) add_test(NAME startup_runtime_gpa_patch_name_only_control COMMAND startup_runtime_gpa_patch --mutate name-only) set_tests_properties(startup_runtime_gpa_patch_name_only_control PROPERTIES PASS_REGULAR_EXPRESSION "FAIL: ") +# X2W_DEVICE_TYPE: the OEM ConsoleMode registry read, answered or passed on, against fake registry +# functions. The control leaves the switch unset for the answered cases and must FAIL. +add_executable(startup_console_mode tests/startup_console_mode_check.cpp) +target_include_directories(startup_console_mode PRIVATE src) +target_compile_features(startup_console_mode PRIVATE cxx_std_17) +add_test(NAME startup_console_mode COMMAND startup_console_mode) +add_test(NAME startup_console_mode_control COMMAND startup_console_mode --control) +set_tests_properties(startup_console_mode_control PROPERTIES PASS_REGULAR_EXPRESSION "FAIL: ") +add_executable(startup_view_dimension tests/startup_view_dimension_check.cpp) +target_include_directories(startup_view_dimension PRIVATE src) +target_compile_features(startup_view_dimension PRIVATE cxx_std_17) +add_test(NAME startup_view_dimension COMMAND startup_view_dimension) +add_test(NAME startup_view_dimension_control COMMAND startup_view_dimension --control) +set_tests_properties(startup_view_dimension_control PROPERTIES PASS_REGULAR_EXPRESSION "FAIL: ") # EXE + late-loaded package helper through the real Windows loader: proxied xgameruntime QueryApiImpl, # unrelated same-named export stays original. Notification only enqueues; rewrite runs after link. if (WIN32) @@ -1899,6 +1913,12 @@ foreach(adapter IN ITEMS warp hardware) add_test(NAME startup_sharedexp_target_${adapter} COMMAND offscreen_check ${adapter} --startup-sharedexp-target) set_tests_properties(startup_sharedexp_target_${adapter} PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77) endforeach() +add_executable(startup_present_planes tests/startup_present_planes_check.cpp) +target_include_directories(startup_present_planes PRIVATE src) +target_compile_features(startup_present_planes PRIVATE cxx_std_17) +add_test(NAME startup_present_planes COMMAND startup_present_planes) +add_test(NAME startup_present_planes_control COMMAND startup_present_planes --control) +set_tests_properties(startup_present_planes_control PROPERTIES PASS_REGULAR_EXPRESSION "FAIL: ") # Static samplers built from smp and smpc manifest lines (src/startup_stubs/translated_sampler_bindings.h). add_executable(startup_sampler_comparison_check tests/startup_sampler_comparison_check.cpp) target_include_directories(startup_sampler_comparison_check PRIVATE src) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 673534dbfe..ece40cbb5d 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -271,6 +271,26 @@ presenter, its owned window and a dialog stay visible. Where the host lets the t it also checks that the foreground moves to the output window. A run under Wine did; the fixture prints which case applied. +### Presented planes + +A console present (CommandQueue slot 32) carries a plane count and an array of plane records +(`src/startup_stubs/present_planes.h`). Measured from the first presents: one record is 0x48 bytes, +with +0x00 a frame token, +0x08 the resource count and +0x10 a pointer to the resource array. On the +Series S profile a title presented two planes: plane 0 at 1920x1080 stayed black and plane 1 at +3840x2160 held the picture, with alpha 255 wherever it drew. Showing plane 0 alone gave a black +window. The output window now composites the planes bottom to top: the lowest shown plane opaque, each +later one blended by its own alpha (`composite_steps`); planes the presenter cannot draw and repeats of +a surface are left out. The plane whose surface is read back and reported is the topmost one. Why +plane 0 stays black is not known. The first presents and every 300th log each plane: + +```text +x2w-present frame plane /: x format flags=0x +``` + +`ctest --preset dev --no-tests=error -R '^startup_present_planes(_control)?$'` checks the record layout +and the composite order; the control reads 0x40-byte records and composites plane 0 alone, and must +print `FAIL:`. + ## Null Texture2D descriptors When the adapter lacks typed UAV support for B5G5R5A1_UNORM or render-target support for @@ -1352,6 +1372,8 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_DEPTH_STATE=1` | translated draws of slot 57 pipelines take their depth-stencil state and stencil reference from state block A instead of the desktop default (depth and stencil off); a refused block keeps the default. Off by default, then nothing changes: see [Shortcuts that are known to be wrong](#shortcuts-that-are-known-to-be-wrong) | | `X2W_PRESENT_SIGNATURE_EVERY=` | in render mode, samples a coarse signature of the presented picture every `n` presents from the start, without a script request (`0` off). Unset, sampling starts, every 4 presents, only once a script with a `wait` asks for it: see [Waiting for the presented picture](#waiting-for-the-presented-picture) | | `X2W_D3D12_DUMP_SURFACE=` | writes the last presented surface | +| `X2W_DEVICE_TYPE=` | with `X2W_RUNTIME_PROXY=1`, answers the title's reads of the OEM `ConsoleMode` registry value: `6` = 0x60 (Series S), `7` = 0x64 (Series X), `1` = value missing (PC); unset, the real registry answers. See [Console profile](#console-profile) | +| `X2W_PRESENT_PLANE=` | diagnostic, in render mode: the output window shows plane `n` of each present alone (plane 0 when `n` is past the count) instead of compositing every plane. See [Presented planes](#presented-planes) | | `X2W_HIDE_TITLE_WINDOW=1` (`run.sh --hide-title-window`) | once a present has reached the output window, hides the title's own window; dialogs stay visible, and the window is shown again when a present misses the output window, until the next present reaches it ([Output window and fallback diagnostics](#output-window-and-fallback-diagnostics)). Keyboard input to the title after the hide is not measured. Off by default on every host | | `X2W_DRAW_DUMP_FRAME=`, `X2W_DRAW_DUMP_DIR` | Full-resolution RGB snapshots of single-sample RGBA8/BGRA8 UNORM or sRGB targets after translated draws. A later present writes completed queue-fenced copies. At most 48 copies are pending or written; a copy whose fence reports device removal (`UINT64_MAX`) is released unwritten and frees its slot (`src/startup_stubs/draw_dump_tracking.h`, `ctest --preset dev --no-tests=error -R '^startup_dump_fence_(removed_control_)?warp$' -V`; the control must fail). | | `X2W_AUDIO_PERMISSIVE=1` | enables the audio stand-ins. Without a DSP provider, `XDspActivate` clears valid outputs and reports unavailable resources, and failed `XDspSubmitCommand` calls leave the sequence unchanged. `XDspDeactivate` and `XDspDisconnect` refuse null and unknown handles with `E_INVALIDARG`. | @@ -1384,6 +1406,36 @@ together under their original name. A 16-dword table load can contain two independent image descriptors at offsets 0 and 32 from the load address. For a read-only census of cached shader refusals, use `python -B tools/startup/gfx2hlsl.py --refusals [--json]` with a translator that supports the flag. Earlier versions treat it as `--pending` and write into the directory. See [Startup translator refusal census](experiments.md#startup-translator-refusal-census). +## Console profile + +`X2W_DEVICE_TYPE` answers the two registry reads a title makes of +`HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM\ConsoleMode` +(`src/startup_stubs/console_mode.h`, `registry_console_mode.inl`): with `X2W_RUNTIME_PROXY=1` the +stand-in rewrites the registry imports of the EXE and package helpers. `6` answers 0x60 (Series S), +`7` answers 0x64 (Series X) and `1` reports the value missing (PC); unset, every call goes to the real +registry. Opening the key and reading the value are logged a few times either way. What the values +mean on the console is taken from public notes, not measured here. +`ctest --preset dev --no-tests=error -R '^startup_console_mode(_control)?$'` runs it against fake +registry functions; the control leaves the switch unset for the answered cases and must print `FAIL:`. + +The Series S profile loads an upscaler package module that the other profiles do not. Three desktop +refusals stopped it; the stand-in now avoids each: + +- `Device::slot76` (Xbox order) is desktop `CreateCommittedResource` with seven arguments (heap + properties, heap flags, desc, initial state, clear value, riid, ppv). It shares the committed-resource + path of slot 127. +- A view description with `ViewDimension` 0 (UNKNOWN) makes desktop D3D12 remove the device. Measured: + the module makes such SRVs on 2D RGBA8 textures. Views of slots 18 to 21 with dimension 0 now get the + resource's default view (null description) where desktop allows one (not for buffers, typeless or + unknown formats, or depth formats in an SRV); otherwise the view is skipped and logged. A view whose + dimension does not fit the resource is skipped too (`src/startup_stubs/view_dimension.h`; + `ctest --preset dev --no-tests=error -R '^startup_view_dimension(_control)?$'`). +- `R9G9B9E5_SHAREDEXP` textures with unordered access fail with `E_INVALIDARG`; the + [shared-exponent stand-in](#shared-exponent-render-and-unordered-access-targets) covers them. + +With these, a Series S profile run reaches the same scripted point as the Series X and PC profiles. +That is a start-up milestone, not evidence that a title runs. + ## D3D12 resource budget Set `X2W_D3D12_BUDGET=1` before startup to add one `x2w-budget` line to each diff --git a/src/startup_stubs/console_mode.h b/src/startup_stubs/console_mode.h new file mode 100644 index 0000000000..7bc01ac3fd --- /dev/null +++ b/src/startup_stubs/console_mode.h @@ -0,0 +1,96 @@ +// Experimental (docs/startup-runtime.md): which console the title is told it runs on. +// +// Public GDK documentation describes XSystemGetDeviceType and the XSystemDeviceType values +// (Pc = 1, XboxScarlettLockhart = 6, XboxScarlettAnaconda = 7). The proxied runtime calls seen in +// startup runs include no device-type method. A public runtime reimplementation's notes +// (github.com/Marvisak/VIctory, facts only) say the value is not a runtime call: title code reads +// HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM, DWORD value ConsoleMode, where 0x60 is +// Series S, 0x64 is Series X and a missing value is a PC. Those three readings are that source's, +// not measured here. +// +// X2W_DEVICE_TYPE= (with X2W_RUNTIME_PROXY) answers that one value: 6 -> 0x60, 7 -> 0x64, +// 1 -> missing. Unset or any other number passes every read to the real registry. +// Pure helpers, no Windows calls, so a source-built control can check them. +#pragma once + +#include +#include + +namespace x2w_console_mode { + +constexpr long status_ok = 0, status_not_found = 2, status_invalid = 87, status_more_data = 234, status_wrong_type = 1630; +constexpr unsigned long type_dword = 4; +constexpr unsigned long rrf_rt_reg_dword = 0x10; +constexpr std::uint32_t series_s = 0x60, series_x = 0x64; + +inline wchar_t fold(wchar_t c) noexcept +{ + return (c >= L'A' && c <= L'Z') ? static_cast(c - L'A' + L'a') : c; +} + +inline bool equal_ci(const wchar_t* a, const wchar_t* b) noexcept +{ + if (!a || !b) return false; + for (;; ++a, ++b) { + if (fold(*a) != fold(*b)) return false; + if (!*a) return true; + } +} + +// Subkey of HKEY_LOCAL_MACHINE. One leading or trailing backslash is accepted. +inline bool is_oem_subkey(const wchar_t* subkey) noexcept +{ + static constexpr wchar_t expect[] = L"software\\microsoft\\windows nt\\currentversion\\oem"; + if (!subkey) return false; + if (*subkey == L'\\') ++subkey; + std::size_t i = 0; + for (; expect[i]; ++i) + if (fold(subkey[i]) != expect[i]) return false; + return !subkey[i] || (subkey[i] == L'\\' && !subkey[i + 1]); +} + +inline bool is_console_mode_value(const wchar_t* name) noexcept +{ + return equal_ci(name, L"ConsoleMode"); +} + +enum class Answer { pass, value, missing }; + +// device_set is false when X2W_DEVICE_TYPE is absent or not a number. +inline Answer answer_for(bool device_set, unsigned long device_type, std::uint32_t* mode) noexcept +{ + if (!device_set) return Answer::pass; + switch (device_type) { + case 1: return Answer::missing; + case 6: if (mode) *mode = series_s; return Answer::value; + case 7: if (mode) *mode = series_x; return Answer::value; + default: return Answer::pass; + } +} + +// RegQueryValueExW's output rules for one REG_DWORD. +inline long fill_query(std::uint32_t value, unsigned long* type, unsigned char* data, unsigned long* bytes) noexcept +{ + if (data && !bytes) return status_invalid; + if (type) *type = type_dword; + if (!data) { + if (bytes) *bytes = sizeof(value); + return status_ok; + } + if (*bytes < sizeof(value)) { + *bytes = sizeof(value); + return status_more_data; + } + for (std::size_t i = 0; i < sizeof(value); ++i) data[i] = static_cast(value >> (8 * i)); + *bytes = sizeof(value); + return status_ok; +} + +// RegGetValueW's: the flags must allow a DWORD (RRF_RT_REG_DWORD, part of RRF_RT_DWORD and RRF_RT_ANY). +inline long fill_get(unsigned long flags, std::uint32_t value, unsigned long* type, void* data, unsigned long* bytes) noexcept +{ + if (!(flags & rrf_rt_reg_dword)) return status_wrong_type; + return fill_query(value, type, static_cast(data), bytes); +} + +} // namespace x2w_console_mode diff --git a/src/startup_stubs/d3d12_present.inl b/src/startup_stubs/d3d12_present.inl index 58bec8cf4b..10d9a5f096 100644 --- a/src/startup_stubs/d3d12_present.inl +++ b/src/startup_stubs/d3d12_present.inl @@ -2,8 +2,8 @@ // Included inside d3d12_xs_device.cpp's anonymous namespace, before queue_present. // // A flip-model swap chain on the title window, created on the queue the title presents with; each -// present draws the presented surface into the back buffer with a full-window triangle (the surface -// is usually larger than the window) and flips. Diagnostics go to the window title, because GDI +// present draws the presented planes into the back buffer, bottom to top (present_planes.h), each +// with a full-window triangle (a surface is usually larger than the window), and flips. Diagnostics go to the window title, because GDI // drawing does not mix with a flip-model swap chain. struct WindowPresenter { @@ -14,13 +14,15 @@ struct WindowPresenter { ID3D12CommandAllocator* allocator = nullptr; ID3D12GraphicsCommandList* list = nullptr; ID3D12RootSignature* root = nullptr; - ID3D12PipelineState* pipeline = nullptr; + ID3D12PipelineState* pipeline = nullptr; // the bottom plane, opaque + ID3D12PipelineState* blend_pipeline = nullptr; // later planes, over it by their alpha ID3D12Fence* fence = nullptr; HANDLE reached = nullptr; UINT64 fence_value = 0; UINT width = 0, height = 0; bool failed = false; }; +constexpr UINT window_planes = 4; WindowPresenter window_presenter; LONG window_presents; @@ -124,7 +126,7 @@ bool create_window_presenter(ID3D12CommandQueue* queue, HWND window) if (chain1) chain1->Release(); if (factory) factory->Release(); const D3D12_DESCRIPTOR_HEAP_DESC target_heap{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 2, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; - const D3D12_DESCRIPTOR_HEAP_DESC texture_heap{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + const D3D12_DESCRIPTOR_HEAP_DESC texture_heap{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, window_planes, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; if (SUCCEEDED(hr)) hr = device->CreateDescriptorHeap(&target_heap, IID_PPV_ARGS(&p.targets)); if (SUCCEEDED(hr)) hr = device->CreateDescriptorHeap(&texture_heap, IID_PPV_ARGS(&p.textures)); const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); @@ -142,12 +144,15 @@ bool create_window_presenter(ID3D12CommandQueue* queue, HWND window) "Texture2D surface : register(t0); SamplerState smooth : register(s0);\n" "struct V { float4 position : SV_Position; float2 uv : TEXCOORD0; };\n" "V vs(uint id : SV_VertexID) { V o; o.uv = float2((id << 1) & 2, id & 2); o.position = float4(o.uv * float2(2, -2) + float2(-1, 1), 0, 1); return o; }\n" - "float4 ps(V i) : SV_Target0 { return float4(surface.Sample(smooth, i.uv).rgb, 1); }\n"; + "float4 ps(V i) : SV_Target0 { return float4(surface.Sample(smooth, i.uv).rgb, 1); }\n" + "float4 ps_over(V i) : SV_Target0 { return surface.Sample(smooth, i.uv); }\n"; ID3DBlob* vs = nullptr; ID3DBlob* ps = nullptr; + ID3DBlob* ps_over = nullptr; ID3DBlob* blob = nullptr; if (SUCCEEDED(hr)) hr = D3DCompile(source, sizeof(source) - 1, "present", nullptr, nullptr, "vs", "vs_5_0", 0, 0, &vs, nullptr); if (SUCCEEDED(hr)) hr = D3DCompile(source, sizeof(source) - 1, "present", nullptr, nullptr, "ps", "ps_5_0", 0, 0, &ps, nullptr); + if (SUCCEEDED(hr)) hr = D3DCompile(source, sizeof(source) - 1, "present", nullptr, nullptr, "ps_over", "ps_5_0", 0, 0, &ps_over, nullptr); if (SUCCEEDED(hr)) { const D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; D3D12_ROOT_PARAMETER parameter{}; @@ -177,29 +182,50 @@ bool create_window_presenter(ID3D12CommandQueue* queue, HWND window) desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; desc.SampleDesc.Count = 1; hr = device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&p.pipeline)); + if (SUCCEEDED(hr)) { + desc.PS = {ps_over->GetBufferPointer(), ps_over->GetBufferSize()}; + D3D12_RENDER_TARGET_BLEND_DESC& blend = desc.BlendState.RenderTarget[0]; + blend.BlendEnable = TRUE; + blend.SrcBlend = D3D12_BLEND_SRC_ALPHA; + blend.DestBlend = D3D12_BLEND_INV_SRC_ALPHA; + blend.BlendOp = D3D12_BLEND_OP_ADD; + blend.SrcBlendAlpha = D3D12_BLEND_ONE; + blend.DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA; + blend.BlendOpAlpha = D3D12_BLEND_OP_ADD; + hr = device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&p.blend_pipeline)); + } } if (vs) vs->Release(); if (ps) ps->Release(); + if (ps_over) ps_over->Release(); if (blob) blob->Release(); log("x2w-present window swap chain %ux%u -> 0x%08lx", p.width, p.height, static_cast(hr)); check_device("window presenter", 0); return SUCCEEDED(hr); } -// Draws `surface` (resting in COMMON) into the window and flips. Returns false if not shown. -bool present_to_window(ID3D12CommandQueue* queue, ID3D12Resource* surface) +// Whether the window presenter can draw `surface` (present_view_format.h); logs the first refusals. +bool presentable_surface(ID3D12Resource* surface) +{ + if (!surface) return false; + const D3D12_RESOURCE_DESC desc = surface->GetDesc(); + if (x2w_startup::present_surface_supported(desc)) return true; + static LONG refused; + if (first_calls(refused, 4)) + log("x2w-present surface dim=%d samples=%u flags=0x%x format=%d not supported (present_view_format.h)", + desc.Dimension, desc.SampleDesc.Count, desc.Flags, desc.Format); + return false; +} + +// Draws `count` surfaces (each resting in COMMON and presentable) into the window, in order: the +// first replaces the back buffer, each later one with blended[i] set is drawn over it by its alpha +// (present_planes.h composite_steps), then flips. Returns false if not shown. +bool present_to_window(ID3D12CommandQueue* queue, ID3D12Resource* const* surfaces, const bool* blended, UINT count) { X2W_ZONE("window present (blit + fence wait)"); WindowPresenter& p = window_presenter; - if (p.failed || !queue || !surface) return false; - const D3D12_RESOURCE_DESC desc = surface->GetDesc(); - if (!x2w_startup::present_surface_supported(desc)) { - static LONG refused; - if (first_calls(refused, 4)) - log("x2w-present surface dim=%d samples=%u flags=0x%x format=%d not supported (present_view_format.h)", - desc.Dimension, desc.SampleDesc.Count, desc.Flags, desc.Format); - return false; - } + if (p.failed || !queue || !surfaces || !count) return false; + if (count > window_planes) count = window_planes; HWND window = output_window(); if (!window) return false; if (!p.chain && !create_window_presenter(queue, window)) { @@ -207,31 +233,39 @@ bool present_to_window(ID3D12CommandQueue* queue, ID3D12Resource* surface) return false; } ID3D12Device* device = device_of(the_device); - const DXGI_FORMAT view_format = x2w_startup::present_view_format(desc.Format); - D3D12_SHADER_RESOURCE_VIEW_DESC view{}; - view.Format = view_format; - view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; - view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - view.Texture2D.MipLevels = 1; - device->CreateShaderResourceView(surface, &view, p.textures->GetCPUDescriptorHandleForHeapStart()); + const UINT texture_step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + for (UINT i = 0; i < count; ++i) { + D3D12_SHADER_RESOURCE_VIEW_DESC view{}; + view.Format = x2w_startup::present_view_format(surfaces[i]->GetDesc().Format); + view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + view.Texture2D.MipLevels = 1; + device->CreateShaderResourceView(surfaces[i], &view, + D3D12_CPU_DESCRIPTOR_HANDLE{p.textures->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T{i} * texture_step}); + } const UINT index = p.chain->GetCurrentBackBufferIndex(); const D3D12_CPU_DESCRIPTOR_HANDLE target{p.targets->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T{index} * device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV)}; if (FAILED(p.allocator->Reset()) || FAILED(p.list->Reset(p.allocator, p.pipeline))) return false; - transition(p.list, surface, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); + for (UINT i = 0; i < count; ++i) + transition(p.list, surfaces[i], D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); transition(p.list, p.buffers[index], D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET); const D3D12_VIEWPORT viewport{0, 0, static_cast(p.width), static_cast(p.height), 0, 1}; const D3D12_RECT scissor{0, 0, static_cast(p.width), static_cast(p.height)}; p.list->SetGraphicsRootSignature(p.root); p.list->SetDescriptorHeaps(1, &p.textures); - p.list->SetGraphicsRootDescriptorTable(0, p.textures->GetGPUDescriptorHandleForHeapStart()); p.list->RSSetViewports(1, &viewport); p.list->RSSetScissorRects(1, &scissor); p.list->OMSetRenderTargets(1, &target, FALSE, nullptr); p.list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - p.list->DrawInstanced(3, 1, 0, 0); + for (UINT i = 0; i < count; ++i) { + p.list->SetPipelineState(i && blended[i] ? p.blend_pipeline : p.pipeline); + p.list->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{p.textures->GetGPUDescriptorHandleForHeapStart().ptr + UINT64{i} * texture_step}); + p.list->DrawInstanced(3, 1, 0, 0); + } transition(p.list, p.buffers[index], D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT); - transition(p.list, surface, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COMMON); + for (UINT i = 0; i < count; ++i) + transition(p.list, surfaces[i], D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COMMON); if (FAILED(p.list->Close())) { p.failed = true; return false; diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 06a1eb1c16..0c6ce5907b 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -46,6 +46,8 @@ #include "startup_stubs/buffer_format_word3.h" #include "startup_stubs/memory_srv_buffer.h" #include "startup_stubs/single_element_srv.h" +#include "startup_stubs/view_dimension.h" +#include "startup_stubs/present_planes.h" #include "startup_stubs/list_copy.h" #include "startup_stubs/rect_indirect_args.h" #include "startup_stubs/profile_zone.h" @@ -866,8 +868,9 @@ __declspec(noinline) u64 create_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d, Kind kind = other_kind; if (SUCCEEDED(static_cast(result)) && iid && out && *out) { kind = kind_for(*iid); - if (Desc >= 0 && kind == resource_kind && requested_format != DXGI_FORMAT_UNKNOWN) + if (Desc >= 0 && kind == resource_kind && requested_format != DXGI_FORMAT_UNKNOWN) { x2w_startup::mark_packed_stand_in(static_cast(*out), requested_format); + } Wrapper* child = wrap(static_cast(*out), kind); if constexpr (K == device_kind && N == 27) { if (kind == resource_kind && args[0]) @@ -1835,7 +1838,7 @@ void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface) if (FAILED(readback->Map(0, &range, &mapped))) return; AcquireSRWLockExclusive(&shown_lock); shown_pixels.resize(shown_width * shown_height); - std::uint64_t sum = 0; + std::uint64_t sum = 0, alpha_sum = 0; for (int y = 0; y < shown_height; ++y) { const auto* row = static_cast(mapped) + footprint.Offset + static_cast(y) * desc.Height / shown_height * footprint.Footprint.RowPitch; @@ -1844,6 +1847,7 @@ void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface) const unsigned r = rgba ? texel[0] : texel[2], g = texel[1], b = rgba ? texel[2] : texel[0]; shown_pixels[y * shown_width + x] = (r << 16) | (g << 8) | b; sum += r + g + b; + alpha_sum += texel[3]; } } ReleaseSRWLockExclusive(&shown_lock); @@ -1876,8 +1880,9 @@ void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface) const D3D12_RANGE none{0, 0}; readback->Unmap(0, &none); const LONG count = InterlockedIncrement(&shown_frames); - std::snprintf(shown_note, sizeof(shown_note), "surface %llux%u format %d, readback %ld, mean level %.2f/255", - desc.Width, desc.Height, desc.Format, count, sum / (3.0 * shown_width * shown_height)); + std::snprintf(shown_note, sizeof(shown_note), "surface %llux%u format %d, readback %ld, mean level %.2f/255, mean alpha %.2f/255", + desc.Width, desc.Height, desc.Format, count, sum / (3.0 * shown_width * shown_height), + alpha_sum / (1.0 * shown_width * shown_height)); if ((count > 0 && count <= 3) || count % 40 == 0) log("x2w-render presented %s", shown_note); } @@ -4025,6 +4030,7 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) described_bytes, title_dest, args[D], materialized); }; const char* skip = nullptr; + bool default_view = false; if (N == 17) skip = "constant buffer view (title GPU address)"; if (N >= 18 && N <= 21 && args[0]) { const UINT flags = reinterpret_cast(args[0])->GetDesc().Flags; @@ -4032,6 +4038,32 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) if (N == 19 && !(flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) skip = "resource lacks unordered access"; if (N == 20 && !(flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) skip = "resource lacks render target"; if (N == 21 && !(flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) skip = "resource lacks depth stencil"; + // Every view description of slots 18-21 starts with Format, then ViewDimension. + const u64 described = N == 19 ? args[2] : args[1]; + UINT view_dimension = 0; + if (!skip && described && x2w_local::readable(reinterpret_cast(described), 8)) { + std::memcpy(&view_dimension, reinterpret_cast(described) + 4, sizeof(view_dimension)); + const D3D12_RESOURCE_DESC resource_desc = reinterpret_cast(args[0])->GetDesc(); + const auto dimension = static_cast(resource_desc.Dimension); + if (view_dimension == 0) { + // UNKNOWN: desktop refuses it; make the resource's default view where that is allowed. + if (x2w_view_dimension::default_view_allowed(N, dimension, static_cast(resource_desc.Format))) + default_view = true; + else + skip = "unknown view dimension, and the resource has no default view"; + static LONG unknown_dimension; + if (first_calls(unknown_dimension, 6)) + log("x2w-d3d12 Device::slot%d view dimension 0 (unknown), view format %u, resource dim=%u fmt=%d -> %s", N, + *reinterpret_cast(described), dimension, resource_desc.Format, + default_view ? "default view" : "skipped"); + } else if (!x2w_view_dimension::fits(N, view_dimension, dimension)) { + skip = "view dimension does not suit the resource"; + static LONG mismatched; + if (first_calls(mismatched, 6)) + log("x2w-d3d12 Device::slot%d view dimension %u needs resource dimension %u, resource has %u", N, view_dimension, + x2w_view_dimension::needed(N, view_dimension), dimension); + } + } } if (skip) { record_view(false); @@ -4084,6 +4116,8 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) *reinterpret_cast(b), null_rtv)) args[1] = reinterpret_cast(&null_rtv); } + if (default_view) args[desc_index] = 0; + const LONG removed_before = removal_reported; const u64 result = method_of(self->own().real, N)(self->own().real, args[0], args[1], args[2], args[3], 0, 0, 0, 0); // A desktop view creation returns void, so the only failure it reports is a removed device. Only a created view // may keep the resource: on failure the slot is recorded unmaterialized, which releases the slot's previous view @@ -4100,6 +4134,19 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) if ((N == 20 || N == 21) && args[0] && created) note_view_target(args[D], reinterpret_cast(args[0]), N); check_device("Device view", N); + if (!removed_before && removal_reported && N >= 18 && N <= 21) { + // The view that removed the device: its forwarded description and the resource's shape. + char bytes[3 * 40 + 1] = {}; + const u64 described = args[desc_index]; + if (described) hex_text(reinterpret_cast(described), 40, bytes, sizeof(bytes)); + log("x2w-d3d12 Device::slot%d removing view desc %s", N, described ? bytes : "(null)"); + if (args[0]) { + const D3D12_RESOURCE_DESC rd = reinterpret_cast(args[0])->GetDesc(); + log("x2w-d3d12 Device::slot%d removing view resource: dim=%d %llux%u depth/array=%u mips=%u fmt=%d samples=%u flags=0x%x", N, + rd.Dimension, static_cast(rd.Width), rd.Height, rd.DepthOrArraySize, rd.MipLevels, rd.Format, + rd.SampleDesc.Count, static_cast(rd.Flags)); + } + } static LONG calls; if (first_calls(calls)) log("x2w-d3d12 Device::slot%d view(0x%llx, 0x%llx, 0x%llx, 0x%llx) dest 0x%llx -> 0x%llx", N, a, b, c, d, @@ -5517,10 +5564,10 @@ HRESULT __stdcall device_create_derived_pipeline(Wrapper*, void* base, UINT coun // COMMON, GENERIC_READ on an upload heap and COPY_DEST on a readback heap (the initial states D3D12 // requires there; the Windows 10 runtime refuses COMMON with E_INVALIDARG). When desktop rejects the // clear value it is retried without one. -HRESULT __stdcall device_create_committed_x(Wrapper* self, const D3D12_HEAP_PROPERTIES* props, UINT heap_flags, - const D3D12_RESOURCE_DESC* desc, UINT state, const D3D12_CLEAR_VALUE* clear, - void* session, UINT castable_count, const void* castable, const GUID* iid, - void** out) +// Slot 76 shares the work with the slot number in the log line. +HRESULT create_committed(int slot, Wrapper* self, const D3D12_HEAP_PROPERTIES* props, UINT heap_flags, + const D3D12_RESOURCE_DESC* desc, UINT state, const D3D12_CLEAR_VALUE* clear, void* session, + UINT castable_count, const void* castable, const GUID* iid, void** out) { char text[48]; guid_text(iid, text, sizeof(text)); @@ -5529,7 +5576,7 @@ HRESULT __stdcall device_create_committed_x(Wrapper* self, const D3D12_HEAP_PROP const D3D12_RESOURCE_DESC copy = sanitized(*desc); const auto flags = static_cast(heap_flags); const D3D12_RESOURCE_ALLOCATION_INFO info = device_of(self)->GetResourceAllocationInfo(0, 1, ©); - check_device("Device before slot", 127); + check_device("Device before slot", slot); void* const title_memory = info.SizeInBytes != ~0ull ? title_resource_memory(info.SizeInBytes, info.Alignment) : nullptr; ID3D12Resource* resource = nullptr; const D3D12_RESOURCE_STATES initial = props->Type == D3D12_HEAP_TYPE_UPLOAD ? D3D12_RESOURCE_STATE_GENERIC_READ @@ -5547,8 +5594,9 @@ HRESULT __stdcall device_create_committed_x(Wrapper* self, const D3D12_HEAP_PROP } static LONG calls; if (first_calls(calls, 12)) - log("x2w-d3d12 Device::slot127(CreateCommittedResource3?) heap=%d flags=0x%x dim=%d %llux%u fmt=%d rflags=0x%x " - "state=0x%x clear=%p%s session=%p castable=%u/%p riid=%s -> 0x%08lx", props->Type, heap_flags, desc->Dimension, + log("x2w-d3d12 Device::slot%d(%s) heap=%d flags=0x%x dim=%d %llux%u fmt=%d rflags=0x%x " + "state=0x%x clear=%p%s session=%p castable=%u/%p riid=%s -> 0x%08lx", slot, + slot == 76 ? "CreateCommittedResource" : "CreateCommittedResource3?", props->Type, heap_flags, desc->Dimension, desc->Width, desc->Height, desc->Format, desc->Flags, state, static_cast(clear), clear && !cleared ? "(dropped)" : "", session, castable_count, castable, text, static_cast(hr)); if (FAILED(hr)) return hr; @@ -5562,6 +5610,25 @@ HRESULT __stdcall device_create_committed_x(Wrapper* self, const D3D12_HEAP_PROP return S_OK; } +HRESULT __stdcall device_create_committed_x(Wrapper* self, const D3D12_HEAP_PROPERTIES* props, UINT heap_flags, + const D3D12_RESOURCE_DESC* desc, UINT state, const D3D12_CLEAR_VALUE* clear, + void* session, UINT castable_count, const void* castable, const GUID* iid, + void** out) +{ + return create_committed(127, self, props, heap_flags, desc, state, clear, session, castable_count, castable, iid, out); +} + +// Device slot 76 (Xbox order, +0x260): the seven arguments of desktop CreateCommittedResource +// (heap properties, heap flags, desc, initial state, clear value, riid, ppv). Seen from an upscaler +// package module that runs only on the lower-resolution console profile (X2W_DEVICE_TYPE=6). +// Same desktop creation as slot 127. +HRESULT __stdcall device_create_committed(Wrapper* self, const D3D12_HEAP_PROPERTIES* props, UINT heap_flags, + const D3D12_RESOURCE_DESC* desc, UINT state, const D3D12_CLEAR_VALUE* clear, + const GUID* iid, void** out) +{ + return create_committed(76, self, props, heap_flags, desc, state, clear, nullptr, 0, nullptr, iid, out); +} + // Device slot 80 (Xbox order): (type, timeout, 0, flags, &token) -> HRESULT, the frame-event wait // that hands out a frame token (called with type 2 / timeout -1 and type 0 / timeout 0, flags 0/2). // Paces to the interval from slot 78 (33.3 ms by default) and returns increasing tokens. @@ -5754,6 +5821,63 @@ void report_budget(ID3D12CommandQueue* queue) // Queue slot 32 (Xbox order): (plane count, plane parameters*, present parameters*) -> HRESULT, the // console present. Nothing is shown yet; frames are counted and a heartbeat is logged. +// The planes of a present, resolved to real resources the window presenter can draw. +// X2W_PRESENT_PLANE= (diagnostic) keeps plane n alone (plane 0 when n is past the count); +// otherwise every plane is kept and the window composites them (present_planes.h). +struct PresentedPlanes { + Wrapper* surfaces[window_planes] = {}; + x2w_startup::PlaneStep steps[window_planes]; + unsigned count = 0; // composite steps + // The topmost composited plane's surface (the one shown and read back for diagnostics). + Wrapper* top() const { return count ? surfaces[steps[count - 1].plane] : nullptr; } +}; +PresentedPlanes presented_planes(UINT planes, const void* plane_parameters) +{ + static const long wanted = [] { + char value[16]{}; + return GetEnvironmentVariableA("X2W_PRESENT_PLANE", value, sizeof(value)) ? std::atol(value) : -1L; + }(); + const auto readable = [](const void* address, std::size_t bytes) { return x2w_local::readable(address, bytes); }; + PresentedPlanes out; + std::uint64_t shown[window_planes] = {}; + const unsigned total = planes < window_planes ? planes : window_planes; + const unsigned only = wanted >= 0 ? (static_cast(wanted) < planes ? static_cast(wanted) : 0u) : ~0u; + for (unsigned i = 0; i < total; ++i) { + if (only != ~0u && i != only) continue; + const std::uint64_t resource = x2w_startup::present_plane_resource(plane_parameters, planes, i, readable); + Wrapper* const surface = resource ? as_wrapper(reinterpret_cast(resource)) : nullptr; + if (!surface || surface->own().kind != resource_kind || !surface->own().real) continue; + out.surfaces[i] = surface; + if (presentable_surface(static_cast(surface->own().real))) shown[i] = resource; + } + out.count = x2w_startup::composite_steps(shown, total, out.steps, window_planes); + // A known surface the window cannot draw is still the one reported and read back. + if (!out.count) + for (unsigned i = 0; i < total && !out.count; ++i) + if (out.surfaces[i]) out.steps[out.count++] = x2w_startup::PlaneStep{i, false}; + return out; +} + +// The first presents and every 300th: each plane's first resource and its shape. +void log_present_planes(LONG frame, UINT planes, const void* plane_parameters) +{ + if (frame > 2 && frame % 300 != 0) return; + static LONG lines; + if (!first_calls(lines, 24)) return; + const auto readable = [](const void* address, std::size_t bytes) { return x2w_local::readable(address, bytes); }; + for (unsigned i = 0; i < planes && i < 4; ++i) { + const std::uint64_t resource = x2w_startup::present_plane_resource(plane_parameters, planes, i, readable); + Wrapper* const surface = resource ? as_wrapper(reinterpret_cast(resource)) : nullptr; + if (!surface || surface->own().kind != resource_kind || !surface->own().real) { + log("x2w-present frame %ld plane %u/%u: resource %p is not a known resource", frame, i, planes, reinterpret_cast(resource)); + continue; + } + const D3D12_RESOURCE_DESC desc = static_cast(surface->own().real)->GetDesc(); + log("x2w-present frame %ld plane %u/%u: %llux%u format %d flags=0x%x", frame, i, planes, + static_cast(desc.Width), desc.Height, desc.Format, static_cast(desc.Flags)); + } +} + HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_parameters, const void* present_parameters) { // First, before anything reads or copies the surface: a presented resource keeps its old lifetime. @@ -5787,17 +5911,27 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa } } bool shown_in_window = false; + log_present_planes(frame, planes, plane_parameters); + const PresentedPlanes presented = presented_planes(planes, plane_parameters); { - Wrapper* surface = nullptr; - const auto* words = static_cast(plane_parameters); - if (planes && words && x2w_local::readable(words, 0x18) && words[1] >= 1 && x2w_local::readable(reinterpret_cast(words[2]), 8)) - surface = as_wrapper(*reinterpret_cast(words[2])); + Wrapper* const surface = presented.top(); capture::present(frame, surface); if (surface && surface->own().kind == resource_kind) red_producers().present(static_cast(surface->own().real)); - // Render mode: the presented surface goes to the title's window through a swap chain. - if (render_mode() && surface && surface->own().kind == resource_kind && surface->own().real) - shown_in_window = present_to_window(static_cast(self->own().real), static_cast(surface->own().real)); + // Render mode: the presented planes go to the output window through a swap chain. + if (render_mode() && surface) { + ID3D12Resource* drawn[window_planes] = {}; + bool blended[window_planes] = {}; + UINT drawn_count = 0; + for (unsigned i = 0; i < presented.count; ++i) { + auto* const resource = static_cast(presented.surfaces[presented.steps[i].plane]->own().real); + if (!presentable_surface(resource)) continue; + blended[drawn_count] = presented.steps[i].blended; + drawn[drawn_count++] = resource; + } + if (drawn_count) + shown_in_window = present_to_window(static_cast(self->own().real), drawn, blended, drawn_count); + } InterlockedExchange(&last_frame_shown, shown_in_window ? 1 : 0); if (render_mode()) present_signature(self, surface, frame); } @@ -5810,16 +5944,12 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa log("x2w-d3d12 CommandQueue::slot32(present) planes=%u plane=[%s] present=[%s]", planes, a, b); } if (render_mode() && frame % (shown_in_window ? 60 : 6) == 0 && planes && plane_parameters) { - // Plane parameters: +0x00 frame token, +0x08 resource count, +0x10 pointer to the resources. - const auto* words = static_cast(plane_parameters); - if (x2w_local::readable(words, 0x18) && words[1] >= 1 && x2w_local::readable(reinterpret_cast(words[2]), 8)) { - Wrapper* surface = as_wrapper(*reinterpret_cast(words[2])); - if (surface && surface->own().kind == resource_kind && surface->own().real) - read_back_presented(static_cast(self->own().real), static_cast(surface->own().real)); - else - std::snprintf(shown_note, sizeof(shown_note), "presented object %p is not a known resource", - *reinterpret_cast(words[2])); - } + // Plane records: present_planes.h. + Wrapper* const surface = presented.top(); + if (surface) + read_back_presented(static_cast(self->own().real), static_cast(surface->own().real)); + else + std::snprintf(shown_note, sizeof(shown_note), "presented plane has no known resource"); } if (shown_in_window) { if (frame % 30 == 0) { @@ -6012,6 +6142,7 @@ void build_tables() tables[device_kind][48] = reinterpret_cast(&device_create_command_queue_x); tables[device_kind][70] = reinterpret_cast(&device_memory_srv); tables[device_kind][73] = reinterpret_cast(&device_create_command_list_x); + tables[device_kind][76] = reinterpret_cast(&device_create_committed); tables[device_kind][78] = reinterpret_cast(&device_frame_interval); tables[device_kind][79] = reinterpret_cast(&device_frame_event); tables[device_kind][80] = reinterpret_cast(&device_wait_frame_event); diff --git a/src/startup_stubs/present_planes.h b/src/startup_stubs/present_planes.h new file mode 100644 index 0000000000..0c71c7ac1d --- /dev/null +++ b/src/startup_stubs/present_planes.h @@ -0,0 +1,61 @@ +// Experimental (docs/startup-runtime.md): the planes of a console present (CommandQueue slot 32). +// +// The present takes a plane count and an array of plane records. Measured from the first presents +// of a console executable: one record is 0x48 bytes, with +0x00 a frame token, +0x08 the resource +// count and +0x10 a pointer to the array of resources; the second plane's token sits at +0x48 when +// two planes are presented. The fields after +0x10 (source and destination rectangles, flags) are +// not decoded here. Pure: the caller passes a readability check, so a control can run it on +// synthetic records. +#pragma once + +#include +#include +#include + +namespace x2w_startup { +inline constexpr std::size_t present_plane_stride = 0x48; + +// The first resource of plane `index`, or 0 when the plane, its record or its resource array is +// not readable or has no resource. readable(address, bytes) answers whether memory can be read. +template +std::uint64_t present_plane_resource(const void* planes, unsigned count, unsigned index, Readable&& readable, + std::size_t stride = present_plane_stride) +{ + if (!planes || index >= count) return 0; + const auto* record = static_cast(planes) + std::size_t{index} * stride; + if (!readable(record, 0x18)) return 0; + std::uint64_t resources = 0, resource_count = 0, first = 0; + std::memcpy(&resource_count, record + 0x08, 8); + std::memcpy(&resources, record + 0x10, 8); + if (resource_count == 0 || !resources || !readable(reinterpret_cast(resources), 8)) return 0; + std::memcpy(&first, reinterpret_cast(resources), 8); + return first; +} + +// One draw of the window composite: plane `plane`, either replacing what is below (the bottom +// layer) or blended over it by the plane's own alpha. +struct PlaneStep { + unsigned plane = 0; + bool blended = false; +}; + +// The window composite of a present, bottom to top, the way planes stack on the console: plane 0 +// first, each later plane over it. `resources[i]` is plane i's surface, 0 when it cannot be shown; +// those planes and repeats of a surface already drawn are left out. The lowest drawn plane is +// opaque (nothing is below it), every later one blended. Returns the number of steps written. +// Measured on a two-plane present: plane 0 was black and plane 1, with alpha 255 wherever the +// picture was, held it; showing plane 0 alone gave a black window. +inline unsigned composite_steps(const std::uint64_t* resources, unsigned count, PlaneStep* steps, unsigned max_steps) +{ + unsigned written = 0; + for (unsigned i = 0; resources && i < count && written < max_steps; ++i) { + if (!resources[i]) continue; + bool repeat = false; + for (unsigned j = 0; j < written; ++j) repeat = repeat || resources[steps[j].plane] == resources[i]; + if (repeat) continue; + steps[written] = PlaneStep{i, written != 0}; + ++written; + } + return written; +} +} // namespace x2w_startup diff --git a/src/startup_stubs/registry_console_mode.inl b/src/startup_stubs/registry_console_mode.inl new file mode 100644 index 0000000000..c0c95d96f7 --- /dev/null +++ b/src/startup_stubs/registry_console_mode.inl @@ -0,0 +1,227 @@ +// Experimental (docs/startup-runtime.md): registry reads of the console mode (see console_mode.h). +// Included inside runtime_proxy.cpp's anonymous namespace, and on its own by +// tests/startup_console_mode_check.cpp. Needs , , local_log.h, +// runtime_gpa_patch.h and console_mode.h. +// +// With X2W_RUNTIME_PROXY the stand-in rewrites five registry imports of the EXE and package helpers +// (regular IAT and GetProcAddress by name). Every call goes to the real function except a read of +// ConsoleMode under HKLM\...\OEM while X2W_DEVICE_TYPE names a known console. Opening the OEM +// key and reading the value are logged a few times in either case, so a run shows whether the +// title asks at all. + +enum RegistryImport { reg_open_key_ex_w, reg_open_key_w, reg_query_value_ex_w, reg_get_value_w, reg_close_key, registry_imports }; +constexpr const char* registry_import_names[registry_imports] = {"RegOpenKeyExW", "RegOpenKeyW", "RegQueryValueExW", "RegGetValueW", + "RegCloseKey"}; +using RegOpenKeyExWFn = LSTATUS(WINAPI*)(HKEY, LPCWSTR, DWORD, REGSAM, PHKEY); +using RegOpenKeyWFn = LSTATUS(WINAPI*)(HKEY, LPCWSTR, PHKEY); +using RegQueryValueExWFn = LSTATUS(WINAPI*)(HKEY, LPCWSTR, LPDWORD, LPDWORD, LPBYTE, LPDWORD); +using RegGetValueWFn = LSTATUS(WINAPI*)(HKEY, LPCWSTR, LPCWSTR, DWORD, LPDWORD, PVOID, LPDWORD); +using RegCloseKeyFn = LSTATUS(WINAPI*)(HKEY); + +std::atomic real_registry[registry_imports]; + +int registry_import_index(const char* name) noexcept +{ + if (!name) return -1; + for (int i = 0; i < registry_imports; ++i) + if (std::strcmp(name, registry_import_names[i]) == 0) return i; + return -1; +} + +// ---- OEM key handles the title opened ----------------------------------------------------------- +SRWLOCK oem_lock = SRWLOCK_INIT; +HKEY oem_keys[16]; + +void track_oem(HKEY key) noexcept +{ + AcquireSRWLockExclusive(&oem_lock); + for (HKEY& slot : oem_keys) { + if (!slot) { + slot = key; + break; + } + } + ReleaseSRWLockExclusive(&oem_lock); +} + +bool oem_key(HKEY key) noexcept +{ + if (!key) return false; + AcquireSRWLockShared(&oem_lock); + bool found = false; + for (HKEY slot : oem_keys) found = found || slot == key; + ReleaseSRWLockShared(&oem_lock); + return found; +} + +void untrack_oem(HKEY key) noexcept +{ + AcquireSRWLockExclusive(&oem_lock); + for (HKEY& slot : oem_keys) + if (slot == key) slot = nullptr; + ReleaseSRWLockExclusive(&oem_lock); +} + +// ---- the answer --------------------------------------------------------------------------------- +x2w_console_mode::Answer console_answer(std::uint32_t* mode, unsigned long* device) noexcept +{ + const DWORD saved = GetLastError(); + char text[16]{}; + const DWORD length = GetEnvironmentVariableA("X2W_DEVICE_TYPE", text, sizeof(text)); + SetLastError(saved); + char* end = nullptr; + const unsigned long value = length && length < sizeof(text) ? std::strtoul(text, &end, 0) : 0; + const bool set = length && length < sizeof(text) && end && end != text && !*end; + *device = value; + return x2w_console_mode::answer_for(set, value, mode); +} + +void note_oem_open(const char* via, LSTATUS status) noexcept +{ + static volatile LONG logged; + if (x2w_local::first_calls(logged, 4)) + x2w_local::logf("x2w-runtime console mode: %s opened the OEM key, real status %ld", via, static_cast(status)); +} + +// One line per read (the first eight): what was answered, and the real status or value when passed on. +void note_console_read(const char* via, x2w_console_mode::Answer answer, unsigned long device, std::uint32_t value, LSTATUS status) noexcept +{ + static volatile LONG logged; + if (!x2w_local::first_calls(logged, 8)) return; + if (answer == x2w_console_mode::Answer::value) + x2w_local::logf("x2w-runtime console mode: %s ConsoleMode -> 0x%x for X2W_DEVICE_TYPE=%lu, status %ld", via, value, device, + static_cast(status)); + else if (answer == x2w_console_mode::Answer::missing) + x2w_local::logf("x2w-runtime console mode: %s ConsoleMode -> missing (PC) for X2W_DEVICE_TYPE=%lu", via, device); + else if (status == ERROR_SUCCESS) + x2w_local::logf("x2w-runtime console mode: %s ConsoleMode passed through -> 0x%x", via, value); + else + x2w_local::logf("x2w-runtime console mode: %s ConsoleMode passed through -> status %ld", via, static_cast(status)); +} + +template +Fn real_reg(RegistryImport which) noexcept +{ + return reinterpret_cast(real_registry[which].load(std::memory_order_acquire)); +} + +LSTATUS WINAPI hooked_reg_open_key_ex_w(HKEY root, LPCWSTR subkey, DWORD options, REGSAM access, PHKEY out) +{ + const auto real = real_reg(reg_open_key_ex_w); + if (!real) return ERROR_PROC_NOT_FOUND; + const LSTATUS status = real(root, subkey, options, access, out); + if (root == HKEY_LOCAL_MACHINE && x2w_console_mode::is_oem_subkey(subkey)) { + note_oem_open("RegOpenKeyExW", status); + if (status == ERROR_SUCCESS && out) track_oem(*out); + } + return status; +} + +LSTATUS WINAPI hooked_reg_open_key_w(HKEY root, LPCWSTR subkey, PHKEY out) +{ + const auto real = real_reg(reg_open_key_w); + if (!real) return ERROR_PROC_NOT_FOUND; + const LSTATUS status = real(root, subkey, out); + if (root == HKEY_LOCAL_MACHINE && x2w_console_mode::is_oem_subkey(subkey)) { + note_oem_open("RegOpenKeyW", status); + if (status == ERROR_SUCCESS && out) track_oem(*out); + } + return status; +} + +std::uint32_t dword_read(LSTATUS status, const void* data, const DWORD* bytes) noexcept +{ + std::uint32_t value = 0; + if (status == ERROR_SUCCESS && data && bytes && *bytes >= sizeof(value)) std::memcpy(&value, data, sizeof(value)); + return value; +} + +LSTATUS WINAPI hooked_reg_query_value_ex_w(HKEY key, LPCWSTR name, LPDWORD reserved, LPDWORD type, LPBYTE data, LPDWORD bytes) +{ + const auto real = real_reg(reg_query_value_ex_w); + if (!x2w_console_mode::is_console_mode_value(name) || !oem_key(key)) + return real ? real(key, name, reserved, type, data, bytes) : ERROR_PROC_NOT_FOUND; + std::uint32_t mode = 0; + unsigned long device = 0; + const auto answer = console_answer(&mode, &device); + LSTATUS status = ERROR_FILE_NOT_FOUND; + if (answer == x2w_console_mode::Answer::value) + status = x2w_console_mode::fill_query(mode, reinterpret_cast(type), data, reinterpret_cast(bytes)); + else if (answer == x2w_console_mode::Answer::pass) + status = real ? real(key, name, reserved, type, data, bytes) : ERROR_PROC_NOT_FOUND; + note_console_read("RegQueryValueExW", answer, device, answer == x2w_console_mode::Answer::value ? mode : dword_read(status, data, bytes), status); + return status; +} + +LSTATUS WINAPI hooked_reg_get_value_w(HKEY key, LPCWSTR subkey, LPCWSTR name, DWORD flags, LPDWORD type, PVOID data, LPDWORD bytes) +{ + const auto real = real_reg(reg_get_value_w); + const bool oem = (key == HKEY_LOCAL_MACHINE && x2w_console_mode::is_oem_subkey(subkey)) || (oem_key(key) && (!subkey || !*subkey)); + if (!oem || !x2w_console_mode::is_console_mode_value(name)) + return real ? real(key, subkey, name, flags, type, data, bytes) : ERROR_PROC_NOT_FOUND; + std::uint32_t mode = 0; + unsigned long device = 0; + const auto answer = console_answer(&mode, &device); + LSTATUS status = ERROR_FILE_NOT_FOUND; + if (answer == x2w_console_mode::Answer::value) + status = x2w_console_mode::fill_get(flags, mode, reinterpret_cast(type), data, reinterpret_cast(bytes)); + else if (answer == x2w_console_mode::Answer::pass) + status = real ? real(key, subkey, name, flags, type, data, bytes) : ERROR_PROC_NOT_FOUND; + note_console_read("RegGetValueW", answer, device, answer == x2w_console_mode::Answer::value ? mode : dword_read(status, data, bytes), status); + return status; +} + +LSTATUS WINAPI hooked_reg_close_key(HKEY key) +{ + const auto real = real_reg(reg_close_key); + untrack_oem(key); + return real ? real(key) : ERROR_PROC_NOT_FOUND; +} + +void* const registry_hooks[registry_imports] = { + reinterpret_cast(&hooked_reg_open_key_ex_w), reinterpret_cast(&hooked_reg_open_key_w), + reinterpret_cast(&hooked_reg_query_value_ex_w), reinterpret_cast(&hooked_reg_get_value_w), + reinterpret_cast(&hooked_reg_close_key)}; + +// Keep the first real address for each import; never one of the hooks themselves. +bool remember_registry(int which, void* real) noexcept +{ + if (which < 0 || which >= registry_imports || !real) return false; + for (void* hook : registry_hooks) + if (real == hook) return false; + void* expected = nullptr; + real_registry[which].compare_exchange_strong(expected, real, std::memory_order_acq_rel); + return true; +} + +// GetProcAddress by name: the hook for a registry import, or null for any other name. +FARPROC registry_hook_for(LPCSTR name, FARPROC real) noexcept +{ + const int which = registry_import_index(name); + if (which < 0 || !remember_registry(which, reinterpret_cast(real))) return nullptr; + return reinterpret_cast(registry_hooks[which]); +} + +// Rewrite one image's regular registry IAT slots. Delay-import slots hold a thunk and are left alone. +int patch_registry_imports(unsigned char* base, std::size_t image_size) noexcept +{ + int patched = 0; + const auto classify = [](const char*, const char* name, x2w_runtime_patch::Kind* kind) { + if (registry_import_index(name) < 0) return false; + *kind = x2w_runtime_patch::Kind::registry; + return true; + }; + x2w_runtime_patch::visit_imports_with(base, image_size, classify, [&](const x2w_runtime_patch::Hit& hit) { + if (hit.delay_import) return; + const int which = registry_import_index(hit.import_name); + auto* slot = reinterpret_cast(base + hit.first_thunk_rva); + if (*slot == reinterpret_cast(registry_hooks[which])) return; + if (!remember_registry(which, reinterpret_cast(*slot))) return; + DWORD old = 0; + if (!VirtualProtect(slot, 8, PAGE_READWRITE, &old)) return; + *slot = reinterpret_cast(registry_hooks[which]); + VirtualProtect(slot, 8, old, &old); + ++patched; + }); + return patched; +} diff --git a/src/startup_stubs/runtime_gpa_patch.h b/src/startup_stubs/runtime_gpa_patch.h index e5b23da826..b9dd8a4d09 100644 --- a/src/startup_stubs/runtime_gpa_patch.h +++ b/src/startup_stubs/runtime_gpa_patch.h @@ -16,7 +16,8 @@ namespace x2w_runtime_patch { -enum class Kind : unsigned char { get_proc_address = 1, query_api_impl = 2 }; +// registry: one of the registry imports named by console_mode.h (classified by its own caller). +enum class Kind : unsigned char { get_proc_address = 1, query_api_impl = 2, registry = 3 }; struct Hit { Kind kind; @@ -113,9 +114,9 @@ inline bool c_string_in_image(const unsigned char* base, std::size_t image_size, return false; } -template +template int visit_named_thunks(const unsigned char* base, std::size_t image_size, const char* dll, std::uint32_t name_table_rva, - std::uint32_t iat_rva, bool delay_import, Fn on_hit) + std::uint32_t iat_rva, bool delay_import, Classify classify, Fn on_hit) { int hits = 0; for (std::uint32_t ti = 0;; ++ti) { @@ -139,10 +140,11 @@ int visit_named_thunks(const unsigned char* base, std::size_t image_size, const return hits; } -// Walk a PE image's import and delay-import tables. Invokes `on_hit(Hit)` for each classified import. -// Returns the number of hits. Malformed images stop the walk and return what was found. -template -int visit_imports(const unsigned char* base, std::size_t image_size, Fn on_hit) +// Walk a PE image's import and delay-import tables. Invokes `on_hit(Hit)` for each import that +// `classify(dll, name, &kind)` accepts. Returns the number of hits. Malformed images stop the walk +// and return what was found. +template +int visit_imports_with(const unsigned char* base, std::size_t image_size, Classify classify, Fn on_hit) { if (!readable_range(base, image_size, 0, sizeof(DosStub))) return 0; const auto* dos = reinterpret_cast(base); @@ -167,7 +169,7 @@ int visit_imports(const unsigned char* base, std::size_t image_size, Fn on_hit) if (!imp->name || !imp->original_first_thunk || !imp->first_thunk) continue; if (!c_string_in_image(base, image_size, imp->name)) continue; const char* dll = reinterpret_cast(base + imp->name); - hits += visit_named_thunks(base, image_size, dll, imp->original_first_thunk, imp->first_thunk, false, on_hit); + hits += visit_named_thunks(base, image_size, dll, imp->original_first_thunk, imp->first_thunk, false, classify, on_hit); } } @@ -181,10 +183,18 @@ int visit_imports(const unsigned char* base, std::size_t image_size, Fn on_hit) if (!delay->dll_name || !delay->original_first_thunk || !delay->first_thunk) continue; if (!c_string_in_image(base, image_size, delay->dll_name)) continue; const char* dll = reinterpret_cast(base + delay->dll_name); - hits += visit_named_thunks(base, image_size, dll, delay->original_first_thunk, delay->first_thunk, true, on_hit); + hits += visit_named_thunks(base, image_size, dll, delay->original_first_thunk, delay->first_thunk, true, classify, on_hit); } } return hits; } +// The runtime proxy's own imports: GetProcAddress from any module, QueryApiImpl from xgameruntime.dll. +template +int visit_imports(const unsigned char* base, std::size_t image_size, Fn on_hit) +{ + return visit_imports_with(base, image_size, [](const char* dll, const char* name, Kind* kind) { return classify(dll, name, kind); }, + on_hit); +} + } // namespace x2w_runtime_patch diff --git a/src/startup_stubs/runtime_proxy.cpp b/src/startup_stubs/runtime_proxy.cpp index 7c9a170462..3774a12203 100644 --- a/src/startup_stubs/runtime_proxy.cpp +++ b/src/startup_stubs/runtime_proxy.cpp @@ -14,6 +14,7 @@ // X2W_FAKE_USER=1 additionally answers the user API for one local user (see fake_user below) // and, while the proxy is on, XStoreCreateContext for that user (see area_call). #include "startup_stubs/api_trace.h" +#include "startup_stubs/console_mode.h" #include "startup_stubs/local_log.h" #include "startup_stubs/runtime_gpa_patch.h" #include "startup_stubs/save_blob_pack.h" @@ -484,12 +485,15 @@ bool module_is_exe_or_package_helper(HMODULE module) noexcept return true; } +#include "startup_stubs/registry_console_mode.inl" + FARPROC WINAPI hooked_get_proc_address(HMODULE module, LPCSTR name) { const FARPROC real = GetProcAddress(module, name); if (real && reinterpret_cast(name) > 0xffff) { static LONG logged; if (x2w_local::first_calls(logged, 40)) x2w_local::logf("x2w-runtime GetProcAddress(%p, \"%s\") -> %p", static_cast(module), name, static_cast(real)); + if (const FARPROC hook = registry_hook_for(name, real)) return hook; // Wrap gaming-runtime exports only when the provider module is xgameruntime.dll. if (module_is_xgameruntime(module) && std::strcmp(name, "QueryApiImpl") == 0 && remember_real_query(reinterpret_cast(real))) @@ -555,6 +559,13 @@ int patch_module(HMODULE module) } VirtualProtect(slot, 8, old, &old); }); + // Registry imports for the console mode (registry_console_mode.inl), counted on their own line. + if (!self) { + const int registry = patch_registry_imports(base, image_size); + if (registry > 0) + x2w_local::logf("x2w-runtime console mode: %d registry import(s) patched in the %s", registry, + module == GetModuleHandleW(nullptr) ? "main module" : "package module"); + } return patched; } diff --git a/src/startup_stubs/view_dimension.h b/src/startup_stubs/view_dimension.h new file mode 100644 index 0000000000..59f6b3684e --- /dev/null +++ b/src/startup_stubs/view_dimension.h @@ -0,0 +1,80 @@ +// Experimental (docs/startup-runtime.md): whether a view description's ViewDimension suits the +// resource it is made on. Desktop D3D12 removes the device (DXGI_ERROR_INVALID_CALL, debug-layer +// message "The ViewDimension in the View Desc is incompatible with the type of the Resource") +// instead of failing the call, so the stand-in checks first and skips such a view with a log. +// Values are the public d3d12.h enumerations. Pure, no Windows calls, so a control can check it. +#pragma once + +namespace x2w_view_dimension { + +enum ResourceDimension : unsigned { unknown = 0, buffer = 1, texture1d = 2, texture2d = 3, texture3d = 4 }; + +// Which resource dimension one view dimension needs, by the device slot that makes the view +// (18 shader resource, 19 unordered access, 20 render target, 21 depth stencil). unknown when the +// view dimension is not one of that view type's values (or is 0); such a view is not judged here. +inline unsigned needed(int slot, unsigned view_dimension) noexcept +{ + switch (slot) { + case 18: // D3D12_SRV_DIMENSION + switch (view_dimension) { + case 1: return buffer; + case 2: case 3: return texture1d; + case 4: case 5: case 6: case 7: case 9: case 10: return texture2d; // 2D, arrays, MS, cube, cube array + case 8: return texture3d; + default: return unknown; // 11 is a raytracing structure, made with a null resource + } + case 19: // D3D12_UAV_DIMENSION + case 20: // D3D12_RTV_DIMENSION (same numbering) + switch (view_dimension) { + case 1: return buffer; + case 2: case 3: return texture1d; + case 4: case 5: case 6: case 7: return texture2d; + case 8: return texture3d; + default: return unknown; + } + case 21: // D3D12_DSV_DIMENSION + switch (view_dimension) { + case 1: case 2: return texture1d; + case 3: case 4: case 5: case 6: return texture2d; + default: return unknown; + } + default: + return unknown; + } +} + +// False only when the view dimension names a resource dimension other than the resource's. +inline bool fits(int slot, unsigned view_dimension, unsigned resource_dimension) noexcept +{ + const unsigned need = needed(slot, view_dimension); + return need == unknown || need == resource_dimension; +} + +// A description with ViewDimension 0 (UNKNOWN) is always refused by desktop D3D12. Measured: a +// title module makes one on a two-dimensional RGBA8 texture (format R32G32B32A32_FLOAT, default +// component mapping). The stand-in makes the resource's default view instead (a null description), +// which desktop allows only for a texture with a typed format, and for a shader resource view not +// a depth format. Whether the console gives UNKNOWN that meaning is a hypothesis. +inline bool typeless(unsigned format) noexcept +{ + switch (format) { + case 1: case 5: case 9: case 15: case 19: case 23: case 27: case 33: case 39: case 44: case 48: case 53: case 59: + case 70: case 73: case 76: case 79: case 82: case 90: case 92: case 94: case 97: + return true; + default: + return false; + } +} + +inline bool depth_format(unsigned format) noexcept { return format == 20 || format == 40 || format == 45 || format == 55; } + +inline bool default_view_allowed(int slot, unsigned resource_dimension, unsigned resource_format) noexcept +{ + if (slot < 18 || slot > 21) return false; + if (resource_dimension == unknown || resource_dimension == buffer) return false; + if (resource_format == 0 || typeless(resource_format)) return false; + if (slot == 18 && depth_format(resource_format)) return false; + return true; +} + +} // namespace x2w_view_dimension diff --git a/tests/startup_console_mode_check.cpp b/tests/startup_console_mode_check.cpp new file mode 100644 index 0000000000..75c34c3080 --- /dev/null +++ b/tests/startup_console_mode_check.cpp @@ -0,0 +1,221 @@ +// Source-built control for console_mode.h and registry_console_mode.inl: the console mode a title +// reads from HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM (value ConsoleMode). +// +// The real registry functions are replaced by local fakes that report the value as missing (a PC), +// so no machine state is read or changed. The hooks are reached the way a title reaches them +// through GetProcAddress. Cases: unset passes the read to the fake; 6 and 7 answer 0x60 and 0x64 +// without calling it; 1 answers missing; other keys, values and closed handles pass through. +// --control leaves X2W_DEVICE_TYPE unset for the answered cases, which must print FAIL. +#include + +#include +#include +#include +#include +#include + +#include "startup_stubs/console_mode.h" +#include "startup_stubs/local_log.h" +#include "startup_stubs/runtime_gpa_patch.h" + +namespace x2w_local { +std::string fixture_log; +void fixture_logf(const char* format, ...) +{ + char line[512]; + va_list args; + va_start(args, format); + std::vsnprintf(line, sizeof(line), format, args); + va_end(args); + fixture_log += line; + fixture_log += '\n'; +} +} // namespace x2w_local + +#define logf fixture_logf +namespace { +#include "../src/startup_stubs/registry_console_mode.inl" +} +#undef logf + +namespace { +int failures; +bool control; + +void check(const char* what, bool ok) +{ + if (!ok) { + std::printf("FAIL: %s\n", what); + ++failures; + } +} + +HKEY const fake_oem = reinterpret_cast(0x5100); +HKEY const fake_other = reinterpret_cast(0x5200); +int real_queries, real_gets, real_closes; + +LSTATUS WINAPI fake_open_ex(HKEY root, LPCWSTR subkey, DWORD, REGSAM, PHKEY out) +{ + if (root != HKEY_LOCAL_MACHINE || !out) return ERROR_FILE_NOT_FOUND; + *out = x2w_console_mode::is_oem_subkey(subkey) ? fake_oem : fake_other; + return ERROR_SUCCESS; +} +LSTATUS WINAPI fake_open(HKEY root, LPCWSTR subkey, PHKEY out) { return fake_open_ex(root, subkey, 0, 0, out); } +LSTATUS WINAPI fake_query(HKEY, LPCWSTR, LPDWORD, LPDWORD, LPBYTE, LPDWORD) +{ + ++real_queries; + return ERROR_FILE_NOT_FOUND; // as on a PC: the value is absent +} +LSTATUS WINAPI fake_get(HKEY, LPCWSTR, LPCWSTR, DWORD, LPDWORD, PVOID, LPDWORD) +{ + ++real_gets; + return ERROR_FILE_NOT_FOUND; +} +LSTATUS WINAPI fake_close(HKEY) +{ + ++real_closes; + return ERROR_SUCCESS; +} + +template +Fn hook(const char* name, Fn fake) +{ + return reinterpret_cast(registry_hook_for(name, reinterpret_cast(fake))); +} + +void device(const char* value, bool answered_case) +{ + // In the control the answered cases run without the switch, so their checks must fail. + if (!value || (control && answered_case)) + SetEnvironmentVariableA("X2W_DEVICE_TYPE", nullptr); + else + SetEnvironmentVariableA("X2W_DEVICE_TYPE", value); +} + +void pure_checks() +{ + using namespace x2w_console_mode; + check("OEM subkey", is_oem_subkey(L"Software\\Microsoft\\Windows NT\\CurrentVersion\\OEM")); + check("OEM subkey in capitals", is_oem_subkey(L"SOFTWARE\\MICROSOFT\\WINDOWS NT\\CURRENTVERSION\\OEM")); + check("OEM subkey with a leading and a trailing backslash", + is_oem_subkey(L"\\Software\\Microsoft\\Windows NT\\CurrentVersion\\OEM\\")); + check("a longer subkey is not the OEM key", !is_oem_subkey(L"Software\\Microsoft\\Windows NT\\CurrentVersion\\OEMx")); + check("a child of the OEM key is not the OEM key", !is_oem_subkey(L"Software\\Microsoft\\Windows NT\\CurrentVersion\\OEM\\a")); + check("a parent is not the OEM key", !is_oem_subkey(L"Software\\Microsoft\\Windows NT\\CurrentVersion")); + check("null subkey", !is_oem_subkey(nullptr)); + check("value name ignores case", is_console_mode_value(L"consolemode")); + check("other value name", !is_console_mode_value(L"ConsoleModeX")); + + std::uint32_t mode = 0; + check("unset passes", answer_for(false, 7, &mode) == Answer::pass); + check("6 is Series S", answer_for(true, 6, &mode) == Answer::value && mode == series_s); + check("7 is Series X", answer_for(true, 7, &mode) == Answer::value && mode == series_x); + check("1 is missing", answer_for(true, 1, &mode) == Answer::missing); + check("8 is passed on", answer_for(true, 8, &mode) == Answer::pass); + + unsigned long type = 0, bytes = 0; + unsigned char data[8] = {}; + check("size query", fill_query(series_x, &type, nullptr, &bytes) == status_ok && bytes == 4 && type == type_dword); + bytes = 3; + check("short buffer", fill_query(series_x, &type, data, &bytes) == status_more_data && bytes == 4 && data[0] == 0); + check("data without size", fill_query(series_x, &type, data, nullptr) == status_invalid); + bytes = sizeof(data); + check("value written", fill_query(series_x, &type, data, &bytes) == status_ok && bytes == 4 && data[0] == 0x64 && data[1] == 0); + bytes = sizeof(data); + check("RegGetValue refuses a string-only request", fill_get(0x2 /* RRF_RT_REG_SZ */, series_s, &type, data, &bytes) == status_wrong_type); + bytes = sizeof(data); + check("RegGetValue with RRF_RT_DWORD", fill_get(0x18, series_s, &type, data, &bytes) == status_ok && data[0] == 0x60); +} + +DWORD query(RegQueryValueExWFn query_fn, HKEY key, const wchar_t* name, LSTATUS* status) +{ + DWORD type = 0, value = 0xffffffff, bytes = sizeof(value); + *status = query_fn(key, name, nullptr, &type, reinterpret_cast(&value), &bytes); + return value; +} + +void hook_checks() +{ + const auto open_ex = hook("RegOpenKeyExW", &fake_open_ex); + const auto open = hook("RegOpenKeyW", &fake_open); + const auto query_fn = hook("RegQueryValueExW", &fake_query); + const auto get = hook("RegGetValueW", &fake_get); + const auto close = hook("RegCloseKey", &fake_close); + check("every registry name has a hook", open_ex && open && query_fn && get && close); + if (!(open_ex && open && query_fn && get && close)) return; + check("other names have no hook", !registry_hook_for("RegSetValueExW", reinterpret_cast(&fake_close))); + check("a hook is never kept as the real function", !registry_hook_for("RegCloseKey", reinterpret_cast(close))); + + const wchar_t* oem_path = L"Software\\Microsoft\\Windows NT\\CurrentVersion\\OEM"; + HKEY key = nullptr, other = nullptr; + check("OEM key opens through the hook", open_ex(HKEY_LOCAL_MACHINE, oem_path, 0, KEY_READ, &key) == ERROR_SUCCESS && key == fake_oem); + check("other key opens through the hook", open_ex(HKEY_LOCAL_MACHINE, L"Software\\Other", 0, KEY_READ, &other) == ERROR_SUCCESS); + + LSTATUS status = 0; + device(nullptr, false); + int before = real_queries; + query(query_fn, key, L"ConsoleMode", &status); + check("unset: the read reaches the registry", real_queries == before + 1 && status == ERROR_FILE_NOT_FOUND); + + device("6", true); + before = real_queries; + DWORD value = query(query_fn, key, L"ConsoleMode", &status); + check("6: Series S answered locally", status == ERROR_SUCCESS && value == 0x60 && real_queries == before); + + device("7", true); + value = query(query_fn, key, L"ConsoleMode", &status); + check("7: Series X answered locally", status == ERROR_SUCCESS && value == 0x64 && real_queries == before); + + DWORD type = 0, bytes = 0; + status = query_fn(key, L"ConsoleMode", nullptr, &type, nullptr, &bytes); + check("7: size query", status == ERROR_SUCCESS && bytes == 4 && type == REG_DWORD); + + DWORD got = 0, got_bytes = sizeof(got); + before = real_gets; + status = get(HKEY_LOCAL_MACHINE, oem_path, L"ConsoleMode", RRF_RT_REG_DWORD, &type, &got, &got_bytes); + check("7: RegGetValueW by path answered locally", status == ERROR_SUCCESS && got == 0x64 && real_gets == before); + + device("1", false); + before = real_queries; + query(query_fn, key, L"ConsoleMode", &status); + check("1: missing, as on a PC", status == ERROR_FILE_NOT_FOUND && real_queries == before); + + device("7", false); + before = real_queries; + query(query_fn, key, L"OtherValue", &status); + check("7: another value passes through", real_queries == before + 1); + query(query_fn, other, L"ConsoleMode", &status); + check("7: ConsoleMode under another key passes through", real_queries == before + 2); + device("not-a-number", false); + query(query_fn, key, L"ConsoleMode", &status); + check("a value that is not a number passes through", real_queries == before + 3); + + HKEY second = nullptr; + device("7", true); + check("RegOpenKeyW opens the OEM key", open(HKEY_LOCAL_MACHINE, oem_path, &second) == ERROR_SUCCESS && second == fake_oem); + check("RegCloseKey reaches the registry", close(key) == ERROR_SUCCESS && real_closes == 1); + device("7", false); + before = real_queries; + query(query_fn, key, L"ConsoleMode", &status); + check("a closed OEM handle passes through", real_queries == before + 1); + + device(nullptr, false); + const std::string& log = x2w_local::fixture_log; + check("open is logged", log.find("RegOpenKeyExW opened the OEM key, real status 0") != std::string::npos); + check("pass-through is logged", log.find("RegQueryValueExW ConsoleMode passed through -> status 2") != std::string::npos); + check("answer is logged", log.find("ConsoleMode -> 0x64 for X2W_DEVICE_TYPE=7") != std::string::npos); +} +} // namespace + +int main(int argc, char** argv) +{ + control = argc > 1 && std::strcmp(argv[1], "--control") == 0; + pure_checks(); + hook_checks(); + if (failures) { + std::printf("startup_console_mode: FAIL (%d)\n", failures); + return 1; + } + std::puts("startup_console_mode: ok"); + return 0; +} diff --git a/tests/startup_present_planes_check.cpp b/tests/startup_present_planes_check.cpp new file mode 100644 index 0000000000..88473d3c6c --- /dev/null +++ b/tests/startup_present_planes_check.cpp @@ -0,0 +1,89 @@ +// Checks src/startup_stubs/present_planes.h on synthetic plane records: two 0x48-byte records, each +// with a frame token, a resource count and a pointer to its resource array. +// Also checks the window composite order (composite_steps) on synthetic plane surfaces. +// --control reads the records with a 0x40-byte stride (the record size before the second plane was +// measured) and composites plane 0 alone (the window present before planes were composited); the +// second-plane rows must print FAIL. +#include "startup_stubs/present_planes.h" + +#include +#include + +namespace { +int failures; + +void check(const char* what, bool ok) +{ + if (!ok) { + std::printf("FAIL: %s\n", what); + ++failures; + } +} + +void put(unsigned char* at, std::uint64_t value) { std::memcpy(at, &value, 8); } +} // namespace + +int main(int argc, char** argv) +{ + const bool control = argc > 1 && std::strcmp(argv[1], "--control") == 0; + const std::size_t stride = control ? 0x40 : x2w_startup::present_plane_stride; + const std::uint64_t first_plane[] = {0x1111}, second_plane[] = {0x2222, 0x3333}; + alignas(8) unsigned char records[2 * 0x48] = {}; + alignas(8) unsigned char empty[0x48] = {}; + // Readable: only this fixture's own records and resource arrays. + const auto inside = [](const void* address, std::size_t bytes, const void* base, std::size_t size) { + const auto* a = static_cast(address); + const auto* b = static_cast(base); + return a >= b && a + bytes <= b + size; + }; + const auto readable = [&](const void* address, std::size_t bytes) { + return inside(address, bytes, records, sizeof(records)) || inside(address, bytes, empty, sizeof(empty)) || + inside(address, bytes, first_plane, sizeof(first_plane)) || inside(address, bytes, second_plane, sizeof(second_plane)); + }; + put(records + 0x00, 7); // frame token + put(records + 0x08, 1); + put(records + 0x10, reinterpret_cast(first_plane)); + put(records + 0x48, 7); + put(records + 0x50, 2); + put(records + 0x58, reinterpret_cast(second_plane)); + + using x2w_startup::present_plane_resource; + check("plane 0 resource", present_plane_resource(records, 2, 0, readable, stride) == 0x1111); + check("plane 1 resource (the second record starts at +0x48)", present_plane_resource(records, 2, 1, readable, stride) == 0x2222); + check("a plane past the count has no resource", present_plane_resource(records, 1, 1, readable, stride) == 0); + check("no records", present_plane_resource(nullptr, 2, 0, readable, stride) == 0); + + put(empty + 0x10, reinterpret_cast(first_plane)); + check("a plane with no resources has none", present_plane_resource(empty, 1, 0, readable, stride) == 0); + const auto unreadable = [](const void*, std::size_t) { return false; }; + check("an unreadable record has no resource", present_plane_resource(records, 2, 0, unreadable, stride) == 0); + + // Composite order: the lowest shown plane is opaque, later ones blend over it. + using x2w_startup::PlaneStep; + const auto composite = [&](const std::uint64_t* resources, unsigned count, PlaneStep* steps) { + return x2w_startup::composite_steps(resources, control && count > 1 ? 1 : count, steps, 4); + }; + PlaneStep steps[4]; + const std::uint64_t two[] = {0x1111, 0x2222}; + unsigned n = composite(two, 2, steps); + check("two planes give two steps", n == 2); + check("plane 0 is drawn first, opaque", n >= 1 && steps[0].plane == 0 && !steps[0].blended); + check("plane 1 is drawn over plane 0, blended", n >= 2 && steps[1].plane == 1 && steps[1].blended); + const std::uint64_t missing_base[] = {0, 0x2222}; + n = composite(missing_base, 2, steps); + check("with plane 0 not shown, plane 1 is the opaque base", n == 1 && steps[0].plane == 1 && !steps[0].blended); + const std::uint64_t repeated[] = {0x1111, 0x1111}; + n = x2w_startup::composite_steps(repeated, 2, steps, 4); + check("a surface presented twice is drawn once", n == 1 && steps[0].plane == 0); + const std::uint64_t one[] = {0x1111}; + n = composite(one, 1, steps); + check("one plane is one opaque step", n == 1 && steps[0].plane == 0 && !steps[0].blended); + check("no planes, no steps", x2w_startup::composite_steps(nullptr, 2, steps, 4) == 0); + + if (failures) { + std::printf("startup_present_planes: FAIL (%d)\n", failures); + return 1; + } + std::puts("startup_present_planes: ok"); + return 0; +} diff --git a/tests/startup_view_dimension_check.cpp b/tests/startup_view_dimension_check.cpp new file mode 100644 index 0000000000..2105a23dd5 --- /dev/null +++ b/tests/startup_view_dimension_check.cpp @@ -0,0 +1,88 @@ +// Source-built control for view_dimension.h: whether a view's ViewDimension suits the dimension of +// the resource it is made on (desktop D3D12 removes the device for a mismatch). Values are the +// public d3d12.h enumerations. --control swaps the resource dimension of the mismatched cases for +// the matching one, so the checks that expect a refusal must print FAIL. +#include +#include + +#include "startup_stubs/view_dimension.h" + +namespace { +int failures; +bool control; + +void check(const char* what, bool ok) +{ + if (!ok) { + std::printf("FAIL: %s\n", what); + ++failures; + } +} + +// A refusal case: in the control the resource is given the dimension the view needs. +bool refused(int slot, unsigned view_dimension, unsigned resource_dimension) +{ + using namespace x2w_view_dimension; + if (control) resource_dimension = needed(slot, view_dimension); + return !fits(slot, view_dimension, resource_dimension); +} +} // namespace + +int main(int argc, char** argv) +{ + using namespace x2w_view_dimension; + control = argc > 1 && std::strcmp(argv[1], "--control") == 0; + + // Matching shapes are accepted. + check("SRV texture 2D on a 2D texture", fits(18, 4, texture2d)); + check("SRV cube on a 2D texture", fits(18, 9, texture2d)); + check("SRV cube array on a 2D texture", fits(18, 10, texture2d)); + check("SRV texture 3D on a 3D texture", fits(18, 8, texture3d)); + check("SRV buffer on a buffer", fits(18, 1, buffer)); + check("SRV texture 1D array on a 1D texture", fits(18, 3, texture1d)); + check("UAV texture 2D array on a 2D texture", fits(19, 5, texture2d)); + check("UAV texture 3D on a 3D texture", fits(19, 8, texture3d)); + check("RTV buffer on a buffer", fits(20, 1, buffer)); + check("RTV texture 2D on a 2D texture", fits(20, 4, texture2d)); + check("DSV texture 1D on a 1D texture", fits(21, 1, texture1d)); + check("DSV texture 2D on a 2D texture", fits(21, 3, texture2d)); + + // Values this check does not judge pass on: unknown dimension, raytracing structure, other slots. + check("SRV unknown dimension is not judged", fits(18, 0, texture3d)); + check("SRV raytracing structure is not judged", fits(18, 11, unknown)); + check("out-of-range SRV dimension is not judged", fits(18, 99, buffer)); + check("DSV dimension 7 is not judged", fits(21, 7, buffer)); + check("sampler slot is not judged", fits(22, 4, buffer)); + + // Mismatches are refused (the control turns each into a match, so these print FAIL). + check("SRV texture 2D on a 3D texture is refused", refused(18, 4, texture3d)); + check("SRV texture 3D on a 2D texture is refused", refused(18, 8, texture2d)); + check("SRV buffer on a 2D texture is refused", refused(18, 1, texture2d)); + check("SRV cube on a 3D texture is refused", refused(18, 9, texture3d)); + check("UAV texture 2D on a buffer is refused", refused(19, 4, buffer)); + check("RTV texture 3D on a 2D texture is refused", refused(20, 8, texture2d)); + check("DSV texture 2D on a 1D texture is refused", refused(21, 3, texture1d)); + + // ViewDimension 0 (unknown): a default view only where desktop allows a null description. + check("default SRV of an RGBA8 2D texture", default_view_allowed(18, texture2d, 28)); + check("default RTV of an RGBA8 2D texture", default_view_allowed(20, texture2d, 28)); + check("default DSV of a D32 2D texture", default_view_allowed(21, texture2d, 40)); + check("default SRV of a 3D texture", default_view_allowed(18, texture3d, 10)); + const auto no_default = [](int slot, unsigned dimension, unsigned format) { + if (control) dimension = texture2d, format = 28; // a texture that has a default view + return !default_view_allowed(slot, dimension, format); + }; + check("no default view of a buffer", no_default(18, buffer, 28)); + check("no default view of a typeless texture", no_default(18, texture2d, 27)); + check("no default view of a typeless BC7 texture", no_default(19, texture2d, 97)); + check("no default SRV of a depth texture", no_default(18, texture2d, 40)); + check("no default view of an unknown format", no_default(18, texture2d, 0)); + check("no default view on the constant-buffer slot", !default_view_allowed(17, texture2d, 28)); + + if (failures) { + std::printf("startup_view_dimension: FAIL (%d)\n", failures); + return 1; + } + std::puts("startup_view_dimension: ok"); + return 0; +}