Compare commits

..
Author SHA1 Message Date
ates 23d631e3c7 Merge remote-tracking branch 'origin/main' into track-a/665-clzero-loop
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 16:49:50 +03:00
Ateş 64f9b1dcb5 Merge pull request #684 from MacosPorters/track-c/669-serialized-pipelines-fail
[Boot] d3d12_xs: fail serialized and derived pipeline calls in null-render mode
2026-11-29 15:44:46 +03:00
Ateş 740df46b10 Merge pull request #689 from MacosPorters/process/agent-self-setup
[Process] A collaborator only says "work": the agent makes the machine ready itself
2026-11-29 15:44:23 +03:00
erkinemreta1 77af218878 d3d12_xs: fail serialized and derived pipeline calls in null-render mode
Signed-off-by: erkinemreta1 <erkinemreta1@users.noreply.github.com>
2026-11-29 14:08:41 +03:00
ates 6db66dc4a4 Merge remote-tracking branch 'origin/main' into track-a/665-clzero-loop 2026-11-29 11:36:35 +03:00
ates 65eef5b08e runtime_veh: complete a CLZERO loop in one exception (#665)
A title that zeroes memory with
    clzero ; add rax, 0x40 ; cmp rax, <reg64> ; jb <the clzero>
raised one illegal-instruction exception per 64 bytes under Rosetta 2.
A project-authorized target build spent tens of seconds of its frame
loop there (more than two million exceptions in a run).

When the trapped CLZERO is followed by exactly that form, the handler
zeroes every remaining line below the limit and leaves RAX at the last
one, so the title's own add/cmp/jb leaves the loop. The range is zeroed
region by region and stops at memory that is not committed and writable;
the title's next CLZERO then traps and faults as before. Any other loop
form keeps the per-instruction path.

test_veh_clzero_loop runs its own machine-code loops, checks the memory
result line by line with sentinels, and counts illegal-instruction
exceptions with a handler registered ahead of BetterXen's: one per
recognised loop, one per line otherwise, three for a range that runs
into a read-only page. On the old handler five of its sixteen checks
fail.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 11:14:52 +03:00
7 changed files with 494 additions and 20 deletions

No files matched your search

+2
View File
@@ -86,6 +86,8 @@ remains unsupported.
- `d3d12_xs.dll!D3D12ConfigureVirtualMemoryX` now decodes the Xbox virtual-memory configuration (`D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION`) alongside the existing `BXVM` contract. Layout and behaviour follow the authorized GDK documentation of the function and structure: no flags, a GPU page-table size in 4 MB units clamped to 33, a frame-buffer preserve size (0, -1 for the legacy size, or bytes clamped to 64 MiB), and two output addresses, the minimum always 2 GiB and the maximum 159.375 GiB at the default 5 pages. The call fails with `E_FAIL` once a D3D12 device exists. Call-site observation of a project-authorized target build agrees with the documented layout. Inferred, and marked as such: the maximum for other page-table sizes scales linearly (`max_estimated=1` in the log), and a page-table size of 0, an unreadable configuration or unwritable outputs fail with `E_INVALIDARG`. The host sizes no GPU page tables and keeps no cross-process frame buffer, so the path records both (`vmem_config_recorded`, `applied=0 recorded_only=1`), leaves the `BXVM` record and cached backing heap untouched, and still emits `BX_STUB_LOG`. `tests/conformance/test_d3d12_vmem_xbox/` checks the documented outputs, clamps and post-device `E_FAIL`, the refused cases, and that a cached `BXVM` backing heap survives.
### Fixed
- `bx_runtime_veh.dll` completes a `CLZERO` loop in one exception (#665). A title that zeroes memory with `clzero; add rax,0x40; cmp rax,<reg64>; jb` raised one illegal-instruction exception per 64 bytes under Rosetta 2, which stalled a project-authorized target build's frame loop for tens of seconds. When the trapped `CLZERO` is followed by exactly that form, the handler zeroes every remaining line below the limit and leaves `RAX` at the last one, so the title's own `add`/`cmp`/`jb` leaves the loop. The range is zeroed region by region and stops at memory that is not committed and writable, where the next `CLZERO` traps and faults as before. Other loop forms keep the per-instruction path. `test_veh_clzero_loop` checks the memory result and counts the exceptions; it fails on the old handler.
- `d3d12_xs.dll` no longer turns `DeserializeGraphicsPipelineStateX`, `DeserializeComputePipelineStateX`, `CreateDerivedGraphicsPipelineStateX` or `CreateDerivedComputePipelineStateX` into null pipelines in null-render mode (`BX_NULL_RENDER=1`) (#669). All four calls now always return `E_NOTIMPL`, clear `*ppv` and log `pipeline_refused` without `; null pipeline returned`, so a title falls back to creating pipelines from shader containers instead of silently receiving null pipelines. `test_d3d12_serialized_pipelines` checks all four slots and their refusal log lines with `BX_NULL_RENDER=1` active alongside a control shader-container null pipeline.
- `XCRDAPI.dll` Xbox DirectStorage fixes:
- **Zlib requests read the file.** The file handle was not set for them, so every compressed file request failed. The request options are now decoded, and zlib streams are inflated in-tree.
- **`AutoSubmitDisabled` is honoured.** Xbox `CreateQueueX` respects `DSTORAGE_QUEUE_OPTIONS.AutoSubmitDisabled`: a queue with the flag runs nothing before `Submit`, and when it is full the enqueuer waits until `Submit` is called on another thread. A queue without the flag submits by itself once half full.
+26 -17
View File
@@ -173,6 +173,13 @@ HRESULT refused(ID3D12Device* device, HRESULT hr, const char* kind, REFIID riid,
return bx_xbox_wrap_result(S_OK, riid, ppv);
}
HRESULT refused_always_fail(HRESULT hr, const char* kind) {
char detail[128];
std::snprintf(detail, sizeof(detail), "%s pipeline refused hr=0x%08lx", kind, static_cast<unsigned long>(hr));
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "pipeline_refused", detail);
return hr;
}
void log_extended(const char* kind, UINT count) {
if (!count) return;
char detail[96];
@@ -433,33 +440,35 @@ void STDMETHODCALLTYPE bx_xbox_allocator_set_callback_x(void*, void* callback, U
/*
* DeserializeGraphics/ComputePipelineStateX create a pipeline from a serialized console pipeline
* (console shader code), which has no host form. They fail with E_NOTIMPL (logged as a refused
* pipeline); in null-render mode they return a null pipeline like any other refused pipeline.
* (console shader code), which has no host form. They always fail with E_NOTIMPL and log
* `pipeline_refused` — even in null-render mode — so a title falls back to creating its pipelines
* from shader containers instead of receiving a null pipeline (#669).
*/
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_graphics_pipeline_state_x(void* self, const void*, REFIID riid,
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_graphics_pipeline_state_x(void*, const void*, REFIID,
void** ppv) {
BX_D3D_TRACE("XboxDevice", "DeserializeGraphicsPipelineStateX");
if (!ppv) return E_POINTER;
*ppv = nullptr;
return refused(bx_xbox_host<ID3D12Device>(self), E_NOTIMPL, "deserialized graphics (console code)", riid, ppv);
return refused_always_fail(E_NOTIMPL, "deserialized graphics (console code)");
}
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_compute_pipeline_state_x(void* self, const void*, REFIID riid,
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_compute_pipeline_state_x(void*, const void*, REFIID,
void** ppv) {
BX_D3D_TRACE("XboxDevice", "DeserializeComputePipelineStateX");
if (!ppv) return E_POINTER;
*ppv = nullptr;
return refused(bx_xbox_host<ID3D12Device>(self), E_NOTIMPL, "deserialized compute (console code)", riid, ppv);
return refused_always_fail(E_NOTIMPL, "deserialized compute (console code)");
}
/*
* CreateDerived{Graphics,Compute}PipelineStateX: a pipeline equal to `source` with some state
* groups replaced. Derived from a null pipeline, the result is a null pipeline too. Deriving
* from a host pipeline needs its creation description, which this layer does not keep yet: that
* case is refused (logged) and, in null-render mode, is a null pipeline as well.
* groups replaced. Deriving from a host pipeline needs its creation description, which this layer
* does not keep yet. Both calls always fail with E_NOTIMPL and log `pipeline_refused` — even in
* null-render mode — so a title falls back to creating its pipelines from shader containers
* instead of silently receiving null pipelines (#669).
*/
namespace {
HRESULT derived(void* self, ID3D12PipelineState* source, REFIID riid, void** ppv, const char* kind) {
HRESULT derived(ID3D12PipelineState* source, void** ppv, const char* kind) {
if (!ppv) return E_POINTER;
*ppv = nullptr;
const bool from_null = bx_xbox_pipeline_is_null(source);
@@ -470,18 +479,18 @@ HRESULT derived(void* self, ID3D12PipelineState* source, REFIID riid, void** ppv
"deriving from a host pipeline is not implemented (its creation description is not kept)");
}
}
return refused(bx_xbox_host<ID3D12Device>(self), E_NOTIMPL, kind, riid, ppv);
return refused_always_fail(E_NOTIMPL, kind);
}
} // namespace
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_graphics_pipeline_state_x(void* self, ID3D12PipelineState* source,
UINT, const void*, REFIID riid, void** ppv) {
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_graphics_pipeline_state_x(void*, ID3D12PipelineState* source,
UINT, const void*, REFIID, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateDerivedGraphicsPipelineStateX");
return derived(self, source, riid, ppv, "derived graphics");
return derived(source, ppv, "derived graphics");
}
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_compute_pipeline_state_x(void* self, ID3D12PipelineState* source,
UINT, const void*, REFIID riid, void** ppv) {
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_compute_pipeline_state_x(void*, ID3D12PipelineState* source,
UINT, const void*, REFIID, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateDerivedComputePipelineStateX");
return derived(self, source, riid, ppv, "derived compute");
return derived(source, ppv, "derived compute");
}
+63 -3
View File
@@ -279,12 +279,72 @@ bool zero_guest_cache_line(uint64_t address, EXCEPTION_RECORD& exception) {
return false;
}
// A title that zeroes memory with CLZERO does it in a loop, and each iteration would trap again
// (an exception round trip per 64 bytes: seconds per 100 MB). When the trapped CLZERO is followed
// by exactly
// add rax, 0x40 ; cmp rax, <reg64> ; jb <the clzero>
// the remaining iterations are done here: every further line below the limit is zeroed and RAX is
// left at the last one, so the title's own add/cmp/jb then leaves the loop. The range is zeroed
// region by region and stops early at memory that is not committed and writable, where the
// title's next CLZERO traps as before. Returns the number of extra lines zeroed.
uint64_t clzero_loop_fast_path(CONTEXT& context) {
const auto* code = reinterpret_cast<const uint8_t*>(context.Rip);
MEMORY_BASIC_INFORMATION text{};
if (!VirtualQuery(code, &text, sizeof(text)) || text.State != MEM_COMMIT ||
reinterpret_cast<uintptr_t>(code) + 12 > reinterpret_cast<uintptr_t>(text.BaseAddress) + text.RegionSize) {
return 0;
}
if (code[0] != 0x0F || code[1] != 0x01 || code[2] != 0xFC) return 0; // clzero
if (code[3] != 0x48 || code[4] != 0x83 || code[5] != 0xC0 || code[6] != 0x40) return 0; // add rax, 0x40
if ((code[7] != 0x48 && code[7] != 0x4C) || code[8] != 0x39 || (code[9] & 0xC7) != 0xC0) return 0; // cmp rax, r64
if (code[10] != 0x72 || code[11] != 0xF4) return 0; // jb -12
const unsigned reg = ((code[9] >> 3) & 7) | (code[7] == 0x4C ? 8 : 0);
const DWORD64* registers = &context.Rax; // Rax, Rcx, Rdx, Rbx, Rsp, Rbp, Rsi, Rdi, R8..R15
const uint64_t limit = registers[reg];
constexpr uint64_t line = 64;
uint64_t next = context.Rax + line;
if (reg == 0 || next >= limit || limit - next > (1ull << 32)) return 0;
const uint64_t last = next + ((limit - 1 - next) / line) * line; // largest next + 64k below limit
constexpr DWORD writable = PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY;
uint64_t done = 0;
while (next <= last) {
const uint64_t start = next & ~(line - 1);
MEMORY_BASIC_INFORMATION page{};
if (!VirtualQuery(reinterpret_cast<const void*>(start), &page, sizeof(page)) || page.State != MEM_COMMIT ||
!(page.Protect & writable) || (page.Protect & PAGE_GUARD)) {
break;
}
const uint64_t region_end = reinterpret_cast<uintptr_t>(page.BaseAddress) + page.RegionSize;
uint64_t lines = (last - next) / line + 1;
const uint64_t fit = (region_end - start) / line;
if (fit == 0) break;
if (lines > fit) lines = fit;
std::memset(reinterpret_cast<void*>(start), 0, static_cast<size_t>(lines * line));
context.Rax = next + (lines - 1) * line;
next += lines * line;
done += lines;
}
return done;
}
bool apply_amd_instruction(const AmdInstruction& instruction, CONTEXT& context,
EXCEPTION_RECORD& exception) {
switch (instruction.kind) {
case kClzero:
return zero_guest_cache_line(instruction.address32 ? static_cast<uint32_t>(context.Rax)
: context.Rax, exception);
case kClzero: {
if (!zero_guest_cache_line(instruction.address32 ? static_cast<uint32_t>(context.Rax) : context.Rax,
exception)) {
return false;
}
if (!instruction.address32) {
static std::atomic<uint64_t> batched{0};
const uint64_t lines = clzero_loop_fast_path(context);
if (lines && batched.fetch_add(1) == 0) {
bx_log_emit(BX_LOG_INFO, "runtime_veh", "clzero_loop",
"CLZERO loop (add rax,0x40; cmp; jb) completed in one trap; later loops are not logged");
}
}
return true;
}
case kMonitorx:
// There is no host monitor state. MWAITX may complete immediately.
return true;
@@ -0,0 +1,3 @@
add_executable(test_d3d12_serialized_pipelines main.cpp)
target_compile_definitions(test_d3d12_serialized_pipelines PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
target_link_libraries(test_d3d12_serialized_pipelines PRIVATE d3d12_xs kernel32 uuid)
@@ -0,0 +1,198 @@
/*
* Conformance test for #669: serialized and derived Xbox pipeline-state calls must fail with
* E_NOTIMPL and log `pipeline_refused` even when BX_NULL_RENDER=1 is active, so a title falls
* back to creating pipelines from shader containers instead of silently receiving null pipelines.
*
* Slot numbers follow the Xbox Series ID3D12Device vtable layout (ADR 0009):
* 2 = Release
* 11 = CreateComputePipelineState
* 55 = CreateDerivedGraphicsPipelineStateX
* 57 = DeserializeGraphicsPipelineStateX
* 63 = CreateDerivedComputePipelineStateX
* 67 = DeserializeComputePipelineStateX
*/
#include <windows.h>
#include <d3d12.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
void** ppv);
namespace {
constexpr int kRelease = 2;
constexpr int kDevCreateComputePipelineState = 11;
constexpr int kDevCreateDerivedGraphicsPipelineStateX = 55;
constexpr int kDevDeserializeGraphicsPipelineStateX = 57;
constexpr int kDevCreateDerivedComputePipelineStateX = 63;
constexpr int kDevDeserializeComputePipelineStateX = 67;
int g_checks = 0;
int g_failed = 0;
#define CHECK(cond, ...) \
do { \
++g_checks; \
if (!(cond)) { \
++g_failed; \
std::fprintf(stderr, "FAIL: test_d3d12_serialized_pipelines:%d: ", __LINE__); \
std::fprintf(stderr, __VA_ARGS__); \
std::fprintf(stderr, "\n"); \
} \
} while (0)
template <typename Fn>
Fn slot(void* object, int index) {
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
}
using ReleaseFn = ULONG(STDMETHODCALLTYPE*)(void*);
using CreateComputePsoFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, REFIID, void**);
using DeserializePsoFn = HRESULT(STDMETHODCALLTYPE*)(void*, const void*, REFIID, void**);
using CreateDerivedPsoFn = HRESULT(STDMETHODCALLTYPE*)(void*, ID3D12PipelineState*, UINT, const void*, REFIID, void**);
std::string read_log() {
char path[MAX_PATH];
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
if (n == 0 || n >= sizeof(path)) return {};
std::string text;
if (FILE* f = std::fopen(path, "rb")) {
char buffer[4096];
size_t got;
while ((got = std::fread(buffer, 1, sizeof(buffer), f)) > 0) text.append(buffer, got);
std::fclose(f);
}
return text;
}
bool log_has_refusal_without_null(const std::string& log, const char* kind) {
size_t pos = 0;
while (pos < log.size()) {
size_t end = log.find('\n', pos);
if (end == std::string::npos) end = log.size();
const std::string line = log.substr(pos, end - pos);
if (line.find("\"event\":\"pipeline_refused\"") != std::string::npos && line.find(kind) != std::string::npos) {
return line.find("null pipeline returned") == std::string::npos;
}
pos = end + 1;
}
return false;
}
} // namespace
int main() {
// Enable null-render mode before any pipeline call so d3d12_xs caches BX_NULL_RENDER=1.
SetEnvironmentVariableA("BX_NULL_RENDER", "1");
alignas(8) unsigned char title_params[80] = {};
const UINT version = 0x20004;
std::memcpy(title_params, &version, sizeof(version));
void* dev = nullptr;
HRESULT hr = D3D12XboxCreateDevice(nullptr, title_params, __uuidof(ID3D12Device), &dev);
if (hr == E_NOINTERFACE) {
std::printf("SKIP: test_d3d12_serialized_pipelines: host lacks Xbox-layout device interface (E_NOINTERFACE)\n");
return 77;
}
CHECK(hr == S_OK && dev != nullptr, "Xbox-layout device creation hr=0x%08lx", static_cast<unsigned long>(hr));
if (!dev) return 1;
// 1. Control check: a refused shader-container pipeline still becomes a null pipeline when
// BX_NULL_RENDER=1, confirming null-render mode is active.
static const uint8_t kBogusShader[16] = {0x44, 0x58, 0x42, 0x43};
D3D12_COMPUTE_PIPELINE_STATE_DESC compute_desc{};
compute_desc.CS.pShaderBytecode = kBogusShader;
compute_desc.CS.BytecodeLength = sizeof(kBogusShader);
void* null_pso = nullptr;
hr = slot<CreateComputePsoFn>(dev, kDevCreateComputePipelineState)(
dev, &compute_desc, __uuidof(ID3D12PipelineState), &null_pso);
CHECK(hr == S_OK && null_pso != nullptr,
"control: refused CreateComputePipelineState returns null pipeline in BX_NULL_RENDER=1 (hr=0x%08lx)",
static_cast<unsigned long>(hr));
// 2. Serialized pipeline calls must fail with E_NOTIMPL and clear *ppv even with BX_NULL_RENDER=1.
auto* sentinel = reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD));
void* out = sentinel;
hr = slot<DeserializePsoFn>(dev, kDevDeserializeGraphicsPipelineStateX)(
dev, nullptr, __uuidof(ID3D12PipelineState), &out);
CHECK(hr == E_NOTIMPL && out == nullptr,
"DeserializeGraphicsPipelineStateX must fail with E_NOTIMPL and null out (hr=0x%08lx, out=%p)",
static_cast<unsigned long>(hr), out);
hr = slot<DeserializePsoFn>(dev, kDevDeserializeGraphicsPipelineStateX)(
dev, nullptr, __uuidof(ID3D12PipelineState), nullptr);
CHECK(hr == E_POINTER, "DeserializeGraphicsPipelineStateX(ppv=nullptr) must return E_POINTER (hr=0x%08lx)",
static_cast<unsigned long>(hr));
out = sentinel;
hr = slot<DeserializePsoFn>(dev, kDevDeserializeComputePipelineStateX)(
dev, nullptr, __uuidof(ID3D12PipelineState), &out);
CHECK(hr == E_NOTIMPL && out == nullptr,
"DeserializeComputePipelineStateX must fail with E_NOTIMPL and null out (hr=0x%08lx, out=%p)",
static_cast<unsigned long>(hr), out);
hr = slot<DeserializePsoFn>(dev, kDevDeserializeComputePipelineStateX)(
dev, nullptr, __uuidof(ID3D12PipelineState), nullptr);
CHECK(hr == E_POINTER, "DeserializeComputePipelineStateX(ppv=nullptr) must return E_POINTER (hr=0x%08lx)",
static_cast<unsigned long>(hr));
// 3. Derived pipeline calls must also fail with E_NOTIMPL and clear *ppv (both from a null
// pipeline source and from a nullptr source) even with BX_NULL_RENDER=1.
auto* null_src = static_cast<ID3D12PipelineState*>(null_pso);
out = sentinel;
hr = slot<CreateDerivedPsoFn>(dev, kDevCreateDerivedGraphicsPipelineStateX)(
dev, null_src, 0, nullptr, __uuidof(ID3D12PipelineState), &out);
CHECK(hr == E_NOTIMPL && out == nullptr,
"CreateDerivedGraphicsPipelineStateX(null source) must fail with E_NOTIMPL and null out (hr=0x%08lx, out=%p)",
static_cast<unsigned long>(hr), out);
out = sentinel;
hr = slot<CreateDerivedPsoFn>(dev, kDevCreateDerivedGraphicsPipelineStateX)(
dev, nullptr, 0, nullptr, __uuidof(ID3D12PipelineState), &out);
CHECK(hr == E_NOTIMPL && out == nullptr,
"CreateDerivedGraphicsPipelineStateX(nullptr) must fail with E_NOTIMPL and null out (hr=0x%08lx, out=%p)",
static_cast<unsigned long>(hr), out);
hr = slot<CreateDerivedPsoFn>(dev, kDevCreateDerivedGraphicsPipelineStateX)(
dev, null_src, 0, nullptr, __uuidof(ID3D12PipelineState), nullptr);
CHECK(hr == E_POINTER, "CreateDerivedGraphicsPipelineStateX(ppv=nullptr) must return E_POINTER (hr=0x%08lx)",
static_cast<unsigned long>(hr));
out = sentinel;
hr = slot<CreateDerivedPsoFn>(dev, kDevCreateDerivedComputePipelineStateX)(
dev, null_src, 0, nullptr, __uuidof(ID3D12PipelineState), &out);
CHECK(hr == E_NOTIMPL && out == nullptr,
"CreateDerivedComputePipelineStateX(null source) must fail with E_NOTIMPL and null out (hr=0x%08lx, out=%p)",
static_cast<unsigned long>(hr), out);
out = sentinel;
hr = slot<CreateDerivedPsoFn>(dev, kDevCreateDerivedComputePipelineStateX)(
dev, nullptr, 0, nullptr, __uuidof(ID3D12PipelineState), &out);
CHECK(hr == E_NOTIMPL && out == nullptr,
"CreateDerivedComputePipelineStateX(nullptr) must fail with E_NOTIMPL and null out (hr=0x%08lx, out=%p)",
static_cast<unsigned long>(hr), out);
hr = slot<CreateDerivedPsoFn>(dev, kDevCreateDerivedComputePipelineStateX)(
dev, null_src, 0, nullptr, __uuidof(ID3D12PipelineState), nullptr);
CHECK(hr == E_POINTER, "CreateDerivedComputePipelineStateX(ppv=nullptr) must return E_POINTER (hr=0x%08lx)",
static_cast<unsigned long>(hr));
// 4. When BX_LOG_FILE is active, verify each refusal was logged without "null pipeline returned".
const std::string log = read_log();
if (!log.empty()) {
CHECK(log_has_refusal_without_null(log, "deserialized graphics (console code)"),
"log must record deserialized graphics refusal without null pipeline");
CHECK(log_has_refusal_without_null(log, "deserialized compute (console code)"),
"log must record deserialized compute refusal without null pipeline");
CHECK(log_has_refusal_without_null(log, "derived graphics"),
"log must record derived graphics refusal without null pipeline");
CHECK(log_has_refusal_without_null(log, "derived compute"),
"log must record derived compute refusal without null pipeline");
}
if (null_pso) slot<ReleaseFn>(null_pso, kRelease)(null_pso);
slot<ReleaseFn>(dev, kRelease)(dev);
std::printf("%s: test_d3d12_serialized_pipelines (%d of %d checks passed)\n",
g_failed ? "FAIL" : "PASS", g_checks - g_failed, g_checks);
return g_failed ? 1 : 0;
}
@@ -0,0 +1,3 @@
add_executable(test_veh_clzero_loop main.cpp)
target_include_directories(test_veh_clzero_loop PRIVATE "${BX_ABI_INCLUDE_DIR}")
target_link_libraries(test_veh_clzero_loop PRIVATE bx_runtime_veh kernel32)
@@ -0,0 +1,199 @@
// Synthetic Windows x64 fixture for CLZERO loops under the Rosetta exception path (#665).
//
// CLZERO (AMD APM vol. 3, 24594) zeroes the 64-byte cache line that contains the address in RAX
// and changes no register. Rosetta 2 does not run it, so bx_runtime_veh.dll emulates it from the
// illegal-instruction exception. A loop of the form
//
// clzero ; add rax, 0x40 ; cmp rax, <reg64> ; jb <the clzero>
//
// would raise one exception per line. The handler completes such a loop in the first exception.
//
// This fixture runs its own machine-code loops (bytes written here, no title code) and checks:
// * the memory result against the instruction's definition, line by line, with sentinels;
// * the number of illegal-instruction exceptions, counted by a handler of its own that runs
// before BetterXen's: one per loop that matches the form, one per line otherwise;
// * a range that runs into a read-only page: the loop stops there with a write fault at that
// page, and finishes once the page is writable.
// On a host that runs CLZERO natively no exception is raised and the fixture skips (exit 77).
#include <windows.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
extern "C" uint64_t bx_veh_get_clwb_trap_count(void); // imports bx_runtime_veh.dll, which installs the handler
namespace {
unsigned failures = 0;
unsigned checks = 0;
void expect(bool passed, const char* name) {
++checks;
if (passed) {
std::printf("ok: %s\n", name);
} else {
std::fprintf(stderr, "FAIL: %s\n", name);
++failures;
}
}
volatile LONG g_illegal = 0; // illegal-instruction exceptions seen first-chance
volatile LONG g_write_faults = 0; // write faults that reached the last handler
volatile ULONG_PTR g_fault_address = 0;
void* g_unprotect = nullptr; // page the last handler makes writable when it faults
SIZE_T g_unprotect_size = 0;
// Registered first: sees every illegal instruction before BetterXen's handler emulates it.
LONG CALLBACK count_first(PEXCEPTION_POINTERS ep) {
if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) InterlockedIncrement(&g_illegal);
return EXCEPTION_CONTINUE_SEARCH;
}
// Registered last: sees the write fault BetterXen passes on when a line is not writable.
LONG CALLBACK fix_last(PEXCEPTION_POINTERS ep) {
const EXCEPTION_RECORD& r = *ep->ExceptionRecord;
if (r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION || r.NumberParameters < 2 || r.ExceptionInformation[0] != 1) {
return EXCEPTION_CONTINUE_SEARCH;
}
InterlockedIncrement(&g_write_faults);
g_fault_address = r.ExceptionInformation[1];
DWORD old = 0;
if (!g_unprotect || !VirtualProtect(g_unprotect, g_unprotect_size, PAGE_READWRITE, &old)) {
return EXCEPTION_CONTINUE_SEARCH;
}
g_unprotect = nullptr;
return EXCEPTION_CONTINUE_EXECUTION; // the CLZERO runs again
}
using Loop = void (*)(uint8_t* start, uint8_t* limit); // rcx = start, rdx = limit
// mov rax, rcx ; L: clzero ; add rax, 0x40 ; cmp rax, rdx ; jb L ; ret
const uint8_t kLoopRdx[] = {0x48, 0x89, 0xC8, 0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4, 0xC3};
// mov rax, rcx ; mov r10, rdx ; L: clzero ; add rax, 0x40 ; cmp rax, r10 ; jb L ; ret
const uint8_t kLoopR10[] = {0x48, 0x89, 0xC8, 0x49, 0x89, 0xD2, 0x0F, 0x01, 0xFC, 0x48, 0x83,
0xC0, 0x40, 0x4C, 0x39, 0xD0, 0x72, 0xF4, 0xC3};
// The same loop with a NOP before the add, which is not the recognised form:
// mov rax, rcx ; L: clzero ; nop ; add rax, 0x40 ; cmp rax, rdx ; jb L ; ret
const uint8_t kLoopOther[] = {0x48, 0x89, 0xC8, 0x0F, 0x01, 0xFC, 0x90, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF3, 0xC3};
Loop make(const uint8_t* code, size_t size) {
void* page = VirtualAlloc(nullptr, 4096, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if (!page) return nullptr;
std::memcpy(page, code, size);
FlushInstructionCache(GetCurrentProcess(), page, size);
return reinterpret_cast<Loop>(page);
}
constexpr size_t kLine = 64;
// Lines [first, first + count) of `base` are zero and every other line of the `lines`-line buffer
// still holds the fill byte.
bool only_zeroed(const uint8_t* base, size_t lines, size_t first, size_t count) {
for (size_t line = 0; line < lines; ++line) {
const uint8_t want = (line >= first && line < first + count) ? 0x00 : 0xAA;
for (size_t i = 0; i < kLine; ++i) {
if (base[line * kLine + i] != want) return false;
}
}
return true;
}
LONG run(Loop loop, uint8_t* start, uint8_t* limit) {
InterlockedExchange(&g_illegal, 0);
loop(start, limit);
return g_illegal;
}
} // namespace
int main() {
(void)bx_veh_get_clwb_trap_count();
void* first = AddVectoredExceptionHandler(1, count_first);
void* last = AddVectoredExceptionHandler(0, fix_last);
Loop loop_rdx = make(kLoopRdx, sizeof(kLoopRdx));
Loop loop_r10 = make(kLoopR10, sizeof(kLoopR10));
Loop loop_other = make(kLoopOther, sizeof(kLoopOther));
if (!first || !last || !loop_rdx || !loop_r10 || !loop_other) {
std::fprintf(stderr, "FAIL: setup\n");
return 1;
}
// 1,026 lines: a sentinel line, 1,024 lines to work in, a sentinel line.
constexpr size_t kLines = 1026;
auto* buffer = static_cast<uint8_t*>(VirtualAlloc(nullptr, kLines * kLine, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
if (!buffer) {
std::fprintf(stderr, "FAIL: buffer\n");
return 1;
}
uint8_t* work = buffer + kLine;
// One line: the loop body runs once.
std::memset(buffer, 0xAA, kLines * kLine);
LONG illegal = run(loop_rdx, work, work + kLine);
if (illegal == 0) {
std::printf("SKIP: test_veh_clzero_loop: CLZERO raised no exception on this host (it runs natively)\n");
return 77;
}
expect(only_zeroed(buffer, kLines, 1, 1), "one line: exactly that line is zero");
expect(illegal == 1, "one line: one exception");
// 1,000 lines through the recognised form.
std::memset(buffer, 0xAA, kLines * kLine);
illegal = run(loop_rdx, work, work + 1000 * kLine);
expect(only_zeroed(buffer, kLines, 1, 1000), "1000 lines (cmp rax, rdx): exactly those lines are zero");
expect(illegal == 1, "1000 lines (cmp rax, rdx): one exception for the whole loop");
// The limit register is r10.
std::memset(buffer, 0xAA, kLines * kLine);
illegal = run(loop_r10, work, work + 1000 * kLine);
expect(only_zeroed(buffer, kLines, 1, 1000), "1000 lines (cmp rax, r10): exactly those lines are zero");
expect(illegal == 1, "1000 lines (cmp rax, r10): one exception for the whole loop");
// A limit one byte into an eleventh line: the loop runs while rax < limit, so eleven lines.
std::memset(buffer, 0xAA, kLines * kLine);
illegal = run(loop_rdx, work, work + 10 * kLine + 1);
expect(only_zeroed(buffer, kLines, 1, 11), "limit inside a line: that line is zeroed too");
expect(illegal == 1, "limit inside a line: one exception");
// A start 8 bytes into a line: each CLZERO zeroes the whole line containing rax. With the limit
// at the end of the tenth line, rax takes ten values below it.
std::memset(buffer, 0xAA, kLines * kLine);
illegal = run(loop_rdx, work + 8, work + 10 * kLine);
expect(only_zeroed(buffer, kLines, 1, 10), "unaligned start: ten whole lines are zero");
expect(illegal == 1, "unaligned start: one exception");
// A loop that is not the recognised form keeps the per-instruction path: same memory result,
// one exception per line.
std::memset(buffer, 0xAA, kLines * kLine);
illegal = run(loop_other, work, work + 8 * kLine);
expect(only_zeroed(buffer, kLines, 1, 8), "other loop form: exactly eight lines are zero");
expect(illegal == 8, "other loop form: one exception per line");
// A range that runs from a writable page into a read-only one. The lines of the first page are
// zeroed; the first line of the second page faults as a write to that page; once the last
// handler makes it writable the loop finishes.
auto* pages = static_cast<uint8_t*>(VirtualAlloc(nullptr, 2 * 4096, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
if (!pages) {
std::fprintf(stderr, "FAIL: pages\n");
return 1;
}
std::memset(pages, 0xAA, 2 * 4096);
DWORD old = 0;
VirtualProtect(pages + 4096, 4096, PAGE_READONLY, &old);
g_unprotect = pages + 4096;
g_unprotect_size = 4096;
InterlockedExchange(&g_write_faults, 0);
g_fault_address = 0;
illegal = run(loop_rdx, pages + 4096 - 4 * kLine, pages + 4096 + 4 * kLine);
expect(g_write_faults == 1, "read-only page: one write fault is passed on");
expect(g_fault_address == reinterpret_cast<ULONG_PTR>(pages + 4096), "read-only page: the fault names the first line of that page");
expect(only_zeroed(pages, 2 * 4096 / kLine, 4096 / kLine - 4, 8), "read-only page: all eight lines are zero after it is made writable");
// First exception zeroes the four writable lines; the fifth line traps and faults; its retry
// traps again and finishes the range.
expect(illegal == 3, "read-only page: three exceptions (range start, the fault, the retry)");
RemoveVectoredExceptionHandler(last);
RemoveVectoredExceptionHandler(first);
std::printf("%s: test_veh_clzero_loop (%u of %u checks passed)\n", failures ? "FAIL" : "PASS", checks - failures, checks);
return failures ? 1 : 0;
}