From 0ddf806359d30022a3152e61c93ed077212d25aa Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Mon, 23 Nov 2026 14:36:22 -0500 Subject: pe_loader: move an image with no relocation directory, refuse only on IMAGE_FILE_RELOCS_STRIPPED The loader refused any image whose preferred base was taken when it had no relocation directory. Windows' loader decides on the file header flag instead (LdrRelocateImage, the same in Wine's perform_relocations and ReactOS's LdrRelocateImageWithBias): IMAGE_FILE_RELOCS_STRIPPED set means the image cannot move and is refused (STATUS_CONFLICTING_ADDRESSES); with the flag clear and an empty directory the image is moved with nothing to fix up, as a second copy of such a DLL is. map_image now does the same, for an EXE and a DLL alike: it refuses to move a flag-set image (also one that has a relocation table, as Windows does), moves a flag-clear image without a directory and logs one "[rt] loader: ... moved ... with no relocations" line, so a move without fix-ups shows in traces. base_reservation::needed keeps reserving the main image's range for both kinds of image without relocations, and now also for a flag-set image with a table, so the main image keeps its base wherever it did before. The retail executable and every package DLL have a relocation table and the flag clear, so neither path applies to them. loader_test covers a flag-clear image moved when its base is held (it loads elsewhere, nothing is fixed up, its DllMain runs), the same image with the flag set (refused), the flag at a free base (maps), and the flag with a relocation table (refused). test_failed_dependency_not_registered's dependency shared its parent's base and was refused for that; it now fails on its corrupt import table, which is what the test describes. Co-Authored-By: Claude Opus 5.5 --- runtime/src/pe_loader.cpp | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) (limited to 'runtime/src/pe_loader.cpp') diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index c29a288a9..253a773b5 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -1425,10 +1425,7 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string& if (!m->base) m->base = static_cast(VirtualAlloc(reinterpret_cast(oh.ImageBase), oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); - if (!m->base) { - const auto relocs = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); - if (!relocs.Size) - throw std::runtime_error(m->name + ": preferred base is taken and the image has no relocations"); + if (!m->base) { // whether the image may move is decided at the relocation step below m->base = static_cast(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); if (!m->base) throw std::runtime_error(m->name + ": VirtualAlloc failed"); } @@ -1453,10 +1450,19 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string& } int64_t delta = reinterpret_cast(m->base) - static_cast(oh.ImageBase); - if (delta) { - m->relocated = true; - const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); - if (!dir.Size) throw std::runtime_error(m->name + ": the image has no relocations and isn't at its base"); + // Windows' loader (LdrRelocateImage) refuses to move an image only when IMAGE_FILE_RELOCS_STRIPPED is set; with the + // flag clear and no relocation directory it moves it and fixes up nothing, so the image is trusted to hold no + // absolute addresses. That move is logged so it shows in traces. base_reservation::needed still keeps the main + // image's range free when it has no relocation directory, so a main image is moved this way only where the + // range could not be had. + const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); + if (delta) m->relocated = true; + if (delta && (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)) + throw std::runtime_error(m->name + ": preferred base is taken and the image's relocations are stripped"); + if (delta && !dir.Size) + std::fprintf(stderr, "[rt] loader: %s: preferred base %#llx is taken, moved to %p with no relocations\n", + m->name.c_str(), static_cast(oh.ImageBase), static_cast(m->base)); + if (delta && dir.Size) { require_range(m->name, dir.VirtualAddress, dir.Size, m->size, "the relocation table"); auto* block = at(m->base, dir.VirtualAddress); auto* end = reinterpret_cast(block) + dir.Size; -- cgit v1.2.3 From ca56a0d5eff2f6217a593babcfaff87d46daa15d Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Mon, 23 Nov 2026 15:12:44 -0500 Subject: pe_loader: a relocation table is applied whatever RELOCS_STRIPPED says (Windows 11 measurement) Zombins2 measured the Windows 11 (26200) loader with synthetic x64 DLLs in #8847. An image with IMAGE_FILE_RELOCS_STRIPPED set and a relocation table was moved and fixed up when its base was taken. The previous commit refused that case, while main relocated it. That is now back to main's behaviour: a moved image with a table is fixed up whatever the flag says, and the flag refuses a move only when there is no table. base_reservation::needed is back to main's test (the directory size) and no longer reserves for a flag-set image with a table. The core change stays: with the flag clear and no relocation directory, the image is moved with nothing fixed up and the move is logged. That matches the measurement. Windows also refused flag-set DLLs without a relocation directory at a free base (error 487), and it is not known why. The loader keeps main's behaviour there and maps them at their base. runtime/README.md records this as an open question, and loader_test's check for it no longer claims Windows parity. The flag-with-table check now expects a move with the DIR64 fix-up applied. Co-Authored-By: Claude Opus 5.5 --- runtime/README.md | 9 +++++++-- runtime/src/base_reservation.h | 11 +++++------ runtime/src/pe_loader.cpp | 12 ++++++------ runtime/test/loader_test.cpp | 35 ++++++++++++++++++++++++++--------- 4 files changed, 44 insertions(+), 23 deletions(-) (limited to 'runtime/src/pe_loader.cpp') diff --git a/runtime/README.md b/runtime/README.md index b91689582..abe3e841b 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -133,8 +133,13 @@ with the seed on stderr; a seed of 0 uses a fixed non-zero state. Unset, the hos ## PE loader `src/pe_loader.cpp` maps x86-64 images at their preferred base, or elsewhere (with relocations) when -that base is taken. As on Windows, only `IMAGE_FILE_RELOCS_STRIPPED` refuses the move; an image with the flag -clear and no relocation directory is moved with nothing fixed up, and the loader logs that. It copies headers and +that base is taken. An image with a relocation table is moved and fixed up whatever `IMAGE_FILE_RELOCS_STRIPPED` +says; without one, the flag refuses the move, and an image with the flag clear is moved with nothing fixed up (the +loader logs that). The Windows 11 loader does the same in these three cases, as measured by Zombins2 with +synthetic DLLs ([#8847](https://github.com/ItsNotRexed/Leonida/pull/8847#issuecomment-7112587898)). Open +question from the same measurement: Windows also refused flag-set DLLs without a relocation directory at a free +preferred base (error 487, linker-built `/FIXED` DLLs included), and why is not known; the loader still maps those +at their base, as before. It copies headers and sections, applies `IMAGE_REL_BASED_DIR64` relocations, binds imports by name or ordinal, parses the export table, sets section protections, and registers the image's x64 unwind table (`.pdata`) with `RtlAddFunctionTable`, so exceptions raised in or passing diff --git a/runtime/src/base_reservation.h b/runtime/src/base_reservation.h index 485cf5917..5ccfe1aaa 100644 --- a/runtime/src/base_reservation.h +++ b/runtime/src/base_reservation.h @@ -63,10 +63,10 @@ inline void* commit_reserved(std::uint64_t base, std::uint64_t size) { } // The preferred range of `image` when it has no relocations and that range is not free in this process; nullopt -// when the image can be mapped as it is (or is not a readable PE32+, which the loader reports itself). "No -// relocations" is either IMAGE_FILE_RELOCS_STRIPPED, which the loader refuses to move, or an empty relocation -// directory with the flag clear, which it moves with nothing fixed up (as Windows does): that is right only for an -// image with no absolute addresses in it, so its range is kept free all the same. +// when the image can be mapped as it is (or is not a readable PE32+, which the loader reports itself). Without a +// relocation directory the loader refuses to move an image that has IMAGE_FILE_RELOCS_STRIPPED, and moves one with +// the flag clear with nothing fixed up: that is right only for an image with no absolute addresses in it, so its +// range is kept free either way. An image with a relocation table is moved and fixed up whatever the flag says. inline std::optional needed(const std::filesystem::path& image) { std::ifstream file(image, std::ios::binary); IMAGE_DOS_HEADER dos{}; @@ -78,8 +78,7 @@ inline std::optional needed(const std::filesystem::path& image) { !nt.OptionalHeader.SizeOfImage) return std::nullopt; const auto& oh = nt.OptionalHeader; - if (!(nt.FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED) && - oh.NumberOfRvaAndSizes > IMAGE_DIRECTORY_ENTRY_BASERELOC && + if (oh.NumberOfRvaAndSizes > IMAGE_DIRECTORY_ENTRY_BASERELOC && oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].Size) return std::nullopt; // relocatable: the loader moves it if the base is taken const Range r{oh.ImageBase, (static_cast(oh.SizeOfImage) + 0xffff) & ~std::uint64_t{0xffff}}; diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index 253a773b5..1c6b91b54 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -1450,14 +1450,14 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string& } int64_t delta = reinterpret_cast(m->base) - static_cast(oh.ImageBase); - // Windows' loader (LdrRelocateImage) refuses to move an image only when IMAGE_FILE_RELOCS_STRIPPED is set; with the - // flag clear and no relocation directory it moves it and fixes up nothing, so the image is trusted to hold no - // absolute addresses. That move is logged so it shows in traces. base_reservation::needed still keeps the main - // image's range free when it has no relocation directory, so a main image is moved this way only where the - // range could not be had. + // A moved image with a relocation table is fixed up, whatever IMAGE_FILE_RELOCS_STRIPPED says. Without a table, + // the flag refuses the move; with the flag clear the image is moved and nothing is fixed up, so it is trusted to + // hold no absolute addresses. The Windows 11 loader does all three (measured in #8847); that move is logged so + // it shows in traces. base_reservation::needed still keeps the main image's range free when it has no + // relocation directory, so a main image is moved this way only where the range could not be had. const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); if (delta) m->relocated = true; - if (delta && (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)) + if (delta && !dir.Size && (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)) throw std::runtime_error(m->name + ": preferred base is taken and the image's relocations are stripped"); if (delta && !dir.Size) std::fprintf(stderr, "[rt] loader: %s: preferred base %#llx is taken, moved to %p with no relocations\n", diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp index a49a75385..926becd12 100644 --- a/runtime/test/loader_test.cpp +++ b/runtime/test/loader_test.cpp @@ -654,10 +654,11 @@ void test_initialise_rejects() { } } -// An image with no relocation directory whose preferred base is taken. Windows' loader (LdrRelocateImage) refuses to -// move an image only when IMAGE_FILE_RELOCS_STRIPPED is set; with the flag clear it maps it elsewhere and fixes up -// nothing, as it does for a second copy of such a DLL. The DllMain stub stores through an absolute address in this -// process, not in the image, so it runs correctly wherever the image lands. +// IMAGE_FILE_RELOCS_STRIPPED against a relocation directory, when the preferred base is taken. Measured on the +// Windows 11 (26200) loader with synthetic DLLs (#8847): with no relocation directory the flag refuses the move and +// an image with the flag clear is moved with nothing fixed up; with a relocation table the image is moved and fixed +// up whatever the flag says. The DllMain stub stores through an absolute address in this process, not in the image, +// so it runs correctly wherever the image lands. void test_moved_without_relocations() { auto img = make_image(); auto* nt = nt_of(img); @@ -704,13 +705,16 @@ void test_moved_without_relocations() { } if (held) VirtualFree(held, 0, MEM_RELEASE); { - // The flag only forbids moving: at a free base such an image maps as usual. + // At a free base such an image maps, as it did before. Not Windows parity: the Windows 11 loader refused these + // DLLs (error 487) at a free base too, for a reason not yet known (#8847); runtime/README.md keeps the question. auto stripped = img; nt_of(stripped)->FileHeader.Characteristics |= IMAGE_FILE_RELOCS_STRIPPED; - expect_loads("an image with IMAGE_FILE_RELOCS_STRIPPED maps at its free base", stripped); + expect_loads("an image with IMAGE_FILE_RELOCS_STRIPPED and no relocations maps at its free base", stripped); } { - // Windows refuses on the flag, whatever the relocation directory holds. ImageBase 0 makes the loader move it. + // With a relocation table the flag does not stop the move: the table is applied, as Windows does it. + // ImageBase 0 makes the loader move it; the one DIR64 entry points at the qword at RVA 0x1100. + const char* what = "an image with IMAGE_FILE_RELOCS_STRIPPED and a relocation table is moved and fixed up"; auto stripped = make_image(); auto* snt = nt_of(stripped); snt->FileHeader.Characteristics |= IMAGE_FILE_RELOCS_STRIPPED; @@ -719,8 +723,21 @@ void test_moved_without_relocations() { auto* block = reinterpret_cast(stripped.data() + 0x200); block->VirtualAddress = 0x1000; block->SizeOfBlock = 0x0A; - reinterpret_cast(block + 1)[0] = IMAGE_REL_BASED_DIR64 << 12; - expect_rejects("an image with IMAGE_FILE_RELOCS_STRIPPED and a relocation table is not moved", stripped); + reinterpret_cast(block + 1)[0] = (IMAGE_REL_BASED_DIR64 << 12) | 0x100; + uint64_t original; + std::memcpy(&original, stripped.data() + 0x300, sizeof original); + auto p = write_image(stripped); + try { + rt::Loader loader(g_dir); + rt::Module& m = loader.load(p); + uint64_t moved; + std::memcpy(&moved, m.base + 0x1100, sizeof moved); + if (!m.relocated) failed(what, "it was not moved"); + else if (moved != original + reinterpret_cast(m.base)) failed(what, "the pointer wasn't fixed up"); + else pass(what); + } catch (const std::exception& e) { + failed(what, e.what()); + } } } -- cgit v1.2.3 From bb256ebbf32d7493e3d867923ec737e60d3f9f9d Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Tue, 24 Nov 2026 05:00:08 -0500 Subject: pe_loader: the relocation-move notes stop citing the old pull request number The Windows 11 measurement behind this behaviour was posted in a review of pull request 8847 of the original repository, which went private on 2026-11-23, so its link and the "#8847" references in pe_loader.cpp and loader_test.cpp lead nowhere now. runtime/README.md keeps the measurement and the open question in its own words and names where it came from; the code comments point at the README. No behaviour changes. Co-Authored-By: Claude Opus 5.5 --- runtime/README.md | 9 ++++----- runtime/src/pe_loader.cpp | 2 +- runtime/test/loader_test.cpp | 10 +++++----- 3 files changed, 10 insertions(+), 11 deletions(-) (limited to 'runtime/src/pe_loader.cpp') diff --git a/runtime/README.md b/runtime/README.md index abe3e841b..268ceb45f 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -135,12 +135,11 @@ with the seed on stderr; a seed of 0 uses a fixed non-zero state. Unset, the hos `src/pe_loader.cpp` maps x86-64 images at their preferred base, or elsewhere (with relocations) when that base is taken. An image with a relocation table is moved and fixed up whatever `IMAGE_FILE_RELOCS_STRIPPED` says; without one, the flag refuses the move, and an image with the flag clear is moved with nothing fixed up (the -loader logs that). The Windows 11 loader does the same in these three cases, as measured by Zombins2 with -synthetic DLLs ([#8847](https://github.com/ItsNotRexed/Leonida/pull/8847#issuecomment-7112587898)). Open -question from the same measurement: Windows also refused flag-set DLLs without a relocation directory at a free +loader logs that). The Windows 11 (build 26200) loader does the same in these three cases, as Zombins2 measured +with synthetic DLLs in a review of old pull request 8847 of the original repository, which is no longer readable. +Open question from the same measurement: Windows also refused flag-set DLLs without a relocation directory at a free preferred base (error 487, linker-built `/FIXED` DLLs included), and why is not known; the loader still maps those -at their base, as before. It copies headers and -sections, applies `IMAGE_REL_BASED_DIR64` relocations, binds +at their base, as before. It copies headers and sections, applies `IMAGE_REL_BASED_DIR64` relocations, binds imports by name or ordinal, parses the export table, sets section protections, and registers the image's x64 unwind table (`.pdata`) with `RtlAddFunctionTable`, so exceptions raised in or passing through a mapped image are dispatched and stack walks can step over its frames. The table is validated diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index 1c6b91b54..de42996f5 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -1452,7 +1452,7 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string& int64_t delta = reinterpret_cast(m->base) - static_cast(oh.ImageBase); // A moved image with a relocation table is fixed up, whatever IMAGE_FILE_RELOCS_STRIPPED says. Without a table, // the flag refuses the move; with the flag clear the image is moved and nothing is fixed up, so it is trusted to - // hold no absolute addresses. The Windows 11 loader does all three (measured in #8847); that move is logged so + // hold no absolute addresses. The Windows 11 loader does all three (runtime/README.md); that move is logged so // it shows in traces. base_reservation::needed still keeps the main image's range free when it has no // relocation directory, so a main image is moved this way only where the range could not be had. const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp index 926becd12..6930878a9 100644 --- a/runtime/test/loader_test.cpp +++ b/runtime/test/loader_test.cpp @@ -655,10 +655,10 @@ void test_initialise_rejects() { } // IMAGE_FILE_RELOCS_STRIPPED against a relocation directory, when the preferred base is taken. Measured on the -// Windows 11 (26200) loader with synthetic DLLs (#8847): with no relocation directory the flag refuses the move and -// an image with the flag clear is moved with nothing fixed up; with a relocation table the image is moved and fixed -// up whatever the flag says. The DllMain stub stores through an absolute address in this process, not in the image, -// so it runs correctly wherever the image lands. +// Windows 11 (26200) loader with synthetic DLLs (runtime/README.md): with no relocation directory the flag refuses +// the move and an image with the flag clear is moved with nothing fixed up; with a relocation table the image is +// moved and fixed up whatever the flag says. The DllMain stub stores through an absolute address in this process, +// not in the image, so it runs correctly wherever the image lands. void test_moved_without_relocations() { auto img = make_image(); auto* nt = nt_of(img); @@ -706,7 +706,7 @@ void test_moved_without_relocations() { if (held) VirtualFree(held, 0, MEM_RELEASE); { // At a free base such an image maps, as it did before. Not Windows parity: the Windows 11 loader refused these - // DLLs (error 487) at a free base too, for a reason not yet known (#8847); runtime/README.md keeps the question. + // DLLs (error 487) at a free base too, for a reason not yet known; runtime/README.md keeps the question. auto stripped = img; nt_of(stripped)->FileHeader.Characteristics |= IMAGE_FILE_RELOCS_STRIPPED; expect_loads("an image with IMAGE_FILE_RELOCS_STRIPPED and no relocations maps at its free base", stripped); -- cgit v1.2.3 From 82d6883bed1c18dfb4d409314e7805262aded79e Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Mon, 23 Nov 2026 11:41:08 -0500 Subject: pe_loader: trace delay imports bound to an unimplemented thunk; note delay-load and thread-attach order Delay imports are bound eagerly (deliberate: --dry-run shows the whole import surface). A delay-loaded DLL or function that nothing serves becomes an unimplemented thunk returning 0 at its first call, where Windows' delay-load helper raises 0xC06D007E / 0xC06D007F, which a title can catch for a fallback. The binding is unchanged; --trace now writes a delay_import_unimplemented event (module, import) for each such import at load, so the first boot names them before any image code runs. docs/runtime_imports.md gets two notes on where the loader differs from Windows: the eager delay binding above, and that DLL_THREAD_ATTACH reaches TLS callbacks in TLS slot order, which puts the executable before the DLLs it imports (Windows' order is undocumented). runtime/README.md lists the new trace event and now says the loader applies DIR64 and HIGHLOW relocations and rejects HIGH, LOW and HIGHADJ (old upstream 761). startup_trace_test gets a synthetic DLL with one ordinary and two delay imports (one missing, one bound to kernel32): exactly one delay_import_unimplemented event, naming the missing delay import. Findings by cynbun in the old upstream coordination issue (old upstream 7231). Co-Authored-By: Claude Opus 5.5 --- docs/runtime_imports.md | 16 ++++++ runtime/README.md | 4 +- runtime/shims/startup_trace.h | 9 ++-- runtime/src/pe_loader.cpp | 13 +++-- runtime/test/startup_trace_test.cpp | 100 +++++++++++++++++++++++++++++++++++- 5 files changed, 133 insertions(+), 9 deletions(-) (limited to 'runtime/src/pe_loader.cpp') diff --git a/docs/runtime_imports.md b/docs/runtime_imports.md index 7b9f62d5a..79741f785 100644 --- a/docs/runtime_imports.md +++ b/docs/runtime_imports.md @@ -287,6 +287,22 @@ families are not listed. The sources are the Microsoft Learn pages for the D3D12 (`gaming/gdk/docs/reference/system//functions/`); `D3D12XboxCreateDevice` is matched by name from the measurement in `d3d12_vulkan.md`, because its page could not be found. +### Delay imports and thread events: where the loader differs from Windows + +- **Delay imports are bound eagerly.** `Loader::bind_imports` (`runtime/src/pe_loader.cpp`) binds the delay-import + table at load time, like the import table, so `--dry-run` shows the whole import surface. A delay-loaded DLL or + function that nothing serves becomes an unimplemented thunk, which follows `LEONIDA_UNIMPLEMENTED` at its first + call (return 0 by default). On Windows the delay-load helper raises `0xC06D007E` (module not found) or + `0xC06D007F` (procedure not found) at that call instead, and a title can catch it and take a fallback; that fallback + never runs here. `--trace` writes a `delay_import_unimplemented` event (`module`, `import`) for each such import + when the image is loaded. +- **Thread events reach TLS callbacks in TLS slot order.** A new thread's `DLL_THREAD_ATTACH` runs the mapped + modules' TLS callbacks in the order of their TLS slots (`DLL_THREAD_DETACH` in reverse). A module takes the lowest + free slot when it is mapped, before its imports are loaded, so the executable's callbacks run before those of the + DLLs it imports; a slot freed by an unloaded module goes to the next one. Windows does not document its order, so a + title that depends on DLL-first order would see a difference here. Mapped DLLs' `DllMain` gets no thread events + (`runtime/README.md`, PE loader). + ## Run-time loaded modules Not every console module is reached through an import table. `libHttpClient.GDK.dll` and `XCurl.dll` both use the diff --git a/runtime/README.md b/runtime/README.md index 61794a2c2..5859d4fe5 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -133,7 +133,8 @@ with the seed on stderr; a seed of 0 uses a fixed non-zero state. Unset, the hos ## PE loader `src/pe_loader.cpp` maps x86-64 images at their preferred base, or elsewhere (with relocations) when -that base is taken, copies headers and sections, applies `IMAGE_REL_BASED_DIR64` relocations, binds +that base is taken, copies headers and sections, applies `IMAGE_REL_BASED_DIR64` and `HIGHLOW` relocations +(rejecting the other types, such as `HIGH`, `LOW` and `HIGHADJ`, which no x64 MSVC image contains), binds imports by name or ordinal, parses the export table, sets section protections, and registers the image's x64 unwind table (`.pdata`) with `RtlAddFunctionTable`, so exceptions raised in or passing through a mapped image are dispatched and stack walks can step over its frames. The table is validated @@ -449,6 +450,7 @@ from the ANSI code page. | `tls_callback` | before each TLS callback the Loader runs (process attach and detach; thread events run under the Windows loader lock and are not traced) | `module`, `at` (module+RVA), `reason` | | `dllmain` | after `DllMain(DLL_PROCESS_ATTACH)` returns | `module`, `result` | | `unimplemented_call` | first call of each unimplemented import | `import` (`dll!name`), `caller` (module+RVA) | +| `delay_import_unimplemented` | at load, for each delay import that binds to an unimplemented thunk (Windows would raise `0xC06D007E`/`0xC06D007F` at its first call; [runtime_imports.md](../docs/runtime_imports.md#delay-imports-and-thread-events-where-the-loader-differs-from-windows)) | `module`, `import` (`dll!name`) | | `xmem_attributes` | the first `XMemAlloc`, `XMemFree`, `XMemAllocDefault`, `XMemFreeDefault` and `XMemVirtualAlloc` for each distinct raw attribute word (not every allocation) | `api`, `attributes`, `size` (not for the frees), `caller` (module+RVA) | | `xmem_physical_pages` | the first `XMemAllocatePhysicalPages` for each distinct attribute word | `api`, `attributes`, `pages`, `caller` | | `file_open_failed` | a guest `CreateFileW`/`CreateFile2` that fails (at most 256 events) | `api`, `path` (as the title passed it), `error` (Win32), `caller` (module+RVA) | diff --git a/runtime/shims/startup_trace.h b/runtime/shims/startup_trace.h index 7b47d993a..7fb9cdfea 100644 --- a/runtime/shims/startup_trace.h +++ b/runtime/shims/startup_trace.h @@ -6,11 +6,12 @@ // {"seq":2,"t":0.001,"kind":"map","module":"a.dll","base":"0x...","size":"0x2000","relocated":false} // {"seq":3,"t":0.002,"kind":"tls_callback","module":"a.dll","at":"a.dll+0x1200","reason":1} // {"seq":4,"t":0.002,"kind":"dllmain","module":"a.dll","result":1} -// {"seq":5,"t":0.010,"kind":"unimplemented_call","import":"x.dll!Foo","caller":"a.dll+0x3f10"} (first call only) -// {"seq":6,"t":0.011,"kind":"debug_string","text":"..."} -// {"seq":7,"t":0.020,"kind":"exception","code":"0xc0000005","at":"a.dll+0x4a00","access":"read","address":"0x0", +// {"seq":5,"t":0.002,"kind":"delay_import_unimplemented","module":"a.dll","import":"x.dll!Bar"} (at load) +// {"seq":6,"t":0.010,"kind":"unimplemented_call","import":"x.dll!Foo","caller":"a.dll+0x3f10"} (first call only) +// {"seq":7,"t":0.011,"kind":"debug_string","text":"..."} +// {"seq":8,"t":0.020,"kind":"exception","code":"0xc0000005","at":"a.dll+0x4a00","access":"read","address":"0x0", // "stack":["a.dll+0x4a00","a.dll+0x2210"]} -// {"seq":8,"t":0.030,"kind":"exit","code":0} +// {"seq":9,"t":0.030,"kind":"exit","code":0} // // The exception handler is vectored, logs and returns EXCEPTION_CONTINUE_SEARCH: it never changes what the process // does (except LEONIDA_SKIP_INT3, below). diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index c29a288a9..ebb1531bd 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -1796,7 +1796,10 @@ void Loader::bind_imports(Module& m) { const uint64_t headers_end = nt->OptionalHeader.SizeOfHeaders; // Thunk tables have no length field: they end at a zero entry, so each step is checked against the image. - auto bind_thunks = [&](const std::string& dll, uint64_t lookup_rva, uint64_t iat_rva) { + // `delayed`: a delay import that binds to an unimplemented thunk is traced. Windows' delay-load helper would raise + // 0xC06D007E (module) or 0xC06D007F (procedure) at its first call, which a title can catch for a fallback; the + // thunk returns 0 instead, so the trace names each such import before any image code runs. + auto bind_thunks = [&](const std::string& dll, uint64_t lookup_rva, uint64_t iat_rva, bool delayed) { for (;; lookup_rva += sizeof(IMAGE_THUNK_DATA64), iat_rva += sizeof(IMAGE_THUNK_DATA64)) { require_range(m.name, lookup_rva, sizeof(IMAGE_THUNK_DATA64), m.size, "an import lookup table"); require_range(m.name, iat_rva, sizeof(IMAGE_THUNK_DATA64), m.size, "an import address table"); @@ -1814,6 +1817,10 @@ void Loader::bind_imports(Module& m) { throw std::runtime_error(m.name + ": an import address table lands in the headers"); at(m.base, static_cast(iat_rva))->u1.Function = reinterpret_cast(resolve(m, dll, name, ord, by_ord)); + if (delayed && startup_trace::enabled() && m.imports.back().binding == Binding::Unimplemented) + startup_trace::event("delay_import_unimplemented", + "\"module\":" + startup_trace::quote(m.name) + ",\"import\":" + + startup_trace::quote(dll + "!" + m.imports.back().name)); } }; @@ -1826,7 +1833,7 @@ void Loader::bind_imports(Module& m) { if (!d->Name) break; std::string dll = read_string(m.name, m.base, m.size, d->Name, "an imported DLL name"); uint32_t lookup = d->OriginalFirstThunk ? d->OriginalFirstThunk : d->FirstThunk; - bind_thunks(dll, lookup, d->FirstThunk); + bind_thunks(dll, lookup, d->FirstThunk, false); } } // Delay imports are bound eagerly: simpler, and the full import surface shows up in --dry-run. @@ -1849,7 +1856,7 @@ void Loader::bind_imports(Module& m) { // thunk addresses as name RVAs. if (!d->ImportNameTableRVA) throw std::runtime_error(m.name + ": a delay-import descriptor has no name table"); - bind_thunks(dll, d->ImportNameTableRVA, d->ImportAddressTableRVA); + bind_thunks(dll, d->ImportNameTableRVA, d->ImportAddressTableRVA, true); } } } diff --git a/runtime/test/startup_trace_test.cpp b/runtime/test/startup_trace_test.cpp index 336f957eb..75dcc669b 100644 --- a/runtime/test/startup_trace_test.cpp +++ b/runtime/test/startup_trace_test.cpp @@ -7,7 +7,8 @@ // 0x1220 reads address 0 (an access violation the test catches) // The loader maps it with the trace open, the test calls the three functions, closes the trace and checks the lines: // map, unimplemented_call with the caller as module+RVA, debug_string with the text, exception with the faulting -// RVA and access kind. No game data and no GPU are involved. +// RVA and access kind. A second image with delay imports checks delay_import_unimplemented (make_delay_image). +// No game data and no GPU are involved. // LEONIDA_TEST_DIR names the folder for the image and the trace, as for loader_test; the default is the temp folder. #include @@ -277,6 +278,102 @@ void test_trace(const fs::path& dir) { check(find_line(lines, "exit") == &lines.back(), "exit comes last"); } +// A DLL image with no code: one ordinary import that binds to nothing, and two delay-import descriptors, one naming a +// function nothing serves and one naming kernel32!GetTickCount (bound to the host). Delay imports are bound when the +// image is loaded, so the trace names the missing one then; the ordinary missing import and the bound delay import +// give no such event. +constexpr const char* kDelayImageName = "delay_image.bin"; + +std::vector make_delay_image() { + std::vector b(0x600, 0); + auto* dos = reinterpret_cast(b.data()); + dos->e_magic = IMAGE_DOS_SIGNATURE; + dos->e_lfanew = 0x80; + auto* nt = reinterpret_cast(b.data() + dos->e_lfanew); + nt->Signature = IMAGE_NT_SIGNATURE; + nt->FileHeader.Machine = IMAGE_FILE_MACHINE_AMD64; + nt->FileHeader.NumberOfSections = 1; + nt->FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER64); + nt->FileHeader.Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_DLL | IMAGE_FILE_LARGE_ADDRESS_AWARE; + nt->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC; + nt->OptionalHeader.ImageBase = 0x1a0000000; + nt->OptionalHeader.SizeOfHeaders = 0x200; + nt->OptionalHeader.SizeOfImage = 0x2000; + nt->OptionalHeader.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI; + nt->OptionalHeader.NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES; + auto* sec = IMAGE_FIRST_SECTION(nt); + std::memcpy(sec->Name, ".data", 6); + sec->VirtualAddress = kTextRva; + sec->Misc.VirtualSize = 0x400; + sec->PointerToRawData = 0x200; + sec->SizeOfRawData = 0x400; + sec->Characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE; + + uint8_t* data = b.data() + 0x200; + auto put_string = [&](uint32_t off, const char* s) { std::strcpy(reinterpret_cast(data + off), s); }; + // One name table entry and its terminator at `lookup_off`, the import's hint/name at `hint_off`. + auto put_thunk = [&](uint32_t lookup_off, uint32_t hint_off, const char* name) { + *reinterpret_cast(data + lookup_off) = kTextRva + hint_off; + put_string(hint_off + 2, name); + }; + put_string(0x100, "leonida_trace_probe.dll"); + put_string(0x120, "kernel32.dll"); + + auto* d = reinterpret_cast(data); + d->Name = kTextRva + 0x100; + d->OriginalFirstThunk = kTextRva + 0x140; + d->FirstThunk = kTextRva + 0x160; + put_thunk(0x140, 0x180, "NormalProbeMissing"); + + const struct { + uint32_t dll_off, int_off, iat_off, hint_off; + const char* name; + } delayed[2] = {{0x100, 0x1A0, 0x1C0, 0x1E0, "DelayProbeMissing"}, {0x120, 0x200, 0x220, 0x240, "GetTickCount"}}; + for (int i = 0; i < 2; ++i) { + auto* dd = reinterpret_cast(data + 0x40) + i; + dd->Attributes.AllAttributes = 1; // dlattrRva + dd->DllNameRVA = kTextRva + delayed[i].dll_off; + dd->ImportNameTableRVA = kTextRva + delayed[i].int_off; + dd->ImportAddressTableRVA = kTextRva + delayed[i].iat_off; + put_thunk(delayed[i].int_off, delayed[i].hint_off, delayed[i].name); + } + + auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; + dir.VirtualAddress = kTextRva; + dir.Size = 2 * sizeof(IMAGE_IMPORT_DESCRIPTOR); + auto& ddir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT]; + ddir.VirtualAddress = kTextRva + 0x40; + ddir.Size = 3 * sizeof(IMAGE_DELAYLOAD_DESCRIPTOR); + return b; +} + +void test_delay_import_trace(const fs::path& dir) { + const fs::path image = write_file(dir / kDelayImageName, make_delay_image()); + const fs::path trace = dir / "delay_trace.jsonl"; + check(rt::startup_trace::open(trace.c_str()), "open the delay-import trace file"); + { + rt::Loader loader(dir); + rt::Module& m = loader.load(image); + int unimplemented = 0, host = 0; + for (const auto& r : m.imports) { + unimplemented += r.binding == rt::Binding::Unimplemented; + host += r.binding == rt::Binding::Host; + } + check(m.imports.size() == 3 && unimplemented == 2 && host == 1, + "the delay image binds 3 imports: 2 unimplemented, 1 host"); + } + rt::startup_trace::close(); + + const auto lines = read_lines(trace); + int events = 0; + for (auto& l : lines) events += l.find("\"kind\":\"delay_import_unimplemented\"") != std::string::npos; + const std::string* e = find_line(lines, "delay_import_unimplemented"); + check(events == 1, "one delay_import_unimplemented event (got " + std::to_string(events) + ")"); + check(has(e, "\"module\":\"" + std::string(kDelayImageName) + "\"") && + has(e, "\"import\":\"leonida_trace_probe.dll!DelayProbeMissing\""), + "delay_import_unimplemented names the module and the delay import"); +} + } // namespace int wmain() { @@ -285,6 +382,7 @@ int wmain() { test_disabled_is_silent(); test_existing_file_is_kept(dir); test_trace(dir); + test_delay_import_trace(dir); std::error_code ec; fs::remove_all(dir, ec); } catch (const std::exception& e) { -- cgit v1.2.3 From 582e14d922ad9b24a63ba55f7b8e57bd4aef3c08 Mon Sep 17 00:00:00 2001 From: Mike7581 <168859477+Mike7581@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:38:28 -0300 Subject: loader: a run-time LoadLibrary takes the LEONIDA_COMPAT_DIR module too LEONIDA_COMPAT_DIR only applied to static imports: runtime/README.md said "a run-time LoadLibrary of the same name does not yet". A mapped image's LoadLibrary of a module the folder holds got the shim's pseudo-handle instead of the drop-in DLL, and GetProcAddress on the compat DLL's real handle looked the name up in the shim of the same module name first, so one console module could be served half by the drop-in and half by the shim, which the static step exists to prevent. Now shims::BundledModuleOps gains compat_module / owns_compat_handle, which rt::Loader answers from the same compat_handle() its static step (resolve_compat) uses, so both get one HMODULE per module. In shims/library_loader.cpp: - LoadLibrary* checks the compat folder before the shim registry and the bundled package DLLs; - GetModuleHandle* answers a compat module's handle once it is loaded and NULL before (never the shim's pseudo-handle); - GetProcAddress on a compat handle gives only that DLL's exports; - FreeLibrary on it returns TRUE and keeps it loaded (it is the Loader's reference, static imports may be bound through it; compat modules stay for the process lifetime). A compat file Windows refuses fails that LoadLibrary with Windows' error (logged) instead of throwing into the title. loader_test links library_loader.cpp and gains test_compat_runtime_loads: eight cases with a synthetic drop-in DLL and the test shim module, no game data. --- runtime/CMakeLists.txt | 1 + runtime/README.md | 6 ++- runtime/shims/library_loader.cpp | 33 +++++++++++++- runtime/shims/registry.cpp | 21 +++++++++ runtime/shims/shims.h | 8 ++++ runtime/src/pe_loader.cpp | 97 ++++++++++++++++++++++++++++++---------- runtime/src/pe_loader.h | 9 ++++ runtime/test/loader_test.cpp | 87 +++++++++++++++++++++++++++++++++++ 8 files changed, 235 insertions(+), 27 deletions(-) (limited to 'runtime/src/pe_loader.cpp') diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 48c8af360..7e093864b 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -771,6 +771,7 @@ if(BUILD_TESTING) test/loader_test.cpp src/pe_loader.cpp shims/registry.cpp + shims/library_loader.cpp # the run-time LEONIDA_COMPAT_DIR cases call its LoadLibrary / GetProcAddress ) target_compile_definitions(loader_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE) target_compile_options(loader_test PRIVATE /W4 /permissive- /utf-8 /EHsc) diff --git a/runtime/README.md b/runtime/README.md index fadaa47ef..6a98d5039 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -111,8 +111,10 @@ bundled package DLLs and the host, and the DLL owns all of its module's imports: the unimplemented thunk, not to a shim, so one console DLL is never served by two implementations that do not share state. The binding is reported as `host`, and `[rt] compat: -> ` is printed once per DLL. A file in the folder that Windows refuses to load stops the run with the error code. Unset or empty: no change. The DLLs stay -loaded for the process lifetime. Only static imports go through this step; a run-time `LoadLibrary` of the same name -does not yet. +loaded for the process lifetime. A run-time `LoadLibrary` of the same name (from a mapped image, through +`shims/library_loader.cpp`) gets the same DLL and handle, ahead of the shim; `GetModuleHandle` answers it once loaded, +`GetProcAddress` on it gives only its own exports, and `FreeLibrary` leaves it loaded. A file Windows refuses to load +there fails that `LoadLibrary` with Windows' error instead of stopping the run. It exists for drop-in implementations of console DLLs that have no shim here, such as the `AcpHal`, `chad`, `xapu` and `XCRDAPI` crates of [omonkeyz/xbox-emulator](https://github.com/omonkeyz/xbox-emulator) (GPL-3.0-or-later). diff --git a/runtime/shims/library_loader.cpp b/runtime/shims/library_loader.cpp index 3a96092df..9e7270723 100644 --- a/runtime/shims/library_loader.cpp +++ b/runtime/shims/library_loader.cpp @@ -12,6 +12,10 @@ // registry doesn't serve returns NULL with ERROR_PROC_NOT_FOUND, as a real module would, and is logged once. Every // other module uses the same named shims as static imports, falling back to the host. Only images mapped by the // loader see these: they are bound through the registry, the runtime's own code calls the host directly. +// +// A module whose DLL is in LEONIDA_COMPAT_DIR comes first, as for static imports: LoadLibrary returns that DLL (the +// handle the Loader's static imports use), GetModuleHandle returns it once loaded and NULL before, GetProcAddress on +// it gives only its own exports, and FreeLibrary leaves it loaded. #include #include @@ -141,6 +145,16 @@ constexpr DWORD kDataFileLoadFlags = HMODULE load_shim_or_bundled(const std::string& path, DWORD flags, bool& handled) { handled = false; + // LEONIDA_COMPAT_DIR first, as for static imports (rt::Loader::resolve): a drop-in DLL owns its module, so a + // run-time load gets the same Windows-loaded DLL, never the shim. Its handle is a real module handle. + if (const std::string dll = module_name(path); !dll.empty()) { + bool compat = false; + void* h = compat_module(dll, true, compat); + if (compat) { + handled = true; + return reinterpret_cast(h); + } + } if (HMODULE h = owned_handle(path)) { handled = true; return h; @@ -200,10 +214,20 @@ HMODULE WINAPI load_library_ex_w(LPCWSTR name, HANDLE file, DWORD flags) { return LoadLibraryExW(name, file, flags); } +// A LEONIDA_COMPAT_DIR module answers GetModuleHandle as Windows would for it: its handle once loaded, else NULL. It is +// never the shim's pseudo-handle (`handled` is set when the folder holds the DLL). +HMODULE compat_loaded(const std::string& path, bool& handled) { + handled = false; + const std::string dll = module_name(path); + return dll.empty() ? nullptr : reinterpret_cast(compat_module(dll, false, handled)); +} + // GetModuleHandle answers for an owned module as if it were loaded (the GDK may probe before it loads), and for any // bundled package module already mapped by the native loader. HMODULE WINAPI get_module_handle_a(LPCSTR name) { if (name) { + bool compat = false; + if (HMODULE h = compat_loaded(name, compat); compat) return h; if (HMODULE h = owned_handle(name)) return h; const std::string dll = module_name(name); if (!dll.empty()) @@ -216,6 +240,8 @@ HMODULE WINAPI get_module_handle_w(LPCWSTR name) { if (name) { if (ascii_basename(name)) { const std::string path = narrow(name); + bool compat = false; + if (HMODULE h = compat_loaded(path, compat); compat) return h; if (HMODULE h = owned_handle(path)) return h; const std::string dll = module_name(path); if (!dll.empty()) @@ -267,7 +293,9 @@ FARPROC WINAPI get_proc_address(HMODULE module, LPCSTR name) { SetLastError(ERROR_PROC_NOT_FOUND); return nullptr; } - if (module) { + // A LEONIDA_COMPAT_DIR module's exports are its own: a name it lacks is not filled in from the shim of the same + // module name, as for its static imports. + if (module && !owns_compat_module_handle(module)) { const DWORD error = GetLastError(); const std::string dll = host_module_name(module); void* shim = dll.empty() ? nullptr : find(dll, what); @@ -280,6 +308,9 @@ FARPROC WINAPI get_proc_address(HMODULE module, LPCSTR name) { BOOL WINAPI free_library(HMODULE module) { if (pseudo(module)) return TRUE; // owned modules are never unloaded if (owns_bundled_module_handle(module)) return TRUE; // mapped modules stay live until ~Loader detaches them + // A run-time load of a LEONIDA_COMPAT_DIR module hands out the Loader's own reference, which static imports may + // be bound through: compat modules stay for the process lifetime. + if (owns_compat_module_handle(module)) return TRUE; return FreeLibrary(module); } diff --git a/runtime/shims/registry.cpp b/runtime/shims/registry.cpp index 59f1da106..a8dec0e4c 100644 --- a/runtime/shims/registry.cpp +++ b/runtime/shims/registry.cpp @@ -508,6 +508,27 @@ void* get_bundled_proc_address(void* module, const std::string& sym, bool& owns_ return nullptr; } +void* compat_module(const std::string& dll_lower, bool load, bool& handled) { + handled = false; + for (const auto& entry : snapshot_bundled_loaders()) { + if (!entry.ops->compat_module) continue; + bool loader_handled = false; + void* h = entry.ops->compat_module(entry.ctx, dll_lower, load, loader_handled); + if (loader_handled) { + handled = true; + return h; + } + } + return nullptr; +} + +bool owns_compat_module_handle(void* module) { + if (!module) return false; + for (const auto& entry : snapshot_bundled_loaders()) + if (entry.ops->owns_compat_handle && entry.ops->owns_compat_handle(entry.ctx, module)) return true; + return false; +} + bool owns_bundled_module_handle(void* module) { for (const auto& entry : snapshot_bundled_loaders()) if (entry.ops->owns_handle(entry.ctx, module)) return true; diff --git a/runtime/shims/shims.h b/runtime/shims/shims.h index a7fa7b9ce..6b7151b51 100644 --- a/runtime/shims/shims.h +++ b/runtime/shims/shims.h @@ -69,6 +69,12 @@ struct BundledModuleOps { // (library_loader's W entries use them when a name has a character outside ASCII). Either may be null. void* (*find_loaded_w)(void* ctx, const std::wstring& basename); void* (*load_bundled_w)(void* ctx, const std::wstring& basename, uint32_t flags, bool& handled); + // LEONIDA_COMPAT_DIR at run time. compat_module: `handled` when the folder holds `dll_lower`, which then owns + // the module ahead of any shim; the result is its handle (loaded first when `load`, else null until something + // loaded it), or null with the Windows error set when Windows refused the file. owns_compat_handle: whether + // `module` is one of those handles, whose exports are the DLL's own. Either may be null. + void* (*compat_module)(void* ctx, const std::string& dll_lower, bool load, bool& handled); + bool (*owns_compat_handle)(void* ctx, void* module); }; void add_bundled_loader(void* ctx, const BundledModuleOps* ops); void remove_bundled_loader(void* ctx); @@ -79,6 +85,8 @@ void* find_loaded_bundled_module_w(const std::wstring& basename); void* load_bundled_module_w(const std::wstring& basename, uint32_t flags, bool& handled); void* get_bundled_proc_address(void* module, const std::string& sym, bool& owns_handle); bool owns_bundled_module_handle(void* module); +void* compat_module(const std::string& dll_lower, bool load, bool& handled); +bool owns_compat_module_handle(void* module); // Title-exported __XMemAllocationHooks__ (GDK XMEM_ALLOCATION_HOOKS): the console runtime routes internal // allocations (including D3D12 descriptor heaps) through these callbacks when the mapped image exports the struct. diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index 3558cffb5..d076c5aa0 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -1341,6 +1341,14 @@ void* bundled_load_w(void* ctx, const std::wstring& basename, uint32_t flags, bo return static_cast(ctx)->load_runtime_module_w(basename, flags, handled); } +void* bundled_compat_module(void* ctx, const std::string& dll_lower, bool load, bool& handled) { + return static_cast(ctx)->runtime_compat_module(dll_lower, load, handled); +} + +bool bundled_owns_compat_handle(void* ctx, void* module) { + return static_cast(ctx)->owns_compat_handle(module); +} + const shims::BundledModuleOps kBundledOps{ &bundled_find_loaded, &bundled_load, @@ -1348,6 +1356,8 @@ const shims::BundledModuleOps kBundledOps{ &bundled_owns_handle, &bundled_find_loaded_w, &bundled_load_w, + &bundled_compat_module, + &bundled_owns_compat_handle, }; // Marks what a run-time load maps as a dynamic load for as long as it is in scope (the caller holds the mutex). @@ -2040,37 +2050,76 @@ void* Loader::resolve_forwarder(const std::string& spec, Binding& binding, int d return reinterpret_cast(p); } +void* Loader::compat_handle(const std::string& key, const std::string& dll, bool load, bool& exists, + uint32_t& error) { + exists = false; + error = ERROR_SUCCESS; + if (compat_dir_.empty() || key.empty() || key.find_first_of("/\\:") != std::string::npos) return nullptr; + if (auto it = compat_modules_.find(key); it != compat_modules_.end()) { + exists = true; + return it->second; + } + const std::filesystem::path candidate = compat_dir_ / std::filesystem::path(dll); + std::error_code ec; + if (!std::filesystem::is_regular_file(candidate, ec)) return nullptr; + exists = true; + if (!load) return nullptr; + // The full path, with the compat folder on the DLL's own search path for its dependencies; never the game + // folder. Windows maps it, so its CRT, TLS and SEH work as for any host DLL. + // A file Windows cannot map (truncated, wrong machine, not a PE image) otherwise raises a modal "Bad Image" + // box and LoadLibraryExW does not return until someone clicks it: a headless run would hang on a failure + // that the caller reports anyway. The mode is this thread's, and goes back as it was. + DWORD previous_mode = 0; + const bool mode_set = SetThreadErrorMode(GetThreadErrorMode() | SEM_FAILCRITICALERRORS, &previous_mode) != 0; + HMODULE h = LoadLibraryExW(candidate.c_str(), nullptr, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32); + error = h ? ERROR_SUCCESS : GetLastError(); + if (mode_set) SetThreadErrorMode(previous_mode, nullptr); + if (!h) return nullptr; + compat_modules_.emplace(key, h); + std::fprintf(stderr, "[rt] compat: %s -> %s\n", dll.c_str(), path_utf8(candidate).c_str()); + return h; +} + bool Loader::resolve_compat(const std::string& key, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal, void*& out) { out = nullptr; - if (compat_dir_.empty() || key.empty() || key.find_first_of("/\\:") != std::string::npos) return false; - HMODULE h = nullptr; - if (auto it = compat_modules_.find(key); it != compat_modules_.end()) { - h = static_cast(it->second); - } else { - const std::filesystem::path candidate = compat_dir_ / std::filesystem::path(dll); - std::error_code ec; - if (!std::filesystem::is_regular_file(candidate, ec)) return false; - // The full path, with the compat folder on the DLL's own search path for its dependencies; never the game - // folder. Windows maps it, so its CRT, TLS and SEH work as for any host DLL. - // A file Windows cannot map (truncated, wrong machine, not a PE image) otherwise raises a modal "Bad Image" - // box and LoadLibraryExW does not return until someone clicks it: a headless run would hang on a failure - // that is reported right below anyway. The mode is this thread's, and goes back as it was. - DWORD previous_mode = 0; - const bool mode_set = SetThreadErrorMode(GetThreadErrorMode() | SEM_FAILCRITICALERRORS, &previous_mode) != 0; - h = LoadLibraryExW(candidate.c_str(), nullptr, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32); - const DWORD load_error = h ? ERROR_SUCCESS : GetLastError(); - if (mode_set) SetThreadErrorMode(previous_mode, nullptr); - if (!h) - throw std::runtime_error("LEONIDA_COMPAT_DIR: " + path_utf8(candidate) + " exists but Windows could not " + - "load it (error " + std::to_string(load_error) + ")"); - compat_modules_.emplace(key, h); - std::fprintf(stderr, "[rt] compat: %s -> %s\n", dll.c_str(), path_utf8(candidate).c_str()); - } + bool exists = false; + uint32_t error = ERROR_SUCCESS; + HMODULE h = static_cast(compat_handle(key, dll, true, exists, error)); + if (!exists) return false; + if (!h) + throw std::runtime_error("LEONIDA_COMPAT_DIR: " + path_utf8(compat_dir_ / std::filesystem::path(dll)) + + " exists but Windows could not load it (error " + std::to_string(error) + ")"); out = reinterpret_cast(GetProcAddress(h, by_ordinal ? MAKEINTRESOURCEA(ordinal) : name.c_str())); return true; } +void* Loader::runtime_compat_module(const std::string& dll_lower, bool load, bool& handled) { + std::lock_guard lock(mutex_); + bool exists = false; + uint32_t error = ERROR_SUCCESS; + void* h = compat_handle(dll_lower, dll_lower, load, exists, error); + handled = exists; + if (exists && !h && load) { + // As a LoadLibrary of a file Windows refuses: null and its error, never the shim (the player put the DLL + // there to own the module). + std::fprintf(stderr, "[rt] compat: %s exists but Windows could not load it (error %u, run-time load)\n", + path_utf8(compat_dir_ / std::filesystem::path(dll_lower)).c_str(), error); + SetLastError(error); + } else if (exists && !h) { + SetLastError(ERROR_MOD_NOT_FOUND); // GetModuleHandle of a module nothing has loaded yet + } + return h; +} + +bool Loader::owns_compat_handle(void* module) const { + if (!module) return false; + std::lock_guard lock(mutex_); + for (const auto& [key, h] : compat_modules_) + if (h == module) return true; + return false; +} + void* Loader::resolve(Module& m, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal) { std::string key = lower(dll); std::string sym = by_ordinal ? "#" + std::to_string(ordinal) : name; diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h index f75426e41..9bc1ca607 100644 --- a/runtime/src/pe_loader.h +++ b/runtime/src/pe_loader.h @@ -137,6 +137,11 @@ public: void* load_runtime_module_w(const std::wstring& basename, uint32_t flags, bool& handled); void* resolve_module_export(void* module_handle, const std::string& sym, bool& owns_handle); bool owns_module_handle(void* module_handle) const; + // LEONIDA_COMPAT_DIR for a run-time LoadLibrary / GetModuleHandle (shims::BundledModuleOps::compat_module): the + // same DLL, and the same handle, a static import of `dll_lower` binds to. owns_compat_handle: whether `module` is + // one of them. + void* runtime_compat_module(const std::string& dll_lower, bool load, bool& handled); + bool owns_compat_handle(void* module) const; private: void initialise(Module& m); @@ -153,6 +158,10 @@ private: // owns every import of that DLL; `out` is the export, or null when the DLL lacks it. Caller holds mutex_. bool resolve_compat(const std::string& key, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal, void*& out); + // The compat DLL for `key` (lower-case DLL name), `dll` its file name in compat_dir_: its handle, loaded by + // Windows first when `load`. `exists`: the folder holds it (or it is loaded already). Null with `error` (a Windows + // error code) when Windows refused the file, or when it is not loaded and `load` is false. Caller holds mutex_. + void* compat_handle(const std::string& key, const std::string& dll, bool load, bool& exists, uint32_t& error); void* resolve_forwarder(const std::string& spec, Binding& binding, int depth); void parse_exports(Module& m); void protect_sections(Module& m); diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp index d985ba423..4bc3c8e01 100644 --- a/runtime/test/loader_test.cpp +++ b/runtime/test/loader_test.cpp @@ -1444,6 +1444,92 @@ void test_compat_modules() { while (HMODULE h = GetModuleHandleW(p.c_str())) FreeLibrary(h); } +// LEONIDA_COMPAT_DIR at run time: a mapped image's LoadLibrary / GetModuleHandle / GetProcAddress / FreeLibrary go +// through shims/library_loader.cpp, which must give the compat DLL ahead of the shim, as static imports get it. +void test_compat_runtime_loads() { + using LoadW = HMODULE(WINAPI*)(LPCWSTR); + using ModuleW = HMODULE(WINAPI*)(LPCWSTR); + using ProcA = FARPROC(WINAPI*)(HMODULE, LPCSTR); + using FreeLib = BOOL(WINAPI*)(HMODULE); + const auto load_w = reinterpret_cast(rt::shims::find("kernel32.dll", "LoadLibraryW")); + const auto module_w = reinterpret_cast(rt::shims::find("kernel32.dll", "GetModuleHandleW")); + const auto proc = reinterpret_cast(rt::shims::find("kernel32.dll", "GetProcAddress")); + const auto free_lib = reinterpret_cast(rt::shims::find("kernel32.dll", "FreeLibrary")); + if (!load_w || !module_w || !proc || !free_lib) { + failed("LEONIDA_COMPAT_DIR at run time", "the library_loader shims are not registered"); + return; + } + const std::filesystem::path compat = g_dir / "compat_rt"; + std::filesystem::create_directories(compat); + const auto dll_path = compat / "testshim.dll"; + write_image_as(make_os_dll(0x1C0000000), "compat_rt/testshim.dll"); // has Answer, not the shim's F + write_image_as(std::vector(64, 0x5A), "compat_rt/testbad.dll"); + struct Reset { + ~Reset() { SetEnvironmentVariableW(L"LEONIDA_COMPAT_DIR", nullptr); } + } reset; + try { + { + const char* what = "without LEONIDA_COMPAT_DIR a run-time load of a shim's module gives the shim"; + SetEnvironmentVariableW(L"LEONIDA_COMPAT_DIR", nullptr); + rt::Loader loader(g_dir); + HMODULE h = load_w(L"testshim.dll"); + if (!h) failed(what, "LoadLibraryW returned NULL"); + else if (proc(h, "F") != reinterpret_cast(&test_shim_function)) failed(what, "F is not the shim's"); + else pass(what); + } + SetEnvironmentVariableW(L"LEONIDA_COMPAT_DIR", compat.c_str()); + rt::Loader loader(g_dir); + { + const char* what = "with LEONIDA_COMPAT_DIR GetModuleHandle of a compat module not loaded yet is NULL"; + if (module_w(L"testshim.dll")) failed(what, "it returned a handle (the shim's?)"); + else pass(what); + } + HMODULE h = load_w(L"TestShim.dll"); + { + const char* what = "with LEONIDA_COMPAT_DIR a run-time LoadLibrary gives the drop-in DLL"; + if (!h) failed(what, "LoadLibraryW returned NULL"); + else if (h != GetModuleHandleW(dll_path.c_str())) failed(what, "the handle is not the compat DLL's"); + else pass(what); + } + if (h) { + const char* what = "a run-time compat module answers GetModuleHandle, with or without the extension"; + if (module_w(L"testshim.dll") != h || module_w(L"TESTSHIM") != h) failed(what, "another handle came back"); + else pass(what); + } + if (h) { + const char* what = "GetProcAddress on a run-time compat module gives its own exports, never the shim's"; + const FARPROC answer = proc(h, "Answer"); + if (!answer || reinterpret_cast(answer)() != 42) failed(what, "Answer is missing or wrong"); + else if (proc(h, "F")) failed(what, "F, which the DLL lacks, resolved (to the shim?)"); + else pass(what); + } + if (h) { + const char* what = "a static import of the same module binds to the run-time handle's export"; + rt::Module& m = loader.load(write_image(make_import_image("testshim.dll", "Answer"))); + void* bound = *reinterpret_cast(m.base + 0x1180); + if (bound != reinterpret_cast(GetProcAddress(h, "Answer"))) failed(what, "another export was bound"); + else pass(what); + } + if (h) { + const char* what = "FreeLibrary leaves a compat module loaded (static imports may use it)"; + if (!free_lib(h) || GetModuleHandleW(dll_path.c_str()) != h) failed(what, "the DLL was unloaded"); + else pass(what); + } + { + const char* what = "a compat file Windows cannot load fails that LoadLibrary, without the shim or a throw"; + SetLastError(ERROR_SUCCESS); + HMODULE bad = load_w(L"testbad.dll"); + const DWORD error = GetLastError(); + if (bad) failed(what, "LoadLibraryW returned a handle"); + else if (error == ERROR_SUCCESS) failed(what, "no Windows error was set"); + else pass(what); + } + } catch (const std::exception& e) { + failed("LEONIDA_COMPAT_DIR at run time", e.what()); + } + while (HMODULE h = GetModuleHandleW(dll_path.c_str())) FreeLibrary(h); +} + } // namespace int main() { @@ -1491,6 +1577,7 @@ int main() { test_unwind_registration(); test_lookup_during_loads(); test_compat_modules(); + test_compat_runtime_loads(); } catch (const std::exception& e) { // A write that fails (write_image throws) ends the run with the reason, instead of terminating the process. failed("writing the test images", e.what()); -- cgit v1.2.3 From 2cca47b5c8971c885961c35741ab8b0f0debaa01 Mon Sep 17 00:00:00 2001 From: Mike7581 <168859477+Mike7581@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:05:13 -0300 Subject: loader: compat run-time loads honour LoadLibraryEx flags and Windows-loaded dependencies Review follow-up for #1565: - LoadLibraryEx with DONT_RESOLVE_DLL_REFERENCES on a LEONIDA_COMPAT_DIR module fails with ERROR_NOT_SUPPORTED, before loading or returning a loaded handle, as for bundled DLLs. - A compat DLL that Windows loaded as another compat DLL's dependency is recognised: compat_handle() finds it by its full path, and owns_compat_handle() by its folder (read outside mutex_, since GetModuleFileNameW can take the loader lock), so GetModuleHandle and LoadLibrary return it and GetProcAddress never fills in a missing export from the shim. - A name with a directory gets the compat DLL only when it is that file; any other path goes on as without the folder. - Names outside ASCII reach the compat lookup (it runs before the ASCII / wide split). - The folder's file names are listed once per Loader, so lookups no longer touch the disk. loader_test: test_compat_runtime_edges adds six cases for the first four points, through LoadLibraryExA/W, LoadLibraryW, GetModuleHandleW and GetProcAddress; all six fail on 582e14d. The listing has no functional test. --- runtime/README.md | 7 +- runtime/shims/library_loader.cpp | 68 +++++++++------- runtime/shims/registry.cpp | 5 +- runtime/shims/shims.h | 15 ++-- runtime/src/pe_loader.cpp | 126 ++++++++++++++++++++++-------- runtime/src/pe_loader.h | 23 ++++-- runtime/test/loader_test.cpp | 165 ++++++++++++++++++++++++++++++++++++++- 7 files changed, 330 insertions(+), 79 deletions(-) (limited to 'runtime/src/pe_loader.cpp') diff --git a/runtime/README.md b/runtime/README.md index 6a98d5039..107da39bc 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -114,7 +114,12 @@ folder that Windows refuses to load stops the run with the error code. Unset or loaded for the process lifetime. A run-time `LoadLibrary` of the same name (from a mapped image, through `shims/library_loader.cpp`) gets the same DLL and handle, ahead of the shim; `GetModuleHandle` answers it once loaded, `GetProcAddress` on it gives only its own exports, and `FreeLibrary` leaves it loaded. A file Windows refuses to load -there fails that `LoadLibrary` with Windows' error instead of stopping the run. +there fails that `LoadLibrary` with Windows' error instead of stopping the run. A name with a directory gets the +compat DLL only when it is that file, any name outside ASCII is looked up as well, and `LoadLibraryEx` with +`DONT_RESOLVE_DLL_REFERENCES` fails with `ERROR_NOT_SUPPORTED`, as for bundled DLLs. A DLL Windows loaded from the +folder as another compat DLL's dependency is found by `GetModuleHandle` and `LoadLibrary` of its name, and +`GetProcAddress` on it gives only its own exports. The folder's file names are listed once, when the loader starts: +a file added during the run is not seen. It exists for drop-in implementations of console DLLs that have no shim here, such as the `AcpHal`, `chad`, `xapu` and `XCRDAPI` crates of [omonkeyz/xbox-emulator](https://github.com/omonkeyz/xbox-emulator) (GPL-3.0-or-later). diff --git a/runtime/shims/library_loader.cpp b/runtime/shims/library_loader.cpp index 9e7270723..54e112d66 100644 --- a/runtime/shims/library_loader.cpp +++ b/runtime/shims/library_loader.cpp @@ -15,7 +15,9 @@ // // A module whose DLL is in LEONIDA_COMPAT_DIR comes first, as for static imports: LoadLibrary returns that DLL (the // handle the Loader's static imports use), GetModuleHandle returns it once loaded and NULL before, GetProcAddress on -// it gives only its own exports, and FreeLibrary leaves it loaded. +// it gives only its own exports, and FreeLibrary leaves it loaded. That holds for any name, ASCII or not, and for a +// name with a directory only when it is the compat file itself; a DLL that Windows loaded from the folder as another +// one's dependency counts too. #include #include @@ -63,6 +65,16 @@ std::string narrow(const wchar_t* w) { return s; } +// An ANSI name widened through the code page, as LoadLibraryA does (empty for an empty name). +std::wstring widen(const char* s) { + const int n = s && *s ? MultiByteToWideChar(CP_ACP, 0, s, -1, nullptr, 0) : 0; + if (n <= 1) return {}; + std::wstring w(static_cast(n), L'\0'); + MultiByteToWideChar(CP_ACP, 0, s, -1, w.data(), n); + w.pop_back(); // the terminator + return w; +} + bool is_ascii(const wchar_t* w) { for (; w && *w; ++w) if (*w >= 0x80) return false; @@ -143,18 +155,19 @@ namespace { constexpr DWORD kDataFileLoadFlags = LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE; +// LEONIDA_COMPAT_DIR first, as for static imports (rt::Loader::resolve): a drop-in DLL owns its module, so a run-time +// load gets the same Windows-loaded DLL, never the shim, and GetModuleHandle (`load` false) its handle once loaded. +// Its handle is a real module handle. By the wide name, before the ASCII / wide split below, so a basename outside +// ASCII reaches the folder too. `handled` when the folder claims the name. +HMODULE compat_first(const std::wstring& name, bool load, DWORD flags, bool& handled) { + handled = false; + const std::wstring dll = module_name_w(name); + if (name.empty() || dll.empty()) return nullptr; + return reinterpret_cast(compat_module(dll, name, load, static_cast(flags), handled)); +} + HMODULE load_shim_or_bundled(const std::string& path, DWORD flags, bool& handled) { handled = false; - // LEONIDA_COMPAT_DIR first, as for static imports (rt::Loader::resolve): a drop-in DLL owns its module, so a - // run-time load gets the same Windows-loaded DLL, never the shim. Its handle is a real module handle. - if (const std::string dll = module_name(path); !dll.empty()) { - bool compat = false; - void* h = compat_module(dll, true, compat); - if (compat) { - handled = true; - return reinterpret_cast(h); - } - } if (HMODULE h = owned_handle(path)) { handled = true; return h; @@ -170,7 +183,8 @@ HMODULE load_shim_or_bundled(const std::string& path, DWORD flags, bool& handled HMODULE WINAPI load_library_a(LPCSTR name) { if (name) { bool handled = false; - HMODULE h = load_shim_or_bundled(name, 0, handled); + HMODULE h = compat_first(widen(name), true, 0, handled); + if (!handled) h = load_shim_or_bundled(name, 0, handled); if (handled) return h; } return LoadLibraryA(name); @@ -189,7 +203,9 @@ HMODULE load_bundled_w(LPCWSTR name, DWORD flags, bool& handled) { HMODULE WINAPI load_library_w(LPCWSTR name) { if (name) { bool handled = false; - HMODULE h = ascii_basename(name) ? load_shim_or_bundled(narrow(name), 0, handled) : load_bundled_w(name, 0, handled); + HMODULE h = compat_first(name, true, 0, handled); + if (!handled) + h = ascii_basename(name) ? load_shim_or_bundled(narrow(name), 0, handled) : load_bundled_w(name, 0, handled); if (handled) return h; } return LoadLibraryW(name); @@ -198,7 +214,8 @@ HMODULE WINAPI load_library_w(LPCWSTR name) { HMODULE WINAPI load_library_ex_a(LPCSTR name, HANDLE file, DWORD flags) { if (name && (flags & kDataFileLoadFlags) == 0) { bool handled = false; - HMODULE h = load_shim_or_bundled(name, flags, handled); + HMODULE h = compat_first(widen(name), true, flags, handled); + if (!handled) h = load_shim_or_bundled(name, flags, handled); if (handled) return h; } return LoadLibraryExA(name, file, flags); @@ -207,27 +224,22 @@ HMODULE WINAPI load_library_ex_a(LPCSTR name, HANDLE file, DWORD flags) { HMODULE WINAPI load_library_ex_w(LPCWSTR name, HANDLE file, DWORD flags) { if (name && (flags & kDataFileLoadFlags) == 0) { bool handled = false; - HMODULE h = ascii_basename(name) ? load_shim_or_bundled(narrow(name), flags, handled) - : load_bundled_w(name, flags, handled); + HMODULE h = compat_first(name, true, flags, handled); + if (!handled) + h = ascii_basename(name) ? load_shim_or_bundled(narrow(name), flags, handled) + : load_bundled_w(name, flags, handled); if (handled) return h; } return LoadLibraryExW(name, file, flags); } -// A LEONIDA_COMPAT_DIR module answers GetModuleHandle as Windows would for it: its handle once loaded, else NULL. It is -// never the shim's pseudo-handle (`handled` is set when the folder holds the DLL). -HMODULE compat_loaded(const std::string& path, bool& handled) { - handled = false; - const std::string dll = module_name(path); - return dll.empty() ? nullptr : reinterpret_cast(compat_module(dll, false, handled)); -} - -// GetModuleHandle answers for an owned module as if it were loaded (the GDK may probe before it loads), and for any +// GetModuleHandle answers for a LEONIDA_COMPAT_DIR module as Windows would (its handle once loaded, else NULL, never +// the shim's pseudo-handle), for an owned module as if it were loaded (the GDK may probe before it loads), and for any // bundled package module already mapped by the native loader. HMODULE WINAPI get_module_handle_a(LPCSTR name) { if (name) { bool compat = false; - if (HMODULE h = compat_loaded(name, compat); compat) return h; + if (HMODULE h = compat_first(widen(name), false, 0, compat); compat) return h; if (HMODULE h = owned_handle(name)) return h; const std::string dll = module_name(name); if (!dll.empty()) @@ -238,10 +250,10 @@ HMODULE WINAPI get_module_handle_a(LPCSTR name) { HMODULE WINAPI get_module_handle_w(LPCWSTR name) { if (name) { + bool compat = false; + if (HMODULE h = compat_first(name, false, 0, compat); compat) return h; if (ascii_basename(name)) { const std::string path = narrow(name); - bool compat = false; - if (HMODULE h = compat_loaded(path, compat); compat) return h; if (HMODULE h = owned_handle(path)) return h; const std::string dll = module_name(path); if (!dll.empty()) diff --git a/runtime/shims/registry.cpp b/runtime/shims/registry.cpp index a8dec0e4c..9ef03b476 100644 --- a/runtime/shims/registry.cpp +++ b/runtime/shims/registry.cpp @@ -508,12 +508,13 @@ void* get_bundled_proc_address(void* module, const std::string& sym, bool& owns_ return nullptr; } -void* compat_module(const std::string& dll_lower, bool load, bool& handled) { +void* compat_module(const std::wstring& basename, const std::wstring& name, bool load, uint32_t flags, + bool& handled) { handled = false; for (const auto& entry : snapshot_bundled_loaders()) { if (!entry.ops->compat_module) continue; bool loader_handled = false; - void* h = entry.ops->compat_module(entry.ctx, dll_lower, load, loader_handled); + void* h = entry.ops->compat_module(entry.ctx, basename, name, load, flags, loader_handled); if (loader_handled) { handled = true; return h; diff --git a/runtime/shims/shims.h b/runtime/shims/shims.h index 6b7151b51..e72427945 100644 --- a/runtime/shims/shims.h +++ b/runtime/shims/shims.h @@ -69,11 +69,13 @@ struct BundledModuleOps { // (library_loader's W entries use them when a name has a character outside ASCII). Either may be null. void* (*find_loaded_w)(void* ctx, const std::wstring& basename); void* (*load_bundled_w)(void* ctx, const std::wstring& basename, uint32_t flags, bool& handled); - // LEONIDA_COMPAT_DIR at run time. compat_module: `handled` when the folder holds `dll_lower`, which then owns - // the module ahead of any shim; the result is its handle (loaded first when `load`, else null until something - // loaded it), or null with the Windows error set when Windows refused the file. owns_compat_handle: whether - // `module` is one of those handles, whose exports are the DLL's own. Either may be null. - void* (*compat_module)(void* ctx, const std::string& dll_lower, bool load, bool& handled); + // LEONIDA_COMPAT_DIR at run time. compat_module: `handled` when the folder holds `basename` (`name` is what the + // caller gave: a name with a directory counts only when it is that file), which then owns the module ahead of + // any shim; the result is its handle (loaded first when `load`, with the LoadLibraryEx `flags`, else null until + // something loaded it), or null with the Windows error set when it cannot be loaded. owns_compat_handle: whether + // `module` is a DLL from that folder, whose exports are its own. Either may be null. + void* (*compat_module)(void* ctx, const std::wstring& basename, const std::wstring& name, bool load, + uint32_t flags, bool& handled); bool (*owns_compat_handle)(void* ctx, void* module); }; void add_bundled_loader(void* ctx, const BundledModuleOps* ops); @@ -85,7 +87,8 @@ void* find_loaded_bundled_module_w(const std::wstring& basename); void* load_bundled_module_w(const std::wstring& basename, uint32_t flags, bool& handled); void* get_bundled_proc_address(void* module, const std::string& sym, bool& owns_handle); bool owns_bundled_module_handle(void* module); -void* compat_module(const std::string& dll_lower, bool load, bool& handled); +void* compat_module(const std::wstring& basename, const std::wstring& name, bool load, uint32_t flags, + bool& handled); bool owns_compat_module_handle(void* module); // Title-exported __XMemAllocationHooks__ (GDK XMEM_ALLOCATION_HOOKS): the console runtime routes internal diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index d076c5aa0..c5e97e649 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -1341,8 +1341,9 @@ void* bundled_load_w(void* ctx, const std::wstring& basename, uint32_t flags, bo return static_cast(ctx)->load_runtime_module_w(basename, flags, handled); } -void* bundled_compat_module(void* ctx, const std::string& dll_lower, bool load, bool& handled) { - return static_cast(ctx)->runtime_compat_module(dll_lower, load, handled); +void* bundled_compat_module(void* ctx, const std::wstring& basename, const std::wstring& name, bool load, + uint32_t flags, bool& handled) { + return static_cast(ctx)->runtime_compat_module(basename, name, load, flags, handled); } bool bundled_owns_compat_handle(void* ctx, void* module) { @@ -1373,7 +1374,18 @@ struct RuntimeLoadScope { Loader::Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) { std::vector compat(32768); const DWORD n = GetEnvironmentVariableW(L"LEONIDA_COMPAT_DIR", compat.data(), static_cast(compat.size())); - if (n > 0 && n < compat.size()) compat_dir_ = std::filesystem::path(compat.data()); + if (n > 0 && n < compat.size()) { + // Absolute, with backslashes and no trailing separator: LoadLibraryExW with LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR + // needs a full path, and owns_compat_handle() compares it with a module's own folder. + std::error_code ec; + compat_dir_ = std::filesystem::absolute(std::filesystem::path(compat.data()), ec).lexically_normal(); + compat_dir_.make_preferred(); + if (!compat_dir_.has_filename()) compat_dir_ = compat_dir_.parent_path(); + for (std::filesystem::directory_iterator it(compat_dir_, ec), end; !ec && it != end; it.increment(ec)) { + std::error_code file_ec; + if (it->is_regular_file(file_ec)) compat_files_.push_back(it->path().filename()); + } + } shims::add_module_lookup(this, &lookup_in_loader); shims::add_bundled_loader(this, &kBundledOps); } @@ -2050,19 +2062,27 @@ void* Loader::resolve_forwarder(const std::string& spec, Binding& binding, int d return reinterpret_cast(p); } -void* Loader::compat_handle(const std::string& key, const std::string& dll, bool load, bool& exists, - uint32_t& error) { - exists = false; +const std::filesystem::path* Loader::compat_file(const std::wstring& basename) const { + if (basename.empty()) return nullptr; + for (const auto& file : compat_files_) + if (same_module_name(file.c_str(), basename.c_str())) return &file; + return nullptr; +} + +void* Loader::compat_handle(const std::filesystem::path& file, bool load, uint32_t& error) { error = ERROR_SUCCESS; - if (compat_dir_.empty() || key.empty() || key.find_first_of("/\\:") != std::string::npos) return nullptr; - if (auto it = compat_modules_.find(key); it != compat_modules_.end()) { - exists = true; - return it->second; + const std::string key = lower(path_utf8(file)); + if (auto it = compat_modules_.find(key); it != compat_modules_.end()) return it->second; + const std::filesystem::path candidate = compat_dir_ / file; + // Already live without a lookup through here: Windows loaded it from the folder as another compat DLL's + // dependency (LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR), or something loaded it by its path. That is the module a + // static import or a run-time load must share. The reference taken here is kept, as for the DLLs loaded below. + if (HMODULE live = nullptr; GetModuleHandleExW(0, candidate.c_str(), &live) && live) { + compat_modules_.emplace(key, live); + std::fprintf(stderr, "[rt] compat: %s -> %s (already loaded)\n", path_utf8(file).c_str(), + path_utf8(candidate).c_str()); + return live; } - const std::filesystem::path candidate = compat_dir_ / std::filesystem::path(dll); - std::error_code ec; - if (!std::filesystem::is_regular_file(candidate, ec)) return nullptr; - exists = true; if (!load) return nullptr; // The full path, with the compat folder on the DLL's own search path for its dependencies; never the game // folder. Windows maps it, so its CRT, TLS and SEH work as for any host DLL. @@ -2076,48 +2096,92 @@ void* Loader::compat_handle(const std::string& key, const std::string& dll, bool if (mode_set) SetThreadErrorMode(previous_mode, nullptr); if (!h) return nullptr; compat_modules_.emplace(key, h); - std::fprintf(stderr, "[rt] compat: %s -> %s\n", dll.c_str(), path_utf8(candidate).c_str()); + std::fprintf(stderr, "[rt] compat: %s -> %s\n", path_utf8(file).c_str(), path_utf8(candidate).c_str()); return h; } bool Loader::resolve_compat(const std::string& key, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal, void*& out) { out = nullptr; - bool exists = false; + if (compat_dir_.empty() || key.empty() || key.find_first_of("/\\:") != std::string::npos) return false; + const std::filesystem::path* file = compat_file(acp_to_wide(dll)); + if (!file) return false; uint32_t error = ERROR_SUCCESS; - HMODULE h = static_cast(compat_handle(key, dll, true, exists, error)); - if (!exists) return false; + HMODULE h = static_cast(compat_handle(*file, true, error)); if (!h) - throw std::runtime_error("LEONIDA_COMPAT_DIR: " + path_utf8(compat_dir_ / std::filesystem::path(dll)) + + throw std::runtime_error("LEONIDA_COMPAT_DIR: " + path_utf8(compat_dir_ / *file) + " exists but Windows could not load it (error " + std::to_string(error) + ")"); out = reinterpret_cast(GetProcAddress(h, by_ordinal ? MAKEINTRESOURCEA(ordinal) : name.c_str())); return true; } -void* Loader::runtime_compat_module(const std::string& dll_lower, bool load, bool& handled) { +void* Loader::runtime_compat_module(const std::wstring& basename, const std::wstring& name, bool load, + uint32_t flags, bool& handled) { + handled = false; + if (compat_dir_.empty()) return nullptr; std::lock_guard lock(mutex_); - bool exists = false; + const std::filesystem::path* file = compat_file(basename); + if (!file) return nullptr; + const std::filesystem::path compat_path = compat_dir_ / *file; + // A name with a directory names one file, which Windows would load even when another of the same name is in use: + // the compat DLL answers it only when it is that file (".dll" added as LoadLibrary adds it). Any other path goes + // on as without the folder. + if (name.find_first_of(L"\\/:") != std::wstring::npos) { + std::filesystem::path given(name); + given.replace_filename(basename); + std::error_code ec; + if (!std::filesystem::equivalent(given, compat_path, ec)) return nullptr; + } + handled = true; + // DONT_RESOLVE_DLL_REFERENCES maps a DLL without its dependencies, TLS or DllMain. The compat DLL is shared with + // static imports, initialised, so refuse it before loading or returning a handle, as for bundled DLLs + // (load_runtime_candidate). + if (load && (flags & DONT_RESOLVE_DLL_REFERENCES) != 0) { + std::fprintf(stderr, "[rt] compat: LoadLibraryEx(%s, DONT_RESOLVE_DLL_REFERENCES) is not supported\n", + path_utf8(compat_path).c_str()); + SetLastError(ERROR_NOT_SUPPORTED); + return nullptr; + } uint32_t error = ERROR_SUCCESS; - void* h = compat_handle(dll_lower, dll_lower, load, exists, error); - handled = exists; - if (exists && !h && load) { + void* h = compat_handle(*file, load, error); + if (!h && load) { // As a LoadLibrary of a file Windows refuses: null and its error, never the shim (the player put the DLL // there to own the module). std::fprintf(stderr, "[rt] compat: %s exists but Windows could not load it (error %u, run-time load)\n", - path_utf8(compat_dir_ / std::filesystem::path(dll_lower)).c_str(), error); + path_utf8(compat_path).c_str(), error); SetLastError(error); - } else if (exists && !h) { + } else if (!h) { SetLastError(ERROR_MOD_NOT_FOUND); // GetModuleHandle of a module nothing has loaded yet } return h; } -bool Loader::owns_compat_handle(void* module) const { - if (!module) return false; +bool Loader::owns_compat_handle(void* module) { + if (!module || compat_dir_.empty()) return false; + { + std::lock_guard lock(mutex_); + for (const auto& [key, h] : compat_modules_) + if (h == module) return true; + } + // A DLL from the folder that no lookup has seen yet (Windows loaded it as another compat DLL's dependency): its + // exports are its own too. Recorded, with a kept reference, through compat_handle(). GetModuleFileNameW can take + // the Windows loader lock, so the path is read without mutex_ held; compat_dir_ and compat_files_ do not change + // after construction. + std::vector path(MAX_PATH); + DWORD length = 0; + for (;;) { + length = GetModuleFileNameW(static_cast(module), path.data(), static_cast(path.size())); + if (!length || length < path.size() || path.size() >= 32768) break; + path.resize(path.size() * 2); + } + if (!length || length >= path.size()) return false; + const std::filesystem::path file(std::wstring(path.data(), length)); + if (!same_module_name(file.parent_path().c_str(), compat_dir_.c_str())) return false; + const std::filesystem::path* entry = compat_file(file.filename().native()); + if (!entry) return false; std::lock_guard lock(mutex_); - for (const auto& [key, h] : compat_modules_) - if (h == module) return true; - return false; + uint32_t error = ERROR_SUCCESS; + return compat_handle(*entry, false, error) == module; } void* Loader::resolve(Module& m, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal) { diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h index 9bc1ca607..31be1a9d3 100644 --- a/runtime/src/pe_loader.h +++ b/runtime/src/pe_loader.h @@ -138,10 +138,13 @@ public: void* resolve_module_export(void* module_handle, const std::string& sym, bool& owns_handle); bool owns_module_handle(void* module_handle) const; // LEONIDA_COMPAT_DIR for a run-time LoadLibrary / GetModuleHandle (shims::BundledModuleOps::compat_module): the - // same DLL, and the same handle, a static import of `dll_lower` binds to. owns_compat_handle: whether `module` is - // one of them. - void* runtime_compat_module(const std::string& dll_lower, bool load, bool& handled); - bool owns_compat_handle(void* module) const; + // same DLL, and the same handle, a static import of `basename` binds to. `name` is the caller's: one with a + // directory is handled only when it names the compat file. DONT_RESOLVE_DLL_REFERENCES in `flags` is refused, as + // for bundled DLLs. owns_compat_handle: whether `module` is a DLL from the folder, including one Windows loaded + // there as another's dependency (it is then kept, as the others are). + void* runtime_compat_module(const std::wstring& basename, const std::wstring& name, bool load, uint32_t flags, + bool& handled); + bool owns_compat_handle(void* module); private: void initialise(Module& m); @@ -158,10 +161,12 @@ private: // owns every import of that DLL; `out` is the export, or null when the DLL lacks it. Caller holds mutex_. bool resolve_compat(const std::string& key, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal, void*& out); - // The compat DLL for `key` (lower-case DLL name), `dll` its file name in compat_dir_: its handle, loaded by - // Windows first when `load`. `exists`: the folder holds it (or it is loaded already). Null with `error` (a Windows + // The file in compat_dir_ named `basename` (case-insensitively, as Windows matches module names), or null. + const std::filesystem::path* compat_file(const std::wstring& basename) const; + // The handle of `file` (a compat_file() entry): the one already in use (looked up before, or loaded by Windows on + // its own, as another compat DLL's dependency), else loaded by Windows when `load`. Null with `error` (a Windows // error code) when Windows refused the file, or when it is not loaded and `load` is false. Caller holds mutex_. - void* compat_handle(const std::string& key, const std::string& dll, bool load, bool& exists, uint32_t& error); + void* compat_handle(const std::filesystem::path& file, bool load, uint32_t& error); void* resolve_forwarder(const std::string& spec, Binding& binding, int depth); void parse_exports(Module& m); void protect_sections(Module& m); @@ -171,8 +176,10 @@ private: std::filesystem::path game_dir_; // LEONIDA_COMPAT_DIR, read when the Loader is made; empty = no compat step. Drop-in DLLs named like console // modules (runtime/README.md, "Compat modules"), loaded by Windows from there and kept for the process lifetime. + // The folder's file names are listed once, then, so a lookup by name never touches the disk. std::filesystem::path compat_dir_; - std::map compat_modules_; // lower-case DLL name -> HMODULE + std::vector compat_files_; // file names in compat_dir_ + std::map compat_modules_; // file name (UTF-8, ASCII lower case) -> HMODULE std::map by_name_; // native basename, ASCII case folded std::vector order_; // mapping order; owns the modules std::vector init_order_; // dependencies first, see initialisation_order() diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp index 4bc3c8e01..b1c694fbe 100644 --- a/runtime/test/loader_test.cpp +++ b/runtime/test/loader_test.cpp @@ -1309,8 +1309,8 @@ std::string written_images_blocked() { } // A DLL Windows' own loader accepts (LEONIDA_COMPAT_DIR loads with LoadLibraryExW, not with rt::Loader): no entry -// point, no imports, one export "Answer" (ordinal 1) whose code returns 42. -std::vector make_os_dll(uint64_t image_base) { +// point, no imports, one export "Answer" (ordinal 1) whose code returns `answer` (42 unless a case tells two apart). +std::vector make_os_dll(uint64_t image_base, uint8_t answer = 42) { auto img = make_image(); std::fill(img.begin() + 0x200, img.begin() + 0x400, uint8_t{0}); auto* nt = nt_of(img); @@ -1339,7 +1339,7 @@ std::vector make_os_dll(uint64_t image_base) { *reinterpret_cast(img.data() + 0x320) = 0x1160; *reinterpret_cast(img.data() + 0x340) = 0; std::memcpy(img.data() + 0x360, "Answer\0", 7); - const uint8_t code[] = {0xB8, 0x2A, 0x00, 0x00, 0x00, 0xC3}; // mov eax, 42; ret + const uint8_t code[] = {0xB8, answer, 0x00, 0x00, 0x00, 0xC3}; // mov eax, answer; ret std::memcpy(img.data() + 0x380, code, sizeof(code)); auto& dir = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; dir.VirtualAddress = 0x1000; @@ -1347,6 +1347,32 @@ std::vector make_os_dll(uint64_t image_base) { return img; } +// make_os_dll with one import, `dll`!`symbol` by name, which Windows resolves when it loads the DLL. The section +// grows to 0x400 bytes for the import tables at RVA 0x1200, and is writable: Windows fills the address table in place. +std::vector make_os_importer_dll(uint64_t image_base, const char* dll, const char* symbol) { + auto img = make_os_dll(image_base); + img.resize(0x600, 0); + auto* nt = nt_of(img); + auto* sec = IMAGE_FIRST_SECTION(nt); + sec->Misc.VirtualSize = 0x400; + sec->SizeOfRawData = 0x400; + sec->Characteristics |= IMAGE_SCN_MEM_WRITE; + nt->OptionalHeader.SizeOfCode = 0x400; + auto* d = reinterpret_cast(img.data() + 0x400); // then the zero descriptor + d->OriginalFirstThunk = 0x1240; + d->FirstThunk = 0x1260; + d->Name = 0x1280; + *reinterpret_cast(img.data() + 0x440) = 0x12A0; // lookup table -> hint/name + *reinterpret_cast(img.data() + 0x460) = 0x12A0; // address table, before binding + std::memcpy(img.data() + 0x480, dll, std::strlen(dll) + 1); + *reinterpret_cast(img.data() + 0x4A0) = 0; + std::memcpy(img.data() + 0x4A2, symbol, std::strlen(symbol) + 1); + auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; + dir.VirtualAddress = 0x1200; + dir.Size = 2 * sizeof(IMAGE_IMPORT_DESCRIPTOR); + return img; +} + // An importer of `dll`!`symbol` bound under LEONIDA_COMPAT_DIR = `compat` (empty = unset). Returns its one record and // writes the IAT slot to `bound`. rt::ImportRecord bind_with_compat(const std::filesystem::path& compat, const char* dll, const char* symbol, @@ -1530,6 +1556,138 @@ void test_compat_runtime_loads() { while (HMODULE h = GetModuleHandleW(dll_path.c_str())) FreeLibrary(h); } +// Run-time LEONIDA_COMPAT_DIR cases where Windows itself decides: LoadLibraryEx flags, a path naming another file of a +// compat module's name, a name outside ASCII, and a compat DLL that Windows loaded as another compat DLL's dependency. +void test_compat_runtime_edges() { + using LoadW = HMODULE(WINAPI*)(LPCWSTR); + using LoadExA = HMODULE(WINAPI*)(LPCSTR, HANDLE, DWORD); + using LoadExW = HMODULE(WINAPI*)(LPCWSTR, HANDLE, DWORD); + using ModuleW = HMODULE(WINAPI*)(LPCWSTR); + using ProcA = FARPROC(WINAPI*)(HMODULE, LPCSTR); + const auto load_w = reinterpret_cast(rt::shims::find("kernel32.dll", "LoadLibraryW")); + const auto load_ex_a = reinterpret_cast(rt::shims::find("kernel32.dll", "LoadLibraryExA")); + const auto load_ex_w = reinterpret_cast(rt::shims::find("kernel32.dll", "LoadLibraryExW")); + const auto module_w = reinterpret_cast(rt::shims::find("kernel32.dll", "GetModuleHandleW")); + const auto proc = reinterpret_cast(rt::shims::find("kernel32.dll", "GetProcAddress")); + if (!load_w || !load_ex_a || !load_ex_w || !module_w || !proc) { + failed("LEONIDA_COMPAT_DIR at run time (edges)", "the library_loader shims are not registered"); + return; + } + const std::filesystem::path compat = g_dir / "compat_edges"; + const std::filesystem::path other = g_dir / "compat_edges_other"; + const std::filesystem::path dep = g_dir / "compat_dep"; + for (const auto& d : {compat, other, dep}) std::filesystem::create_directories(d); + write_image_as(make_os_dll(0x1D0000000, 42), "compat_edges/testpath.dll"); + write_image_as(make_os_dll(0x1E0000000, 43), "compat_edges_other/testpath.dll"); + const auto wide_dll = compat / L"tëstcompat.dll"; // write_image_as takes a narrow name + { + const auto img = make_os_dll(0x1F0000000, 44); + std::ofstream out(wide_dll, std::ios::binary); + out.write(reinterpret_cast(img.data()), static_cast(img.size())); + } + write_image_as(make_os_dll(0x200000000), "compat_dep/testshim.dll"); // has Answer, not the shim's F + write_image_as(make_os_importer_dll(0x210000000, "testshim.dll", "Answer"), "compat_dep/depimporter.dll"); + const auto path_dll = compat / "testpath.dll"; + const auto other_dll = other / "testpath.dll"; + const auto dep_shim = dep / "testshim.dll"; + const auto dep_importer = dep / "depimporter.dll"; + const auto answer = [](HMODULE h) { + const FARPROC f = h ? GetProcAddress(h, "Answer") : nullptr; + return f ? reinterpret_cast(f)() : -1; + }; + struct Reset { + ~Reset() { SetEnvironmentVariableW(L"LEONIDA_COMPAT_DIR", nullptr); } + } reset; + try { + SetEnvironmentVariableW(L"LEONIDA_COMPAT_DIR", compat.c_str()); + { + rt::Loader loader(g_dir); + { + const char* what = "LoadLibraryExA/W of a compat module with DONT_RESOLVE_DLL_REFERENCES is refused"; + SetLastError(ERROR_SUCCESS); + const HMODULE a = load_ex_a("testpath.dll", nullptr, DONT_RESOLVE_DLL_REFERENCES); + const DWORD error_a = GetLastError(); + SetLastError(ERROR_SUCCESS); + const HMODULE w = load_ex_w(L"testpath.dll", nullptr, DONT_RESOLVE_DLL_REFERENCES); + const DWORD error_w = GetLastError(); + if (a || w) failed(what, "a handle came back"); + else if (error_a != ERROR_NOT_SUPPORTED || error_w != ERROR_NOT_SUPPORTED) + failed(what, "errors " + std::to_string(error_a) + " and " + std::to_string(error_w)); + else if (GetModuleHandleW(path_dll.c_str())) failed(what, "the DLL was loaded anyway"); + else pass(what); + } + const HMODULE h = load_w(L"testpath"); + { + const char* what = "DONT_RESOLVE_DLL_REFERENCES is refused for a compat module already loaded too"; + SetLastError(ERROR_SUCCESS); + const HMODULE again = load_ex_w(L"testpath.dll", nullptr, DONT_RESOLVE_DLL_REFERENCES); + if (!h) failed(what, "the plain LoadLibraryW failed"); + else if (again || GetLastError() != ERROR_NOT_SUPPORTED) failed(what, "the loaded handle came back"); + else pass(what); + } + { + const char* what = "a full path to another file of a compat module's name loads that file"; + const HMODULE o = load_w(other_dll.c_str()); + if (!o) failed(what, "LoadLibraryW returned NULL"); + else if (o == h || answer(o) != 43) failed(what, "the compat DLL came back instead"); + else pass(what); + if (o && o != h) FreeLibrary(o); + } + { + const char* what = "a full path to the compat file itself gives the compat module"; + if (!h || load_w(path_dll.c_str()) != h || module_w(path_dll.c_str()) != h) + failed(what, "another handle came back"); + else pass(what); + } + { + const char* what = "a compat module whose name is outside ASCII answers LoadLibraryW and GetModuleHandleW"; + const HMODULE u = load_w(L"TËSTCOMPAT"); + if (!u) failed(what, "LoadLibraryW returned NULL"); + else if (u != GetModuleHandleW(wide_dll.c_str()) || answer(u) != 44) + failed(what, "the handle is not the compat DLL's"); + else if (module_w(L"tëstcompat.dll") != u) failed(what, "GetModuleHandleW did not find it"); + else pass(what); + } + } + // Windows loads the pair itself; each case below then asks a fresh Loader, which has looked nothing up yet, so + // the two ways of recognising the dependency (by its handle's folder, by its name) are checked apart. + HMODULE importer = nullptr, live = nullptr; + if (GetModuleHandleW(L"testshim.dll")) { + failed("a compat DLL Windows loaded as another's dependency", "a testshim.dll from an earlier case is loaded"); + } else { + importer = LoadLibraryExW(dep_importer.c_str(), nullptr, + LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32); + const DWORD error = GetLastError(); + live = GetModuleHandleW(dep_shim.c_str()); + if (!importer || !live) + failed("a compat DLL Windows loaded as another's dependency", + "Windows did not load the pair (error " + std::to_string(error) + ")"); + } + if (live) { + SetEnvironmentVariableW(L"LEONIDA_COMPAT_DIR", dep.c_str()); + { + const char* what = "GetProcAddress on a compat DLL Windows loaded as a dependency gives only its exports"; + rt::Loader loader(g_dir); + if (proc(live, "F")) failed(what, "F, which the DLL lacks, was filled in from the shim"); + else pass(what); + } + { + const char* what = "GetModuleHandle / LoadLibrary of a compat DLL Windows loaded as a dependency give it"; + rt::Loader loader(g_dir); + if (module_w(L"testshim.dll") != live) failed(what, "GetModuleHandle did not return the live DLL"); + else if (load_w(L"testshim.dll") != live) failed(what, "LoadLibrary did not return the live DLL"); + else pass(what); + } + } + if (importer) FreeLibrary(importer); + } catch (const std::exception& e) { + failed("LEONIDA_COMPAT_DIR at run time (edges)", e.what()); + } + // Loaders keep compat DLLs for the process lifetime; drop the references so the work folder can be removed. + for (const auto& p : {path_dll, other_dll, wide_dll, dep_importer, dep_shim}) + while (HMODULE m = GetModuleHandleW(p.c_str())) FreeLibrary(m); +} + } // namespace int main() { @@ -1578,6 +1736,7 @@ int main() { test_lookup_during_loads(); test_compat_modules(); test_compat_runtime_loads(); + test_compat_runtime_edges(); } catch (const std::exception& e) { // A write that fails (write_image throws) ends the run with the reason, instead of terminating the process. failed("writing the test images", e.what()); -- cgit v1.2.3 From 660e6f80641a6e1e3cd9968bac293b354108fc17 Mon Sep 17 00:00:00 2001 From: NotRexed Date: Thu, 26 Nov 2026 02:16:17 -0500 Subject: loader: GetModuleHandle(NULL) and GetModuleFileName name the title's image Port VIctory's kernel.rs (GPL-3.0-or-later) overrides: in mapped code GetModuleHandleA/W(NULL) answered with gta6rt.exe's base and GetModuleFileNameA/W(NULL) with gta6rt.exe's path, and GetModuleFileName of a manually mapped image failed with ERROR_MOD_NOT_FOUND. main.cpp now sets the main image after load(); the library_loader shims answer NULL with it, and GetModuleFileName of any mapped image with the file it was mapped from (a new BundledModuleOps::module_path, Loader::module_path), truncating as Windows does. Host modules keep the host's answers. module_identity_test covers it with a stand-in loader, no game files. Co-Authored-By: Claude Opus 5.5 --- runtime/CMakeLists.txt | 12 +++++ runtime/shims/library_loader.cpp | 54 +++++++++++++++++++- runtime/shims/registry.cpp | 13 +++++ runtime/shims/shims.h | 9 ++++ runtime/src/main.cpp | 2 + runtime/src/pe_loader.cpp | 18 +++++++ runtime/src/pe_loader.h | 2 + runtime/test/module_identity_test.cpp | 93 +++++++++++++++++++++++++++++++++++ 8 files changed, 201 insertions(+), 2 deletions(-) create mode 100644 runtime/test/module_identity_test.cpp (limited to 'runtime/src/pe_loader.cpp') diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 7a42642b5..9d006a0c1 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -418,6 +418,17 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) target_link_options(xgameruntime_test PRIVATE /OPT:NOREF) target_link_libraries(xgameruntime_test PRIVATE gta6rt_xtaskqueue) + # GetModuleHandle(NULL) / GetModuleFileName in mapped code name the title's image (library_loader.cpp). No game files. + add_executable(module_identity_test + test/module_identity_test.cpp + shims/library_loader.cpp + shims/registry.cpp + ) + target_include_directories(module_identity_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) + target_compile_definitions(module_identity_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(module_identity_test PRIVATE /W4 /permissive- /utf-8) + target_link_options(module_identity_test PRIVATE /OPT:NOREF) + # XUserImpl (offline local user) through QueryApiImpl, slot by slot as xgameruntime.lib's thunks call it. add_executable(xgameruntime_user_test test/xgameruntime_user_test.cpp @@ -1311,6 +1322,7 @@ if(BUILD_TESTING) endif() if(WIN32 AND TARGET xgameruntime_test) add_test(NAME xgameruntime COMMAND xgameruntime_test) + add_test(NAME module_identity COMMAND module_identity_test) add_test(NAME xgameruntime_user COMMAND xgameruntime_user_test) add_test(NAME xgameruntime_gamesave COMMAND xgameruntime_gamesave_test) add_test(NAME xgameruntime_store COMMAND xgameruntime_store_test) diff --git a/runtime/shims/library_loader.cpp b/runtime/shims/library_loader.cpp index 82dd75493..4a1f0cce3 100644 --- a/runtime/shims/library_loader.cpp +++ b/runtime/shims/library_loader.cpp @@ -13,6 +13,7 @@ // loader see these: they are bound through the registry, the runtime's own code calls the host directly. #include +#include #include #include #include @@ -200,8 +201,12 @@ HMODULE WINAPI load_library_ex_w(LPCWSTR name, HANDLE file, DWORD flags) { } // GetModuleHandle answers for an owned module as if it were loaded (the GDK may probe before it loads), and for any -// bundled package module already mapped by the native loader. +// bundled package module already mapped by the native loader. NULL names the title's main image once main.cpp has +// set it (VIctory victory-hle src/modules/kernel.rs, GPL-3.0-or-later: "GetModuleHandleW(NULL) must return the +// title's image, not our exe"), as the console's loader would answer: the title's process is its own. HMODULE WINAPI get_module_handle_a(LPCSTR name) { + if (!name) + if (void* main = main_image()) return static_cast(main); if (name) { if (HMODULE h = owned_handle(name)) return h; const std::string dll = module_name(name); @@ -212,6 +217,8 @@ HMODULE WINAPI get_module_handle_a(LPCSTR name) { } HMODULE WINAPI get_module_handle_w(LPCWSTR name) { + if (!name) + if (void* main = main_image()) return static_cast(main); if (name) { if (ascii_basename(name)) { const std::string path = narrow(name); @@ -276,6 +283,49 @@ FARPROC WINAPI get_proc_address(HMODULE module, LPCSTR name) { return GetProcAddress(module, name); } +// GetModuleFileName of a mapped image (NULL: the main image, once set) is the file it was mapped from, the title's +// own path, not gta6rt.exe's; Windows cannot answer for an image it did not map (ERROR_MOD_NOT_FOUND). Ported from +// VIctory kernel.rs: the title relaunches itself and finds its folder through this path. The copy follows +// Windows' rules: a buffer too small gets the truncated, terminated path, the return value `size` and +// ERROR_INSUFFICIENT_BUFFER; otherwise the length without the terminator. +bool mapped_module_path(HMODULE module, std::wstring& path) { + void* const base = module ? static_cast(module) : main_image(); + return base && bundled_module_path(base, path); +} + +template DWORD copy_module_path(const std::basic_string& path, Char* out, DWORD size) { + if (!out || size == 0) { + SetLastError(ERROR_INSUFFICIENT_BUFFER); + return 0; + } + if (path.size() >= size) { + std::copy_n(path.data(), size - 1, out); + out[size - 1] = 0; + SetLastError(ERROR_INSUFFICIENT_BUFFER); + return size; + } + std::copy_n(path.data(), path.size(), out); + out[path.size()] = 0; + SetLastError(ERROR_SUCCESS); + return static_cast(path.size()); +} + +DWORD WINAPI get_module_file_name_w(HMODULE module, LPWSTR out, DWORD size) { + std::wstring path; + if (!mapped_module_path(module, path)) return GetModuleFileNameW(module, out, size); + return copy_module_path(path, out, size); +} + +DWORD WINAPI get_module_file_name_a(HMODULE module, LPSTR out, DWORD size) { + std::wstring path; + if (!mapped_module_path(module, path)) return GetModuleFileNameA(module, out, size); + // In the ANSI code page, as GetModuleFileNameA gives it. + const int n = WideCharToMultiByte(CP_ACP, 0, path.c_str(), -1, nullptr, 0, nullptr, nullptr); + std::string narrow(n > 0 ? static_cast(n - 1) : 0, ' '); + if (n > 1) WideCharToMultiByte(CP_ACP, 0, path.c_str(), -1, narrow.data(), n, nullptr, nullptr); + return copy_module_path(narrow, out, size); +} + BOOL WINAPI free_library(HMODULE module) { if (pseudo(module)) return TRUE; // owned modules are never unloaded if (owns_bundled_module_handle(module)) return TRUE; // mapped modules stay live until ~Loader detaches them @@ -302,7 +352,7 @@ BOOL WINAPI disable_thread_calls(HMODULE module) { {dll, "GetModuleHandleW", reinterpret_cast(&rt::shims::library_loader::get_module_handle_w)}, \ {dll, "GetProcAddress", reinterpret_cast(&rt::shims::library_loader::get_proc_address)}, \ {dll, "FreeLibrary", reinterpret_cast(&rt::shims::library_loader::free_library)}, \ - {dll, "DisableThreadLibraryCalls", reinterpret_cast(&rt::shims::library_loader::disable_thread_calls)} + {dll, "DisableThreadLibraryCalls", reinterpret_cast(&rt::shims::library_loader::disable_thread_calls)}, {dll, "GetModuleFileNameA", reinterpret_cast(&rt::shims::library_loader::get_module_file_name_a)}, {dll, "GetModuleFileNameW", reinterpret_cast(&rt::shims::library_loader::get_module_file_name_w)} } // namespace } // namespace rt::shims::library_loader diff --git a/runtime/shims/registry.cpp b/runtime/shims/registry.cpp index d6a0d74b4..866b55f8d 100644 --- a/runtime/shims/registry.cpp +++ b/runtime/shims/registry.cpp @@ -480,6 +480,19 @@ bool owns_bundled_module_handle(void* module) { return false; } +bool bundled_module_path(void* module, std::wstring& path) { + if (!module) return false; + for (const auto& entry : snapshot_bundled_loaders()) + if (entry.ops->module_path && entry.ops->module_path(entry.ctx, module, path)) return true; + return false; +} + +namespace { +std::atomic g_main_image{nullptr}; +} +void set_main_image(void* base) { g_main_image.store(base); } +void* main_image() { return g_main_image.load(); } + Table::Table(const Entry* entries, size_t count) { for (size_t i = 0; i < count; ++i) table()[lower_ascii(entries[i].dll) + "!" + entries[i].name] = entries[i].fn; } diff --git a/runtime/shims/shims.h b/runtime/shims/shims.h index 76a7e761f..007f52f1b 100644 --- a/runtime/shims/shims.h +++ b/runtime/shims/shims.h @@ -69,6 +69,8 @@ struct BundledModuleOps { // (library_loader's W entries use them when a name has a character outside ASCII). Either may be null. void* (*find_loaded_w)(void* ctx, const std::wstring& basename); void* (*load_bundled_w)(void* ctx, const std::wstring& basename, uint32_t flags, bool& handled); + // The file a mapped module was mapped from, for GetModuleFileName on its handle (null: not answered). + bool (*module_path)(void* ctx, void* module, std::wstring& path); }; void add_bundled_loader(void* ctx, const BundledModuleOps* ops); void remove_bundled_loader(void* ctx); @@ -79,6 +81,13 @@ void* find_loaded_bundled_module_w(const std::wstring& basename); void* load_bundled_module_w(const std::wstring& basename, uint32_t flags, bool& handled); void* get_bundled_proc_address(void* module, const std::string& sym, bool& owns_handle); bool owns_bundled_module_handle(void* module); +// The file a live Loader mapped `module` from (its original path in the game folder); false for any other handle. +bool bundled_module_path(void* module, std::wstring& path); + +// The title's main image, which GetModuleHandle(NULL) and GetModuleFileName(NULL) answer with in mapped code, as the +// console's loader would (VIctory victory-hle src/modules/kernel.rs). Null until set: those calls then reach the host. +void set_main_image(void* base); +void* main_image(); // Test seam: called at the top of every unimplemented-import call with the address of rt_unimplemented's return // address slot (so a test can check stack alignment) and from inside the call (so it can walk the stack). diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp index 6ec344aab..0a8e0d51c 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp @@ -263,6 +263,8 @@ int wmain(int argc, wchar_t** argv) { try { rt::Loader loader(game_dir); rt::Module& main_module = loader.load(image); // maps, binds and installs TLS; runs no image code + // GetModuleHandle(NULL) and GetModuleFileName(NULL) in mapped code name the title, not gta6rt.exe. + rt::shims::set_main_image(main_module.base); if (init || run) { apply_display_profile(main_module); apply_frame_step(main_module); diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index 5e55ac1f9..d76df5ed4 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -1046,6 +1046,10 @@ void* bundled_load_w(void* ctx, const std::wstring& basename, uint32_t flags, bo return static_cast(ctx)->load_runtime_module_w(basename, flags, handled); } +bool bundled_module_path(void* ctx, void* module, std::wstring& path) { + return static_cast(ctx)->module_path(module, path); +} + const shims::BundledModuleOps kBundledOps{ &bundled_find_loaded, &bundled_load, @@ -1053,6 +1057,7 @@ const shims::BundledModuleOps kBundledOps{ &bundled_owns_handle, &bundled_find_loaded_w, &bundled_load_w, + &bundled_module_path, }; // Marks what a run-time load maps as a dynamic load for as long as it is in scope (the caller holds the mutex). @@ -1299,6 +1304,19 @@ bool Loader::find_address(uint64_t address, std::string& module, uint32_t& rva) return false; } +bool Loader::module_path(void* module_handle, std::wstring& path) const { + if (!module_handle) return false; + std::lock_guard lock(mutex_); + for (const Module* m : order_) + if (m->base == module_handle) { + std::error_code ec; + const std::filesystem::path absolute = std::filesystem::absolute(m->path, ec); + path = (ec ? m->path : absolute).wstring(); + return true; + } + return false; +} + bool Loader::owns_module_handle(void* module_handle) const { if (!module_handle) return false; std::lock_guard lock(mutex_); diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h index fda924440..c61fc2f5e 100644 --- a/runtime/src/pe_loader.h +++ b/runtime/src/pe_loader.h @@ -133,6 +133,8 @@ public: void* load_runtime_module_w(const std::wstring& basename, uint32_t flags, bool& handled); void* resolve_module_export(void* module_handle, const std::string& sym, bool& owns_handle); bool owns_module_handle(void* module_handle) const; + // The file a mapped module was mapped from, by its handle (base); false for any other handle. + bool module_path(void* module_handle, std::wstring& path) const; private: void initialise(Module& m); diff --git a/runtime/test/module_identity_test.cpp b/runtime/test/module_identity_test.cpp new file mode 100644 index 000000000..912acb2d1 --- /dev/null +++ b/runtime/test/module_identity_test.cpp @@ -0,0 +1,93 @@ +// GetModuleHandle(NULL) and GetModuleFileName in mapped code name the title's image (shims/library_loader.cpp, +// ported from VIctory victory-hle src/modules/kernel.rs). No game files: a stand-in loader answers for one fake image +// base with a made-up path. +#include + +#include +#include +#include + +#include "shims.h" + +namespace { + +int g_failures = 0; +void check(bool condition, const char* what) { + std::printf("%s: %s\n", condition ? "ok" : "FAIL", what); + if (!condition) ++g_failures; +} + +// Any address no host module has; never dereferenced. +alignas(64) unsigned char g_fake_image[16]; +void* const kImage = g_fake_image; +const wchar_t kPath[] = L"C:\\Games\\Title\\title_master.exe"; + +void* find_loaded(void*, const std::string&) { return nullptr; } +void* load_bundled(void*, const std::string&, uint32_t, bool& handled) { + handled = false; + return nullptr; +} +void* get_proc(void*, void* module, const std::string&, bool& owns) { + owns = module == kImage; + return nullptr; +} +bool owns_handle(void*, void* module) { return module == kImage; } +bool module_path(void*, void* module, std::wstring& path) { + if (module != kImage) return false; + path = kPath; + return true; +} +const rt::shims::BundledModuleOps kOps{&find_loaded, &load_bundled, &get_proc, &owns_handle, nullptr, nullptr, + &module_path}; + +} // namespace + +int main() { + using HandleW = HMODULE(WINAPI*)(LPCWSTR); + using HandleA = HMODULE(WINAPI*)(LPCSTR); + using NameW = DWORD(WINAPI*)(HMODULE, LPWSTR, DWORD); + using NameA = DWORD(WINAPI*)(HMODULE, LPSTR, DWORD); + const auto handle_w = reinterpret_cast(rt::shims::find("kernel32.dll", "GetModuleHandleW")); + const auto handle_a = reinterpret_cast(rt::shims::find("kernelbase.dll", "GetModuleHandleA")); + const auto name_w = reinterpret_cast(rt::shims::find("kernel32.dll", "GetModuleFileNameW")); + const auto name_a = + reinterpret_cast(rt::shims::find("api-ms-win-core-libraryloader-l1-2-0.dll", "GetModuleFileNameA")); + check(handle_w && handle_a && name_w && name_a, "the four imports are served"); + if (!(handle_w && handle_a && name_w && name_a)) return 1; + + // Before the main image is set, everything is the host's. + check(handle_w(nullptr) == GetModuleHandleW(nullptr), "no main image yet: GetModuleHandleW(NULL) is the host's"); + wchar_t host[MAX_PATH] = {}, got[MAX_PATH] = {}; + GetModuleFileNameW(nullptr, host, MAX_PATH); + check(name_w(nullptr, got, MAX_PATH) > 0 && std::wcscmp(host, got) == 0, + "no main image yet: GetModuleFileNameW(NULL) is the host's"); + + rt::shims::add_bundled_loader(&g_failures, &kOps); + rt::shims::set_main_image(kImage); + check(handle_w(nullptr) == kImage && handle_a(nullptr) == kImage, "GetModuleHandleA/W(NULL) is the title's image"); + check(handle_w(L"kernel32.dll") == GetModuleHandleW(L"kernel32.dll"), "a named host module is still the host's"); + + const DWORD length = static_cast(std::wcslen(kPath)); + std::memset(got, 0, sizeof(got)); + check(name_w(nullptr, got, MAX_PATH) == length && std::wcscmp(got, kPath) == 0, + "GetModuleFileNameW(NULL) is the title's file, its length without the terminator"); + std::memset(got, 0, sizeof(got)); + check(name_w(static_cast(kImage), got, MAX_PATH) == length && std::wcscmp(got, kPath) == 0, + "GetModuleFileNameW(title base) is the same file"); + char narrow[MAX_PATH] = {}; + check(name_a(nullptr, narrow, MAX_PATH) == length && std::strcmp(narrow, "C:\\Games\\Title\\title_master.exe") == 0, + "GetModuleFileNameA(NULL) is the same file in the ANSI code page"); + wchar_t small[8] = {}; + SetLastError(0); + check(name_w(nullptr, small, 8) == 8 && small[7] == 0 && std::wcsncmp(small, kPath, 7) == 0 && + GetLastError() == ERROR_INSUFFICIENT_BUFFER, + "a short buffer gets the truncated, terminated path, its size and ERROR_INSUFFICIENT_BUFFER"); + const HMODULE k32 = GetModuleHandleW(L"kernel32.dll"); + GetModuleFileNameW(k32, host, MAX_PATH); + check(name_w(k32, got, MAX_PATH) > 0 && std::wcscmp(host, got) == 0, "a host module's file is the host's answer"); + + rt::shims::set_main_image(nullptr); + rt::shims::remove_bundled_loader(&g_failures); + std::printf("%s\n", g_failures ? "FAILED" : "PASSED"); + return g_failures ? 1 : 0; +} -- cgit v1.2.3 From 00131bb85ee294179e5179b00a2c68f4ea3610b5 Mon Sep 17 00:00:00 2001 From: NotRexed Date: Fri, 27 Nov 2026 17:58:38 -0500 Subject: main keeps its own runtime, tools and tests; the branch's variants stay on port/d3d12-nvidia After the merge the tree held this branch's older states of files main maintains. Run against main's code, tests/test_acphal_abi.py and 11 of the 15 translator tests that differed failed, and the C++ runtime would have been built from two generations of its sources. So that the merge cannot break what main builds and tests: - runtime/ is main's, file for file (68 files only this branch had are not carried over); - every file under tools/, tests/ and docs/ that both sides have is main's (80 files); - ten translator tests only this branch has, which test rules main's translator does not have, and their fixtures are left out. What main gains: d3d12/ (the Rust D3D12 runtime), its launchers and helpers (Launcher.bat, scripts/play*.ps1, play-linux.sh, port_ctl.py, smooth-motion.ps1, fetch_vkd3d_proton.py, sync_victory.py), mods/example_lua, eleven notes under docs/, seven tools and the tests that pass with main's code, the README's sections and credits, and the "Runtime traps" section of AGENTS.md. Everything left out here is on the branch port/d3d12-nvidia. Checked: compileall; make_game.py --help; check_no_game_data.py over every file this adds to main; the line-ending, docs-encoding, CI-registration and docs tests; each test file that differs from main, on its own. Not run: the whole translator suite, the C++ build, cargo over d3d12/ after the merge (d3d12/ is byte for byte the branch's), CI. Co-Authored-By: Claude Fable 5.2 --- docs/d3d12_command_objects.md | 7 - docs/i18n/fr/quickstart.md | 4 +- docs/mobile.md | 2 +- docs/modding.md | 7 - docs/restofworld.md | 29 +- docs/story.md | 15 +- runtime/shims/app_state.cpp | 132 --- runtime/shims/chad_dsp.cpp | 183 ---- runtime/shims/d3d12_xs.cpp | 55 +- runtime/shims/d3d12_xs_slots.h | 416 -------- runtime/shims/dstorage_xs.cpp | 1053 -------------------- runtime/shims/dstorage_xs.h | 233 ----- runtime/shims/file_system.h | 5 - runtime/shims/gameinput_xinput.cpp | 1067 --------------------- runtime/shims/gameinput_xinput.h | 62 -- runtime/shims/library_loader.cpp | 54 +- runtime/shims/media_foundation.cpp | 357 ------- runtime/shims/media_foundation.h | 17 - runtime/shims/process.cpp | 54 -- runtime/shims/registry_oem.cpp | 102 -- runtime/shims/shims.h | 19 - runtime/shims/title_window.cpp | 106 -- runtime/shims/winsock_offline.cpp | 324 ------- runtime/shims/xbox_display.cpp | 389 -------- runtime/shims/xbox_display.h | 62 -- runtime/shims/xbox_present.h | 27 - runtime/shims/xbox_window.cpp | 568 ----------- runtime/shims/xbox_window.h | 73 -- runtime/shims/xgameruntime_user.cpp | 5 +- runtime/src/aspect_fit.h | 222 ----- runtime/src/bcpack_decode.h | 19 - runtime/src/bcpack_decode_stub.cpp | 12 - runtime/src/console_insn.cpp | 334 ------- runtime/src/console_insn.h | 73 -- runtime/src/debug_magenta_spv.h | 71 -- runtime/src/display_mode.h | 55 -- runtime/src/display_profile.h | 170 ---- runtime/src/frame_meter.h | 97 -- runtime/src/frame_step.h | 184 ---- runtime/src/gfx10_descriptors.h | 17 - runtime/src/gfx10_tiling.h | 618 ------------ runtime/src/host_cpu.h | 3 +- runtime/src/opus_packet.h | 128 --- runtime/src/pe_loader.cpp | 18 - runtime/src/pe_loader.h | 2 - runtime/src/pipeline_queue.h | 749 --------------- runtime/src/png_write.h | 257 ----- runtime/src/rect_list_gs.cpp | 691 ------------- runtime/src/rect_list_gs.h | 108 --- runtime/src/resource_detile.h | 8 - runtime/src/spirv_output_splat.h | 116 --- runtime/src/title_memory.h | 145 --- runtime/src/xma_context.cpp | 224 ----- runtime/src/xma_context.h | 143 --- runtime/src/xma_decode.cpp | 897 ----------------- runtime/src/xma_decode.h | 154 --- runtime/src/xma_tables.h | 226 ----- runtime/test/app_state_test.cpp | 68 -- runtime/test/aspect_fit_test.cpp | 127 --- runtime/test/bcpack_test.cpp | 673 ------------- runtime/test/chad_dsp_test.cpp | 150 --- runtime/test/check_tiny_present.py | 183 ---- runtime/test/console_insn_test.cpp | 166 ---- runtime/test/d3d12_async_pipeline_test.cpp | 487 ---------- runtime/test/d3d12_depth_twin_test.cpp | 345 ------- runtime/test/d3d12_sampler2_test.cpp | 81 -- runtime/test/d3d12_title_memory_test.cpp | 1056 -------------------- runtime/test/d3d12_xs_exports_test.cpp | 55 -- runtime/test/dstorage_xs_test.cpp | 746 -------------- runtime/test/file_system_test.cpp | 26 - runtime/test/fixtures/ntuser_window_stub.cpp | 10 - runtime/test/fixtures/ntuser_window_stub.def | 3 - runtime/test/fixtures/tiny_present.cpp | 308 ------ runtime/test/frame_step_test.cpp | 202 ---- runtime/test/gameinput_xinput_test.cpp | 475 --------- runtime/test/gfx10_descriptors_test.cpp | 12 - runtime/test/gfx10_tiling_test.cpp | 250 +---- runtime/test/glsl/cs_depth_twin.comp | 64 -- runtime/test/glsl/cs_sparse_title_memory.comp | 45 - runtime/test/loader_test.cpp | 3 - runtime/test/media_foundation_test.cpp | 161 ---- runtime/test/module_identity_test.cpp | 93 -- runtime/test/pipeline_queue_test.cpp | 224 ----- runtime/test/predication_barrier_test.cpp | 67 -- runtime/test/present_window_parts_test.cpp | 255 ----- runtime/test/process_cmdline_test.cpp | 17 - runtime/test/rect_list_gs_tool.cpp | 61 -- runtime/test/registry_oem_test.cpp | 83 -- runtime/test/spirv_output_splat_test.cpp | 117 --- runtime/test/vk_pipeline_paths.cpp | 402 -------- runtime/test/vk_sparse_title_memory_test.cpp | 663 ------------- runtime/test/winsock_offline_test.cpp | 134 --- runtime/test/xgameruntime_store_test.cpp | 9 - runtime/test/xgameruntime_user_test.cpp | 11 +- runtime/test/xma_test.cpp | 768 --------------- tests/semantic/fixtures/cs_w64_half_local.asm | 14 - tests/semantic/fixtures/cs_w64_lds_swap.asm | 16 - tests/semantic/fixtures/discard_keeps_helper.asm | 21 - tests/semantic/fixtures/image_load_tfe.asm | 14 - tests/semantic/fixtures/loop_limit_back.asm | 12 - tests/semantic/fixtures/loop_limit_barrier.asm | 19 - tests/semantic/fixtures/loop_limit_jump.asm | 13 - tests/semantic/fixtures/ms_w64_skeleton.asm | 50 - tests/semantic/fixtures/quad_helper_reads.asm | 32 - tests/semantic/fixtures/wave64_cmp_sgpr_pair.asm | 26 - tests/semantic/support.py | 26 - tests/semantic/test_console_stage_wave32.py | 68 -- tests/semantic/test_ds_permute.py | 10 +- tests/semantic/test_exec_computed.py | 19 - tests/semantic/test_interp.py | 9 +- tests/semantic/test_interp_p2_f16_opsel_dst.py | 83 -- tests/semantic/test_loop_limit.py | 190 ---- tests/semantic/test_mimg_tfe_status.py | 88 -- tests/semantic/test_ms_barrier_fence.py | 47 - tests/semantic/test_quad_helper_lanes.py | 163 ---- tests/semantic/test_wave64_append_bitreplicate.py | 115 --- tests/semantic/test_wave64_compute_tiers.py | 338 ------- tests/semantic/test_wave64_halves_victory.py | 159 --- tests/semantic/test_wave64_mask_pairs.py | 63 -- tests/test_acphal_abi.py | 39 +- tests/test_anim_glb.py | 9 - tests/test_audio_wav.py | 15 +- tests/test_awc_names.py | 20 - tests/test_bink_index.py | 21 - tests/test_bink_names.py | 28 - tests/test_build_runtime_cmake.py | 6 +- tests/test_bvh_index.py | 23 - tests/test_bvh_slot_check.py | 18 - tests/test_cvt_norm_mods_probe.py | 13 +- tests/test_dds_png.py | 20 - tests/test_f32_fuzz.py | 12 - tests/test_file_mode.py | 13 - tests/test_glb_writer.py | 17 - tests/test_gpu_test_timeout.py | 10 +- tests/test_instance_lists.py | 16 - tests/test_leonida_mods.py | 33 - tests/test_navmesh_cell_fit.py | 14 - tests/test_navmesh_tile_obj.py | 25 - tests/test_pool_workers.py | 10 - tests/test_rsc8_audio.py | 16 - tests/test_rtti_scan.py | 23 - tests/test_run_gpu_tests_paths.py | 6 +- tests/test_sandbox_scene.py | 12 - tests/test_shader_link_check.py | 21 - tests/test_skin_streams.py | 16 - tests/test_text_tables.py | 25 - tests/test_world_build.py | 18 - tests/test_world_build_output_lock.py | 14 - tests/test_world_census.py | 22 - tests/test_world_index.py | 17 - tests/test_world_lights_paths.py | 22 - tests/test_world_names.py | 16 - tests/test_x64_recomp.py | 9 +- tools/anim_clips.py | 13 +- tools/anim_glb.py | 9 +- tools/audio_wav.py | 11 +- tools/awc_names.py | 5 +- tools/bink_index.py | 11 +- tools/bink_names.py | 7 +- tools/bvh_index.py | 4 +- tools/bvh_slot_check.py | 9 +- tools/cfg_structure.py | 42 - tools/dds_png.py | 6 +- tools/f32_fuzz.py | 8 - tools/file_mode.py | 1 - tools/glb_writer.py | 1 - tools/instance_lists.py | 12 +- tools/leonida_mods.py | 30 +- tools/navmesh_cell_fit.py | 9 +- tools/navmesh_tile_obj.py | 6 - tools/odrp_7a.py | 16 +- tools/pool_workers.py | 2 - tools/restofworld_model_join.py | 16 +- tools/rsc8_audio.py | 1 - tools/rtti_scan.py | 12 +- tools/sandbox_scene.py | 4 - tools/shader_link_check.py | 4 - tools/shader_profile.py | 14 +- tools/skin_streams.py | 15 +- tools/tex_headers.py | 14 +- tools/text_tables.py | 18 +- tools/ttpf_assets.py | 9 +- tools/ttpf_mips.py | 14 +- tools/vertex_types.py | 13 +- tools/world_build.py | 11 +- tools/world_census.py | 8 +- tools/world_index.py | 20 +- tools/world_lights_paths.py | 10 - tools/world_names.py | 8 +- tools/x64_recomp.py | 9 +- 190 files changed, 221 insertions(+), 22143 deletions(-) delete mode 100644 runtime/shims/app_state.cpp delete mode 100644 runtime/shims/chad_dsp.cpp delete mode 100644 runtime/shims/d3d12_xs_slots.h delete mode 100644 runtime/shims/dstorage_xs.cpp delete mode 100644 runtime/shims/dstorage_xs.h delete mode 100644 runtime/shims/gameinput_xinput.cpp delete mode 100644 runtime/shims/gameinput_xinput.h delete mode 100644 runtime/shims/media_foundation.cpp delete mode 100644 runtime/shims/media_foundation.h delete mode 100644 runtime/shims/registry_oem.cpp delete mode 100644 runtime/shims/title_window.cpp delete mode 100644 runtime/shims/winsock_offline.cpp delete mode 100644 runtime/shims/xbox_display.cpp delete mode 100644 runtime/shims/xbox_display.h delete mode 100644 runtime/shims/xbox_window.cpp delete mode 100644 runtime/shims/xbox_window.h delete mode 100644 runtime/src/aspect_fit.h delete mode 100644 runtime/src/bcpack_decode.h delete mode 100644 runtime/src/bcpack_decode_stub.cpp delete mode 100644 runtime/src/console_insn.cpp delete mode 100644 runtime/src/console_insn.h delete mode 100644 runtime/src/debug_magenta_spv.h delete mode 100644 runtime/src/display_mode.h delete mode 100644 runtime/src/display_profile.h delete mode 100644 runtime/src/frame_meter.h delete mode 100644 runtime/src/frame_step.h delete mode 100644 runtime/src/opus_packet.h delete mode 100644 runtime/src/pipeline_queue.h delete mode 100644 runtime/src/png_write.h delete mode 100644 runtime/src/rect_list_gs.cpp delete mode 100644 runtime/src/rect_list_gs.h delete mode 100644 runtime/src/spirv_output_splat.h delete mode 100644 runtime/src/title_memory.h delete mode 100644 runtime/src/xma_context.cpp delete mode 100644 runtime/src/xma_context.h delete mode 100644 runtime/src/xma_decode.cpp delete mode 100644 runtime/src/xma_decode.h delete mode 100644 runtime/src/xma_tables.h delete mode 100644 runtime/test/app_state_test.cpp delete mode 100644 runtime/test/aspect_fit_test.cpp delete mode 100644 runtime/test/bcpack_test.cpp delete mode 100644 runtime/test/chad_dsp_test.cpp delete mode 100644 runtime/test/check_tiny_present.py delete mode 100644 runtime/test/console_insn_test.cpp delete mode 100644 runtime/test/d3d12_async_pipeline_test.cpp delete mode 100644 runtime/test/d3d12_depth_twin_test.cpp delete mode 100644 runtime/test/d3d12_title_memory_test.cpp delete mode 100644 runtime/test/d3d12_xs_exports_test.cpp delete mode 100644 runtime/test/dstorage_xs_test.cpp delete mode 100644 runtime/test/fixtures/ntuser_window_stub.cpp delete mode 100644 runtime/test/fixtures/ntuser_window_stub.def delete mode 100644 runtime/test/fixtures/tiny_present.cpp delete mode 100644 runtime/test/frame_step_test.cpp delete mode 100644 runtime/test/gameinput_xinput_test.cpp delete mode 100644 runtime/test/glsl/cs_depth_twin.comp delete mode 100644 runtime/test/glsl/cs_sparse_title_memory.comp delete mode 100644 runtime/test/media_foundation_test.cpp delete mode 100644 runtime/test/module_identity_test.cpp delete mode 100644 runtime/test/pipeline_queue_test.cpp delete mode 100644 runtime/test/predication_barrier_test.cpp delete mode 100644 runtime/test/present_window_parts_test.cpp delete mode 100644 runtime/test/rect_list_gs_tool.cpp delete mode 100644 runtime/test/registry_oem_test.cpp delete mode 100644 runtime/test/spirv_output_splat_test.cpp delete mode 100644 runtime/test/vk_pipeline_paths.cpp delete mode 100644 runtime/test/vk_sparse_title_memory_test.cpp delete mode 100644 runtime/test/winsock_offline_test.cpp delete mode 100644 runtime/test/xma_test.cpp delete mode 100644 tests/semantic/fixtures/cs_w64_half_local.asm delete mode 100644 tests/semantic/fixtures/cs_w64_lds_swap.asm delete mode 100644 tests/semantic/fixtures/discard_keeps_helper.asm delete mode 100644 tests/semantic/fixtures/image_load_tfe.asm delete mode 100644 tests/semantic/fixtures/loop_limit_back.asm delete mode 100644 tests/semantic/fixtures/loop_limit_barrier.asm delete mode 100644 tests/semantic/fixtures/loop_limit_jump.asm delete mode 100644 tests/semantic/fixtures/ms_w64_skeleton.asm delete mode 100644 tests/semantic/fixtures/quad_helper_reads.asm delete mode 100644 tests/semantic/fixtures/wave64_cmp_sgpr_pair.asm delete mode 100644 tests/semantic/test_console_stage_wave32.py delete mode 100644 tests/semantic/test_interp_p2_f16_opsel_dst.py delete mode 100644 tests/semantic/test_loop_limit.py delete mode 100644 tests/semantic/test_mimg_tfe_status.py delete mode 100644 tests/semantic/test_ms_barrier_fence.py delete mode 100644 tests/semantic/test_quad_helper_lanes.py delete mode 100644 tests/semantic/test_wave64_append_bitreplicate.py delete mode 100644 tests/semantic/test_wave64_compute_tiers.py delete mode 100644 tests/semantic/test_wave64_halves_victory.py delete mode 100644 tests/semantic/test_wave64_mask_pairs.py (limited to 'runtime/src/pe_loader.cpp') diff --git a/docs/d3d12_command_objects.md b/docs/d3d12_command_objects.md index 7afd38a5f..eea693c70 100644 --- a/docs/d3d12_command_objects.md +++ b/docs/d3d12_command_objects.md @@ -807,13 +807,6 @@ first calls; a wrong slot would therefore be visible as a misnamed call, not a s Queues and fences are wrapped the same way. -A device created as `ID3D12Device11`, as the title creates its own, has the console layouts instead: its queues, -fences, allocators and lists follow the slot tables in `runtime/shims/d3d12_xs_slots.h`, taken from VIctory -(`victory/crates/victory-gpu/src/{device,queue,list,fence}.rs`, which runs the title) and from the measurements on -this page, each entry with its source. There the queue methods from slot 14 on are two later than the PC's, the -fence has a value address at slot 12, and device slot 12 makes console list proxies. What follows describes the PC -layout, which every other device keeps. - - **What is wrapped.** Device slots 8 (`CreateCommandQueue`), 75 (`CreateCommandQueue1`), 36 (`CreateFence`) and 32 (`OpenSharedHandle`, when it opens a fence) return queue and fence proxies. Each proxy forwards the public chain in PC order: 19 queue slots, and 11 or 12 fence slots, in SDK 10.0.26100. diff --git a/docs/i18n/fr/quickstart.md b/docs/i18n/fr/quickstart.md index a3bc71e2b..933a74d4e 100644 --- a/docs/i18n/fr/quickstart.md +++ b/docs/i18n/fr/quickstart.md @@ -44,7 +44,7 @@ l'[issue #166](https://github.com/ItsNotRexed/Leonida/issues/166). - **Votre propre copie** du paquet Xbox Series, version `1.0.2.1` : le dossier qui contient `MicrosoftGame.Config` et les archives `.rpf`, sous forme de fichiers lisibles sur le disque. -- **Windows 10/11 x64**, avec environ **400 Go libres** pour les fichiers de travail. Ils peuvent aller sur un autre +- **Windows 10/11 x64**, avec environ **350 Go libres** pour les fichiers de travail. Ils peuvent aller sur un autre disque avec `--work`. - [Python 3.12+](https://www.python.org/downloads/) (cochez « Add python.exe to PATH » à l'installation). - [SDK .NET 8](https://dotnet.microsoft.com/download/dotnet/8.0). @@ -137,7 +137,7 @@ encore ce cache. - **Ce qui est refait automatiquement** : la compilation enregistre la commande et la version de `llvm-mc`, les sources du traducteur et le décodeur des ressources (`third_party/rpf9-explorer` et `tools/rpf9dump`). Si l'un d'eux change, seule l'étape concernée est refaite (désassemblage, traduction ou export des modèles et textures). -- **`--work`** : choisissez un disque avec au moins 400 Go libres. La traduction des shaders est l'étape la plus +- **`--work`** : choisissez un disque avec au moins 350 Go libres. La traduction des shaders est l'étape la plus longue ; elle utilise par défaut la moitié des threads du processeur (réglable avec `--jobs`). - **`--wav`** : désactivé par défaut, car le WAV PCM 16 bits est plusieurs fois plus volumineux que l'Ogg Opus. - **Linux et Wine/Proton** : `make_game.py` fonctionne aussi sous Linux. L'étape `pipelines` utilise diff --git a/docs/mobile.md b/docs/mobile.md index aaca95670..d2a8b9dca 100644 --- a/docs/mobile.md +++ b/docs/mobile.md @@ -32,7 +32,7 @@ of the x86-64 → arm64 groundwork. | Dispatch runtime | `tools/x64_recomp.py` `emit_rt` | `rt_dispatch` (guest pc → host pc through a generated table), `rt_mkflags` (NZCV+operands → canonical x86 EFLAGS; preserves NZCV), `rt_print` (semihosting result output) | | Verification | `tools/x64_recomp.py` `build_test_kernel`/`run_kernel` | flat kernel image → `qemu-system-aarch64 -M virt -cpu cortex-a53 -kernel -semihosting`; guest `ret` off the sentinel stack exits and prints `R=xxxxxxxx` (guest edi) | | PE census | `tools/recomp_census.py` | walks every `.pdata` function, decodes + translates it, reports coverage %, hazard mnemonics, indirect control flow, unwind-info flags | -| Tests | `tests/test_x64_recomp.py`, `tests/test_recomp_census.py` | hand-built byte fixtures only; exec tests skip when qemu is absent (`QEMU_AARCH64` names the binary, else `qemu-system-aarch64` on `PATH`) | +| Tests | `tests/test_x64_recomp.py`, `tests/test_recomp_census.py` | hand-built byte fixtures only; exec tests skip when qemu is absent | ### Translator contract (as implemented) diff --git a/docs/modding.md b/docs/modding.md index e0ccbb953..41ee5daed 100644 --- a/docs/modding.md +++ b/docs/modding.md @@ -74,13 +74,6 @@ are installed disabled so a copied folder cannot surprise anyone or silently fig | `monalisa_player_model` | `player_story000_00` -> `cs_monalisa` | disabled | | `mandy_to_monalisa` | `cs_mandy` -> `cs_monalisa` | disabled | -## Lua mods - -The D3D12 runtime (`leonida.exe`) also runs a `"script": "main.lua"` that sits next to a `mod.json` in the same -`mods//`; `tools/leonida_mods.py` lists, enables, disables, installs and packs such a mod like any other (it -shows `Lua main.lua` where an asset mod shows its swaps, and does not warn that it has none). What a script can do is -in [lua-modding.md](lua-modding.md); `mods/example_lua` is the example, installed disabled. - ## mod.json ```json diff --git a/docs/restofworld.md b/docs/restofworld.md index b21203300..ae2bb90c3 100644 --- a/docs/restofworld.md +++ b/docs/restofworld.md @@ -734,11 +734,16 @@ triangle or accept that documented exception. This does not by itself explain th 8-bit score above, whose per-block UV coverage was not measured here; the mixed-determinant vertex is one candidate. +Opaque: the encrypted RPF9 tables of contents, the Bink 2 bodies, the `LSNS` record contents, the bodies of the +`RSC8` headers, the nested RPF9 payloads, and the whole `appdata0` data area. Across the 971 +core graphics blocks, final-slot widths remain unresolved (`0x21`, the last unread component type, +is decoded above). The stride check Opaque: the encrypted RPF9 tables of contents, the Bink 2 bodies, the `LSNS` record contents, the nested RPF9 payloads, and the whole `appdata0` data area. The bodies of the nine `RSC8` headers are decoded in -[rsc8_audio.md](rsc8_audio.md): facial/lip-sync clips. Across the 971 core graphics blocks, final-slot widths remain -unresolved (the recurring component types, including both the normal and tangent bits of `0x21`, are decoded above). -The stride check also leaves 436 blocks unclassified, including 18 with a validated following meshlet group. +[rsc8_audio.md](rsc8_audio.md): facial/lip-sync clips. Across the 971 +core graphics blocks, final-slot widths remain unresolved, and of the component types the non-normal +bits of `0x21` (see above). The stride check +also leaves 436 blocks unclassified, including 18 with a validated following meshlet group. "Unread" in the tables above is not a claim that those bytes are empty: in `story000_restofworld` the 9.33 MB unread gap contains 15 `ADAT` (AWC) banks (8,908,216 bytes), which hold the nine `RSC8` headers as tag `0x5c` clips, and nested RPF9 headers, and @@ -928,13 +933,11 @@ streams found with `tools/restofworld_index.py`'s `find_rage_textures` / `is_pg_ all 924 `core_restofworld` model resources (936 drawables across 926 system and 1,020 graphics streams) and the single `story000_restofworld` drawable dictionary (3 drawables) without the TOC. Archive path names and external texture-dictionary links still need the TOC or hash matching. -7. A full vertex decoder for `42 40 00 00` blocks. ASSET-57 measured recurring stream widths, - `tools/vertex_types.py` decodes the recurring component types above (`0x42`, `0x28`, `0x27`, - `0x26`, `0x25`, `0x21`), and `tools/meshlet_page.py --draw-system` / - `tools/restofworld_model_join.py` resolve draw ownership when system metadata is available; - final-stream widths and locating the owning geometry from a graphics page alone remain open. - (Texture identification is resolved above under **Textures (`ASSET-148`)**: embedded `0x980` - descriptors in `zero-prefix` CPU-segment streams plus the companion `ttdb/*.ttpf` pools.) +7. A vertex decoder for `42 40 00 00` blocks. ASSET-57 measured recurring stream widths; + decoding vertex values still requires component types, final-stream widths and a way to + locate the owning geometry when only a graphics page is available. (Texture identification is + resolved above under **Textures (`ASSET-148`)**: embedded `0x980` descriptors in `zero-prefix` + CPU-segment streams plus the companion `ttdb/*.ttpf` pools.) 8. Runtime consumers for the XML content-definition records read by `tools/content_definitions.py` (see above). Their roots describe configuration, not UI layout; reference resolution and mapping to resources remain unimplemented. @@ -971,6 +974,6 @@ decrypts the TOC. - [docs/rpf.md](rpf.md) - RPF9 carving and recovery tools. - [docs/design.md](design.md) - the model manifest and the archive-stage table. -- [docs/story.md](story.md) - the `story000`/`shared_minigame000` archive family. -- [docs/world.md](world.md) - map placement and the `0x7a` metadata resource (PR #117). -- [docs/psin.md](psin.md) - the `PSIN` container measured on `script.rpf` and `data.rpf` (PR #110). +- `docs/story.md` - the `story000`/`shared_minigame000` archive family (pending story PR). +- `docs/world.md` - map placement and the `0x7a` metadata resource (PR #117). +- `docs/psin.md` - the `PSIN` container measured on `script.rpf` and `data.rpf` (PR #110). diff --git a/docs/story.md b/docs/story.md index 49e8c8064..a0a0e1770 100644 --- a/docs/story.md +++ b/docs/story.md @@ -278,7 +278,7 @@ Deliberately wrong reads of the first 300 streams don't hold up: - **The low bytes swapped between `a` and `b`:** the same at 25°, but fewer neighbours within 0.1° than with no low bytes at all. Within 0.1° the counts are 7.56% swapped, 8.59% with the high 16 bits only, and 9.19% with the rule. -The 4-byte attribute streams (`0x21` and `0x27` normals and tangents) are decoded below; `0x26` (colour/skin weights) and `0x28` (`int16` UVs) are measured across the full corpus in [restofworld.md](restofworld.md). +The 4-byte attribute streams (tags 0x21, 0x26, 0x27, 0x28) are still not decoded. With these blocks sized, the archive walk accepts 1,569 streams and leaves 0 unparsed: @@ -406,6 +406,7 @@ chunks on a 256-byte boundary behind zero padding; the walk stops there (`stoppe | positions finite | all | | positions within 300 m | 29,572,450 (99.9%) | | shared edges with neighbouring faces within ~25° | 33,342,470 of 36,707,506 (90.8%); 1.4% opposed | +| normals within 8° / 25° of their faces | 76.5% / 94.6% of 20,801,089; 2.1% opposed | | normals within 8° / 25° of their faces | 76.5% / 94.5% of 20,801,089; 2.1% opposed | | tangents perpendicular to the normal | 30,473,135 of 30,569,246 (99.7%) | | radius covers the farthest vertex from the stored centre | 257,091 of 275,832 meshlets (93.2%); 94.8% within rounding | @@ -570,12 +571,10 @@ was found in the inflated sample. headers in `story000`; a decoder needs their spans and TOCs to group resources. 3. An `RSC8` decoder for version 8001: done. `tools/rsc8_audio.py` decodes the header and the facial/lip-sync clip payload ([rsc8_audio.md](rsc8_audio.md)). -4. A `PSIN` section and instance decoder: `tools/psin_index.py`, `tools/psin_data.py` and - `tools/odrp_7a.py` decode `LSCH`, `LENM`, `LRSC`, `CHKS`, the `LSNS` block layout and instance - data ([psin.md](psin.md)); `LSNS` 16-byte record contents and unhashed schema names remain open. -5. `0DRP` page grouping: `tools/page_index.py` and `tools/odrp_7a.py` derive resource stream - boundaries from the `q38` table (`+0x20` was tested on `story000.rpf` and does not mark stream - boundaries; see [page_directory.md](page_directory.md#the-0x20-count-does-not-mark-stream-boundaries)). +4. A `PSIN` section walker. The tag/length chain is measured; `LSCH`, `LENM`, `LSNS`, `LGID`, + `LRSC` and `CHKS` semantics are still open. +5. `0DRP` page grouping. The page count at +0x20 is the only measured grouping field; a decoder + still needs the following stream boundaries. 6. Bink 2 decoding for the 264 story streams and 7 restofworld streams (see `docs/movies.md`). 7. The existing model exporter for drawables; texture identification needs a real container signature, which this pass did not find. @@ -593,7 +592,7 @@ sizes, signatures and header fields; it does not write resource payloads or carv python -I tools/story_index.py [--start N] [--limit BYTES] python -I tools/rpf9_carve.py --index-only [--start N] [--limit BYTES] python -I tests/test_story_index.py -python -I tools/meshlet_page.py [...] [--faces] [--normals] [--cones] [--centres] [--json out.json] [--quiet] +python -I tools/meshlet_page.py [...] [--json out.json] [--quiet] python -I tests/test_meshlet_page.py ``` diff --git a/runtime/shims/app_state.cpp b/runtime/shims/app_state.cpp deleted file mode 100644 index 4044db7c9..000000000 --- a/runtime/shims/app_state.cpp +++ /dev/null @@ -1,132 +0,0 @@ -// app_state: the title's suspend routines, and how a run ends. -// -// A console title is never told it is closing: quitting it first suspends it (the routines it registered with -// RegisterAppStateChangeNotification run with Quiesced = TRUE, and it has about a second to save), and then the -// process ends. Ported from VIctory victory-hle src/modules/lifecycle.rs (GPL-3.0-or-later): -// RegisterAppStateChangeNotification / UnregisterAppStateChangeNotification keep the title's routines here (the -// host's psm-appnotify set is for packaged apps and never calls them), and end_title(), which the title's window -// calls when it is closed (title_window.cpp), runs them on a thread of their own (titles hand the suspend to their -// window thread and wait for it inside the routine, so not on the caller's) and ends the process when they return or -// after kSuspendDeadlineMs, whichever is first. -#include - -#include -#include -#include -#include -#include - -#include "shims.h" - -namespace rt::shims::app_state { -namespace { - -using Routine = void(CALLBACK*)(BOOLEAN quiesced, void* context); - -struct Registration { - uintptr_t id; - Routine routine; - void* context; -}; - -std::mutex& routines_mutex() { - static auto* m = new std::mutex; - return *m; -} -std::vector& routines() { - static auto* v = new std::vector; // immortal: read during process teardown - return *v; -} -std::atomic g_next{1}; - -constexpr DWORD kSuspendDeadlineMs = 1000; // how long the console lets suspend routines run - -// DWORD RegisterAppStateChangeNotification(PAPPSTATE_CHANGE_ROUTINE routine, PVOID context, -// PAPPSTATE_REGISTRATION* registration) -DWORD WINAPI register_app_state(Routine routine, void* context, void** registration) { - if (!routine || !registration) return ERROR_INVALID_PARAMETER; - const uintptr_t id = g_next.fetch_add(1); - { - std::lock_guard lock(routines_mutex()); - routines().push_back({id, routine, context}); - } - *registration = reinterpret_cast(id); - return ERROR_SUCCESS; -} - -// void UnregisterAppStateChangeNotification(PAPPSTATE_REGISTRATION registration) -void WINAPI unregister_app_state(void* registration) { - const auto id = reinterpret_cast(registration); - std::lock_guard lock(routines_mutex()); - auto& v = routines(); - for (auto it = v.begin(); it != v.end(); ++it) - if (it->id == id) { - v.erase(it); - break; - } -} - -DWORD WINAPI suspend_thread(void*) { - std::vector copy; - { - std::lock_guard lock(routines_mutex()); - copy = routines(); - } - for (const Registration& r : copy) r.routine(TRUE, r.context); - return 0; -} - -} // namespace - -size_t registered_routines() { - std::lock_guard lock(routines_mutex()); - return routines().size(); -} - -bool run_suspend_routines(unsigned deadline_ms) { - HANDLE thread = CreateThread(nullptr, 0, &suspend_thread, nullptr, 0, nullptr); - if (!thread) return false; - const bool finished = WaitForSingleObject(thread, deadline_ms) == WAIT_OBJECT_0; - CloseHandle(thread); - return finished; -} - -namespace { -DWORD WINAPI end_thread(void* why) { - const size_t count = registered_routines(); - std::fprintf(stderr, "[rt] app: %s: suspending the title (%zu suspend routine%s)\n", static_cast(why), - count, count == 1 ? "" : "s"); - const bool finished = run_suspend_routines(kSuspendDeadlineMs); - std::fprintf(stderr, "[rt] app: %s; the run ends\n", - finished ? "the title suspended" : "the title did not finish suspending in time"); - std::fflush(nullptr); - TerminateProcess(GetCurrentProcess(), 0); - return 0; -} -} // namespace - -void end_title(const char* why) { - static std::atomic s_ending{false}; - if (s_ending.exchange(true)) return; - HANDLE thread = CreateThread(nullptr, 0, &end_thread, const_cast(why), 0, nullptr); - if (thread) { - CloseHandle(thread); - return; - } - std::fflush(nullptr); - TerminateProcess(GetCurrentProcess(), 0); -} - -} // namespace rt::shims::app_state - -namespace { -#define APP_STATE(dll) \ - {dll, "RegisterAppStateChangeNotification", reinterpret_cast(&rt::shims::app_state::register_app_state)}, \ - {dll, "UnregisterAppStateChangeNotification", \ - reinterpret_cast(&rt::shims::app_state::unregister_app_state)} -} // namespace - -SHIM_TABLE(app_state, - APP_STATE("api-ms-win-core-psm-appnotify-l1-1-0.dll"), - APP_STATE("api-ms-win-core-psm-appnotify-l1-1-1.dll"), -); diff --git a/runtime/shims/chad_dsp.cpp b/runtime/shims/chad_dsp.cpp deleted file mode 100644 index dfa1f0093..000000000 --- a/runtime/shims/chad_dsp.cpp +++ /dev/null @@ -1,183 +0,0 @@ -// chad.dll: the console's audio DSP. Streams that convolve blocks of float samples with an impulse response (reverb), -// or run other block transforms, on a coprocessor. -// -// Ported from VIctory (crates/victory-hle/src/modules/dsp.rs), GPL-3.0-or-later, by Marvisak and contributors (DexNom -// fork). Leonida is GPL-3.0-or-later. The structure layouts, limits, option bits and HRESULTs are VIctory's, which ran -// the title with them. -// -// A title connects once with a memory block for the DSP, activates streams, and submits one command per block (gains, -// an input and an output buffer). Activation hands back a status block whose second word is the ticket of the last -// completed command and whose fourth is its result; the title checks it one block later and treats a late command as -// an overrun. Commands complete when submitted here. The title (1.0.2.1) connects for 0x80 streams (its fourth -// argument, docs/audio_hal_exe_calls.md) and activates stereo convolutions with option 2 (VIctory's test, "as the -// title asks for"). -// -// PLACEHOLDER, as in VIctory: the transforms themselves are not computed. The hardware takes impulse responses already -// in its own partitioned frequency-domain layout, which is not known. Outputs are silence, so reverb returns are dry; -// the completion (status words and tickets) is real. -#include - -#include -#include -#include -#include -#include -#include -#include - -#include "shims.h" -#include "startup_trace.h" - -namespace { - -constexpr HRESULT kPointer = static_cast(0x80004003u); -constexpr HRESULT kOutOfMemory = static_cast(0x8007000Eu); -constexpr HRESULT kInvalidArg = static_cast(0x80070057u); - -constexpr uint32_t kConvolution = 1; -// Option bits that need a stereo stream, and one convolution refuses. -constexpr uint32_t kStereoOptions = 2 | 8; -constexpr uint32_t kNotForConvolution = 4; - -struct Dsp { - uint32_t max_streams = 0; - std::mutex mutex; - uint32_t active = 0; -}; - -#pragma pack(push, 1) -// What activation describes. -struct StreamDesc { - uint32_t kind; - uint32_t options; - uint32_t frames; - uint32_t channels; - uint32_t ir_floats; - const float* ir; -}; -#pragma pack(pop) -static_assert(sizeof(StreamDesc) == 0x1c && offsetof(StreamDesc, ir) == 0x14); - -// The status block a stream's owner polls. -struct Status { - uint32_t submitted; - uint32_t completed; - uint32_t reserved; - HRESULT result; -}; -static_assert(sizeof(Status) == 16 && offsetof(Status, completed) == 4 && offsetof(Status, result) == 12); - -struct Stream { - Dsp* dsp = nullptr; - uint32_t frames = 0; - uint32_t channels = 0; - Status status{}; // handed to the title; lives as long as the stream -}; - -// One block of work. -struct Command { - float gains[2]; - const float* input; - float* output; - uint64_t reserved; -}; -static_assert(sizeof(Command) == 0x20 && offsetof(Command, input) == 8 && offsetof(Command, output) == 0x10); - -void trace_call(const char* api, const std::string& detail) { - if (!rt::startup_trace::enabled()) return; - rt::startup_trace::event("chad", std::string("\"api\":\"") + api + "\"" + detail); -} - -bool valid(const StreamDesc& desc) { - const bool shape = desc.kind == kConvolution - ? desc.channels >= 1 && desc.channels <= 2 && (desc.frames == 0x200 || desc.frames == 0x400) && - (desc.options & kNotForConvolution) == 0 - : desc.channels == 1 && (desc.frames == 0x200 || desc.frames == 0x400 || desc.frames == 0x800); - return shape && ((desc.options & kStereoOptions) == 0 || desc.channels == 2); -} - -HRESULT __stdcall XDspConnectWithMaximumStreamLimit(void* base, uint32_t base_length, uint32_t ir_seconds, - uint32_t max_streams, uint32_t max_channels, Dsp** out) { - if (!base || base_length < 0x10000 || base_length > 0x1F400000 || ir_seconds > 0x80 || max_streams > 0x100 || - max_channels > 2) - return kInvalidArg; - if (!out) return kPointer; - auto* dsp = new Dsp; - dsp->max_streams = max_streams; - *out = dsp; - std::fprintf(stderr, - "[rt] chad: audio DSP connected (0x%x bytes, %u s of impulse response, %u streams, %u channels); " - "block transforms output silence\n", - base_length, ir_seconds, max_streams, max_channels); - trace_call("XDspConnectWithMaximumStreamLimit", - ",\"length\":" + std::to_string(base_length) + ",\"streams\":" + std::to_string(max_streams)); - return S_OK; -} - -// Disconnected once, after its streams. -HRESULT __stdcall XDspDisconnect(Dsp* dsp) { - if (!dsp) return kInvalidArg; - delete dsp; - trace_call("XDspDisconnect", ""); - return S_OK; -} - -HRESULT __stdcall XDspActivate(Dsp* dsp, const StreamDesc* desc, const Status** status, Stream** stream) { - if (!status || !stream) return kPointer; - if (!dsp || !desc) return kInvalidArg; - StreamDesc d; - std::memcpy(&d, desc, sizeof d); - if (!valid(d)) return kInvalidArg; - { - std::lock_guard lock(dsp->mutex); - if (dsp->active >= dsp->max_streams) return kOutOfMemory; - ++dsp->active; - } - auto* created = new Stream; - created->dsp = dsp; - created->frames = d.frames; - created->channels = d.channels; - created->status.result = S_OK; - *status = &created->status; - *stream = created; - trace_call("XDspActivate", ",\"kind\":" + std::to_string(d.kind) + ",\"options\":" + std::to_string(d.options) + - ",\"frames\":" + std::to_string(d.frames) + - ",\"channels\":" + std::to_string(d.channels)); - return S_OK; -} - -// Deactivated once; the connection outlives its streams. -HRESULT __stdcall XDspDeactivate(Stream* stream) { - if (!stream) return kInvalidArg; - { - std::lock_guard lock(stream->dsp->mutex); - --stream->dsp->active; - } - delete stream; - return S_OK; -} - -// Completes the command at once: its output block is silence. -HRESULT __stdcall XDspSubmitCommand(Stream* stream, const Command* command, uint32_t* ticket) { - if (!stream || !command) return kInvalidArg; - // The title's output buffer holds one block of the stream. - if (command->output) std::memset(command->output, 0, size_t{stream->frames} * stream->channels * sizeof(float)); - // The status block is read by title code on other threads: the result before the completed ticket. - Status& status = stream->status; - const uint32_t next = status.submitted + 1; - std::atomic_ref(status.submitted).store(next, std::memory_order_release); - std::atomic_ref(status.result).store(S_OK, std::memory_order_release); - std::atomic_ref(status.completed).store(next, std::memory_order_release); - if (ticket) *ticket = next; - return S_OK; -} - -} // namespace - -SHIM_TABLE(chad_dsp, - {"chad.dll", "XDspActivate", reinterpret_cast(&XDspActivate)}, - {"chad.dll", "XDspConnectWithMaximumStreamLimit", reinterpret_cast(&XDspConnectWithMaximumStreamLimit)}, - {"chad.dll", "XDspDeactivate", reinterpret_cast(&XDspDeactivate)}, - {"chad.dll", "XDspDisconnect", reinterpret_cast(&XDspDisconnect)}, - {"chad.dll", "XDspSubmitCommand", reinterpret_cast(&XDspSubmitCommand)}, -); diff --git a/runtime/shims/d3d12_xs.cpp b/runtime/shims/d3d12_xs.cpp index 2102f5dab..a6c7934e4 100644 --- a/runtime/shims/d3d12_xs.cpp +++ b/runtime/shims/d3d12_xs.cpp @@ -19,9 +19,6 @@ #ifdef LEONIDA_VULKAN_DEVICE #include "d3d12_com.h" -#include "xbox_display.h" -#include "xbox_window.h" -#include "../src/pipeline_queue.h" #endif #include "d3d12_trace.h" #include "d3d12_xs_device.h" @@ -223,16 +220,6 @@ HRESULT WINAPI D3D12XboxCreateDevice(IUnknown* adapter, const void* params, cons return result(method, vhr); } rt::d3d12::set_device_outer(vulkan, static_cast(*out)); - // A title (its device created as ID3D12Device11, the console layouts): the console's DXGI adapter and output, - // whose display mode it reads (xbox_display.h), and PresentX in a window (xbox_window.h). - if (rt::d3d12_xs::device_proxy_console_layout(*out)) { - rt::d3d12_xs::set_device_adapter_provider(*out, &rt::d3d12::console_adapter_provider); - rt::d3d12::attach_title_presentation(*out); - // Pipelines (src/pipeline_queue.h): a bind's wait is bounded from now on, before the frame clock's first - // frame too (VIctory's frame 0); the translator's index is read while the title sets up. - leonida::pipelines::title_running().store(true, std::memory_order_relaxed); - rt::d3d12::prefetch_shader_library(vulkan); - } if (!tracing) std::fprintf(stderr, "[rt] d3d12_xs: D3D12XboxCreateDevice -> proxy %p (Vulkan device %p)\n", *out, static_cast(vulkan)); @@ -271,46 +258,12 @@ static_assert(std::is_same_v); // Measured call (RT-5, 1.0.2.1): the title calls it once at startup with one pointer to a zeroed 32-byte block whose -// dword at +4 it sets (a count), and checks the result for failure. The PC/Vulkan side owns virtual memory, so the -// inputs are only logged. The block's second half is an output, the range graphics addresses fall in (ported from -// VIctory, victory-gpu device.rs:184-226, GPL-3.0-or-later): GPU addresses are the title's CPU addresses here (title -// memory is mapped at the address the title gave it), so the range is all of user space, as VIctory answers. A null -// block is E_INVALIDARG, as there. -HRESULT WINAPI configure_virtual_memory(void* desc) { - auto* config = static_cast(desc); - if (!config) return E_INVALIDARG; - static std::atomic logged{false}; - if (!logged.exchange(true, std::memory_order_relaxed)) - std::fprintf(stderr, - "[rt] d3d12_xs: D3D12ConfigureVirtualMemoryX flags 0x%x, page table %u x 4 MiB pages, %u bytes " - "preserved\n", - config->flags, config->page_table_pages, config->preserved_bytes); - rt::d3d12_xs::user_address_range(config->lowest, config->highest); - return S_OK; -} - -// The interface id a title imports as data (d3d12_xs.dll!IID_ID3D12Device): it reads the 16 bytes at the import's -// address. The PC id, as on the console (VIctory victory-hle d3d12x.rs:80-84 binds the same import to its id). -const GUID kIidD3D12Device = __uuidof(ID3D12Device); +// dword at +4 it sets (a count), and only checks the result for failure. The PC/Vulkan side owns virtual memory, +// so the policy is accepted and ignored. +HRESULT WINAPI configure_virtual_memory(void* /*desc*/) { return S_OK; } } // namespace -namespace rt::d3d12_xs { - -void user_address_range(std::uint64_t& lowest, std::uint64_t& highest) { -#ifdef _WIN32 - SYSTEM_INFO info{}; - GetSystemInfo(&info); - lowest = reinterpret_cast(info.lpMinimumApplicationAddress); - highest = reinterpret_cast(info.lpMaximumApplicationAddress); -#else - lowest = 0x10000; // V device.rs:224: the x64 user half below the last 64 KiB - highest = 0x7ffffffeffffull; -#endif -} - -} // namespace rt::d3d12_xs - SHIM_TABLE(d3d12_xs, {"d3d12_xs.dll", "D3D12SerializeVersionedRootSignature", reinterpret_cast(&serialize_root_signature)}, {"d3d12_xs.dll", "D3D12SerializeRootSignature", reinterpret_cast(&serialize_root_signature_legacy)}, @@ -321,6 +274,4 @@ SHIM_TABLE(d3d12_xs, {"d3d12_xs.dll", "#7", reinterpret_cast(&create_versioned_root_signature_deserializer)}, {"d3d12_xs.dll", "D3D12XboxCreateDevice", reinterpret_cast(&D3D12XboxCreateDevice)}, {"d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX", reinterpret_cast(&configure_virtual_memory)}, - // A data import: the entry is the address of the id, not of a function. - {"d3d12_xs.dll", "IID_ID3D12Device", const_cast(&kIidD3D12Device)}, ); diff --git a/runtime/shims/d3d12_xs_slots.h b/runtime/shims/d3d12_xs_slots.h deleted file mode 100644 index 7186cdc47..000000000 --- a/runtime/shims/d3d12_xs_slots.h +++ /dev/null @@ -1,416 +0,0 @@ -// Console D3D12 slot tables for the Xbox-ABI proxies (d3d12_xs_device.cpp): which method every vtable slot of the -// device, the command queue, the command list and the fence is, as data. A slot is the absolute vtable index (x64, -// 8 bytes each, QueryInterface = 0); the byte offset a title calls through is slot * 8. -// -// Sources, cited per block: -// V = victory/crates/victory-gpu/src/, which runs the title on host D3D12: device.rs:402-458, queue.rs:957-1001, -// list.rs:1378-1387 and 2055-2173, fence.rs:141-154. Its tables are what the title was seen to call. -// L = Leonida's own measurements: docs/d3d12_command_objects.md (the package's BVH builder and FSR DLL, compiled -// against the same console headers) and docs/retail_boot_chain.md (the title under gta6rt). -// Where the two disagree, the table follows the one with evidence from the title and says so. -// -// The layout switch (V device.rs:149-168): a title that creates its device as ID3D12Device11 gets the newer console -// layouts. In them every queue slot from 14 and every list slot from 59 is two later (V queue.rs:978-987, -// list.rs:2127-2136), and the list has three methods the older layout lacks (V list.rs:2138-2148). The device's own -// table does not change with the layout (V device.rs:402-458 is one table). -#pragma once - -#include - -namespace rt::d3d12_xs::slots { - -enum class Layout : std::uint8_t { - // Not a console layout: the device keeps forwarding in PC order past its measured slots, queues and fences forward - // the public chain in PC order, and device slot 12 hands out the PC list. A device created as any interface other - // than ID3D12Device11 gets it: Leonida's own tests and fixtures drive the proxies through the PC C++ interfaces. - // VIctory's older console layout (V's FUNCTIONS tables, Minecraft 2022) is not modelled; no title here uses it. - pc, - // The newer console layouts (V device.rs:149-168, NEWER_FUNCTIONS): the device was created as ID3D12Device11. - console, -}; - -// ---- Device ---------------------------------------------------------------------------------------------------- - -enum class DeviceMethod : std::uint8_t { - forward, // the PC method at the same slot (refused when the real device's table is shorter) - refuse, // E_NOTIMPL, logged once with the first argument words: no source names the slot - open, // E_NOTIMPL, logged once: a console method the proxy does not implement yet - ignore, // accepted and ignored: S_OK - query_interface, - add_ref, - release, - create_queue, // 8: a queue proxy - create_allocator, // 9: an allocator proxy - create_list, // 12: the PC list (pc layout) or a console list proxy (console layout) - create_heap, // 14: a descriptor-heap proxy - struct_return, // 25, 26, 108: the PC method; the title passes the return buffer first (resolved per call) - unwrap, // the PC method, with heap/queue/fence/allocator proxies replaced by their real objects - open_shared_handle, // 32: a fence comes back wrapped - create_fence, // 36: a fence proxy - routed, // 48, 73, 78-81: the Xbox routes, movable with LEONIDA_XS_*_SLOT - create_queue1, // 75 in the pc layout: PC ID3D12Device9::CreateCommandQueue1 - unknown_pipeline, // 57: refused with the output nulled (V device.rs:349-400) - compute_pso_x, // 62 - native_compute_pso, // 67 - committed_resource_x, // 76 - register_page_pool, // 74 in the console layout - unregister_page_pool, // 75 in the console layout - committed_resource3, // 127 - placed_resource_x, // 133 - placed_view, // 70, 71: a view of title memory (rt::d3d12_xs::set_placed_view_handler) - sampler_x, // 61: the console's sampler description (rt::d3d12_xs::set_sampler_x_handler) - stream_pso, // 86 in the console layout: PC CreatePipelineState with the console's stream renumbered - feature_support, // 13 in the console layout: the console's OPTIONS layout and feature level 12_2 (V device.rs) -}; - -struct DeviceSlot { - DeviceMethod pc; // the method in the pc layout - DeviceMethod console; // the method in the console layout - const char* name; // null when no source names the slot -}; - -inline constexpr unsigned kDeviceSlots = 192; // the proxy's table; the title calls slot 133 (L retail_boot_chain §3.4) - -struct DeviceEntry { - std::uint8_t slot; - DeviceMethod pc, console; - const char* name; -}; - -// The named slots. Every other slot is forward in the pc layout; in the console layout it is forward below 44 and -// refused from 44 on. The console device keeps the PC ID3D12Device order through slot 43 and has its own methods -// after it (V device.rs:1-6 and 402-405: 76 base device methods, slots 7-82, then ID3D12Device1-8's at 83-116; L -// retail_boot_chain §3.2-3.4 measured 48, 73, 78, 79 and 133 as console methods where the PC has others). So a -// console slot from 44 on that no source names is refused, not sent to the PC method that happens to be there. -inline constexpr DeviceEntry kDeviceEntries[] = { - {0, DeviceMethod::query_interface, DeviceMethod::query_interface, "QueryInterface"}, - {1, DeviceMethod::add_ref, DeviceMethod::add_ref, "AddRef"}, - {2, DeviceMethod::release, DeviceMethod::release, "Release"}, - {7, DeviceMethod::forward, DeviceMethod::forward, "GetNodeCount"}, - {8, DeviceMethod::create_queue, DeviceMethod::create_queue, "CreateCommandQueue -> queue proxy"}, - {9, DeviceMethod::create_allocator, DeviceMethod::create_allocator, "CreateCommandAllocator -> allocator proxy"}, - {10, DeviceMethod::forward, DeviceMethod::forward, "CreateGraphicsPipelineState"}, - {11, DeviceMethod::forward, DeviceMethod::forward, "CreateComputePipelineState"}, - // V device.rs:413 and list.rs:566: the list has the console layout (L: the PC list in the pc layout). - {12, DeviceMethod::create_list, DeviceMethod::create_list, "CreateCommandList"}, - // V device.rs:240-347: the console's OPTIONS query is 16 words (one console-only field at index 11, after PC's - // StandardSwizzle64KBSupported), and the hardware is feature level 12_2. Other features are the PC method's. - {13, DeviceMethod::forward, DeviceMethod::feature_support, "CheckFeatureSupport"}, - {14, DeviceMethod::create_heap, DeviceMethod::create_heap, "CreateDescriptorHeap -> heap proxy"}, - {15, DeviceMethod::forward, DeviceMethod::forward, "GetDescriptorHandleIncrementSize"}, - {16, DeviceMethod::forward, DeviceMethod::forward, "CreateRootSignature"}, - {17, DeviceMethod::forward, DeviceMethod::forward, "CreateConstantBufferView"}, - {18, DeviceMethod::forward, DeviceMethod::forward, "CreateShaderResourceView"}, - {19, DeviceMethod::forward, DeviceMethod::forward, "CreateUnorderedAccessView"}, - {20, DeviceMethod::forward, DeviceMethod::forward, "CreateRenderTargetView"}, - {21, DeviceMethod::forward, DeviceMethod::forward, "CreateDepthStencilView"}, - {22, DeviceMethod::forward, DeviceMethod::forward, "CreateSampler"}, - {23, DeviceMethod::forward, DeviceMethod::forward, "CopyDescriptors"}, - {24, DeviceMethod::forward, DeviceMethod::forward, "CopyDescriptorsSimple"}, - // Struct returns take the return buffer first: V resource.rs:802-811 (25) and 2583-2593 (26); L retail_boot_chain - // §3.1 measured 26. The thunk tells the two orders apart, so a PC-order caller still works. - {25, DeviceMethod::struct_return, DeviceMethod::struct_return, "GetResourceAllocationInfo (return buffer first)"}, - {26, DeviceMethod::struct_return, DeviceMethod::struct_return, "GetCustomHeapProperties (return buffer first)"}, - {27, DeviceMethod::forward, DeviceMethod::forward, "CreateCommittedResource"}, - {28, DeviceMethod::forward, DeviceMethod::forward, "CreateHeap"}, - {29, DeviceMethod::forward, DeviceMethod::forward, "CreatePlacedResource"}, - {30, DeviceMethod::forward, DeviceMethod::forward, "CreateReservedResource"}, - {31, DeviceMethod::unwrap, DeviceMethod::unwrap, "CreateSharedHandle (proxies unwrapped)"}, - {32, DeviceMethod::open_shared_handle, DeviceMethod::open_shared_handle, - "OpenSharedHandle (a fence comes back wrapped)"}, - {34, DeviceMethod::unwrap, DeviceMethod::unwrap, "MakeResident (proxies unwrapped)"}, - {35, DeviceMethod::unwrap, DeviceMethod::unwrap, "Evict (proxies unwrapped)"}, - {36, DeviceMethod::create_fence, DeviceMethod::create_fence, "CreateFence -> fence proxy"}, - {38, DeviceMethod::forward, DeviceMethod::forward, "GetCopyableFootprints"}, - {39, DeviceMethod::forward, DeviceMethod::forward, "CreateQueryHeap"}, - {41, DeviceMethod::forward, DeviceMethod::forward, "CreateCommandSignature"}, - {43, DeviceMethod::forward, DeviceMethod::forward, "GetAdapterLuid"}, - // PC ID3D12Device1/3 methods in the pc layout. On the console these slots are console methods nobody has named - // (V device.rs:402-405; the PC ones would be at 84, 85 and 89). - {45, DeviceMethod::unwrap, DeviceMethod::refuse, "SetEventOnMultipleFenceCompletion (pc layout)"}, - {46, DeviceMethod::unwrap, DeviceMethod::refuse, "SetResidencyPriority (pc layout)"}, - {48, DeviceMethod::routed, DeviceMethod::routed, "Xbox CreateCommandQueueX -> queue proxy"}, - {50, DeviceMethod::unwrap, DeviceMethod::refuse, "EnqueueMakeResident (pc layout)"}, - {57, DeviceMethod::forward, DeviceMethod::unknown_pipeline, - "Xbox pipeline creation (V device.rs:438, not written)"}, - // V device.rs:439, descriptor.rs:828-832, sampler.rs: (27-word console sampler description, handle), no result. - {61, DeviceMethod::forward, DeviceMethod::sampler_x, "Xbox CreateSamplerX (V device.rs:439)"}, - {62, DeviceMethod::compute_pso_x, DeviceMethod::compute_pso_x, "Xbox CreateComputePipelineState"}, - // V device.rs:441 does not implement 67 (same call shape, an unknown pipeline); L §3.5a measured it in the FSR DLL. - {67, DeviceMethod::native_compute_pso, DeviceMethod::native_compute_pso, "Xbox DeserializeComputePipelineStateX"}, - {69, DeviceMethod::forward, DeviceMethod::ignore, "Xbox debug error filter (V device.rs:442, ignored)"}, - // V device.rs:443-444, descriptor.rs:795-818: (resource desc, view desc, handle), no result. - {70, DeviceMethod::forward, DeviceMethod::placed_view, "Xbox placed SRV over title memory (V device.rs:443)"}, - {71, DeviceMethod::forward, DeviceMethod::placed_view, "Xbox placed UAV over title memory (V device.rs:444)"}, - {73, DeviceMethod::routed, DeviceMethod::routed, "Xbox CreateCommandListX -> console list proxy"}, - {74, DeviceMethod::forward, DeviceMethod::register_page_pool, "Xbox RegisterPagePoolX (V resource.rs:2196-2212)"}, - {75, DeviceMethod::create_queue1, DeviceMethod::unregister_page_pool, - "CreateCommandQueue1 (pc layout) / Xbox UnregisterPagePoolX (V resource.rs:2214-2223)"}, - {76, DeviceMethod::committed_resource_x, DeviceMethod::committed_resource_x, "Xbox CreateCommittedResourceX"}, - {78, DeviceMethod::routed, DeviceMethod::routed, "Xbox SetFrameIntervalX"}, - {79, DeviceMethod::routed, DeviceMethod::routed, "Xbox ScheduleFrameEventX"}, - {80, DeviceMethod::routed, DeviceMethod::routed, "Xbox WaitFrameEventX"}, - {81, DeviceMethod::routed, DeviceMethod::routed, "Xbox GetFrameStatisticsX"}, - // V device.rs:454 (f[86] = pipeline::create_stream), pipeline.rs:671-758: (stream desc, riid, out). - {86, DeviceMethod::forward, DeviceMethod::stream_pso, "Xbox CreatePipelineState from streams -> PC CreatePipelineState"}, - // V resource.rs:840-849: ID3D12Device8's GetResourceAllocationInfo2 (PC slot 68), return buffer first. - {108, DeviceMethod::struct_return, DeviceMethod::struct_return, "GetResourceAllocationInfo2 (return buffer first)"}, - {127, DeviceMethod::committed_resource3, DeviceMethod::committed_resource3, "Xbox CreateCommittedResource3"}, - {133, DeviceMethod::placed_resource_x, DeviceMethod::placed_resource_x, "Xbox CreatePlacedResourceX"}, -}; - -constexpr DeviceSlot device_slot(unsigned slot) { - for (const DeviceEntry& e : kDeviceEntries) - if (e.slot == slot) return {e.pc, e.console, e.name}; - return {DeviceMethod::forward, slot < 44 ? DeviceMethod::forward : DeviceMethod::refuse, nullptr}; -} - -// ---- Command queue (console layout) ---------------------------------------------------------------------------- - -enum class QueueMethod : std::uint8_t { - refuse, // E_NOTIMPL, logged once with the first argument words: no source names the slot - open, // E_NOTIMPL, logged once: a console method the proxy does not implement yet - forward, // the PC method at `pc` - execute, // the PC ExecuteCommandLists with list proxies unwrapped (ExecuteCommandLists, ExecuteX) - marker, // ignored: V queue.rs:611-612 ("markers and events only matter to profilers") - signal, // the PC Signal with the fence unwrapped, and the fence's value word kept up to date (Signal, Signal2X) - wait, // the PC Wait with the fence unwrapped - get_desc, // the PC GetDesc; the return buffer may come first (resolved per call) - present, // PresentX: the device's present handler, or accepted (V queue.rs:757-841 always answers S_OK) - page_mappings, // CopyPageMappingsBatchX: the page mapper (rt::d3d12_xs::set_page_mapper) - accept, // S_OK, nothing done -}; - -struct QueueSlot { - QueueMethod method; - std::uint8_t pc; // the PC slot for forward, execute, signal, wait and get_desc - const char* name; // null when no source names the slot -}; - -// The proxy's queue table (the console layout's last known slot is 35; the rest is the refused tail). -inline constexpr unsigned kQueueSlots = 128; - -struct QueueEntry { - std::uint8_t older_slot; // the older layout's slot, as V lists it - QueueMethod method; - std::uint8_t pc; - const char* name; -}; - -// V queue.rs:957-976 (METHODS), in the older layout. QueryInterface, AddRef, Release and GetDevice are the proxy's own. -inline constexpr QueueEntry kQueueEntries[] = { - {3, QueueMethod::forward, 3, "GetPrivateData"}, - {4, QueueMethod::forward, 4, "SetPrivateData"}, - {5, QueueMethod::forward, 5, "SetPrivateDataInterface"}, - {6, QueueMethod::forward, 6, "SetName"}, - {10, QueueMethod::execute, 10, "ExecuteCommandLists"}, - {11, QueueMethod::marker, 0, "SetMarker"}, - {12, QueueMethod::marker, 0, "BeginEvent"}, - {13, QueueMethod::marker, 0, "EndEvent"}, - {14, QueueMethod::signal, 14, "Signal"}, - {15, QueueMethod::wait, 15, "Wait"}, - {16, QueueMethod::forward, 16, "GetTimestampFrequency"}, - // V queue.rs:998: suspend and resume at 0xb8/0xc0 in the newer layout (V leaves them E_NOTIMPL). Nothing here - // suspends a title, so there is no queue state to stop or bring back: accepted. - {21, QueueMethod::accept, 0, "SuspendX"}, - {22, QueueMethod::accept, 0, "ResumeX"}, - {26, QueueMethod::get_desc, 18, "GetDesc"}, - {29, QueueMethod::page_mappings, 0, "CopyPageMappingsBatchX"}, // V queue.rs:897-962 - {30, QueueMethod::present, 0, "PresentX"}, - {32, QueueMethod::signal, 14, "Signal2X"}, // V queue.rs:600-610: signals at once, the sync settings unused - {33, QueueMethod::execute, 10, "ExecuteX"}, // V queue.rs:595-599: the frame token and flags unused -}; - -// V queue.rs:978-987: in the newer layout every slot from 14 (0x70) on is two later. -constexpr unsigned newer_queue_slot(unsigned older) { return older >= 14 ? older + 2 : older; } - -constexpr QueueSlot console_queue_slot(unsigned slot) { - for (const QueueEntry& e : kQueueEntries) - if (newer_queue_slot(e.older_slot) == slot) return {e.method, e.pc, e.name}; - return {QueueMethod::refuse, 0, nullptr}; -} - -// ---- Command list (console layout; every list proxy has it) ---------------------------------------------------- - -enum class ListMethod : std::uint8_t { - unknown, // no source names the slot: returns 0, logged once with the first argument words - open, // a console method not written yet: returns 0 (no memory from 148), logged once - ignore, // accepted, nothing recorded: V's no-ops (hints, syncs, markers) - forward, // the PC method at `pc` - reset, // the PC Reset at `pc`: the allocator proxy unwrapped and the inline cursor pinned again - heaps, // the PC SetDescriptorHeaps at `pc` with heap proxies unwrapped - typed, // the PC method at `pc` through a thunk with the real prototype: the method takes floats in XMM - // registers, which a forwarding thunk declared with integer words does not keep - // Methods on title addresses (rt::d3d12_xs::set_list_title_handlers), and the ones the proxy does itself. - copy_memory, // CopyMemoryToMemoryX(dst, src, size, flags) - write32, // Write32(address, value, flush, flags) - write64, // Write64(address, value, flush, flags) - wait32, // WaitValue32(address, comparison, reference): recorded for the queue - wait64, // WaitValue64 - dispatch_mesh_x, // DispatchMeshX(x, flags, indirect, payload): the PC DispatchMesh at `pc` when not indirect - allocate_upload, // AllocateUploadMemory(size, alignment) -> pointer -}; - -struct ListSlot { - ListMethod method; - std::uint8_t pc; // the PC slot for forward, reset, heaps and typed - const char* name; // null when no source names the slot -}; - -inline constexpr unsigned kListSlots = 160; - -struct ListEntry { - std::uint8_t slot; - bool older; // the slot as V lists it in the older layout (newer_list_slot applies); else a newer-layout slot - ListMethod method; - std::uint8_t pc; - const char* name; -}; - -// V list.rs:2134-2136: in the newer layout every slot from 59 (0x1d8) on is two later. -constexpr unsigned newer_list_slot(unsigned older) { return older >= 59 ? older + 2 : older; } - -inline constexpr ListEntry kListEntries[] = { - // PC order up to ResourceBarrier: V list.rs:2059-2079 names 7-26 but 11 and 18, L §3.3/§3.5a measured 14, 15, 25 - // and 26. ClearState (11) and CopyTiles (18) sit inside that run, so they keep their PC slots too. - {3, false, ListMethod::forward, 3, "GetPrivateData"}, - {4, false, ListMethod::forward, 4, "SetPrivateData"}, - {5, false, ListMethod::forward, 5, "SetPrivateDataInterface"}, - {6, false, ListMethod::forward, 6, "SetName"}, - {8, false, ListMethod::forward, 8, "GetType"}, - {9, false, ListMethod::forward, 9, "Close"}, - {10, false, ListMethod::reset, 10, "Reset"}, - {11, false, ListMethod::forward, 11, "ClearState"}, - {12, false, ListMethod::forward, 12, "DrawInstanced"}, - {13, false, ListMethod::forward, 13, "DrawIndexedInstanced"}, - {14, false, ListMethod::forward, 14, "Dispatch"}, - {15, false, ListMethod::forward, 15, "CopyBufferRegion"}, - {16, false, ListMethod::forward, 16, "CopyTextureRegion"}, - {17, false, ListMethod::forward, 17, "CopyResource"}, - {18, false, ListMethod::forward, 18, "CopyTiles"}, - {19, false, ListMethod::forward, 19, "ResolveSubresource"}, - {20, false, ListMethod::forward, 20, "IASetPrimitiveTopology"}, - {21, false, ListMethod::forward, 21, "RSSetViewports"}, - {22, false, ListMethod::forward, 22, "RSSetScissorRects"}, - {23, false, ListMethod::forward, 23, "OMSetBlendFactor"}, - {24, false, ListMethod::forward, 24, "OMSetStencilRef"}, - {25, false, ListMethod::forward, 25, "SetPipelineState"}, - {26, false, ListMethod::forward, 26, "ResourceBarrier"}, - // Queries right after the barrier: V list.rs:2114-2117 (PC 52-54). The +4 rule this table replaces sent 56-58 - // there instead. - {28, false, ListMethod::forward, 52, "BeginQuery"}, - {29, false, ListMethod::forward, 53, "EndQuery"}, - {30, false, ListMethod::forward, 54, "ResolveQueryData"}, - // PC 28-51 four slots later: V list.rs:2080-2099 names 32-48 and 50-52; L §3.3, §3.3a and §3.5a measured 32, - // 33, 35, 37, 39, 41, 43, 45 and 53-55. SOSetTargets (49) sits inside that run. - {32, false, ListMethod::heaps, 28, "SetDescriptorHeaps"}, - {33, false, ListMethod::forward, 29, "SetComputeRootSignature"}, - {34, false, ListMethod::forward, 30, "SetGraphicsRootSignature"}, - {35, false, ListMethod::forward, 31, "SetComputeRootDescriptorTable"}, - {36, false, ListMethod::forward, 32, "SetGraphicsRootDescriptorTable"}, - {37, false, ListMethod::forward, 33, "SetComputeRoot32BitConstant"}, - {38, false, ListMethod::forward, 34, "SetGraphicsRoot32BitConstant"}, - {39, false, ListMethod::forward, 35, "SetComputeRoot32BitConstants"}, - {40, false, ListMethod::forward, 36, "SetGraphicsRoot32BitConstants"}, - {41, false, ListMethod::forward, 37, "SetComputeRootConstantBufferView"}, - {42, false, ListMethod::forward, 38, "SetGraphicsRootConstantBufferView"}, - {43, false, ListMethod::forward, 39, "SetComputeRootShaderResourceView"}, - {44, false, ListMethod::forward, 40, "SetGraphicsRootShaderResourceView"}, - {45, false, ListMethod::forward, 41, "SetComputeRootUnorderedAccessView"}, - {46, false, ListMethod::forward, 42, "SetGraphicsRootUnorderedAccessView"}, - {47, false, ListMethod::forward, 43, "IASetIndexBuffer"}, - {48, false, ListMethod::forward, 44, "IASetVertexBuffers"}, - {49, false, ListMethod::forward, 45, "SOSetTargets"}, - {50, false, ListMethod::forward, 46, "OMSetRenderTargets"}, - {51, false, ListMethod::typed, 47, "ClearDepthStencilView"}, // its depth is a float (XMM3) - {52, false, ListMethod::forward, 48, "ClearRenderTargetView"}, - {53, false, ListMethod::forward, 49, "ClearUnorderedAccessViewUint"}, - {54, false, ListMethod::forward, 50, "ClearUnorderedAccessViewFloat"}, - {55, false, ListMethod::forward, 51, "DiscardResource"}, - // L §3.5a (docs/d3d12_command_objects.md:565): a console GPU-event marker, (bool, blob, size). Not a PC method. - {59, false, ListMethod::ignore, 0, "GPU event marker (console)"}, - // V list.rs:2100-2111, older layout. - {59, true, ListMethod::forward, 59, "ExecuteIndirect"}, - {60, true, ListMethod::copy_memory, 0, "CopyMemoryToMemoryX"}, // V list.rs:1294-1314 - {68, true, ListMethod::typed, 62, "OMSetDepthBounds"}, // two floats (XMM1, XMM2) - {69, true, ListMethod::write32, 0, "Write32 (bottom-of-pipe value)"}, // V list.rs:1964-1983; L §3.3a slot 71 - {70, true, ListMethod::write64, 0, "Write64 (bottom-of-pipe value or timestamp)"}, - {71, true, ListMethod::wait32, 0, "WaitValue32 (wait for a memory value)"}, // V list.rs:1891-1934; L §3.3a slot 73 - {72, true, ListMethod::wait64, 0, "WaitValue64"}, - {73, true, ListMethod::ignore, 0, "pixel shader depth order hint"}, - {78, true, ListMethod::forward, 14, "DispatchX"}, // V list.rs:1321-1328: (x, y, z, flags); L §3.3a slot 80 - {83, true, ListMethod::forward, 16, "CopyTextureRegionX"}, // V list.rs:1113-1124: a trailing flags word - {84, true, ListMethod::forward, 17, "CopyResourceX"}, // V list.rs:887-889: a trailing flags word - {98, true, ListMethod::dispatch_mesh_x, 79, "DispatchMeshX"}, // V list.rs:1596-1613: indirect ones dropped - {99, true, ListMethod::ignore, 0, "DriverHintX"}, // V list.rs:1316-1319: returns 0 - {124, true, ListMethod::ignore, 0, "shading rate hint"}, - {127, true, ListMethod::forward, 79, "DispatchMesh"}, - {129, true, ListMethod::ignore, 0, "pipeline sync, top of pipe"}, // V list.rs:1397-1401 - {130, true, ListMethod::ignore, 0, "pipeline sync, bottom of pipe"}, - {137, true, ListMethod::reset, 10, "ResetX"}, // V list.rs:1403-1407: a trailing flags word; asserts on failure - // Newer layout only: V list.rs:2138-2148, L §3.3a (146, 148) and §3.5a (141). - {141, false, ListMethod::open, 0, "compute scratch binding (FSR DLL)"}, - {142, false, ListMethod::ignore, 0, "state flush word"}, - {146, false, ListMethod::forward, 80, "Barrier"}, - {148, false, ListMethod::allocate_upload, 0, "AllocateUploadMemory"}, // V list.rs:1409-1431 -}; - -constexpr ListSlot console_list_slot(unsigned slot) { - for (const ListEntry& e : kListEntries) - if ((e.older ? newer_list_slot(e.slot) : e.slot) == slot) return {e.method, e.pc, e.name}; - return {ListMethod::unknown, 0, nullptr}; -} - -// ---- Fence and command allocator ------------------------------------------------------------------------------- - -// V fence.rs:141-154: IUnknown 3, object 4, device child 1, fence 3, Fence1 1, then the console's own: slot 12 hands -// out the address of the fence's 64-bit value, which titles read straight from memory (fence.rs:24-29, 136-139). -inline constexpr unsigned kFenceValueAddressSlot = 12; -// V list.rs:1378-1387: allocator slot 9 is an allocation callback, accepted and ignored. -inline constexpr unsigned kAllocatorCallbackSlot = 9; - -// ---- Checks on the data ---------------------------------------------------------------------------------------- - -namespace detail { -// No two entries of a table name the same slot, and every slot fits the proxy's table. -constexpr bool device_entries_ok() { - for (const DeviceEntry& a : kDeviceEntries) { - if (a.slot >= kDeviceSlots) return false; - unsigned seen = 0; - for (const DeviceEntry& b : kDeviceEntries) seen += a.slot == b.slot; - if (seen != 1) return false; - } - return true; -} -constexpr bool queue_entries_ok() { - for (const QueueEntry& a : kQueueEntries) { - if (newer_queue_slot(a.older_slot) >= kQueueSlots) return false; - unsigned seen = 0; - for (const QueueEntry& b : kQueueEntries) - seen += newer_queue_slot(a.older_slot) == newer_queue_slot(b.older_slot); - if (seen != 1) return false; - } - return true; -} -constexpr unsigned list_entry_slot(const ListEntry& e) { return e.older ? newer_list_slot(e.slot) : e.slot; } -constexpr bool list_entries_ok() { - for (const ListEntry& a : kListEntries) { - if (list_entry_slot(a) >= kListSlots) return false; - unsigned seen = 0; - for (const ListEntry& b : kListEntries) seen += list_entry_slot(a) == list_entry_slot(b); - if (seen != 1) return false; - } - return true; -} -} // namespace detail -static_assert(detail::device_entries_ok(), "kDeviceEntries: a slot twice or past the table"); -static_assert(detail::queue_entries_ok(), "kQueueEntries: a slot twice or past the table"); -static_assert(detail::list_entries_ok(), "kListEntries: a slot twice or past the table"); -// The anchors the port plan names (docs/port_plan.md step 2): the title's Signal, ExecuteIndirect and Barrier. -static_assert(console_queue_slot(16).method == QueueMethod::signal && console_queue_slot(16).pc == 14); -static_assert(console_queue_slot(32).method == QueueMethod::present && console_queue_slot(35).pc == 10); -static_assert(console_list_slot(61).pc == 59 && console_list_slot(146).pc == 80 && console_list_slot(139).pc == 10); -static_assert(console_list_slot(59).method == ListMethod::ignore && - console_list_slot(56).method == ListMethod::unknown); - -} // namespace rt::d3d12_xs::slots diff --git a/runtime/shims/dstorage_xs.cpp b/runtime/shims/dstorage_xs.cpp deleted file mode 100644 index cb99f1e46..000000000 --- a/runtime/shims/dstorage_xs.cpp +++ /dev/null @@ -1,1053 +0,0 @@ -// XCRDAPI.dll: the console's DirectStorage. Ported from VIctory's crates/victory-hle/src/modules/dstorage.rs -// (GPL-3.0-or-later; Marvisak and contributors, DexNom fork); Leonida is GPL-3.0-or-later too. -// -// A factory that opens files and creates request queues and status arrays the title polls. Its interfaces have grown -// since 2020 (new interface ids, new slots); the slots here are the ones the title calls, which VIctory read from its -// call sites (dstorage_xs.h has the layouts). A slot nobody has needed yet logs its offset once and returns E_NOTIMPL. -// -// Submitted requests of every queue run on one pool of workers, as the console's hardware runs them: in parallel, -// started in queue order, queues served by weighted round robin over their priorities (about 10x per level, counted in -// bytes), with at most the staging buffer's worth of compressed source in flight. Each request reads its source (a -// file or memory), inflates zlib data and/or unpacks BCPack data, and writes the destination (an address, or physical -// pages). Completion is what stays in order: a status entry is written once every request enqueued before it on its -// queue has finished, with the first failure (in queue order) since the previous status entry, or success. -// -// What is Leonida's here: files open through the CreateFileW a title's import binds to (shims/file_system.cpp), so -// GAME: paths read the overlay copy or the package file; zlib is leonida::zlib_inflate (src/shader_library.h); BCPack -// is leonida_bcpack_decode (src/bcpack_decode.h, a stub that fails until the decoder is ported); physical pages are -// written through xmem's own view of their section (rt::xmem::physical_span, write_physical). -// -// Diagnostics: LEONIDA_DSTORAGE_TRACE=1 prints a line for every request that fails, with its file; 2 for every request -// (two runs are compared by the list of their reads, by file and offset), plus the 5 s summaries the startup trace -// gets. LEONIDA_DSTORAGE_RETRIES (default 12) is how often a write into physical pages is tried again. -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "../src/bcpack_decode.h" -#include "../src/shader_library.h" -#include "dstorage_xs.h" -#include "shims.h" -#include "startup_trace.h" -#include "xmem.h" - -namespace rt::dstorage { -namespace detail { - -// One of our objects as title code calls it: the method table first. `area` names it in the log when the title calls -// a slot we lack. -struct Object { - const void* const* vtable; - const char* area; -}; - -// A status array: the entries the title polls, each the result of the requests before it (pending, the first -// failure, or success). -struct StatusArray { - Object base; - std::atomic refs{1}; - std::uint32_t capacity = 0; - std::unique_ptr[]> entries; -}; - -} // namespace detail - -namespace { - -using detail::Command; -using detail::Job; -using detail::Lane; -using detail::Lanes; -using detail::Object; -using detail::Status; -using detail::StatusArray; -using Clock = std::chrono::steady_clock; - -// ---- Logging - -std::string text(const char* s) { return s ? std::string(s) : std::string(); } - -std::string utf8(const wchar_t* w) { - const int n = w ? WideCharToMultiByte(CP_UTF8, 0, w, -1, nullptr, 0, nullptr, nullptr) : 0; - if (n <= 1) return {}; - std::string s(static_cast(n) - 1, '\0'); - WideCharToMultiByte(CP_UTF8, 0, w, -1, s.data(), n, nullptr, nullptr); - return s; -} - -std::string iid_text(const GUID* iid) { - if (!iid) return "null"; - char b[40]; - std::snprintf(b, sizeof b, "%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", iid->Data1, iid->Data2, iid->Data3, - iid->Data4[0], iid->Data4[1], iid->Data4[2], iid->Data4[3], iid->Data4[4], iid->Data4[5], - iid->Data4[6], iid->Data4[7]); - return b; -} - -std::string hex32(std::int32_t hr) { - char b[12]; - std::snprintf(b, sizeof b, "0x%08x", static_cast(hr)); - return b; -} - -void trace(const char* api, const std::string& fields) { - if (!rt::startup_trace::enabled()) return; - rt::startup_trace::event("dstorage", std::string("\"api\":\"") + api + "\"" + fields); -} - -// LEONIDA_DSTORAGE_TRACE: 0 or unset off; 1 a line for every request that fails, with its file; 2 for every request, -// and the 5 s summaries on stderr too. VIctory's VICTORY_WALLS_TRACE. -int request_trace_level() { - static const int level = [] { - char buf[8] = {}; - const DWORD n = GetEnvironmentVariableA("LEONIDA_DSTORAGE_TRACE", buf, sizeof buf); - return n > 0 && n < sizeof buf ? std::atoi(buf) : 0; - }(); - return level; -} - -// HRESULT_FROM_WIN32 of a host error. -std::int32_t from_win32(DWORD error) { return static_cast(0x80070000u | (error & 0xffffu)); } - -// ---- Objects - -template -ULONG __stdcall add_ref_instance(T* self) { - return self->refs.fetch_add(1, std::memory_order_relaxed) + 1; -} - -template -ULONG __stdcall release(T* self) { - const std::uint32_t left = self->refs.fetch_sub(1, std::memory_order_acq_rel) - 1; - if (left == 0) delete self; - return left; -} - -// The factory is static: its AddRef and Release count nothing. -ULONG __stdcall static_add_ref(Object*) { return 1; } - -// A slot nobody has needed yet: logged once per object kind and slot, with its byte offset. Wrong for a slot that -// returns bool or a value. -void note_missing(const char* area, unsigned offset) { - static std::mutex mutex; - static std::set> seen; - { - const std::lock_guard lock(mutex); - if (!seen.emplace(area, offset).second) return; - } - char b[24]; - std::snprintf(b, sizeof b, "0x%x", offset); - std::fprintf(stderr, "[rt] dstorage: %s method at %s not implemented (E_NOTIMPL; logged once)\n", area, b); - trace("missing", ",\"object\":" + rt::startup_trace::quote(area) + ",\"slot\":\"" + b + "\""); -} - -template -HRESULT __stdcall missing(const Object* self) { - note_missing(self ? self->area : "?", Slot * 8); - return kNotImpl; -} - -template -const void* method(F* f) { - return reinterpret_cast(f); -} - -// ---- Files - -struct File { - Object base; - std::atomic refs{1}; - HANDLE handle = INVALID_HANDLE_VALUE; - std::string path; // as the title named it, for the request trace - ~File() { - if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle); - } -}; - -const void* const kFileVtable[8] = { - method(&missing<0>), - method(&add_ref_instance), - method(&release), - method(&missing<3>), - method(&missing<4>), - method(&missing<5>), - method(&missing<6>), - method(&missing<7>), -}; - -// ---- Status arrays - -// The result of the requests before entry `index`: pending, the first failure, or success. -HRESULT __stdcall status_result(StatusArray* self, std::uint32_t index) { - if (index >= self->capacity) return kInvalidArg; - return self->entries[index].load(std::memory_order_acquire); -} - -// The title polls this (entry 0, a Sleep(1) loop) and never reads the result itself. -bool __stdcall is_complete(StatusArray* self, std::uint32_t index) { return status_result(self, index) != kPending; } - -const void* const kStatusVtable[5] = { - method(&missing<0>), - method(&add_ref_instance), - method(&release), - method(&is_complete), // 0x18 - method(&status_result), // 0x20 -}; - -// ---- The scheduler - -// Every queue's requests, run by a pool of workers. Immortal: the workers wait on it until the process ends. -struct Scheduler { - std::mutex mutex; - Lanes lanes; - // Requests to start, or staging space freed. - std::condition_variable work; - // A request finished (for full queues and close). - std::condition_variable finished; -}; - -void work(Scheduler* scheduler, unsigned index); - -// The scheduler, with its workers started on first use; null only if it could not be allocated. -Scheduler* scheduler() { - static Scheduler* const instance = new (std::nothrow) Scheduler; - static std::once_flag started; - if (!instance) return nullptr; - std::call_once(started, [] { - unsigned workers = std::thread::hardware_concurrency(); - if (workers == 0) workers = 4; - unsigned running = 0; - for (unsigned i = 0; i < workers; ++i) { - try { - std::thread(work, instance, i).detach(); - ++running; - } catch (...) { - } - } - std::fprintf(stderr, "[rt] dstorage: %u workers\n", running); - trace("workers", ",\"count\":" + std::to_string(running)); - }); - return instance; -} - -// Ends a queue: what was not started is dropped, and this waits for the reads already running (they write title -// memory). -void close_lane(std::uint64_t id) { - Scheduler* const s = scheduler(); - if (!s) return; - std::unique_lock lock(s->mutex); - const auto it = s->lanes.lanes.find(id); - if (it == s->lanes.lanes.end()) return; - Lane& lane = it->second; - lane.closed = true; - lane.unsubmitted.clear(); - lane.reads.clear(); - lane.statuses.clear(); // releases their arrays - s->finished.wait(lock, [&] { - const auto found = s->lanes.lanes.find(id); - return found == s->lanes.lanes.end() || found->second.running.empty(); - }); - s->lanes.lanes.erase(id); - s->finished.notify_all(); -} - -// A queue object: its lane in the scheduler. The last Release ends the lane, as close does. -struct Queue { - Object base; - std::atomic refs{1}; - std::uint64_t id = 0; - ~Queue() { close_lane(id); } -}; - -// Adds a command to the queue; blocks while the queue is full, and submits on its own once half of it is enqueued, as -// the console does. -void queue(Queue* self, Command command) { - Scheduler* const s = scheduler(); - if (!s) return; - std::unique_lock lock(s->mutex); - for (;;) { - const auto it = s->lanes.lanes.find(self->id); - if (it == s->lanes.lanes.end() || it->second.closed) return; // closed: dropped (a status releases its array) - // One slot stays free, as the console's count of empty slots says. - if (it->second.entries() + 1 < (std::max)(it->second.capacity, 2)) break; - s->finished.wait(lock); - } - Lane& lane = s->lanes.lanes.at(self->id); - lane.unsubmitted.push_back(std::move(command)); - if (lane.unsubmitted.size() >= (std::max)(lane.capacity / 2, 1)) { - s->lanes.submit(self->id); - s->work.notify_all(); - } -} - -void __stdcall enqueue_request(Queue* self, const Request* request) { - if (!request) return; - try { - queue(self, Command(std::in_place_type, *request)); - } catch (...) { - std::fprintf(stderr, "[rt] dstorage: a request could not be enqueued (out of memory); it never completes\n"); - } -} - -void __stdcall enqueue_status(Queue* self, StatusArray* array, std::uint32_t index) { - if (!array) return; - if (index >= array->capacity) { - std::fprintf(stderr, "[rt] dstorage: status entry %u out of range (the array holds %u)\n", index, - array->capacity); - return; - } - array->entries[index].store(kPending, std::memory_order_release); - detail::add_ref(array); - try { - queue(self, Command(std::in_place_type, array, index)); - } catch (...) { - std::fprintf(stderr, "[rt] dstorage: a status entry could not be enqueued (out of memory); it stays pending\n"); - } -} - -void __stdcall submit(Queue* self) { - Scheduler* const s = scheduler(); - if (!s) return; - const std::lock_guard lock(s->mutex); - s->lanes.submit(self->id); - s->work.notify_all(); -} - -// Ends the queue whatever its reference count: what was not started never completes, and this returns once the reads -// already running have finished. The title calls this, not Release. -void __stdcall close(Queue* self) { close_lane(self->id); } - -// Slots by the 2020 order, which the argument shapes at the title's call sites match (0x18, 0x20, 0x30 and 0x40 are -// called). -const void* const kQueueVtable[12] = { - method(&missing<0>), - method(&add_ref_instance), - method(&release), - method(&enqueue_request), // 0x18 - method(&enqueue_status), // 0x20 - method(&missing<5>), // 0x28 (2020: fence signal) - method(&submit), // 0x30 - method(&missing<7>), // 0x38 (2020: cancel by tag) - method(&close), // 0x40 - method(&missing<9>), // 0x48 (2020: error event) - method(&missing<10>), // 0x50 (2020: error record) - method(&missing<11>), // 0x58 (2020: queue info) -}; - -// ---- Running a request - -// A buffer for one stage of a request, kept for the worker's next request (up to 8 MiB) so it is not allocated and -// cleared again each time. -class Scratch { -public: - std::uint8_t* get(std::size_t n) { - if (n > size_) { - data_.reset(); - size_ = 0; - data_.reset(new std::uint8_t[n]); - size_ = n; - } - return data_.get(); - } - void trim() { - if (size_ > kKeep) { - data_.reset(); - size_ = 0; - } - } - -private: - static constexpr std::size_t kKeep = std::size_t(8) << 20; - std::unique_ptr data_; - std::size_t size_ = 0; -}; - -// A worker's buffers, owned by its loop and handed down. Not thread_local: a thread_local with a destructor makes -// gta6rt.exe's CRT register its thread-local destructor callback with the UCRT at startup -// (_register_thread_local_exe_atexit_callback), which takes one per process, and the title's CRT startup then -// registering its own (through the host's UCRT) ends the process with 0xC0000409, right after the title's static -// initializers (measured on the retail executable). -struct Buffers { - Scratch source; // a compressed source read from its file - Scratch bounce; // a raw read, before it is copied in - Scratch pages; // a destination in physical pages that are not one allocation's run - std::vector inflated; - - void trim() { - source.trim(); - bounce.trim(); - pages.trim(); - if (inflated.capacity() > (std::size_t(8) << 20)) std::vector().swap(inflated); - } -}; - -// Logs a failed request (the first 64, then at powers of two) and gives its result back. -std::int32_t fail(const Request& request, std::int32_t hr, const char* why) { - static std::atomic failures{0}; - const std::uint64_t n = failures.fetch_add(1, std::memory_order_relaxed) + 1; - if (n <= 64 || (n & (n - 1)) == 0) { - std::fprintf(stderr, - "[rt] dstorage: request failed: %s (options 0x%llx, offset %llu, source_size %u, " - "destination_size %u, intermediate_size %u, tag %llu, name \"%s\", hr %s)%s\n", - why, static_cast(request.options), - static_cast(request.offset), request.source_size, request.destination_size, - request.intermediate_size, static_cast(request.tag), - text(request.name).c_str(), hex32(hr).c_str(), - n > 64 ? " [later failures are logged at powers of two]" : ""); - } - if (n <= 256) - trace("request_failed", ",\"why\":" + rt::startup_trace::quote(why) + ",\"options\":\"" + - rt::startup_trace::hex(request.options) + "\",\"offset\":" + - std::to_string(request.offset) + ",\"hr\":\"" + hex32(hr) + "\""); - return hr; -} - -// A BCPack stage that failed: logged once per BC format. With the stub decoder every BCPack request comes here. -std::int32_t bcpack_failed(const Request& request, unsigned bc) { - static std::atomic seen{0}; - const std::uint32_t bit = 1u << (bc & 15); - if ((seen.fetch_or(bit, std::memory_order_relaxed) & bit) == 0) { - std::fprintf(stderr, - "[rt] dstorage: BCPack (BC%u) requests fail with %s: no BCPack decoder in this build, or a stream " - "it rejects (first: offset %llu, source_size %u, destination_size %u; logged once per format)\n", - bc, hex32(kInvalidData).c_str(), static_cast(request.offset), - request.source_size, request.destination_size); - trace("bcpack_failed", ",\"format\":" + std::to_string(bc)); - } - return kInvalidData; -} - -// Nanoseconds workers spent reading files, for the summary. -std::atomic g_reading{0}; - -// Fills `out` (the source size) from the request's file or memory. -std::int32_t read_into(const Request& request, std::span out) { - if (request.options & kMemorySource) { - // The title's source holds out.size() bytes until completion. - if (!out.empty()) std::memcpy(out.data(), request.source, out.size()); - return kOk; - } - const auto* file = static_cast(request.source); - if (file->base.vtable != kFileVtable) return kInvalidArg; // not a file this factory opened - const auto started = Clock::now(); - std::int32_t result = kOk; - std::size_t done = 0; - while (done < out.size()) { - const std::uint64_t at = request.offset + done; - OVERLAPPED position{}; - position.Offset = static_cast(at); - position.OffsetHigh = static_cast(at >> 32); - const DWORD want = static_cast((std::min)(out.size() - done, std::size_t(1) << 30)); - DWORD got = 0; - if (!ReadFile(file->handle, out.data() + done, want, &got, &position)) { - const DWORD error = GetLastError(); - result = error == ERROR_HANDLE_EOF ? kEndOfFile : from_win32(error); - break; - } - if (got == 0) { - result = kEndOfFile; - break; - } - done += got; - } - g_reading.fetch_add( - static_cast(std::chrono::duration_cast(Clock::now() - started).count()), - std::memory_order_relaxed); - return result; -} - -// A compressed request's source: the title's memory, or read from the file into the worker's buffer. -std::int32_t read_source(const Request& request, Buffers& buffers, std::span& source) { - const std::size_t size = request.source_size; - if (request.options & kMemorySource) { - // The title's source holds `size` bytes until completion. - source = {static_cast(request.source), size}; - return kOk; - } - std::uint8_t* const bytes = buffers.source.get(size); - const std::int32_t hr = read_into(request, {bytes, size}); - source = {bytes, size}; - return hr; -} - -// Inflates a zlib stream into the worker's buffer, at most `limit` bytes. A stream that ends short of the limit -// passes: the title's chunks fill their destination exactly, and nothing says that is required. A valid stream that is -// longer gives its first `limit` bytes; a malformed or truncated stream, or a wrong Adler-32, fails with -// ERROR_INVALID_DATA. -std::int32_t inflate(std::span source, std::size_t limit, std::vector& out) { - if (out.capacity() < limit) out.reserve(limit); - if (leonida::zlib_inflate(source, out, limit)) return kOk; - // A whole, valid stream that inflates past the destination: the title asks for its first `limit` bytes (a - // 1731-byte stream of 16384 bytes into an 8192-byte destination, the request at offset 1413311488 of - // core_restofworld after the start screen), and gets them. Inflated whole, up to 64 times the limit, and cut. - if (leonida::zlib_inflate(source, out, (std::min)(limit * 64, std::size_t(256) << 20)) && out.size() > limit) { - static std::atomic said{false}; - if (!said.exchange(true)) - std::fprintf(stderr, "[rt] dstorage: a zlib stream inflates past its destination (%zu of %zu bytes); " - "its first bytes are given (logged once)\n", limit, out.size()); - out.resize(limit); - return kOk; - } - // LEONIDA_DSTORAGE_DUMP= (diagnostic): the first 16 sources that do not inflate are written there, to - // tell a stream this inflater misreads from one the title's request misdescribes. They are the title's bytes: - // the folder stays on the player's machine. - static const std::string folder = [] { - char buf[MAX_PATH] = {}; - const DWORD n = GetEnvironmentVariableA("LEONIDA_DSTORAGE_DUMP", buf, sizeof buf); - return n && n < sizeof buf ? std::string(buf) : std::string(); - }(); - static std::atomic dumped{0}; - if (!folder.empty()) { - const unsigned n = dumped.fetch_add(1, std::memory_order_relaxed); - if (n < 16) { - const std::string path = folder + "\\zlib-" + std::to_string(n) + "-limit" + std::to_string(limit) + ".bin"; - if (FILE* f = std::fopen(path.c_str(), "wb")) { - std::fwrite(source.data(), 1, source.size(), f); - std::fclose(f); - } - } - } - return kInvalidData; -} - -// The page numbers of a destination. The title fills the array after it enqueued the request (a copy taken then holds -// zeros, or the numbers of the array's last use), so it is read when the request runs; a number that is still zero -// then is waited for, a tenth of a second at most. -std::vector filled(const std::uint64_t* array, std::size_t n) { - static std::atomic late{0}; - const auto read = [&] { - // A page number per 64 KiB of destination; the title keeps the array until the request completes and may - // write it from another thread meanwhile. - std::vector pages(n); - const volatile std::uint64_t* const numbers = array; - for (std::size_t i = 0; i < n; ++i) pages[i] = numbers[i]; - return pages; - }; - const auto has_zero = [](const std::vector& pages) { - return std::find(pages.begin(), pages.end(), std::uint64_t{0}) != pages.end(); - }; - std::vector pages = read(); - if (!has_zero(pages)) return pages; - const auto began = Clock::now(); - while (has_zero(pages) && Clock::now() - began < std::chrono::milliseconds(100)) { - Sleep(2); - pages = read(); - } - const std::uint64_t count = late.fetch_add(1, std::memory_order_relaxed) + 1; - if (count <= 8 || (count & (count - 1)) == 0) { - std::fprintf(stderr, - "[rt] dstorage: a request ran before its page array was filled (requests %llu, pages %zu, " - "waited %lld ms, filled %s)\n", - static_cast(count), n, - static_cast( - std::chrono::duration_cast(Clock::now() - began).count()), - has_zero(pages) ? "no" : "yes"); - } - return pages; -} - -// LEONIDA_DSTORAGE_RETRIES: how often a write into physical pages is tried again before its request fails. -unsigned page_retries() { - static const unsigned retries = [] { - char buf[16] = {}; - const DWORD n = GetEnvironmentVariableA("LEONIDA_DSTORAGE_RETRIES", buf, sizeof buf); - if (n == 0 || n >= sizeof buf) return 12u; - char* end = nullptr; - const unsigned long value = std::strtoul(buf, &end, 10); - return end && *end == '\0' && end != buf ? static_cast(value) : 12u; - }(); - return retries; -} - -// Runs `fill(out, produced)` on the destination's first `len` bytes; `fill` says how many it produced. Destinations -// are title memory at the title's addresses (a GPU address is the CPU address), so an address is written in place; -// physical pages are too when they are consecutive pages of one allocation, and otherwise go through a buffer. -template -std::int32_t into_destination(const Request& request, std::size_t len, Scratch& buffer, Fill&& fill) { - if (!(request.options & kPageDestination)) { - // The title's destination holds destination_size bytes, at least `len`, and nothing else writes it until - // completion. VIctory opens its GPU side's guards over it first and afterwards publishes the bytes produced; - // Leonida's D3D12 layer reads title memory where it lies, so there is nobody to tell. What stays is the check - // that the producer kept within the destination. - std::size_t produced = 0; - const std::int32_t hr = fill(std::span(static_cast(request.destination), len), - produced); - if (hr != kOk) return hr; - return produced <= len ? kOk : kInvalidData; - } - const std::size_t offset = static_cast(request.page_offset & 0xffff); - const std::vector pages = - filled(static_cast(request.destination), (offset + len + kPage - 1) / kPage); - // Consecutive pages of one allocation (the usual case): written in place through the allocation's view. - rt::xmem::PhysicalSpan span; - if (rt::xmem::physical_span(pages.data(), pages.size(), offset, len, span)) { - std::size_t produced = 0; - return fill(std::span(span.data, len), produced); - } - std::uint8_t* const data = buffer.get(len); - std::size_t n = 0; - const std::int32_t hr = fill(std::span(data, len), n); - if (hr != kOk) return hr; - n = (std::min)(n, len); - // A page the title has just made, or a commit the host refuses for a moment (commit short while a load maps many - // at once), can come right a little later: tried again before the request fails (LEONIDA_DSTORAGE_RETRIES, - // default 12, about 1.5 s in all). - bool written = rt::xmem::write_physical(pages.data(), pages.size(), offset, data, n); - unsigned tries = 0; - while (!written && tries < page_retries()) { - Sleep((std::min)(2u << (std::min)(tries, 6u), 128u)); - ++tries; - written = rt::xmem::write_physical(pages.data(), pages.size(), offset, data, n); - } - if (written) { - if (tries > 0) - std::fprintf(stderr, "[rt] dstorage: a destination's physical pages written after %u retries (offset %zu, " - "len %zu)\n", tries, offset, len); - return kOk; - } - const DWORD last_error = GetLastError(); - const bool known = rt::xmem::physical_pages_known(pages.data(), pages.size(), offset, len); - // Said aloud: the title never reads a request's result (it only polls for completion), so a destination left - // unwritten is a model or texture that silently holds whatever its pages held before. - std::fprintf(stderr, - "[rt] dstorage: a destination's physical pages could not be written (%s, last error %lu); its request " - "fails: offset %zu, len %zu, pages %zu, first 0x%llx, options 0x%llx\n", - known ? "a host failure" : "an unknown page", last_error, offset, len, pages.size(), - static_cast(pages.empty() ? 0 : pages.front()), - static_cast(request.options)); - return kInvalidArg; -} - -// Reads, inflates and/or unpacks, and writes one request. -std::int32_t execute(const Request& request, Buffers& buffers) { - const std::uint64_t options = request.options; - if (options & ~(kZlib | kBcpack | kPageDestination | kMemorySource)) - return fail(request, kNotImpl, "unsupported options"); - if (!request.source || !request.destination) return fail(request, kInvalidArg, "no source or destination"); - const unsigned bc = static_cast((options & kBcpack) >> 1); - const std::size_t size = request.destination_size; - if (!(options & (kZlib | kBcpack))) { - if (request.source_size > request.destination_size) - return fail(request, kInvalidArg, "source larger than destination"); - const std::size_t n = request.source_size; - // A file read into a title address is the kernel's write, and the kernel does not fault into a user-mode - // handler. VIctory met it with its GPU side's guard: a block guarded again between kernel_will_write and the - // read (the guard over all the views of a page protects other views from other threads) made the read fail - // with ERROR_INVALID_USER_BUFFER, and the title stops at the failed request (runs amd-C and amd-C2, seconds - // after the world's first frame). Here the same holds for xmem's physical pages, which are committed when - // first touched, by a vectored handler: a ReadFile into an untouched mapped page fails with ERROR_NOACCESS - // (Windows 11 26200; dstorage_xs_test prints what the host does). So it is read beside and copied in: our copy - // faults into the handler like the title's own writes. Physical-page destinations are committed before they - // are written, and memory sources are copied anyway. - const bool bounce = !(options & (kPageDestination | kMemorySource)); - const std::int32_t hr = into_destination(request, n, buffers.pages, [&](std::span out, - std::size_t& produced) -> std::int32_t { - produced = n; - if (!bounce) return read_into(request, out.first(n)); - std::uint8_t* const data = buffers.bounce.get(n); - const std::int32_t read = read_into(request, {data, n}); - if (read != kOk) return read; - if (n) std::memcpy(out.data(), data, n); - return kOk; - }); - return hr == kOk ? kOk : fail(request, hr, "copying"); - } - std::span source; - if (const std::int32_t hr = read_source(request, buffers, source); hr != kOk) - return fail(request, hr, "reading the source"); - std::vector& inflated = buffers.inflated; - // The console's order: zlib first, then BCPack. - if (bc != 0 && (options & kZlib)) { - if (const std::int32_t hr = inflate(source, request.intermediate_size, inflated); hr != kOk) - return fail(request, hr, "zlib"); - source = inflated; - } - return into_destination(request, size, buffers.pages, - [&](std::span out, std::size_t& produced) -> std::int32_t { - if (bc != 0) { - if (!leonida_bcpack_decode(bc, source.data(), source.size(), out.data(), out.size())) - return bcpack_failed(request, bc); - produced = out.size(); - return kOk; - } - if (const std::int32_t hr = inflate(source, out.size(), inflated); hr != kOk) return fail(request, hr, "zlib"); - if (!inflated.empty()) std::memcpy(out.data(), inflated.data(), inflated.size()); - produced = inflated.size(); - return kOk; - }); -} - -// LEONIDA_DSTORAGE_TRACE's line for a request that is done. -void trace_request(const Request& request, std::int32_t result, Clock::time_point started) { - const int level = request_trace_level(); - if (level == 0 || (level == 1 && result == kOk)) return; - std::string file = "memory"; - if (!(request.options & kMemorySource)) { - const auto* f = static_cast(request.source); - file = f && f->base.vtable == kFileVtable ? f->path : std::string("?"); - } - std::fprintf(stderr, - "[rt] dstorage: request done: file %s, offset %llu, source_size %u, destination_size %u, to_pages %d, " - "options 0x%llx, %lld ms, ok %d, hr %s\n", - file.c_str(), static_cast(request.offset), request.source_size, - request.destination_size, (request.options & kPageDestination) ? 1 : 0, - static_cast(request.options), - static_cast(std::chrono::duration_cast(Clock::now() - started).count()), - result == kOk ? 1 : 0, hex32(result).c_str()); -} - -void name_thread(unsigned index) { - using SetThreadDescriptionFn = HRESULT(WINAPI*)(HANDLE, PCWSTR); - static const auto set = reinterpret_cast( - reinterpret_cast(GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "SetThreadDescription"))); - if (!set) return; - wchar_t name[32]; - std::swprintf(name, 32, L"dstorage %u", index); - set(GetCurrentThread(), name); -} - -// A worker: runs the next read of the most deserving queue. -void work(Scheduler* s, unsigned index) { - name_thread(index); - Buffers buffers; - std::unique_lock lock(s->mutex); - for (;;) { - std::optional job = s->lanes.start(); - if (!job) { - s->work.wait(lock); - continue; - } - lock.unlock(); - const auto started = Clock::now(); - std::int32_t result; - try { - result = execute(job->request, buffers); - } catch (...) { - result = fail(job->request, kOutOfMemory, "out of memory"); - } - trace_request(job->request, result, started); - buffers.trim(); - lock.lock(); - s->lanes.finish(*job, result); - s->lanes.count(*job, started); - if (std::exchange(s->lanes.starved, false)) s->work.notify_all(); - s->finished.notify_all(); - } -} - -// ---- The factory - -using CreateFileWFn = HANDLE(WINAPI*)(LPCWSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE); - -// The CreateFileW a mapped title's import binds to (shims/file_system.cpp): GAME: (and G:, T:) paths open the -// overlay copy or the package file, as the title's own opens do, and anything else is a host path. A build without -// that shim opens host paths only. -CreateFileWFn title_create_file() { - static const CreateFileWFn fn = [] { - const auto shim = reinterpret_cast(rt::shims::find("kernel32.dll", "CreateFileW")); - return shim ? shim : &::CreateFileW; - }(); - return fn; -} - -// Opens `path` for reading; the file object owns the handle. -HRESULT __stdcall open_file(Object*, const wchar_t* path, const GUID* iid, void** out) { - if (!path) return kInvalidArg; - try { - const HANDLE handle = - title_create_file()(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); - std::string name = utf8(path); - if (handle == INVALID_HANDLE_VALUE) { - const DWORD error = GetLastError(); - std::fprintf(stderr, "[rt] dstorage: opening a file failed: %s (error %lu)\n", name.c_str(), error); - trace("open_failed", ",\"path\":" + rt::startup_trace::quote(name) + ",\"error\":" + std::to_string(error)); - return from_win32(error); - } - std::fprintf(stderr, "[rt] dstorage: file opened: %s (iid %s)\n", name.c_str(), iid_text(iid).c_str()); - trace("file_opened", ",\"path\":" + rt::startup_trace::quote(name)); - auto* file = new (std::nothrow) File; - if (!file) { - CloseHandle(handle); - return kOutOfMemory; - } - file->base = {kFileVtable, "dstorage file"}; - file->handle = handle; - file->path = std::move(name); - if (!out) { - release(file); - return kInvalidArg; - } - *out = file; - return kOk; - } catch (...) { - return kOutOfMemory; - } -} - -// (capacity, name, iid, out). Entries start complete (S_OK). -HRESULT __stdcall create_status_array(Object*, std::uint32_t capacity, const char* name, const GUID* iid, void** out) { - try { - std::fprintf(stderr, "[rt] dstorage: status array: capacity %u, name \"%s\", iid %s\n", capacity, - text(name).c_str(), iid_text(iid).c_str()); - trace("status_array", ",\"capacity\":" + std::to_string(capacity) + ",\"name\":" + - rt::startup_trace::quote(text(name))); - auto array = std::make_unique(); - array->base = {kStatusVtable, "dstorage status array"}; - array->capacity = capacity; - array->entries.reset(new std::atomic[capacity ? capacity : 1]); - for (std::uint32_t i = 0; i < capacity; ++i) array->entries[i].store(kOk, std::memory_order_relaxed); - if (!out) return kInvalidArg; - *out = array.release(); - return kOk; - } catch (...) { - return kOutOfMemory; - } -} - -HRESULT __stdcall create_queue(Object*, const QueueDesc* desc, const GUID* iid, void** out) { - if (!desc) return kInvalidArg; - try { - std::fprintf(stderr, - "[rt] dstorage: queue: source %llu, capacity %u, priority %d, name \"%s\", unknown %llu, iid %s\n", - static_cast(desc->source_type), desc->capacity, desc->priority, - text(desc->name).c_str(), static_cast(desc->unknown), iid_text(iid).c_str()); - trace("queue", ",\"source\":" + std::to_string(desc->source_type) + ",\"capacity\":" + - std::to_string(desc->capacity) + ",\"priority\":" + std::to_string(desc->priority) + - ",\"name\":" + rt::startup_trace::quote(text(desc->name))); - Scheduler* const s = scheduler(); - if (!s) return kOutOfMemory; - auto queue = std::make_unique(); // its destructor ends the lane - queue->base = {kQueueVtable, "dstorage queue"}; - { - const std::lock_guard lock(s->mutex); - queue->id = s->lanes.next_id++; - s->lanes.lanes.emplace(queue->id, Lane(desc->priority, desc->capacity)); - } - if (!out) return kInvalidArg; - *out = queue.release(); - return kOk; - } catch (...) { - return kOutOfMemory; - } -} - -// The title asks for 32 MiB and stops if this fails. -HRESULT __stdcall set_staging_buffer_size(Object*, std::uint32_t size) { - std::fprintf(stderr, "[rt] dstorage: staging buffer size %u\n", size); - trace("staging_buffer_size", ",\"size\":" + std::to_string(size)); - if (Scheduler* const s = scheduler()) { - const std::lock_guard lock(s->mutex); - s->lanes.staging = size; - } - return kOk; -} - -const void* const kFactoryVtable[16] = { - method(&missing<0>), - method(&static_add_ref), - method(&static_add_ref), - method(&missing<3>), // 0x18 (2020: queue creation) - method(&open_file), // 0x20 - method(&create_status_array), // 0x28 - method(&missing<6>), // 0x30 (2020: CPU affinity) - method(&missing<7>), // 0x38 (2020: debug flags) - method(&set_staging_buffer_size), // 0x40 - method(&missing<9>), - method(&create_queue), // 0x50 - method(&missing<11>), - method(&missing<12>), - method(&missing<13>), - method(&missing<14>), - method(&missing<15>), -}; - -Object g_factory = {kFactoryVtable, "dstorage factory"}; - -HRESULT __stdcall DStorageGetFactory(const GUID* iid, void** out) { - if (iid && std::memcmp(iid, &kFactoryIid, sizeof(GUID)) == 0) { - if (!out) return kInvalidArg; - *out = &g_factory; - static std::atomic told{false}; - if (!told.exchange(true, std::memory_order_relaxed)) { - std::fprintf(stderr, "[rt] dstorage: DStorageGetFactory: the factory\n"); - trace("DStorageGetFactory", ""); - } - return kOk; - } - std::fprintf(stderr, "[rt] dstorage: DStorageGetFactory: unknown interface %s (E_NOINTERFACE)\n", - iid_text(iid).c_str()); - trace("DStorageGetFactory", ",\"unknown_iid\":" + rt::startup_trace::quote(iid_text(iid))); - return kNoInterface; -} - -static_assert(sizeof(GUID) == sizeof(Guid)); - -} // namespace - -// ---- The scheduler's parts (dstorage_xs.h) - -namespace detail { - -void add_ref(StatusArray* array) { add_ref_instance(array); } -void release(StatusArray* array) { rt::dstorage::release(array); } -std::atomic& entry(StatusArray* array, std::uint32_t index) { return array->entries[index]; } - -Lane::Lane(std::int8_t priority, std::uint16_t lane_capacity) - : cls(static_cast(std::clamp(priority, -1, 1) + 1)), capacity(lane_capacity) {} - -std::size_t Lane::entries() const { return unsubmitted.size() + reads.size() + statuses.size() + running.size(); } - -void Lane::flush() { - while (!statuses.empty()) { - const std::uint64_t seq = statuses.front().first; - if (!reads.empty() && reads.front().first < seq) return; - if (!running.empty() && *running.begin() < seq) return; - // The first failure (in queue order) since the previous status entry, or success. - const auto later = failures.lower_bound(seq); - const std::int32_t first = later == failures.begin() ? kOk : failures.begin()->second; - failures.erase(failures.begin(), later); - statuses.front().second.entry().store(first, std::memory_order_release); - statuses.pop_front(); // releases the array - } -} - -std::uint64_t staging_bytes(const Request& request) { - const bool buffered = (request.options & (kZlib | kBcpack | kPageDestination)) != 0; - return buffered && !(request.options & kMemorySource) ? request.source_size : 0; -} - -std::optional Lanes::start() { - // The class with the least virtual time, then its lane that has started the fewest bytes. - std::optional> best_class; - for (const auto& [id, lane] : lanes) { - if (lane.reads.empty()) continue; - const std::pair key{clock[lane.cls], lane.cls}; - if (!best_class || key < *best_class) best_class = key; - } - if (!best_class) return std::nullopt; - const std::size_t cls = best_class->second; - Lane* lane = nullptr; - std::uint64_t lane_id = 0; - std::tuple best{}; - for (auto& [id, candidate] : lanes) { - if (candidate.reads.empty() || candidate.cls != cls) continue; - const std::tuple key{candidate.clock, - candidate.reads.front().first, id}; - if (!lane || key < best) { - best = key; - lane = &candidate; - lane_id = id; - } - } - if (!lane) return std::nullopt; - const Request request = lane->reads.front().second; - const std::uint64_t staging_needed = staging_bytes(request); - if (staged > 0 && staged + staging_needed > staging) { - starved = true; - ++refused; - return std::nullopt; - } - const Job job{lane_id, lane->reads.front().first, request, staging_needed}; - lane->reads.pop_front(); - lane->running.insert(job.seq); - staged += staging_needed; - const std::uint64_t size = - (std::max)((std::max)(request.destination_size, request.source_size), 1); - now = clock[cls]; - clock[cls] += size * kCost[cls]; - lane_now[cls] = lane->clock; - lane->clock += size; - return job; -} - -void Lanes::finish(const Job& job, std::int32_t result) { - staged -= job.staging; - const auto it = lanes.find(job.lane); - if (it == lanes.end()) return; - it->second.running.erase(job.seq); - if (result != kOk) it->second.failures.emplace(job.seq, result); - it->second.flush(); -} - -void Lanes::submit(std::uint64_t id) { - const auto it = lanes.find(id); - if (it == lanes.end()) return; - const std::size_t cls = it->second.cls; - // A class that had nothing waiting starts from now, not from the credit it left behind. - const bool waiting = std::any_of(lanes.begin(), lanes.end(), [&](const auto& entry) { - return entry.second.cls == cls && !entry.second.reads.empty(); - }); - if (!waiting) clock[cls] = (std::max)(clock[cls], now); - Lane& lane = it->second; - if (lane.reads.empty()) lane.clock = (std::max)(lane.clock, lane_now[cls]); - std::vector commands = std::move(lane.unsubmitted); - lane.unsubmitted.clear(); - for (Command& command : commands) { - const std::uint64_t seq = next_seq++; - if (const Request* request = std::get_if(&command)) { - lane.reads.emplace_back(seq, *request); - } else { - lane.statuses.emplace_back(seq, std::move(std::get(command))); - } - } - lane.flush(); -} - -void Lanes::count(const Job& job, Clock::time_point started) { - const auto spent = Clock::now() - started; - ++done_requests; - done_bytes += job.request.destination_size; - done_busy += spent; - if (job.request.options & kBcpack) { - bcpack_bytes += job.request.destination_size; - bcpack_busy += spent; - } - if (!since) since = started; - const double elapsed = std::chrono::duration(Clock::now() - *since).count(); - if (elapsed < 5.0) return; - std::size_t waiting = 0; - for (const auto& [id, lane] : lanes) waiting += lane.reads.size(); - const double reading = static_cast(g_reading.exchange(0, std::memory_order_relaxed)) / 1e9; - char line[320]; - std::snprintf(line, sizeof line, - "\"seconds\":%.1f,\"requests\":%llu,\"mb_per_s\":%.1f,\"busy_workers\":%.2f,\"reading_workers\":%.2f," - "\"staging_waits\":%llu,\"bcpack_mb\":%llu,\"bcpack_workers\":%.2f,\"waiting\":%zu", - elapsed, static_cast(done_requests), - static_cast(done_bytes) / elapsed / 1e6, - std::chrono::duration(done_busy).count() / elapsed, reading / elapsed, - static_cast(refused), static_cast(bcpack_bytes / 1000000), - std::chrono::duration(bcpack_busy).count() / elapsed, waiting); - if (rt::startup_trace::enabled()) rt::startup_trace::event("dstorage_summary", line); - if (request_trace_level() >= 2) std::fprintf(stderr, "[rt] dstorage: summary {%s}\n", line); - done_requests = done_bytes = refused = bcpack_bytes = 0; - done_busy = bcpack_busy = {}; - since.reset(); -} - -} // namespace detail -} // namespace rt::dstorage - -SHIM_TABLE(dstorage_xs, - {"xcrdapi.dll", "DStorageGetFactory", reinterpret_cast(&rt::dstorage::DStorageGetFactory)}, -); diff --git a/runtime/shims/dstorage_xs.h b/runtime/shims/dstorage_xs.h deleted file mode 100644 index 8ef40faa3..000000000 --- a/runtime/shims/dstorage_xs.h +++ /dev/null @@ -1,233 +0,0 @@ -// The console's DirectStorage (XCRDAPI.dll) as the title calls it: the structures it builds, the interface id it asks -// for, the method slots it calls, and the scheduler behind the queues. The shim is shims/dstorage_xs.cpp. -// -// Ported from VIctory's crates/victory-hle/src/modules/dstorage.rs (GPL-3.0-or-later; Marvisak and contributors, -// DexNom fork); Leonida is GPL-3.0-or-later too. The layouts and slots are VIctory's, read from the title's call sites. -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace rt::dstorage { - -// ---- What the title passes - -struct Guid { - std::uint32_t data1; - std::uint16_t data2; - std::uint16_t data3; - std::uint8_t data4[8]; -}; - -// The factory interface the title asks DStorageGetFactory for; any other id is E_NOINTERFACE. -inline constexpr Guid kFactoryIid = {0x62959d11, 0xd45f, 0x4884, {0xa0, 0xa3, 0xf7, 0x86, 0x2e, 0xa2, 0x43, 0xae}}; - -// The queue's description: as in 2020 (source type, capacity, priority, name), plus a field the title sets to 1. -struct QueueDesc { - std::uint64_t source_type; - std::uint16_t capacity; - std::int8_t priority; // -1 low, 0 normal, 1 high, 2 real-time - const char* name; - std::uint64_t unknown; -}; -static_assert(sizeof(QueueDesc) == 0x20 && offsetof(QueueDesc, name) == 0x10 && offsetof(QueueDesc, unknown) == 0x18); - -// A read request as the title builds it, 0x48 bytes. -struct Request { - std::uint64_t options; - // An address, or with kPageDestination an array of 64 KiB page numbers (one per page the bytes touch). - void* destination; - // With kPageDestination, the low 16 bits are where in the first page the destination starts. - std::uint64_t page_offset; - std::uint32_t destination_size; - // Our file object, or with kMemorySource an address. - const void* source; - std::uint64_t offset; - std::uint32_t source_size; - // The size between two decompression stages (zlib, then BCPack). - std::uint32_t intermediate_size; - // Matched by cancellation; the title leaves it 0. - std::uint64_t tag; - const char* name; -}; -static_assert(sizeof(Request) == 0x48); -static_assert(offsetof(Request, destination_size) == 0x18 && offsetof(Request, source) == 0x20 && - offsetof(Request, source_size) == 0x30 && offsetof(Request, intermediate_size) == 0x34 && - offsetof(Request, name) == 0x40); - -// Request options. -inline constexpr std::uint64_t kZlib = 1; // inflate zlib (RFC 1950) data -inline constexpr std::uint64_t kBcpack = 0xfull << 1; // bits 1-4: unpack BCPack data of this BC format (0: none) -inline constexpr std::uint64_t kPageDestination = 1ull << 21; -inline constexpr std::uint64_t kMemorySource = 1ull << 22; -// Bits 5-20 select a further transform, bit 23 a source in physical pages; the title's packages need neither, so a -// request with them fails with E_NOTIMPL. - -inline constexpr std::size_t kPage = 64 * 1024; - -// Results, as HRESULT bits. -inline constexpr std::int32_t kOk = 0; -inline constexpr std::int32_t kPending = static_cast(0x8000000Au); // E_PENDING -inline constexpr std::int32_t kNotImpl = static_cast(0x80004001u); // E_NOTIMPL -inline constexpr std::int32_t kNoInterface = static_cast(0x80004002u); // E_NOINTERFACE -inline constexpr std::int32_t kInvalidArg = static_cast(0x80070057u); // E_INVALIDARG -inline constexpr std::int32_t kOutOfMemory = static_cast(0x8007000Eu); // E_OUTOFMEMORY -// HRESULT_FROM_WIN32(ERROR_HANDLE_EOF): the source ends early. -inline constexpr std::int32_t kEndOfFile = static_cast(0x80070026u); -// HRESULT_FROM_WIN32(ERROR_INVALID_DATA): a bad compressed stream (zlib or BCPack). -inline constexpr std::int32_t kInvalidData = static_cast(0x8007000Du); - -// The slots the title calls, as byte offsets into the method tables (QueryInterface, AddRef and Release first). The -// newer interfaces moved them from their 2020 places; slots in between that nobody has called log their offset. -namespace slot { -inline constexpr std::size_t kAddRef = 0x08; -inline constexpr std::size_t kRelease = 0x10; -// The factory: (path, iid, out), (capacity, name, iid, out), (bytes), (desc, iid, out). -inline constexpr std::size_t kOpenFile = 0x20; -inline constexpr std::size_t kCreateStatusArray = 0x28; -inline constexpr std::size_t kSetStagingBufferSize = 0x40; -inline constexpr std::size_t kCreateQueue = 0x50; -// A queue: (request), (array, index), (), (). -inline constexpr std::size_t kEnqueueRequest = 0x18; -inline constexpr std::size_t kEnqueueStatus = 0x20; -inline constexpr std::size_t kSubmit = 0x30; -inline constexpr std::size_t kClose = 0x40; -// A status array: bool (index), HRESULT (index). -inline constexpr std::size_t kIsComplete = 0x18; -inline constexpr std::size_t kGetResult = 0x20; -} // namespace slot - -// ---- The scheduler (exposed for its test; everything below runs under the scheduler's lock) -// -// Submitted requests of every queue run on one pool of workers, as the console's hardware runs them: in parallel, -// started in queue order, queues served by weighted round robin over their priorities (about 10x per level, counted -// in bytes), with at most the staging buffer's worth of compressed source in flight. Completion is what stays in -// order: a status entry is written once every request enqueued before it on its queue has finished, with the first -// failure (in queue order) since the previous status entry, or success. -namespace detail { - -struct StatusArray; // dstorage_xs.cpp -void add_ref(StatusArray* array); -void release(StatusArray* array); -std::atomic& entry(StatusArray* array, std::uint32_t index); - -// A status entry to write, holding a reference on its array (taken over from the caller). -class Status { -public: - Status(StatusArray* array, std::uint32_t index) : array_(array), index_(index) {} - Status(Status&& other) noexcept : array_(std::exchange(other.array_, nullptr)), index_(other.index_) {} - Status& operator=(Status&& other) noexcept { - if (this != &other) { - reset(); - array_ = std::exchange(other.array_, nullptr); - index_ = other.index_; - } - return *this; - } - Status(const Status&) = delete; - Status& operator=(const Status&) = delete; - ~Status() { reset(); } - - // The index was checked when the status was enqueued. - std::atomic& entry() const { return detail::entry(array_, index_); } - -private: - void reset() { - if (array_) release(std::exchange(array_, nullptr)); - } - StatusArray* array_; - std::uint32_t index_; -}; - -using Command = std::variant; - -// Priority weights per class (low, normal, high and real-time), as the console's: about 10x per level, counted -// against request sizes. -inline constexpr std::array kCost = {100, 10, 1}; -// The console's default staging buffer. -inline constexpr std::uint64_t kStaging = 32ull << 20; - -// A queue's requests. -struct Lane { - Lane(std::int8_t priority, std::uint16_t capacity); - - std::size_t cls; // 0 low, 1 normal, 2 high and real-time - std::size_t capacity; - // Bytes started, for round robin among the lanes of a class. - std::uint64_t clock = 0; - // Enqueued, not yet submitted. - std::vector unsubmitted; - // Submitted, by sequence number: reads not started, status entries not written, reads running, and failures not - // yet reported. - std::deque> reads; - std::deque> statuses; - std::set running; - std::map failures; - bool closed = false; - - // Requests and status entries held, submitted or not. - std::size_t entries() const; - // Writes the status entries whose earlier reads have all finished. - void flush(); -}; - -// A read a worker runs. -struct Job { - std::uint64_t lane; - std::uint64_t seq; - Request request; - std::uint64_t staging; -}; - -struct Lanes { - std::map lanes; - std::uint64_t next_id = 0; - // Submission order over all queues. - std::uint64_t next_seq = 0; - // Bytes of staging held by running requests, and the limit. - std::uint64_t staged = 0; - std::uint64_t staging = kStaging; - // A start waited for staging space since the last finish. - bool starved = false; - // Weighted round robin: each class's virtual time (bytes x cost), and the time of the last start; within a class, - // the lane clock of the last start. - std::array clock{}; - std::uint64_t now = 0; - std::array lane_now{}; - // Since the last summary: requests, bytes written and time spent running them, starts that waited for staging, - // and the BCPack share. - std::uint64_t done_requests = 0; - std::uint64_t done_bytes = 0; - std::chrono::steady_clock::duration done_busy{}; - std::uint64_t refused = 0; - std::uint64_t bcpack_bytes = 0; - std::chrono::steady_clock::duration bcpack_busy{}; - std::optional since; - - // Starts the next read of the class with the least virtual time, from its lane that has started the fewest bytes, - // if the staging buffer has room for it (or nothing else holds any). - std::optional start(); - // A read is done: kOk or its failure. - void finish(const Job& job, std::int32_t result); - // Moves a queue's enqueued commands to the workers. - void submit(std::uint64_t id); - // Counts a finished request; every 5 s a summary goes to the startup trace. - void count(const Job& job, std::chrono::steady_clock::time_point started); -}; - -// Staging bytes a request holds while it runs: what it buffers between the file and the destination. Raw reads go -// straight to their destination, memory sources need none (as on the console). -std::uint64_t staging_bytes(const Request& request); - -} // namespace detail -} // namespace rt::dstorage diff --git a/runtime/shims/file_system.h b/runtime/shims/file_system.h index 9041abc90..420430e13 100644 --- a/runtime/shims/file_system.h +++ b/runtime/shims/file_system.h @@ -42,11 +42,6 @@ std::wstring scratch_stem(); std::filesystem::path reserve_unique_dir(const std::filesystem::path& base, const std::wstring& stem, unsigned long& error, unsigned max_tries = 1000); -// The host file a read of `path` opens, by the rules above: a GAME:/G:/T: path becomes its overlay or package file, -// anything else is returned unchanged. False for a refused console path or a package file the title deleted. -// For shims that hand a path to host code that does its own opening (media_foundation.cpp). -bool read_path(const std::wstring& path, std::filesystem::path& out); - // For tests: true makes the CopyFile2 shim use its CopyFileExW fallback even where the host has CopyFile2, so the // path Wine 9 takes can be checked on Windows. Off by default; main.cpp never sets it. void force_copy_file2_fallback(bool force); diff --git a/runtime/shims/gameinput_xinput.cpp b/runtime/shims/gameinput_xinput.cpp deleted file mode 100644 index 1089a3ac5..000000000 --- a/runtime/shims/gameinput_xinput.cpp +++ /dev/null @@ -1,1067 +0,0 @@ -// gameinput (no SDL3): GameInput v0 for gamepads and the keyboard, from XInput, a wired DualSense and the keyboard. -// -// Ported from VIctory (crates/victory-hle/src/modules/gameinput.rs and gameinput/dualsense.rs), GPL-3.0-or-later, by -// Marvisak and contributors (DexNom fork). Leonida is GPL-3.0-or-later. VIctory runs the title with this design; its -// slot order, error codes, device ids at +0x20, reading history and callback rules are kept: -// -// - devices: XInput slots 0-3, a stand-in pad the keyboard drives while no other pad is connected, the keyboard -// itself (GameInputKindKeyboard readings: scan codes and virtual keys), and a wired DualSense read over HID when -// no XInput slot holds a pad (Steam Input's virtual pad, which is XInput, wins over it); -// - a poll thread reads the host every 8 ms, makes a new reading per device whenever its state changes (32 kept -// per device for GetNextReading / GetPreviousReading), and runs device callbacks when a device comes or goes; -// - RegisterDeviceCallback with blocking enumeration reports the devices already there on the caller's thread -// before it returns (the title registers holding a lock its callback takes again); asynchronous enumeration -// reports them on the next poll; UnregisterCallback waits for a callback that is running, and fails from inside it; -// - SetRumbleState drives an XInput pad's two motors; trigger motors are dropped (XInput has none). -// -// Not implemented, as in VIctory: reading callbacks never run (the title polls), the dispatcher and aggregate devices -// (E_NOTIMPL), force feedback, haptics and raw device I/O (E_NOTIMPL); mouse, touch, motion, sticks and wheels have no -// readings. Deviations: QueryInterface answers the object's own v0 IIDs (VIctory answers none), GetBatteryState writes -// a zeroed state (not present) instead of nothing, and the keyboard pad can be turned off (LEONIDA_KEYBOARD_PAD=off). -// -// gameinput.cpp (SDL3) is the shim when SDL3 is available; this file is built in its place otherwise (CMakeLists.txt), -// instead of binding the title's import to the host's GameInput.dll, which has no keyboard pad. -// LEONIDA_GAMEINPUT=host forwards GameInputCreate to the host's GameInput.dll as before. -// -// The keyboard pad's keys (VIctory's README): Esc Menu, Tab View, Enter A, Backspace B, X X, Y Y, arrows the d-pad, -// Q/E the shoulders, F/H the stick clicks, W/A/S/D the left stick, I/J/K/L the right stick, Z/C the triggers. -// -// Portable outside the host source (XInput, GetAsyncKeyState, HID), which is Win32 and stays behind _WIN32. -#include "gameinput_xinput.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef _WIN32 -#include -#include -#include -#include -#ifdef _MSC_VER -#pragma comment(lib, "hid.lib") -#pragma comment(lib, "setupapi.lib") -#endif -#endif - -#include "shims.h" - -namespace rt::gameinput_xinput { -namespace { - -using namespace gi; -using Clock = std::chrono::steady_clock; - -constexpr GUID kIUnknown = {0x00000000, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}}; - -constexpr uint32_t kKeyboardKind = GameInputKindKeyboard; -constexpr uint32_t kGamepadKind = GameInputKindGamepad; -// The status of a connected device: connected, input enabled. -constexpr uint32_t kStatusConnected = GameInputDeviceConnected | GameInputDeviceInputEnabled; -constexpr size_t kHistory = 32; -constexpr auto kPollPeriod = std::chrono::milliseconds(8); - -// Microseconds since the first call: the clock of every timestamp handed out. -uint64_t now_us() { - static const Clock::time_point start = Clock::now(); - return static_cast(std::chrono::duration_cast(Clock::now() - start).count()); -} - -uint32_t kind_of(int index) { return index == kKeyboard ? kKeyboardKind : kGamepadKind; } - -bool same_pad(const PadState& a, const PadState& b) { - return a.buttons == b.buttons && a.leftTrigger == b.leftTrigger && a.rightTrigger == b.rightTrigger && - a.leftThumbstickX == b.leftThumbstickX && a.leftThumbstickY == b.leftThumbstickY && - a.rightThumbstickX == b.rightThumbstickX && a.rightThumbstickY == b.rightThumbstickY; -} - -bool same_keys(const std::vector& a, const std::vector& b) { - if (a.size() != b.size()) return false; - for (size_t i = 0; i < a.size(); ++i) - if (a[i].scan_code != b[i].scan_code || a[i].code_point != b[i].code_point || - a[i].virtual_key != b[i].virtual_key || a[i].dead_key != b[i].dead_key) - return false; - return true; -} - -// What a reading holds: a pad's state, or the keys held. -struct Value { - bool keys = false; - PadState pad{}; - std::vector held; - - static Value of_pad(const PadState& p) { - Value v; - v.pad = p; - return v; - } - static Value of_keys(std::vector k) { - Value v; - v.keys = true; - v.held = std::move(k); - return v; - } - bool operator==(const Value& o) const { - return keys == o.keys && (keys ? same_keys(held, o.held) : same_pad(pad, o.pad)); - } - uint32_t kind() const { return keys ? kKeyboardKind : kGamepadKind; } -}; - -class Hub; - -HRESULT answer(void* self, REFIID iid, const GUID& own, void** out) { - if (!out) return E_POINTER; - if (iid == kIUnknown || iid == own) { - *out = self; - return S_OK; - } - *out = nullptr; - return E_NOINTERFACE; -} - -// A device lives as long as the process: AddRef and Release count nothing, as in VIctory. -class Device final : public IGameInputDevice { -public: - Hub* hub = nullptr; - int index = 0; - GameInputDeviceInfo info{}; - - HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void** out) override { - return answer(static_cast(this), iid, IID_IGameInputDevice, out); - } - ULONG STDMETHODCALLTYPE AddRef() override { return 1; } - ULONG STDMETHODCALLTYPE Release() override { return 1; } - const GameInputDeviceInfo* STDMETHODCALLTYPE GetDeviceInfo() override { return &info; } - uint32_t STDMETHODCALLTYPE GetDeviceStatus() override; - void STDMETHODCALLTYPE GetBatteryState(GameInputBatteryState* state) override { - if (state) *state = GameInputBatteryState{}; // wired, no battery (GameInputBatteryNotPresent) - } - HRESULT STDMETHODCALLTYPE CreateForceFeedbackEffect(uint32_t, const void*, void** effect) override { - if (effect) *effect = nullptr; - return unsupported("CreateForceFeedbackEffect"); - } - bool STDMETHODCALLTYPE IsForceFeedbackMotorPoweredOn(uint32_t) override { return false; } - void STDMETHODCALLTYPE SetForceFeedbackMotorGain(uint32_t, float) override {} - HRESULT STDMETHODCALLTYPE SetHapticMotorState(uint32_t, const void*) override { - return unsupported("SetHapticMotorState"); - } - void STDMETHODCALLTYPE SetRumbleState(const GameInputRumbleParams* params) override; - void STDMETHODCALLTYPE SetInputSynchronizationState(bool) override {} - void STDMETHODCALLTYPE SendInputSynchronizationHint() override {} - void STDMETHODCALLTYPE PowerOff() override {} - HRESULT STDMETHODCALLTYPE CreateRawDeviceReport(uint32_t, int32_t, void** report) override { - if (report) *report = nullptr; - return unsupported("CreateRawDeviceReport"); - } - HRESULT STDMETHODCALLTYPE GetRawDeviceFeature(uint32_t, void** report) override { - if (report) *report = nullptr; - return unsupported("GetRawDeviceFeature"); - } - HRESULT STDMETHODCALLTYPE SetRawDeviceFeature(void*) override { return unsupported("SetRawDeviceFeature"); } - HRESULT STDMETHODCALLTYPE SendRawDeviceOutput(void*) override { return unsupported("SendRawDeviceOutput"); } - HRESULT STDMETHODCALLTYPE SendRawDeviceOutputWithResponse(void*, void** response) override { - if (response) *response = nullptr; - return unsupported("SendRawDeviceOutputWithResponse"); - } - HRESULT STDMETHODCALLTYPE ExecuteRawDeviceIoControl(uint32_t, size_t, const void*, size_t, void*, - size_t* size) override { - if (size) *size = 0; - return unsupported("ExecuteRawDeviceIoControl"); - } - bool STDMETHODCALLTYPE AcquireExclusiveRawDeviceAccess(uint64_t) override { return false; } - void STDMETHODCALLTYPE ReleaseExclusiveRawDeviceAccess() override {} - -private: - // Logged once per method. - static HRESULT unsupported(const char* method) { - static std::mutex mu; - static std::vector logged; - std::lock_guard lock(mu); - if (std::find(logged.begin(), logged.end(), method) == logged.end()) { - logged.push_back(method); - std::fprintf(stderr, "[rt] gameinput: IGameInputDevice::%s is not implemented (E_NOTIMPL)\n", method); - } - return E_NOTIMPL; - } -}; - -// A reading: counted, freed with its last reference. The hub's history holds one. -class Reading final : public IGameInputReading { -public: - Reading(Device* device, uint64_t sequence, uint64_t timestamp, Value value) - : device_(device), sequence_(sequence), timestamp_(timestamp), value_(std::move(value)) {} - - const Value& value() const { return value_; } - uint64_t sequence() const { return sequence_; } - uint64_t timestamp() const { return timestamp_; } - Device* device() const { return device_; } - uint32_t kind() const { return value_.kind(); } - - HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void** out) override { - const HRESULT hr = answer(static_cast(this), iid, IID_IGameInputReading, out); - if (hr == S_OK) AddRef(); - return hr; - } - ULONG STDMETHODCALLTYPE AddRef() override { return refs_.fetch_add(1, std::memory_order_relaxed) + 1; } - ULONG STDMETHODCALLTYPE Release() override { - const ULONG left = refs_.fetch_sub(1, std::memory_order_acq_rel) - 1; - if (left == 0) delete this; - return left; - } - uint32_t STDMETHODCALLTYPE GetInputKind() override { return kind(); } - uint64_t STDMETHODCALLTYPE GetSequenceNumber(uint32_t kind_mask) override { - return (kind() & kind_mask) ? sequence_ : 0; - } - uint64_t STDMETHODCALLTYPE GetTimestamp() override { return timestamp_; } - // Devices need no reference: they live as long as the process. - void STDMETHODCALLTYPE GetDevice(IGameInputDevice** device) override { - if (device) *device = device_; - } - bool STDMETHODCALLTYPE GetRawReport(void** report) override { - if (report) *report = nullptr; - return false; - } - uint32_t STDMETHODCALLTYPE GetControllerAxisCount() override { return 0; } - uint32_t STDMETHODCALLTYPE GetControllerAxisState(uint32_t, float*) override { return 0; } - uint32_t STDMETHODCALLTYPE GetControllerButtonCount() override { return 0; } - uint32_t STDMETHODCALLTYPE GetControllerButtonState(uint32_t, bool*) override { return 0; } - uint32_t STDMETHODCALLTYPE GetControllerSwitchCount() override { return 0; } - uint32_t STDMETHODCALLTYPE GetControllerSwitchState(uint32_t, GameInputSwitchPosition*) override { return 0; } - uint32_t STDMETHODCALLTYPE GetKeyCount() override { - return value_.keys ? static_cast(value_.held.size()) : 0; - } - uint32_t STDMETHODCALLTYPE GetKeyState(uint32_t count, void* out) override { - if (!value_.keys || !out) return 0; - const size_t n = std::min(value_.held.size(), count); - std::memcpy(out, value_.held.data(), n * sizeof(KeyState)); - return static_cast(n); - } - bool STDMETHODCALLTYPE GetMouseState(void*) override { return false; } - uint32_t STDMETHODCALLTYPE GetTouchCount() override { return 0; } - uint32_t STDMETHODCALLTYPE GetTouchState(uint32_t, void*) override { return 0; } - bool STDMETHODCALLTYPE GetMotionState(void*) override { return false; } - bool STDMETHODCALLTYPE GetArcadeStickState(void*) override { return false; } - bool STDMETHODCALLTYPE GetFlightStickState(void*) override { return false; } - bool STDMETHODCALLTYPE GetGamepadState(GameInputGamepadState* state) override { - if (!state || value_.keys) return false; - *state = value_.pad; - return true; - } - bool STDMETHODCALLTYPE GetRacingWheelState(void*) override { return false; } - bool STDMETHODCALLTYPE GetUiNavigationState(GameInputUiNavigationState*) override { return false; } - -private: - ~Reading() = default; - std::atomic refs_{1}; - Device* device_; - uint64_t sequence_; - uint64_t timestamp_; - Value value_; -}; - -struct Registration { - uint64_t token = 0; - IGameInputDevice* device = nullptr; // one device, or null for any - uint32_t kind = 0; - uint32_t status = 0; - void* context = nullptr; - GameInputDeviceCallback callback = nullptr; -}; - -struct Event { - Registration registration; - int device = 0; - uint64_t timestamp = 0; - uint32_t current = 0; - uint32_t previous = 0; -}; - -struct Slot { - bool connected = false; - uint64_t sequence = 0; - std::deque history; // one reference each -}; - -std::atomic g_next_token{1}; - -class Hub final : public IGameInput { -public: - Hub(std::unique_ptr source, bool stand_in_enabled) - : source_(std::move(source)), stand_in_enabled_(stand_in_enabled) { - for (int i = 0; i < kDevices; ++i) { - Device& d = devices_[i]; - d.hub = this; - d.index = i; - d.info.infoSize = sizeof(GameInputDeviceInfo); - static const char kTag[] = "leonida"; - std::memcpy(d.info.deviceId.value, kTag, sizeof kTag - 1); - d.info.deviceId.value[31] = static_cast(i + 1); - d.info.deviceRootId = d.info.deviceId; - d.info.supportedInput = kind_of(i); - d.info.supportedRumbleMotors = i < kPads ? (GameInputRumbleLowFrequency | GameInputRumbleHighFrequency) : 0; - } - } - - Device* device(int index) { return index >= 0 && index < kDevices ? &devices_[index] : nullptr; } - - bool connected(int index) { - std::lock_guard lock(mu_); - return slots_[index].connected; - } - - // Reads the host once; device callbacks run on the calling thread. - void poll() { - PadState pads[kPads] = {}; - bool have[kPads] = {}; - PadState native{}; - bool have_native = false; - std::vector keys; - bool any = false; - { - std::lock_guard lock(source_mu_); - for (int slot = 0; slot < kPads; ++slot) any |= have[slot] = source_->pad(slot, &pads[slot]); - // XInput first, including a virtual pad Steam Input already supplies. - if (!any) have_native = source_->native_pad(&native); - keys = source_->keys(); - } - // The keyboard's pad stands in only while no other pad is there. - const bool stand_in_on = stand_in_enabled_ && !any && !have_native; - std::vector events; - { - std::lock_guard lock(mu_); - const uint64_t now = now_us(); - events = std::exchange(pending_, {}); - for (int slot = 0; slot < kPads; ++slot) { - const Value v = Value::of_pad(pads[slot]); - update(slot, have[slot] ? &v : nullptr, now, events); - } - const Value pad = Value::of_pad(stand_in(keys)); - update(kStandIn, stand_in_on ? &pad : nullptr, now, events); - const Value held = Value::of_keys(keys); - update(kKeyboard, &held, now, events); - const Value ds = Value::of_pad(native); - update(kDualSense, have_native ? &ds : nullptr, now, events); - } - deliver(std::move(events)); - } - - void rumble(int index, uint16_t low, uint16_t high) { - std::lock_guard lock(source_mu_); - source_->rumble(index, low, high); - } - - // ---- IGameInput ---- - - HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void** out) override { - return answer(static_cast(this), iid, IID_IGameInput, out); - } - ULONG STDMETHODCALLTYPE AddRef() override { return 1; } - ULONG STDMETHODCALLTYPE Release() override { return 1; } - - uint64_t STDMETHODCALLTYPE GetCurrentTimestamp() override { return now_us(); } - - HRESULT STDMETHODCALLTYPE GetCurrentReading(uint32_t kind, IGameInputDevice* device, - IGameInputReading** out) override { - std::lock_guard lock(mu_); - auto newest = [&](int i) -> Reading* { - const auto& h = slots_[i].history; - return !h.empty() && (h.back()->kind() & kind) ? h.back() : nullptr; - }; - Reading* found = nullptr; - if (!device) { - for (int i = 0; i < kDevices; ++i) - if (slots_[i].connected) - if (Reading* r = newest(i); r && (!found || r->timestamp() >= found->timestamp())) found = r; - } else { - const int i = index_of(device); - if (i < 0) return fail(out, E_INVALIDARG); - if (!slots_[i].connected) return fail(out, GAMEINPUT_E_DEVICE_DISCONNECTED); - found = newest(i); - } - return hand(out, found); - } - - HRESULT STDMETHODCALLTYPE GetNextReading(IGameInputReading* reference, uint32_t kind, IGameInputDevice* device, - IGameInputReading** out) override { - return relative(reference, kind, device, out, true); - } - HRESULT STDMETHODCALLTYPE GetPreviousReading(IGameInputReading* reference, uint32_t kind, - IGameInputDevice* device, IGameInputReading** out) override { - return relative(reference, kind, device, out, false); - } - - // The device's reading at `timestamp`, among those still kept. - HRESULT STDMETHODCALLTYPE GetTemporalReading(uint64_t timestamp, IGameInputDevice* device, - IGameInputReading** out) override { - std::lock_guard lock(mu_); - const int i = index_of(device); - if (i < 0) return fail(out, E_INVALIDARG); - const auto& h = slots_[i].history; - for (auto it = h.rbegin(); it != h.rend(); ++it) - if ((*it)->timestamp() <= timestamp) return hand(out, *it); - return hand(out, nullptr); - } - - // Reading callbacks never run; the title registers none (it polls), as VIctory found. - HRESULT STDMETHODCALLTYPE RegisterReadingCallback(IGameInputDevice*, uint32_t, float, void*, - GameInputReadingCallback, GameInputCallbackToken* token) override { - static std::atomic warned{false}; - if (!warned.exchange(true)) - std::fprintf(stderr, "[rt] gameinput: reading callbacks are registered but never called\n"); - return new_token(token); - } - - HRESULT STDMETHODCALLTYPE RegisterDeviceCallback(IGameInputDevice* device, uint32_t kind, uint32_t status, - GameInputEnumerationKind enumeration, void* context, - GameInputDeviceCallback callback, - GameInputCallbackToken* token) override { - if (!callback) return E_INVALIDARG; - Registration r; - r.token = g_next_token.fetch_add(1, std::memory_order_relaxed); - r.device = device; - r.kind = kind; - r.status = status; - r.context = context; - r.callback = callback; - std::vector found; - { - std::lock_guard lock(mu_); - if (enumeration != GameInputNoEnumeration && (status & kStatusConnected)) { - const uint64_t now = now_us(); - for (int i = 0; i < kDevices; ++i) - if (slots_[i].connected && matches(r, i)) found.push_back({r, i, now, kStatusConnected, 0}); - } - std::fprintf(stderr, "[rt] gameinput: device callback for kinds 0x%x, enumeration %d, %zu devices now\n", - kind, static_cast(enumeration), found.size()); - callbacks_.push_back(r); - if (enumeration == GameInputAsyncEnumeration) { - pending_.insert(pending_.end(), found.begin(), found.end()); - found.clear(); - } - } - if (token) *token = r.token; - deliver(std::move(found)); // blocking enumeration: before this returns - return S_OK; - } - - // The guide button and the keyboard layout never change here. - HRESULT STDMETHODCALLTYPE RegisterGuideButtonCallback(IGameInputDevice*, void*, GameInputGuideButtonCallback, - GameInputCallbackToken* token) override { - return new_token(token); - } - HRESULT STDMETHODCALLTYPE RegisterKeyboardLayoutCallback(IGameInputDevice*, void*, GameInputKeyboardLayoutCallback, - GameInputCallbackToken* token) override { - return new_token(token); - } - - void STDMETHODCALLTYPE StopCallback(GameInputCallbackToken token) override { - std::lock_guard lock(mu_); - forget(token); - } - - // Stops the callback, then waits up to `timeout` microseconds for a call of it that is running; false on time-out, - // or from inside that callback (it cannot wait for itself), as documented. Either way it is never called again. - bool STDMETHODCALLTYPE UnregisterCallback(GameInputCallbackToken token, uint64_t timeout) override { - const std::thread::id me = std::this_thread::get_id(); - std::unique_lock lock(mu_); - forget(token); - // A timeout past a year is "forever" (VIctory's checked_add overflows to an endless wait for u64::MAX). - const bool forever = timeout > 365ull * 24 * 3600 * 1000000; - const Clock::time_point deadline = Clock::now() + std::chrono::microseconds(forever ? 0 : timeout); - for (;;) { - bool any = false; - for (const auto& [t, thread] : running_) { - if (t != token) continue; - if (thread == me) return false; - any = true; - } - if (!any) return true; - if (forever) { - returned_.wait(lock); - } else if (returned_.wait_until(lock, deadline) == std::cv_status::timeout) { - // One last look: the callback may have returned just as the wait ran out. - bool still = false; - for (const auto& entry : running_) still |= entry.first == token; - return !still; - } - } - } - - // No title of ours asks for these (VIctory). - HRESULT STDMETHODCALLTYPE CreateDispatcher(IGameInputDispatcher** out) override { - std::fprintf(stderr, "[rt] gameinput: CreateDispatcher is not implemented (E_NOTIMPL)\n"); - return fail(out, E_NOTIMPL); - } - HRESULT STDMETHODCALLTYPE CreateAggregateDevice(uint32_t, IGameInputDevice** out) override { - std::fprintf(stderr, "[rt] gameinput: CreateAggregateDevice is not implemented (E_NOTIMPL)\n"); - return fail(out, E_NOTIMPL); - } - - HRESULT STDMETHODCALLTYPE FindDeviceFromId(const AppLocalDeviceId* id, IGameInputDevice** out) override { - if (!id || !out) return fail(out, E_INVALIDARG); - for (Device& d : devices_) - if (std::memcmp(d.info.deviceId.value, id->value, sizeof id->value) == 0) { - *out = &d; - return S_OK; - } - return fail(out, GAMEINPUT_E_DEVICE_NOT_FOUND); - } - // Our devices have no object, platform handle or platform string. - HRESULT STDMETHODCALLTYPE FindDeviceFromObject(IUnknown*, IGameInputDevice** out) override { - return fail(out, GAMEINPUT_E_DEVICE_NOT_FOUND); - } - HRESULT STDMETHODCALLTYPE FindDeviceFromPlatformHandle(HANDLE, IGameInputDevice** out) override { - return fail(out, GAMEINPUT_E_DEVICE_NOT_FOUND); - } - HRESULT STDMETHODCALLTYPE FindDeviceFromPlatformString(LPCWSTR, IGameInputDevice** out) override { - return fail(out, GAMEINPUT_E_DEVICE_NOT_FOUND); - } - HRESULT STDMETHODCALLTYPE EnableOemDeviceSupport(uint16_t, uint16_t, uint8_t, uint8_t) override { return S_OK; } - void STDMETHODCALLTYPE SetFocusPolicy(uint32_t) override {} - -private: - template - static HRESULT fail(T** out, HRESULT hr) { - if (out) *out = nullptr; - return hr; - } - - // Gives the title a reference to `reading`, or fails as with none. - static HRESULT hand(IGameInputReading** out, Reading* reading) { - if (!out) return E_INVALIDARG; - if (!reading) return fail(out, GAMEINPUT_E_READING_NOT_FOUND); - reading->AddRef(); - *out = reading; - return S_OK; - } - - static HRESULT new_token(GameInputCallbackToken* token) { - if (token) *token = g_next_token.fetch_add(1, std::memory_order_relaxed); - return S_OK; - } - - int index_of(IGameInputDevice* device) const { - for (int i = 0; i < kDevices; ++i) - if (device == &devices_[i]) return i; - return -1; - } - - bool matches(const Registration& r, int index) const { - return (kind_of(index) & r.kind) != 0 && (!r.device || r.device == &devices_[index]); - } - - void forget(uint64_t token) { // under mu_ - callbacks_.erase(std::remove_if(callbacks_.begin(), callbacks_.end(), - [token](const Registration& r) { return r.token == token; }), - callbacks_.end()); - pending_.erase(std::remove_if(pending_.begin(), pending_.end(), - [token](const Event& e) { return e.registration.token == token; }), - pending_.end()); - } - - // The reading after (forward) or before `reference` on its device. With no device given only the reference's - // device is walked (VIctory's shortcut: the title walks only keyboard readings and the current pad's previous one). - HRESULT relative(IGameInputReading* reference, uint32_t kind, IGameInputDevice* device, IGameInputReading** out, - bool forward) { - if (!reference) return fail(out, E_INVALIDARG); - const auto* ref = static_cast(reference); - const int i = index_of(ref->device()); - if (i < 0) return fail(out, E_INVALIDARG); - if (device && device != ref->device()) return fail(out, E_INVALIDARG); - std::lock_guard lock(mu_); - const auto& h = slots_[i].history; - if (h.empty() || ref->sequence() < h.front()->sequence()) return fail(out, GAMEINPUT_E_REFERENCE_READING_TOO_OLD); - Reading* found = nullptr; - if (forward) { - for (Reading* r : h) - if (r->sequence() > ref->sequence() && (r->kind() & kind)) { - found = r; - break; - } - } else { - for (auto it = h.rbegin(); it != h.rend(); ++it) - if ((*it)->sequence() < ref->sequence() && ((*it)->kind() & kind)) { - found = *it; - break; - } - } - return hand(out, found); - } - - // Records a device's state: a reading when it changed, callbacks when the device came or went. Under mu_. - void update(int index, const Value* value, uint64_t now, std::vector& events) { - Slot& s = slots_[index]; - const bool was = s.connected; - s.connected = value != nullptr; - if (value && (!was || s.history.empty() || !(s.history.back()->value() == *value))) { - ++s.sequence; - if (s.history.size() == kHistory) { - s.history.front()->Release(); - s.history.pop_front(); - } - s.history.push_back(new Reading(&devices_[index], s.sequence, now, *value)); - } - if (was == s.connected) return; - std::fprintf(stderr, "[rt] gameinput: device %d (%s) %s\n", index, name(index), - s.connected ? "connected" : "disconnected"); - const uint32_t current = was ? 0 : kStatusConnected, previous = was ? kStatusConnected : 0; - for (const Registration& r : callbacks_) - if (matches(r, index) && (r.status & kStatusConnected)) events.push_back({r, index, now, current, previous}); - } - - static const char* name(int index) { - return index < kPads ? "XInput pad" : index == kStandIn ? "keyboard pad" : index == kKeyboard ? "keyboard" - : "DualSense"; - } - - // Runs callbacks, never under the lock: they call back into the hub. One unregistered since the event was taken - // does not run, and UnregisterCallback waits for one that runs. - void deliver(std::vector events) { - const std::thread::id me = std::this_thread::get_id(); - for (const Event& e : events) { - const Registration& r = e.registration; - { - std::lock_guard lock(mu_); - if (std::none_of(callbacks_.begin(), callbacks_.end(), - [&](const Registration& c) { return c.token == r.token; })) - continue; - running_.emplace_back(r.token, me); - } - r.callback(r.token, r.context, &devices_[e.device], e.timestamp, e.current, e.previous); - { - std::lock_guard lock(mu_); - for (auto it = running_.begin(); it != running_.end(); ++it) - if (it->first == r.token && it->second == me) { - running_.erase(it); - break; - } - } - returned_.notify_all(); - } - } - - Device devices_[kDevices]; - // Apart from the state: XInput can be slow, and the title reads readings every frame. - std::mutex source_mu_; - std::unique_ptr source_; - bool stand_in_enabled_; - std::mutex mu_; - Slot slots_[kDevices]; - std::vector callbacks_; - std::vector pending_; // asynchronous enumerations, delivered by the next poll - std::vector> running_; // device callbacks running now - std::condition_variable returned_; -}; - -uint32_t Device::GetDeviceStatus() { return hub->connected(index) ? kStatusConnected : 0; } - -// Trigger motors are dropped: XInput has none. -void Device::SetRumbleState(const GameInputRumbleParams* params) { - if (index >= kPads) return; - const GameInputRumbleParams p = params ? *params : GameInputRumbleParams{}; - auto speed = [](float level) { return static_cast(std::clamp(level, 0.0f, 1.0f) * 65535.0f); }; - hub->rumble(index, speed(p.lowFrequency), speed(p.highFrequency)); -} - -// ---- the host (Win32) ---- - -#ifdef _WIN32 - -bool env_is(const char* name, const char* value) { - char buf[16] = {}; - const DWORD n = GetEnvironmentVariableA(name, buf, sizeof buf); - return n > 0 && n < sizeof buf && _stricmp(buf, value) == 0; -} - -// The foreground window is one of this process's. -bool focused() { - DWORD process = 0; - GetWindowThreadProcessId(GetForegroundWindow(), &process); - return process == GetCurrentProcessId(); -} - -// A wired DualSense through the Windows HID class driver (VIctory's dualsense.rs, which uses hidapi). -class DualSense { -public: - ~DualSense() { close(); } - - bool poll(PadState* out) { - if (file_ == INVALID_HANDLE_VALUE) { - const Clock::time_point now = Clock::now(); - if (now < retry_at_) return false; - retry_at_ = now + std::chrono::seconds(1); - if (!open()) return false; - } - // Drain queued reports without waiting, bounded even when the pad sends faster than this reads. - for (int i = 0; i < 32; ++i) { - DWORD n = 0; - if (!pending_) { - ResetEvent(overlapped_.hEvent); - if (ReadFile(file_, buffer_, report_length_, &n, &overlapped_)) { - take(n); - continue; - } - if (GetLastError() != ERROR_IO_PENDING) return lost(); - pending_ = true; - } - if (!GetOverlappedResult(file_, &overlapped_, &n, FALSE)) { - if (GetLastError() == ERROR_IO_INCOMPLETE) break; - return lost(); - } - pending_ = false; - take(n); - } - if (have_) *out = state_; - return have_; - } - -private: - static constexpr USHORT kSony = 0x054c, kDualSenseId = 0x0ce6; - static constexpr ULONG kReportLength = 64; // the USB input report; Bluetooth's is longer - - void take(DWORD n) { - PadState s{}; - if (decode_dualsense(buffer_, n, &s)) { - if (!have_) std::fprintf(stderr, "[rt] gameinput: wired DualSense input connected\n"); - state_ = s; - have_ = true; - } - } - - bool lost() { - std::fprintf(stderr, "[rt] gameinput: DualSense input disconnected\n"); - close(); - retry_at_ = Clock::now() + std::chrono::seconds(1); - return false; - } - - // The first present HID interface that is a DualSense's game-pad collection (usage page 1, usage 5) with the - // USB report length. - bool open() { - GUID hid; - HidD_GetHidGuid(&hid); - const HDEVINFO set = SetupDiGetClassDevsW(&hid, nullptr, nullptr, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); - if (set == INVALID_HANDLE_VALUE) return false; - SP_DEVICE_INTERFACE_DATA iface{}; - iface.cbSize = sizeof iface; - bool found = false; - for (DWORD i = 0; !found && SetupDiEnumDeviceInterfaces(set, nullptr, &hid, i, &iface); ++i) { - DWORD size = 0; - SetupDiGetDeviceInterfaceDetailW(set, &iface, nullptr, 0, &size, nullptr); - if (size < sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_W)) continue; - std::vector storage(size); - auto* detail = reinterpret_cast(storage.data()); - detail->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_W); - if (!SetupDiGetDeviceInterfaceDetailW(set, &iface, detail, size, nullptr, nullptr)) continue; - // Access 0 reads the attributes of a device another process holds open; the read handle comes after. - const HANDLE probe = CreateFileW(detail->DevicePath, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, - OPEN_EXISTING, 0, nullptr); - if (probe == INVALID_HANDLE_VALUE) continue; - HIDD_ATTRIBUTES attributes{}; - attributes.Size = sizeof attributes; - bool wanted = HidD_GetAttributes(probe, &attributes) && attributes.VendorID == kSony && - attributes.ProductID == kDualSenseId; - HIDP_CAPS caps{}; - PHIDP_PREPARSED_DATA preparsed = nullptr; - if (wanted && HidD_GetPreparsedData(probe, &preparsed)) { - wanted = HidP_GetCaps(preparsed, &caps) == HIDP_STATUS_SUCCESS && caps.UsagePage == 0x01 && - caps.Usage == 0x05 && caps.InputReportByteLength == kReportLength; - HidD_FreePreparsedData(preparsed); - } else { - wanted = false; - } - CloseHandle(probe); - if (!wanted) continue; - file_ = CreateFileW(detail->DevicePath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, - OPEN_EXISTING, FILE_FLAG_OVERLAPPED, nullptr); - found = file_ != INVALID_HANDLE_VALUE; - } - SetupDiDestroyDeviceInfoList(set); - if (!found) return false; - overlapped_ = OVERLAPPED{}; - overlapped_.hEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr); - if (!overlapped_.hEvent) { - CloseHandle(file_); - file_ = INVALID_HANDLE_VALUE; - return false; - } - report_length_ = kReportLength; - pending_ = false; - return true; - } - - void close() { - if (file_ != INVALID_HANDLE_VALUE) { - if (pending_) { // the driver must not write into the buffer after it is gone - CancelIoEx(file_, &overlapped_); - DWORD n = 0; - GetOverlappedResult(file_, &overlapped_, &n, TRUE); - } - CloseHandle(file_); - file_ = INVALID_HANDLE_VALUE; - } - if (overlapped_.hEvent) CloseHandle(overlapped_.hEvent); - overlapped_ = OVERLAPPED{}; - pending_ = false; - have_ = false; - } - - HANDLE file_ = INVALID_HANDLE_VALUE; - OVERLAPPED overlapped_{}; - uint8_t buffer_[kReportLength] = {}; - DWORD report_length_ = kReportLength; - bool pending_ = false; - bool have_ = false; - PadState state_{}; - Clock::time_point retry_at_{}; -}; - -// XInput pads (xinput1_4, or xinput9_1_0 where it is missing), the keyboard while this process has focus. -class HostSource final : public Source { -public: - HostSource() { - HMODULE x = LoadLibraryExW(L"xinput1_4.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); - if (!x) x = LoadLibraryExW(L"xinput9_1_0.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); - if (x) { - get_state_ = reinterpret_cast(reinterpret_cast(GetProcAddress(x, "XInputGetState"))); - set_state_ = reinterpret_cast(reinterpret_cast(GetProcAddress(x, "XInputSetState"))); - } - if (!get_state_) std::fprintf(stderr, "[rt] gameinput: no XInput on this host: no XInput pads\n"); - } - - bool pad(int slot, PadState* out) override { - if (!get_state_) return false; - const Clock::time_point now = Clock::now(); - // Asking XInput about an empty slot is slow; look again once a second. - if (now < empty_until_[slot]) return false; - XINPUT_STATE state{}; - if (get_state_(static_cast(slot), &state) != ERROR_SUCCESS) { - empty_until_[slot] = now + std::chrono::seconds(1); - return false; - } - empty_until_[slot] = {}; - *out = convert(state.Gamepad); - return true; - } - - bool native_pad(PadState* out) override { return dualsense_.poll(out); } - - std::vector keys() override { - std::vector down; - if (!focused()) return down; - // Left/right modifier keys only, as devices report them (not VK_SHIFT/CONTROL/MENU); no mouse buttons. - for (int vk = 0x08; vk <= 0xFE; ++vk) { - if (vk >= 0x10 && vk <= 0x12) continue; - if (GetAsyncKeyState(vk) >= 0) continue; - KeyState k; - k.scan_code = MapVirtualKeyW(static_cast(vk), MAPVK_VK_TO_VSC_EX); - k.virtual_key = static_cast(vk); - down.push_back(k); - } - return down; - } - - void rumble(int slot, uint16_t low, uint16_t high) override { - if (!set_state_) return; - XINPUT_VIBRATION v{low, high}; - set_state_(static_cast(slot), &v); // an empty slot just fails - } - - // Raw values, no dead zone: titles apply their own. - static PadState convert(const XINPUT_GAMEPAD& g) { - struct Map { - WORD host; - uint32_t bit; - }; - static constexpr Map kButtons[] = { - {XINPUT_GAMEPAD_START, GameInputGamepadMenu}, - {XINPUT_GAMEPAD_BACK, GameInputGamepadView}, - {XINPUT_GAMEPAD_A, GameInputGamepadA}, - {XINPUT_GAMEPAD_B, GameInputGamepadB}, - {XINPUT_GAMEPAD_X, GameInputGamepadX}, - {XINPUT_GAMEPAD_Y, GameInputGamepadY}, - {XINPUT_GAMEPAD_DPAD_UP, GameInputGamepadDPadUp}, - {XINPUT_GAMEPAD_DPAD_DOWN, GameInputGamepadDPadDown}, - {XINPUT_GAMEPAD_DPAD_LEFT, GameInputGamepadDPadLeft}, - {XINPUT_GAMEPAD_DPAD_RIGHT, GameInputGamepadDPadRight}, - {XINPUT_GAMEPAD_LEFT_SHOULDER, GameInputGamepadLeftShoulder}, - {XINPUT_GAMEPAD_RIGHT_SHOULDER, GameInputGamepadRightShoulder}, - {XINPUT_GAMEPAD_LEFT_THUMB, GameInputGamepadLeftThumbstick}, - {XINPUT_GAMEPAD_RIGHT_THUMB, GameInputGamepadRightThumbstick}, - }; - auto stick = [](SHORT v) { return std::max(-1.0f, static_cast(v) / 32767.0f); }; - PadState s{}; - for (const Map& m : kButtons) - if (g.wButtons & m.host) s.buttons |= m.bit; - s.leftTrigger = static_cast(g.bLeftTrigger) / 255.0f; - s.rightTrigger = static_cast(g.bRightTrigger) / 255.0f; - s.leftThumbstickX = stick(g.sThumbLX); - s.leftThumbstickY = stick(g.sThumbLY); - s.rightThumbstickX = stick(g.sThumbRX); - s.rightThumbstickY = stick(g.sThumbRY); - return s; - } - -private: - using GetState = DWORD(WINAPI*)(DWORD, XINPUT_STATE*); - using SetState = DWORD(WINAPI*)(DWORD, XINPUT_VIBRATION*); - GetState get_state_ = nullptr; - SetState set_state_ = nullptr; - Clock::time_point empty_until_[kPads] = {}; - DualSense dualsense_; -}; - -// The process's hub, polled by a thread of its own from the first GameInputCreate on. -Hub& instance() { - static Hub* hub = [] { - const bool stand_in_on = !env_is("LEONIDA_KEYBOARD_PAD", "off") && !env_is("LEONIDA_KEYBOARD_PAD", "0"); - auto* h = new Hub(std::make_unique(), stand_in_on); - std::fprintf(stderr, "[rt] gameinput: XInput, wired DualSense and keyboard%s (no SDL3 shim in this build)\n", - stand_in_on ? ", with the keyboard pad" : ""); - h->poll(); - std::thread([h] { - for (;;) { - std::this_thread::sleep_for(kPollPeriod); - h->poll(); - } - }).detach(); - return h; - }(); - return *hub; -} - -// LEONIDA_GAMEINPUT=host: the host's GameInput.dll, as the loader bound it before this shim existed. -GameInputCreateFn host_create() { - static const GameInputCreateFn create = []() -> GameInputCreateFn { - HMODULE m = LoadLibraryExW(L"GameInput.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); - auto fn = m ? reinterpret_cast(reinterpret_cast(GetProcAddress(m, "GameInputCreate"))) - : nullptr; - std::fprintf(stderr, "[rt] gameinput: LEONIDA_GAMEINPUT=host: %s\n", - fn ? "the host's GameInput.dll" : "no host GameInput.dll; using the shim"); - return fn; - }(); - return create; -} - -// HRESULT GameInputCreate(IGameInput** gameInput): the one hub, static and shared. -HRESULT WINAPI GameInputCreate(IGameInput** out) { - if (!out) return E_INVALIDARG; - if (env_is("LEONIDA_GAMEINPUT", "host")) - if (const GameInputCreateFn create = host_create()) return create(out); - *out = &instance(); - return S_OK; -} - -#endif // _WIN32 - -} // namespace - -PadState stand_in(const std::vector& keys) { - struct Map { - uint8_t vk; - uint32_t bit; - }; - static constexpr Map kButtons[] = { - {0x1B, GameInputGamepadMenu}, // Esc - {0x09, GameInputGamepadView}, // Tab - {0x0D, GameInputGamepadA}, // Enter - {0x08, GameInputGamepadB}, // Backspace - {'X', GameInputGamepadX}, - {'Y', GameInputGamepadY}, - {0x26, GameInputGamepadDPadUp}, // arrows - {0x28, GameInputGamepadDPadDown}, - {0x25, GameInputGamepadDPadLeft}, - {0x27, GameInputGamepadDPadRight}, - {'Q', GameInputGamepadLeftShoulder}, - {'E', GameInputGamepadRightShoulder}, - {'F', GameInputGamepadLeftThumbstick}, - {'H', GameInputGamepadRightThumbstick}, - }; - auto on = [&](uint8_t vk) { - return std::any_of(keys.begin(), keys.end(), [vk](const KeyState& k) { return k.virtual_key == vk; }) ? 1.0f - : 0.0f; - }; - PadState s{}; - for (const Map& m : kButtons) - if (on(m.vk) != 0.0f) s.buttons |= m.bit; - s.leftTrigger = on('Z'); - s.rightTrigger = on('C'); - s.leftThumbstickX = on('D') - on('A'); - s.leftThumbstickY = on('W') - on('S'); - s.rightThumbstickX = on('L') - on('J'); - s.rightThumbstickY = on('I') - on('K'); - return s; -} - -// The USB report begins with its id, four stick axes, two trigger axes, a sequence byte, and the hat/face and -// shoulder/system button fields. -bool decode_dualsense(const uint8_t* r, size_t size, PadState* out) { - if (!r || size != 64 || r[0] != 0x01 || !out) return false; - static constexpr uint32_t kHat[8] = { - GameInputGamepadDPadUp, - GameInputGamepadDPadUp | GameInputGamepadDPadRight, - GameInputGamepadDPadRight, - GameInputGamepadDPadDown | GameInputGamepadDPadRight, - GameInputGamepadDPadDown, - GameInputGamepadDPadDown | GameInputGamepadDPadLeft, - GameInputGamepadDPadLeft, - GameInputGamepadDPadUp | GameInputGamepadDPadLeft, - }; - static constexpr std::pair kBits[] = { - {4, GameInputGamepadX}, - {5, GameInputGamepadA}, - {6, GameInputGamepadB}, - {7, GameInputGamepadY}, - {8, GameInputGamepadLeftShoulder}, - {9, GameInputGamepadRightShoulder}, - {12, GameInputGamepadView}, - {13, GameInputGamepadMenu}, - {14, GameInputGamepadLeftThumbstick}, - {15, GameInputGamepadRightThumbstick}, - }; - auto axis = [](uint8_t v) { return std::max(-1.0f, (static_cast(v) - 128.0f) / 127.0f); }; - const uint8_t face = r[8], shoulders = r[9]; - PadState s{}; - if ((face & 0xF) < 8) s.buttons = kHat[face & 0xF]; - const uint32_t bits = face | static_cast(shoulders) << 8; - for (const auto& [host, title] : kBits) - if (bits & (1u << host)) s.buttons |= title; - s.leftTrigger = static_cast(r[5]) / 255.0f; - s.rightTrigger = static_cast(r[6]) / 255.0f; - s.leftThumbstickX = axis(r[1]); - s.leftThumbstickY = -axis(r[2]); - s.rightThumbstickX = axis(r[3]); - s.rightThumbstickY = -axis(r[4]); - *out = s; - return true; -} - -IGameInput* create_hub(std::unique_ptr source, bool stand_in_on) { - auto* hub = new Hub(std::move(source), stand_in_on); - hub->poll(); - return hub; -} - -void poll(IGameInput* hub) { static_cast(hub)->poll(); } - -IGameInputDevice* device(IGameInput* hub, int index) { return static_cast(hub)->device(index); } - -} // namespace rt::gameinput_xinput - -#ifdef _WIN32 -// Titles import GameInputCreate by ordinal only (VIctory); the name is registered too, as gameinput.cpp does. -SHIM_TABLE(gameinput_xinput, - {"gameinput.dll", "GameInputCreate", reinterpret_cast(&rt::gameinput_xinput::GameInputCreate)}, - {"gameinput.dll", "#1", reinterpret_cast(&rt::gameinput_xinput::GameInputCreate)}, - {"xgameruntime.dll", "GameInputCreate", reinterpret_cast(&rt::gameinput_xinput::GameInputCreate)}, -); -#endif diff --git a/runtime/shims/gameinput_xinput.h b/runtime/shims/gameinput_xinput.h deleted file mode 100644 index b03efd824..000000000 --- a/runtime/shims/gameinput_xinput.h +++ /dev/null @@ -1,62 +0,0 @@ -// GameInput without SDL3: XInput pads, a wired DualSense, the keyboard, and a stand-in pad the keyboard drives. -// Ported from VIctory (crates/victory-hle/src/modules/gameinput.rs, gameinput/dualsense.rs), GPL-3.0-or-later; see -// gameinput_xinput.cpp. Built into gta6rt when the SDL3 shim (gameinput.cpp) is not. These are its test seams. -#pragma once -#include -#include -#include -#include - -#include "gameinput_abi.h" - -namespace rt::gameinput_xinput { - -using PadState = gi::GameInputGamepadState; - -// GameInputKeyState (v0): one key held down. The scan code is 0xE0xx for an extended key; no characters are -// reported (code point 0), as in VIctory: the title reads scan codes and virtual keys. -struct KeyState { - uint32_t scan_code = 0; - uint32_t code_point = 0; - uint8_t virtual_key = 0; - bool dead_key = false; -}; -static_assert(sizeof(KeyState) == 12); - -// Device indices: XInput slots 0-3, the keyboard's stand-in pad, the keyboard, a wired DualSense. -constexpr int kPads = 4; -constexpr int kStandIn = kPads; -constexpr int kKeyboard = kPads + 1; -constexpr int kDualSense = kPads + 2; -constexpr int kDevices = kPads + 3; - -// Host input, or a fake in tests. Called on the poll thread with the source lock held. -class Source { -public: - virtual ~Source() = default; - // The pad in XInput slot `slot`; false when the slot is empty. - virtual bool pad(int slot, PadState* out) = 0; - // A pad of our own (a wired DualSense), asked only when no XInput slot holds one. - virtual bool native_pad(PadState*) { return false; } - // Keys held down; none while no window of this process has focus. - virtual std::vector keys() = 0; - // Motor speeds of an XInput pad: low frequency (left), high frequency (right). - virtual void rumble(int slot, uint16_t low, uint16_t high) = 0; -}; - -// The stand-in pad for the keys held: Esc Menu, Tab View, Enter A, Backspace B, X, Y, arrows the d-pad, Q/E the -// shoulders, F/H the stick clicks; W/A/S/D the left stick, I/J/K/L the right one; Z and C the triggers. -PadState stand_in(const std::vector& keys); - -// A wired DualSense's USB input report (64 bytes with report id 1); false for anything else. -bool decode_dualsense(const uint8_t* report, size_t size, PadState* out); - -// A hub over `source` that no thread polls: a test calls poll(). `stand_in` false leaves the keyboard's pad out. -// Never freed, like the process's own hub. -gi::IGameInput* create_hub(std::unique_ptr source, bool stand_in = true); -// Reads the source once and runs device callbacks on the calling thread. -void poll(gi::IGameInput* hub); -// The hub's device `index` (above). -gi::IGameInputDevice* device(gi::IGameInput* hub, int index); - -} // namespace rt::gameinput_xinput diff --git a/runtime/shims/library_loader.cpp b/runtime/shims/library_loader.cpp index f0a86221f..3a96092df 100644 --- a/runtime/shims/library_loader.cpp +++ b/runtime/shims/library_loader.cpp @@ -14,7 +14,6 @@ // loader see these: they are bound through the registry, the runtime's own code calls the host directly. #include -#include #include #include #include @@ -202,12 +201,8 @@ HMODULE WINAPI load_library_ex_w(LPCWSTR name, HANDLE file, DWORD flags) { } // GetModuleHandle answers for an owned module as if it were loaded (the GDK may probe before it loads), and for any -// bundled package module already mapped by the native loader. NULL names the title's main image once main.cpp has -// set it (VIctory victory-hle src/modules/kernel.rs, GPL-3.0-or-later: "GetModuleHandleW(NULL) must return the -// title's image, not our exe"), as the console's loader would answer: the title's process is its own. +// bundled package module already mapped by the native loader. HMODULE WINAPI get_module_handle_a(LPCSTR name) { - if (!name) - if (void* main = main_image()) return static_cast(main); if (name) { if (HMODULE h = owned_handle(name)) return h; const std::string dll = module_name(name); @@ -218,8 +213,6 @@ HMODULE WINAPI get_module_handle_a(LPCSTR name) { } HMODULE WINAPI get_module_handle_w(LPCWSTR name) { - if (!name) - if (void* main = main_image()) return static_cast(main); if (name) { if (ascii_basename(name)) { const std::string path = narrow(name); @@ -284,49 +277,6 @@ FARPROC WINAPI get_proc_address(HMODULE module, LPCSTR name) { return GetProcAddress(module, name); } -// GetModuleFileName of a mapped image (NULL: the main image, once set) is the file it was mapped from, the title's -// own path, not gta6rt.exe's; Windows cannot answer for an image it did not map (ERROR_MOD_NOT_FOUND). Ported from -// VIctory kernel.rs: the title relaunches itself and finds its folder through this path. The copy follows -// Windows' rules: a buffer too small gets the truncated, terminated path, the return value `size` and -// ERROR_INSUFFICIENT_BUFFER; otherwise the length without the terminator. -bool mapped_module_path(HMODULE module, std::wstring& path) { - void* const base = module ? static_cast(module) : main_image(); - return base && bundled_module_path(base, path); -} - -template DWORD copy_module_path(const std::basic_string& path, Char* out, DWORD size) { - if (!out || size == 0) { - SetLastError(ERROR_INSUFFICIENT_BUFFER); - return 0; - } - if (path.size() >= size) { - std::copy_n(path.data(), size - 1, out); - out[size - 1] = 0; - SetLastError(ERROR_INSUFFICIENT_BUFFER); - return size; - } - std::copy_n(path.data(), path.size(), out); - out[path.size()] = 0; - SetLastError(ERROR_SUCCESS); - return static_cast(path.size()); -} - -DWORD WINAPI get_module_file_name_w(HMODULE module, LPWSTR out, DWORD size) { - std::wstring path; - if (!mapped_module_path(module, path)) return GetModuleFileNameW(module, out, size); - return copy_module_path(path, out, size); -} - -DWORD WINAPI get_module_file_name_a(HMODULE module, LPSTR out, DWORD size) { - std::wstring path; - if (!mapped_module_path(module, path)) return GetModuleFileNameA(module, out, size); - // In the ANSI code page, as GetModuleFileNameA gives it. - const int n = WideCharToMultiByte(CP_ACP, 0, path.c_str(), -1, nullptr, 0, nullptr, nullptr); - std::string narrow(n > 0 ? static_cast(n - 1) : 0, ' '); - if (n > 1) WideCharToMultiByte(CP_ACP, 0, path.c_str(), -1, narrow.data(), n, nullptr, nullptr); - return copy_module_path(narrow, out, size); -} - BOOL WINAPI free_library(HMODULE module) { if (pseudo(module)) return TRUE; // owned modules are never unloaded if (owns_bundled_module_handle(module)) return TRUE; // mapped modules stay live until ~Loader detaches them @@ -353,7 +303,7 @@ BOOL WINAPI disable_thread_calls(HMODULE module) { {dll, "GetModuleHandleW", reinterpret_cast(&rt::shims::library_loader::get_module_handle_w)}, \ {dll, "GetProcAddress", reinterpret_cast(&rt::shims::library_loader::get_proc_address)}, \ {dll, "FreeLibrary", reinterpret_cast(&rt::shims::library_loader::free_library)}, \ - {dll, "DisableThreadLibraryCalls", reinterpret_cast(&rt::shims::library_loader::disable_thread_calls)}, {dll, "GetModuleFileNameA", reinterpret_cast(&rt::shims::library_loader::get_module_file_name_a)}, {dll, "GetModuleFileNameW", reinterpret_cast(&rt::shims::library_loader::get_module_file_name_w)} + {dll, "DisableThreadLibraryCalls", reinterpret_cast(&rt::shims::library_loader::disable_thread_calls)} } // namespace } // namespace rt::shims::library_loader diff --git a/runtime/shims/media_foundation.cpp b/runtime/shims/media_foundation.cpp deleted file mode 100644 index b810ebe2f..000000000 --- a/runtime/shims/media_foundation.cpp +++ /dev/null @@ -1,357 +0,0 @@ -// mfplat.dll: Media Foundation is the host's (the title's other mfplat imports bind to it), except the source -// resolver. The host's resolver would fetch http, rtsp and other URLs over the network; the title gets a proxy that -// opens local files only, with console paths (GAME:, G:, T:) rewritten to their host files, and forwards everything -// else to the host's resolver. -// -// Ported from VIctory (crates/victory-hle/src/modules/media.rs), GPL-3.0-or-later, by Marvisak and contributors -// (DexNom fork). Leonida is GPL-3.0-or-later. VIctory's URL rule, slot order and refusal (MF_E_UNSUPPORTED_SCHEME, -// logged once per scheme and host) are kept. Differences: console paths are Leonida's (rt::fs::read_path, which -// knows GAME: as well as the G: and T: drive letters) rather than VIctory's virtual drives, and a GAME: path is a -// local path, not a URL scheme. QueryInterface answers only the resolver's own interfaces, as in VIctory: anything -// else could hand out the host object unguarded. -// -// Not covered, as in VIctory: CreateObjectFromByteStream and its async pair pass through (the URL is only a hint for -// picking a handler; the title's own byte stream holds the data), and so does a title that loads mfplat.dll at run -// time and calls the host's MFCreateSourceResolver through a pointer it got elsewhere than GetProcAddress -// (library_loader's GetProcAddress serves this shim's name for the host module too). -#include "media_foundation.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "file_system.h" -#include "shims.h" - -namespace rt::media { -namespace { - -constexpr HRESULT kUnsupportedScheme = static_cast(0xC00D36C3u); // MF_E_UNSUPPORTED_SCHEME - -constexpr GUID kIUnknown = {0x00000000, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}}; -constexpr GUID kIResolver = {0xFBE5A32D, 0xA497, 0x4B61, {0xBB, 0x85, 0x97, 0xB1, 0xA8, 0x48, 0xA6, 0xE3}}; - -bool is_alpha(wchar_t c) { return (c >= L'a' && c <= L'z') || (c >= L'A' && c <= L'Z'); } -bool is_alnum(wchar_t c) { return is_alpha(c) || (c >= L'0' && c <= L'9'); } -wchar_t lower(wchar_t c) { return c >= L'A' && c <= L'Z' ? static_cast(c + 32) : c; } - -bool starts_with(const std::wstring& s, const wchar_t* prefix) { return s.rfind(prefix, 0) == 0; } - -bool drive(const std::wstring& s) { return s.size() >= 2 && is_alpha(s[0]) && s[1] == L':'; } - -// "GAME:" in any case: a console path, not a URL scheme. -bool console(const std::wstring& s) { - static const wchar_t kGame[] = L"game:"; - if (s.size() < 5) return false; - for (size_t i = 0; i < 5; ++i) - if (lower(s[i]) != kGame[i]) return false; - return true; -} - -// UTF-16 to UTF-8 and back, by hand so this stays portable; unpaired surrogates become U+FFFD. -std::string utf8(const std::wstring& w) { - std::string out; - for (size_t i = 0; i < w.size(); ++i) { - uint32_t c = static_cast(w[i]); - if (c >= 0xD800 && c <= 0xDBFF && i + 1 < w.size() && w[i + 1] >= 0xDC00 && w[i + 1] <= 0xDFFF) - c = 0x10000 + ((c - 0xD800) << 10) + (static_cast(w[++i]) - 0xDC00); - else if (c >= 0xD800 && c <= 0xDFFF) - c = 0xFFFD; - if (c < 0x80) { - out += static_cast(c); - } else if (c < 0x800) { - out += static_cast(0xC0 | (c >> 6)); - out += static_cast(0x80 | (c & 0x3F)); - } else if (c < 0x10000) { - out += static_cast(0xE0 | (c >> 12)); - out += static_cast(0x80 | ((c >> 6) & 0x3F)); - out += static_cast(0x80 | (c & 0x3F)); - } else { - out += static_cast(0xF0 | (c >> 18)); - out += static_cast(0x80 | ((c >> 12) & 0x3F)); - out += static_cast(0x80 | ((c >> 6) & 0x3F)); - out += static_cast(0x80 | (c & 0x3F)); - } - } - return out; -} - -std::wstring utf16(const std::string& s) { - std::wstring out; - for (size_t i = 0; i < s.size();) { - const auto b = static_cast(s[i]); - const size_t n = b < 0x80 ? 1 : (b >> 5) == 6 ? 2 : (b >> 4) == 14 ? 3 : (b >> 3) == 30 ? 4 : 0; - uint32_t c = n == 1 ? b : n == 2 ? (b & 0x1F) : n == 3 ? (b & 0x0F) : (b & 0x07); - bool ok = n != 0 && i + n <= s.size(); - for (size_t k = 1; ok && k < n; ++k) { - const auto t = static_cast(s[i + k]); - ok = (t >> 6) == 2; - c = (c << 6) | (t & 0x3F); - } - if (!ok) { - out += L'\xFFFD'; - ++i; - continue; - } - i += n; - if (c >= 0x10000) { - c -= 0x10000; - out += static_cast(0xD800 + (c >> 10)); - out += static_cast(0xDC00 + (c & 0x3FF)); - } else { - out += static_cast(c); - } - } - return out; -} - -// %XX escapes decoded as UTF-8 bytes; a % without two hex digits stays as it is. -std::wstring percent_decode(const std::wstring& s) { - const std::string bytes = utf8(s); - std::string out; - auto hex = [](char c) -> int { - return c >= '0' && c <= '9' ? c - '0' : c >= 'a' && c <= 'f' ? c - 'a' + 10 : c >= 'A' && c <= 'F' ? c - 'A' + 10 : -1; - }; - for (size_t i = 0; i < bytes.size(); ++i) { - if (bytes[i] == '%' && i + 2 < bytes.size() && hex(bytes[i + 1]) >= 0 && hex(bytes[i + 2]) >= 0) { - out += static_cast(hex(bytes[i + 1]) * 16 + hex(bytes[i + 2])); - i += 2; - } else { - out += bytes[i]; - } - } - return utf16(out); -} - -std::string host_of(const std::wstring& rest) { - const size_t end = rest.find_first_of(L"/\\"); - return utf8(rest.substr(0, end)); -} - -// A local path to hand the host: a console path becomes its host file; anything else, or a refused console path -// (which the host then fails to open), passes as it is. -std::wstring translated(const std::wstring& path) { - std::filesystem::path host; - if (rt::fs::read_path(path, host)) return host.wstring(); - return path; -} - -} // namespace - -bool local_url(const std::wstring& url, std::wstring& out, std::string& scheme, std::string& host) { - std::wstring path; - if (starts_with(url, L"\\\\?\\")) { - std::wstring rest = url.substr(4); - if (!drive(rest)) { - if (starts_with(rest, L"UNC\\")) rest = rest.substr(4); - scheme = "unc"; - host = host_of(rest); - return false; - } - path = url; - } else if (starts_with(url, L"\\\\") || starts_with(url, L"//")) { - scheme = "unc"; - host = host_of(url.substr(2)); - return false; - } else if (drive(url) || console(url)) { - path = url; - } else if (const size_t colon = url.find(L':'); colon != std::wstring::npos && colon > 1 && - [&] { - for (size_t i = 0; i < colon; ++i) - if (!is_alnum(url[i]) && url[i] != L'+' && url[i] != L'-' && url[i] != L'.') return false; - return true; - }()) { - std::wstring s; - for (size_t i = 0; i < colon; ++i) s += lower(url[i]); - const std::wstring rest = url.substr(colon + 1); - const bool authority = starts_with(rest, L"//"); - if (s != L"file") { - scheme = utf8(s); - host = authority ? host_of(rest.substr(2)) : std::string(); - return false; - } - std::wstring after = rest; - if (authority) { - const std::wstring a = rest.substr(2); - const size_t end = a.find_first_of(L"/\\"); - const std::wstring name = a.substr(0, end); - std::wstring lowered; - for (wchar_t c : name) lowered += lower(c); - if (!name.empty() && lowered != L"localhost") { - scheme = "file"; - host = utf8(name); - return false; - } - after = end == std::wstring::npos ? std::wstring() : a.substr(end); - } - const size_t first = after.find_first_not_of(L"/\\"); - path = percent_decode(first == std::wstring::npos ? std::wstring() : after.substr(first)); - for (wchar_t& c : path) - if (c == L'/') c = L'\\'; - if (!drive(path) && !console(path)) { - out = url; // a local file without a drive: the host resolves it as is - return true; - } - } else { - out = url; // a relative path - return true; - } - out = translated(path); - return true; -} - -namespace { - -// The host's IMFSourceResolver behind the proxy, called through its method table. -template -F method(void* host, size_t slot) { - return reinterpret_cast((*static_cast(host))[slot]); -} - -struct Resolver { - const void* const* vtable; - void* host; - std::atomic refs{1}; -}; - -void* host_resolver(void* self) { return static_cast(self)->host; } - -// The URL to give the host, or the refusal (logged once per scheme and host). -HRESULT checked(const wchar_t* url, std::wstring& out) { - if (!url) return E_POINTER; - std::string scheme, host; - if (local_url(url, out, scheme, host)) return S_OK; - static std::mutex mu; - static std::set> refused; - std::lock_guard lock(mu); - if (refused.emplace(scheme, host).second) - std::fprintf(stderr, "[rt] media: refused a URL that is not a local file (scheme %s, host %s)\n", - scheme.c_str(), host.empty() ? "none" : host.c_str()); - return kUnsupportedScheme; -} - -ULONG STDMETHODCALLTYPE add_ref(void* self) { return ++static_cast(self)->refs; } - -ULONG STDMETHODCALLTYPE release(void* self) { - auto* r = static_cast(self); - const ULONG left = --r->refs; - if (left == 0) { - method(r->host, 2)(r->host); // the host's Release - delete r; - } - return left; -} - -HRESULT STDMETHODCALLTYPE query_interface(void* self, REFIID iid, void** out) { - if (!out) return E_POINTER; - if (iid == kIUnknown || iid == kIResolver) { - *out = self; - add_ref(self); - return S_OK; - } - *out = nullptr; - return E_NOINTERFACE; -} - -// 3: CreateObjectFromURL(url, flags, props, MF_OBJECT_TYPE* type, IUnknown** object) -HRESULT STDMETHODCALLTYPE create_from_url(void* self, const wchar_t* url, DWORD flags, void* props, DWORD* type, - void** object) { - std::wstring local; - if (const HRESULT hr = checked(url, local); hr != S_OK) { - if (object) *object = nullptr; - return hr; - } - void* h = host_resolver(self); - return method(h, 3)( - h, local.c_str(), flags, props, type, object); -} - -// 4: CreateObjectFromByteStream(stream, url, flags, props, type, object): the URL is only a hint. -HRESULT STDMETHODCALLTYPE create_from_stream(void* self, void* stream, const wchar_t* url, DWORD flags, void* props, - DWORD* type, void** object) { - void* h = host_resolver(self); - return method(h, 4)( - h, stream, url, flags, props, type, object); -} - -// 5: BeginCreateObjectFromURL(url, flags, props, IUnknown** cancel, callback, state) -HRESULT STDMETHODCALLTYPE begin_from_url(void* self, const wchar_t* url, DWORD flags, void* props, void** cancel, - void* callback, void* state) { - std::wstring local; - if (const HRESULT hr = checked(url, local); hr != S_OK) { - if (cancel) *cancel = nullptr; - return hr; - } - void* h = host_resolver(self); - return method(h, 5)( - h, local.c_str(), flags, props, cancel, callback, state); -} - -// 6: EndCreateObjectFromURL(result, type, object); 8: EndCreateObjectFromByteStream, the same shape. -template -HRESULT STDMETHODCALLTYPE end_create(void* self, void* result, DWORD* type, void** object) { - void* h = host_resolver(self); - return method(h, Slot)(h, result, type, object); -} - -// 7: BeginCreateObjectFromByteStream(stream, url, flags, props, cancel, callback, state) -HRESULT STDMETHODCALLTYPE begin_from_stream(void* self, void* stream, const wchar_t* url, DWORD flags, void* props, - void** cancel, void* callback, void* state) { - void* h = host_resolver(self); - return method(h, 7)( - h, stream, url, flags, props, cancel, callback, state); -} - -// 9: CancelObjectCreation(cancel) -HRESULT STDMETHODCALLTYPE cancel(void* self, void* cookie) { - void* h = host_resolver(self); - return method(h, 9)(h, cookie); -} - -const void* const kVtable[] = { - reinterpret_cast(&query_interface), reinterpret_cast(&add_ref), - reinterpret_cast(&release), reinterpret_cast(&create_from_url), - reinterpret_cast(&create_from_stream), reinterpret_cast(&begin_from_url), - reinterpret_cast(&end_create<6>), reinterpret_cast(&begin_from_stream), - reinterpret_cast(&end_create<8>), reinterpret_cast(&cancel), -}; -static_assert(sizeof kVtable / sizeof kVtable[0] == 10, "IUnknown + IMFSourceResolver's 7 methods"); - -// HRESULT MFCreateSourceResolver(IMFSourceResolver** resolver): the host's resolver behind the proxy. -HRESULT WINAPI MFCreateSourceResolver(void** out) { - if (!out) return E_POINTER; - using Create = HRESULT(WINAPI*)(void**); - static const Create create = []() -> Create { - HMODULE m = LoadLibraryExW(L"mfplat.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); - return m ? reinterpret_cast(reinterpret_cast(GetProcAddress(m, "MFCreateSourceResolver"))) - : nullptr; - }(); - if (!create) return kUnsupportedScheme; // no Media Foundation on this host (VIctory's answer) - void* host = nullptr; - const HRESULT hr = create(&host); - if (FAILED(hr) || !host) return hr; - return wrap_resolver(host, out); -} - -} // namespace - -long wrap_resolver(void* host_resolver, void** out) { - if (!out) return E_POINTER; - if (!host_resolver) return E_INVALIDARG; - *out = new Resolver{kVtable, host_resolver}; - return S_OK; -} - -} // namespace rt::media - -SHIM_TABLE(media_foundation, - {"mfplat.dll", "MFCreateSourceResolver", reinterpret_cast(&rt::media::MFCreateSourceResolver)}, -); diff --git a/runtime/shims/media_foundation.h b/runtime/shims/media_foundation.h deleted file mode 100644 index 2b6896d21..000000000 --- a/runtime/shims/media_foundation.h +++ /dev/null @@ -1,17 +0,0 @@ -// mfplat.dll: Media Foundation is the host's, except the source resolver, which opens local files only. See -// media_foundation.cpp. These are its test seams. -#pragma once -#include - -namespace rt::media { - -// Where a resolver may read `url` from. True with `out` the path or URL to hand the host resolver: a console path -// (GAME:, G:, T:) or a file: URL naming one becomes its host file, other local files pass as they are. False for -// anything that is not a local file (a network scheme, a UNC share, a file: URL with a host), with the scheme -// ("unc" for a share) and host named for the log. -bool local_url(const std::wstring& url, std::wstring& out, std::string& scheme, std::string& host); - -// Wraps a host IMFSourceResolver (one reference taken over) in the guarding proxy, as MFCreateSourceResolver does. -long wrap_resolver(void* host_resolver, void** out); - -} // namespace rt::media diff --git a/runtime/shims/process.cpp b/runtime/shims/process.cpp index aa33fe750..2c37292e2 100644 --- a/runtime/shims/process.cpp +++ b/runtime/shims/process.cpp @@ -21,7 +21,6 @@ // umbrella libraries a GDK title links (OneCore_apiset.lib, mincore.lib) bind them to. The retail package's own DLLs // import ExitProcess from api-ms-win-core-processthreads-l1-1-0.dll. #include -#include #include #include @@ -514,52 +513,6 @@ int run_entry(void* entry, size_t stack_bytes) { namespace { using namespace rt::process; - -// The title's debug output goes to the log, as VIctory's kernel.rs OutputDebugStringA/W do (GPL-3.0-or-later): no -// debugger needs to be attached to read what the title says about itself. "[title] ", one line per call, the -// trailing newline dropped; LEONIDA_TITLE_DEBUG_OUTPUT=0 silences it. The host's function still gets the text, so an -// attached debugger sees it as before. -bool title_debug_output_on() { - static const bool on = [] { - char v[8] = {}; - const DWORD n = GetEnvironmentVariableA("LEONIDA_TITLE_DEBUG_OUTPUT", v, sizeof(v)); - return !(n > 0 && n < sizeof(v) && v[0] == '0'); - }(); - return on; -} -void log_title_text(std::string text) { - while (!text.empty() && (text.back() == '\n' || text.back() == '\r')) text.pop_back(); - std::fprintf(stderr, "[title] %s\n", text.c_str()); -} -void WINAPI game_output_debug_string_a(LPCSTR text) { - if (text && title_debug_output_on()) log_title_text(text); - OutputDebugStringA(text); -} -void WINAPI game_output_debug_string_w(LPCWSTR text) { - if (text && title_debug_output_on()) { - const int n = WideCharToMultiByte(CP_UTF8, 0, text, -1, nullptr, 0, nullptr, nullptr); - std::string utf8(n > 1 ? static_cast(n - 1) : 0, ' '); - if (n > 1) WideCharToMultiByte(CP_UTF8, 0, text, -1, utf8.data(), n, nullptr, nullptr); - log_title_text(std::move(utf8)); - } - OutputDebugStringW(text); -} - -// TerminateProcess of the game's own process ends gta6rt without a word otherwise; it is logged with its code and -// caller first (VIctory kernel.rs TerminateProcess), then done as asked. -BOOL WINAPI game_terminate_process(HANDLE process, UINT code) { - if (process == GetCurrentProcess() || GetProcessId(process) == GetCurrentProcessId()) { - std::fprintf(stderr, "[rt] process: the game called TerminateProcess(code %u) from %s\n", code, - rt::shims::module_offset(reinterpret_cast(_ReturnAddress())).c_str()); - std::fflush(nullptr); - } - return TerminateProcess(process, code); -} - -#define DEBUG_OUTPUT(dll) \ - {dll, "OutputDebugStringA", reinterpret_cast(&game_output_debug_string_a)}, \ - {dll, "OutputDebugStringW", reinterpret_cast(&game_output_debug_string_w)} -#define TERMINATE_PROCESS(dll) {dll, "TerminateProcess", reinterpret_cast(&game_terminate_process)} #define UCRT(dll) \ {dll, "exit", reinterpret_cast(&game_exit)}, {dll, "_exit", reinterpret_cast(&game_quick_exit)}, \ {dll, "_Exit", reinterpret_cast(&game_quick_exit)}, \ @@ -619,12 +572,5 @@ SHIM_TABLE(process, POOL_AFFINITY("kernelbase.dll"), COMMAND_LINE("kernel32.dll"), COMMAND_LINE("kernelbase.dll"), - DEBUG_OUTPUT("kernel32.dll"), - DEBUG_OUTPUT("kernelbase.dll"), - DEBUG_OUTPUT("api-ms-win-core-debug-l1-1-0.dll"), - DEBUG_OUTPUT("api-ms-win-core-debug-l1-1-1.dll"), - TERMINATE_PROCESS("kernel32.dll"), - TERMINATE_PROCESS("kernelbase.dll"), - TERMINATE_PROCESS("api-ms-win-core-processthreads-l1-1-0.dll"), COMMAND_LINE("api-ms-win-core-processenvironment-l1-1-0.dll"), ); diff --git a/runtime/shims/registry_oem.cpp b/runtime/shims/registry_oem.cpp deleted file mode 100644 index 645db1336..000000000 --- a/runtime/shims/registry_oem.cpp +++ /dev/null @@ -1,102 +0,0 @@ -// The console model, as the title reads it from the registry. -// -// Ported from VIctory's crates/victory-hle/src/modules/xsystem.rs (its registry part; GPL-3.0-or-later, Marvisak and -// contributors, DexNom fork). Leonida is GPL-3.0-or-later. -// -// The title does not take its console model from XSystemGetDeviceType alone: its own code opens -// HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM and maps the DWORD "ConsoleMode" to a device type (VIctory -// measured 0x64 for Series X and 0x60 for Series S). A PC has no such value, so the title fell into its Series S -// path and chose the Series S render-target pool budget: with the Series X package's two 3840x2160 back buffers its -// own pool check (game_scarlett_master.exe+0x247af2d, about 2.7 s in) then stopped the title at a breakpoint. -// -// The title imports only RegOpenKeyW, RegQueryValueExW and RegCloseKey from advapi32.dll (RegOpenKeyExW is answered -// too, as VIctory does). Our key is a pseudo handle that no other call can reach; every other key and value goes to -// the host. advapi32.dll stays a host module for LoadLibrary (owns_dll in registry.cpp). -#include "shims.h" - -#include - -#include -#include -#include - -namespace { - -// Stands for the OEM key; never a host handle value. -char g_oem_marker; -HKEY oem_key() { return reinterpret_cast(&g_oem_marker); } - -constexpr const wchar_t* kOemKey = L"Software\\Microsoft\\Windows NT\\CurrentVersion\\OEM"; -constexpr const wchar_t* kConsoleMode = L"ConsoleMode"; - -bool same(const wchar_t* text, const wchar_t* expected) { return text && _wcsicmp(text, expected) == 0; } - -// What the title's code maps to each console model (VIctory xsystem.rs console_mode): Series X 0x64, Series S 0x60. -// LEONIDA_DEVICE_TYPE=6 (XboxScarlettLockhart) selects Series S here too, as it does for XSystemGetDeviceType. -DWORD console_mode() { - char s[16]; - const DWORD n = GetEnvironmentVariableA("LEONIDA_DEVICE_TYPE", s, sizeof(s)); - if (n > 0 && n < sizeof(s) && std::atoi(s) == 6) return 0x60; - return 0x64; -} - -FARPROC host_proc(const char* name) { - static const HMODULE advapi = LoadLibraryExW(L"advapi32.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); - return advapi ? GetProcAddress(advapi, name) : nullptr; -} - -// Our key for its path (the key has no subkeys); nullopt-like -1: not ours, ask the host. -LONG open_oem(HKEY root, const wchar_t* sub, HKEY* out) { - if (root == oem_key()) return ERROR_FILE_NOT_FOUND; - if (root == HKEY_LOCAL_MACHINE && same(sub, kOemKey) && out) { - *out = oem_key(); - return ERROR_SUCCESS; - } - return -1; -} - -LONG WINAPI reg_open_key_w(HKEY root, const wchar_t* sub, HKEY* out) { - if (const LONG r = open_oem(root, sub, out); r != -1) return r; - auto host = reinterpret_cast(host_proc("RegOpenKeyW")); - return host ? host(root, sub, out) : ERROR_CALL_NOT_IMPLEMENTED; -} - -LONG WINAPI reg_open_key_ex_w(HKEY root, const wchar_t* sub, DWORD options, REGSAM access, HKEY* out) { - if (const LONG r = open_oem(root, sub, out); r != -1) return r; - auto host = reinterpret_cast(host_proc("RegOpenKeyExW")); - return host ? host(root, sub, options, access, out) : ERROR_CALL_NOT_IMPLEMENTED; -} - -LONG WINAPI reg_query_value_ex_w(HKEY key, const wchar_t* name, DWORD* reserved, DWORD* kind, BYTE* data, - DWORD* size) { - if (key != oem_key()) { - auto host = reinterpret_cast(host_proc("RegQueryValueExW")); - return host ? host(key, name, reserved, kind, data, size) : ERROR_CALL_NOT_IMPLEMENTED; - } - if (!same(name, kConsoleMode)) return ERROR_FILE_NOT_FOUND; - if (data && !size) return ERROR_INVALID_PARAMETER; - if (kind) *kind = REG_DWORD; - if (!size) return ERROR_SUCCESS; - const DWORD room = *size; - *size = sizeof(DWORD); - if (!data) return ERROR_SUCCESS; - if (room < sizeof(DWORD)) return ERROR_MORE_DATA; - const DWORD mode = console_mode(); - std::memcpy(data, &mode, sizeof(mode)); - return ERROR_SUCCESS; -} - -LONG WINAPI reg_close_key(HKEY key) { - if (key == oem_key()) return ERROR_SUCCESS; - auto host = reinterpret_cast(host_proc("RegCloseKey")); - return host ? host(key) : ERROR_CALL_NOT_IMPLEMENTED; -} - -} // namespace - -SHIM_TABLE(registry_oem, - {"advapi32.dll", "RegOpenKeyW", reinterpret_cast(®_open_key_w)}, - {"advapi32.dll", "RegOpenKeyExW", reinterpret_cast(®_open_key_ex_w)}, - {"advapi32.dll", "RegQueryValueExW", reinterpret_cast(®_query_value_ex_w)}, - {"advapi32.dll", "RegCloseKey", reinterpret_cast(®_close_key)}, -); diff --git a/runtime/shims/shims.h b/runtime/shims/shims.h index 83fb671a4..a7fa7b9ce 100644 --- a/runtime/shims/shims.h +++ b/runtime/shims/shims.h @@ -69,8 +69,6 @@ struct BundledModuleOps { // (library_loader's W entries use them when a name has a character outside ASCII). Either may be null. void* (*find_loaded_w)(void* ctx, const std::wstring& basename); void* (*load_bundled_w)(void* ctx, const std::wstring& basename, uint32_t flags, bool& handled); - // The file a mapped module was mapped from, for GetModuleFileName on its handle (null: not answered). - bool (*module_path)(void* ctx, void* module, std::wstring& path); }; void add_bundled_loader(void* ctx, const BundledModuleOps* ops); void remove_bundled_loader(void* ctx); @@ -81,13 +79,6 @@ void* find_loaded_bundled_module_w(const std::wstring& basename); void* load_bundled_module_w(const std::wstring& basename, uint32_t flags, bool& handled); void* get_bundled_proc_address(void* module, const std::string& sym, bool& owns_handle); bool owns_bundled_module_handle(void* module); -// The file a live Loader mapped `module` from (its original path in the game folder); false for any other handle. -bool bundled_module_path(void* module, std::wstring& path); - -// The title's main image, which GetModuleHandle(NULL) and GetModuleFileName(NULL) answer with in mapped code, as the -// console's loader would (VIctory victory-hle src/modules/kernel.rs). Null until set: those calls then reach the host. -void set_main_image(void* base); -void* main_image(); // Title-exported __XMemAllocationHooks__ (GDK XMEM_ALLOCATION_HOOKS): the console runtime routes internal // allocations (including D3D12 descriptor heaps) through these callbacks when the mapped image exports the struct. @@ -116,16 +107,6 @@ void report_called_unimplemented(); } // namespace rt::shims -// The title's suspend routines (app_state.cpp, from VIctory lifecycle.rs). -namespace rt::shims::app_state { -size_t registered_routines(); -// Runs every registered routine with Quiesced = TRUE on a thread of its own; true when they returned within the time. -bool run_suspend_routines(unsigned deadline_ms); -// Suspends the title, as the console does when it ends it, then ends the process (after the routines or a second, -// whichever is first). Returns at once; later calls do nothing. -void end_title(const char* why); -} // namespace rt::shims::app_state - #define SHIM_TABLE(id, ...) \ static const ::rt::shims::Entry id##_entries[] = {__VA_ARGS__}; \ static ::rt::shims::Table id##_table(id##_entries, sizeof(id##_entries) / sizeof(id##_entries[0])) diff --git a/runtime/shims/title_window.cpp b/runtime/shims/title_window.cpp deleted file mode 100644 index 46de2d415..000000000 --- a/runtime/shims/title_window.cpp +++ /dev/null @@ -1,106 +0,0 @@ -// The title's own window, ported from VIctory (GPL-3.0-or-later, Marvisak and contributors, DexNom fork; -// victory/crates/victory-hle/src/modules/lifecycle.rs `CreateWindowExA`, `CreateWindowExW`, `fit`, `fit_into`, `hook`, -// `window_proc`). -// -// A GDKX title makes a Win32 window (the title imports CreateWindowExA, RegisterClassExA, ShowWindow and a -// PeekMessageA loop from the ext-ms-win-rtcore-ntuser-* sets) and sizes it to its render target: 3840x2160 on a -// Series X, larger than most screens. CreateWindowExA/W here make the window the title asks for, with two changes for a -// top-level one: -// - with LEONIDA_ASPECT (src/aspect_fit.h, docs/ultrawide.md) it is first widened to that aspect, keeping its height, -// so an ultrawide monitor gets an ultrawide window (a 16:9 frame is then pillarboxed in it, src/vulkan_present.h); -// - a size that does not fit the primary monitor's work area is shrunk to it, keeping its shape, and centred (what the -// window shows is scaled to it: the swapchain follows the client area); -// - a window procedure goes in front of the title's: Close (the close button, Alt+F4, the window menu) ends the run, -// since a console title is never told it is closing: as in VIctory, the title's suspend routines run first -// (app_state.cpp) and the process ends when they return or after a second, and Alt or F10 do not put the window into menu mode: the system would run its -// modal menu loop on the title's thread, which then stops until a key ends the loop. -// The window is then the one PresentX shows the frames in (xbox_window.h, note_title_window). -#include -#include - -#include -#include - -#include "shims.h" -#include "xbox_display.h" -#include "xbox_window.h" - -namespace { - -constexpr wchar_t kTitleProc[] = L"leonida.wndproc"; // the title's own procedure, kept on the window - -bool top_level(HWND parent, DWORD style) { return !parent && !(style & WS_CHILD); } - -// V lifecycle.rs `fit`: only a top-level window that does not fit, and not CW_USEDEFAULT sizes. `caller` is where the -// title called from, logged so a trace can find what sized the window. -void fit(HWND parent, DWORD style, int& x, int& y, int& width, int& height, const void* caller) { - if (!top_level(parent, style) || width <= 0 || height <= 0 || width == CW_USEDEFAULT || height == CW_USEDEFAULT) - return; - if (const double ratio = rt::d3d12::title_aspect_ratio(); ratio > 0.0) { - const leonida::aspect::Size wide = leonida::aspect::widen({std::uint32_t(width), std::uint32_t(height)}, ratio); - if (int(wide.width) != width) { - std::fprintf(stderr, "[rt] window: the title's %dx%d window is widened to %ux%d (LEONIDA_ASPECT)\n", width, - height, wide.width, height); - width = int(wide.width); - } - } - RECT area{}; - if (!SystemParametersInfoW(SPI_GETWORKAREA, 0, &area, 0)) return; - const int aw = area.right - area.left, ah = area.bottom - area.top; - if (aw <= 0 || ah <= 0 || (width <= aw && height <= ah)) return; - const double scale = std::min(double(aw) / double(width), double(ah) / double(height)); - const int w = int(double(width) * scale), h = int(double(height) * scale); - std::fprintf(stderr, "[rt] window: the title's %dx%d window (CreateWindowEx called from %p) is fitted to the screen " - "as %dx%d\n", width, height, caller, w, h); - x = area.left + (aw - w) / 2; - y = area.top + (ah - h) / 2; - width = w; - height = h; -} - -LRESULT CALLBACK window_proc(HWND hwnd, UINT message, WPARAM w, LPARAM l) { - if (message == WM_SYSCOMMAND && (w & 0xFFF0) == SC_CLOSE) { - // As the console ends a title: its suspend routines first, then the process (app_state.cpp). - rt::shims::app_state::end_title("the title's window was closed"); - return 0; - } - if (message == WM_SYSCOMMAND && (w & 0xFFF0) == SC_KEYMENU) return 0; - const auto title = reinterpret_cast(GetPropW(hwnd, kTitleProc)); - if (message == WM_NCDESTROY) RemovePropW(hwnd, kTitleProc); - return title ? CallWindowProcW(title, hwnd, message, w, l) : DefWindowProcW(hwnd, message, w, l); -} - -// V lifecycle.rs `hook`: the title's procedure is stored before ours can run. -void hook(HWND hwnd, HWND parent, DWORD style) { - if (!hwnd || !top_level(parent, style)) return; - const LONG_PTR title = GetWindowLongPtrW(hwnd, GWLP_WNDPROC); - SetPropW(hwnd, kTitleProc, reinterpret_cast(title)); - SetWindowLongPtrW(hwnd, GWLP_WNDPROC, reinterpret_cast(&window_proc)); - rt::d3d12::note_title_window(hwnd); -} - -HWND WINAPI create_window_ex_a(DWORD ex_style, LPCSTR class_name, LPCSTR window_name, DWORD style, int x, int y, - int width, int height, HWND parent, HMENU menu, HINSTANCE instance, LPVOID param) { - fit(parent, style, x, y, width, height, _ReturnAddress()); - const HWND hwnd = CreateWindowExA(ex_style, class_name, window_name, style, x, y, width, height, parent, menu, - instance, param); - hook(hwnd, parent, style); - return hwnd; -} - -HWND WINAPI create_window_ex_w(DWORD ex_style, LPCWSTR class_name, LPCWSTR window_name, DWORD style, int x, int y, - int width, int height, HWND parent, HMENU menu, HINSTANCE instance, LPVOID param) { - fit(parent, style, x, y, width, height, _ReturnAddress()); - const HWND hwnd = CreateWindowExW(ex_style, class_name, window_name, style, x, y, width, height, parent, menu, - instance, param); - hook(hwnd, parent, style); - return hwnd; -} - -} // namespace - -// The sets the title imports them from (V lifecycle.rs: "ext-ms-win-rtcore-ntuser-window-*"). -SHIM_TABLE(title_window, - {"ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0.dll", "CreateWindowExA", reinterpret_cast(&create_window_ex_a)}, - {"ext-ms-win-rtcore-ntuser-window-l1-1-0.dll", "CreateWindowExW", reinterpret_cast(&create_window_ex_w)}, -); diff --git a/runtime/shims/winsock_offline.cpp b/runtime/shims/winsock_offline.cpp deleted file mode 100644 index e0c8f426f..000000000 --- a/runtime/shims/winsock_offline.cpp +++ /dev/null @@ -1,324 +0,0 @@ -// winsock_offline: Winsock for a mapped title, which reaches loopback only. -// -// The retail executable imports 25 functions from ws2_32.dll, 23 by ordinal plus getaddrinfo and freeaddrinfo -// (docs/runtime_imports.md, RT-5), and they were bound to the host's: a --run could open real sockets, against the -// "nothing online" rule. Ported from VIctory victory-hle src/modules/net.rs (GPL-3.0-or-later), "a console without a -// network cable": every way out of Winsock a title can import (by name, or by the classic ordinals below) is vetted -// here, and the rest of ws2_32.dll stays the host's (registry.cpp keeps it a host module, as advapi32.dll). -// - connect / WSAConnect, the ConnectEx and WSASendMsg extensions WSAIoctl hands out, and datagram sends (sendto, -// WSASendTo) to anything but 127.0.0.0/8 and ::1 (IPv4-mapped too) fail with WSAENETUNREACH; nothing is sent; -// - forward lookups (getaddrinfo, GetAddrInfoW, gethostbyname, WSAConnectByNameA/W) of anything but "localhost" and -// IP literals fail with WSAHOST_NOT_FOUND, so no DNS query leaves the machine; -// - reverse lookups (gethostbyaddr, getnameinfo) of other addresses fail or come back numeric (NI_NAMEREQD fails), -// as on a console with no network; -// - a bind to all interfaces (INADDR_ANY, in6addr_any) is narrowed to loopback, so nothing on the network can -// connect in. -// Each refused destination is logged once ("[rt] winsock: offline, refused ..."), never with a payload. Only images -// mapped by the loader see these: they are bound through the registry, the runtime's own code calls the host directly. -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include "shims.h" - -namespace rt::shims::winsock_offline { -namespace { - -void refused(const char* what, const std::string& destination) { - static auto* m = new std::mutex; - static auto* seen = new std::set; - std::lock_guard lock(*m); - if (seen->insert(std::string(what) + " " + destination).second) - std::fprintf(stderr, "[rt] winsock: offline, refused %s %s\n", what, destination.c_str()); -} - -bool loopback_v4(const in_addr& a) { return (ntohl(a.s_addr) >> 24) == 127; } -bool loopback_v6(const in6_addr& a) { - static const unsigned char kLoopback[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}; - if (std::memcmp(a.s6_addr, kLoopback, 16) == 0) return true; - // ::ffff:127.x.y.z, an IPv4 loopback address in IPv6 form - static const unsigned char kMapped[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff}; - return std::memcmp(a.s6_addr, kMapped, 12) == 0 && a.s6_addr[12] == 127; -} - -// Whether a socket address is a loopback one. Families other than IPv4 and IPv6 (a Unix socket, say) are local. -bool loopback(const sockaddr* addr, int len) { - if (!addr || len < static_cast(sizeof(sockaddr))) return true; // the host rejects it as invalid - if (addr->sa_family == AF_INET && len >= static_cast(sizeof(sockaddr_in))) - return loopback_v4(reinterpret_cast(addr)->sin_addr); - if (addr->sa_family == AF_INET6 && len >= static_cast(sizeof(sockaddr_in6))) - return loopback_v6(reinterpret_cast(addr)->sin6_addr); - return addr->sa_family != AF_INET && addr->sa_family != AF_INET6; -} - -std::string describe(const sockaddr* addr, int len) { - char text[INET6_ADDRSTRLEN] = "?"; - if (addr && addr->sa_family == AF_INET && len >= static_cast(sizeof(sockaddr_in))) { - const auto* in = reinterpret_cast(addr); - inet_ntop(AF_INET, &in->sin_addr, text, sizeof(text)); - return std::string(text) + ":" + std::to_string(ntohs(in->sin_port)); - } - if (addr && addr->sa_family == AF_INET6 && len >= static_cast(sizeof(sockaddr_in6))) { - const auto* in = reinterpret_cast(addr); - inet_ntop(AF_INET6, &in->sin6_addr, text, sizeof(text)); - return std::string("[") + text + "]:" + std::to_string(ntohs(in->sin6_port)); - } - return text; -} - -// Refuses a destination that is not loopback: true when refused (WSAENETUNREACH set). -bool refuse_destination(const char* what, const sockaddr* addr, int len) { - if (loopback(addr, len)) return false; - refused(what, describe(addr, len)); - WSASetLastError(WSAENETUNREACH); - return true; -} - -// "localhost" (any case, optionally with a trailing '.') or an IP literal: names that resolve without DNS. -bool local_name(const std::string& name) { - std::string bare = name; - if (!bare.empty() && bare.back() == '.') bare.pop_back(); - if (_stricmp(bare.c_str(), "localhost") == 0) return true; - if (bare.size() > 2 && bare.front() == '[' && bare.back() == ']') bare = bare.substr(1, bare.size() - 2); - in_addr v4{}; - in6_addr v6{}; - return inet_pton(AF_INET, bare.c_str(), &v4) == 1 || inet_pton(AF_INET6, bare.c_str(), &v6) == 1; -} - -std::string narrow(const wchar_t* w) { - std::string s; - for (; w && *w; ++w) s += (*w < 0x80) ? static_cast(*w) : '?'; - return s; -} - -// ---- connects and sends ---- - -int WSAAPI shim_connect(SOCKET s, const sockaddr* name, int namelen) { - if (refuse_destination("connect to", name, namelen)) return SOCKET_ERROR; - return connect(s, name, namelen); -} - -int WSAAPI shim_wsa_connect(SOCKET s, const sockaddr* name, int namelen, LPWSABUF caller, LPWSABUF callee, LPQOS sqos, - LPQOS gqos) { - if (refuse_destination("connect to", name, namelen)) return SOCKET_ERROR; - return WSAConnect(s, name, namelen, caller, callee, sqos, gqos); -} - -int WSAAPI shim_sendto(SOCKET s, const char* buf, int len, int flags, const sockaddr* to, int tolen) { - // A null destination is the connected peer, which connect() kept on loopback. - if (to && refuse_destination("datagram to", to, tolen)) return SOCKET_ERROR; - return sendto(s, buf, len, flags, to, tolen); -} - -int WSAAPI shim_wsa_send_to(SOCKET s, LPWSABUF buffers, DWORD count, LPDWORD sent, DWORD flags, const sockaddr* to, - int tolen, LPWSAOVERLAPPED overlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE completion) { - if (to && refuse_destination("datagram to", to, tolen)) return SOCKET_ERROR; - return WSASendTo(s, buffers, count, sent, flags, to, tolen, overlapped, completion); -} - -// ---- WSAIoctl's extension functions ---- - -std::atomic g_host_connect_ex{nullptr}; -std::atomic g_host_send_msg{nullptr}; - -BOOL PASCAL shim_connect_ex(SOCKET s, const sockaddr* name, int namelen, PVOID send, DWORD send_length, LPDWORD sent, - LPOVERLAPPED overlapped) { - if (refuse_destination("connect to", name, namelen)) return FALSE; - const LPFN_CONNECTEX host = g_host_connect_ex.load(); - if (!host) { - WSASetLastError(WSAEINVAL); - return FALSE; - } - return host(s, name, namelen, send, send_length, sent, overlapped); -} - -INT WSAAPI shim_send_msg(SOCKET s, LPWSAMSG msg, DWORD flags, LPDWORD sent, LPWSAOVERLAPPED overlapped, - LPWSAOVERLAPPED_COMPLETION_ROUTINE completion) { - if (msg && msg->name && refuse_destination("datagram to", msg->name, msg->namelen)) return SOCKET_ERROR; - const LPFN_WSASENDMSG host = g_host_send_msg.load(); - if (!host) { - WSASetLastError(WSAEINVAL); - return SOCKET_ERROR; - } - return host(s, msg, flags, sent, overlapped, completion); -} - -// WSAIoctl is the host's, except that the ConnectEx and WSASendMsg pointers it hands out are ours, which vet the -// destination and then call the host's (one provider per process is assumed: the one the title asked through). -int WSAAPI shim_wsa_ioctl(SOCKET s, DWORD code, LPVOID in, DWORD in_size, LPVOID out, DWORD out_size, LPDWORD returned, - LPWSAOVERLAPPED overlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE completion) { - const int result = WSAIoctl(s, code, in, in_size, out, out_size, returned, overlapped, completion); - if (result != 0 || code != SIO_GET_EXTENSION_FUNCTION_POINTER || !in || in_size < sizeof(GUID) || !out || - out_size < sizeof(void*)) - return result; - const GUID connect_ex = WSAID_CONNECTEX, send_msg = WSAID_WSASENDMSG; - if (std::memcmp(in, &connect_ex, sizeof(GUID)) == 0) { - g_host_connect_ex.store(*static_cast(out)); - *static_cast(out) = &shim_connect_ex; - } else if (std::memcmp(in, &send_msg, sizeof(GUID)) == 0) { - g_host_send_msg.store(*static_cast(out)); - *static_cast(out) = &shim_send_msg; - } - return result; -} - -// ---- binds ---- - -int WSAAPI shim_bind(SOCKET s, const sockaddr* addr, int len) { - if (addr && addr->sa_family == AF_INET && len >= static_cast(sizeof(sockaddr_in)) && - reinterpret_cast(addr)->sin_addr.s_addr == htonl(INADDR_ANY)) { - sockaddr_in narrowed = *reinterpret_cast(addr); - narrowed.sin_addr.s_addr = htonl(INADDR_LOOPBACK); - return bind(s, reinterpret_cast(&narrowed), sizeof(narrowed)); - } - if (addr && addr->sa_family == AF_INET6 && len >= static_cast(sizeof(sockaddr_in6)) && - IN6_IS_ADDR_UNSPECIFIED(&reinterpret_cast(addr)->sin6_addr)) { - sockaddr_in6 narrowed = *reinterpret_cast(addr); - narrowed.sin6_addr = in6addr_loopback; - return bind(s, reinterpret_cast(&narrowed), sizeof(narrowed)); - } - return bind(s, addr, len); -} - -// ---- forward lookups ---- - -INT WSAAPI shim_getaddrinfo(PCSTR node, PCSTR service, const ADDRINFOA* hints, PADDRINFOA* result) { - if (node && !local_name(node)) { - refused("lookup of", node); - if (result) *result = nullptr; - WSASetLastError(WSAHOST_NOT_FOUND); - return WSAHOST_NOT_FOUND; // EAI_NONAME - } - return getaddrinfo(node, service, hints, result); -} - -INT WSAAPI shim_get_addr_info_w(PCWSTR node, PCWSTR service, const ADDRINFOW* hints, PADDRINFOW* result) { - if (node && !local_name(narrow(node))) { - refused("lookup of", narrow(node)); - if (result) *result = nullptr; - WSASetLastError(WSAHOST_NOT_FOUND); - return WSAHOST_NOT_FOUND; - } - return GetAddrInfoW(node, service, hints, result); -} - -#pragma warning(push) -#pragma warning(disable : 4996) // gethostbyname / gethostbyaddr: deprecated, still what the ordinals name -hostent* WSAAPI shim_gethostbyname(const char* name) { - if (name && !local_name(name)) { - refused("lookup of", name); - WSASetLastError(WSAHOST_NOT_FOUND); - return nullptr; - } - return gethostbyname(name); -} - -// ---- reverse lookups ---- - -hostent* WSAAPI shim_gethostbyaddr(const char* addr, int len, int type) { - const bool v4 = type == AF_INET && addr && len >= 4; - const bool v6 = type == AF_INET6 && addr && len >= 16; - bool local = !v4 && !v6; - if (v4) { - in_addr a{}; - std::memcpy(&a, addr, 4); - local = loopback_v4(a); - } else if (v6) { - in6_addr a{}; - std::memcpy(&a, addr, 16); - local = loopback_v6(a); - } - if (!local) { - refused("reverse lookup of", "an address"); - WSASetLastError(WSAHOST_NOT_FOUND); - return nullptr; - } - return gethostbyaddr(addr, len, type); -} -#pragma warning(pop) - -INT WSAAPI shim_getnameinfo(const SOCKADDR* addr, socklen_t len, PCHAR host, DWORD host_size, PCHAR serv, - DWORD serv_size, INT flags) { - if (host && !loopback(addr, len)) { - if (flags & NI_NAMEREQD) { - WSASetLastError(WSAHOST_NOT_FOUND); - return WSAHOST_NOT_FOUND; - } - flags |= NI_NUMERICHOST; // the numeric form needs no DNS - } - return getnameinfo(addr, len, host, host_size, serv, serv_size, flags); -} - -INT WSAAPI shim_get_name_info_w(const SOCKADDR* addr, socklen_t len, PWCHAR host, DWORD host_size, PWCHAR serv, - DWORD serv_size, INT flags) { - if (host && !loopback(addr, len)) { - if (flags & NI_NAMEREQD) { - WSASetLastError(WSAHOST_NOT_FOUND); - return WSAHOST_NOT_FOUND; - } - flags |= NI_NUMERICHOST; - } - return GetNameInfoW(addr, len, host, host_size, serv, serv_size, flags); -} - -// ---- connect by name ---- - -#pragma warning(push) -#pragma warning(disable : 4996) // WSAConnectByNameA: deprecated in favour of the W form, still exported -BOOL PASCAL shim_wsa_connect_by_name_a(SOCKET s, LPCSTR name, LPCSTR service, LPDWORD local_len, LPSOCKADDR local, - LPDWORD remote_len, LPSOCKADDR remote, const timeval* timeout, - LPWSAOVERLAPPED reserved) { - if (!name || !local_name(name)) { - refused("connect to", name ? name : "(null)"); - WSASetLastError(WSAHOST_NOT_FOUND); - return FALSE; - } - return WSAConnectByNameA(s, name, service, local_len, local, remote_len, remote, timeout, reserved); -} -#pragma warning(pop) - -BOOL PASCAL shim_wsa_connect_by_name_w(SOCKET s, LPWSTR name, LPWSTR service, LPDWORD local_len, LPSOCKADDR local, - LPDWORD remote_len, LPSOCKADDR remote, const timeval* timeout, - LPWSAOVERLAPPED reserved) { - if (!name || !local_name(narrow(name))) { - refused("connect to", name ? narrow(name) : "(null)"); - WSASetLastError(WSAHOST_NOT_FOUND); - return FALSE; - } - return WSAConnectByNameW(s, name, service, local_len, local, remote_len, remote, timeout, reserved); -} - -} // namespace -} // namespace rt::shims::winsock_offline - -namespace { -using namespace rt::shims::winsock_offline; -#define WS(name, fn) {"ws2_32.dll", name, reinterpret_cast(&fn)} -} // namespace - -// The classic ordinals (ws2_32.dll's export table: 2 bind, 4 connect, 20 sendto, 51 gethostbyaddr, 52 -// gethostbyname) are what the retail executable imports by number; the names cover everything else. -SHIM_TABLE(winsock_offline, - WS("connect", shim_connect), WS("#4", shim_connect), - WS("bind", shim_bind), WS("#2", shim_bind), - WS("sendto", shim_sendto), WS("#20", shim_sendto), - WS("gethostbyaddr", shim_gethostbyaddr), WS("#51", shim_gethostbyaddr), - WS("gethostbyname", shim_gethostbyname), WS("#52", shim_gethostbyname), - WS("WSAConnect", shim_wsa_connect), - WS("WSASendTo", shim_wsa_send_to), - WS("WSAIoctl", shim_wsa_ioctl), - WS("getaddrinfo", shim_getaddrinfo), - WS("GetAddrInfoW", shim_get_addr_info_w), - WS("getnameinfo", shim_getnameinfo), - WS("GetNameInfoW", shim_get_name_info_w), - WS("WSAConnectByNameA", shim_wsa_connect_by_name_a), - WS("WSAConnectByNameW", shim_wsa_connect_by_name_w), -); diff --git a/runtime/shims/xbox_display.cpp b/runtime/shims/xbox_display.cpp deleted file mode 100644 index ad147f07d..000000000 --- a/runtime/shims/xbox_display.cpp +++ /dev/null @@ -1,389 +0,0 @@ -// The console DXGI adapter and output (xbox_display.h), ported from VIctory's victory-gpu/src/dxgi.rs -// (GPL-3.0-or-later, Marvisak and contributors, DexNom fork). -// -// Both are raw vtables over the layer's PC objects, built the way the device proxy builds its own: the object's first -// word is the table, and a slot the console keeps in PC order goes to the PC method at the same slot. The thunks take -// four argument words after `this`, the most any forwarded DXGI method has, and hand them on in the same positions -// (see d3d12_xs_device.cpp on why a forwarding thunk must not move a caller's stack words). -#include "xbox_display.h" - -#include "d3d12_com.h" - -#include -#include -#include -#include -#include -#include - -namespace rt::d3d12 { -namespace { - -using Word = std::uint64_t; -constexpr unsigned kTableSlots = 64; - -enum class Kind : unsigned { adapter = 0, output = 1 }; - -struct ConsoleObject { - void** vtable; // offset 0: the title's IDXGIAdapter* / IDXGIOutput* points here - IUnknown* inner; // the PC adapter or output (one reference) - std::atomic refs; - Kind kind; - ConsoleObject* adapter; // an output's adapter (one reference); null for an adapter -}; - -std::atomic g_first[2][kTableSlots]; -std::atomic g_refused[2][kTableSlots]; - -const char* kind_name(Kind kind) { return kind == Kind::adapter ? "adapter" : "output"; } - -const char* slot_name(Kind kind, unsigned slot) { - static const char* const shared[] = {"QueryInterface", "AddRef", "Release", "SetPrivateData", - "SetPrivateDataInterface", "GetPrivateData", "GetParent"}; - static const char* const adapter[] = {"EnumOutputs", "GetDesc", "CheckInterfaceSupport", "GetDesc1", "GetDesc2"}; - static const char* const output[] = {"GetDesc", - "GetDisplayModeList", - "FindClosestMatchingMode", - "WaitForVBlank", - "TakeOwnership", - "ReleaseOwnership", - "GetGammaControlCapabilities", - "SetGammaControl", - "GetGammaControl", - "SetDisplaySurface", - "GetDisplaySurfaceData", - "GetFrameStatistics", - "console method (not named)", - "console method (not named)", - "console display modes (V dxgi.rs:243-279)"}; - if (slot < 7) return shared[slot]; - if (kind == Kind::adapter) return slot < 12 ? adapter[slot - 7] : "past the console adapter's 12 slots"; - return slot < 22 ? output[slot - 7] : "past the console output's 22 slots"; -} - -void note(Kind kind, unsigned slot) { - bool expected = false; - if (slot < kTableSlots && !g_first[unsigned(kind)][slot].load(std::memory_order_relaxed) && - g_first[unsigned(kind)][slot].compare_exchange_strong(expected, true, std::memory_order_relaxed)) - std::fprintf(stderr, "[rt] dxgi_xs: console %s slot %u (%s) first call\n", kind_name(kind), slot, - slot_name(kind, slot)); -} - -Word hr_word(HRESULT hr) { return Word(std::uint32_t(hr)); } - -ConsoleObject* make(Kind kind, IUnknown* inner, ConsoleObject* adapter); - -ULONG add_ref(ConsoleObject* self) { return self->refs.fetch_add(1, std::memory_order_relaxed) + 1; } - -ULONG release(ConsoleObject* self) { - const ULONG left = self->refs.fetch_sub(1, std::memory_order_acq_rel) - 1; - if (!left) { - IUnknown* inner = self->inner; - ConsoleObject* adapter = self->adapter; - delete self; - inner->Release(); - if (adapter) release(adapter); - } - return left; -} - -bool answers(Kind kind, const IID& iid) { - if (IsEqualIID(iid, __uuidof(IUnknown)) || IsEqualIID(iid, __uuidof(IDXGIObject))) return true; - // V dxgi.rs:32-51 and 72-77: the adapter answers IDXGIAdapter to IDXGIAdapter2, the output IDXGIOutput. - if (kind == Kind::adapter) - return IsEqualIID(iid, __uuidof(IDXGIAdapter)) || IsEqualIID(iid, __uuidof(IDXGIAdapter1)) || - IsEqualIID(iid, __uuidof(IDXGIAdapter2)); - return IsEqualIID(iid, __uuidof(IDXGIOutput)); -} - -HRESULT query(ConsoleObject* self, const IID* riid, void** out) { - if (!out) return E_POINTER; - *out = nullptr; - if (!riid) return E_POINTER; - if (!answers(self->kind, *riid)) { - static std::atomic logged{0}; - if (logged.fetch_add(1, std::memory_order_relaxed) < 8) - std::fprintf(stderr, - "[rt] dxgi_xs: console %s QueryInterface {%08lx-%04x-%04x-...}: not an interface it has; " - "E_NOINTERFACE\n", - kind_name(self->kind), static_cast(riid->Data1), riid->Data2, riid->Data3); - return E_NOINTERFACE; - } - add_ref(self); - *out = self; - return S_OK; -} - -template -Word WINAPI thunk_query(ConsoleObject* self, Word riid, Word out, Word, Word) { - note(K, 0); - return hr_word(query(self, reinterpret_cast(riid), reinterpret_cast(out))); -} -template -Word WINAPI thunk_add_ref(ConsoleObject* self, Word, Word, Word, Word) { - note(K, 1); - return add_ref(self); -} -template -Word WINAPI thunk_release(ConsoleObject* self, Word, Word, Word, Word) { - note(K, 2); - return release(self); -} - -template -Word WINAPI thunk_forward(ConsoleObject* self, Word a1, Word a2, Word a3, Word a4) { - note(K, Slot); - using Fn = Word(WINAPI*)(void*, Word, Word, Word, Word); - void** table = *reinterpret_cast(self->inner); - return reinterpret_cast(table[Slot])(self->inner, a1, a2, a3, a4); -} - -template -Word WINAPI thunk_refuse(ConsoleObject*, Word a1, Word a2, Word a3, Word a4) { - note(K, Slot); - bool expected = false; - if (g_refused[unsigned(K)][Slot].compare_exchange_strong(expected, true, std::memory_order_relaxed)) - std::fprintf(stderr, - "[rt] dxgi_xs: console %s slot %u (%s) is not implemented; returning E_NOTIMPL (args 0x%llx " - "0x%llx 0x%llx 0x%llx)\n", - kind_name(K), Slot, slot_name(K, Slot), static_cast(a1), - static_cast(a2), static_cast(a3), - static_cast(a4)); - return hr_word(E_NOTIMPL); -} - -// Adapter slot 7: EnumOutputs(index, &output), the output in the console layout. -Word WINAPI adapter_enum_outputs(ConsoleObject* self, Word index, Word out_word, Word, Word) { - note(Kind::adapter, 7); - auto** out = reinterpret_cast(out_word); - if (!out) return hr_word(E_INVALIDARG); - *out = nullptr; - IDXGIOutput* pc = nullptr; - const HRESULT hr = static_cast(self->inner)->EnumOutputs(static_cast(index), &pc); - if (FAILED(hr) || !pc) return hr_word(FAILED(hr) ? hr : DXGI_ERROR_NOT_FOUND); - ConsoleObject* output = make(Kind::output, pc, self); - pc->Release(); - if (!output) return hr_word(E_OUTOFMEMORY); - *out = reinterpret_cast(output); - return hr_word(S_OK); -} - -// Output slot 6: GetParent(riid, &parent), the console adapter it came from. -Word WINAPI output_get_parent(ConsoleObject* self, Word riid, Word out, Word, Word) { - note(Kind::output, 6); - return hr_word(query(self->adapter, reinterpret_cast(riid), reinterpret_cast(out))); -} - -// Output slot 7: GetDesc, with the display mode's size as the desktop coordinates. -Word WINAPI output_get_desc(ConsoleObject* self, Word desc_word, Word, Word, Word) { - note(Kind::output, 7); - auto* desc = reinterpret_cast(desc_word); - const HRESULT hr = static_cast(self->inner)->GetDesc(desc); - if (SUCCEEDED(hr) && desc) { - const leonida::DisplayMode mode = title_display_mode(); - desc->DesktopCoordinates = {0, 0, LONG(mode.width), LONG(mode.height)}; - } - return hr_word(hr); -} - -DXGI_MODE_DESC pc_mode(DXGI_FORMAT format) { - const leonida::DisplayMode mode = title_display_mode(); - DXGI_MODE_DESC m{}; - m.Width = mode.width; - m.Height = mode.height; - m.RefreshRate = {mode.refresh_hz, 1}; - m.Format = format; - m.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_PROGRESSIVE; - m.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; - return m; -} - -// Output slot 8: the PC GetDisplayModeList(format, flags, &count, modes): the display mode alone. -Word WINAPI output_get_display_mode_list(ConsoleObject*, Word format, Word, Word count_word, Word out_word) { - note(Kind::output, 8); - auto* count = reinterpret_cast(count_word); - auto* out = reinterpret_cast(out_word); - if (!count) return hr_word(DXGI_ERROR_INVALID_CALL); - if (!out) { - *count = 1; - return hr_word(S_OK); - } - if (*count < 1) return hr_word(DXGI_ERROR_MORE_DATA); - *count = 1; - out[0] = pc_mode(static_cast(format)); - return hr_word(S_OK); -} - -// Output slot 9: the PC FindClosestMatchingMode(match, &closest, device): the display mode, in the asked format. -Word WINAPI output_find_closest_mode(ConsoleObject*, Word match_word, Word closest_word, Word, Word) { - note(Kind::output, 9); - const auto* match = reinterpret_cast(match_word); - auto* closest = reinterpret_cast(closest_word); - if (!match || !closest) return hr_word(DXGI_ERROR_INVALID_CALL); - *closest = pc_mode(match->Format == DXGI_FORMAT_UNKNOWN ? DXGI_FORMAT_B8G8R8A8_UNORM : match->Format); - return hr_word(S_OK); -} - -// Output slot 21: modes(format, flags, &count, out), V dxgi.rs:243-279. A null count is E_INVALIDARG; a null `out` -// asks for the count (1); room for none is DXGI_ERROR_MORE_DATA; else the one mode: the display mode at 60 Hz, format -// 0 and progressive scanlines, as VIctory writes it. -Word WINAPI output_modes(ConsoleObject*, Word format, Word flags, Word count_word, Word out_word) { - note(Kind::output, kConsoleOutputModesSlot); - auto* count = reinterpret_cast(count_word); - auto* out = reinterpret_cast(out_word); - static std::atomic logged{false}; - const leonida::DisplayMode mode = title_display_mode(); - if (!logged.exchange(true, std::memory_order_relaxed)) - std::fprintf(stderr, - "[rt] dxgi_xs: console output slot 21 (display modes, format %u, flags 0x%x): %ux%u at %u Hz " - "reported\n", - static_cast(format), static_cast(flags), mode.width, mode.height, - mode.refresh_hz); - if (!count) return hr_word(E_INVALIDARG); - if (!out) { - *count = 1; - return hr_word(S_OK); - } - if (*count < 1) return hr_word(DXGI_ERROR_MORE_DATA); - *count = 1; - out[0] = ConsoleDisplayMode{mode.width, mode.height, mode.refresh_hz, 1, 0, 1, 0, 0}; - return hr_word(S_OK); -} - -template -void* entry() { - if constexpr (Slot == 0) return reinterpret_cast(&thunk_query); - else if constexpr (Slot == 1) return reinterpret_cast(&thunk_add_ref); - else if constexpr (Slot == 2) return reinterpret_cast(&thunk_release); - else if constexpr (K == Kind::adapter) { - if constexpr (Slot == 7) return reinterpret_cast(&adapter_enum_outputs); - else if constexpr (Slot < 12) return reinterpret_cast(&thunk_forward); - else return reinterpret_cast(&thunk_refuse); - } else { - if constexpr (Slot == 6) return reinterpret_cast(&output_get_parent); - else if constexpr (Slot == 7) return reinterpret_cast(&output_get_desc); - else if constexpr (Slot == 8) return reinterpret_cast(&output_get_display_mode_list); - else if constexpr (Slot == 9) return reinterpret_cast(&output_find_closest_mode); - else if constexpr (Slot == kConsoleOutputModesSlot) return reinterpret_cast(&output_modes); - else if constexpr (Slot < 19) return reinterpret_cast(&thunk_forward); - else return reinterpret_cast(&thunk_refuse); - } -} - -template -std::array build(std::index_sequence) { - return {entry()...}; -} - -void** table(Kind kind) { - static std::array adapter = build(std::make_index_sequence{}); - static std::array output = build(std::make_index_sequence{}); - return kind == Kind::adapter ? adapter.data() : output.data(); -} - -ConsoleObject* make(Kind kind, IUnknown* inner, ConsoleObject* adapter) { - auto* object = new (std::nothrow) ConsoleObject{table(kind), inner, {1}, kind, adapter}; - if (!object) return nullptr; - inner->AddRef(); - if (adapter) add_ref(adapter); - return object; -} - -} // namespace - -double title_aspect_ratio() { - static const double ratio = [] { - char value[64] = {}; - const DWORD length = GetEnvironmentVariableA("LEONIDA_ASPECT", value, sizeof(value)); - if (length == 0) return 0.0; - leonida::aspect::Request request; - if (length >= sizeof(value) || !leonida::aspect::parse_request(value, &request)) { - std::fprintf(stderr, "[rt] display: LEONIDA_ASPECT=%s is not W:H, a ratio in 1..4, auto or off; ignored\n", - length < sizeof(value) ? value : "(too long)"); - return 0.0; - } - // `auto`: the primary monitor's shape (its size in whatever DPI units this thread has; the ratio is the same). - std::uint32_t monitor_w = 0, monitor_h = 0; - MONITORINFO monitor{sizeof(monitor)}; - if (request.kind == leonida::aspect::Kind::automatic && - GetMonitorInfoW(MonitorFromPoint(POINT{0, 0}, MONITOR_DEFAULTTOPRIMARY), &monitor)) { - monitor_w = std::uint32_t(monitor.rcMonitor.right - monitor.rcMonitor.left); - monitor_h = std::uint32_t(monitor.rcMonitor.bottom - monitor.rcMonitor.top); - } - const double r = leonida::aspect::resolve(request, monitor_w, monitor_h); - if (request.kind == leonida::aspect::Kind::automatic) - std::fprintf(stderr, "[rt] display: LEONIDA_ASPECT=auto: the primary monitor is %ux%u (%.3f:1)%s\n", monitor_w, - monitor_h, r, r > 0.0 ? "" : ", not a ratio in 1..4; ignored"); - else if (r > 0.0) - std::fprintf(stderr, "[rt] display: LEONIDA_ASPECT=%s (%.3f:1)\n", value, r); - return r; - }(); - return ratio; -} - -leonida::DisplayMode title_display_mode() { - static const leonida::DisplayMode mode = [] { - leonida::DisplayMode m; - char value[64] = {}; - const DWORD length = GetEnvironmentVariableA("LEONIDA_DISPLAY_MODE", value, sizeof(value)); - if (length == 0) { - std::fprintf(stderr, "[rt] display: the title is told its display is %ux%u (LEONIDA_DISPLAY_MODE=WxH " - "changes it)\n", m.width, m.height); - } else if (length < sizeof(value) && leonida::parse_display_mode(value, &m)) { - std::fprintf(stderr, "[rt] display: the title is told its display is %ux%u (LEONIDA_DISPLAY_MODE)\n", - m.width, m.height); - } else { - std::fprintf(stderr, "[rt] display: LEONIDA_DISPLAY_MODE=%s is not WxH with W in 640..7680 and H in " - "360..4320; the title is told %ux%u\n", - length < sizeof(value) ? value : "(too long)", m.width, m.height); - } - // LEONIDA_ASPECT (src/aspect_fit.h): the same height, wider. Only the answers here change; the size the title - // renders at is compiled into it (src/display_profile.h), so whether it follows is for a run to show. - if (const double ratio = title_aspect_ratio(); ratio > 0.0) { - const leonida::DisplayMode wide = leonida::aspect::widen_display_mode(m, ratio); - if (wide.width != m.width || wide.height != m.height) - std::fprintf(stderr, "[rt] display: the title is told its display is %ux%u instead (LEONIDA_ASPECT)\n", - wide.width, wide.height); - else - std::fprintf(stderr, "[rt] display: LEONIDA_ASPECT is not wider than %ux%u; the mode is kept\n", m.width, - m.height); - m = wide; - } - return m; - }(); - return mode; -} - -HRESULT create_console_adapter(IDXGIAdapter* pc, REFIID riid, void** out) { - if (!out) return E_POINTER; - *out = nullptr; - if (!pc) return E_INVALIDARG; - ConsoleObject* adapter = make(Kind::adapter, pc, nullptr); - if (!adapter) return E_OUTOFMEMORY; - const HRESULT hr = query(adapter, &riid, out); - release(adapter); - return hr; -} - -HRESULT console_adapter_provider(ID3D12Device* real, REFIID riid, void** out) { - if (!out) return E_POINTER; - *out = nullptr; - IDXGIFactory1* factory = nullptr; - HRESULT hr = create_dxgi_factory(real, __uuidof(IDXGIFactory1), reinterpret_cast(&factory)); - if (FAILED(hr)) return hr; - IDXGIAdapter* adapter = nullptr; - hr = factory->EnumAdapters(0, &adapter); - factory->Release(); - if (FAILED(hr)) return hr; - hr = create_console_adapter(adapter, riid, out); - adapter->Release(); - return hr; -} - -bool is_console_dxgi_object(const void* object) { - if (!object) return false; - void* const* vtable = *static_cast(object); - return vtable == table(Kind::adapter) || vtable == table(Kind::output); -} - -} // namespace rt::d3d12 diff --git a/runtime/shims/xbox_display.h b/runtime/shims/xbox_display.h deleted file mode 100644 index 04af0f9fe..000000000 --- a/runtime/shims/xbox_display.h +++ /dev/null @@ -1,62 +0,0 @@ -#pragma once - -// The console's DXGI adapter and output, as a title on the Vulkan device reaches them: device QueryInterface for -// IDXGIDevice1, GetAdapter, EnumOutputs(0), then the output's console method at slot 21, which lists the display -// modes: LEONIDA_DISPLAY_MODE=WxH, 3840x2160 by default (src/display_mode.h). The 1.0.2.1 title calls it just before its -// first SetFrameIntervalX, but its window and scanout buffers keep the size compiled into it whatever this reports -// (measured with 1920x1080, at 60 and 120 Hz); the size is changed in the executable (src/display_profile.h, applied by -// main.cpp), and this answer is kept in step with it. -// -// Ported from VIctory (GPL-3.0-or-later, Marvisak and contributors, DexNom fork; victory/crates/victory-gpu/src/ -// dxgi.rs): its tables are what the title was seen to call. The adapter keeps the PC IDXGIAdapter2 order (IUnknown 3, -// object 4, adapter 3 + 1 + 1 = 12 slots; the title calls 6 GetParent, 7 EnumOutputs and 8 GetDesc). The output has -// the 12 PC IDXGIOutput methods at 7-18 and then three console ones (V dxgi.rs:281-288: "12 as on PC, then 3 console -// ones"); the title calls 6 GetParent and 21, `modes(format, flags, &count, out)` (V dxgi.rs:243-279), whose entries are -// 32 bytes: width, height, refresh rate (numerator, denominator), format, scanline order, scaling, flags. VIctory -// writes one 60 Hz mode with format 0 and progressive scanlines; so does this. On a PC IDXGIOutput1 slot 21 is -// GetDisplaySurfaceData1, which is what a title reached before: the call failed and the title kept its 4K default. -// -// What the wrappers do with the rest: the PC methods at the same slots forward to the layer's own adapter and output -// (dxgi_com.cpp), except that the output's GetDesc reports desktop coordinates of the display mode's size and its -// GetDisplayModeList lists the display mode, so no answer contradicts slot 21. The console output's slots 19 and 20 and -// every slot past the known ones are refused with E_NOTIMPL and logged once with their first argument words; each -// slot's first call is logged. - -#include -#include -#include - -#include "../src/aspect_fit.h" -#include "../src/display_mode.h" - -#include - -namespace rt::d3d12 { - -// The display mode reported to the title: LEONIDA_DISPLAY_MODE when it parses (read and logged once), else 3840x2160; -// then, with LEONIDA_ASPECT, widened to that aspect at the same height (src/aspect_fit.h, docs/ultrawide.md). -leonida::DisplayMode title_display_mode(); -// LEONIDA_ASPECT as width over height (`auto`: the primary monitor's), read and logged once; 0 when it is unset, off or -// not understood. -double title_aspect_ratio(); - -// `pc` (an IDXGIAdapter of any implementation; one reference is taken) in the console adapter layout described above. -HRESULT create_console_adapter(IDXGIAdapter* pc, REFIID riid, void** out); - -// The device proxy's adapter provider (d3d12_xs::set_device_adapter_provider) for a title on the Vulkan device: this -// layer's adapter (create_dxgi_factory, EnumAdapters(0)) in the console layout. -HRESULT console_adapter_provider(ID3D12Device* real, REFIID riid, void** out); - -// True for an adapter or output made here. -bool is_console_dxgi_object(const void* object); - -// The console output's slot 21, in the layout V dxgi.rs:208-220 gives (32 bytes). -struct ConsoleDisplayMode { - std::uint32_t width, height; - std::uint32_t refresh_numerator, refresh_denominator; - std::uint32_t format, scanline_order, scaling, flags; -}; -static_assert(sizeof(ConsoleDisplayMode) == 32, "V dxgi.rs:220"); -inline constexpr unsigned kConsoleOutputModesSlot = 21; - -} // namespace rt::d3d12 diff --git a/runtime/shims/xbox_present.h b/runtime/shims/xbox_present.h index c6976d1e1..86381f2d6 100644 --- a/runtime/shims/xbox_present.h +++ b/runtime/shims/xbox_present.h @@ -34,7 +34,6 @@ #include #include #include -#include #include #include #include @@ -168,28 +167,6 @@ public: // Peak of HDR10 content in nits, the white point of the tone map onto an SDR output (default 1000; no metadata is read). void set_hdr_peak_nits(float nits) { hdr_peak_nits_ = nits > 0.0f ? nits : 1000.0f; } - // The title's frame calls are answered by the device's frame clock, not by this object: the device proxy's slots - // 78-81 (d3d12_xs_device.cpp), VIctory's clock (victory/crates/victory-gpu/src/frame.rs, GPL-3.0-or-later, Marvisak - // and contributors, DexNom fork), whose waits pace the title and whose tokens count frames. `tokens_issued` says how - // many tokens that clock has handed out (d3d12_xs::device_frames_begun). From then on PresentX: - // - takes its tokens from that clock: one above `tokens_issued()` is logged once and presented anyway (the clock - // never refuses a present, as VIctory's queue.rs:757-841 does not); null, repeated and stale tokens are logged - // once per kind and presented, as before; - // - does not pace: the clock already holds the title to the frame interval, so a present is queued without - // waiting for a vblank (MAILBOX, else IMMEDIATE), as VIctory's host.rs presents with Present(0, 0). Waiting for - // a vblank as well would pace the title by two clocks that share no phase (the timer's ticks and the - // display's refresh), so a frame could wait out both; ImmediateThresholdPercent has nothing to tear then and - // is ignored. - // This object's own frame calls (FramePacer) stay for the tests that drive it directly; the title never reaches them. - void use_device_frame_clock(std::function tokens_issued) { - std::lock_guard serialise(present_mutex_); - device_tokens_ = std::move(tokens_issued); - } - bool uses_device_frame_clock() { - std::lock_guard serialise(present_mutex_); - return static_cast(device_tokens_); - } - leonida::FramePacer& pacer() { return pacer_; } WindowPresenter& presenter() { return *presenter_; } std::uint64_t presents() const { return presents_; } @@ -223,10 +200,6 @@ private: bool worker_stop_ = false; std::thread display_white_thread_; bool logged_null_token_ = false, logged_stale_token_ = false, logged_repeated_token_ = false; - // use_device_frame_clock: the clock's token count, and the newest token presented with it (under present_mutex_). - std::function device_tokens_; - std::uint64_t device_last_presented_ = 0; - bool logged_unissued_token_ = false; }; inline constexpr UINT xbox_frame_event_origin = leonida::frame_event_origin; diff --git a/runtime/shims/xbox_window.cpp b/runtime/shims/xbox_window.cpp deleted file mode 100644 index e8120c90b..000000000 --- a/runtime/shims/xbox_window.cpp +++ /dev/null @@ -1,568 +0,0 @@ -// The title's window, its caption, PresentX onto it, and the screenshots on request (xbox_window.h). Ported from -// VIctory's victory-gpu/src/host.rs and capture.rs (GPL-3.0-or-later, Marvisak and contributors, DexNom fork). -// -// No object here is a static with a destructor or a thread_local (AGENTS.md, "Runtime traps"): the presentation a -// title attaches lives until the process ends, and its threads end with it. -#include "xbox_window.h" - -#include "d3d12_com.h" -#include "d3d12_xs_device.h" -#include "xbox_display.h" -#include "xbox_present.h" - -#include "../src/frame_meter.h" -#include "../src/png_write.h" -#include "../src/vulkan_present.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace rt::d3d12 { -namespace { - -std::uint64_t now_ns() { - return std::uint64_t(std::chrono::duration_cast( - std::chrono::steady_clock::now().time_since_epoch()) - .count()); -} - -// Looked up at run time: Windows 10 1607 and later have both, Wine may not. -void name_thread(const wchar_t* name) { - using Fn = HRESULT(WINAPI*)(HANDLE, PCWSTR); - if (const auto set = reinterpret_cast( - reinterpret_cast(GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "SetThreadDescription")))) - set(GetCurrentThread(), name); -} - -// Only the window's thread is per-monitor DPI aware, so the window's client area is in pixels and Windows does not -// stretch it on a scaled monitor; the rest of the process keeps its awareness. -void make_thread_dpi_aware() { - using Fn = DPI_AWARENESS_CONTEXT(WINAPI*)(DPI_AWARENESS_CONTEXT); - if (const auto set = reinterpret_cast( - reinterpret_cast(GetProcAddress(GetModuleHandleW(L"user32.dll"), "SetThreadDpiAwarenessContext")))) - set(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); -} - -std::string utf8(const std::filesystem::path& path) { - const std::wstring& wide = path.native(); - const int bytes = WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), int(wide.size()), nullptr, 0, nullptr, nullptr); - std::string out(std::size_t(bytes > 0 ? bytes : 0), '\0'); - if (bytes > 0) WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), int(wide.size()), out.data(), bytes, nullptr, nullptr); - return out; -} - -std::wstring environment(const wchar_t* name) { - wchar_t value[1024]; - const DWORD length = GetEnvironmentVariableW(name, value, DWORD(std::size(value))); - return length && length < std::size(value) ? std::wstring(value, length) : std::wstring(); -} - -constexpr wchar_t kWindowClass[] = L"LeonidaWindow"; -constexpr UINT kDestroyRequest = WM_APP + 1; // ~GameWindow: the window is destroyed by its own thread - -LRESULT CALLBACK window_proc(HWND hwnd, UINT message, WPARAM w, LPARAM l) { - switch (message) { - case WM_CLOSE: - // A console title has no way to be closed; the user closing its window ends the run, at once (the title's - // threads are not asked: they would not know how to stop). - std::fprintf(stderr, "[rt] window: closed; the run ends\n"); - std::fflush(nullptr); - TerminateProcess(GetCurrentProcess(), 0); - return 0; - case kDestroyRequest: - DestroyWindow(hwnd); - return 0; - case WM_DESTROY: - PostQuitMessage(0); - return 0; - default: - return DefWindowProcW(hwnd, message, w, l); - } -} - -// V host.rs `make_window`: a WS_OVERLAPPEDWINDOW of the given client size, here shrunk (keeping its shape) to the -// primary monitor's work area and centred in it. -HWND make_window(std::uint32_t width, std::uint32_t height) { - const HINSTANCE instance = GetModuleHandleW(nullptr); - WNDCLASSEXW window_class{sizeof(window_class)}; - window_class.style = CS_HREDRAW | CS_VREDRAW; - window_class.lpfnWndProc = window_proc; - window_class.hInstance = instance; - window_class.hCursor = LoadCursorW(nullptr, MAKEINTRESOURCEW(32512)); // IDC_ARROW - window_class.hIcon = LoadIconW(nullptr, MAKEINTRESOURCEW(32512)); // IDI_APPLICATION - window_class.hbrBackground = static_cast(GetStockObject(BLACK_BRUSH)); - window_class.lpszClassName = kWindowClass; - if (!RegisterClassExW(&window_class) && GetLastError() != ERROR_CLASS_ALREADY_EXISTS) { - std::fprintf(stderr, "[rt] window: RegisterClassExW failed (%lu)\n", GetLastError()); - return nullptr; - } - constexpr DWORD style = WS_OVERLAPPEDWINDOW; - RECT work{0, 0, 1920, 1080}; - MONITORINFO monitor{sizeof(monitor)}; - if (GetMonitorInfoW(MonitorFromPoint(POINT{0, 0}, MONITOR_DEFAULTTOPRIMARY), &monitor)) work = monitor.rcWork; - RECT frame{0, 0, 1000, 1000}; - AdjustWindowRectEx(&frame, style, FALSE, 0); - const LONG frame_w = (frame.right - frame.left) - 1000, frame_h = (frame.bottom - frame.top) - 1000; - const LONG work_w = work.right - work.left, work_h = work.bottom - work.top; - const double scale = std::min({1.0, double(work_w - frame_w) / double(width), double(work_h - frame_h) / double(height)}); - const LONG client_w = std::max(1L, LONG(double(width) * scale)), client_h = std::max(1L, LONG(double(height) * scale)); - const LONG outer_w = client_w + frame_w, outer_h = client_h + frame_h; - const HWND hwnd = CreateWindowExW(0, kWindowClass, L"Leonida", style | WS_VISIBLE, - work.left + std::max(0L, (work_w - outer_w) / 2), - work.top + std::max(0L, (work_h - outer_h) / 2), outer_w, outer_h, nullptr, nullptr, - instance, nullptr); - if (!hwnd) { - std::fprintf(stderr, "[rt] window: CreateWindowExW failed (%lu)\n", GetLastError()); - return nullptr; - } - // The frame of a DPI-aware window can differ from the system-DPI guess above: make the client area exact. - RECT client{}; - if (GetClientRect(hwnd, &client) && (client.right != client_w || client.bottom != client_h)) { - RECT outer{}; - GetWindowRect(hwnd, &outer); - SetWindowPos(hwnd, nullptr, 0, 0, (outer.right - outer.left) + client_w - client.right, - (outer.bottom - outer.top) + client_h - client.bottom, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE); - } - std::fprintf(stderr, "[rt] window: %ldx%ld client area for the title's %ux%u frames%s\n", client_w, client_h, width, - height, scale < 1.0 ? " (shrunk to fit the monitor)" : ""); - return hwnd; -} - -} // namespace - -struct GameWindow::State { - HWND hwnd = nullptr; - bool owned = false; // made here (and destroyed here), not the title's - std::thread pump; - std::thread caption; - std::mutex mutex; - std::condition_variable wake; - bool stop = false; - leonida::FrameMeter meter; -}; - -namespace { - -// V host.rs "victory-caption": setting the text waits for the window's thread, so a thread of ours does it, once a -// second, from the counts the present path leaves. For the title's window that thread is the title's, which may not -// pump for a while: the wait is bounded, and only this thread waits. -void start_caption(GameWindow::State* s) { - s->caption = std::thread([s] { - name_thread(L"leonida-caption"); - leonida::FrameRateSampler sampler; - std::string shown; - std::unique_lock lock(s->mutex); - while (!s->wake.wait_for(lock, std::chrono::seconds(1), [s] { return s->stop; })) { - lock.unlock(); - leonida::FrameFigures figures; - if (sampler.sample(s->meter.read(), now_ns(), &figures)) { - const std::string text = leonida::caption_text(figures); - if (text != shown) { - const std::wstring wide(text.begin(), text.end()); // ASCII - DWORD_PTR result = 0; - SendMessageTimeoutW(s->hwnd, WM_SETTEXT, 0, reinterpret_cast(wide.c_str()), - SMTO_ABORTIFHUNG, 1000, &result); - shown = text; - } - } - lock.lock(); - } - }); -} - -std::atomic g_title_window{nullptr}; -std::atomic g_own_window{nullptr}; - -BOOL CALLBACK find_visible_window(HWND hwnd, LPARAM found) { - DWORD process = 0; - GetWindowThreadProcessId(hwnd, &process); - if (process != GetCurrentProcessId() || !IsWindowVisible(hwnd) || hwnd == g_own_window.load()) return TRUE; - // A console window can be reported as this process's: never present into it. - char window_class[32] = {}; - GetClassNameA(hwnd, window_class, sizeof(window_class)); - if (hwnd == GetConsoleWindow() || !std::strcmp(window_class, "ConsoleWindowClass") || - !std::strcmp(window_class, "PseudoConsoleWindow")) - return TRUE; - *reinterpret_cast(found) = hwnd; - return FALSE; -} - -} // namespace - -void note_title_window(HWND window) { g_title_window.store(window); } - -HWND title_window() { - if (const HWND noted = g_title_window.load(); noted && IsWindow(noted)) return noted; - HWND found = nullptr; - EnumWindows(&find_visible_window, reinterpret_cast(&found)); - return found; -} - -GameWindow::GameWindow(std::unique_ptr state) : state_(std::move(state)) {} - -std::unique_ptr GameWindow::adopt(HWND window) { - if (!window || !IsWindow(window)) return nullptr; - auto state = std::make_unique(); - state->hwnd = window; - RECT client{}; - GetClientRect(window, &client); - std::fprintf(stderr, "[rt] window: the title's own window shows its frames (%ldx%ld client area)\n", client.right, - client.bottom); - start_caption(state.get()); - return std::unique_ptr(new GameWindow(std::move(state))); -} - -std::unique_ptr GameWindow::create(std::uint32_t width, std::uint32_t height) { - if (!width || !height) return nullptr; - auto state = std::make_unique(); - std::promise made; - std::future hwnd = made.get_future(); - // V host.rs `window` and `pump`: the window belongs to a thread of ours that does nothing but pump its messages, - // so it answers (moves, resizes, the caption) while the title's threads are busy. - state->pump = std::thread([made = std::move(made), width, height]() mutable { - name_thread(L"leonida-window"); - make_thread_dpi_aware(); - const HWND window = make_window(width, height); - made.set_value(window); - if (!window) return; - MSG message; - while (GetMessageW(&message, nullptr, 0, 0) > 0) { - TranslateMessage(&message); - DispatchMessageW(&message); - } - }); - state->hwnd = hwnd.get(); - if (!state->hwnd) { - state->pump.join(); - return nullptr; - } - state->owned = true; - g_own_window.store(state->hwnd); - start_caption(state.get()); - return std::unique_ptr(new GameWindow(std::move(state))); -} - -GameWindow::~GameWindow() { - { - std::lock_guard lock(state_->mutex); - state_->stop = true; - } - state_->wake.notify_all(); - if (state_->caption.joinable()) state_->caption.join(); - if (state_->owned && state_->hwnd) { - HWND expected = state_->hwnd; - g_own_window.compare_exchange_strong(expected, nullptr); - PostMessageW(state_->hwnd, kDestroyRequest, 0, 0); - } - if (state_->pump.joinable()) state_->pump.join(); -} - -HWND GameWindow::hwnd() const { return state_->hwnd; } - -void GameWindow::frame_presented() { state_->meter.presented(now_ns()); } - -namespace { - -// The presented frame in a snapshot's swapchain format as 8-bit RGB, `width * 3` bytes a row. False for a format the -// presenter does not make. -bool to_rgb8(const leonida::PresentSnapshot& snapshot, std::vector& rgb) { - const std::size_t texels = std::size_t(snapshot.extent.width) * snapshot.extent.height; - const std::uint8_t* src = snapshot.pixels(); - if (!src || !texels) return false; - rgb.resize(texels * 3); - switch (snapshot.format) { - case VK_FORMAT_B8G8R8A8_UNORM: - case VK_FORMAT_B8G8R8A8_SRGB: - for (std::size_t i = 0; i < texels; ++i) { - rgb[i * 3 + 0] = src[i * 4 + 2]; - rgb[i * 3 + 1] = src[i * 4 + 1]; - rgb[i * 3 + 2] = src[i * 4 + 0]; - } - return true; - case VK_FORMAT_R8G8B8A8_UNORM: - case VK_FORMAT_R8G8B8A8_SRGB: - for (std::size_t i = 0; i < texels; ++i) std::memcpy(&rgb[i * 3], src + i * 4, 3); - return true; - case VK_FORMAT_A2B10G10R10_UNORM_PACK32: - case VK_FORMAT_A2R10G10B10_UNORM_PACK32: { - // An HDR10 swapchain: its PQ code values, scaled to 8 bits as they are (the PNG looks flat; it is not tone mapped). - const bool blue_low = snapshot.format == VK_FORMAT_A2R10G10B10_UNORM_PACK32; - for (std::size_t i = 0; i < texels; ++i) { - std::uint32_t word = 0; - std::memcpy(&word, src + i * 4, sizeof word); - const std::uint32_t low = word & 0x3ffu, mid = (word >> 10) & 0x3ffu, high = (word >> 20) & 0x3ffu; - const auto to8 = [](std::uint32_t v) { return std::uint8_t((v * 255u + 511u) / 1023u); }; - rgb[i * 3 + 0] = to8(blue_low ? high : low); - rgb[i * 3 + 1] = to8(mid); - rgb[i * 3 + 2] = to8(blue_low ? low : high); - } - return true; - } - default: - return false; - } -} - -// LEONIDA_CAPTURE_DIR: see xbox_window.h. -class FrameCapture { -public: - static std::unique_ptr from_environment() { - const std::wstring dir = environment(L"LEONIDA_CAPTURE_DIR"); - if (dir.empty()) return nullptr; - std::wstring request = environment(L"LEONIDA_CAPTURE_REQUEST"); - auto capture = std::unique_ptr(new FrameCapture(dir, request)); - capture->thread_ = std::thread([c = capture.get()] { c->work(); }); - return capture; - } - - ~FrameCapture() { - { - std::lock_guard lock(mutex_); - stop_ = true; - } - wake_.notify_all(); - if (thread_.joinable()) thread_.join(); - } - - // On the present thread, before each present: a request read since the last one asks for the next frame. - void before_present(WindowPresenter& presenter) { - const std::uint64_t wanted = requested_.load(std::memory_order_acquire); - std::uint64_t armed = armed_.load(std::memory_order_relaxed); - do { - if (wanted <= armed) return; - } while (!armed_.compare_exchange_weak(armed, wanted, std::memory_order_relaxed)); - presenter.request_snapshot([this, wanted](leonida::PresentSnapshot snapshot) { - { - std::lock_guard lock(mutex_); - jobs_.push_back(Job{wanted, std::move(snapshot)}); - } - wake_.notify_all(); - }); - } - -private: - struct Job { - std::uint64_t request; - leonida::PresentSnapshot snapshot; - }; - - FrameCapture(const std::filesystem::path& dir, const std::wstring& request) - : dir_(dir), request_file_(request.empty() ? dir / L"request.txt" : std::filesystem::path(request)) { - std::error_code ignored; - std::filesystem::create_directories(dir_, ignored); - std::fprintf(stderr, - "[rt] capture: screenshots on request into %s: a number in %s above the last one saves the next " - "presented frame as capture-.png\n", - utf8(dir_).c_str(), utf8(request_file_).c_str()); - } - - // The thread: the request file every 100 ms, and the snapshots its sink hands over, encoded and written here. - void work() { - name_thread(L"leonida-capture"); - std::unique_lock lock(mutex_); - for (;;) { - wake_.wait_for(lock, std::chrono::milliseconds(100), [this] { return stop_ || !jobs_.empty(); }); - while (!jobs_.empty()) { - Job job = std::move(jobs_.front()); - jobs_.pop_front(); - lock.unlock(); - write(job); - lock.lock(); - } - if (stop_) return; - lock.unlock(); - poll(); - lock.lock(); - } - } - - void poll() { - const HANDLE file = CreateFileW(request_file_.c_str(), GENERIC_READ, - FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, nullptr); - if (file == INVALID_HANDLE_VALUE) return; - char text[32] = {}; - DWORD read = 0; - const BOOL ok = ReadFile(file, text, sizeof(text) - 1, &read, nullptr); - CloseHandle(file); - if (!ok) return; - std::uint64_t number = 0; - std::size_t at = 0; - while (at < read && (text[at] == ' ' || text[at] == '\t' || text[at] == '\r' || text[at] == '\n')) ++at; - bool digits = false; - for (; at < read && text[at] >= '0' && text[at] <= '9' && number < 100000000000000000ull; ++at, digits = true) - number = number * 10 + std::uint64_t(text[at] - '0'); - if (!digits || number <= taken_) return; - taken_ = number; - requested_.store(number, std::memory_order_release); - std::fprintf(stderr, "[rt] capture: request %llu: the next presented frame is saved\n", - static_cast(number)); - } - - void write(Job& job) { - const auto start = std::chrono::steady_clock::now(); - const VkExtent2D extent = job.snapshot.extent; - const std::uint64_t frame = job.snapshot.frame; - std::vector rgb; - const bool converted = to_rgb8(job.snapshot, rgb); - job.snapshot.reset(); // the copy's memory goes back before the encoding - if (!converted) { - std::fprintf(stderr, "[rt] capture: request %llu: the swapchain format cannot be saved\n", - static_cast(job.request)); - return; - } - const std::vector png = leonida::png::encode_rgb8(extent.width, extent.height, rgb.data(), - std::size_t(extent.width) * 3); - const std::filesystem::path target = dir_ / (L"capture-" + std::to_wstring(job.request) + L".png"); - std::filesystem::path part = target; - part += L".part"; - { - std::ofstream out(part, std::ios::binary | std::ios::trunc); - out.write(reinterpret_cast(png.data()), std::streamsize(png.size())); - if (!out) { - std::fprintf(stderr, "[rt] capture: request %llu: cannot write %s\n", - static_cast(job.request), utf8(part).c_str()); - return; - } - } - if (!MoveFileExW(part.c_str(), target.c_str(), MOVEFILE_REPLACE_EXISTING)) { - std::fprintf(stderr, "[rt] capture: request %llu: cannot rename %s (%lu)\n", - static_cast(job.request), utf8(part).c_str(), GetLastError()); - return; - } - const double ms = std::chrono::duration(std::chrono::steady_clock::now() - start).count(); - std::fprintf(stderr, "[rt] capture: request %llu: frame %llu (%ux%u) saved as %s in %.0f ms\n", - static_cast(job.request), static_cast(frame), extent.width, - extent.height, utf8(target).c_str(), ms); - } - - std::filesystem::path dir_; - std::filesystem::path request_file_; - std::atomic requested_{0}; // the newest number read from the request file - std::uint64_t taken_ = 0; // the same, for the capture thread - std::atomic armed_{0}; // the newest asked of the presenter (present threads) - std::mutex mutex_; - std::condition_variable wake_; - std::deque jobs_; - bool stop_ = false; - std::thread thread_; -}; - -// The present handler's context: the device proxy, and what the first PresentX makes. -class TitlePresentation { -public: - explicit TitlePresentation(void* device) : device_(device), capture_(FrameCapture::from_environment()) {} - - HRESULT present(ID3D12CommandQueue* queue, std::uint32_t plane_count, const void* planes_word, - const void* params_word) { - const auto* planes = static_cast(planes_word); - const auto* params = static_cast(params_word); - XboxPresentation* presentation = presentation_.load(std::memory_order_acquire); - if (!presentation) presentation = ready(queue, plane_count, planes); - if (!presentation) return S_OK; // nothing can be shown (logged once by ready) - if (capture_) capture_->before_present(presentation->presenter()); - const HRESULT hr = presentation->PresentX(plane_count, planes, params); - if (SUCCEEDED(hr)) { - window_->frame_presented(); - return hr; - } - // V queue.rs:757-841 answers S_OK whatever it showed; a console title does not expect PresentX to fail. - if (failures_logged_.fetch_add(1, std::memory_order_relaxed) < 8) - std::fprintf(stderr, "[rt] present: PresentX with %u plane(s) was not shown (0x%08lx); answered S_OK\n", - plane_count, static_cast(hr)); - return S_OK; - } - -private: - XboxPresentation* ready(ID3D12CommandQueue* queue, std::uint32_t plane_count, - const XboxPresentPlaneParameters* planes) { - std::lock_guard lock(setup_); - if (XboxPresentation* made = presentation_.load(std::memory_order_acquire)) return made; - if (failed_) return nullptr; - failed_ = true; // until everything below is made - // V host.rs `presenter`: the window has the first plane's size (the display mode for a blank first present). - const leonida::DisplayMode mode = title_display_mode(); - std::uint32_t width = mode.width, height = mode.height; - if (plane_count && planes && planes[0].ResourceCount && planes[0].ppResources && planes[0].ppResources[0]) { - const D3D12_RESOURCE_DESC desc = planes[0].ppResources[0]->GetDesc(); - if (desc.Width && desc.Height && desc.Width <= 16384 && desc.Height <= 16384) { - width = std::uint32_t(desc.Width); - height = desc.Height; - } - } - // LEONIDA_ASPECT: a window the runtime makes is that wide too, as the title's own is (title_window.cpp). - if (const double ratio = title_aspect_ratio(); ratio > 0.0) width = leonida::aspect::widen({width, height}, ratio).width; - const HWND title = title_window(); - window_ = title ? GameWindow::adopt(title) : GameWindow::create(width, height); - if (!window_) { - std::fprintf(stderr, "[rt] present: no window: the title's frames are not shown\n"); - return nullptr; - } - std::unique_ptr presenter = - create_window_presenter(static_cast(device_), window_->hwnd(), queue); - if (!presenter) { - std::fprintf(stderr, "[rt] present: no swapchain on the window: the title's frames are not shown\n"); - return nullptr; - } - if (capture_ && !presenter->enable_snapshots()) - std::fprintf(stderr, "[rt] capture: this swapchain cannot be copied from: no screenshots\n"); - owned_ = std::make_unique(std::move(presenter)); - void* const device = device_; - owned_->use_device_frame_clock([device] { return d3d12_xs::device_frames_begun(device); }); - failed_ = false; - presentation_.store(owned_.get(), std::memory_order_release); - std::fprintf(stderr, "[rt] present: the title's frames go to its window (swapchain %ux%u), paced by the device's " - "frame clock\n", - owned_->presenter().extent().width, owned_->presenter().extent().height); - return owned_.get(); - } - - void* const device_; - std::unique_ptr capture_; - std::mutex setup_; - bool failed_ = false; - std::unique_ptr window_; - std::unique_ptr owned_; - std::atomic presentation_{nullptr}; - std::atomic failures_logged_{0}; -}; - -HRESULT title_present(void* context, ID3D12CommandQueue* queue, std::uint32_t plane_count, const void* planes, - const void* parameters) { - return static_cast(context)->present(queue, plane_count, planes, parameters); -} - -} // namespace - -bool attach_title_presentation(void* device) { - void* const proxy = d3d12_xs::device_proxy_primary(device); - if (!proxy) { - std::fprintf(stderr, "[rt] present: %p is not a device proxy; PresentX is not shown\n", device); - return false; - } - // Lives as long as the process: the device proxy keeps a pointer to it and its threads run to the end. - auto* presentation = new (std::nothrow) TitlePresentation(proxy); - if (!presentation) return false; - if (!d3d12_xs::set_present_handler(proxy, &title_present, presentation)) { - delete presentation; - return false; - } - std::fprintf(stderr, "[rt] present: PresentX (console queue slot 32) is shown in a window, opened at the first " - "frame\n"); - return true; -} - -} // namespace rt::d3d12 diff --git a/runtime/shims/xbox_window.h b/runtime/shims/xbox_window.h deleted file mode 100644 index 4b6638a72..000000000 --- a/runtime/shims/xbox_window.h +++ /dev/null @@ -1,73 +0,0 @@ -#pragma once - -// The title's window, and what puts the frames the title presents there (docs/d3d12_vulkan.md section 4.5). -// -// A GDKX title makes no window and presents through the console queue's PresentX (queue slot 32 in the console -// layout). attach_title_presentation sets the device proxy's present handler (d3d12_xs::set_present_handler): at the -// first PresentX a window is made, a Vulkan swapchain on it on the queue the title presents on (create_window_presenter), -// and an XboxPresentation over that, which composes the title's planes into the swapchain. The title's frame calls stay -// with the device's frame clock (device slots 78-81, VIctory's frame.rs); the presentation takes its tokens from there -// and does not pace (XboxPresentation::use_device_frame_clock). -// -// Ported from VIctory (GPL-3.0-or-later, Marvisak and contributors, DexNom fork; victory/crates/victory-gpu/src/ -// host.rs `presenter`, `title_window`, `window`, `make_window`, `pump`, `Meter` and the "victory-caption" thread; -// queue.rs:757-841 `present`): -// - The frames go to the title's own window when it has one (V `title_window`): the title makes a top-level window -// itself (CreateWindowExA, which title_window.cpp fits to the screen) and pumps its messages. Otherwise a window is -// made at the first present, with a client area of the first plane's size, on a thread of its own that pumps its -// messages ("leonida-window"; V "victory-window"). That size is shrunk, keeping its shape, to fit the primary -// monitor's work area (a 3840x2160 back buffer on a 2560x1440 monitor would not fit), the window is centred and -// per-monitor DPI aware (only its own thread is), and closing it ends the run. -// - Its caption is "Leonida | fps ms/frame" (src/frame_meter.h), set once a second by a thread of its own -// ("leonida-caption"), so presenting never waits for the window's thread. -// - A PresentX that cannot be shown (no window, no swapchain, a refused plane) is answered S_OK, as VIctory's present -// always is, and logged; the d3d12 trace still says `XboxPresentation::PresentX failed`. -// -// Screenshots for automation (V capture.rs:170-185 VICTORY_CAPTURE_REQUEST, `save_as`): with LEONIDA_CAPTURE_DIR=, -// a thread ("leonida-capture") reads the request file every 100 ms: LEONIDA_CAPTURE_REQUEST, else \request.txt, -// holding a number. When the number is above the last one it took (0 at the start), the next frame presented after it is -// copied (VulkanPresenter::request_snapshot: in the frame's own command buffer, nothing read on the present path) and -// that thread writes it as \capture-.png: 8-bit RGB at the swapchain's size (src/png_write.h), written to a -// .part file and renamed, so a file that exists is whole. VIctory halves its frames and reads the request file on the -// present path; this keeps the size and reads it off that path. -#include - -#include -#include - -namespace rt::d3d12 { - -// The window: see the top comment. Destroying it joins its threads, and closes the window if it made it. -class GameWindow { -public: - // A window whose client area is `width` x `height`, shrunk to fit the primary monitor's work area. Null on failure - // (logged). - static std::unique_ptr create(std::uint32_t width, std::uint32_t height); - // The title's own window: only the caption is ours. Null for something that is not a window. - static std::unique_ptr adopt(HWND window); - ~GameWindow(); - GameWindow(const GameWindow&) = delete; - GameWindow& operator=(const GameWindow&) = delete; - - HWND hwnd() const; - // A frame was shown: counted for the caption. Lock-free; any thread. - void frame_presented(); - - struct State; - -private: - explicit GameWindow(std::unique_ptr state); - std::unique_ptr state_; -}; - -// Sets the present handler of `device` (an Xbox-ABI device proxy over the Vulkan device, or its DXGI pointer) to the -// title presentation above. False, with nothing set, for anything else. The window opens at the first PresentX. -bool attach_title_presentation(void* device); - -// The title made `window`, a top-level window (title_window.cpp): the frames go there. -void note_title_window(HWND window); -// The window the frames go to if the title presents now: the one noted above while it exists, else a visible top-level -// window of this process that is not the runtime's (V host.rs `title_window`), else null. -HWND title_window(); - -} // namespace rt::d3d12 diff --git a/runtime/shims/xgameruntime_user.cpp b/runtime/shims/xgameruntime_user.cpp index 7c8cdf654..d4f991995 100644 --- a/runtime/shims/xgameruntime_user.cpp +++ b/runtime/shims/xgameruntime_user.cpp @@ -555,10 +555,7 @@ const void* const kUserVtable[] = { FN(user_find_by_id), // 12 XUserFindUserById FN(user_get_is_guest), // 13 XUserGetIsGuest FN(user_get_state), // 14 XUserGetState - // 15: the older XUserGetGamertag slot, (user, component, size, buffer, used) as the separate gamertag - // interface's slot 3 takes them (VIctory victory-hle src/modules/xuser.rs, GPL-3.0-or-later: "older gamertag - // slot", 0x78, measured on the same title). - FN(user_get_gamertag), // 15 XUserGetGamertag (older slot) + FN(unknown_slot<15>), // 15 (unknown in the docs) FN((offline_failure<16, E_FAIL>)), // 16 XUserGetGamerPictureAsync FN((offline_failure<17, E_FAIL>)), // 17 XUserGetGamerPictureResultSize FN((offline_failure<18, E_FAIL>)), // 18 XUserGetGamerPictureResult diff --git a/runtime/src/aspect_fit.h b/runtime/src/aspect_fit.h deleted file mode 100644 index feef6c6a2..000000000 --- a/runtime/src/aspect_fit.h +++ /dev/null @@ -1,222 +0,0 @@ -#pragma once - -// Ultrawide support (docs/ultrawide.md): the aspect the user asks for, the wider display mode the title is told about, -// and where a frame goes in a window of another shape. Pure arithmetic, no Windows or Vulkan headers; -// test/aspect_fit_test.cpp checks it. -// -// LEONIDA_ASPECT=W:H (or a decimal, or `auto` for the primary monitor's shape): the console output's display mode -// (shims/xbox_display.cpp) and the title's window (shims/title_window.cpp) are widened to that aspect, keeping their -// height. Unset, empty, `off` or `none`: nothing changes. A ratio at or below the mode's own aspect changes nothing. -// LEONIDA_PRESENT_SCALE=fit|stretch: how a frame is put in a window of another shape (src/vulkan_present.h). `fit` -// keeps the frame's aspect: it is centred, as large as fits, with black bars beside it (pillarbox) or above and below -// (letterbox). `stretch` fills the window whatever the shapes, as before. Default: `fit` when LEONIDA_ASPECT asks for -// an aspect, else `stretch`. - -#include "display_mode.h" - -#include -#include -#include - -namespace leonida::aspect { - -// The ratios LEONIDA_ASPECT takes: square up to four times as wide as high (32:9 is 3.56). -inline constexpr double kMinRatio = 1.0; -inline constexpr double kMaxRatio = 4.0; - -enum class Kind { none, ratio, automatic }; - -struct Request { - Kind kind = Kind::none; - double ratio = 0.0; // width over height, for Kind::ratio -}; - -namespace detail { -inline std::string_view trim(std::string_view s) { - while (!s.empty() && (s.front() == ' ' || s.front() == '\t')) s.remove_prefix(1); - while (!s.empty() && (s.back() == ' ' || s.back() == '\t' || s.back() == '\r' || s.back() == '\n')) s.remove_suffix(1); - return s; -} -inline bool same_word(std::string_view a, std::string_view b) { - if (a.size() != b.size()) return false; - for (std::size_t i = 0; i < a.size(); ++i) { - char c = a[i]; - if (c >= 'A' && c <= 'Z') c = char(c - 'A' + 'a'); - if (c != b[i]) return false; - } - return true; -} -// A decimal number without sign or exponent ("21", "2.39", ".5"), locale-independent. False for anything else. -inline bool number(std::string_view s, double* out) { - s = trim(s); - if (s.empty() || s.size() > 12) return false; - double value = 0.0, scale = 1.0; - bool dot = false, digits = false; - for (const char c : s) { - if (c == '.') { - if (dot) return false; - dot = true; - } else if (c >= '0' && c <= '9') { - digits = true; - if (dot) { - scale /= 10.0; - value += scale * double(c - '0'); - } else { - value = value * 10.0 + double(c - '0'); - } - } else { - return false; - } - } - if (!digits) return false; - *out = value; - return true; -} -inline std::uint32_t round_even(double v) { return std::uint32_t(std::lround(v / 2.0)) * 2u; } -} // namespace detail - -// LEONIDA_ASPECT's text: empty, `off` or `none` (any case) is Kind::none; `auto` is Kind::automatic; `W:H` or `W/H` -// (decimals allowed on either side) or a single decimal is Kind::ratio when the ratio is in kMinRatio..kMaxRatio. -// False, with `*out` untouched, for anything else. -inline bool parse_request(std::string_view text, Request* out) { - text = detail::trim(text); - Request r; - if (text.empty() || detail::same_word(text, "off") || detail::same_word(text, "none")) { - r.kind = Kind::none; - } else if (detail::same_word(text, "auto")) { - r.kind = Kind::automatic; - } else { - const std::size_t colon = text.find_first_of(":/"); - double ratio = 0.0; - if (colon == std::string_view::npos) { - if (!detail::number(text, &ratio)) return false; - } else { - double w = 0.0, h = 0.0; - if (!detail::number(text.substr(0, colon), &w) || !detail::number(text.substr(colon + 1), &h) || !(h > 0.0)) - return false; - ratio = w / h; - } - if (!(ratio >= kMinRatio && ratio <= kMaxRatio)) return false; - r.kind = Kind::ratio; - r.ratio = ratio; - } - if (out) *out = r; - return true; -} - -// The ratio a request stands for: the monitor's `monitor_width` / `monitor_height` for Kind::automatic (0 when that is -// not known or outside kMinRatio..kMaxRatio), 0 for Kind::none. -inline double resolve(const Request& request, std::uint32_t monitor_width = 0, std::uint32_t monitor_height = 0) { - if (request.kind == Kind::ratio) return request.ratio; - if (request.kind == Kind::automatic && monitor_width && monitor_height) { - const double ratio = double(monitor_width) / double(monitor_height); - return ratio >= kMinRatio && ratio <= kMaxRatio ? ratio : 0.0; - } - return 0.0; -} - -struct Size { - std::uint32_t width = 0, height = 0; -}; - -// `size` made `ratio` wide by widening it (the height kept, the width rounded to an even number). Unchanged when the -// ratio is not wider than the size already is, or for an empty size. -inline Size widen(Size size, double ratio) { - if (!size.width || !size.height || !(ratio > 0.0) || !std::isfinite(ratio)) return size; - const double width = double(size.height) * ratio; - if (width < double(size.width) + 1.0) return size; - size.width = detail::round_even(width); - return size; -} - -// The display mode the console output reports with LEONIDA_ASPECT: `mode` widened to `ratio` (widen above), kept inside -// parse_display_mode's range: a width above 7680 is 7680, with the height made smaller to keep the ratio. -inline DisplayMode widen_display_mode(DisplayMode mode, double ratio) { - const Size wide = widen({mode.width, mode.height}, ratio); - if (wide.width == mode.width) return mode; - mode.width = wide.width; - if (mode.width > 7680) { - mode.width = 7680; - mode.height = detail::round_even(7680.0 / ratio); - if (mode.height < 360) mode.height = 360; - } - return mode; -} - -enum class Scaling { stretch, fit }; - -// LEONIDA_PRESENT_SCALE's text: `fit` or `stretch` (any case). False, with `*out` untouched, for anything else. -inline bool parse_scaling(std::string_view text, Scaling* out) { - text = detail::trim(text); - Scaling s; - if (detail::same_word(text, "fit")) s = Scaling::fit; - else if (detail::same_word(text, "stretch")) s = Scaling::stretch; - else return false; - if (out) *out = s; - return true; -} - -// The scaling from the two variables' values (null: unset): LEONIDA_PRESENT_SCALE when it parses, else `fit` when -// LEONIDA_ASPECT asks for an aspect (a ratio or `auto`), else `stretch`. -inline Scaling scaling_from(const char* present_scale, const char* aspect_text) { - Scaling s = Scaling::stretch; - if (present_scale && parse_scaling(present_scale, &s)) return s; - Request request; - if (aspect_text && parse_request(aspect_text, &request) && request.kind != Kind::none) return Scaling::fit; - return Scaling::stretch; -} - -// A rectangle of the output in pixels: left/top inclusive, right/bottom exclusive. -struct Box { - std::int32_t left = 0, top = 0, right = 0, bottom = 0; - std::int32_t width() const { return right - left; } - std::int32_t height() const { return bottom - top; } -}; - -inline bool is_whole(const Box& box, std::uint32_t out_width, std::uint32_t out_height) { - return box.left == 0 && box.top == 0 && box.right == std::int32_t(out_width) && box.bottom == std::int32_t(out_height); -} - -// Where content of aspect `content` (width over height) goes in an output of `out_width` x `out_height` with -// Scaling::fit: centred, as large as fits, so the bars are beside it when the content is narrower (pillarbox) and -// above and below when it is wider (letterbox). The whole output when the two shapes differ by less than a pixel, and -// for an empty output or a content aspect that is not a positive finite number. -inline Box fit_box(double content, std::uint32_t out_width, std::uint32_t out_height) { - const Box whole{0, 0, std::int32_t(out_width), std::int32_t(out_height)}; - if (!out_width || !out_height || !(content > 0.0) || !std::isfinite(content)) return whole; - const double ow = double(out_width), oh = double(out_height); - if (content < ow / oh) { // narrower: pillarbox - const double width = oh * content; - if (ow - width < 1.0) return whole; - std::int32_t w = std::int32_t(std::lround(width)); - if (w < 1) w = 1; - const std::int32_t left = (std::int32_t(out_width) - w) / 2; - return {left, 0, left + w, std::int32_t(out_height)}; - } - const double height = ow / content; // wider (or the same): letterbox - if (oh - height < 1.0) return whole; - std::int32_t h = std::int32_t(std::lround(height)); - if (h < 1) h = 1; - const std::int32_t top = (std::int32_t(out_height) - h) / 2; - return {0, top, std::int32_t(out_width), top + h}; -} - -// The aspect of the output a plane was composed for: a source of `source_width` x `source_height` texels shown -// undistorted in `dest` (left, top, right, bottom as fractions of that output) makes it -// (source_width / source_height) * (dest height / dest width). 0 for an empty source or destination. -inline double content_aspect(double source_width, double source_height, const float dest[4]) { - const double dw = double(dest[2]) - double(dest[0]), dh = double(dest[3]) - double(dest[1]); - if (!(source_width > 0.0) || !(source_height > 0.0) || !(dw > 0.0) || !(dh > 0.0)) return 0.0; - return source_width / source_height * dh / dw; -} - -// `dest` (fractions of the title's output) in output pixels once that output is `box`. -inline void place(const float dest[4], const Box& box, float out[4]) { - const float w = float(box.width()), h = float(box.height()); - out[0] = float(box.left) + dest[0] * w; - out[1] = float(box.top) + dest[1] * h; - out[2] = float(box.left) + dest[2] * w; - out[3] = float(box.top) + dest[3] * h; -} - -} // namespace leonida::aspect diff --git a/runtime/src/bcpack_decode.h b/runtime/src/bcpack_decode.h deleted file mode 100644 index 37175caa4..000000000 --- a/runtime/src/bcpack_decode.h +++ /dev/null @@ -1,19 +0,0 @@ -// The BCPack entry point DirectStorage calls (shims/dstorage_xs.cpp, ported from VIctory's -// crates/victory-hle/src/modules/dstorage.rs). Defined in bcpack.cpp, a port of VIctory's victory-formats BCPack -// decoder (GPL-3.0-or-later, Marvisak and contributors, DexNom fork); Leonida is GPL-3.0-or-later too. -// bcpack_decode_stub.cpp defines it too, always false, for dstorage_xs_test only (see runtime/CMakeLists.txt). -// -// BCPack is the Xbox Series' packed form of BCn texture blocks, which the console's DirectStorage hardware unpacks -// while it reads. -// format: the BC number of the request (DSTORAGE_BCPACK_MODE, options bits 1-4): 1 and 3-7; BC2 is not supported. -// dst_size: the decoded size, a whole number of blocks. Bytes after the last one the stream needs are ignored. -// Returns false when the format tables are missing or refused (see bcpack.h), for an unsupported format, a bad size -// or a stream that ends early or is corrupt; `dst` may then hold some blocks already, and the request completes with -// HRESULT_FROM_WIN32(ERROR_INVALID_DATA). Thread-safe. -#pragma once - -#include -#include - -bool leonida_bcpack_decode(std::uint32_t format, const std::uint8_t* src, std::size_t src_size, std::uint8_t* dst, - std::size_t dst_size); diff --git a/runtime/src/bcpack_decode_stub.cpp b/runtime/src/bcpack_decode_stub.cpp deleted file mode 100644 index 57bd7cd54..000000000 --- a/runtime/src/bcpack_decode_stub.cpp +++ /dev/null @@ -1,12 +0,0 @@ -// No BCPack decoder yet: the stand-in for leonida_bcpack_decode (bcpack_decode.h) until the decoder is ported. Part of -// the port of VIctory's crates/victory-hle/src/modules/dstorage.rs (GPL-3.0-or-later; Marvisak and contributors, -// DexNom fork); Leonida is GPL-3.0-or-later too. -// -// Every call fails, so a DirectStorage request with a BCPack stage completes with an error status, which the shim logs -// once per BC format, instead of leaving whatever the destination held. The decoder's own file takes this one's place -// in the gta6rt target. -#include "bcpack_decode.h" - -bool leonida_bcpack_decode(std::uint32_t, const std::uint8_t*, std::size_t, std::uint8_t*, std::size_t) { - return false; -} diff --git a/runtime/src/console_insn.cpp b/runtime/src/console_insn.cpp deleted file mode 100644 index e8f079fc6..000000000 --- a/runtime/src/console_insn.cpp +++ /dev/null @@ -1,334 +0,0 @@ -// The console-only instruction emulation of console_insn.h: the decoder (portable) and the vectored handler that -// uses it (Win32). Behaviour ported from VIctory victory-loader src/console_insn.rs (GPL-3.0-or-later); see the header -// for what is VIctory's and where the encodings come from. -#include "console_insn.h" - -#include -#include -#include - -#if defined(_WIN32) -#include - -#include "../shims/shims.h" -#endif - -namespace rt::console_insn { - -namespace { - -// The ModRM operand's length (ModRM, SIB and displacement) at `b`, 0 when the bytes run out. -size_t modrm_length(const uint8_t* b, size_t size) { - if (size < 1) return 0; - const uint8_t mod = b[0] >> 6, rm = b[0] & 7; - if (mod == 3) return 1; - size_t length = 1; - uint8_t base = rm; - if (rm == 4) { - if (size < 2) return 0; - base = b[1] & 7; - ++length; - } - if (mod == 1) length += 1; - else if (mod == 2 || (mod == 0 && base == 5)) length += 4; // mod 0 base 5: disp32 (RIP-relative without a SIB) - return length <= size ? length : 0; -} - -} // namespace - -Decoded decode(const uint8_t* code, size_t size) { - Decoded none; - if (!code) return none; - size_t i = 0; - bool p66 = false, p67 = false; - uint8_t rep = 0; // the last of F2 / F3: the one that selects the instruction - uint8_t rex = 0; // a REX counts only right before the opcode; a legacy prefix after it cancels it - for (; i < size && i < 15; ++i) { - const uint8_t b = code[i]; - if (b >= 0x40 && b <= 0x4F) { - rex = b; - continue; - } - if (b == 0x66) p66 = true; - else if (b == 0x67) p67 = true; - else if (b == 0xF2 || b == 0xF3) rep = b; - else if (b != 0x26 && b != 0x2E && b != 0x36 && b != 0x3E && b != 0x64 && b != 0x65) break; - rex = 0; - } - if (i + 2 > size || code[i] != 0x0F) return none; - const uint8_t op = code[i + 1]; - const bool rex_r = (rex & 4) != 0, rex_b = (rex & 1) != 0; - - if (op == 0x0B) return {Kind::Ud2, static_cast(i + 2)}; - if (i + 3 > size) return none; - const uint8_t m = code[i + 2]; - const uint8_t mod = m >> 6, reg = (m >> 3) & 7, rm = m & 7; - - switch (op) { - case 0x01: - if (m == 0xFC) { - // clzero; add rax, 40h (48 83 C0 40); cmp rax, r64 (48|4C 39 /r, r/m = rax); jb -12 (72 F4), the jb - // landing on the clzero. Not after a 67: that CLZERO is at EAX, and it is stepped alone. - const uint8_t* l = code + i; - if (!p67 && size >= i + 12 && l[3] == 0x48 && l[4] == 0x83 && l[5] == 0xC0 && l[6] == 0x40 && - (l[7] == 0x48 || l[7] == 0x4C) && l[8] == 0x39 && (l[9] >> 6) == 3 && (l[9] & 7) == 0 && - l[10] == 0x72 && l[11] == 0xF4) { - Decoded d{Kind::ClzeroLoop, static_cast(i + 12)}; - d.reg = static_cast(((l[9] >> 3) & 7) | (l[7] == 0x4C ? 8 : 0)); - return d; - } - Decoded d{Kind::Clzero, static_cast(i + 3)}; - d.address32 = p67; - return d; - } - if (m == 0xFD) return {Kind::Rdpru, static_cast(i + 3)}; - if (m == 0xFA) return {Kind::Monitorx, static_cast(i + 3)}; - if (m == 0xFB) return {Kind::Mwaitx, static_cast(i + 3)}; - return none; - case 0xAE: { - // 66 0F AE /6 with a memory operand; without the 66 it is XSAVEOPT, with F3 another instruction. - if (!p66 || rep || reg != 6 || mod == 3) return none; - const size_t operand = modrm_length(code + i + 2, size - (i + 2)); - if (!operand) return none; - return {Kind::Clwb, static_cast(i + 2 + operand)}; - } - case 0xC7: { - if (rep != 0xF3 || reg != 7 || mod != 3) return none; - Decoded d{Kind::Rdpid, static_cast(i + 3)}; - d.reg = static_cast(rm | (rex_b ? 8 : 0)); - return d; - } - case 0x78: - case 0x79: { - // SSE4a, register operands only. F2 selects INSERTQ, F3 nothing; 66 without either selects EXTRQ. - if (mod != 3) return none; - const bool insert = rep == 0xF2; - if (!insert && !(rep == 0 && p66)) return none; - const uint8_t xreg = static_cast(reg | (rex_r ? 8 : 0)); - const uint8_t xrm = static_cast(rm | (rex_b ? 8 : 0)); - Decoded d{insert ? Kind::Insertq : Kind::Extrq}; - if (op == 0x78) { - if (i + 5 > size) return none; - if (!insert && reg != 0) return none; // EXTRQ xmm, imm8, imm8 is /0 - d.reg = insert ? xreg : xrm; - d.src = xrm; - d.field_length = code[i + 3] & 63; - d.field_index = code[i + 4] & 63; - d.length = static_cast(i + 5); - } else { - d.reg = xreg; - d.src = xrm; - d.from_register = true; - d.length = static_cast(i + 3); - } - return d; - } - default: - return none; - } -} - -namespace { -unsigned field_bits(unsigned length) { return (length & 63) ? (length & 63) : 64; } -uint64_t low_ones(unsigned bits) { return bits >= 64 ? ~0ull : (1ull << bits) - 1; } -} // namespace - -uint64_t extrq(uint64_t value, unsigned field_length, unsigned field_index) { - const unsigned bits = field_bits(field_length), index = field_index & 63; - return (value >> index) & low_ones(bits); -} - -uint64_t insertq(uint64_t dst, uint64_t src, unsigned field_length, unsigned field_index) { - const unsigned bits = field_bits(field_length), index = field_index & 63; - const uint64_t mask = low_ones(bits) << index; // the bits of the field that fall inside the quadword - return (dst & ~mask) | ((src << index) & mask); -} - -namespace { -std::atomic g_emulated{0}; -} -uint64_t emulated_count() { return g_emulated.load(std::memory_order_relaxed); } - -#if defined(_WIN32) - -namespace { - -// Where the committed, writable memory `at` lies in ends, at most `end`; 0 when `at` is not in such memory. -uintptr_t writable_until(uintptr_t at, uintptr_t end) { - MEMORY_BASIC_INFORMATION mbi{}; - if (!VirtualQuery(reinterpret_cast(at), &mbi, sizeof(mbi)) || mbi.State != MEM_COMMIT) return 0; - if (mbi.Protect & (PAGE_GUARD | PAGE_NOACCESS)) return 0; - if (!(mbi.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_WRITECOPY))) return 0; - const uintptr_t region_end = reinterpret_cast(mbi.BaseAddress) + mbi.RegionSize; - return region_end < end ? region_end : end; -} - -DWORD64* gpr(CONTEXT* c, unsigned index) { - DWORD64* const regs[16] = {&c->Rax, &c->Rcx, &c->Rdx, &c->Rbx, &c->Rsp, &c->Rbp, &c->Rsi, &c->Rdi, - &c->R8, &c->R9, &c->R10, &c->R11, &c->R12, &c->R13, &c->R14, &c->R15}; - return regs[index & 15]; -} - -const char* name(Kind k) { - switch (k) { - case Kind::Clwb: return "CLWB"; - case Kind::Clzero: return "CLZERO"; - case Kind::ClzeroLoop: return "a CLZERO loop"; - case Kind::Rdpru: return "RDPRU"; - case Kind::Monitorx: return "MONITORX"; - case Kind::Mwaitx: return "MWAITX"; - case Kind::Rdpid: return "RDPID"; - case Kind::Extrq: return "EXTRQ"; - case Kind::Insertq: return "INSERTQ"; - default: return "?"; - } -} - -} // namespace - -bool emulate(CONTEXT* ctx, const uint8_t* code, size_t size) { - const Decoded d = decode(code, size); - if (d.kind == Kind::None || d.kind == Kind::Ud2) return false; - - static std::atomic s_logged[16]; - if (!s_logged[static_cast(d.kind) & 15].exchange(true)) - std::fprintf(stderr, "[rt] cpu: %s is a console CPU instruction this CPU lacks: emulated (logged once)\n", - name(d.kind)); - - switch (d.kind) { - case Kind::Clwb: { - // Nothing to write back on a PC: the instruction becomes NOPs, so it never faults again. - DWORD old = 0; - void* at = reinterpret_cast(ctx->Rip); - if (VirtualProtect(at, d.length, PAGE_EXECUTE_READWRITE, &old)) { - std::memset(at, 0x90, d.length); - VirtualProtect(at, d.length, old, &old); - FlushInstructionCache(GetCurrentProcess(), at, d.length); - } - break; - } - case Kind::Monitorx: - break; - case Kind::Mwaitx: - YieldProcessor(); - break; - case Kind::Clzero: { - const uintptr_t line = static_cast(d.address32 ? (ctx->Rax & 0xFFFFFFFFull) : ctx->Rax) & ~uintptr_t{63}; - if (writable_until(line, line + 64) != line + 64) return false; // the real instruction faults there too - std::memset(reinterpret_cast(line), 0, 64); - break; - } - case Kind::ClzeroLoop: { - // The loop's effect: every line from rAX's up to the first rAX + 64k at or past the end is zeroed, and rAX - // is left there with the jb not taken (CF clear; ZF as the last compare set it). - const uint64_t start = ctx->Rax, end = *gpr(ctx, d.reg); - if (end <= start || end - start >= (uint64_t{2} << 30)) { - // One line and once round, as the CPU would take it. - const uintptr_t line = static_cast(start) & ~uintptr_t{63}; - if (writable_until(line, line + 64) != line + 64) return false; - std::memset(reinterpret_cast(line), 0, 64); - ctx->Rax = start + 64; - ctx->Rip += (d.length - 12) + 7; // past clzero and add: the cmp and jb run as code - g_emulated.fetch_add(1, std::memory_order_relaxed); - return true; - } - const uint64_t final_rax = start + ((end - start + 63) / 64) * 64; - const uintptr_t from = static_cast(start) & ~uintptr_t{63}; - const uintptr_t to = static_cast((final_rax - 64) & ~uint64_t{63}) + 64; - uintptr_t at = from; - while (at < to) { - const uintptr_t until = writable_until(at, to); - if (!until) break; - std::memset(reinterpret_cast(at), 0, until - at); - at = until; - } - if (at == from) return false; - if (at < to) { - // What follows is not writable: the loop resumes at that line (the same instruction again), where the - // real one faults too. rAX keeps its offset in the line. - ctx->Rax = at + (start & 63); - g_emulated.fetch_add(1, std::memory_order_relaxed); - return true; - } - ctx->Rax = final_rax; - constexpr DWORD kCarry = 0x1, kZero = 0x40; - ctx->EFlags = (ctx->EFlags & ~(kCarry | kZero)) | (final_rax == end ? kZero : 0); - break; - } - case Kind::Rdpru: { - LARGE_INTEGER counter{}; - QueryPerformanceCounter(&counter); - const uint64_t v = (ctx->Rcx & 0xFFFFFFFFull) <= 1 ? static_cast(counter.QuadPart) : 0; - ctx->Rax = v & 0xFFFFFFFFull; - ctx->Rdx = v >> 32; - break; - } - case Kind::Rdpid: - *gpr(ctx, d.reg) = GetCurrentProcessorNumber(); - break; - case Kind::Extrq: { - M128A* x = ctx->FltSave.XmmRegisters; - unsigned length = d.field_length, index = d.field_index; - if (d.from_register) { - const uint64_t control = x[d.src & 15].Low; - length = control & 63; - index = (control >> 8) & 63; - } - x[d.reg & 15].Low = extrq(x[d.reg & 15].Low, length, index); - x[d.reg & 15].High = 0; - break; - } - case Kind::Insertq: { - M128A* x = ctx->FltSave.XmmRegisters; - const M128A source = x[d.src & 15]; - unsigned length = d.field_length, index = d.field_index; - if (d.from_register) { - const uint64_t control = static_cast(source.High); - length = control & 63; - index = (control >> 8) & 63; - } - x[d.reg & 15].Low = insertq(x[d.reg & 15].Low, source.Low, length, index); - x[d.reg & 15].High = 0; - break; - } - default: - return false; - } - ctx->Rip += d.length; - g_emulated.fetch_add(1, std::memory_order_relaxed); - return true; -} - -namespace { - -LONG CALLBACK illegal_instruction(EXCEPTION_POINTERS* info) { - if (!info || !info->ExceptionRecord || !info->ContextRecord || - info->ExceptionRecord->ExceptionCode != EXCEPTION_ILLEGAL_INSTRUCTION) - return EXCEPTION_CONTINUE_SEARCH; - const uintptr_t rip = static_cast(info->ContextRecord->Rip); - uint64_t base = 0; - if (!rt::shims::mapped_image_base(rip, base)) return EXCEPTION_CONTINUE_SEARCH; // only the title's code - MEMORY_BASIC_INFORMATION mbi{}; - if (!VirtualQuery(reinterpret_cast(rip), &mbi, sizeof(mbi)) || mbi.State != MEM_COMMIT || - (mbi.Protect & (PAGE_GUARD | PAGE_NOACCESS))) - return EXCEPTION_CONTINUE_SEARCH; - const uintptr_t region_end = reinterpret_cast(mbi.BaseAddress) + mbi.RegionSize; - const size_t readable = region_end - rip < 16 ? region_end - rip : 16; - return emulate(info->ContextRecord, reinterpret_cast(rip), readable) ? EXCEPTION_CONTINUE_EXECUTION - : EXCEPTION_CONTINUE_SEARCH; -} - -} // namespace - -void install() { - static const bool installed = AddVectoredExceptionHandler(1, &illegal_instruction) != nullptr; - (void)installed; -} - -#else - -void install() {} - -#endif - -} // namespace rt::console_insn diff --git a/runtime/src/console_insn.h b/runtime/src/console_insn.h deleted file mode 100644 index f6916b48c..000000000 --- a/runtime/src/console_insn.h +++ /dev/null @@ -1,73 +0,0 @@ -// Instructions the console's CPU (Zen 2) has and a PC's CPU may lack. A title compiled for the console runs them as -// they are; on an Intel CPU (CLZERO, RDPRU, MONITORX/MWAITX and SSE4a's EXTRQ/INSERTQ are AMD's, CLWB and RDPID are -// missing before Ice Lake / Alder Lake) each raises STATUS_ILLEGAL_INSTRUCTION, and the retail title zeroes memory -// with a CLZERO loop from its first frames. The vectored handler in console_insn.cpp decodes the faulting -// instruction here, emulates it and steps over it. -// -// Which instructions to emulate and how is VIctory's (victory-loader src/console_insn.rs, GPL-3.0-or-later), -// measured on the same title: CLWB is a no-op (a PC's memory is coherent) and is patched to NOPs, MONITORX/MWAITX -// are a skipped wait, RDPRU reads a counter, RDPID the processor number, a whole `clzero; add rax,40h; cmp rax,reg; -// jb` loop is done at once, and the high quadword of an EXTRQ/INSERTQ destination is zeroed (as a Zen 5 does; AMD -// leaves it undefined). This decoder is written from the encodings in AMD's Architecture Programmer's Manual -// (volume 3 for CLZERO, RDPRU, MONITORX, MWAITX, CLWB, RDPID; volume 4 for EXTRQ and INSERTQ), not translated from -// VIctory's, whose decoder is XCL's (GPL-2.0-only); the prefix rules VIctory measured on a Zen 5 (the last of F2/F3 -// decides, 66 only without either, a REX counts only right before the opcode) are followed as facts. -// -// Portable: no Win32 here. The handler and its memory checks are the Win32 boundary. -#pragma once - -#include -#include - -#if defined(_WIN32) -struct _CONTEXT; // 's CONTEXT -#endif - -namespace rt::console_insn { - -enum class Kind : uint8_t { - None, // not one of ours: the exception goes on to the title's handlers and the crash report - Ud2, // the title's own trap, never emulated - Clwb, // 66 0F AE /6 (memory operand): write back a cache line - Clzero, // 0F 01 FC: zero the 64-byte line at rAX (EAX with a 67 prefix) - ClzeroLoop, // clzero; add rax,40h; cmp rax,; jb back to the clzero: zero [rax, reg) - Rdpru, // 0F 01 FD: ECX 0 MPERF, 1 APERF into EDX:EAX - Monitorx, // 0F 01 FA - Mwaitx, // 0F 01 FB - Rdpid, // F3 0F C7 /7 (register operand): TSC_AUX, the processor number - Extrq, // 66 0F 78 /0 ib ib, or 66 0F 79 /r - Insertq, // F2 0F 78 /r ib ib, or F2 0F 79 /r -}; - -struct Decoded { - Kind kind = Kind::None; - uint8_t length = 0; // bytes to step over (for ClzeroLoop the whole loop) - uint8_t reg = 0; // Rdpid's destination, ClzeroLoop's end register (CONTEXT order: rax, rcx, rdx, rbx, rsp, - // rbp, rsi, rdi, r8-r15); Extrq/Insertq's destination XMM register - uint8_t src = 0; // Extrq (register form) / Insertq: the source XMM register - bool from_register = false; // Extrq/Insertq: length and index come from the source register, not immediates - uint8_t field_length = 0; // immediate forms: the field's length (0 means 64) and index, low 6 bits each - uint8_t field_index = 0; - bool address32 = false; // Clzero: a 67 prefix, the line is at EAX -}; - -// The console-only instruction at the start of `code` (up to `size` readable bytes), or Kind::None. -Decoded decode(const uint8_t* code, size_t size); - -// SSE4a on a low quadword. A field length of 0 is 64; a field past bit 63 gives what the shifts give. -uint64_t extrq(uint64_t value, unsigned field_length, unsigned field_index); -uint64_t insertq(uint64_t dst, uint64_t src, unsigned field_length, unsigned field_index); - -// Installs the vectored handler (Windows; a no-op elsewhere). Emulates only in images the loader mapped. Once. -void install(); - -// How many instructions the handler has emulated, for the log and tests. -uint64_t emulated_count(); - -#if defined(_WIN32) -// The handler's work on a faulting thread's context, with `size` readable code bytes at its RIP (`code`): true when -// the instruction was emulated (RIP is past it, or at it again for a CLZERO loop stopped by memory it cannot write). -bool emulate(::_CONTEXT* ctx, const uint8_t* code, size_t size); -#endif - -} // namespace rt::console_insn diff --git a/runtime/src/debug_magenta_spv.h b/runtime/src/debug_magenta_spv.h deleted file mode 100644 index 826f82e2c..000000000 --- a/runtime/src/debug_magenta_spv.h +++ /dev/null @@ -1,71 +0,0 @@ -#pragma once - -// A pixel shader that writes solid magenta to colour outputs 0-3: LEONIDA_DEBUG_SOLID_PS=1 swaps it in for every -// translated pixel shader, to tell a geometry or target problem (still black) from a shader-input one (magenta). -// Built from this GLSL with glslangValidator -V --vn kMagentaFragment: -// #version 450 -// layout(location = 0..3) out vec4 c0..c3; -// void main() { c0 = vec4(1.0, 0.0, 1.0, 1.0); c1 = c0; c2 = c0; c3 = c0; } -#include - -namespace leonida { - -inline constexpr std::uint32_t kMagentaFragment[] = { - 0x07230203,0x00010000,0x0008000b,0x00000013,0x00000000,0x00020011,0x00000001,0x0006000b, - 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001, - 0x0009000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x00000009,0x0000000d,0x0000000f, - 0x00000011,0x00030010,0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005, - 0x00000004,0x6e69616d,0x00000000,0x00030005,0x00000009,0x00003063,0x00030005,0x0000000d, - 0x00003163,0x00030005,0x0000000f,0x00003263,0x00030005,0x00000011,0x00003363,0x00040047, - 0x00000009,0x0000001e,0x00000000,0x00040047,0x0000000d,0x0000001e,0x00000001,0x00040047, - 0x0000000f,0x0000001e,0x00000002,0x00040047,0x00000011,0x0000001e,0x00000003,0x00020013, - 0x00000002,0x00030021,0x00000003,0x00000002,0x00030016,0x00000006,0x00000020,0x00040017, - 0x00000007,0x00000006,0x00000004,0x00040020,0x00000008,0x00000003,0x00000007,0x0004003b, - 0x00000008,0x00000009,0x00000003,0x0004002b,0x00000006,0x0000000a,0x3f800000,0x0004002b, - 0x00000006,0x0000000b,0x00000000,0x0007002c,0x00000007,0x0000000c,0x0000000a,0x0000000b, - 0x0000000a,0x0000000a,0x0004003b,0x00000008,0x0000000d,0x00000003,0x0004003b,0x00000008, - 0x0000000f,0x00000003,0x0004003b,0x00000008,0x00000011,0x00000003,0x00050036,0x00000002, - 0x00000004,0x00000000,0x00000003,0x000200f8,0x00000005,0x0003003e,0x00000009,0x0000000c, - 0x0004003d,0x00000007,0x0000000e,0x00000009,0x0003003e,0x0000000d,0x0000000e,0x0004003d, - 0x00000007,0x00000010,0x00000009,0x0003003e,0x0000000f,0x00000010,0x0004003d,0x00000007, - 0x00000012,0x00000009,0x0003003e,0x00000011,0x00000012,0x000100fd,0x00010038 -}; - -// LEONIDA_DEBUG_SOLID_VS=1: a vertex shader that draws one full-screen triangle from gl_VertexIndex (positions only). -inline constexpr std::uint32_t kFullscreenVertex[] = { - 0x07230203,0x00010000,0x0008000b,0x00000027,0x00000000,0x00020011,0x00000001,0x0006000b, - 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001, - 0x0007000f,0x00000000,0x00000004,0x6e69616d,0x00000000,0x0000000a,0x00000015,0x00030003, - 0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d,0x00000000,0x00030005,0x00000008, - 0x00000069,0x00060005,0x0000000a,0x565f6c67,0x65747265,0x646e4978,0x00007865,0x00060005, - 0x00000013,0x505f6c67,0x65567265,0x78657472,0x00000000,0x00060006,0x00000013,0x00000000, - 0x505f6c67,0x7469736f,0x006e6f69,0x00070006,0x00000013,0x00000001,0x505f6c67,0x746e696f, - 0x657a6953,0x00000000,0x00070006,0x00000013,0x00000002,0x435f6c67,0x4470696c,0x61747369, - 0x0065636e,0x00070006,0x00000013,0x00000003,0x435f6c67,0x446c6c75,0x61747369,0x0065636e, - 0x00030005,0x00000015,0x00000000,0x00040047,0x0000000a,0x0000000b,0x0000002a,0x00030047, - 0x00000013,0x00000002,0x00050048,0x00000013,0x00000000,0x0000000b,0x00000000,0x00050048, - 0x00000013,0x00000001,0x0000000b,0x00000001,0x00050048,0x00000013,0x00000002,0x0000000b, - 0x00000003,0x00050048,0x00000013,0x00000003,0x0000000b,0x00000004,0x00020013,0x00000002, - 0x00030021,0x00000003,0x00000002,0x00040015,0x00000006,0x00000020,0x00000001,0x00040020, - 0x00000007,0x00000007,0x00000006,0x00040020,0x00000009,0x00000001,0x00000006,0x0004003b, - 0x00000009,0x0000000a,0x00000001,0x0004002b,0x00000006,0x0000000c,0x00000003,0x00030016, - 0x0000000e,0x00000020,0x00040017,0x0000000f,0x0000000e,0x00000004,0x00040015,0x00000010, - 0x00000020,0x00000000,0x0004002b,0x00000010,0x00000011,0x00000001,0x0004001c,0x00000012, - 0x0000000e,0x00000011,0x0006001e,0x00000013,0x0000000f,0x0000000e,0x00000012,0x00000012, - 0x00040020,0x00000014,0x00000003,0x00000013,0x0004003b,0x00000014,0x00000015,0x00000003, - 0x0004002b,0x00000006,0x00000016,0x00000000,0x0004002b,0x00000006,0x00000018,0x00000001, - 0x00020014,0x00000019,0x0004002b,0x0000000e,0x0000001b,0x40400000,0x0004002b,0x0000000e, - 0x0000001c,0xbf800000,0x0004002b,0x00000006,0x0000001f,0x00000002,0x0004002b,0x0000000e, - 0x00000022,0x3f000000,0x0004002b,0x0000000e,0x00000023,0x3f800000,0x00040020,0x00000025, - 0x00000003,0x0000000f,0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8, - 0x00000005,0x0004003b,0x00000007,0x00000008,0x00000007,0x0004003d,0x00000006,0x0000000b, - 0x0000000a,0x0005008b,0x00000006,0x0000000d,0x0000000b,0x0000000c,0x0003003e,0x00000008, - 0x0000000d,0x0004003d,0x00000006,0x00000017,0x00000008,0x000500aa,0x00000019,0x0000001a, - 0x00000017,0x00000018,0x000600a9,0x0000000e,0x0000001d,0x0000001a,0x0000001b,0x0000001c, - 0x0004003d,0x00000006,0x0000001e,0x00000008,0x000500aa,0x00000019,0x00000020,0x0000001e, - 0x0000001f,0x000600a9,0x0000000e,0x00000021,0x00000020,0x0000001b,0x0000001c,0x00070050, - 0x0000000f,0x00000024,0x0000001d,0x00000021,0x00000022,0x00000023,0x00050041,0x00000025, - 0x00000026,0x00000015,0x00000016,0x0003003e,0x00000026,0x00000024,0x000100fd,0x00010038 -}; - -} // namespace leonida diff --git a/runtime/src/display_mode.h b/runtime/src/display_mode.h deleted file mode 100644 index 7d622cbc4..000000000 --- a/runtime/src/display_mode.h +++ /dev/null @@ -1,55 +0,0 @@ -#pragma once - -// The display mode the console reports to the title: LEONIDA_DISPLAY_MODE=WxH, default 3840x2160. -// -// Ported from VIctory (GPL-3.0-or-later, Marvisak and contributors, DexNom fork; -// victory/crates/victory-gpu/src/dxgi.rs:222-240 `display_size`, VICTORY_DISPLAY_MODE): a console reports the -// television it is plugged into (a Series X on a 1080p set lists a 1080p mode). VIctory accepts W in 640..7680 and H in -// 360..4320 and otherwise reports 3840x2160; so does this. It does not follow the host monitor either (V: "not yet the -// host display's own size by default"). The title reads the mode but does not size its frames by it: what does is -// display_profile.h. No Windows headers; present_window_parts_test checks the parser. - -#include -#include - -namespace leonida { - -struct DisplayMode { - std::uint32_t width = 3840; - std::uint32_t height = 2160; - std::uint32_t refresh_hz = 60; // V dxgi.rs `modes`: one mode at 60 Hz -}; - -// "WxH" (an `x` or `X` between, spaces around the numbers allowed), W in 640..7680 and H in 360..4320. False, with -// `*out` untouched, for anything else. -inline bool parse_display_mode(std::string_view text, DisplayMode* out) { - const auto trim = [](std::string_view s) { - while (!s.empty() && (s.front() == ' ' || s.front() == '\t')) s.remove_prefix(1); - while (!s.empty() && (s.back() == ' ' || s.back() == '\t' || s.back() == '\r' || s.back() == '\n')) - s.remove_suffix(1); - return s; - }; - const auto number = [](std::string_view s, std::uint32_t* value) { - if (s.empty() || s.size() > 5) return false; - std::uint32_t v = 0; - for (const char c : s) { - if (c < '0' || c > '9') return false; - v = v * 10 + std::uint32_t(c - '0'); - } - *value = v; - return true; - }; - text = trim(text); - const std::size_t x = text.find_first_of("xX"); - if (x == std::string_view::npos) return false; - std::uint32_t width = 0, height = 0; - if (!number(trim(text.substr(0, x)), &width) || !number(trim(text.substr(x + 1)), &height)) return false; - if (width < 640 || width > 7680 || height < 360 || height > 4320) return false; - if (out) { - out->width = width; - out->height = height; - } - return true; -} - -} // namespace leonida diff --git a/runtime/src/display_profile.h b/runtime/src/display_profile.h deleted file mode 100644 index b8d9abf47..000000000 --- a/runtime/src/display_profile.h +++ /dev/null @@ -1,170 +0,0 @@ -#pragma once - -// The size the title outputs and renders at: LEONIDA_DISPLAY_MODE=WxH (and LEONIDA_RENDER_SCALE), applied to the mapped -// executable before any of its code runs. -// -// Ported from VIctory (GPL-3.0-or-later, Marvisak and contributors, DexNom fork; upstream commit ab34a8b21, -// apps/victory/src/native_1440p.rs `prepare`). The title does not size its frames by the display mode DXGI reports -// (shims/xbox_display.h answers that too): the Series X SDR mode is a constant in the executable, 3840x2160 at 60 Hz, -// and the title builds its window, its two scanout buffers and its frontend from it. Its scene is rendered at 2/3 of -// that and scaled up temporally (2560x1440 into 3840x2160). VIctory's native 1440p profile changes four places of the -// retail executable, each checked against its stock bytes first: -// - the SDR mode (W, H, 60, 1); -// - the size reserved for the two scanout buffers (`mov ecx, imm32`): two 64 KiB-aligned RGBA8 surfaces in the -// 64 KiB D_X swizzle, rounded up to 2 MiB, "matching the title's allocation check" (V). The stock value, -// 0x04000000, is what this gives for 3840x2160, which scanout_pool_bytes checks; -// - the temporal scene scale (a float, stock 2/3): the render size over the output size; -// - the Settings screen's viewport load, which reads a separate 3840x2160 pair: pointed at the SDR mode instead. -// VIctory checks the build by the BLAKE3 hash of the file as well; here every patch is checked against the bytes it -// replaces, all before any is written, so another build is left alone (and says so). -// -// VIctory applies it for 2560x1440 output, rendered at 2560x1440 (scale 1) or 1920x1080 (VICTORY_RENDER_1080P, scale -// 0.75); so does this, with LEONIDA_RENDER_SCALE (0.25..1, default 1) for the scale. Other outputs are refused: with -// the SDR mode set to 1920x1080 the 1.0.2.1 title still makes a 2560x1440 window and 2560x1440 scanout buffers -// (measured under gta6rt --run), which a reservation sized for 1920x1080 would not hold. 3840x2160 (the default) -// changes nothing. - -#include "display_mode.h" - -#include -#include -#include -#include -#include -#include - -#ifdef _WIN32 -#ifndef NOMINMAX -#define NOMINMAX // std::min and std::max, not the macros -#endif -#include -#endif - -namespace leonida::display_profile { - -// RVAs in the 1.0.2.1 retail executable (V native_1440p.rs). -inline constexpr std::uint32_t kSdrModeRva = 0x0615c100; -inline constexpr std::uint32_t kScanoutReservationRva = 0x0247ad4a; -inline constexpr std::uint32_t kSceneScaleRva = 0x028f1e7e; -inline constexpr std::uint32_t kSettingsViewportLoadRva = 0x058048d4; - -// Two scanout surfaces of `width` x `height` RGBA8 in the 64 KiB D_X swizzle (128x128 texels a 64 KiB block), each -// 64 KiB aligned, together rounded up to 2 MiB. -inline std::uint32_t scanout_pool_bytes(std::uint32_t width, std::uint32_t height) { - const std::uint64_t blocks = std::uint64_t((width + 127) / 128) * ((height + 127) / 128); - const std::uint64_t surface = blocks * 65536; // already a multiple of 64 KiB - const std::uint64_t two_mib = std::uint64_t(2) << 20; - return std::uint32_t((surface * 2 + two_mib - 1) / two_mib * two_mib); -} - -struct Patch { - std::uint32_t rva = 0; - std::vector stock; // what must be there - std::vector bytes; // what goes there - const char* what = ""; -}; - -struct Plan { - DisplayMode output; - std::uint32_t render_width = 0, render_height = 0; - float scale = 2.0f / 3.0f; - std::uint32_t pool = 0; - std::vector patches; // empty: the stock 3840x2160 profile, or a refused one (`refused` says why) - const char* refused = nullptr; -}; - -namespace detail { -inline void put32(std::vector& out, std::uint32_t v) { - for (int i = 0; i < 4; ++i) out.push_back(std::uint8_t(v >> (8 * i))); -} -inline void put_float(std::vector& out, float f) { - std::uint32_t v = 0; - std::memcpy(&v, &f, sizeof v); - put32(out, v); -} -} // namespace detail - -// The patches for an output of `mode` rendered at `render_scale` of it (0: 1). -inline Plan plan(const DisplayMode& mode, float render_scale = 0.0f) { - Plan p; - p.output = mode; - const DisplayMode stock; - if (mode.width == stock.width && mode.height == stock.height) { - p.render_width = 2560; - p.render_height = 1440; - p.pool = scanout_pool_bytes(stock.width, stock.height); - if (render_scale > 0.0f) p.refused = "a render scale is only applied with a 2560x1440 output"; - return p; - } - if (mode.width != 2560 || mode.height != 1440) { - p.refused = "only 2560x1440 is an output the title takes (VIctory's profile)"; - return p; - } - p.scale = render_scale > 0.0f ? render_scale : 1.0f; - p.render_width = std::uint32_t(float(mode.width) * p.scale); - p.render_height = std::uint32_t(float(mode.height) * p.scale); - p.pool = scanout_pool_bytes(mode.width, mode.height); - - Patch sdr{kSdrModeRva, {}, {}, "SDR mode"}; - for (const std::uint32_t v : {stock.width, stock.height, 60u, 1u}) detail::put32(sdr.stock, v); - for (const std::uint32_t v : {mode.width, mode.height, 60u, 1u}) detail::put32(sdr.bytes, v); - Patch pool{kScanoutReservationRva, {0xb9}, {0xb9}, "scanout reservation"}; - detail::put32(pool.stock, scanout_pool_bytes(stock.width, stock.height)); - detail::put32(pool.bytes, p.pool); - Patch scale{kSceneScaleRva, {}, {}, "temporal scene scale"}; - detail::put_float(scale.stock, 2.0f / 3.0f); - detail::put_float(scale.bytes, p.scale); - // vmovsd xmm1, qword [rip + disp32]: the Settings viewport's 3840x2160 pair, then the SDR mode's. - Patch viewport{kSettingsViewportLoadRva, {0xc5, 0xfb, 0x10, 0x0d, 0x10, 0xf0, 0x13, 0x05}, {0xc5, 0xfb, 0x10, 0x0d}, - "Settings viewport load"}; - detail::put32(viewport.bytes, std::uint32_t(std::int32_t(kSdrModeRva) - std::int32_t(kSettingsViewportLoadRva + 8))); - p.patches = {sdr, pool, scale, viewport}; - return p; -} - -// True when every patch's stock bytes are in the image, read through `at(rva, length)` (a pointer to that many bytes -// of the image, or null past it); else false with `*error` set. -template -bool check(Access&& at, const Plan& p, std::string* error) { - for (const Patch& patch : p.patches) { - const std::uint8_t* there = at(patch.rva, patch.stock.size()); - if (!there || std::memcmp(there, patch.stock.data(), patch.stock.size()) != 0) { - if (error) *error = std::string("the ") + patch.what + " is not the 1.0.2.1 executable's"; - return false; - } - } - return true; -} - -// check(), then every patch written through `at`. Nothing is written when the check fails. -template -bool apply(Access&& at, const Plan& p, std::string* error) { - if (!check(at, p, error)) return false; - for (const Patch& patch : p.patches) std::memcpy(at(patch.rva, patch.bytes.size()), patch.bytes.data(), patch.bytes.size()); - return true; -} - -#ifdef _WIN32 -// apply() on a mapped image of `size` bytes at `base`, each write made writable for its length and its protection put -// back after. -inline bool apply_to_image(std::uint8_t* base, std::uint32_t size, const Plan& p, std::string* error) { - const auto at = [&](std::uint32_t rva, std::size_t length) -> std::uint8_t* { - return std::uint64_t(rva) + length <= size ? base + rva : nullptr; - }; - if (!check(at, p, error)) return false; - for (const Patch& patch : p.patches) { - std::uint8_t* where = at(patch.rva, patch.bytes.size()); - DWORD old = 0; - if (!VirtualProtect(where, patch.bytes.size(), PAGE_EXECUTE_READWRITE, &old)) { - if (error) *error = std::string("the ") + patch.what + " could not be made writable"; - return false; - } - std::memcpy(where, patch.bytes.data(), patch.bytes.size()); - VirtualProtect(where, patch.bytes.size(), old, &old); - FlushInstructionCache(GetCurrentProcess(), where, patch.bytes.size()); - } - return true; -} -#endif - -} // namespace leonida::display_profile diff --git a/runtime/src/frame_meter.h b/runtime/src/frame_meter.h deleted file mode 100644 index cc6620b34..000000000 --- a/runtime/src/frame_meter.h +++ /dev/null @@ -1,97 +0,0 @@ -#pragma once - -// The frame rate in the title's window caption: "Leonida | fps ms/frame", refreshed once a second. -// -// Ported from VIctory (GPL-3.0-or-later, Marvisak and contributors, DexNom fork; -// victory/crates/victory-gpu/src/host.rs `Meter::frame` and the "victory-caption" thread): the present path only -// counts the frame, and a thread of the runtime's own sets the caption, so presenting never waits for the window's -// thread. VIctory computes its figures at the first present a second after the last report; here the caption thread -// samples once a second and measures the frames between the newest present before its previous sample and the newest -// present now, so a figure always spans whole frames. A second without a frame keeps the previous figures until the -// frame being waited for has taken longer than they say, and then shows that wait ("0 fps 2400.0 ms/frame"), where -// VIctory's caption would stand still. No Windows headers: frame_meter_test drives it with made-up times. - -#include -#include -#include -#include - -namespace leonida { - -class FrameMeter { -public: - // A frame was presented at `now_ns` (one monotonic clock, nanoseconds). Any thread; lock-free. - void presented(std::uint64_t now_ns) { - std::uint64_t none = 0; - first_ns_.compare_exchange_strong(none, now_ns, std::memory_order_relaxed); - last_ns_.store(now_ns, std::memory_order_relaxed); - count_.fetch_add(1, std::memory_order_release); - } - struct Reading { - std::uint64_t count = 0; // frames presented so far - std::uint64_t first_ns = 0; // when the first was - std::uint64_t last_ns = 0; // when the newest was - }; - Reading read() const { - Reading r; - r.count = count_.load(std::memory_order_acquire); - r.first_ns = first_ns_.load(std::memory_order_relaxed); - r.last_ns = last_ns_.load(std::memory_order_relaxed); - return r; - } - -private: - std::atomic count_{0}; - std::atomic first_ns_{0}; - std::atomic last_ns_{0}; -}; - -struct FrameFigures { - double fps = 0.0; - double ms = 0.0; // per frame -}; - -// One sampling thread's view of a FrameMeter (see the top comment). -class FrameRateSampler { -public: - // False while there is no figure yet: no frame, or one frame that has not been waited on for a second. - bool sample(const FrameMeter::Reading& r, std::uint64_t now_ns, FrameFigures* out) { - if (r.count == 0) return false; - if (count_ == 0) { // the first sample that sees a frame: measure from the first one - count_ = 1; - last_ns_ = r.first_ns; - } - if (r.count > count_ && r.last_ns > last_ns_) { - const double frames = double(r.count - count_); - const double span_ns = double(r.last_ns - last_ns_); - figures_ = {frames * 1e9 / span_ns, span_ns / 1e6 / frames}; - have_ = true; - count_ = r.count; - last_ns_ = r.last_ns; - } else if (now_ns > r.last_ns) { - // No new frame: the one being waited for, once it has taken longer than the last figures say. - const double waited_ms = double(now_ns - r.last_ns) / 1e6; - if ((have_ && waited_ms > figures_.ms) || (!have_ && waited_ms >= 1000.0)) { - figures_ = {1000.0 / waited_ms, waited_ms}; - have_ = true; - } - } - if (have_ && out) *out = figures_; - return have_; - } - -private: - std::uint64_t count_ = 0; - std::uint64_t last_ns_ = 0; - FrameFigures figures_{}; - bool have_ = false; -}; - -// "Leonida | 60 fps 16.7 ms/frame" (V host.rs: `{fps:.0} fps {ms:.1} ms/frame`). -inline std::string caption_text(const FrameFigures& f) { - char text[96]; - std::snprintf(text, sizeof text, "Leonida | %.0f fps %.1f ms/frame", f.fps, f.ms); - return text; -} - -} // namespace leonida diff --git a/runtime/src/frame_step.h b/runtime/src/frame_step.h deleted file mode 100644 index 690eee018..000000000 --- a/runtime/src/frame_step.h +++ /dev/null @@ -1,184 +0,0 @@ -#pragma once - -// The title's time step from the measured frame time at any frame rate: LEONIDA_TIME_STEP (default `measured`; -// `stock` keeps the title's own step), applied to the mapped executable before any of its code runs. -// -// How the 1.0.2.1 title makes its step (measured by static analysis and under VIctory; RVAs below, in the style of -// display_profile.h): once a frame its timer takes the frame's real time from QueryPerformanceCounter (the previous -// count's difference times 1 / QueryPerformanceFrequency) and gives every one of its time sets (game time, game time -// not paused, camera, ...: a millisecond count, a frame count and the step in seconds) a step made from it: -// -// step = max(nominal, min(1/15 s, measured)) * time scale (re-clamped to [min step, 1/15 s] when scaled) -// -// `nominal` is one frame at the frame rate the title aims for (its settings' frame-rate cap, else the display's refresh -// over the vsync interval, else 30): 1/30 s. The cap is a 1/15 s constant. So the step is real only between 15 and 30 frames a second: above -// 30 every frame still steps 1/30 s and the world runs fps/30 times too fast (the doubled speed seen on the console when -// a glitch doubles the frame rate), below 15 every frame steps 1/15 s and the world runs at fps/15 of real time -// (0.13 at VIctory's 2 fps). The nominal floor is taken while a switch of the timer is set, which the retail build's -// init sets (the same switch picks where in the frame the timer runs); without it the floor is the timer's own minimum -// step, 1/3000 s, which its init writes. -// -// The patch moves two loads in each of the timer's two step computations (the time sets' and the camera's), keeping -// the code: the floor reads the timer's minimum step instead of the nominal frame time, and the cap reads the timer's -// own 1.0 constant instead of 1/15 s. The step is then the measured frame time between 1/3000 s and 1 s: real time -// from 1 to 3000 frames a second. Each load is checked against its stock bytes, and the two targets against theirs, -// before anything is written; another build is left alone (and says so). Frames longer than 1 s (a loading hitch) -// still step 1 s. The approach is BlueShell's for the same class of bug (the measured frame time at the engine's step, -// its commit 1a429f6); the check-then-patch shape is display_profile.h's. -// -// Measured under VIctory, the same four loads written into the running title (game time against the title's own -// unclipped real-time set and the wall clock): stock, 30 fps menus 1.00, a 42 fps loading screen 1.54, the world at -// 1.5 fps 0.15; patched, 30 fps 1.00, 70 fps 1.00, the world at 1.6 fps 1.00 over every frame under 1 s. -// -// Not changed: what counts frames instead of reading the step. The game time's frame count (the u32 after its -// millisecond count) has about 690 readers, nearly all "once a frame" or "N frames since" bookkeeping; a few turn -// frames into time and stay frame-paced at any rate, e.g. a blend over 15 frames (+0x8eee32: frames since times the -// 1/15 constant, at most 1) and a check of frames since times the current step against 0.5 s (+0x244b584). - -#include -#include -#include -#include - -#ifdef _WIN32 -#ifndef NOMINMAX -#define NOMINMAX -#endif -#include -#endif - -namespace leonida::frame_step { - -// RVAs in the 1.0.2.1 retail executable. Each load is `vmovss xmmN, dword [rip + disp32]` (C5 FA 10 modrm disp32), -// 8 bytes long. -inline constexpr std::uint32_t kTimeSetCapLoadRva = 0x02226045; // xmm3 = 1/15 s -inline constexpr std::uint32_t kTimeSetFloorLoadRva = 0x0222605a; // xmm4 = nominal frame time -inline constexpr std::uint32_t kCameraCapLoadRva = 0x02226833; // xmm0 = 1/15 s -inline constexpr std::uint32_t kCameraFloorLoadRva = 0x02226854; // xmm1 = nominal frame time -// What they read: the 1/15 s constant (.rdata), the nominal frame time (.data, 1/30 until the settings set it). -inline constexpr std::uint32_t kStockCapRva = 0x06159ec0; -inline constexpr std::uint32_t kNominalRva = 0x06849844; -// What they read after the patch: the timer's 1.0 constant (.rdata) and its minimum step (.data: 1/30 in the file, -// 1/3000 s once the timer's init has run, before its first step). -inline constexpr std::uint32_t kOneRva = 0x05fc6ed8; -inline constexpr std::uint32_t kMinStepRva = 0x06847660; - -inline constexpr std::uint32_t kLoadLength = 8; - -struct Patch { - std::uint32_t rva = 0; - std::vector stock; // what must be there - std::vector bytes; // what goes there (empty: only checked) - const char* what = ""; -}; - -namespace detail { -inline void put32(std::vector& out, std::uint32_t v) { - for (int i = 0; i < 4; ++i) out.push_back(std::uint8_t(v >> (8 * i))); -} -inline std::vector float_bytes(float f) { - std::uint32_t v = 0; - std::memcpy(&v, &f, sizeof v); - std::vector out; - put32(out, v); - return out; -} -// `vmovss xmm, dword [rip + disp32]` at `at`, reading `target`. -inline std::vector load(std::uint32_t at, std::uint8_t reg, std::uint32_t target) { - std::vector out{0xc5, 0xfa, 0x10, std::uint8_t(0x05 | (reg << 3))}; - put32(out, std::uint32_t(std::int32_t(target) - std::int32_t(at + kLoadLength))); - return out; -} -} // namespace detail - -// The patches, in the order they are checked: the two targets' values (checked only), then the four loads. -inline std::vector plan() { - using detail::load; - std::vector p; - p.push_back({kOneRva, detail::float_bytes(1.0f), {}, "timer's 1.0 constant"}); - p.push_back({kMinStepRva, detail::float_bytes(1.0f / 30.0f), {}, "timer's minimum step"}); - p.push_back({kTimeSetCapLoadRva, load(kTimeSetCapLoadRva, 3, kStockCapRva), load(kTimeSetCapLoadRva, 3, kOneRva), - "time sets' step cap"}); - p.push_back({kTimeSetFloorLoadRva, load(kTimeSetFloorLoadRva, 4, kNominalRva), - load(kTimeSetFloorLoadRva, 4, kMinStepRva), "time sets' step floor"}); - p.push_back({kCameraCapLoadRva, load(kCameraCapLoadRva, 0, kStockCapRva), load(kCameraCapLoadRva, 0, kOneRva), - "camera step cap"}); - p.push_back({kCameraFloorLoadRva, load(kCameraFloorLoadRva, 1, kNominalRva), - load(kCameraFloorLoadRva, 1, kMinStepRva), "camera step floor"}); - return p; -} - -// LEONIDA_TIME_STEP: unset, empty or `measured` (any case): patch; `stock`, `0` or `off`: the title's own step. -// Anything else is refused (`*known` false) and patches as the default does. -inline bool wanted(const char* value, bool* known = nullptr) { - if (known) *known = true; - if (!value || !*value) return true; - std::string v(value); - for (char& c : v) c = char(c >= 'A' && c <= 'Z' ? c - 'A' + 'a' : c); - if (v == "measured" || v == "1" || v == "on") return true; - if (v == "stock" || v == "0" || v == "off") return false; - if (known) *known = false; - return true; -} - -// True when every patch's stock bytes are in the image, read through `at(rva, length)` (a pointer to that many bytes -// of the image, or null past it); else false with `*error` set. -template -bool check(Access&& at, const std::vector& patches, std::string* error) { - for (const Patch& patch : patches) { - const std::uint8_t* there = at(patch.rva, patch.stock.size()); - if (!there || std::memcmp(there, patch.stock.data(), patch.stock.size()) != 0) { - if (error) *error = std::string("the ") + patch.what + " is not the 1.0.2.1 executable's"; - return false; - } - } - return true; -} - -// check(), then every patch with bytes written through `at`. Nothing is written when the check fails. -template -bool apply(Access&& at, const std::vector& patches, std::string* error) { - if (!check(at, patches, error)) return false; - for (const Patch& patch : patches) - if (!patch.bytes.empty()) std::memcpy(at(patch.rva, patch.bytes.size()), patch.bytes.data(), patch.bytes.size()); - return true; -} - -#ifdef _WIN32 -// apply() on a mapped image of `size` bytes at `base`: every place is made writable first (or nothing is written), then -// all are written, then the protections are put back in reverse order (two loads share a page: the second -// VirtualProtect saw the first one's writable protection) and the instruction cache flushed. All the loads or none: a -// floor without the cap (or the other way round) would still not be real time. -inline bool apply_to_image(std::uint8_t* base, std::uint32_t size, const std::vector& patches, - std::string* error) { - const auto at = [&](std::uint32_t rva, std::size_t length) -> std::uint8_t* { - return std::uint64_t(rva) + length <= size ? base + rva : nullptr; - }; - if (!check(at, patches, error)) return false; - std::vector old(patches.size(), 0); - for (std::size_t i = 0; i < patches.size(); ++i) { - const Patch& patch = patches[i]; - if (patch.bytes.empty()) continue; - if (!VirtualProtect(at(patch.rva, patch.bytes.size()), patch.bytes.size(), PAGE_EXECUTE_READWRITE, &old[i])) { - for (std::size_t j = i; j-- > 0;) - if (!patches[j].bytes.empty()) - VirtualProtect(at(patches[j].rva, patches[j].bytes.size()), patches[j].bytes.size(), old[j], &old[j]); - if (error) *error = std::string("the ") + patch.what + " could not be made writable"; - return false; - } - } - for (const Patch& patch : patches) - if (!patch.bytes.empty()) std::memcpy(at(patch.rva, patch.bytes.size()), patch.bytes.data(), patch.bytes.size()); - for (std::size_t i = patches.size(); i-- > 0;) { - const Patch& patch = patches[i]; - if (patch.bytes.empty()) continue; - std::uint8_t* where = at(patch.rva, patch.bytes.size()); - DWORD ignored = 0; - VirtualProtect(where, patch.bytes.size(), old[i], &ignored); - FlushInstructionCache(GetCurrentProcess(), where, patch.bytes.size()); - } - return true; -} -#endif - -} // namespace leonida::frame_step diff --git a/runtime/src/gfx10_descriptors.h b/runtime/src/gfx10_descriptors.h index b35ffc934..acfa590f8 100644 --- a/runtime/src/gfx10_descriptors.h +++ b/runtime/src/gfx10_descriptors.h @@ -762,21 +762,4 @@ inline bool decode(const BufferWords& words, Buffer& out) { return true; } -// The V# of a constant-buffer view: `size` bytes at `address` as records of one float4 (16 bytes), checked by index. -// The title's console-compiled shaders index a constant buffer's float4 rows with `buffer_load_dwordx4 ... idxen` -// and the row number as the index (a Scaleform batch vertex shader reads row 4 * batch + k of its constant buffer -// that way), which only reaches row k with a 16-byte stride: a raw view (stride 0) gives every row the first one. -// Scalar loads still see `size` bytes (s_buffer_load is bounded at NUM_RECORDS * STRIDE), offset loads (offen, -// index 0) reach the whole buffer, and index loads stop at the last row (OOB_SELECT structured, index only). D3D12 -// sizes constant buffers in 256-byte units; a size that is not a multiple of 16 keeps its last partial row. -inline Buffer constant_buffer_descriptor(std::uint64_t address, std::uint32_t size) { - Buffer buffer{}; - buffer.address = address; - buffer.stride = 16; - buffer.num_records = size / 16 + (size % 16 ? 1 : 0); - buffer.format = 77; // GFX10_FORMAT_32_32_32_32_FLOAT - buffer.oob_select = OobSelect::structured; - return buffer; -} - } // namespace leonida::gfx10 diff --git a/runtime/src/gfx10_tiling.h b/runtime/src/gfx10_tiling.h index 71dcd4343..d869d1102 100644 --- a/runtime/src/gfx10_tiling.h +++ b/runtime/src/gfx10_tiling.h @@ -1,15 +1,11 @@ #pragma once -#include -#include #include #include #include #include #include #include -#include -#include namespace leonida::gfx10 { @@ -159,618 +155,4 @@ private: std::size_t tile_width_ = 0, tile_height_ = 0, tiles_x_ = 0, size_ = 0; }; -// ---- Whole textures: mips, mip tails, array slices, 3D, depth/stencil planes ---------------------------------------- -// -// Ported from VIctory (GPL-3.0-or-later, Marvisak and contributors, DexNom fork), victory-formats texture.rs, which -// follows AMD's address library (addrlib, as shipped in Mesa under src/amd/addrlib: block dimensions, mip placement -// and mip tails from gfx10addrlib.cpp and addrlib2.cpp, the 256-byte micro tile patterns from gfx10SwizzlePattern.h, -// the RB+ tables as on RDNA2). addrlib carries this notice: -// -// Copyright (C) 2007-2026 Advanced Micro Devices, Inc. All rights reserved. -// SPDX-License-Identifier: MIT -// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated -// documentation files (the "Software"), to deal in the Software without restriction, including without limitation -// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and -// to permit persons to whom the Software is furnished to do so, subject to the following conditions: the above -// copyright notice and this permission notice shall be included in all copies or substantial portions of the -// Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. -// -// Units: an element is a texel, or a 4x4 block of a block-compressed format. Mips of one array slice (or one depth slab -// of a thick 3D texture) are stored together, smallest first: the mip tail (the small mips sharing one block) at -// offset 0, mip 0 last. Addressable: linear, and the S and D modes without pipe/bank XOR (256 B, 4 KiB, 64 KiB, thin -// and thick); SW_64KB_R_X for one-mip, one-slice, one-sample 2D textures of 2-, 4- or 8-byte elements (Series X or S -// pipe tables). Other XOR modes and MSAA layouts are sized but have no address equation (addressable() is false). - -// A swizzle mode by its hardware number (addrlib's ADDR_SW_* order). -namespace swizzle { -inline constexpr std::uint32_t linear = 0, sw_256b_s = 1, sw_256b_d = 2, sw_4kb_s = 5, sw_4kb_d = 6, sw_64kb_s = 9, - sw_64kb_d = 10, sw_64kb_s_t = 17, sw_64kb_d_t = 18, sw_4kb_s_x = 21, sw_4kb_d_x = 22, - sw_4kb_r_x = 23, sw_64kb_z_x = 24, sw_64kb_s_x = 25, sw_64kb_d_x = 26, - sw_64kb_r_x = 27; -// log2 of the block size in bytes (0 for linear), or -1 for a mode GFX10 does not have. -constexpr int block_log2(std::uint32_t mode) { - switch (mode) { - case 0: return 0; - case 1: case 2: return 8; - case 5: case 6: case 21: case 22: case 23: return 12; - case 9: case 10: case 17: case 18: case 24: case 25: case 26: case 27: return 16; - default: return -1; - } -} -constexpr bool standard(std::uint32_t mode) { return mode == 1 || mode == 5 || mode == 9 || mode == 17 || mode == 21 || mode == 25; } -constexpr bool display(std::uint32_t mode) { return mode == 2 || mode == 6 || mode == 10 || mode == 18 || mode == 22 || mode == 26; } -constexpr bool z_order(std::uint32_t mode) { return mode == 24; } -// Pipe and bank XOR modes (_T, _X): their addresses depend on the GPU's pipe configuration. -constexpr bool xor_mode(std::uint32_t mode) { return mode >= 16; } -} // namespace swizzle - -enum class Dimension : std::uint8_t { tex1d, tex2d, tex3d }; - -// One plane of a texture. -struct LayoutDesc { - Dimension dimension = Dimension::tex2d; - std::uint32_t width = 1, height = 1; // texels - std::uint32_t depth = 1; // depth of a 3D texture, else the array size - std::uint32_t mips = 1; - std::uint32_t element_bytes = 4; // 1, 2, 4, 8 or 16 - std::uint32_t block = 1; // texels per element side: 1, or 4 for block compression - std::uint32_t samples = 1; - std::uint32_t swizzle = swizzle::linear; -}; - -// Where one mip lives inside a slice. -struct MipLayout { - std::uint32_t width = 0, height = 0, depth = 0; // elements (depth 1 unless the texture is 3D) - // Padded size in elements: whole blocks, or the tail's share of one. - std::uint32_t pitch = 0, rows = 0, depth_pitch = 0; - std::uint64_t offset = 0; // byte offset of its first block in the slice (0 in the tail) - // In the mip tail: byte offset inside the tail block and the element position the mip starts at. - bool in_tail = false; - std::uint32_t tail_offset = 0, tail_x = 0, tail_y = 0; -}; - -class TextureLayout { -public: - // False for a description that makes no texture (zero or oversized extent, a bad element size, a mode this - // dimension cannot use, too many mips). `series_s` picks the Series S pipe tables of SW_64KB_R_X. - static bool make(const LayoutDesc& d, bool series_s, TextureLayout& out) { - const int block_log2 = swizzle::block_log2(d.swizzle); - const auto in = [](std::uint32_t v) { return v >= 1 && v <= kMaxExtent; }; - const bool valid = - block_log2 >= 0 && in(d.width) && in(d.height) && in(d.depth) && d.mips >= 1 && d.mips <= kMaxMips && - std::has_single_bit(d.element_bytes) && d.element_bytes <= 16 && (d.block == 1 || d.block == 4) && - std::has_single_bit(d.samples) && d.samples <= 8 && - (d.samples == 1 || (d.dimension == Dimension::tex2d && d.mips == 1)) && - (d.dimension != Dimension::tex1d || d.height == 1) && - (d.dimension != Dimension::tex3d || d.swizzle == 0 || d.swizzle == 5 || d.swizzle == 9 || d.swizzle == 17 || - d.swizzle == 21 || (d.swizzle >= 24 && d.swizzle <= 27)); - if (!valid) return false; - TextureLayout layout; - if (block_log2 == 0) layout.linear(d); - else layout.tiled(d, std::uint32_t(block_log2), series_s); - out = std::move(layout); - return true; - } - - const LayoutDesc& desc() const { return desc_; } - // Block dimensions in elements (linear: the pitch alignment, 1, 1). - const std::array& block() const { return block_; } - bool thick() const { return thick_; } // 3D blocks span block()[2] depth slices (GFX10 3D S and D modes) - // Array slices, depth slabs of block()[2] slices (thick), or depth slices (thin and linear 3D). - std::uint32_t slices() const { return slices_; } - std::uint64_t slice_size() const { return slice_size_; } // bytes of one slice: its whole mip chain - std::uint64_t size() const { return size_; } - std::uint64_t alignment() const { return alignment_; } - std::uint32_t first_tail_mip() const { return first_tail_mip_; } // mips().size() without a tail - const std::vector& mips() const { return mips_; } - - // Whether offsets and copies have a known address equation. - bool addressable() const { return desc_.swizzle == swizzle::linear || !pattern_[0].empty(); } - - // Byte offset of element (x, y) of mip `mip` in array slice or depth slice `z`; false outside the mip or for a - // layout that is not addressable. - bool offset(std::uint32_t mip, std::uint32_t x, std::uint32_t y, std::uint32_t z, std::uint64_t& out) const { - if (mip >= mips_.size() || !addressable()) return false; - const MipLayout& m = mips_[mip]; - const std::uint32_t depth = desc_.dimension == Dimension::tex3d ? m.depth : slices_; - if (x >= m.width || y >= m.height || z >= depth) return false; - const auto [slice, inner] = split(z); - const std::uint64_t base = std::uint64_t(slice) * slice_size_ + m.offset; - if (desc_.swizzle == swizzle::linear) { - out = base + (std::uint64_t(y) * m.pitch + x) * desc_.element_bytes; - } else if (desc_.swizzle == swizzle::sw_64kb_r_x) { - out = render_xor_offset(m, x, y); - } else { - out = base + row(m, y, inner) + column(m, x); - } - return true; - } - - // The bytes from the texture's start that mip `first` and the smaller ones take: the smaller a mip, the nearer - // the start it lies (a title that streams textures has memory for the smaller mips only). All of the layout - // where slices follow each other. - std::uint64_t bytes_from(std::uint32_t first) const { - if (first == 0 || slices_ != 1 || thick_ || desc_.dimension == Dimension::tex3d || desc_.samples != 1 || - first >= desc_.mips) - return size_; - std::uint64_t most = 0; - for (std::size_t i = first; i < mips_.size(); ++i) { - const MipLayout& m = mips_[i]; - most = std::max(most, m.in_tail ? alignment_ - : m.offset + std::uint64_t(m.pitch) * m.rows * desc_.element_bytes); - } - return std::min(most ? most : size_, size_); - } - - // One subresource out of tiled memory (the whole texture, size() bytes, or bytes_from(mip)) into linear rows: mip - // `mip` of array slice `slice` (3D: every depth slice of the mip, `slice` 0). Rows are `row_pitch` bytes apart, - // depth slices `depth_pitch`. False, with nothing written past what was copied, for a bad mip or slice, a layout - // that is not addressable, or buffers too small. - bool detile(std::span tiled, std::uint32_t mip, std::uint32_t slice, std::span linear, - std::size_t row_pitch, std::size_t depth_pitch) const { - return walk(tiled.size(), mip, slice, linear.size(), row_pitch, depth_pitch, - [&](std::size_t t, std::size_t l, std::size_t n) { std::memcpy(linear.data() + l, tiled.data() + t, n); }); - } - - // The reverse of detile: linear rows into tiled memory. - bool tile(std::span tiled, std::uint32_t mip, std::uint32_t slice, std::span linear, - std::size_t row_pitch, std::size_t depth_pitch) const { - return walk(tiled.size(), mip, slice, linear.size(), row_pitch, depth_pitch, - [&](std::size_t t, std::size_t l, std::size_t n) { std::memcpy(tiled.data() + t, linear.data() + l, n); }); - } - -private: - static constexpr std::uint32_t kMaxMips = 16; - // GFX10's image descriptors hold at most 16384 texels per side; the bound also keeps every size computed here in - // range for values a title passes unchecked. - static constexpr std::uint32_t kMaxExtent = 1u << 14; - - static constexpr std::uint32_t div_ceil(std::uint32_t a, std::uint32_t b) { return (a + b - 1) / b; } - static constexpr std::uint32_t round_up(std::uint32_t a, std::uint32_t b) { return div_ceil(a, b) * b; } - // Elements along one side of mip `mip`, as data and copies see it: texels halve rounding down (to at least 1), - // then round up to whole elements. - static constexpr std::uint32_t dim(std::uint32_t texels, std::uint32_t mip, std::uint32_t block) { - return div_ceil(std::max(texels >> mip, 1u), block); - } - // Elements along one side for placement (padding, tail, offsets): addrlib halves mip 0's elements rounding up, - // which can be one more than dim() for odd sizes. - static constexpr std::uint32_t padded_dim(std::uint32_t texels, std::uint32_t mip, std::uint32_t block) { - return div_ceil(div_ceil(std::max(texels, 1u), block), 1u << mip); - } - - // 256-byte micro tile patterns by log2 of the element size: for each address bit, the element coordinate bit it - // takes, "--" for the bits inside an element. Thin S, thin D, thick S (also the D 3D modes), from addrlib's - // GFX10_SW_256_S_RBPLUS, GFX10_SW_256_D_RBPLUS and GFX10_SW_4K_S3_RBPLUS; larger blocks add Y, X (thin) or Y, X, Z - // (thick) in turn. - static constexpr const char* kMicro[3][5] = { - {"x0x1x2x3y0y1y2y3", "--x0x1x2y0y1y2x3", "----x0x1y0y1y2x2", "------x0y0y1x1x2", "--------y0y1x0x1"}, - {"x0x1x2y1y0y2x3y3", "--x0x1x2y0y1y2x3", "----x0x1y0y1x2y2", "------x0y0x1x2y1", "--------x0y0x1y1"}, - {"x0x1z0y0z1y1x2z2", "--x0z0y0z1y1x1z2", "----x0y0z0y1x1z1", "------x0z0y0x1z1", "--------z0y0x0z1"}, - }; - static constexpr std::uint32_t kBlock256_2d[5][2] = {{16, 16}, {16, 8}, {8, 8}, {8, 4}, {4, 4}}; - static constexpr std::uint32_t kBlock256_3d[5][3] = {{8, 4, 8}, {4, 4, 8}, {4, 4, 4}, {4, 2, 4}, {2, 2, 4}}; - static constexpr std::uint32_t kBlock1k_3d[5][3] = {{16, 8, 8}, {8, 8, 8}, {8, 8, 4}, {8, 4, 4}, {4, 4, 4}}; - - // For each axis, the address bit each coordinate bit lands on. - static std::array, 3> pattern(int kind, std::uint32_t element_log2, - std::uint32_t block_log2) { - std::array, 3> axes; - const char* micro = kMicro[kind][element_log2]; - for (std::uint32_t bit = 0; bit < 8; ++bit) { - const char axis = micro[2 * bit]; - const int to = axis == 'x' ? 0 : axis == 'y' ? 1 : axis == 'z' ? 2 : -1; - if (to < 0) continue; - const std::size_t index = std::size_t(micro[2 * bit + 1] - '0'); - if (axes[to].size() <= index) axes[to].resize(index + 1, 0); - axes[to][index] = bit; - } - static constexpr int thin[2] = {1, 0}, thick_order[3] = {1, 0, 2}; - for (std::uint32_t bit = 8, i = 0; bit < block_log2; ++bit, ++i) - axes[kind == 2 ? thick_order[i % 3] : thin[i % 2]].push_back(bit); - return axes; - } - - // Byte offsets inside a block for coordinates 0..2^bits of one axis. - static std::vector spread(const std::vector& bits) { - std::vector out(std::size_t(1) << bits.size()); - for (std::uint32_t c = 0; c < out.size(); ++c) - for (std::size_t i = 0; i < bits.size(); ++i) out[c] |= ((c >> i) & 1u) << bits[i]; - return out; - } - - // AMD GFX10_SW_64K_R_X_1xaa_RBPLUS with no additional base pipe XOR: the in-block byte offset each coordinate bit - // toggles. 32 pipes / 8 packers on Series X, 8 / 4 on Series S. - static std::array, 3> render_xor_pattern(bool series_s, std::uint32_t element_bytes) { - std::vector x, y; - if (!series_s && element_bytes == 2) { - x = {2, 4, 8, 0x80, 0x200, 0x800, 0x1400, 0x8100, 0x1000}; - y = {0x10, 0x20, 0x40, 0x2000, 0x300, 0x400, 0x4800, 0x8100, 0x1000}; - } else if (!series_s && element_bytes == 4) { - x = {4, 8, 0x40, 0x2000, 0x200, 0x800, 0x1400, 0x8100, 0x1000}; - y = {0x10, 0x20, 0x80, 0x4000, 0x300, 0x400, 0x8800, 0x100, 0x1000}; - } else if (!series_s && element_bytes == 8) { - x = {8, 0x20, 0x40, 0x4000, 0x200, 0x800, 0x1400, 0x8100, 0x1000}; - y = {0x10, 0x80, 0x2000, 0x8000, 0x300, 0x400, 0x800, 0x100, 0x1000}; - } else if (series_s && element_bytes == 2) { - x = {2, 4, 8, 0x80, 0x200, 0x1400, 0x2100, 0x8000, 0x4000}; - y = {0x10, 0x20, 0x40, 0x800, 0x300, 0x400, 0x4100, 0x8000, 0x2000}; - } else if (series_s && element_bytes == 4) { - x = {4, 8, 0x40, 0x800, 0x200, 0x2400, 0x4100, 0x8000}; - y = {0x10, 0x20, 0x80, 0x1000, 0x300, 0x400, 0x8100, 0x4000, 0x2000}; - } else if (series_s && element_bytes == 8) { - x = {8, 0x20, 0x40, 0x1000, 0x200, 0x4400, 0x8100, 0x2000}; - y = {0x10, 0x80, 0x800, 0x2000, 0x300, 0x400, 0x8100, 0x4000}; - } else { - return {}; - } - const auto contributions = [](const std::vector& basis) { - std::vector offsets(std::size_t(1) << basis.size(), 0); - for (std::size_t bit = 0; bit < basis.size(); ++bit) { - const std::size_t n = std::size_t(1) << bit; - for (std::size_t i = 0; i < n; ++i) offsets[n + i] = offsets[i] ^ basis[bit]; - } - return offsets; - }; - return {contributions(x), contributions(y), {}}; - } - - // HwlComputeSurfaceInfoLinear: rows aligned to 256 bytes, mips packed smallest first, a 3D texture's depth slices - // each hold the chain. - void linear(const LayoutDesc& d) { - desc_ = d; - const std::uint64_t bpe = d.element_bytes; - const std::uint32_t align = 256 / d.element_bytes; - const bool three_d = d.dimension == Dimension::tex3d; - std::uint64_t offset = 0; - mips_.resize(d.mips); - for (std::uint32_t i = d.mips; i-- > 0;) { - MipLayout& m = mips_[i]; - const std::uint32_t h = padded_dim(d.height, i, d.block); - m.pitch = round_up(padded_dim(d.width, i, d.block), align); - m.width = dim(d.width, i, d.block); - m.height = dim(d.height, i, d.block); - m.depth = three_d ? dim(d.depth, i, 1) : 1; - m.rows = h; - m.depth_pitch = three_d ? d.depth : 1; - m.offset = offset; - offset += std::uint64_t(m.pitch) * h * bpe; - } - block_ = {align, 1, 1}; - thick_ = false; - slices_ = d.depth; - slice_size_ = offset; - size_ = offset * d.depth; - alignment_ = 256; - first_tail_mip_ = d.mips; - } - - void tiled(const LayoutDesc& d, std::uint32_t block_log2, bool series_s) { - desc_ = d; - const std::uint32_t element_log2 = std::uint32_t(std::countr_zero(d.element_bytes)); - const std::uint64_t bpe = d.element_bytes; - const std::uint64_t block_bytes = std::uint64_t(1) << block_log2; - const bool three_d = d.dimension == Dimension::tex3d; - thick_ = three_d && (swizzle::standard(d.swizzle) || swizzle::display(d.swizzle)); - if (thick_) { // ComputeThickBlockDimension - const std::uint32_t amp = (block_log2 - 10) / 3, rest = (block_log2 - 10) % 3; - const auto& b = kBlock1k_3d[element_log2]; - block_ = {b[0] << amp, b[1] << (amp + rest / 2), b[2] << (amp + (rest != 0 ? 1 : 0))}; - } else { // ComputeThinBlockDimension - const std::uint32_t samples_log2 = std::uint32_t(std::countr_zero(d.samples)); - const std::uint32_t elements_log2 = block_log2 - element_log2 - samples_log2; - const bool wide = (samples_log2 & 1) == 0 || (block_log2 & 1) != 0; - const std::uint32_t w = (elements_log2 + (wide ? 1 : 0)) / 2; - block_ = {1u << w, 1u << (elements_log2 - w), 1}; - } - std::uint32_t slices = round_up(d.depth, block_[2]); - const auto mip_depth = [&](std::uint32_t i) { return thick_ ? padded_dim(d.depth, i, 1) : 1u; }; - const auto depth_of = [&](std::uint32_t i) { return three_d ? dim(d.depth, i, 1) : 1u; }; - first_tail_mip_ = d.mips; - std::uint64_t slice_size = 0; - if (d.mips == 1) { - MipLayout m; - m.width = dim(d.width, 0, d.block); - m.height = dim(d.height, 0, d.block); - m.depth = depth_of(0); - m.pitch = round_up(m.width, block_[0]); - m.rows = round_up(m.height, block_[1]); - m.depth_pitch = three_d ? slices : 1; - mips_.push_back(m); - slice_size = std::uint64_t(m.pitch) * m.rows * bpe * d.samples; - } else { - // GetMipTailDim: the largest mip the tail takes. - std::array tail_max = block_; - if (thick_) { - switch (block_log2 % 3) { - case 0: tail_max[1] >>= 1; break; - case 1: tail_max[0] >>= 1; break; - default: tail_max[2] >>= 1; break; - } - } else { - tail_max[0] >>= 1; - } - // GetMaxNumMipsInTail; 256-byte blocks have no tail (ComputeSurfaceInfoMicroTiled). - const std::uint32_t effective = thick_ ? block_log2 - (block_log2 - 8) / 3 : block_log2; - const std::uint32_t max_in_tail = effective == 8 ? 0 - : effective >= 9 && effective <= 11 ? 1 + (1u << (effective - 9)) - : effective - 4; - // dsMipmapHtileFix: 8- and 16-bit depth enter the tail as 32-bit. - std::array fixed = tail_max; - if (swizzle::z_order(d.swizzle) && element_log2 <= 1) { - fixed[0] /= kBlock256_2d[element_log2][0] / kBlock256_2d[2][0]; - fixed[1] /= kBlock256_2d[element_log2][1] / kBlock256_2d[2][1]; - } - std::vector sizes; - for (std::uint32_t i = 0; i < d.mips; ++i) { - const std::uint32_t w = padded_dim(d.width, i, d.block), h = padded_dim(d.height, i, d.block); - if (w <= fixed[0] && h <= fixed[1] && d.mips - i <= max_in_tail) { - first_tail_mip_ = i; - slice_size += block_bytes / block_[2]; - break; - } - MipLayout m; - m.pitch = round_up(w, block_[0]); - m.rows = round_up(h, block_[1]); - const std::uint32_t depth = round_up(mip_depth(i), block_[2]); - const std::uint64_t one = std::uint64_t(m.pitch) * m.rows * bpe; - slice_size += one; - sizes.push_back(one * block_[2]); - m.width = dim(d.width, i, d.block); - m.height = dim(d.height, i, d.block); - m.depth = depth_of(i); - m.depth_pitch = three_d ? depth : 1; - mips_.push_back(m); - } - // Standard mips from the smallest up, after the tail block. - std::uint64_t offset = first_tail_mip_ < d.mips ? block_bytes : 0; - for (std::uint32_t i = first_tail_mip_; i-- > 0;) { - mips_[i].offset = offset; - offset += sizes[i]; - } - const std::uint32_t micro_w = thick_ ? kBlock256_3d[element_log2][0] : kBlock256_2d[element_log2][0]; - const std::uint32_t micro_h = thick_ ? kBlock256_3d[element_log2][1] : kBlock256_2d[element_log2][1]; - std::uint32_t pitch = tail_max[0], rows = tail_max[1]; - for (std::uint32_t i = first_tail_mip_; i < d.mips; ++i) { - const std::uint32_t m = max_in_tail - 1 - (i - first_tail_mip_); - const std::uint32_t tail_offset = m > 6 ? 16u << m : m << 8; - // Address bits 8.. of the offset, odd ones x, even ones y. - const auto bits = [&](std::uint32_t from) { - std::uint32_t v = 0; - for (std::uint32_t b = 0; b < 6; ++b) v |= ((tail_offset >> (from + 2 * b)) & 1u) << b; - return v; - }; - std::uint32_t x = bits(9), y = bits(8); - if (block_log2 & 1) { - std::swap(x, y); - if (element_log2 & 1) { - y = (y << 1) | (x & 1); - x >>= 1; - } - } - MipLayout mip; - mip.width = dim(d.width, i, d.block); - mip.height = dim(d.height, i, d.block); - mip.depth = depth_of(i); - mip.pitch = pitch; - mip.rows = rows; - mip.depth_pitch = thick_ ? round_up(mip_depth(i), kBlock256_3d[element_log2][2]) : 1; - mip.in_tail = true; - mip.tail_offset = tail_offset; - mip.tail_x = x * micro_w; - mip.tail_y = y * micro_h; - mips_.push_back(mip); - pitch = std::max(pitch >> 1, micro_w); - rows = std::max(rows >> 1, micro_h); - } - } - // Thick layouts store each depth slab's chain together. - slice_size_ = slice_size * (thick_ ? block_[2] : 1); - slices_ = slices / block_[2]; - size_ = slice_size_ * slices_; - alignment_ = block_bytes; - if (!swizzle::xor_mode(d.swizzle) && d.samples == 1) { - const int kind = thick_ ? 2 : swizzle::display(d.swizzle) ? 1 : 0; - const auto bits = pattern(kind, element_log2, block_log2); - for (int axis = 0; axis < 3; ++axis) pattern_[axis] = spread(bits[axis]); - } else if (d.swizzle == swizzle::sw_64kb_r_x && d.dimension == Dimension::tex2d && d.depth == 1 && - d.mips == 1 && d.samples == 1 && d.block == 1) { - pattern_ = render_xor_pattern(series_s, d.element_bytes); - } - } - - // The slice and the depth inside it for `z` (an array slice or a 3D depth slice). - std::pair split(std::uint32_t z) const { - return thick_ ? std::pair{z / block_[2], z % block_[2]} : std::pair{z, 0u}; - } - - std::uint64_t render_xor_offset(const MipLayout& m, std::uint32_t x, std::uint32_t y) const { - const std::uint64_t block = std::uint64_t(y / block_[1]) * (m.pitch / block_[0]) + x / block_[0]; - const auto& ox = pattern_[0]; - const auto& oy = pattern_[1]; - return block * alignment_ + (ox[x & (ox.size() - 1)] ^ oy[y & (oy.size() - 1)]); - } - - // The part of an address that depends on the row (and the depth in a thick block). In the tail the pattern of the - // shifted position gives the mip's offset inside the tail block. - std::uint64_t row(const MipLayout& m, std::uint32_t y, std::uint32_t z) const { - const unsigned log2 = unsigned(std::countr_zero(alignment_)); - y += m.in_tail ? m.tail_y : 0; - const std::uint64_t blocks = std::uint64_t(y / block_[1]) * (m.pitch / block_[0]); - return (blocks << log2) + (pattern_[1][y % block_[1]] | pattern_[2][z]); - } - - // The part of an address that depends on the column. - std::uint64_t column(const MipLayout& m, std::uint32_t x) const { - x += m.in_tail ? m.tail_x : 0; - return (std::uint64_t(x / block_[0]) << std::countr_zero(alignment_)) + pattern_[0][x % block_[0]]; - } - - // Visits contiguous runs as (tiled byte offset, linear byte offset, length). - template - bool walk(std::size_t tiled_len, std::uint32_t mip, std::uint32_t slice, std::size_t linear_len, - std::size_t row_pitch, std::size_t depth_pitch, Copy&& copy) const { - if (mip >= mips_.size()) return false; - const MipLayout& m = mips_[mip]; - std::uint32_t first = slice; - if (desc_.dimension == Dimension::tex3d) { - if (slice != 0) return false; - first = 0; - } - if (first >= slices_ || !addressable()) return false; - const std::size_t n = desc_.element_bytes; - const std::size_t bytes = std::size_t(m.width) * n; - constexpr std::size_t max = std::numeric_limits::max(); - const std::size_t dz = m.depth - 1, dy = m.height - 1; - if ((dz && depth_pitch > max / dz) || (dy && row_pitch > max / dy)) return false; - const std::size_t a = dz * depth_pitch, b = dy * row_pitch; - if (a > max - b || a + b > max - bytes) return false; - const std::size_t need = a + b + bytes; - if (tiled_len < bytes_from(mip) || linear_len < need || row_pitch < bytes) return false; - if (desc_.swizzle == swizzle::sw_64kb_r_x) { - // The low four address bits are column and element bits only, so every element size has 16-byte runs. - for (std::uint32_t y = 0; y < m.height; ++y) - for (std::uint32_t x = 0; x < m.width; x += std::uint32_t(16 / n)) { - const std::size_t lx = std::size_t(x) * n; - copy(std::size_t(render_xor_offset(m, x, y)), std::size_t(y) * row_pitch + lx, - std::min(16, bytes - lx)); - } - return true; - } - const bool is_linear = desc_.swizzle == swizzle::linear; - // The row and depth contribute one common base to every column, so the same runs repeat on every row. - std::vector> runs; // (tiled, linear, length) within a row - if (!is_linear) { - std::size_t first_linear = 0, first_tiled = std::size_t(column(m, 0)); - for (std::uint32_t x = 1; x < m.width; ++x) { - const std::size_t at_tiled = std::size_t(column(m, x)), at_linear = std::size_t(x) * n; - if (at_tiled != first_tiled + (at_linear - first_linear)) { - runs.push_back({first_tiled, first_linear, at_linear - first_linear}); - first_tiled = at_tiled; - first_linear = at_linear; - } - } - runs.push_back({first_tiled, first_linear, bytes - first_linear}); - } - for (std::uint32_t z = 0; z < m.depth; ++z) { - const auto [s, inner] = split(first + z); - const std::uint64_t base = std::uint64_t(s) * slice_size_ + m.offset; - for (std::uint32_t y = 0; y < m.height; ++y) { - const std::size_t linear_row = std::size_t(z) * depth_pitch + std::size_t(y) * row_pitch; - if (is_linear) { - copy(std::size_t(base + std::uint64_t(y) * m.pitch * n), linear_row, bytes); - } else { - const std::size_t tiled_row = std::size_t(base + row(m, y, inner)); - for (const auto& run : runs) copy(tiled_row + run[0], linear_row + run[1], run[2]); - } - } - } - return true; - } - - LayoutDesc desc_{}; - std::array block_{}; - bool thick_ = false; - std::uint32_t slices_ = 0; - std::uint64_t slice_size_ = 0, size_ = 0, alignment_ = 0; - std::uint32_t first_tail_mip_ = 0; - std::vector mips_; - // Byte offsets inside a block of each element coordinate, per axis; empty for linear and unaddressable modes. - std::array, 3> pattern_; -}; - -// What a DXGI format stores per element on the console: bytes, texels per element side (4 for block compression), and -// whether its stencil is a second plane (the GPU keeps depth and stencil apart). False for 96-bit, 1-bit, packed 4:2:2 -// and video formats (VIctory texture.rs format(): not laid out there either). -struct ElementFormat { - std::uint32_t bytes = 0, block = 1; - bool stencil = false; -}; -constexpr bool element_format(std::uint32_t dxgi, ElementFormat& out) { - const auto in = [&](std::uint32_t a, std::uint32_t b) { return dxgi >= a && dxgi <= b; }; - if (in(1, 4)) out = {16, 1, false}; - else if (in(9, 18)) out = {8, 1, false}; - else if (in(19, 22) || in(44, 47)) out = {4, 1, true}; - else if (in(23, 43) || dxgi == 67 || in(87, 93) || dxgi == 116 || dxgi == 117) out = {4, 1, false}; - else if (in(48, 59) || dxgi == 85 || dxgi == 86 || dxgi == 115) out = {2, 1, false}; - else if (in(118, 120)) out = {2, 1, true}; - else if (in(60, 65)) out = {1, 1, false}; - else if (in(70, 72) || in(79, 81)) out = {8, 4, false}; - else if (in(73, 78) || in(82, 84) || in(94, 99)) out = {16, 4, false}; - else return false; - return true; -} - -// A texture as the console allocates it: every data plane (depth, then stencil), one after the other. -// shortcut (as VIctory's): no compression metadata planes (HTILE, CMASK, FMASK, DCC). -struct ConsoleTextureDesc { - Dimension dimension = Dimension::tex2d; - std::uint32_t width = 1, height = 1, depth_or_array = 1; - std::uint32_t mips = 1; // 0: the full chain - std::uint32_t format = 0; // DXGI format number - std::uint32_t samples = 1; - std::uint32_t swizzle = swizzle::linear; -}; - -struct TexturePlane { - std::uint64_t offset = 0; // from the start of the texture - bool stencil = false; - TextureLayout layout; -}; - -struct ConsoleTexture { - std::vector planes; - std::uint64_t size = 0, alignment = 1; - - static bool make(const ConsoleTextureDesc& d, bool series_s, ConsoleTexture& out) { - ElementFormat f; - if (!element_format(d.format, f)) return false; - const std::uint32_t depth3d = d.dimension == Dimension::tex3d ? d.depth_or_array : 1; - const std::uint32_t mips = - d.mips ? d.mips : std::uint32_t(std::bit_width(std::max({d.width, d.height, depth3d, 1u}))); - LayoutDesc plane{d.dimension, d.width, d.height, d.depth_or_array, mips, f.bytes, f.block, - std::max(d.samples, 1u), d.swizzle}; - ConsoleTexture t; - TexturePlane first; - if (!TextureLayout::make(plane, series_s, first.layout)) return false; - t.planes.push_back(std::move(first)); - if (f.stencil) { - plane.element_bytes = 1; - TexturePlane second; - if (!TextureLayout::make(plane, series_s, second.layout)) return false; - const std::uint64_t a = second.layout.alignment(); - second.offset = (t.planes[0].layout.size() + a - 1) / a * a; - second.stencil = true; - t.planes.push_back(std::move(second)); - } - t.size = t.planes.back().offset + t.planes.back().layout.size(); - for (const TexturePlane& p : t.planes) t.alignment = std::max(t.alignment, p.layout.alignment()); - out = std::move(t); - return true; - } -}; - -// The mode the console's layout library (xg_xs.dll XGSuggestSwizzleMode) picks for a texture: linear for 1D, the XOR -// depth and render modes for depth and render targets, else SW_4KB_S (.ttpf textures without a mode of their own use -// it). VIctory victory-hle xg.rs suggested(), which marks it a shortcut: the rule of the library's older optimal-mode -// function (any size, 2D, 3D and cubes alike); XGSuggestSwizzleMode itself is newer than every copy VIctory could -// check, so revisit if streamed textures come out scrambled. The layer reads layout word 0 with the same rule. -constexpr std::uint32_t suggested_swizzle(Dimension dimension, bool depth_stencil, bool render_target) { - return dimension == Dimension::tex1d ? swizzle::linear - : depth_stencil ? swizzle::sw_64kb_z_x - : render_target ? swizzle::sw_64kb_r_x - : swizzle::sw_4kb_s; -} - -// The swizzle mode a console D3D12_RESOURCE_DESC::Layout word names (VIctory xg.rs texture(), victory-gpu -// resource.rs texture_layout): 0x100 | the mode, 1 row major (linear), 0 the library's pick (suggested_swizzle). False -// for any other word. -constexpr bool swizzle_from_layout_word(std::uint32_t word, Dimension dimension, bool depth_stencil, - bool render_target, std::uint32_t& mode) { - if (word == 0) mode = suggested_swizzle(dimension, depth_stencil, render_target); - else if (word == 1) mode = swizzle::linear; - else if ((word & ~0xffu) == 0x100) mode = word & 0xff; - else return false; - return true; -} - } // namespace leonida::gfx10 diff --git a/runtime/src/host_cpu.h b/runtime/src/host_cpu.h index 5f36581aa..b9dd143db 100644 --- a/runtime/src/host_cpu.h +++ b/runtime/src/host_cpu.h @@ -1,8 +1,7 @@ // Host CPU preflight for --init and --run: the game executes AVX instructions from its TLS callbacks on, so a host // whose CPU or OS lacks AVX (a QEMU qemu64 guest, for one) dies there with a bare EXCEPTION_ILLEGAL_INSTRUCTION // (0xC000001D) that reads like a loader bug. This checks AVX only, which is what was measured; it claims nothing -// about AVX2, FMA or BMI2. No emulation here: the console-only instructions (CLZERO, SSE4a, ...) are emulated by -// console_insn.h's handler. Rosetta on macOS runs AVX code but leaves +// about AVX2, FMA or BMI2. No emulation here: that is RT-500's scope. Rosetta on macOS runs AVX code but leaves // AVX out of CPUID unless ROSETTA_ADVERTISE_AVX=1 is set, so the check fails there until that variable is set. #pragma once diff --git a/runtime/src/opus_packet.h b/runtime/src/opus_packet.h deleted file mode 100644 index d4e9ea243..000000000 --- a/runtime/src/opus_packet.h +++ /dev/null @@ -1,128 +0,0 @@ -// Opus packet framing (RFC 6716, section 3): how many samples a packet decodes to, and whether its framing is valid. -// -// Leonida has no Opus decoder yet. VIctory's xapu.dll (crates/victory-hle/src/modules/apu.rs, GPL-3.0-or-later, by -// Marvisak and contributors, DexNom fork) decodes with the opus-pure crate (BSD-3-Clause), which is not in this -// repository; the xapu shim ported from it uses this parser instead, so a packet gives the sample count and the -// errors a decoder would report, and silence for its samples. The checks are libopus's opus_packet_parse for a packet -// that is not self-delimited (the requirements R1-R7 of RFC 6716 section 3.4); the sample count is what opus_decode -// returns for such a packet at 48 kHz. Written for Leonida from the RFC; GPL-3.0-or-later. Pure C++: no OS headers. -#pragma once - -#include -#include - -namespace rt::opus { - -inline constexpr int kBufferTooSmall = -2; // OPUS_BUFFER_TOO_SMALL -inline constexpr int kInvalidPacket = -4; // OPUS_INVALID_PACKET -inline constexpr int kMaxFrameBytes = 1275; -inline constexpr int kMaxPacketSamples = 5760; // 120 ms at 48 kHz - -// Samples per channel at 48 kHz in each frame of a packet with this TOC byte (configuration, bits 7-3; section 3.1). -constexpr int samples_per_frame(uint8_t toc) { - if (toc & 0x80) return (48000 << ((toc >> 3) & 3)) / 400; // CELT-only: 2.5, 5, 10, 20 ms - if ((toc & 0x60) == 0x60) return (toc & 0x08) ? 960 : 480; // hybrid: 10, 20 ms - const int size = (toc >> 3) & 3; // SILK-only: 10, 20, 40, 60 ms - return size == 3 ? 2880 : (48000 << size) / 100; -} - -namespace detail { - -// A frame length (section 3.2.1): one byte below 252, else two. Returns the bytes used, -1 (and size -1) without them. -inline int parse_size(const uint8_t* data, ptrdiff_t len, int* size) { - if (len < 1) { - *size = -1; - return -1; - } - if (data[0] < 252) { - *size = data[0]; - return 1; - } - if (len < 2) { - *size = -1; - return -1; - } - *size = 4 * data[1] + data[0]; - return 2; -} - -} // namespace detail - -// The number of frames in the packet (frame count codes 0-3, section 3.2), or kInvalidPacket for one RFC 6716 does -// not allow. -inline int frame_count(const uint8_t* data, size_t length) { - if (!data || length == 0) return kInvalidPacket; - const uint8_t toc = data[0]; - const int framesize = samples_per_frame(toc); - const uint8_t* p = data + 1; - ptrdiff_t len = static_cast(length) - 1; - ptrdiff_t last_size = len; - int count = 0; - switch (toc & 3) { - case 0: // one frame - count = 1; - break; - case 1: // two frames of the same size - count = 2; - if (len & 1) return kInvalidPacket; - last_size = len / 2; - break; - case 2: { // two frames, the first's size given - count = 2; - int size = 0; - const int bytes = detail::parse_size(p, len, &size); - len -= bytes; - if (size < 0 || size > len) return kInvalidPacket; - p += bytes; - last_size = len - size; - break; - } - default: { // a frame count byte: 1 to 48 frames, CBR or VBR, optional padding - if (len < 1) return kInvalidPacket; - const uint8_t ch = *p++; - --len; - count = ch & 0x3f; - if (count <= 0 || framesize * count > kMaxPacketSamples) return kInvalidPacket; - if (ch & 0x40) { - int pad = 0; - do { - if (len <= 0) return kInvalidPacket; - pad = *p++; - --len; - len -= pad == 255 ? 254 : pad; - } while (pad == 255); - } - if (len < 0) return kInvalidPacket; - if (ch & 0x80) { // VBR: every frame's size but the last - last_size = len; - for (int i = 0; i < count - 1; ++i) { - int size = 0; - const int bytes = detail::parse_size(p, len, &size); - len -= bytes; - if (size < 0 || size > len) return kInvalidPacket; - p += bytes; - last_size -= bytes + size; - } - if (last_size < 0) return kInvalidPacket; - } else { // CBR - last_size = len / count; - if (last_size * count != len) return kInvalidPacket; - } - break; - } - } - // The last frame's size (all of them, CBR) is not coded and may exceed what a frame can hold. - if (last_size > kMaxFrameBytes) return kInvalidPacket; - return count; -} - -// Samples per channel at 48 kHz that decoding the packet gives, as opus_decode returns it: its frames times the -// samples per frame, kInvalidPacket for a malformed packet, kBufferTooSmall when that is more than `max_samples`. -inline int packet_samples(const uint8_t* data, size_t length, int max_samples = kMaxPacketSamples) { - const int count = frame_count(data, length); - if (count < 0) return count; - const int samples = count * samples_per_frame(data[0]); - return samples > max_samples ? kBufferTooSmall : samples; -} - -} // namespace rt::opus diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index 54440459d..fc73f37f5 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -1341,10 +1341,6 @@ void* bundled_load_w(void* ctx, const std::wstring& basename, uint32_t flags, bo return static_cast(ctx)->load_runtime_module_w(basename, flags, handled); } -bool bundled_module_path(void* ctx, void* module, std::wstring& path) { - return static_cast(ctx)->module_path(module, path); -} - const shims::BundledModuleOps kBundledOps{ &bundled_find_loaded, &bundled_load, @@ -1352,7 +1348,6 @@ const shims::BundledModuleOps kBundledOps{ &bundled_owns_handle, &bundled_find_loaded_w, &bundled_load_w, - &bundled_module_path, }; // Marks what a run-time load maps as a dynamic load for as long as it is in scope (the caller holds the mutex). @@ -1600,19 +1595,6 @@ bool Loader::find_address(uint64_t address, std::string& module, uint32_t& rva) return false; } -bool Loader::module_path(void* module_handle, std::wstring& path) const { - if (!module_handle) return false; - std::lock_guard lock(mutex_); - for (const Module* m : order_) - if (m->base == module_handle) { - std::error_code ec; - const std::filesystem::path absolute = std::filesystem::absolute(m->path, ec); - path = (ec ? m->path : absolute).wstring(); - return true; - } - return false; -} - bool Loader::owns_module_handle(void* module_handle) const { if (!module_handle) return false; std::lock_guard lock(mutex_); diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h index 542808f88..f75426e41 100644 --- a/runtime/src/pe_loader.h +++ b/runtime/src/pe_loader.h @@ -137,8 +137,6 @@ public: void* load_runtime_module_w(const std::wstring& basename, uint32_t flags, bool& handled); void* resolve_module_export(void* module_handle, const std::string& sym, bool& owns_handle); bool owns_module_handle(void* module_handle) const; - // The file a mapped module was mapped from, by its handle (base); false for any other handle. - bool module_path(void* module_handle, std::wstring& path) const; private: void initialise(Module& m); diff --git a/runtime/src/pipeline_queue.h b/runtime/src/pipeline_queue.h deleted file mode 100644 index 299b2a096..000000000 --- a/runtime/src/pipeline_queue.h +++ /dev/null @@ -1,749 +0,0 @@ -// Pipelines made by worker threads instead of the thread that creates or first binds them, a per-frame budget for -// waiting on them at the bind, and the list of pipelines earlier runs bound, started early. -// -// Ported from VIctory (victory/crates/victory-gpu/src/pipeline/make.rs and pipeline/library.rs; GPL-3.0-or-later, -// Marvisak and contributors, DexNom fork). The title creates some 60,000 pipelines in its first 20 s and draws with a -// few dozen of them (pipeline.rs:6-11); its first world frame wants over 1,200 new ones, and made on the recording -// threads that frame took more than 30 s, past the title's GPU watchdog (make.rs:1-8, 181-185). So, as there: -// - A pipeline state records what its pipeline is made from and returns; a Job makes the pipeline on a worker. -// - Creation starts a pipeline an earlier run bound (EarlyList, library.rs:10-13 and make.rs `early`); any other -// pipeline is started by its first bind (make.rs `ready`). Requests go first, then early depth-only pipelines, -// then the other early ones (make.rs Queue). -// - A bind waits for its pipeline while the frame's budget lasts (make.rs `wait`): per frame and kind (graphics, -// compute), a window of waiting time the binding threads share (FrameWait), never for a pipeline the driver has -// held for long (held_too_long). A draw or dispatch whose pipeline is not made then is dropped and counted -// (pipeline.rs `note_drop`), and the counts are logged once a second. -// Also as there: its 12 s default budget per frame and kind (LEONIDA_PIPELINE_WAIT_MS) and its loading allowance -// (make.rs:193-223, waits of up to 4 s / 12 s per frame while a world loads, LEONIDA_PIPELINE_GATE_S). -// Leonida's own rule: on a device of no title (the PC interface, the tests) a bind waits for its pipeline however long -// it takes until the console frame clock begins a frame (device slot 80, frame.rs:120-184), so nothing is dropped -// there: D3D12 has a PSO usable once it is created. The title's device is bounded from its creation (title_running). -// -// The worker threads are the process's and are never stopped; the builder is never destroyed (a static destructor -// at exit would run under them). Nothing here is thread_local (AGENTS.md, "Runtime traps"). -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef _WIN32 -#ifndef NOMINMAX -#define NOMINMAX -#endif -#include -#endif - -namespace leonida::pipelines { - -using Clock = std::chrono::steady_clock; - -// ---- Frames --------------------------------------------------------------------------------------------------- - -// Frames the console frame clock has begun (origin waits that hand out a token, frame.rs:163-171). 0: none yet. -inline std::atomic& frame_counter() { - static std::atomic frames{0}; - return frames; -} -inline std::uint64_t current_frame() { return frame_counter().load(std::memory_order_relaxed); } -inline std::uint64_t begin_frame() { return frame_counter().fetch_add(1, std::memory_order_relaxed) + 1; } - -// A title is running: D3D12XboxCreateDevice made its device in the console layout. From then on a bind's wait is -// bounded even before the frame clock's first frame, which is VIctory's frame 0 (make.rs `wait` with frame::current() -// 0): the title creates and uses pipelines while it sets up, and a 30 s watchdog of its own ends a main thread that -// stops for that long (the first CreateComputePipelineState stalled ~28 s on the synchronous compile). -inline std::atomic& title_running() { - static std::atomic running{false}; - return running; -} -// Whether binds wait within a frame's budget (else as long as the build takes: the PC interface, the tests). -inline bool waits_bounded() { return title_running().load(std::memory_order_relaxed) || current_frame() > 0; } - -// ---- Settings ------------------------------------------------------------------------------------------------- - -// How the threads that wait in one frame share its budget (make.rs:290-332, VICTORY_PIPELINE_WAIT_SHARED; here -// LEONIDA_PIPELINE_WAIT_SHARED): a window of waiting time by default, `reserve` or `0` as VIctory had them before. -enum class Sharing { window, reserve, per_thread }; - -inline Sharing sharing_from(const char* value) { - if (!value) return Sharing::window; - std::string v(value); - const auto first = v.find_first_not_of(" \t"); - v = first == std::string::npos ? std::string() : v.substr(first, v.find_last_not_of(" \t") - first + 1); - if (v == "0") return Sharing::per_thread; - if (v == "reserve") return Sharing::reserve; - return Sharing::window; -} - -// VIctory's default (make.rs:170-182, decision 0007): the picture before frame rate. A frame waits for pipelines still -// being made rather than drop their draws and dispatches, up to 12 s for each kind, the threads together; both kinds' -// windows one after the other stay under the title's 30 s hang watchdog (kMaxWaitMs). Until 2026-11-26 this was -// 500 ms, and the world load dropped the passes the title dispatches once (VIctory: walls, floors and faces missing). -inline constexpr std::int64_t kDefaultWaitMs = 12000; - -// While a world loads (make.rs:184-223): a frame whose budget is shorter may still wait up to 4 s for a graphics and -// 12 s for a compute pipeline, until LEONIDA_PIPELINE_GATE_S (120) seconds of such waiting are spent for that kind. -inline constexpr std::int64_t kLoadingFrameMs = 4000; -inline constexpr std::int64_t kLoadingFrameComputeMs = 12000; - -inline long long env_number(const char* name, long long fallback) { - char text[32] = {}; -#ifdef _WIN32 - std::size_t length = 0; - if (getenv_s(&length, text, sizeof(text), name) != 0 || length <= 1) return fallback; -#else - const char* value = std::getenv(name); - if (!value || !*value) return fallback; - std::snprintf(text, sizeof(text), "%s", value); -#endif - char* end = nullptr; - const long long n = std::strtoll(text, &end, 10); - return end == text || n < 0 ? fallback : n; -} - -// The most LEONIDA_PIPELINE_WAIT_MS may ask for. The title's hang watchdog (a thread that wakes once a second) ends the -// process when the main loop has not stamped its progress for 30 checks in a row: a deliberate write to address 0, -// which the runtime's log shows as an access violation writing 0x0. Both waits of a frame (graphics and compute) and -// the frame's own work must fit in that, so the two together stay under 24 s (VIctory's bound, make.rs:183-187). Measured: a run with the budget at 600 s -// stopped drawing at 180 s (its frames waited on pipelines made on 4 threads, one of them 10.3 s) and the title wrote -// to 0 at 211 s. -inline constexpr std::int64_t kMaxWaitMs = 12000; -static_assert(2 * kMaxWaitMs < 30000 && kLoadingFrameComputeMs <= kMaxWaitMs); - -// The budget the variable asks for, kept under kMaxWaitMs. -inline std::int64_t wait_budget_from_env(std::int64_t asked) { - if (asked <= kMaxWaitMs) return asked; - std::fprintf(stderr, - "[rt] d3d12: pipelines: LEONIDA_PIPELINE_WAIT_MS %lld is past the title's 30 s hang watchdog; " - "%lld ms is used\n", - static_cast(asked), static_cast(kMaxWaitMs)); - return kMaxWaitMs; -} - -// LEONIDA_PIPELINE_WAIT_MS: the waiting a frame allows per kind of pipeline, over all threads (make.rs:154-179), at -// most kMaxWaitMs. 0 waits for nothing once frames have begun. Read once; set_wait_budget overrides it (tests). -inline std::atomic& wait_budget_ms() { - static std::atomic ms{wait_budget_from_env(env_number("LEONIDA_PIPELINE_WAIT_MS", kDefaultWaitMs))}; - return ms; -} -inline Clock::duration wait_budget() { return std::chrono::milliseconds(wait_budget_ms().load(std::memory_order_relaxed)); } -inline void set_wait_budget(std::chrono::milliseconds budget) { wait_budget_ms().store(budget.count()); } - -inline Sharing shared_budget() { -#ifdef _WIN32 - char text[16] = {}; - std::size_t length = 0; - static const Sharing sharing = - getenv_s(&length, text, sizeof(text), "LEONIDA_PIPELINE_WAIT_SHARED") == 0 && length > 1 ? sharing_from(text) - : Sharing::window; -#else - static const Sharing sharing = sharing_from(std::getenv("LEONIDA_PIPELINE_WAIT_SHARED")); -#endif - return sharing; -} - -// LEONIDA_PIPELINE_WORKERS: build threads (make.rs:528-561: half the logical processors, 2 to 8). 0 builds each -// pipeline on the thread that starts it, as before. -inline unsigned worker_count() { - const unsigned hardware = std::max(1u, std::thread::hardware_concurrency()); - const long long fallback = std::clamp(hardware / 2, 2u, 8u); - return unsigned(std::min(env_number("LEONIDA_PIPELINE_WORKERS", fallback), 64)); -} - -// ---- One frame's waiting (make.rs:334-394) --------------------------------------------------------------------- - -struct FrameWait { - std::uint64_t frame = UINT64_MAX; - // The waiting counted against the budget so far (the window: time in which some thread waited, up to `since`). - Clock::duration spent{}; - // The window: threads waiting now, and since when one has been. - std::uint32_t waiting = 0; - bool open = false; - Clock::time_point since{}; - - // A thread is to wait in `frame` at `now`: how long it may. - Clock::duration begin(Sharing sharing, std::uint64_t at_frame, Clock::duration budget, Clock::time_point now) { - if (frame != at_frame) *this = FrameWait{at_frame}; - if (sharing == Sharing::window) { - const Clock::duration opened = open ? now - since : Clock::duration::zero(); - const Clock::duration left = std::max(Clock::duration::zero(), budget - (spent + opened)); - if (left > Clock::duration::zero()) { - if (waiting == 0) { - since = now; - open = true; - } - ++waiting; - } - return left; - } - const Clock::duration left = std::max(Clock::duration::zero(), budget - spent); - if (sharing == Sharing::reserve) spent += left; - return left; - } - - // The thread `begin` gave `left` (more than nothing) in `at_frame` has waited `waited` and stops at `now`. A frame - // that began meanwhile has its own budget. - void end(Sharing sharing, std::uint64_t at_frame, Clock::duration left, Clock::duration waited, - Clock::time_point now) { - if (frame != at_frame) return; - switch (sharing) { - case Sharing::window: - if (waiting) --waiting; - if (waiting == 0 && open) { - spent += now - since; - open = false; - } - break; - case Sharing::reserve: spent = std::max(Clock::duration::zero(), spent - (left - waited)); break; - case Sharing::per_thread: spent += waited; break; - } - } -}; - -// Whether the driver has held a pipeline longer than most take, so no frame waits for it (make.rs:225-234): 10 s for -// a compute pipeline, 3 s for others, while the frame budget is shorter than that. -inline bool held_too_long(Clock::duration held, bool compute, Clock::duration base) { - const Clock::duration most = std::chrono::seconds(compute ? 10 : 3); - return base < most && held > most; -} - -// LEONIDA_PIPELINE_GATE_S (120): the most a run waits past the frame budget for each kind while a world loads, all -// frames together (make.rs:198-211); 0 waits as the budget alone. -// Read once; set_loading_allowance overrides it (tests that measure the frame budget alone set 0). -inline std::atomic& loading_allowance_s() { - static std::atomic seconds{env_number("LEONIDA_PIPELINE_GATE_S", 120)}; - return seconds; -} -inline Clock::duration loading_allowance() { - return std::chrono::seconds(loading_allowance_s().load(std::memory_order_relaxed)); -} -inline void set_loading_allowance(std::chrono::seconds total) { loading_allowance_s().store(total.count()); } - -// A frame's budget for a pipeline of one kind (make.rs:213-219): the frame budget, or while the run's allowance for -// that kind lasts (`spent` of it gone) up to kLoadingFrameMs or kLoadingFrameComputeMs. -inline Clock::duration frame_budget(Clock::duration base, bool compute, Clock::duration allowance, - Clock::duration spent) { - const Clock::duration loading = std::chrono::milliseconds(compute ? kLoadingFrameComputeMs : kLoadingFrameMs); - const Clock::duration rest = std::max(Clock::duration::zero(), allowance - spent); - return std::max(base, std::min(loading, rest)); -} - -// ---- A pipeline to make ---------------------------------------------------------------------------------------- - -inline constexpr std::uint8_t kNotQueued = 0, kEarly = 1, kRequested = 2, kMaking = 3; - -class Builder; - -// What a pipeline state's Vulkan pipeline is made from (a function the state sets once), and whether it is made. -class Job { -public: - Job(bool compute, bool depth_only) : compute_(compute), depth_only_(depth_only) {} - Job(const Job&) = delete; - Job& operator=(const Job&) = delete; - - // The pipeline is made: what the draws and dispatches recorded with it check. - bool ready() const { return made_.load(std::memory_order_acquire); } - // The build ran, and made the pipeline or did not (refused). - bool finished() const { return finished_.load(std::memory_order_acquire); } - bool compute() const { return compute_; } - bool depth_only() const { return depth_only_; } - std::uint8_t queue_state() const { return queue_.load(std::memory_order_relaxed); } - - // Set once, before the job is started. `work` returns whether it made the pipeline. - void set_work(std::function work) { work_ = std::move(work); } - - // The pipeline state is going away: a queued build is not run, and a running one is waited for. - void retire() { - std::unique_lock lock(mutex_); - retired_ = true; - done_.wait(lock, [&] { return !running_; }); - work_ = nullptr; - } - - // Makes it on this thread unless a worker has it, then waits for that worker (make.rs `now`); whether it is made. - // The builder's counts leave such a build out. - bool run_now() { - run(); - wait_finished(); - return ready(); - } - - // Waits however long the build takes (a retired job that never ran ends the wait too). - void wait_finished() { - std::unique_lock lock(mutex_); - done_.wait(lock, [&] { return finished_.load(std::memory_order_relaxed) || (retired_ && !running_); }); - } - bool wait_finished_for(Clock::duration limit) { - std::unique_lock lock(mutex_); - return done_.wait_for(lock, limit, [&] { return finished_.load(std::memory_order_relaxed); }); - } - - // How long a worker has been at it; zero when none has begun. - Clock::duration held() const { - const std::int64_t begun = begun_.load(std::memory_order_relaxed); - if (!begun || finished()) return Clock::duration::zero(); - return Clock::now().time_since_epoch() - Clock::duration(begun); - } - - // How long the build took (zero before it finished). - Clock::duration took() const { return Clock::duration(took_.load(std::memory_order_relaxed)); } - -private: - friend class Builder; - - // Runs the build unless it ran or the job was retired; whether it ran here. - bool run() { - { - std::lock_guard lock(mutex_); - if (retired_ || claimed_) return false; - claimed_ = true; - running_ = true; - } - const Clock::time_point begun = Clock::now(); - begun_.store(begun.time_since_epoch().count(), std::memory_order_relaxed); - bool made = false; - try { - made = work_ && work_(); - } catch (...) { - made = false; // nothing may leave a worker - } - took_.store((Clock::now() - begun).count(), std::memory_order_relaxed); - std::lock_guard lock(mutex_); - running_ = false; - made_.store(made, std::memory_order_release); - finished_.store(true, std::memory_order_release); - done_.notify_all(); - return true; - } - - const bool compute_; - const bool depth_only_; - std::atomic queue_{kNotQueued}; - std::atomic made_{false}; - std::atomic finished_{false}; - std::atomic begun_{0}; - std::atomic took_{0}; - std::mutex mutex_; - std::condition_variable done_; - bool retired_ = false; - bool claimed_ = false; - bool running_ = false; - std::function work_; -}; - -// ---- Drops (pipeline.rs:461-564) --------------------------------------------------------------------------------- - -struct DropCounts { - std::uint64_t draws = 0; // a draw whose pipeline was still being made - std::uint64_t dispatches = 0; // a dispatch whose pipeline was still being made - std::uint64_t refused = 0; // either, whose pipeline could not be made -}; - -class Drops { -public: - static Drops& get() { - static Drops* drops = new Drops(); // never destroyed: see the file's notes - return *drops; - } - - // A draw or dispatch recorded with `job` (not ready) is dropped. Logged once a second, with what was dropped - // since the last line. - void note(const Job& job, bool dispatch, std::uint64_t waiting) { - if (job.finished()) refused_.fetch_add(1, std::memory_order_relaxed); - else (dispatch ? dispatches_ : draws_).fetch_add(1, std::memory_order_relaxed); - const std::int64_t now = std::chrono::duration_cast( - Clock::now().time_since_epoch()).count(); - std::int64_t last = last_ms_.load(std::memory_order_relaxed); - if (now - last < 1000 || !last_ms_.compare_exchange_strong(last, now, std::memory_order_relaxed)) return; - const DropCounts total = counts(); - std::lock_guard lock(log_mutex_); - std::fprintf(stderr, - "[rt] d3d12: pipelines: %llu draws and %llu dispatches dropped while their pipelines are made, " - "%llu whose pipelines could not be made (since the last line; %llu pipelines waiting to be " - "made)\n", - static_cast(total.draws - logged_.draws), - static_cast(total.dispatches - logged_.dispatches), - static_cast(total.refused - logged_.refused), - static_cast(waiting)); - logged_ = total; - } - - DropCounts counts() const { - return {draws_.load(std::memory_order_relaxed), dispatches_.load(std::memory_order_relaxed), - refused_.load(std::memory_order_relaxed)}; - } - -private: - std::atomic draws_{0}, dispatches_{0}, refused_{0}; - std::atomic last_ms_{0}; - std::mutex log_mutex_; - DropCounts logged_; -}; - -// ---- Pipelines earlier runs bound (library.rs:10-13, 431-438, 567-714) ------------------------------------------- - -// Keys (known at creation: a hash of the description) of the pipelines this and earlier runs bound, one per line in -// `early-pipelines.txt` beside the pipeline cache. A run starts those at creation. The file keeps what earlier runs -// listed (library.rs:613-616), at most kMax keys; it is written whole to a temporary file and renamed over the list, -// so a reader never sees a part (library.rs:676-682). -class EarlyList { -public: - static constexpr std::size_t kMax = 8192; // library.rs:437 - static constexpr std::chrono::seconds kSaveEvery{20}; // library.rs:571 - - static EarlyList& get() { - static EarlyList* list = new EarlyList(); // never destroyed: see the file's notes - return *list; - } - - // Where the list is kept (empty: nowhere). `always`: written whatever runs (a path the user or a test named); - // otherwise only for a title (waits_bounded), so the PC-interface tests leave no file beside their executables. - // The first call wins, unless `replace`. - void configure(const std::filesystem::path& file, bool always, bool replace = false) { - std::lock_guard lock(mutex_); - if (configured_ && !replace) return; - configured_ = true; - file_ = file; - always_ = always; - loaded_ = false; - keys_.clear(); - changed_ = false; - last_save_ = Clock::time_point{}; - } - - // Whether a pipeline with `key` was bound in this or an earlier run (library.rs:702-705). - bool wanted(const std::string& key) { - std::lock_guard lock(mutex_); - load_locked(); - return keys_.count(key) != 0; - } - - // A bind asked for the pipeline with `key` (library.rs:707-714). - void note_used(const std::string& key) { - if (key.empty()) return; - std::lock_guard lock(mutex_); - load_locked(); - if (keys_.size() < kMax && keys_.insert(key).second) changed_ = true; - } - - // Writes the list if it changed since the last save and kSaveEvery has passed (or `now`); whether it wrote. One save - // at a time, start to rename: a call returns after any save under way has put its file in place. - bool save(bool now) { - std::lock_guard saving(save_mutex_); - std::vector keys; - std::filesystem::path file; - { - std::lock_guard lock(mutex_); - if (!changed_ || file_.empty() || (!always_ && !waits_bounded())) return false; - const Clock::time_point at = Clock::now(); - if (!now && last_save_ != Clock::time_point{} && at - last_save_ < kSaveEvery) return false; - last_save_ = at; - changed_ = false; - keys.assign(keys_.begin(), keys_.end()); - file = file_; - } - std::sort(keys.begin(), keys.end()); - std::string text; - for (const std::string& key : keys) text += key + "\n"; - std::error_code ec; - std::filesystem::path tmp = file; - tmp += ".tmp"; - { - std::ofstream out(tmp, std::ios::binary | std::ios::trunc); - out.write(text.data(), std::streamsize(text.size())); - if (!out) { - std::fprintf(stderr, "[rt] d3d12: pipelines: the early list could not be written\n"); - std::lock_guard lock(mutex_); - changed_ = true; - return false; - } - } - std::filesystem::rename(tmp, file, ec); - if (ec) { - std::filesystem::remove(tmp, ec); - std::lock_guard lock(mutex_); - changed_ = true; - return false; - } - saves_.fetch_add(1, std::memory_order_relaxed); - return true; - } - - std::size_t size() { - std::lock_guard lock(mutex_); - load_locked(); - return keys_.size(); - } - std::uint64_t saves() const { return saves_.load(std::memory_order_relaxed); } - - // Reads the file again, as the next run would (tests). - void reload() { - std::lock_guard lock(mutex_); - loaded_ = false; - keys_.clear(); - changed_ = false; - load_locked(); - } - -private: - void load_locked() { - if (loaded_) return; - loaded_ = true; - if (file_.empty()) return; - std::ifstream in(file_, std::ios::binary); - std::string line; - while (in && std::getline(in, line) && keys_.size() < kMax) { - if (!line.empty() && line.back() == '\r') line.pop_back(); - if (!line.empty()) keys_.insert(line); - } - if (!keys_.empty()) - std::fprintf(stderr, "[rt] d3d12: pipelines: %zu pipelines earlier runs bound are started at creation\n", - keys_.size()); - } - - std::mutex mutex_; - std::mutex save_mutex_; // held through a whole save; taken before mutex_ - std::filesystem::path file_; - bool configured_ = false; - bool always_ = false; - bool loaded_ = false; - bool changed_ = false; - Clock::time_point last_save_{}; - std::unordered_set keys_; - std::atomic saves_{0}; -}; - -// ---- The builder (make.rs:440-580) --------------------------------------------------------------------------------- - -struct BuilderStats { - std::uint64_t made = 0; // pipelines made - std::uint64_t refused = 0; // builds that made none - std::uint64_t started_early = 0; // started at creation from the early list - std::uint64_t waiting = 0; // queued and not made yet - std::uint64_t waited_us = 0; // waiting at binds in all -}; - -class Builder { -public: - static Builder& get() { - static Builder* builder = new Builder(); // never destroyed: see the file's notes - return *builder; - } - - // Starts `job` (kEarly at creation, kRequested at a bind), or promotes one queued early (make.rs `start`). - void start(const std::shared_ptr& job, std::uint8_t priority) { - if (job->queue_.load(std::memory_order_relaxed) >= priority) return; - if (!workers()) { - if (job->queue_.exchange(kMaking, std::memory_order_relaxed) == kNotQueued && job->run()) count(*job); - return; - } - std::lock_guard lock(mutex_); - const std::uint8_t previous = job->queue_.load(std::memory_order_relaxed); - if (previous >= priority) return; - job->queue_.store(priority, std::memory_order_relaxed); - if (priority == kRequested) requested_.push_back(job); - else if (job->depth_only()) early_depth_.push_back(job); // shadow maps and depth prepasses feed later draws - else early_.push_back(job); - if (previous == kNotQueued) { - if (priority == kEarly) started_early_.fetch_add(1, std::memory_order_relaxed); - peak_ = std::max(peak_, ++waiting_); - } - available_.notify_one(); - } - - // At a bind of a pipeline `start` was given: waits for it while the current frame's budget lasts (make.rs `wait`), - // or without a limit where waits are not bounded (waits_bounded). Whether it is made. - bool wait(Job& job) { - if (job.finished()) return job.ready(); - const std::uint64_t frame = current_frame(); - const Clock::time_point started = Clock::now(); - if (!waits_bounded()) { - job.wait_finished(); - add_wait(Clock::now() - started); - return job.ready(); - } - const Clock::duration base = wait_budget(); - if (base <= Clock::duration::zero() || held_too_long(job.held(), job.compute(), base)) return job.ready(); - const Sharing sharing = shared_budget(); - const int kind = job.compute() ? 1 : 0; - FrameWait& frame_wait = frames_[kind]; - Clock::duration left; - { - std::lock_guard lock(frames_mutex_); - const Clock::duration budget = frame_budget(base, kind == 1, loading_allowance(), loading_spent_[kind]); - left = frame_wait.begin(sharing, frame, budget, started); - } - if (left <= Clock::duration::zero()) return job.ready(); - { - std::unique_lock lock(job.mutex_); - while (!job.finished_.load(std::memory_order_relaxed) && !job.retired_ && - !held_too_long(job.held(), job.compute(), base)) { - const Clock::duration rest = left - (Clock::now() - started); - if (rest <= Clock::duration::zero()) break; - // Woken now and then to see whether it has become a slow one. - job.done_.wait_for(lock, std::min(rest, std::chrono::milliseconds(250))); - } - } - const Clock::time_point ended = Clock::now(); - const Clock::duration waited = std::min(ended - started, left); - { - std::lock_guard lock(frames_mutex_); - frame_wait.end(sharing, frame, left, waited, ended); - // What the frame budget alone would not have allowed counts against the loading allowance. - if (waited > base) loading_spent_[kind] += waited - base; - } - add_wait(waited); - return job.ready(); - } - - BuilderStats stats() const { - std::lock_guard lock(mutex_); - return {made_.load(std::memory_order_relaxed), refused_.load(std::memory_order_relaxed), - started_early_.load(std::memory_order_relaxed), waiting_, - waited_us_.load(std::memory_order_relaxed)}; - } - std::uint64_t waiting() const { - std::lock_guard lock(mutex_); - return waiting_; - } - - // Tests: while held, workers take no job (queued ones wait), so a test can see draws dropped deterministically. - void hold(bool held) { - std::lock_guard lock(mutex_); - held_ = held; - if (!held_) available_.notify_all(); - } - -private: - Builder() = default; - - void add_wait(Clock::duration waited) { - waited_us_.fetch_add(std::uint64_t(std::chrono::duration_cast(waited).count()), - std::memory_order_relaxed); - } - - void count(const Job& job) { - (job.ready() ? made_ : refused_).fetch_add(1, std::memory_order_relaxed); - const auto took = job.took(); - if (took > std::chrono::seconds(10)) - std::fprintf(stderr, "[rt] d3d12: pipelines: one %s pipeline took %.1f s to make\n", - job.compute() ? "compute" : "graphics", std::chrono::duration(took).count()); - } - - // Starts the workers on first use; false when none could be started (or LEONIDA_PIPELINE_WORKERS=0). - bool workers() { - std::call_once(workers_once_, [this] { - const unsigned count = worker_count(); - unsigned started = 0; - for (unsigned i = 0; i < count; ++i) { - try { - std::thread([this, i] { loop(i); }).detach(); - ++started; - } catch (const std::exception&) { - break; - } - } - running_ = started > 0; - std::fprintf(stderr, - "[rt] d3d12: pipelines: made on %u threads; a bind waits up to %lld ms per frame and kind " - "(LEONIDA_PIPELINE_WAIT_MS) once the frame clock runs\n", - started, static_cast(wait_budget_ms().load())); - }); - return running_; - } - - void loop(unsigned index) { - (void)index; -#ifdef _WIN32 - // Below the title's own threads (loading, recording), as make.rs:538-543. - SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); -#endif - for (;;) { - std::shared_ptr job = next(); - if (job->run()) count(*job); - job.reset(); - bool drained = false; - std::uint64_t peak = 0; - { - std::lock_guard lock(mutex_); - if (waiting_) --waiting_; - if (waiting_ == 0) { - drained = true; - peak = peak_; - peak_ = 0; - } - } - if (drained && peak >= 10) { - const BuilderStats s = stats(); - std::fprintf(stderr, - "[rt] d3d12: pipelines: all made (%llu made, %llu could not be made, %llu started early; " - "%.1f s waited for at binds in all)\n", - static_cast(s.made), static_cast(s.refused), - static_cast(s.started_early), double(s.waited_us) / 1e6); - } - EarlyList::get().save(drained); - } - } - - std::shared_ptr next() { - std::unique_lock lock(mutex_); - for (;;) { - if (!held_) { - if (std::shared_ptr job = pop()) return job; - } - available_.wait(lock); - } - } - - std::shared_ptr pop() { - std::shared_ptr job; - if (!requested_.empty()) { - job = std::move(requested_.front()); - requested_.pop_front(); - } else { - // An early entry can have been promoted and claimed already. - for (auto* queue : {&early_depth_, &early_}) { - while (!job && !queue->empty()) { - std::shared_ptr front = std::move(queue->front()); - queue->pop_front(); - if (front->queue_.load(std::memory_order_relaxed) == kEarly) job = std::move(front); - } - if (job) break; - } - if (!job) return nullptr; - } - job->queue_.store(kMaking, std::memory_order_relaxed); - return job; - } - - mutable std::mutex mutex_; - std::condition_variable available_; - std::deque> requested_, early_depth_, early_; - std::uint64_t waiting_ = 0; - std::uint64_t peak_ = 0; - bool held_ = false; - std::once_flag workers_once_; - bool running_ = false; - std::atomic made_{0}, refused_{0}, started_early_{0}, waited_us_{0}; - std::mutex frames_mutex_; - FrameWait frames_[2]; // graphics, compute - Clock::duration loading_spent_[2]{}; // waiting past the frame budget, per kind (loading_allowance) -}; - -} // namespace leonida::pipelines diff --git a/runtime/src/png_write.h b/runtime/src/png_write.h deleted file mode 100644 index bf9e9e06e..000000000 --- a/runtime/src/png_write.h +++ /dev/null @@ -1,257 +0,0 @@ -#pragma once - -// PNG files for the presented-frame screenshots (shims/xbox_window.cpp, LEONIDA_CAPTURE_DIR): 8-bit RGB, one IDAT -// chunk, a zlib stream (RFC 1950) of one deflate block (RFC 1951) with the fixed Huffman codes and greedy LZ77 -// matches over a 32 KiB window. Each row gets the PNG filter (None, Sub, Up or Paeth) whose output has the smallest sum -// of absolute values, the usual heuristic. No third-party code and no Windows headers; the round trip is checked -// against leonida::zlib_inflate (src/shader_library.h) by png_write_test. -// -// VIctory (GPL-3.0-or-later, Marvisak and contributors, DexNom fork; victory/crates/victory-gpu/src/capture.rs -// `save_as`, `chunk`, `crc32`) writes its frames as 8-bit RGB PNGs with the same chunk layout and CRC; it compresses -// with zlib-rs and halves the frame. This writer keeps the full size (a check reads the presented pixels) and carries -// its own deflate. - -#include -#include -#include -#include -#include -#include -#include - -namespace leonida::png { - -// CRC-32 (ISO 3309, the one PNG chunks carry), continued from `crc` (0 to start). -inline std::uint32_t crc32(std::span bytes, std::uint32_t crc = 0) { - static const std::array table = [] { - std::array t{}; - for (std::uint32_t n = 0; n < 256; ++n) { - std::uint32_t c = n; - for (int k = 0; k < 8; ++k) c = (c & 1) ? 0xedb88320u ^ (c >> 1) : c >> 1; - t[n] = c; - } - return t; - }(); - crc = ~crc; - for (const std::uint8_t b : bytes) crc = table[(crc ^ b) & 0xff] ^ (crc >> 8); - return ~crc; -} - -inline std::uint32_t adler32(std::span bytes) { - std::uint32_t a = 1, b = 0; - std::size_t at = 0; - while (at < bytes.size()) { - const std::size_t run = std::min(bytes.size() - at, 5552); // no overflow before the modulo - for (std::size_t i = 0; i < run; ++i) { - a += bytes[at + i]; - b += a; - } - a %= 65521u; - b %= 65521u; - at += run; - } - return (b << 16) | a; -} - -namespace detail { - -class BitWriter { -public: - explicit BitWriter(std::vector& out) : out_(out) {} - // `count` bits of `value`, least significant first (deflate's order for everything but Huffman codes). - void bits(std::uint32_t value, unsigned count) { - held_ |= std::uint64_t(value) << used_; - used_ += count; - while (used_ >= 8) { - out_.push_back(std::uint8_t(held_)); - held_ >>= 8; - used_ -= 8; - } - } - // A Huffman code of `length` bits, most significant bit first. - void code(std::uint32_t code, unsigned length) { - std::uint32_t reversed = 0; - for (unsigned i = 0; i < length; ++i) reversed |= ((code >> i) & 1u) << (length - 1 - i); - bits(reversed, length); - } - void flush() { - if (used_) out_.push_back(std::uint8_t(held_)); - held_ = 0; - used_ = 0; - } - -private: - std::vector& out_; - std::uint64_t held_ = 0; - unsigned used_ = 0; -}; - -// The fixed literal/length code (RFC 1951 3.2.6). -inline void literal(BitWriter& w, unsigned symbol) { - if (symbol < 144) w.code(0x30 + symbol, 8); - else if (symbol < 256) w.code(0x190 + (symbol - 144), 9); - else if (symbol < 280) w.code(symbol - 256, 7); - else w.code(0xc0 + (symbol - 280), 8); -} - -inline constexpr std::uint16_t length_base[29] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, - 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258}; -inline constexpr std::uint8_t length_extra[29] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, - 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0}; -inline constexpr std::uint16_t distance_base[30] = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, - 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, - 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577}; -inline constexpr std::uint8_t distance_extra[30] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, - 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; - -inline void match(BitWriter& w, unsigned length, unsigned distance) { - unsigned l = 28; - while (length_base[l] > length) --l; - literal(w, 257 + l); - if (length_extra[l]) w.bits(length - length_base[l], length_extra[l]); - unsigned d = 29; - while (distance_base[d] > distance) --d; - w.code(d, 5); - if (distance_extra[d]) w.bits(distance - distance_base[d], distance_extra[d]); -} - -} // namespace detail - -// Raw deflate data (one final block, fixed Huffman codes) for `in`, appended to `out`. `chain` is how many earlier -// positions with the same three bytes are tried for a match (more: smaller and slower). -inline void deflate_fixed(std::span in, std::vector& out, unsigned chain = 16) { - constexpr std::size_t window = 32768, min_match = 3, max_match = 258; - constexpr unsigned hash_bits = 15; - detail::BitWriter w(out); - w.bits(1, 1); // BFINAL - w.bits(1, 2); // BTYPE 01: fixed Huffman codes - std::vector head(std::size_t(1) << hash_bits, 0); // position + 1 of the newest with this hash - std::vector previous(window, 0); // the one before it, by position % window - const std::size_t n = in.size(); - const auto hash = [&](std::size_t at) { - const std::uint32_t v = std::uint32_t(in[at]) | std::uint32_t(in[at + 1]) << 8 | std::uint32_t(in[at + 2]) << 16; - return (v * 2654435761u) >> (32 - hash_bits); - }; - const auto insert = [&](std::size_t at) { - const std::uint32_t h = hash(at); - previous[at % window] = head[h]; - head[h] = std::uint32_t(at + 1); - }; - std::size_t at = 0; - while (at < n) { - std::size_t best_length = 0, best_distance = 0; - if (at + min_match <= n) { - const std::size_t limit = std::min(max_match, n - at); - std::uint32_t candidate = head[hash(at)]; - for (unsigned tries = 0; candidate && tries < chain; ++tries) { - const std::size_t from = candidate - 1; - if (at - from > window - 1) break; // deflate's distances stop at 32768; keep one back for safety - if (in[from + best_length] == in[at + best_length]) { - std::size_t length = 0; - while (length < limit && in[from + length] == in[at + length]) ++length; - if (length > best_length) { - best_length = length; - best_distance = at - from; - if (length == limit) break; - } - } - const std::uint32_t next = previous[from % window]; - if (next >= candidate) break; // the slot was reused by a newer position: the chain ends here - candidate = next; - } - } - if (best_length >= min_match) { - detail::match(w, unsigned(best_length), unsigned(best_distance)); - for (std::size_t i = 0; i < best_length; ++i) - if (at + i + min_match <= n) insert(at + i); - at += best_length; - } else { - detail::literal(w, in[at]); - if (at + min_match <= n) insert(at); - ++at; - } - } - detail::literal(w, 256); // end of block - w.flush(); -} - -// A zlib stream (RFC 1950) of `in`. -inline std::vector zlib_compress(std::span in) { - std::vector out{0x78, 0x01}; // deflate, 32 KiB window, no dictionary; (0x7801 % 31) == 0 - out.reserve(in.size() / 2 + 64); - deflate_fixed(in, out); - const std::uint32_t adler = adler32(in); - for (int shift = 24; shift >= 0; shift -= 8) out.push_back(std::uint8_t(adler >> shift)); - return out; -} - -namespace detail { - -inline std::uint8_t paeth(std::uint8_t a, std::uint8_t b, std::uint8_t c) { - const int p = int(a) + int(b) - int(c); - const int pa = std::abs(p - int(a)), pb = std::abs(p - int(b)), pc = std::abs(p - int(c)); - return pa <= pb && pa <= pc ? a : pb <= pc ? b : c; -} - -inline void put_chunk(std::vector& png, const char (&kind)[5], std::span data) { - const std::uint32_t length = std::uint32_t(data.size()); - for (int shift = 24; shift >= 0; shift -= 8) png.push_back(std::uint8_t(length >> shift)); - const std::size_t start = png.size(); - png.insert(png.end(), kind, kind + 4); - png.insert(png.end(), data.begin(), data.end()); - const std::uint32_t crc = crc32(std::span(png.data() + start, png.size() - start)); - for (int shift = 24; shift >= 0; shift -= 8) png.push_back(std::uint8_t(crc >> shift)); -} - -} // namespace detail - -// A PNG of 8-bit RGB pixels: `height` rows of `width * 3` bytes, `pitch` bytes apart. Empty for a zero size. -inline std::vector encode_rgb8(std::uint32_t width, std::uint32_t height, const std::uint8_t* rgb, - std::size_t pitch) { - if (!width || !height || !rgb) return {}; - const std::size_t row = std::size_t(width) * 3; - std::vector filtered; - filtered.reserve((row + 1) * height); - std::array, 4> candidates; // None, Sub, Up and Paeth (Average is not tried) - for (auto& c : candidates) c.resize(row); - for (std::uint32_t y = 0; y < height; ++y) { - const std::uint8_t* line = rgb + std::size_t(y) * pitch; - const std::uint8_t* above = y ? rgb + std::size_t(y - 1) * pitch : nullptr; - for (std::size_t i = 0; i < row; ++i) { - const std::uint8_t left = i >= 3 ? line[i - 3] : 0; - const std::uint8_t up = above ? above[i] : 0; - const std::uint8_t corner = above && i >= 3 ? above[i - 3] : 0; - candidates[0][i] = line[i]; - candidates[1][i] = std::uint8_t(line[i] - left); - candidates[2][i] = std::uint8_t(line[i] - up); - candidates[3][i] = std::uint8_t(line[i] - detail::paeth(left, up, corner)); - } - static constexpr std::uint8_t type[4] = {0, 1, 2, 4}; - std::size_t best = 0; - std::uint64_t best_sum = ~std::uint64_t(0); - for (std::size_t c = 0; c < 4; ++c) { - std::uint64_t sum = 0; - for (const std::uint8_t v : candidates[c]) sum += v < 128 ? v : 256 - v; - if (sum < best_sum) { - best_sum = sum; - best = c; - } - } - filtered.push_back(type[best]); - filtered.insert(filtered.end(), candidates[best].begin(), candidates[best].end()); - } - std::vector png{0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'}; - std::uint8_t header[13] = {}; - for (int i = 0; i < 4; ++i) { - header[i] = std::uint8_t(width >> (24 - 8 * i)); - header[4 + i] = std::uint8_t(height >> (24 - 8 * i)); - } - header[8] = 8; // bits per channel - header[9] = 2; // colour type 2: RGB - detail::put_chunk(png, "IHDR", header); - detail::put_chunk(png, "IDAT", zlib_compress(filtered)); - detail::put_chunk(png, "IEND", {}); - return png; -} - -} // namespace leonida::png diff --git a/runtime/src/rect_list_gs.cpp b/runtime/src/rect_list_gs.cpp deleted file mode 100644 index 9394aa0b1..000000000 --- a/runtime/src/rect_list_gs.cpp +++ /dev/null @@ -1,691 +0,0 @@ -// The rectangle-list geometry stage (rect_list_gs.h). Ported from VIctory (GPL-3.0-or-later, Marvisak and -// contributors, DexNom fork; victory/crates/victory-shader/src/emit/rect.rs); Leonida is GPL-3.0-or-later too. -#include "rect_list_gs.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace leonida::rect_list { -namespace { - -constexpr std::uint32_t kMagic = 0x07230203u; -constexpr std::uint32_t kMaxScalarsPerVertex = 128; // maxGeometryOutputComponents on the GPUs the layer targets -constexpr std::uint32_t kMaxScalars = 1024; // maxGeometryTotalOutputComponents' required minimum - -namespace op { -enum : std::uint32_t { - memory_model = 14, entry_point = 15, execution_mode = 16, capability = 17, type_void = 19, type_bool = 20, - type_int = 21, type_float = 22, type_vector = 23, type_array = 28, type_struct = 30, type_pointer = 32, - type_function = 33, constant = 43, function = 54, function_end = 56, variable = 59, load = 61, store = 62, - access_chain = 65, decorate = 71, member_decorate = 72, composite_construct = 80, composite_extract = 81, - bitcast = 124, f_add = 129, f_sub = 131, logical_or = 166, logical_and = 167, logical_not = 168, select = 169, - i_equal = 170, f_ord_equal = 180, f_ord_greater_than = 186, emit_vertex = 218, end_primitive = 219, label = 248, - return_ = 253, -}; -} // namespace op -enum : std::uint32_t { cap_shader = 1, cap_geometry = 2, cap_clip_distance = 32, cap_cull_distance = 33 }; -enum : std::uint32_t { model_vertex = 0, model_geometry = 3 }; -enum : std::uint32_t { - mode_invocations = 0, mode_triangles = 22, mode_output_vertices = 26, mode_output_triangle_strip = 29, -}; -enum : std::uint32_t { storage_input = 1, storage_output = 3 }; -enum : std::uint32_t { deco_block = 2, deco_builtin = 11, deco_location = 30, deco_component = 31 }; -enum : std::uint32_t { - builtin_position = 0, builtin_point_size = 1, builtin_clip_distance = 3, builtin_cull_distance = 4, - builtin_primitive_id = 7, builtin_layer = 9, builtin_viewport_index = 10, -}; - -const char* builtin_name(std::uint32_t b) { - switch (b) { - case builtin_position: return "Position"; - case builtin_point_size: return "PointSize"; - case builtin_clip_distance: return "ClipDistance"; - case builtin_cull_distance: return "CullDistance"; - case builtin_layer: return "Layer"; - case builtin_viewport_index: return "ViewportIndex"; - default: return nullptr; - } -} - -// ---- Reading the vertex shader's interface ---- - -struct Type { - std::uint32_t op = 0; - std::uint32_t a = 0, b = 0; // float: width; int: width, signedness; vector: component, count; - // array: element, length id; pointer: storage, pointee - std::vector members; // struct -}; - -struct Decorations { - std::uint32_t builtin = Output::kNoBuiltin; - bool has_location = false; - std::uint32_t location = 0, component = 0; -}; - -class Interface { -public: - bool read(const std::vector& w, std::string& why) { - if (w.size() < 5 || w[0] != kMagic) return fail(why, "not a SPIR-V module"); - bool entry = false; - for (std::size_t at = 5; at < w.size();) { - const std::uint32_t count = w[at] >> 16, code = w[at] & 0xffffu; - if (!count || at + count > w.size()) return fail(why, "a truncated instruction"); - const std::uint32_t* o = &w[at + 1]; // operands - const std::uint32_t n = count - 1; - switch (code) { - case op::capability: - if (n >= 1 && o[0] == cap_clip_distance) clip_capability = true; - if (n >= 1 && o[0] == cap_cull_distance) cull_capability = true; - break; - case op::entry_point: - if (n >= 2 && o[0] == model_vertex && !entry) { - entry = true; - std::uint32_t i = 2; - while (i < n) { // the name: a nul-terminated string - const std::uint32_t word = o[i++]; - if (!(word & 0xff000000u) || !(word & 0xff0000u) || !(word & 0xff00u) || !(word & 0xffu)) break; - } - interface.assign(o + i, o + n); - } - break; - case op::decorate: - if (n >= 3 && o[1] == deco_builtin) decorations[o[0]].builtin = o[2]; - if (n >= 3 && o[1] == deco_location) { - decorations[o[0]].has_location = true; - decorations[o[0]].location = o[2]; - } - if (n >= 3 && o[1] == deco_component) decorations[o[0]].component = o[2]; - break; - case op::member_decorate: - if (n >= 4 && o[2] == deco_builtin) member_builtins[o[0]][o[1]] = o[3]; - if (n >= 3 && (o[2] == deco_location || o[2] == deco_component)) located_members.insert(o[0]); - break; - case op::type_float: - if (n >= 2) types[o[0]] = {code, o[1], 0, {}}; - break; - case op::type_int: - if (n >= 3) types[o[0]] = {code, o[1], o[2], {}}; - break; - case op::type_vector: - case op::type_array: - case op::type_pointer: - if (n >= 3) types[o[0]] = {code, o[1], o[2], {}}; - break; - case op::type_struct: - if (n >= 1) types[o[0]] = {code, 0, 0, std::vector(o + 1, o + n)}; - break; - case op::constant: - if (n >= 3) constants[o[1]] = o[2]; - break; - case op::variable: - if (n >= 3) variables[o[1]] = {o[0], o[2]}; - break; - default: break; - } - at += count; - } - if (!entry) return fail(why, "no vertex entry point"); - return true; - } - - // A 32-bit scalar or vector: its kind and size. - bool scalar_or_vector(std::uint32_t id, Kind& kind, std::uint32_t& count) const { - const Type* t = find(id); - count = 1; - if (t && t->op == op::type_vector) { - count = t->b; - t = find(t->a); - if (count < 2 || count > 4) return false; - } - if (!t || t->a != 32) return false; - if (t->op == op::type_float) kind = Kind::f32; - else if (t->op == op::type_int) kind = t->b ? Kind::i32 : Kind::u32; - else return false; - return true; - } - // An array of 32-bit floats with a constant length. - bool float_array(std::uint32_t id, std::uint32_t& length) const { - const Type* t = find(id); - if (!t || t->op != op::type_array) return false; - Kind kind; - std::uint32_t count; - const auto c = constants.find(t->b); - if (!scalar_or_vector(t->a, kind, count) || kind != Kind::f32 || count != 1 || c == constants.end()) - return false; - length = c->second; - return length >= 1 && length <= 8; - } - const Type* find(std::uint32_t id) const { - const auto t = types.find(id); - return t == types.end() ? nullptr : &t->second; - } - - bool clip_capability = false, cull_capability = false; - std::vector interface; - std::unordered_map decorations; - std::unordered_map> member_builtins; // struct -> member -> b - std::set located_members; - std::unordered_map types; - std::unordered_map constants; // id -> first word - std::unordered_map> variables; // id -> type, storage - -private: - static bool fail(std::string& why, const char* what) { - why = what; - return false; - } -}; - -// A built-in output of the vertex shader (alone or a block member) as the stage declares it. -bool builtin_output(const Interface& in, std::uint32_t builtin, std::uint32_t type, Output& out, std::string& why) { - out = {}; - out.builtin = builtin; - const char* name = builtin_name(builtin); - if (builtin == builtin_layer || builtin == builtin_viewport_index) { - why = std::string("the vertex shader writes ") + name + ", which a geometry stage cannot read"; - return false; - } - if (!name) { - why = "the vertex shader writes built-in " + std::to_string(builtin); - return false; - } - Kind kind; - std::uint32_t count = 0; - const bool not_array = builtin == builtin_position || builtin == builtin_point_size; - const bool ok = not_array ? in.scalar_or_vector(type, kind, count) && kind == Kind::f32 && - count == (builtin == builtin_position ? 4u : 1u) - : in.float_array(type, out.array); - if (!ok) { - why = std::string("the vertex shader's ") + name + " has an unexpected type"; - return false; - } - out.count = builtin == builtin_position ? 4 : 1; - return true; -} - -// ---- Writing the geometry shader ---- - -class Builder { -public: - std::uint32_t id() { return next_++; } - static void put(std::vector& to, std::uint32_t code, std::initializer_list operands) { - to.push_back(std::uint32_t(operands.size() + 1) << 16 | code); - to.insert(to.end(), operands.begin(), operands.end()); - } - static void put(std::vector& to, std::uint32_t code, const std::vector& operands) { - to.push_back(std::uint32_t(operands.size() + 1) << 16 | code); - to.insert(to.end(), operands.begin(), operands.end()); - } - // A type or constant declared once: `operands` follow its result id. - std::uint32_t global(std::uint32_t code, std::vector operands, bool result_type_first = false) { - const auto key = std::make_pair(code, operands); - if (const auto found = declared_.find(key); found != declared_.end()) return found->second; - const std::uint32_t result = id(); - operands.insert(operands.begin() + (result_type_first ? 1 : 0), result); - put(globals, code, operands); - declared_.emplace(key, result); - return result; - } - // A value instruction in the function: `type`, a fresh result id, then `operands`. - std::uint32_t value(std::uint32_t code, std::uint32_t type, std::initializer_list operands) { - const std::uint32_t result = id(); - std::vector all{type, result}; - all.insert(all.end(), operands.begin(), operands.end()); - put(body, code, all); - return result; - } - std::uint32_t value(std::uint32_t code, std::uint32_t type, const std::vector& operands) { - const std::uint32_t result = id(); - std::vector all{type, result}; - all.insert(all.end(), operands.begin(), operands.end()); - put(body, code, all); - return result; - } - - std::uint32_t t_void() { return global(op::type_void, {}); } - std::uint32_t t_bool() { return global(op::type_bool, {}); } - std::uint32_t t_f32() { return global(op::type_float, {32}); } - std::uint32_t t_i32() { return global(op::type_int, {32, 1}); } - std::uint32_t t_u32() { return global(op::type_int, {32, 0}); } - std::uint32_t t_scalar(Kind k) { return k == Kind::f32 ? t_f32() : k == Kind::i32 ? t_i32() : t_u32(); } - std::uint32_t t_vector(std::uint32_t scalar, std::uint32_t count) { - return count == 1 ? scalar : global(op::type_vector, {scalar, count}); - } - std::uint32_t t_array(std::uint32_t element, std::uint32_t length) { - return global(op::type_array, {element, c_u32(length)}); - } - std::uint32_t t_pointer(std::uint32_t storage, std::uint32_t pointee) { - return global(op::type_pointer, {storage, pointee}); - } - std::uint32_t c_u32(std::uint32_t v) { return global(op::constant, {t_u32(), v}, true); } - std::uint32_t c_i32(std::uint32_t v) { return global(op::constant, {t_i32(), v}, true); } - std::uint32_t c_f32(float f) { - std::uint32_t bits; - std::memcpy(&bits, &f, 4); - return global(op::constant, {t_f32(), bits}, true); - } - // A struct type is declared every time: the input and output blocks are two types, as glslang has them. - std::uint32_t t_struct(const std::vector& members) { - const std::uint32_t result = id(); - std::vector operands{result}; - operands.insert(operands.end(), members.begin(), members.end()); - put(globals, op::type_struct, operands); - return result; - } - std::uint32_t variable(std::uint32_t pointer, std::uint32_t storage) { - const std::uint32_t result = id(); - put(globals, op::variable, {pointer, result, storage}); - interface.push_back(result); - return result; - } - - std::uint32_t bound() const { return next_; } - - std::vector decorations, globals, body, interface; - -private: - std::uint32_t next_ = 1; - std::map>, std::uint32_t> declared_; -}; - -// One value copied from each input vertex to each emitted one: a whole Location output or Position, or one element -// of a clip or cull distance array. -struct Slot { - std::uint32_t in = 0, out = 0; // variables - std::vector path; // constant indices after the vertex (input) / from the variable (output) - Kind kind = Kind::f32; - std::uint32_t count = 1; - bool position = false; -}; - -} // namespace - -std::string Signature::key() const { - std::string k; - const auto kind = [](Kind x) { return x == Kind::f32 ? 'f' : x == Kind::i32 ? 'i' : 'u'; }; - for (const Output& o : locations) - k += "L" + std::to_string(o.location) + "." + std::to_string(o.component) + kind(o.kind) + - std::to_string(o.count) + ";"; - k += block ? "B:" : "V:"; - for (const Output& o : builtins) k += std::to_string(o.builtin) + "x" + std::to_string(o.array) + ","; - k += clip ? ";clip" : ";"; - k += cull ? ";cull" : ";"; - return k; -} - -bool read_signature(const std::vector& vs, Signature& out, std::string& why) { - out = {}; - Interface in; - if (!in.read(vs, why)) return false; - bool position = false; - bool separate = false; - for (const std::uint32_t var : in.interface) { - const auto v = in.variables.find(var); - if (v == in.variables.end() || v->second.second != storage_output) continue; - const Type* pointer = in.find(v->second.first); - if (!pointer || pointer->op != op::type_pointer) { - why = "an output variable without a pointer type"; - return false; - } - const std::uint32_t type = pointer->b; - const auto deco = in.decorations.find(var); - const Decorations d = deco == in.decorations.end() ? Decorations{} : deco->second; - const Type* t = in.find(type); - if (d.builtin != Output::kNoBuiltin) { // a built-in variable - Output o; - if (!builtin_output(in, d.builtin, type, o, why)) return false; - if (out.block) { - why = "the vertex shader declares built-ins both in a block and alone"; - return false; - } - separate = true; - position |= o.builtin == builtin_position; - if (o.builtin != builtin_point_size) out.builtins.push_back(o); // a triangle has no point size - } else if (t && t->op == op::type_struct && in.member_builtins.count(type)) { // gl_PerVertex - if (out.block || separate) { - why = "the vertex shader declares more than one built-in output block"; - return false; - } - const auto& members = in.member_builtins.at(type); - for (std::uint32_t m = 0; m < t->members.size(); ++m) { - const auto b = members.find(m); - if (b == members.end()) { - why = "the vertex shader's built-in block has a member that is not a built-in"; - return false; - } - Output o; - if (!builtin_output(in, b->second, t->members[m], o, why)) return false; - position |= o.builtin == builtin_position; - out.builtins.push_back(o); - } - out.block = true; - } else if (d.has_location) { - Output o; - o.location = d.location; - o.component = d.component; - if (!in.scalar_or_vector(type, o.kind, o.count)) { - why = "the output at location " + std::to_string(d.location) + - " is not a 32-bit scalar or vector (an array, a struct or another width)"; - return false; - } - out.locations.push_back(o); - } else { - why = t && t->op == op::type_struct && in.located_members.count(type) - ? "the vertex shader has an output block with locations" - : "an output without a location or a built-in"; - return false; - } - } - if (!position) { - why = "the vertex shader writes no Position"; - return false; - } - for (const Output& o : out.builtins) { - out.clip |= o.builtin == builtin_clip_distance && in.clip_capability; - out.cull |= o.builtin == builtin_cull_distance && in.cull_capability; - } - if (!out.block) { // alone, a built-in the vertex shader does not write is not declared either - out.builtins.erase(std::remove_if(out.builtins.begin(), out.builtins.end(), - [&](const Output& o) { - return (o.builtin == builtin_clip_distance && !out.clip) || - (o.builtin == builtin_cull_distance && !out.cull); - }), - out.builtins.end()); - std::stable_sort(out.builtins.begin(), out.builtins.end(), - [](const Output& a, const Output& b) { return a.builtin < b.builtin; }); - } - std::stable_sort(out.locations.begin(), out.locations.end(), [](const Output& a, const Output& b) { - return std::make_pair(a.location, a.component) < std::make_pair(b.location, b.component); - }); - return true; -} - -std::vector build(const Signature& s, std::string& why) { - std::uint32_t scalars = 1; // the primitive ID - for (const Output& o : s.locations) scalars += o.count; - std::uint32_t user = scalars - 1; - for (const Output& o : s.builtins) { - if (o.builtin == builtin_position) scalars += 4; - if ((o.builtin == builtin_clip_distance && s.clip) || (o.builtin == builtin_cull_distance && s.cull)) - scalars += o.array; - } - if (user > kMaxScalarsPerVertex || scalars * kVertices > kMaxScalars) { - why = "the vertex shader has more output components (" + std::to_string(user) + - ") than a geometry stage emits in six vertices"; - return {}; - } - - Builder b; - const std::uint32_t t_void = b.t_void(), t_bool = b.t_bool(), t_f32 = b.t_f32(), t_i32 = b.t_i32(); - const std::uint32_t t_fn = b.global(op::type_function, {t_void}); - std::vector slots; - const auto decorate = [&](std::uint32_t target, std::initializer_list words) { - std::vector operands{target}; - operands.insert(operands.end(), words.begin(), words.end()); - Builder::put(b.decorations, op::decorate, operands); - }; - // A variable pair: an array of three `type` in, one `type` out. - const auto pair = [&](std::uint32_t type) { - const std::uint32_t in = b.variable(b.t_pointer(storage_input, b.t_array(type, 3)), storage_input); - const std::uint32_t out = b.variable(b.t_pointer(storage_output, type), storage_output); - return std::make_pair(in, out); - }; - - for (const Output& o : s.locations) { - const auto [in, out] = pair(b.t_vector(b.t_scalar(o.kind), o.count)); - for (const std::uint32_t v : {in, out}) { - decorate(v, {deco_location, o.location}); - if (o.component) decorate(v, {deco_component, o.component}); - } - slots.push_back({in, out, {}, o.kind, o.count, false}); - } - const auto copied = [&](const Output& o) { - return o.builtin == builtin_position || (o.builtin == builtin_clip_distance && s.clip) || - (o.builtin == builtin_cull_distance && s.cull); - }; - // The slots of a built-in reached through `path` from variables `in` / `out`. - const auto builtin_slots = [&](const Output& o, std::uint32_t in, std::uint32_t out, - std::vector path) { - if (!copied(o)) return; - if (o.builtin == builtin_position) { - slots.push_back({in, out, path, Kind::f32, 4, true}); - return; - } - for (std::uint32_t e = 0; e < o.array; ++e) { - std::vector element = path; - element.push_back(b.c_i32(e)); - slots.push_back({in, out, element, Kind::f32, 1, false}); - } - }; - const auto builtin_type = [&](const Output& o) { - return o.array ? b.t_array(t_f32, o.array) : b.t_vector(t_f32, o.count); - }; - if (s.block) { - std::vector members; - for (const Output& o : s.builtins) members.push_back(builtin_type(o)); - const std::uint32_t block_in = b.t_struct(members), block_out = b.t_struct(members); - for (const std::uint32_t block : {block_in, block_out}) { - decorate(block, {deco_block}); - for (std::uint32_t m = 0; m < s.builtins.size(); ++m) - Builder::put(b.decorations, op::member_decorate, {block, m, deco_builtin, s.builtins[m].builtin}); - } - const std::uint32_t in = - b.variable(b.t_pointer(storage_input, b.t_array(block_in, 3)), storage_input); - const std::uint32_t out = b.variable(b.t_pointer(storage_output, block_out), storage_output); - for (std::uint32_t m = 0; m < s.builtins.size(); ++m) builtin_slots(s.builtins[m], in, out, {b.c_i32(m)}); - } else { - for (const Output& o : s.builtins) { - if (!copied(o)) continue; - const auto [in, out] = pair(builtin_type(o)); - decorate(in, {deco_builtin, o.builtin}); - decorate(out, {deco_builtin, o.builtin}); - builtin_slots(o, in, out, {}); - } - } - const std::uint32_t primitive_in = b.variable(b.t_pointer(storage_input, t_i32), storage_input); - const std::uint32_t primitive_out = b.variable(b.t_pointer(storage_output, t_i32), storage_output); - decorate(primitive_in, {deco_builtin, builtin_primitive_id}); - decorate(primitive_out, {deco_builtin, builtin_primitive_id}); - - // Types and constants the body uses, declared before the function. - std::vector value_type, uint_type, bool_type; - for (const Slot& slot : slots) { - value_type.push_back(b.t_vector(b.t_scalar(slot.kind), slot.count)); - uint_type.push_back(b.t_vector(b.t_u32(), slot.count)); - bool_type.push_back(b.t_vector(t_bool, slot.count)); - } - std::vector in_pointer, out_pointer; - for (const std::uint32_t t : value_type) { - in_pointer.push_back(b.t_pointer(storage_input, t)); - out_pointer.push_back(b.t_pointer(storage_output, t)); - } - const std::array vertex{b.c_i32(0), b.c_i32(1), b.c_i32(2)}; - const std::uint32_t zero = b.c_f32(0.0f); - const std::uint32_t function = b.id(), entry_label = b.id(); - - Builder::put(b.body, op::function, {t_void, function, 0, t_fn}); - Builder::put(b.body, op::label, {entry_label}); - // Every input of the three vertices: [slot][vertex]. - std::vector> p(slots.size()); - std::size_t position = 0; - for (std::size_t i = 0; i < slots.size(); ++i) { - if (slots[i].position) position = i; - for (std::uint32_t v = 0; v < 3; ++v) { - std::vector chain{slots[i].in, vertex[v]}; - chain.insert(chain.end(), slots[i].path.begin(), slots[i].path.end()); - const std::uint32_t pointer = b.value(op::access_chain, in_pointer[i], chain); - p[i][v] = b.value(op::load, value_type[i], {pointer}); - } - } - std::array x{}, y{}, w{}; - for (std::uint32_t v = 0; v < 3; ++v) { - x[v] = b.value(op::composite_extract, t_f32, {p[position][v], 0}); - y[v] = b.value(op::composite_extract, t_f32, {p[position][v], 1}); - w[v] = b.value(op::composite_extract, t_f32, {p[position][v], 3}); - } - const auto same = [&](std::uint32_t l, std::uint32_t r) { return b.value(op::f_ord_equal, t_bool, {l, r}); }; - const auto both = [&](std::uint32_t l, std::uint32_t r) { return b.value(op::logical_and, t_bool, {l, r}); }; - const auto either = [&](std::uint32_t l, std::uint32_t r) { return b.value(op::logical_or, t_bool, {l, r}); }; - const auto no = [&](std::uint32_t l) { return b.value(op::logical_not, t_bool, {l}); }; - // One positive w, and no two vertices in one place. - std::uint32_t plain = b.value(op::f_ord_greater_than, t_bool, {w[0], zero}); - plain = both(plain, same(w[1], w[0])); - plain = both(plain, same(w[2], w[0])); - for (const auto [i, j] : {std::pair{0, 1}, std::pair{0, 2}, std::pair{1, 2}}) - plain = both(plain, no(both(same(x[i], x[j]), same(y[i], y[j])))); - // corner[i]: vertex i is the corner between the other two (the first that shares x with one and y with the other). - std::array corner{}; - for (std::uint32_t i = 0; i < 3; ++i) { - const std::uint32_t a = (i + 1) % 3, c = (i + 2) % 3; - const std::uint32_t one = both(same(x[i], x[a]), same(y[i], y[c])); - const std::uint32_t other = both(same(x[i], x[c]), same(y[i], y[a])); - std::uint32_t here = both(either(one, other), plain); - for (std::uint32_t earlier = 0; earlier < i; ++earlier) here = both(here, no(corner[earlier])); - corner[i] = here; - } - // The corner flags as conditions of each vector size (SPIR-V 1.0 selects a vector by a vector of bools). - std::map> splat; - for (const Slot& slot : slots) { - if (splat.count(slot.count)) continue; - std::array& flags = splat[slot.count]; - for (std::uint32_t k = 0; k < 3; ++k) { - if (slot.count == 1) { - flags[k] = corner[k]; - continue; - } - std::vector parts(slot.count, corner[k]); - flags[k] = b.value(op::composite_construct, b.t_vector(t_bool, slot.count), parts); - } - } - - // What the six emitted vertices carry: [slot][vertex]. - std::vector> emitted(slots.size()); - for (std::size_t i = 0; i < slots.size(); ++i) { - const std::uint32_t t = value_type[i]; - const auto& flag = splat[slots[i].count]; - const auto& [p0, p1, p2] = p[i]; - std::uint32_t fourth = p0; // integers (flat), and three vertices without a corner, keep the first vertex's - if (slots[i].kind == Kind::f32) { - // The vertex opposite the corner `at` of `a` and `c`: a + c - at, or exactly c (a) where a (c) has the - // corner's bits. - const std::array bits{b.value(op::bitcast, uint_type[i], {p0}), - b.value(op::bitcast, uint_type[i], {p1}), - b.value(op::bitcast, uint_type[i], {p2})}; - const auto equal = [&](std::uint32_t l, std::uint32_t r) { - return b.value(op::i_equal, bool_type[i], {bits[l], bits[r]}); - }; - const std::uint32_t eq01 = equal(0, 1), eq02 = equal(0, 2), eq12 = equal(1, 2); - const auto opposite = [&](std::uint32_t a, std::uint32_t c, std::uint32_t at, std::uint32_t a_is, - std::uint32_t c_is) { - const std::uint32_t sum = b.value(op::f_add, t, {a, c}); - std::uint32_t r = b.value(op::f_sub, t, {sum, at}); - r = b.value(op::select, t, {c_is, a, r}); - return b.value(op::select, t, {a_is, c, r}); - }; - fourth = b.value(op::select, t, {flag[0], opposite(p1, p2, p0, eq01, eq02), fourth}); - fourth = b.value(op::select, t, {flag[1], opposite(p2, p0, p1, eq12, eq01), fourth}); - fourth = b.value(op::select, t, {flag[2], opposite(p0, p1, p2, eq02, eq12), fourth}); - } - // Corner first: (v0, v1, v3), (v0, v3, v2). Second: (v0, v1, v2), (v0, v2, v3). Third: (v0, v1, v2), - // (v0, v3, v1). - const std::uint32_t third = b.value(op::select, t, {flag[0], fourth, p2}); - const std::uint32_t fifth = b.value(op::select, t, {flag[1], p2, fourth}); - const std::uint32_t second = b.value(op::select, t, {flag[0], p2, p1}); - const std::uint32_t sixth = b.value(op::select, t, {flag[1], fourth, second}); - emitted[i] = {p0, p1, third, p0, fifth, sixth}; - } - // The rectangle's number: the triangle's, one triangle a rectangle. - const std::uint32_t primitive = b.value(op::load, t_i32, {primitive_in}); - std::vector target(slots.size()); - for (std::size_t i = 0; i < slots.size(); ++i) { - if (slots[i].path.empty()) { - target[i] = slots[i].out; - continue; - } - std::vector chain{slots[i].out}; - chain.insert(chain.end(), slots[i].path.begin(), slots[i].path.end()); - target[i] = b.value(op::access_chain, out_pointer[i], chain); - } - for (std::uint32_t v = 0; v < kVertices; ++v) { - for (std::size_t i = 0; i < slots.size(); ++i) Builder::put(b.body, op::store, {target[i], emitted[i][v]}); - Builder::put(b.body, op::store, {primitive_out, primitive}); - Builder::put(b.body, op::emit_vertex, {}); - if (v == 2 || v == kVertices - 1) Builder::put(b.body, op::end_primitive, {}); // two triangles - } - Builder::put(b.body, op::return_, {}); - Builder::put(b.body, op::function_end, {}); - - std::vector words{kMagic, 0x00010000u, 0, b.bound(), 0}; - Builder::put(words, op::capability, {cap_shader}); - Builder::put(words, op::capability, {cap_geometry}); - if (s.clip) Builder::put(words, op::capability, {cap_clip_distance}); - if (s.cull) Builder::put(words, op::capability, {cap_cull_distance}); - Builder::put(words, op::memory_model, {0, 1}); // Logical, GLSL450 - std::uint32_t name = 0; - std::memcpy(&name, "main", 4); - std::vector entry{model_geometry, function, name, 0}; - entry.insert(entry.end(), b.interface.begin(), b.interface.end()); - Builder::put(words, op::entry_point, entry); - Builder::put(words, op::execution_mode, {function, mode_triangles}); - Builder::put(words, op::execution_mode, {function, mode_invocations, 1}); - Builder::put(words, op::execution_mode, {function, mode_output_triangle_strip}); - Builder::put(words, op::execution_mode, {function, mode_output_vertices, kVertices}); - for (const auto* section : {&b.decorations, &b.globals, &b.body}) - words.insert(words.end(), section->begin(), section->end()); - return words; -} - -std::shared_ptr> geometry_shader(const std::vector& vs, - std::string& why) { - Signature signature; - if (!read_signature(vs, signature, why)) return nullptr; - static std::mutex mutex; - static std::map>> cache; - const std::string key = signature.key(); - std::lock_guard lock(mutex); - if (const auto found = cache.find(key); found != cache.end()) return found->second; - std::vector words = build(signature, why); - if (words.empty()) return nullptr; - auto shared = std::make_shared>(std::move(words)); - cache.emplace(key, shared); - return shared; -} - -bool append_stage(PFN_vkCreateShaderModule create_module, VkDevice device, bool geometry_shader_feature, - const std::vector& vs, std::vector& modules, - std::vector& stages) { - const auto refuse = [](const std::string& why) { - static std::mutex mutex; - static std::set seen; - std::lock_guard lock(mutex); - if (seen.insert(why).second) - std::fprintf(stderr, "[rt] d3d12: a rectangle-list pipeline is refused: %s (logged once)\n", why.c_str()); - return false; - }; - if (!geometry_shader_feature) return refuse("its geometry stage needs the Vulkan geometryShader feature"); - std::string why; - const auto words = geometry_shader(vs, why); - if (!words) return refuse(why); - VkShaderModuleCreateInfo info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - info.codeSize = words->size() * 4; - info.pCode = words->data(); - VkShaderModule module = VK_NULL_HANDLE; - if (!create_module || create_module(device, &info, nullptr, &module) != VK_SUCCESS) - return refuse("vkCreateShaderModule failed for its geometry stage"); - modules.push_back(module); - VkPipelineShaderStageCreateInfo stage{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; - stage.stage = VK_SHADER_STAGE_GEOMETRY_BIT; - stage.module = module; - stage.pName = "main"; - stages.push_back(stage); - return true; -} - -} // namespace leonida::rect_list diff --git a/runtime/src/rect_list_gs.h b/runtime/src/rect_list_gs.h deleted file mode 100644 index 1d3cf8d87..000000000 --- a/runtime/src/rect_list_gs.h +++ /dev/null @@ -1,108 +0,0 @@ -#pragma once - -// Rectangle lists: the geometry stage that completes the console's rectangles on Vulkan. -// -// Ported from VIctory (GPL-3.0-or-later, Marvisak and contributors, DexNom fork; -// victory/crates/victory-shader/src/emit/rect.rs, commit 683ad7a99, and victory/crates/victory-gpu/src/primitive.rs); -// Leonida is GPL-3.0-or-later too. VIctory emits DXIL for host D3D12; this emits SPIR-V for the Vulkan layer. -// -// The title draws its full-screen passes and tiled lighting as rectangle lists: pipeline topology type 19 -// (kPipelineTopologyType) and list topology 17 (kListTopology; VIctory pipeline/host.rs:312, draw.rs:4022). A -// rectangle comes as three vertices, three corners of a screen-aligned rectangle; the console's hardware draws the -// whole rectangle and continues every vertex output linearly into the fourth corner. Vulkan has no such topology, so -// a rectangle pipeline gets this geometry shader behind the translated vertex shader and takes triangle lists: vertex -// counts, vertex numbers, indices and indirect arguments stay the title's, and each rectangle reaches the stage as one -// triangle (list topology 17 already draws as a triangle list, vulkan_replay.h vulkan_topology). -// -// The rule is VIctory's: -// * the corner is the vertex that shares x with one of the other two and y with the other (the title's full-screen -// rectangles come as top left, bottom left, bottom right: the second; its tiled lighting as top left, bottom -// left, top right: the first); the first vertex that qualifies wins; -// * the fourth vertex lies opposite it: a + b - corner for the position and every float output. Here a component -// whose a (or b) has the corner's exact bits takes b (or a) as it is, the same value without the rounding, so a -// position keeps its exact edges and a value equal on all three vertices (a bit pattern in a float output -// included) keeps its bits; -// * integer outputs, which are flat, take the first vertex's value at the fourth vertex; -// * three vertices whose w differ (or whose w is not positive), two in one place, or three that are not such -// corners, stay the triangle they make (the second triangle is empty). -// The stage emits two triangles, both starting with the first vertex: (v0, v1, v3), (v0, v3, v2) when the corner is -// the first vertex, (v0, v1, v2), (v0, v2, v3) when it is the second, (v0, v1, v2), (v0, v3, v1) when it is the -// third. Both turn as the title's triangle does (so culling is unchanged), and the first vertex is the provoking -// vertex of both, so a flat input reads it there and a PerVertexKHR input finds it at index 0. That is six vertices, -// not one four-vertex strip: in a strip the second triangle's provoking vertex would be the strip's second vertex. -// The primitive ID is passed on (the rectangle's number: one triangle a rectangle), since with a geometry stage the -// pixel shader reads the one that stage writes. -// -// shortcut: that the console takes a rectangle's flat values from its first vertex follows from the hardware's -// provoking-vertex setting for triangles; it is not measured on a rectangle (VIctory rect.rs says the same). A pixel -// shader that reads its barycentrics raw (not to interpolate) sees the second triangle's, not the rectangle's. -// -// The stage is built from the vertex shader's SPIR-V output interface, so it links with the module as created (after -// the f16-halves link, which can add outputs): every Location output (32-bit float, int or uint, scalar or vector), -// Position, and ClipDistance / CullDistance when the shader declares their capability, which the translator and -// glslang do only when they write them. Built-ins are declared as the vertex shader declares them: separate -// variables (the translator) or one gl_PerVertex block (glslang), mirrored member for member. Refused with a reason: -// no Position, a Layer or ViewportIndex output (a geometry stage cannot read them), an output of another type, and -// more components than a geometry stage may emit (6 vertices of at most 128 scalars, at most 1024 in all). -// The words are cached per output signature (Signature::key); tests/test_rect_list_gs.py runs the generator through -// rect_list_gs_tool and checks what the stage emits, d3d12_rect_list_test draws rectangles with it on the GPU. - -#include -#include -#include -#include - -#include - -namespace leonida::rect_list { - -// D3D12.X's rectangle-list topologies: the pipeline's PrimitiveTopologyType and the list's IASetPrimitiveTopology. -constexpr std::uint32_t kPipelineTopologyType = 19; -constexpr std::uint32_t kListTopology = 17; - -// Vertices the stage emits per rectangle: two triangles. -constexpr std::uint32_t kVertices = 6; - -enum class Kind : std::uint8_t { f32, i32, u32 }; - -// One value the stage copies from each vertex: a Location output, or a built-in (alone or a member of the vertex -// shader's gl_PerVertex block). -struct Output { - static constexpr std::uint32_t kNoBuiltin = ~0u; - std::uint32_t builtin = kNoBuiltin; // SPIR-V BuiltIn, or kNoBuiltin for a Location output - std::uint32_t location = 0; - std::uint32_t component = 0; - Kind kind = Kind::f32; - std::uint32_t count = 1; // vector size; 1 is a scalar - std::uint32_t array = 0; // ClipDistance / CullDistance: an array of `array` floats (count 1) -}; - -struct Signature { - std::vector locations; // by (location, component) - // Built-ins: Position, and PointSize, ClipDistance, CullDistance as the vertex shader declares them. - std::vector builtins; - bool block = false; // `builtins` are the members of one gl_PerVertex block, in order - bool clip = false, cull = false; // the vertex shader writes ClipDistance / CullDistance (declares the capability) - std::string key() const; -}; - -// The output interface of a vertex shader's SPIR-V (its first Vertex entry point). False with `why` when the stage -// cannot be made for it. -bool read_signature(const std::vector& vs, Signature& out, std::string& why); - -// The geometry shader's SPIR-V (version 1.0) for a signature read_signature accepted. Empty, with `why`, when the -// stage would emit more than a geometry shader may. -std::vector build(const Signature& signature, std::string& why); - -// read_signature, then build, cached per Signature::key (thread safe). Null with `why` when refused. -std::shared_ptr> geometry_shader(const std::vector& vs, - std::string& why); - -// For a rectangle pipeline: creates the stage's module for the vertex shader `vs` on `device`, appends it to -// `modules` (the pipeline destroys it with its others) and its stage to `stages`. False, logged once per reason, -// without the geometryShader feature, when the stage is refused, or when the module cannot be created. -bool append_stage(PFN_vkCreateShaderModule create_module, VkDevice device, bool geometry_shader_feature, - const std::vector& vs, std::vector& modules, - std::vector& stages); - -} // namespace leonida::rect_list diff --git a/runtime/src/resource_detile.h b/runtime/src/resource_detile.h index 368b0a377..74f22aac5 100644 --- a/runtime/src/resource_detile.h +++ b/runtime/src/resource_detile.h @@ -9,14 +9,6 @@ // // Independent X and Y coordinate bit mappings permit O(1) intra-tile offset resolution via compile-time // lookup tables (lut_x[x % tile_w] | lut_y[y % tile_h]). No Windows or Vulkan dependency. -// -// Scope, against the console's whole layout (gfx10::ConsoleTexture, VIctory texture.rs, which xg_xs.dll's texture -// computer and the layer's fill_from_title use): one SW_64KB_D level read from the start of its memory. For that, -// both agree byte for byte (xg_xs_test detiler_agrees, every element size and BC). They disagree on two things: -// - with mips the console puts the mip tail first and mip 0 last (256x256 BC7: mip 0 at 64 KiB), so this reads mip -// 0 only from that mip's offset in the layout; -// - VIctory reads the layout word as 0x100 | the swizzle mode, so 0x101 is SW_256B_S, not SW_64KB_D as assumed -// here (docs/d3d12_vulkan.md section 4.2). Nothing on the layer's path calls this file's functions. #include "resource_tiling.h" diff --git a/runtime/src/spirv_output_splat.h b/runtime/src/spirv_output_splat.h deleted file mode 100644 index d98aabc94..000000000 --- a/runtime/src/spirv_output_splat.h +++ /dev/null @@ -1,116 +0,0 @@ -#pragma once - -// A fragment shader's colour output whose alpha is stored in all four components (`.wwww`), for a render target the -// GPU has no format for: an A8_UNORM target is an R8_UNORM attachment, which stores the first component, while the -// pixel shader writes the target's one channel, alpha, in the fourth (D3D12's SV_Target.a for an A8 target). -// -// The translator (tools/rdna2spirv.py `export`) writes each colour output as one whole-vector OpStore to an Output -// variable decorated with its Location. Each such store is given an OpVectorShuffle of the stored value first. Loads -// of the output (the translator keeps an earlier export for lanes that do not export) read the splatted value, which -// splats to itself, so a later partial export still ends with the latest alpha in every component. -// -// No Vulkan headers; the caller has checked the binary's framing (spirv_words.h). Portable C++20. - -#include -#include -#include -#include -#include - -namespace leonida { - -// `words` with every store to the Output variable at `location` made `.wwww`, or an empty vector with `why` set when -// the module has no such four-component output (then the caller leaves the target as it is). -inline std::vector splat_output_alpha(std::span words, std::uint32_t location, - std::string& why) { - constexpr std::uint32_t magic = 0x07230203; - constexpr std::uint16_t op_type_vector = 23, op_type_pointer = 32, op_variable = 59, op_store = 62, - op_decorate = 71, op_vector_shuffle = 79; - constexpr std::uint32_t decoration_location = 30, class_output = 3; - if (words.size() < 5 || words[0] != magic) { - why = "not a SPIR-V module"; - return {}; - } - const auto for_each = [&](auto&& visit) { - for (std::size_t at = 5; at < words.size();) { - const std::uint32_t count = words[at] >> 16; - if (!count || at + count > words.size()) return false; - visit(at, static_cast(words[at] & 0xffff), count); - at += count; - } - return true; - }; - // The Location decorations, the Output variables and their pointer types, the vector types. - std::vector at_location; - struct Variable { - std::uint32_t id, pointer; - }; - std::vector outputs; - struct Pointer { - std::uint32_t id, pointee; - }; - std::vector output_pointers; - struct Vector { - std::uint32_t id, count; - }; - std::vector vectors; - const bool framed = for_each([&](std::size_t at, std::uint16_t op, std::uint32_t count) { - if (op == op_decorate && count >= 4 && words[at + 2] == decoration_location && words[at + 3] == location) - at_location.push_back(words[at + 1]); - else if (op == op_variable && count >= 4 && words[at + 3] == class_output) - outputs.push_back({words[at + 2], words[at + 1]}); - else if (op == op_type_pointer && count >= 4 && words[at + 2] == class_output) - output_pointers.push_back({words[at + 1], words[at + 3]}); - else if (op == op_type_vector && count >= 4) - vectors.push_back({words[at + 1], words[at + 3]}); - }); - if (!framed) { - why = "an instruction runs past the module"; - return {}; - } - std::uint32_t variable = 0, vector_type = 0; - for (const Variable& v : outputs) { - bool located = false; - for (std::uint32_t id : at_location) located |= id == v.id; - if (!located) continue; - for (const Pointer& p : output_pointers) - if (p.id == v.pointer) - for (const Vector& vec : vectors) - if (vec.id == p.pointee && vec.count == 4) vector_type = vec.id; - if (vector_type) { - variable = v.id; - break; - } - } - if (!variable) { - why = "no four-component Output variable at Location " + std::to_string(location); - return {}; - } - std::vector out; - out.reserve(words.size() + 64); - out.insert(out.end(), words.begin(), words.begin() + 5); - std::uint32_t bound = words[3]; - unsigned stores = 0; - for_each([&](std::size_t at, std::uint16_t op, std::uint32_t count) { - if (op == op_store && count >= 3 && words[at + 1] == variable) { - const std::uint32_t splat = bound++; - const std::uint32_t value = words[at + 2]; - out.insert(out.end(), {(9u << 16) | op_vector_shuffle, vector_type, splat, value, value, 3u, 3u, 3u, 3u}); - out.push_back(words[at]); - out.push_back(variable); - out.push_back(splat); - out.insert(out.end(), words.begin() + std::ptrdiff_t(at + 3), words.begin() + std::ptrdiff_t(at + count)); - ++stores; - return; - } - out.insert(out.end(), words.begin() + std::ptrdiff_t(at), words.begin() + std::ptrdiff_t(at + count)); - }); - if (!stores) { - why = "the output at Location " + std::to_string(location) + " is never stored"; - return {}; - } - out[3] = bound; - return out; -} - -} // namespace leonida diff --git a/runtime/src/title_memory.h b/runtime/src/title_memory.h deleted file mode 100644 index 1a4387bfc..000000000 --- a/runtime/src/title_memory.h +++ /dev/null @@ -1,145 +0,0 @@ -#pragma once - -// Title memory as GPU memory: a GPU address is the title's CPU address (docs/d3d12_vulkan.md section 3.3, "Title -// memory"). The translated shaders reach memory at heap_base + VA (push-constant dwords 32-33), so the D3D12 layer -// gives every piece of GPU-visible memory the device address heap_base + its VA: -// - the GPU address arena (default-heap buffers, the layer's own descriptor heaps, shader code) at VA = its offset, -// so its device memory sits at heap_base; -// - the title's graphics memory (xmem) at VA = its CPU address, imported with VK_EXT_external_memory_host at -// heap_base + that address. -// Both are allocated with an opaque capture address (bufferDeviceAddressCaptureReplay), which asks the driver for that -// device address. Measured on an RTX 4060 Ti, driver 616.64 (Vulkan 1.4.351; probes run 2026-11-25): -// - capture-replay memory, plain device-local, BAR and imported host memory alike, gets the device address asked for -// anywhere in about [0x2_FFF1_0000, 0xFF_FFFF_FFFF] (12 GiB to 1 TiB); an address at or above 2^40 is refused -// with VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS, and so is one the driver already uses; -// - a buffer bound at offset X of such memory has the memory's address + X; two imports at heap_base + their host -// addresses both get them; -// - the buffer's own opaque capture address reads 0: the address comes with the memory; -// - imported host memory cannot be bound into a sparse buffer there (a sparse buffer takes memory type 1, the device -// heap, only; host pointers import as types 2 and 3), so one sparse 2^40 mirror buffer (docs/port_plan.md, Frame -// time) is not possible on this driver. test/vk_sparse_title_memory_test.cpp asks again (2026-11-25): every sparse -// buffer, with or without residency, capture replay or VkExternalMemoryBufferCreateInfo for host allocations, -// lists type 1 alone, although vkGetPhysicalDeviceExternalBufferProperties calls host allocations importable for a -// sparse buffer (features 0x6). Bound anyway (--force-bind, invalid usage: the validation layer reports the memory -// type), the pages work: reads, GPU writes the CPU sees, CPU writes the GPU sees, one frame at two VAs, rebinds, -// and unbound pages read zero. One vkQueueBindSparse of 16,384 64 KiB pages took 70 ms to idle, 16,384 calls of one -// page 1.7 s; a sparse buffer at a capture-replay address may be up to 64 GiB (128 GiB was refused). The AMD -// driver (2026.04.17) lists host memory types for sparse buffers but has no bufferDeviceAddressCaptureReplay; -// - an import pins its pages (256 MiB never touched: 17.9 ms and +256 MiB of working set) but does not stop the CPU -// from decommitting or protecting them: the import keeps the old physical pages, so a range the title frees has to -// leave the GPU first (xmem tells the layer, rt::xmem::set_graphics_listener). -// - every host import but a device's first also gets an ordinary device address from the driver, of its size, -// first fit right after the arena: the retail title's 4.5 GB of pools took [heap_base + 256 MiB, -// heap_base + 4.7 GiB) that way, so its 32-bit memory, imported later, found its addresses taken. A sparse buffer -// at a capture-replay address holds addresses without memory, and keeps those mappings out (one of 384 GiB was -// refused, 16 GiB pieces were not); -// - device addresses go to imports 2 MiB at a time: an import that ends inside a 2 MiB block takes the rest of it, -// one that starts inside a block another holds is refused, and from 64 MiB on one must start on a 2 MiB line. The -// retail title's 32-bit windows lie side by side on 1 MiB lines, so imports that share a block are merged. -// -// Sparse title memory (the default: the imports path lost the device on the title; LEONIDA_TITLE_MEMORY=imports opts out; SparseTitleMemory in shims/d3d12_vulkan_device.cpp, -// docs/d3d12_vulkan.md section 3.3): sparse buffers over both windows at heap_base + VA, xmem's physical-page pools -// imported once each (in 256 MiB pieces) and every mapped page a sparse bind of its VA to its pool's import, every -// unmapped page bound to nothing (it reads zero), the title's other GPU memory imported once per range and bound at its -// own address. ON NVIDIA THAT BIND IS OUTSIDE THE VULKAN SPEC: the host imports' memory types (2, 3) are not in the -// sparse buffers' memoryTypeBits (1), which breaks VUID-VkSparseMemoryBind-memory-01096 (the validation layer: -// "memory has a type index (2) that is not among the allowed types mask (0x2) for this resource"). The driver does it -// correctly (measured above), so the path runs only after a self-test on the device passes; otherwise the imports -// below run. -// -// So heap_base is fixed at 512 GiB and the arena lies at [heap_base, heap_base + arena size). xmem places the title's -// 32-bit graphics memory (VIctory xmem.rs:69-88, attribute bit 2) in [1 GiB, 4 GiB), where the descriptor-table -// pointers the shaders truncate to 32 bits need it (docs/d3d12_vulkan.md, "Descriptor-table high-dword truncation"), -// and its other memory in [64 GiB, 448 GiB). The layer holds both windows' device addresses with sparse buffers and -// gives an import the part it needs; the driver's own mappings get [heap_base + 4 GiB, heap_base + 64 GiB) and what -// lies above 448 GiB, and heap_base + every title address stays below 1 TiB. -// -// No Windows or Vulkan dependency. - -#include - -namespace leonida::title_memory { - -inline constexpr std::uint64_t kHeapBase = std::uint64_t(1) << 39; // 512 GiB: heap_base on a capture-replay device -inline constexpr std::uint64_t kDeviceAddressEnd = std::uint64_t(1) << 40; // the driver's capture-replay limit -// Where xmem puts the title's memory (VIctory xmem.rs:73-88, which uses [4 GiB, 2^40) and the low 4 GiB for 32-bit -// memory; narrowed here to leave the driver's mappings room, as above). -inline constexpr std::uint64_t kLow32Start = std::uint64_t(1) << 30; // above any arena of up to 1 GiB -inline constexpr std::uint64_t kLow32End = std::uint64_t(1) << 32; -inline constexpr std::uint64_t kWindowStart = std::uint64_t(64) << 30; -inline constexpr std::uint64_t kWindowEnd = std::uint64_t(448) << 30; -static_assert(kHeapBase + kWindowEnd <= kDeviceAddressEnd); - -// The largest single import. Bigger visible ranges are imported in pieces of this size, which keeps one failed or -// released import from taking more than this with it (Windows drivers cap a process at 4,096 allocations, so imports -// are kept few and large: docs/port_plan.md, Frame time). -inline constexpr std::uint64_t kMaxImport = std::uint64_t(1) << 30; - -// The device address of title VA `va` on a capture-replay device. -constexpr std::uint64_t device_address(std::uint64_t va) { return kHeapBase + va; } - -// Whether [va, va + bytes) can have the device address heap_base + va: inside one window, non-empty, no wrap. -constexpr bool addressable(std::uint64_t va, std::uint64_t bytes) { - const auto inside = [&](std::uint64_t first, std::uint64_t end) { - return va >= first && va < end && bytes <= end - va; - }; - return bytes && (inside(kLow32Start, kLow32End) || inside(kWindowStart, kWindowEnd)); -} - -// XMem attribute words (VIctory xmem.rs:63-88): bits 0-1 the memory type, 3 for graphics memory (both processors); -// bit 2 a 32-bit address; bits 12-14, when set, the address width as 47 minus the field. The retail title passes -// 0x21, 0x3, 0x183, 0x283, 0x181, 0x7 and 0x27 (gta6rt --trace, xmem_attributes events). -constexpr bool graphics_attributes(std::uint64_t attributes) { return (attributes & 3) == 3; } -constexpr bool address_32bit(std::uint64_t attributes) { return (attributes & 4) != 0; } - -// The address range xmem places an allocation with these attributes in: [first, last] (VIctory's address_range, -// narrowed to the device-address window above). -struct Range { - std::uint64_t first; - std::uint64_t last; -}; -constexpr Range placement(std::uint64_t attributes) { - if (address_32bit(attributes)) return {kLow32Start, kLow32End - 1}; - const std::uint64_t field = attributes >> 12 & 7; - std::uint64_t end = kWindowEnd; - if (field) { - const std::uint64_t bits = 47 - field; - if (bits < 63 && (std::uint64_t(1) << bits) < end) end = std::uint64_t(1) << bits; - } - return {kWindowStart, end - 1}; -} - -// XMemAlloc attribute words, another layout than XMemVirtualAlloc's above (VIctory xmem.rs:228-233 and resource.rs: -// 951-963, GPL-3.0-or-later, Marvisak and contributors, DexNom fork): bits 14-15 the page size (1: 64 KiB, 2: 2 MiB), -// 16-23 the allocator id, 24-28 the alignment as log2, 29-32 the memory type, bit 33 a 32-bit address. -// ASSUMPTION: memory type 0 is the CPU heap and every other type memory both processors reach. VIctory gives its -// committed resources type 1 (a default heap, write-combined on the console) or 3 (the CPU-visible heaps, cacheable); -// no other type has been seen. -constexpr unsigned alloc_page_size(std::uint64_t attributes) { return unsigned(attributes >> 14 & 3); } -constexpr unsigned alloc_allocator_id(std::uint64_t attributes) { return unsigned(attributes >> 16 & 0xff); } -constexpr unsigned alloc_alignment_log2(std::uint64_t attributes) { return unsigned(attributes >> 24 & 0x1f); } -constexpr unsigned alloc_memory_type(std::uint64_t attributes) { return unsigned(attributes >> 29 & 0xf); } -constexpr bool alloc_32bit(std::uint64_t attributes) { return (attributes >> 33 & 1) != 0; } -// Whether XMemAllocDefault gives GPU memory (pages in the window above, visible to the D3D12 layer) for these -// attributes: a graphics memory type or a 32-bit address (VIctory's XMemAllocDefault takes 32-bit graphics memory -// for the latter). -constexpr bool alloc_gpu_memory(std::uint64_t attributes) { - return alloc_memory_type(attributes) != 0 || alloc_32bit(attributes); -} - -// The attributes of a committed resource's memory, as the console's D3D runtime asks the title's allocator for it -// (VIctory resource.rs:951-963, resource_attributes): the graphics allocator id 128, 2 MiB pages from 2 MiB up (else -// 64 KiB), the alignment as log2, memory type 1 for a default heap and 3 for the CPU-visible ones. VIctory's own -// note: the console runtime's page size and memory type are not known, these are the plausible ones. -inline constexpr std::uint64_t kGraphicsAllocatorId = 128; -constexpr std::uint64_t resource_attributes(std::uint64_t size, std::uint64_t alignment, bool default_heap) { - std::uint64_t log2 = 0; - for (std::uint64_t a = alignment ? alignment : 1; !(a & 1) && log2 < 63; a >>= 1) ++log2; // trailing zeros - const std::uint64_t pages = size >= (std::uint64_t(2) << 20) ? 2 : 1; - const std::uint64_t memory = default_heap ? 1 : 3; - return kGraphicsAllocatorId << 16 | pages << 14 | (log2 & 0x1f) << 24 | memory << 29; -} -static_assert(resource_attributes(33423360, 0x10000, true) == 0x30808000); // a 3840x2160 RGBA8 back buffer -static_assert(resource_attributes(0x10000, 0x10000, false) == 0x70804000); - -} // namespace leonida::title_memory diff --git a/runtime/src/xma_context.cpp b/runtime/src/xma_context.cpp deleted file mode 100644 index dec4d1a79..000000000 --- a/runtime/src/xma_context.cpp +++ /dev/null @@ -1,224 +0,0 @@ -// The SHAPE XMA context machine. Ported from VIctory (crates/victory-hle/src/modules/audio.rs), GPL-3.0-or-later, by -// Marvisak and contributors (DexNom fork). Leonida is GPL-3.0-or-later. See xma_context.h. -#include "xma_context.h" - -#include -#include - -namespace rt::xma { - -namespace { - -constexpr uint32_t kRates[4] = {24000, 32000, 44100, 48000}; - -int16_t saturating_abs(int16_t v) { return v == INT16_MIN ? INT16_MAX : static_cast(v < 0 ? -v : v); } - -} // namespace - -void pump(Context context, Voice& voice, ApuBytes memory) { - const uint32_t size = context.field(0, 22, 5); - if (size == 0) return; - while (context.field(1, 31, 1) == 1) { - if (voice.pcm.size() < kSamplesPerBlock && !decode(context, voice, memory)) return; - // The write block is the title's too: taken modulo the ring before the first write, which would otherwise - // land past the ring's end. - uint32_t write = context.field(0, 27, 5) % size; - const uint32_t address = static_cast(context.get(7) + uint64_t{write} * kBlockBytes); - uint8_t* out = memory(address, kBlockBytes); - if (!out) return; - for (size_t i = 0; i < kSamplesPerBlock; ++i) { - int16_t sample = 0; - if (!voice.pcm.empty()) { - sample = voice.pcm.front(); - voice.pcm.pop_front(); - } - voice.trace.peak = std::max(voice.trace.peak, saturating_abs(sample)); - const uint16_t bits = static_cast(sample); - out[2 * i] = static_cast(bits & 0xff); - out[2 * i + 1] = static_cast(bits >> 8); - } - voice.trace.produced += kSamplesPerBlock / context.channels(); - write = (write + 1) % size; - context.set_field(0, 27, 5, write); - // The read block is the title's: taken modulo the ring like the write block and advance_read's. Compared as - // it is, one at or past the end would never be met, and a stream that loops would keep this voice (and its - // lock) filling forever. - if (write == context.field(9, 0, 5) % size) { - // Full: nothing more until the title advances its read block. - context.set_field(1, 31, 1, 0); - } - } -} - -bool decode(Context context, Voice& voice, ApuBytes memory) { - if (voice.ended) return false; - const size_t channels = context.channels(); - uint32_t current = context.field(4, 31, 1); - const uint32_t valid = context.field(0, 20, 2); - if ((valid & (1u << current)) == 0) { - if ((valid & (1u << (1 - current))) == 0) { - // Out of input: the overlap tail, then nothing. - if (voice.decoder) { - voice.frame.clear(); - voice.decoder->flush(voice.frame); - voice.pcm.insert(voice.pcm.end(), voice.frame.begin(), voice.frame.end()); - } - voice.ended = true; - voice.trace.input_ended = true; - context.set_field(2, 26, 5, kInputInvalid); - context.set_field(2, 31, 1, 1); - return !voice.pcm.empty(); - } - current = 1 - current; - context.set_field(4, 31, 1, current); - context.set_field(2, 0, 26, 0); - } - const uint32_t address = current == 0 ? context.get(5) : context.get(6); - const uint32_t packets = current == 0 ? context.field(0, 0, 12) : context.field(1, 0, 12); - const size_t bytes = size_t{packets} * kPacketBytes; - const uint8_t* data = memory(address & ~0x7ffu, bytes); - if (!data) { - context.set_field(0, 20 + current, 1, 0); - return true; - } - const std::span input(data, bytes); - size_t at = context.field(2, 0, 26); - if (at < kHeaderBits) { - const auto first = packet(input, 0); - at = kHeaderBits + (first ? first->first_frame_bit : 0); - } - const auto frame = read_frame(input, at); - if (!frame) { - // This input is used up. - context.set_field(0, 20 + current, 1, 0); - return true; - } - if (!voice.decoder) voice.decoder.emplace(channels, kRates[context.field(1, 27, 2)]); - voice.frame.clear(); - ++voice.trace.frames; - if (voice.decoder->decode(frame->data, frame->bits, voice.frame)) ++voice.trace.bad_frames; - size_t next = frame->next.value_or(0); - const uint32_t loops = context.field(0, 12, 8); - const size_t loop_end = context.field(4, 0, 26); - const bool ends_loop = loop_end != 0 && (frame->start == loop_end || - (frame->start < loop_end && (!frame->next || loop_end < *frame->next))); - const bool looping = loops > 0 && ends_loop; - if (looping) { - const size_t keep = (context.field(1, 12, 2) + size_t{1}) * kSubframeSamples * channels; - if (voice.frame.size() > keep) voice.frame.resize(keep); - next = context.field(3, 0, 26); - if (loops != 255) context.set_field(0, 12, 8, loops - 1); - } - // What is still to skip is this frame's (the stream's first, or a loop's first when it is its last too). - const size_t skip = std::min(voice.skip * channels, voice.frame.size()); - voice.skip -= skip / channels; - voice.pcm.insert(voice.pcm.end(), voice.frame.begin() + static_cast(skip), voice.frame.end()); - if (looping) { - // The loop's own skip is of its first frame, decoded next: not of this one, its last. - voice.skip = context.field(1, 17, 3) * kSubframeSamples; - } - if (next == 0) context.set_field(0, 20 + current, 1, 0); - context.set_field(2, 0, 26, static_cast(next)); - return true; -} - -void Engine::attach(uint32_t* array, uint32_t count) { - std::unique_lock lock(lock_); - array_ = array; - count_ = array ? count : 0; - slots_ = count_ ? std::make_unique(count_) : nullptr; -} - -void Engine::detach() { - std::unique_lock lock(lock_); - array_ = nullptr; - count_ = 0; - slots_.reset(); -} - -std::optional Engine::context(uint32_t index) const { - if (index >= count_ || !array_) return std::nullopt; - return Context(array_ + size_t{index} * (kContextBytes / 4)); -} - -void Engine::enable(uint32_t index) { - const auto context = this->context(index); - if (!context) return; - { - std::lock_guard slot(slots_[index].mutex); - context->set_field(2, 26, 6, 0); - Voice& voice = slots_[index].voice.emplace(); - voice.skip = context->field(1, 24, 3) * kSubframeSamples; - } - if (wake_) wake_(); -} - -void Engine::disable(uint32_t index) { - if (!this->context(index)) return; - std::lock_guard slot(slots_[index].mutex); - slots_[index].voice.reset(); -} - -void Engine::advance_read(uint32_t index, uint32_t blocks) { - const auto context = this->context(index); - if (!context) return; - { - // The decoder writes the same words. - std::lock_guard slot(slots_[index].mutex); - const uint32_t size = std::max(context->field(0, 22, 5), 1); - // The count is the title's: reduced first, so the sum stays small. - const uint32_t read = (context->field(9, 0, 5) + blocks % size) % size; - context->set_field(9, 0, 5, read); - if (blocks > 0) context->set_field(1, 31, 1, 1); - if (auto& voice = slots_[index].voice) { - voice->trace.taken += blocks; - ++voice->trace.takes; - voice->trace.partial_takes += blocks < size ? 1 : 0; - } - } - if (wake_) wake_(); -} - -bool Engine::command(uint32_t command, const void* data) { - const auto word = [data](size_t at) -> std::optional { - if (!data) return std::nullopt; - uint32_t v = 0; - std::memcpy(&v, static_cast(data) + at * 4, sizeof v); - return v; - }; - std::shared_lock lock(lock_); - switch (command) { - case kEnableXma: enable(word(0).value_or(UINT32_MAX)); break; - case kDisableXma: disable(word(0).value_or(UINT32_MAX)); break; - case kEnableXmas: - case kDisableXmas: - for (uint32_t i = 0; i < count_; ++i) { - if ((word(i / 32).value_or(0) & (1u << (i % 32))) == 0) continue; - if (command == kEnableXmas) enable(i); - else disable(i); - } - break; - case kAdvanceXmaRead: advance_read(word(0).value_or(UINT32_MAX), word(1).value_or(0)); break; - default: return false; - } - return true; -} - -void Engine::pump() { - std::shared_lock lock(lock_); - for (uint32_t index = 0; index < count_; ++index) { - const auto context = this->context(index); - std::lock_guard slot(slots_[index].mutex); - if (context && slots_[index].voice) xma::pump(*context, *slots_[index].voice, memory_); - } -} - -std::optional Engine::trace(uint32_t index) { - std::shared_lock lock(lock_); - if (!this->context(index)) return std::nullopt; - std::lock_guard slot(slots_[index].mutex); - if (!slots_[index].voice) return std::nullopt; - return slots_[index].voice->trace; -} - -} // namespace rt::xma diff --git a/runtime/src/xma_context.h b/runtime/src/xma_context.h deleted file mode 100644 index f4c6dbe16..000000000 --- a/runtime/src/xma_context.h +++ /dev/null @@ -1,143 +0,0 @@ -// The audio coprocessor's XMA decoder: enabled SHAPE XMA contexts are decoded into their output rings, like the -// hardware does. -// -// Ported from VIctory (crates/victory-hle/src/modules/audio.rs, the XMA part), GPL-3.0-or-later, by Marvisak and -// contributors (DexNom fork). Leonida is GPL-3.0-or-later. The DexNom snapshot in victory/ is the base; three fixes -// from VIctory's own history in this repository that the snapshot lacks are kept: the write block (7a5d85e6a) and the -// read block (1054fe87d) are taken modulo the ring, so neither writes past the ring's end nor fills it for good, and -// a loop's start skip applies to the loop's first frame, not its last (985d8d4b0). Pure C++: no OS headers; the -// acphal shim owns the decoding thread and the APU memory lookup. -// -// An XMA context (16 words in the shared context array) names up to two input buffers of 2 KiB packets, a ring of -// 256-byte output blocks the hardware fills with 16-bit PCM, and the read offset the title advances by command. Words -// and bit fields, as titles write them: -// 0: input 0 size in packets (0-11), loop count (12-19, 255 forever), valid inputs (20-21), output size in blocks -// (22-26), write block (27-31, hardware); -// 1: input 1 size (0-11), loop end subframe (12-13), loop start subframes to skip (17-19), subframes to skip at the -// start (24-26), sample rate (27-28: 24, 32, 44.1, 48 kHz), stereo (29), output writable (31); -// 2: read position in bits (0-25), error status (26-30), error (31); -// 3: loop start in bits (0-25); 4: loop end in bits (0-25), current input (31); 5, 6: input addresses; 7: output -// address; 8: overlap buffer; 9: read block (0-4). -// Titles read back only the write block, "writable" and the read block, and take whatever lies between read and -// write. Each enabled context decodes from a cold state and the overlap buffer is ignored (titles copy it between -// consecutive contexts of one voice), as in VIctory. -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "xma_decode.h" - -namespace rt::xma { - -// Coprocessor commands that drive XMA contexts (IAcpHal::SubmitCommand ids, VIctory audio.rs). -inline constexpr uint32_t kEnableXma = 5; // word 0: the context index -inline constexpr uint32_t kEnableXmas = 6; // words: a bit per context -inline constexpr uint32_t kDisableXma = 7; // word 0: the context index -inline constexpr uint32_t kDisableXmas = 8; // words: a bit per context -inline constexpr uint32_t kAdvanceXmaRead = 18; // word 0: the context index, word 1: blocks the title took - -inline constexpr size_t kContextBytes = 64; -inline constexpr size_t kBlockBytes = 256; -inline constexpr size_t kSamplesPerBlock = kBlockBytes / 2; -// Error status (word 2, bits 26-30): the input ran out. -inline constexpr uint32_t kInputInvalid = 4; - -// `len` host bytes of APU memory at a device address when one live heap block holds them all, else null. -using ApuBytes = uint8_t* (*)(uint32_t apu, size_t len); - -// A context's words in title memory. Read and written as volatile: the title reads and writes them concurrently, as -// it does the hardware's. -class Context { -public: - explicit Context(uint32_t* words) : words_(words) {} - - uint32_t get(size_t word) const { return static_cast(words_)[word]; } - void set(size_t word, uint32_t value) const { static_cast(words_)[word] = value; } - uint32_t field(size_t word, uint32_t shift, uint32_t bits) const { - return (get(word) >> shift) & ((uint32_t{1} << bits) - 1); - } - void set_field(size_t word, uint32_t shift, uint32_t bits, uint32_t value) const { - const uint32_t mask = ((uint32_t{1} << bits) - 1) << shift; - set(word, (get(word) & ~mask) | ((value << shift) & mask)); - } - size_t channels() const { return 1 + field(1, 29, 1); } - -private: - uint32_t* words_; -}; - -// What a voice did. -struct Trace { - size_t produced = 0; // samples per channel written to the ring - size_t taken = 0; // blocks the title took (command 18), how often, and how often it found the ring not full - uint32_t takes = 0; - uint32_t partial_takes = 0; - uint32_t frames = 0; - uint32_t bad_frames = 0; - int16_t peak = 0; // the loudest sample written - bool input_ended = false; -}; - -// An enabled context's decoding state. -struct Voice { - std::optional decoder; - std::deque pcm; - size_t skip = 0; // samples per channel still to drop (start or loop subframe skips) - bool ended = false; - Trace trace; - std::vector frame; // one frame's samples, reused -}; - -// Decodes the next frame of the context's current input into voice.pcm; false when there is nothing left to decode. -bool decode(Context context, Voice& voice, ApuBytes memory); - -// Fills the context's output ring as far as it has room. -void pump(Context context, Voice& voice, ApuBytes memory); - -// The voices of the XMA context array: one per context, set while the context is enabled. Each has its own lock, so a -// command for one voice never waits for others to decode (the title sends them from its time-critical mixer thread). -// The array is attached when the context arrays are allocated and detached when they are released. -class Engine { -public: - // `wake` (optional) is called when a voice was enabled or read from, to have the decoding thread fill rings now. - explicit Engine(ApuBytes memory, void (*wake)() = nullptr) : memory_(memory), wake_(wake) {} - - void attach(uint32_t* array, uint32_t count); - void detach(); - - // Runs an XMA command whose data words start at `data` (null: none); false for a command this does not know. - bool command(uint32_t command, const void* data); - - // Fills every enabled context's output as far as it has room. - void pump(); - - // The trace of an enabled voice; none when the context is not enabled. - std::optional trace(uint32_t index); - -private: - struct Slot { - std::mutex mutex; - std::optional voice; - }; - - std::optional context(uint32_t index) const; - void enable(uint32_t index); - void disable(uint32_t index); - void advance_read(uint32_t index, uint32_t blocks); - - ApuBytes memory_; - void (*wake_)(); - std::shared_mutex lock_; // exclusive only to attach and detach - uint32_t* array_ = nullptr; - uint32_t count_ = 0; - std::unique_ptr slots_; -}; - -} // namespace rt::xma diff --git a/runtime/src/xma_decode.cpp b/runtime/src/xma_decode.cpp deleted file mode 100644 index add0e5e89..000000000 --- a/runtime/src/xma_decode.cpp +++ /dev/null @@ -1,897 +0,0 @@ -// XMA2 frame decoder. Ported from VIctory (crates/victory-formats/src/xma.rs), GPL-3.0-or-later, by Marvisak and -// contributors (DexNom fork). Leonida is GPL-3.0-or-later. See xma_decode.h for what it covers and which of VIctory's -// later fixes are kept. -#include "xma_decode.h" - -#include -#include -#include -#include - -#include "xma_tables.h" - -namespace rt::xma { - -namespace detail { - -// Bitstream reading inside one gathered frame, MSB first. Reads past the data see zeros; `end` is where the frame's -// bits end, so a decoder that read further has overread. -struct BitReader { - std::span data; - size_t pos = 0; - size_t end = 0; - - uint32_t peek32() const { - uint64_t v = 0; - const size_t byte = pos / 8; - for (size_t i = 0; i < 5; ++i) v = v << 8 | (byte + i < data.size() ? data[byte + i] : 0u); - return static_cast((v << (24 + pos % 8)) >> 32); - } - - uint32_t read(uint32_t n) { - if (n == 0) return 0; - const uint32_t v = peek32() >> (32 - n); - pos += n; - return v; - } - - bool bit() { return read(1) != 0; } - - int32_t sign_extend(uint32_t n) { return static_cast(read(n) << (32 - n)) >> (32 - n); } - - bool overread() const { return pos > end; } -}; - -} // namespace detail - -namespace { - -using detail::BitReader; - -// 512 >> 2: the smallest subframe. -constexpr size_t kMinSubframe = kSubframeSamples; - -uint32_t log2_floor(size_t v) { - v = std::max(v, 1); - uint32_t r = 0; - while (v >>= 1) ++r; - return r; -} - -// Packets. - -// Bit positions in a buffer of packets, skipping each packet's header and the packets of other streams. -struct Cursor { - std::span data; - size_t pos = 0; - - bool bit(uint32_t& out) { - // Past the data nothing is read, whatever the skips would say; checking first keeps the packet arithmetic - // below from overflowing for a position far past the end. - if (pos / 8 >= data.size()) return false; - if (pos % kPacketBits == 0) { - // Leaving a packet: jump over the other streams' packets. - const size_t previous = pos / kPacketBits; - if (previous > 0) { - const auto header = packet(data, previous - 1); - if (!header) return false; - pos = (previous + header->skip) * kPacketBits; - } - pos += kHeaderBits; - } - if (pos / 8 >= data.size()) return false; - out = (data[pos / 8] >> (7 - pos % 8)) & 1u; - ++pos; - return true; - } - - bool bits(uint32_t n, uint32_t& out) { - uint32_t v = 0; - for (uint32_t i = 0; i < n; ++i) { - uint32_t b = 0; - if (!bit(b)) return false; - v = v << 1 | b; - } - out = v; - return true; - } - - // A payload byte, MSB first. At a packet edge the individual bits may be separated by a header and other - // streams' packets. - bool byte(uint8_t& out) { - const size_t in_packet = pos % kPacketBits; - if (in_packet == 0 || in_packet > kPacketBits - 8) { - uint32_t v = 0; - if (!bits(8, v)) return false; - out = static_cast(v); - return true; - } - const size_t at = pos / 8; - const unsigned shift = static_cast(pos % 8); - if (at >= data.size()) return false; - const unsigned first = data[at]; - if (shift == 0) { - out = static_cast(first); - } else { - if (at + 1 >= data.size()) return false; - out = static_cast(((first << shift) | (data[at + 1] >> (8 - shift))) & 0xffu); - } - pos += 8; - return true; - } -}; - -// Where the frame after the one at `start`..`end` begins: right after it, unless it was the last frame to begin in its -// packet and the rest of that packet is padding. -std::optional next_frame(std::span data, size_t start, size_t end) { - const size_t index = start / kPacketBits; - const auto header = packet(data, index); - if (!header) return std::nullopt; - size_t at = index * kPacketBits + kHeaderBits + header->first_frame_bit; - uint32_t number = 0; - while (at < start) { - Cursor cursor{data, at}; - uint32_t bits = 0; - if (!cursor.bits(kLengthBits, bits)) return std::nullopt; - // The same rule as read_frame: a length that does not cover its own field is not a frame. A zero length - // would never move `at`, so a damaged packet would loop here for good. - if (bits <= kLengthBits) return std::nullopt; - at += bits; - ++number; - } - const bool last = number + 1 >= header->frames; - // A frame that ends in a packet where no frame begins (the tail of a frame that crossed packets, then padding) - // is the last one before the next packet that has frames. - bool ends_in_packet_without_frames = false; - if (end / kPacketBits != index && end % kPacketBits != 0) { - const auto there = packet(data, end / kPacketBits); - if (!there) return std::nullopt; - ends_in_packet_without_frames = there->frames == 0; - } - if (end % kPacketBits == 0 || (last && end / kPacketBits == index) || ends_in_packet_without_frames) { - // The next frame begins in the next packet of this stream that has one; a packet with none (a frame spans - // all of it) holds no start. - const auto ending = packet(data, (end - 1) / kPacketBits); - if (!ending) return std::nullopt; - size_t next = (end - 1) / kPacketBits + 1 + ending->skip; - auto following = packet(data, next); - if (!following) return std::nullopt; - while (following->frames == 0) { - next += 1 + following->skip; - following = packet(data, next); - if (!following) return std::nullopt; - } - end = next * kPacketBits + kHeaderBits + following->first_frame_bit; - } - if (end / 8 < data.size()) return end; - return std::nullopt; -} - -// A prefix code built like FFmpeg's ff_vlc_init_from_lengths: codes are handed out in table order, each the next free -// one of its length. -class Vlc { -public: - void add(int32_t symbol, uint8_t length) { - codes_.push_back({static_cast(next_), length, symbol}); - next_ += uint64_t{1} << (32 - length); - } - - int32_t read(BitReader& b) const { - const uint32_t v = b.peek32(); - // The last code at or below v; the first code is 0, so there is always one. - auto it = std::upper_bound(codes_.begin(), codes_.end(), v, - [](uint32_t value, const Code& c) { return value < c.code; }); - const Code& c = *(it - 1); - b.pos += c.length; - return c.symbol; - } - -private: - struct Code { - uint32_t code; // left-aligned - uint8_t length; - int32_t symbol; - }; - std::vector codes_; // sorted by code - uint64_t next_ = 0; -}; - -struct Codes { - Vlc scale, scale_rl, coef[2], vec4, vec2, vec1; -}; - -template -void add_pairs(Vlc& vlc, const tables::SymbolLength (&pairs)[N], int32_t offset) { - for (const auto& p : pairs) vlc.add(static_cast(p.symbol) + offset, p.length); -} - -const Codes& codes() { - static const Codes built = [] { - Codes c; - add_pairs(c.scale, tables::kScale, -60); - add_pairs(c.scale_rl, tables::kScaleRl, 0); - static_assert(std::size(tables::kCoef0Syms) == std::size(tables::kCoef0Lens)); - for (size_t i = 0; i < std::size(tables::kCoef0Syms); ++i) - c.coef[0].add(static_cast(tables::kCoef0Syms[i]), tables::kCoef0Lens[i]); - add_pairs(c.coef[1], tables::kCoef1, 0); - static_assert(std::size(tables::kVec4Syms) == std::size(tables::kVec4Lens)); - for (size_t i = 0; i < std::size(tables::kVec4Syms); ++i) - c.vec4.add(static_cast(tables::kVec4Syms[i]) - 1, tables::kVec4Lens[i]); - add_pairs(c.vec2, tables::kVec2, -1); - add_pairs(c.vec1, tables::kVec1, 0); - return c; - }(); - return built; -} - -// ff_wma_get_large_val. -uint32_t large_value(BitReader& b) { - uint32_t n = 8; - if (b.bit()) { - n += 8; - if (b.bit()) { - n += 8; - if (b.bit()) n += 7; - } - } - return b.read(n); -} - -// The inverse transform. - -// Everything imdct_half needs for one size `n` that does not depend on the coefficients: the pre-rotation -// exp(-iπk/n) and post-rotation exp(-iπ(4k+1)/4n) of each of the n/2 FFT points, the FFT's bit-reversed order and its -// butterfly rotations. Each value is computed with the expression (for the butterflies the running product) the -// transform would work out on every call, so it gives the same bits. -struct Rotations { - std::vector pre_re, pre_im, post_re, post_im; - std::vector reversed; // where the bit-reversal permutation puts each point - // The butterfly rotations of every stage, the stage of length `len` starting at len / 2 - 1. - std::vector twiddle_re, twiddle_im; - - explicit Rotations(size_t n) { - const size_t m = n / 2; - constexpr double pi = std::numbers::pi; - for (size_t k = 0; k < m; ++k) { - const double a = -pi * static_cast(k) / static_cast(n); - pre_re.push_back(std::cos(a)); - pre_im.push_back(std::sin(a)); - const double b = -pi * static_cast(4 * k + 1) / static_cast(4 * n); - post_re.push_back(std::cos(b)); - post_im.push_back(std::sin(b)); - } - // The swaps of the in-place bit reversal, applied to the identity. - for (size_t i = 0; i < m; ++i) reversed.push_back(static_cast(i)); - size_t j = 0; - for (size_t i = 1; i < m; ++i) { - size_t bit = m >> 1; - while (j & bit) { - j ^= bit; - bit >>= 1; - } - j |= bit; - if (i < j) std::swap(reversed[i], reversed[j]); - } - for (size_t len = 2; len <= m; len <<= 1) { - const double a = -2.0 * pi / static_cast(len); - const double ws = std::sin(a), wc = std::cos(a); - double cr = 1.0, ci = 0.0; - for (size_t k = 0; k < len / 2; ++k) { - twiddle_re.push_back(cr); - twiddle_im.push_back(ci); - const double nr = cr * wc - ci * ws; - const double ni = cr * ws + ci * wc; - cr = nr; - ci = ni; - } - } - } - - // The butterfly stages of an in-place radix-2 forward DFT (exp(-2πi nk/N)) on m points already in bit-reversed - // order. - void butterflies(double* re, double* im, size_t m) const { - for (size_t len = 2; len <= m; len <<= 1) { - const size_t half = len / 2; - const double* wr = twiddle_re.data() + (half - 1); - const double* wi = twiddle_im.data() + (half - 1); - for (size_t start = 0; start < m; start += len) { - for (size_t k = 0; k < half; ++k) { - const size_t a = start + k, b = a + half; - const double tr = re[b] * wr[k] - im[b] * wi[k]; - const double ti = re[b] * wi[k] + im[b] * wr[k]; - re[b] = re[a] - tr; - im[b] = im[a] - ti; - re[a] = re[a] + tr; - im[a] = im[a] + ti; - } - } - } - } -}; - -// Rotations for subframes of 128, 256 and 512 samples. -const Rotations* cached_rotations(size_t n) { - static const Rotations r128(128), r256(256), r512(512); - switch (n) { - case 128: return &r128; - case 256: return &r256; - case 512: return &r512; - default: return nullptr; - } -} - -// Sine windows for blocks of 128, 256 and 512 samples. -const std::vector& window_for(size_t winlen) { - static const std::vector w[3] = {sine_window(128), sine_window(256), sine_window(512)}; - return w[log2_floor(winlen) - 7]; -} - -int16_t to_i16(float v) { - const float s = std::round(v * 32768.0f); - if (s != s) return 0; // NaN, as Rust's saturating cast gives - if (s <= -32768.0f) return -32768; - if (s >= 32767.0f) return 32767; - return static_cast(s); -} - -} // namespace - -std::optional packet(std::span data, size_t index) { - if (index > (SIZE_MAX - 4) / kPacketBytes) return std::nullopt; - const size_t start = index * kPacketBytes; - if (start > data.size() || data.size() - start < 4) return std::nullopt; - const uint32_t h = static_cast(data[start]) << 24 | static_cast(data[start + 1]) << 16 | - static_cast(data[start + 2]) << 8 | data[start + 3]; - return Packet{h >> 26, (h >> 11) & 0x7fffu, h & 0xffu}; -} - -std::optional read_frame(std::span data, size_t start) { - Cursor cursor{data, start}; - uint32_t length = 0; - if (!cursor.bits(kLengthBits, length)) return std::nullopt; - const size_t bits = length; - if (bits <= kLengthBits || bits == 0x7fff) return std::nullopt; - Frame frame; - frame.data.reserve((bits + 7) / 8); - Cursor gather{data, start}; - for (size_t i = 0; i < bits / 8; ++i) { - uint8_t v = 0; - if (!gather.byte(v)) return std::nullopt; - frame.data.push_back(v); - } - const uint32_t tail = static_cast(bits % 8); - if (tail != 0) { - uint32_t v = 0; - if (!gather.bits(tail, v)) return std::nullopt; - frame.data.push_back(static_cast(v << (8 - tail))); - } - frame.bits = bits; - frame.start = start; - frame.next = next_frame(data, start, gather.pos); - return frame; -} - -void imdct_half(std::span input, std::span out, float scale) { - const size_t n = input.size(); - const size_t m = n / 2; - if (m == 0 || out.size() < n) return; - const Rotations* rotations = cached_rotations(n); - std::optional built; - if (!rotations) rotations = &built.emplace(n); - double stack[kFrameSamples]; - std::vector heap; - double* re = stack; - if (m > kFrameSamples / 2) { - heap.resize(2 * m); - re = heap.data(); - } - double* im = re + m; - // Pre-rotation, each point stored at its bit-reversed place, which is where the FFT's input permutation would - // move it. - for (size_t k = 0; k < m; ++k) { - const double a = input[2 * k], b = input[n - 1 - 2 * k]; - const double c = rotations->pre_re[k], s = rotations->pre_im[k]; - const size_t to = rotations->reversed[k]; - re[to] = a * c - b * s; - im[to] = a * s + b * c; - } - rotations->butterflies(re, im, m); - for (size_t k = 0; k < m; ++k) { - const double c = rotations->post_re[k], s = rotations->post_im[k]; - const double wr = re[k] * c - im[k] * s; - const double wi = re[k] * s + im[k] * c; - // DCT-IV: c[2k] = Re, c[n-1-2k] = -Im; output j is c[n-1-j]. - out[n - 1 - 2 * k] = static_cast(wr) * scale; - out[2 * k] = -static_cast(wi) * scale; - } -} - -std::vector sine_window(size_t n) { - std::vector w(n); - for (size_t i = 0; i < n; ++i) - w[i] = static_cast( - std::sin((static_cast(i) + 0.5) * std::numbers::pi / (2.0 * static_cast(n)))); - return w; -} - -void window_overlap(std::span block, std::span window) { - const size_t len = block.size() / 2; - if (window.size() < 2 * len) return; - for (size_t k = 0; k < len; ++k) { - const size_t i = k, j = 2 * len - 1 - k; - const float s0 = block[i], s1 = block[j]; - const float wi = window[i], wj = window[j]; - block[i] = s0 * wj - s1 * wi; - block[j] = s0 * wi + s1 * wj; - } -} - -// The frame decoder. - -Decoder::Decoder(size_t channels, uint32_t sample_rate) { - channels_ = std::clamp(channels, 1, 2); - const size_t rate = sample_rate > 44100 ? 48000 : sample_rate > 32000 ? 44100 : sample_rate > 24000 ? 32000 : 24000; - for (size_t i = 0; i < kBlockSizes; ++i) { - const size_t subframe_len = kFrameSamples >> i; - auto& offsets = sfb_offsets_[i]; - size_t band = 1; - for (size_t f = 0; f < kMaxBands - 1; ++f) { - if (offsets[band - 1] >= subframe_len) break; - const size_t offset = ((subframe_len * 2 * tables::kCriticalFreq[f]) / rate + 2) & ~size_t{3}; - if (offset > offsets[band - 1]) { - offsets[band] = offset; - ++band; - } - if (offset >= subframe_len) break; - } - offsets[band - 1] = subframe_len; - num_sfb_[i] = band - 1; - } - for (size_t i = 0; i < kBlockSizes; ++i) { - for (size_t b = 0; b < num_sfb_[i]; ++b) { - const size_t offset = ((sfb_offsets_[i][b] + sfb_offsets_[i][b + 1] - 1) << i) >> 1; - for (size_t x = 0; x < kBlockSizes; ++x) { - size_t v = 0; - while (v + 1 < kMaxBands && (sfb_offsets_[x][v + 1] << x) < offset) ++v; - sf_offsets_[i][x][b] = v; - } - } - } -} - -void Decoder::reset() { ch_ = {}; } - -const char* Decoder::decode(std::span data, size_t bits, std::vector& out) { - // Past the data there are only zeros to read. A count beyond it would never let a stereo tile header overread, - // and its loop takes no subframe on zero bits, so it would spin for good. - const size_t data_bits = data.size() > SIZE_MAX / 8 ? SIZE_MAX : data.size() * 8; - BitReader b{data, 0, std::min(bits, data_bits)}; - const size_t len = b.read(kLengthBits); - const char* result = frame(b, len); - if (result) { - // Whatever the frame held is lost; keep the stream's timing. - for (size_t c = 0; c < channels_; ++c) ch_[c].out.fill(0.0f); - } - out.reserve(out.size() + kFrameSamples * channels_); - for (size_t i = 0; i < kFrameSamples; ++i) - for (size_t c = 0; c < channels_; ++c) out.push_back(to_i16(ch_[c].out[i])); - for (size_t c = 0; c < channels_; ++c) - std::copy(ch_[c].out.begin() + kFrameSamples, ch_[c].out.end(), ch_[c].out.begin()); - return result; -} - -void Decoder::flush(std::vector& out) { - for (size_t i = 0; i < kFrameSamples / 2; ++i) - for (size_t c = 0; c < channels_; ++c) out.push_back(to_i16(ch_[c].out[i])); - reset(); -} - -const char* Decoder::frame(BitReader& b, size_t len) { - if (const char* e = tile_header(b)) return e; - // Post-processing transform. - if (channels_ > 1 && b.bit() && b.bit()) b.read(static_cast(channels_ * channels_ * 4)); - // Dynamic range compression gain, unused. - b.read(8); - if (b.bit()) { - // Trim at start and end, which only WMA Pro files apply. - if (b.bit()) b.read(log2_floor(kFrameSamples * 2)); - if (b.bit()) b.read(log2_floor(kFrameSamples * 2)); - } - parsed_all_subframes_ = false; - for (size_t c = 0; c < channels_; ++c) { - ch_[c].decoded_samples = 0; - ch_[c].cur_subframe = 0; - ch_[c].reuse_sf = false; - } - while (!parsed_all_subframes_) - if (const char* e = subframe(b)) return e; - // FFmpeg flags `len != consumed + 2` but keeps the samples; so do we. - if (b.overread() || b.pos > len) return "frame overread"; - return nullptr; -} - -const char* Decoder::subframe_length(BitReader& b, size_t offset, size_t& len) { - if (offset == kFrameSamples - kMinSubframe) { - len = kMinSubframe; - return nullptr; - } - // Four subframe sizes: a 1-bit "not maximal", then 1 bit of shift. - const uint32_t shift = b.bit() ? 1 + b.read(1) : 0; - len = kFrameSamples >> shift; - if (len < kMinSubframe) return "subframe length"; - return nullptr; -} - -const char* Decoder::tile_header(BitReader& b) { - size_t num_samples[2] = {0, 0}; - bool contains[2] = {false, false}; - size_t channels_for_cur_subframe = channels_; - size_t min_channel_len = 0; - for (size_t c = 0; c < channels_; ++c) ch_[c].num_subframes = 0; - const bool fixed = b.bit(); - for (;;) { - for (size_t c = 0; c < channels_; ++c) - contains[c] = num_samples[c] == min_channel_len && - (fixed || channels_for_cur_subframe == 1 || - min_channel_len == kFrameSamples - kMinSubframe || b.bit()); - size_t subframe_len = 0; - if (const char* e = subframe_length(b, min_channel_len, subframe_len)) return e; - min_channel_len += subframe_len; - for (size_t c = 0; c < channels_; ++c) { - Channel& ch = ch_[c]; - if (contains[c]) { - if (ch.num_subframes >= kMaxSubframes) return "too many subframes"; - ch.subframe_len[ch.num_subframes] = subframe_len; - num_samples[c] += subframe_len; - ++ch.num_subframes; - if (num_samples[c] > kFrameSamples) return "channel longer than a frame"; - } else if (num_samples[c] <= min_channel_len) { - if (num_samples[c] < min_channel_len) { - channels_for_cur_subframe = 0; - min_channel_len = num_samples[c]; - } - ++channels_for_cur_subframe; - } - } - if (min_channel_len >= kFrameSamples || b.overread()) break; - } - if (b.overread()) return "tile header"; - return nullptr; -} - -const char* Decoder::channel_transform(BitReader& b) { - transform_ = false; - if (channels_ == 1) return nullptr; - if (b.bit()) return "channel transform bit"; - // One group holding every channel of the subframe. - if (channels_for_cur_subframe_ == 2) { - if (b.bit()) { - if (b.bit()) return "channel transform type"; - } else { - transform_ = true; - } - } - if (transform_) { - if (!b.bit()) { - for (size_t i = 0; i < num_bands_; ++i) transform_band_[i] = b.bit(); - } else { - transform_band_.fill(true); - } - } - return nullptr; -} - -const char* Decoder::coefficients(BitReader& b, size_t c) { - const Codes& vlc = codes(); - const size_t table = b.bit() ? 1 : 0; - const uint16_t* run = table == 1 ? tables::kCoef1Run : tables::kCoef0Run; - const float* level = table == 1 ? tables::kCoef1Level : tables::kCoef0Level; - const size_t subframe_len = subframe_len_; - Channel& ch = ch_[c]; - bool rl_mode = false; - size_t cur = 0; - size_t num_zeros = 0; - while ((transmit_num_vec_coeffs_ || !rl_mode) && cur + 3 < ch.num_vec_coeffs) { - uint32_t vals[4] = {0, 0, 0, 0}; - const int32_t idx = vlc.vec4.read(b); - if (idx < 0) { - for (size_t i = 0; i < 4; i += 2) { - const int32_t idx2 = vlc.vec2.read(b); - if (idx2 < 0) { - for (size_t k = i; k < i + 2; ++k) { - uint32_t x = static_cast(vlc.vec1.read(b)); - if (x == std::size(tables::kVec1) - 1) x += large_value(b); - vals[k] = x; - } - } else { - vals[i] = static_cast(idx2 >> 4); - vals[i + 1] = static_cast(idx2 & 0xf); - } - } - } else { - vals[0] = static_cast(idx >> 12); - vals[1] = static_cast((idx >> 8) & 0xf); - vals[2] = static_cast((idx >> 4) & 0xf); - vals[3] = static_cast(idx & 0xf); - } - for (const uint32_t v : vals) { - if (v != 0) { - const bool negative = !b.bit(); - ch.coeffs[cur] = negative ? -static_cast(v) : static_cast(v); - num_zeros = 0; - } else { - ch.coeffs[cur] = 0.0f; - ++num_zeros; - rl_mode |= num_zeros > (subframe_len >> 8); - } - ++cur; - } - if (b.overread()) return "vector coefficients"; - } - if (cur < subframe_len) { - std::fill(ch.coeffs.begin() + static_cast(cur), - ch.coeffs.begin() + static_cast(subframe_len), 0.0f); - // ff_wma_run_level_decode, version 1. - const size_t mask = subframe_len - 1; - size_t offset = cur; - while (offset < subframe_len) { - const int32_t code = vlc.coef[table].read(b); - if (code > 1) { - offset += run[code]; - const bool negative = !b.bit(); - const float v = level[code]; - ch.coeffs[offset & mask] = negative ? -v : v; - } else if (code == 1) { - break; - } else { - const int32_t value = static_cast(large_value(b)); - if (b.bit()) { - if (b.bit()) { - // A broken escape ends the channel's coefficients, as in FFmpeg. - if (b.bit()) break; - offset += b.read(esc_len_) + 4; - } else { - offset += b.read(2) + 1; - } - } - const bool negative = !b.bit(); - ch.coeffs[offset & mask] = static_cast(negative ? -value : value); - } - if (b.overread()) return "run level coefficients"; - ++offset; - } - } - return nullptr; -} - -const char* Decoder::scale_factors(BitReader& b) { - const Codes& vlc = codes(); - for (size_t i = 0; i < channels_for_cur_subframe_; ++i) { - const size_t c = channel_indexes_[i]; - const auto sf_offsets = sf_offsets_[table_idx_][ch_[c].table_idx]; - Channel& ch = ch_[c]; - const size_t target = 1 - ch.scale_factor_idx; - ch.scale_factors = target; - if (ch.reuse_sf) { - const auto from = ch.saved_scale_factors[ch.scale_factor_idx]; - for (size_t band = 0; band < num_bands_; ++band) - ch.saved_scale_factors[target][band] = from[sf_offsets[band]]; - } - if (ch.cur_subframe == 0 || b.bit()) { - if (!ch.reuse_sf) { - ch.scale_factor_step = static_cast(b.read(2)) + 1; - int32_t val = 45 / ch.scale_factor_step; - for (size_t band = 0; band < num_bands_; ++band) { - val += vlc.scale.read(b); - ch.saved_scale_factors[target][band] = val; - } - } else { - size_t band = 0; - while (band < num_bands_) { - const int32_t idx = vlc.scale_rl.read(b); - size_t skip = 0; - int32_t val = 0; - bool negative = false; - if (idx == 0) { - const uint32_t code = b.read(14); - skip = (code & 0x3f) >> 1; - val = static_cast(code >> 6); - negative = (code & 1) == 0; - } else if (idx == 1) { - break; - } else { - skip = tables::kScaleRlRun[idx]; - val = tables::kScaleRlLevel[idx]; - negative = !b.bit(); - } - band += skip; - if (band >= num_bands_) return "scale factor run"; - ch.saved_scale_factors[target][band] += negative ? -val : val; - ++band; - } - } - ch.scale_factor_idx = target; - ch.table_idx = table_idx_; - ch.reuse_sf = true; - } - const auto& sf = ch.saved_scale_factors[ch.scale_factors]; - int32_t max = 0; - for (size_t band = 0; band < num_bands_; ++band) max = band == 0 ? sf[band] : std::max(max, sf[band]); - ch.max_scale_factor = max; - } - return nullptr; -} - -const char* Decoder::subframe(BitReader& b) { - size_t offset = kFrameSamples; - size_t subframe_len = kFrameSamples; - int64_t total_samples = static_cast(kFrameSamples * channels_); - for (size_t c = 0; c < channels_; ++c) { - const Channel& ch = ch_[c]; - if (offset > ch.decoded_samples) { - offset = ch.decoded_samples; - subframe_len = ch.subframe_len[std::min(ch.cur_subframe, kMaxSubframes - 1)]; - } - } - channels_for_cur_subframe_ = 0; - for (size_t c = 0; c < channels_; ++c) { - Channel& ch = ch_[c]; - total_samples -= static_cast(ch.decoded_samples); - if (offset == ch.decoded_samples && ch.cur_subframe < ch.num_subframes && - subframe_len == ch.subframe_len[ch.cur_subframe]) { - total_samples -= static_cast(subframe_len); - ch.decoded_samples += subframe_len; - channel_indexes_[channels_for_cur_subframe_] = c; - ++channels_for_cur_subframe_; - } - } - // A tile header that parsed gives every channel subframes of 128 to 512 samples; a length outside that is a - // channel without one, which no subframe can take. - if (channels_for_cur_subframe_ == 0 || subframe_len < kMinSubframe) return "no channel in subframe"; - if (total_samples == 0) parsed_all_subframes_ = true; - table_idx_ = log2_floor(kFrameSamples / subframe_len); - num_bands_ = num_sfb_[table_idx_]; - subframe_len_ = subframe_len; - esc_len_ = log2_floor(subframe_len - 1) + 1; - - // Extended header: fill bits. - if (b.bit()) { - size_t fill = b.read(2); - if (fill == 0) { - const uint32_t len = b.read(4); - fill = static_cast(b.read(len)) + 1; - } - b.pos += fill; - } - if (b.bit()) return "reserved bit"; - if (const char* e = channel_transform(b)) return e; - - bool transmit_coeffs = false; - for (size_t i = 0; i < channels_for_cur_subframe_; ++i) { - const size_t c = channel_indexes_[i]; - ch_[c].transmit_coefs = b.bit(); - transmit_coeffs |= ch_[c].transmit_coefs; - } - if (transmit_coeffs) { - transmit_num_vec_coeffs_ = b.bit(); - if (transmit_num_vec_coeffs_) { - const uint32_t num_bits = log2_floor((subframe_len + 3) / 4) + 1; - for (size_t i = 0; i < channels_for_cur_subframe_; ++i) { - const size_t c = channel_indexes_[i]; - const size_t n = static_cast(b.read(num_bits)) << 2; - if (n > subframe_len) return "vector coefficient count"; - ch_[c].num_vec_coeffs = n; - } - } else { - for (size_t i = 0; i < channels_for_cur_subframe_; ++i) - ch_[channel_indexes_[i]].num_vec_coeffs = subframe_len; - } - // Quantisation step (16-bit samples: 90 * 16 >> 4). - int32_t quant_step = 90; - int32_t step = b.sign_extend(6); - quant_step += step; - if (step == -32 || step == 31) { - const bool negative = step == -32; - int32_t quant = 0; - while (b.pos + 5 < b.end) { - step = static_cast(b.read(5)); - if (step != 31) break; - quant += 31; - } - quant_step += negative ? -(quant + step) : quant + step; - } - if (channels_for_cur_subframe_ == 1) { - ch_[channel_indexes_[0]].quant_step = quant_step; - } else { - const uint32_t modifier_len = b.read(3); - for (size_t i = 0; i < channels_for_cur_subframe_; ++i) { - const size_t c = channel_indexes_[i]; - ch_[c].quant_step = quant_step; - if (b.bit()) - ch_[c].quant_step += modifier_len > 0 ? static_cast(b.read(modifier_len)) + 1 : 1; - } - } - if (const char* e = scale_factors(b)) return e; - } - - for (size_t i = 0; i < channels_for_cur_subframe_; ++i) { - const size_t c = channel_indexes_[i]; - if (ch_[c].transmit_coefs && b.pos < b.end) { - if (const char* e = coefficients(b, c)) return e; - } else { - std::fill(ch_[c].coeffs.begin(), ch_[c].coeffs.begin() + static_cast(subframe_len), 0.0f); - } - } - - // Where this subframe's samples go in the channel output. - const size_t at = offset + kFrameSamples / 2; - if (transmit_coeffs) { - inverse_channel_transform(); - // Output in [-1, 1] for 16-bit streams. - const float scale = 2.0f / static_cast(subframe_len) / 32768.0f; - const auto& sfb = sfb_offsets_[table_idx_]; - float tmp[kFrameSamples] = {}; - for (size_t i = 0; i < channels_for_cur_subframe_; ++i) { - Channel& ch = ch_[channel_indexes_[i]]; - const auto& sf = ch.saved_scale_factors[ch.scale_factors]; - for (size_t band = 0; band < num_bands_; ++band) { - const size_t end = std::min(sfb[band + 1], subframe_len); - const int32_t exp = ch.quant_step - (ch.max_scale_factor - sf[band]) * ch.scale_factor_step; - const float quant = std::pow(10.0f, static_cast(exp) / 20.0f); - for (size_t k = sfb[band]; k < end; ++k) tmp[k] = ch.coeffs[k] * quant; - } - imdct_half({tmp, subframe_len}, {ch.out.data() + at, subframe_len}, scale); - } - } else { - for (size_t i = 0; i < channels_for_cur_subframe_; ++i) { - Channel& ch = ch_[channel_indexes_[i]]; - std::fill(ch.out.begin() + static_cast(at), - ch.out.begin() + static_cast(at + subframe_len), 0.0f); - } - } - - // Window and overlap-add with the previous block. - for (size_t i = 0; i < channels_for_cur_subframe_; ++i) { - Channel& ch = ch_[channel_indexes_[i]]; - size_t winlen = ch.prev_block_len; - size_t start = at - winlen / 2; - if (subframe_len < winlen) { - start += (winlen - subframe_len) / 2; - winlen = subframe_len; - } - window_overlap({ch.out.data() + start, winlen}, window_for(winlen)); - ch.prev_block_len = subframe_len; - } - - for (size_t i = 0; i < channels_for_cur_subframe_; ++i) { - Channel& ch = ch_[channel_indexes_[i]]; - if (ch.cur_subframe >= ch.num_subframes) return "subframe overrun"; - ++ch.cur_subframe; - } - if (b.overread()) return "subframe overread"; - return nullptr; -} - -void Decoder::inverse_channel_transform() { - if (!transform_ || channels_for_cur_subframe_ != 2) return; - const auto& sfb = sfb_offsets_[table_idx_]; - Channel& a = ch_[0]; - Channel& b = ch_[1]; - for (size_t band = 0; band < num_bands_; ++band) { - const size_t end = std::min(sfb[band + 1], subframe_len_); - if (transform_band_[band]) { - for (size_t y = sfb[band]; y < end; ++y) { - const float l = a.coeffs[y], r = b.coeffs[y]; - a.coeffs[y] = l - r; - b.coeffs[y] = l + r; - } - } else { - for (size_t y = sfb[band]; y < end; ++y) { - a.coeffs[y] *= 181.0f / 128.0f; - b.coeffs[y] *= 181.0f / 128.0f; - } - } - } -} - -} // namespace rt::xma diff --git a/runtime/src/xma_decode.h b/runtime/src/xma_decode.h deleted file mode 100644 index 6a983a562..000000000 --- a/runtime/src/xma_decode.h +++ /dev/null @@ -1,154 +0,0 @@ -// XMA2, the console's hardware audio codec: mono or stereo WMA Pro frames of 512 samples per channel, packed into -// 2048-byte packets. -// -// Ported from VIctory (crates/victory-formats/src/xma.rs), GPL-3.0-or-later, by Marvisak and contributors (DexNom -// fork). Leonida is GPL-3.0-or-later. The DexNom snapshot in victory/ is the base; four fixes from VIctory's own -// history in this repository that the snapshot lacks are kept (ba42db643: the frame after packets a frame spans -// whole; d4d182204: a frame's bit count is clamped to its data; 03a6f2290 and 4eb0898b3: payload bytes gathered a byte -// at a time and the inverse transform's rotations built once per size, which give the same bits). -// -// A packet starts with a 32-bit header (MSB first): the number of frames that begin in it (6 bits), the number of -// bits that finish the previous frame before the first new one (15), metadata (3) and how many packets of other -// streams follow before this stream's next packet (8). Every frame starts with its length in bits (15) and ends with a -// "more frames" bit. -// -// The frame decoder follows FFmpeg's wmaprodec.c (LGPL-2.1-or-later, used under GPL-3.0-or-later) restricted to what -// XMA needs: at most two channels, four subframe sizes (512 down to 128), no LFE channel. Pure C++: no OS headers. -// wmaprodec.c's own notices, kept as the LGPL asks: Copyright (c) 2007 Baptiste Coudurier, Benjamin Larsson, Ulion; -// Copyright (c) 2008 - 2011 Sascha Sommer, Benjamin Larsson (the same lines are in third_party/xma/NOTICE.md). -#pragma once - -#include -#include -#include -#include -#include -#include - -namespace rt::xma { - -inline constexpr size_t kPacketBytes = 2048; -inline constexpr size_t kPacketBits = kPacketBytes * 8; -inline constexpr size_t kHeaderBits = 32; -// Samples per channel in one frame. -inline constexpr size_t kFrameSamples = 512; -// Samples per channel in one subframe, the unit of skips and loop ends. -inline constexpr size_t kSubframeSamples = 128; -inline constexpr uint32_t kLengthBits = 15; - -// A packet's header fields. -struct Packet { - uint32_t frames = 0; - uint32_t first_frame_bit = 0; - uint32_t skip = 0; -}; - -// The header of packet `index` of `data`; none when the packet's header is not all inside `data`. -std::optional packet(std::span data, size_t index); - -// One frame's bits gathered out of its packets. -struct Frame { - std::vector data; // the frame from its length field on, MSB first; unused bits of the last byte are 0 - size_t bits = 0; - size_t start = 0; // bit offset in the buffer where it starts - std::optional next; // where the next frame starts; none when the buffer has no further frame -}; - -// Reads the frame starting at bit `start` (a frame start inside a packet's payload) of `data`, a buffer of whole -// packets of one stream. -std::optional read_frame(std::span data, size_t start); - -namespace detail { -struct BitReader; // xma_decode.cpp -} - -// Decodes the frames of one mono or stereo stream. -class Decoder { -public: - // The stream format: the channel count (clamped to 1..2) and the sample rate, which sets the scale factor band - // layout. - Decoder(size_t channels, uint32_t sample_rate); - - size_t channels() const { return channels_; } - - // Forgets the overlap with earlier frames (a new stream or a seek). - void reset(); - - // Decodes one frame (Frame::data, Frame::bits) and appends kFrameSamples interleaved samples per channel to - // `out`, whether it decodes or not. Null on success, else what was wrong; a frame that does not decode leaves - // silence, so the stream keeps its timing. - const char* decode(std::span data, size_t bits, std::vector& out); - - // The overlap left after the last frame, then silence: half a frame of samples per channel. - void flush(std::vector& out); - - static constexpr size_t kMaxBands = 29; - static constexpr size_t kMaxSubframes = 32; - static constexpr size_t kBlockSizes = 3; - -private: - using Bits = detail::BitReader; - - struct Channel { - size_t prev_block_len = kFrameSamples; - bool transmit_coefs = false; - size_t num_subframes = 0; - std::array subframe_len{}; - size_t cur_subframe = 0; - size_t decoded_samples = 0; - int32_t quant_step = 0; - bool reuse_sf = false; - int32_t scale_factor_step = 1; - int32_t max_scale_factor = 0; - std::array, 2> saved_scale_factors{}; - size_t scale_factor_idx = 0; - size_t scale_factors = 0; // which of the two saved sets is in use for this subframe - size_t table_idx = 0; - size_t num_vec_coeffs = 0; - std::array coeffs{}; - // The frame's output, then half a frame of overlap for the next one. - std::array out{}; - }; - - const char* frame(Bits& b, size_t len); - const char* subframe_length(Bits& b, size_t offset, size_t& len); - const char* tile_header(Bits& b); - const char* channel_transform(Bits& b); - const char* coefficients(Bits& b, size_t c); - const char* scale_factors(Bits& b); - const char* subframe(Bits& b); - void inverse_channel_transform(); - - size_t channels_ = 1; - std::array num_sfb_{}; - std::array, kBlockSizes> sfb_offsets_{}; - std::array, kBlockSizes>, kBlockSizes> sf_offsets_{}; - std::array ch_{}; - // Per subframe. - size_t subframe_len_ = kFrameSamples; - size_t channels_for_cur_subframe_ = 0; - std::array channel_indexes_{0, 1}; - size_t num_bands_ = 0; - size_t table_idx_ = 0; - uint32_t esc_len_ = 0; - bool transmit_num_vec_coeffs_ = false; - bool transform_ = false; - std::array transform_band_{}; - bool parsed_all_subframes_ = false; -}; - -// Exposed for the tests. - -// Half-length inverse MDCT as FFmpeg defines it (av_tx MDCT, inverse): `n` coefficients (input.size(), a power of -// two) to the middle `n` samples of the 2n-sample window, negated and scaled by `scale`. Computed as a DCT-IV through -// an n/2-point complex FFT. -void imdct_half(std::span input, std::span out, float scale); - -// ff_sine_windows: the rising half of a sine window of length `n`. -std::vector sine_window(size_t n); - -// FFmpeg's vector_fmul_window in place: the first half of `block` holds the previous block's tail, the second half the -// current block's head. -void window_overlap(std::span block, std::span window); - -} // namespace rt::xma diff --git a/runtime/src/xma_tables.h b/runtime/src/xma_tables.h deleted file mode 100644 index 548255da7..000000000 --- a/runtime/src/xma_tables.h +++ /dev/null @@ -1,226 +0,0 @@ -// Huffman and level tables of the WMA Pro bitstream that XMA2 frames use. -// -// Ported from VIctory (crates/victory-formats/src/xma/tables.rs), GPL-3.0-or-later, by Marvisak and contributors -// (DexNom fork); converted mechanically, value for value. VIctory converted them from FFmpeg's -// libavcodec/wmaprodata.h (LGPL-2.1-or-later, used under GPL-3.0-or-later as that licence allows). Leonida is -// GPL-3.0-or-later. Pairs are (symbol, code length) in canonical code order. -#pragma once - -#include - -namespace rt::xma::tables { - -struct SymbolLength { - uint16_t symbol; - uint8_t length; -}; - -constexpr uint16_t kCriticalFreq[28] = { - 100, 200, 300, 400, 510, 630, 770, 920, 1080, 1270, 1480, 1720, 2000, 2320, 2700, 3150, 3700, 4400, 5300, 6400, - 7700, 9500, 12000, 15500, 20675, 28575, 41375, 63875, -}; - -constexpr SymbolLength kScale[121] = { - {58, 5}, {64, 6}, {66, 7}, {65, 7}, {62, 5}, {63, 6}, {68, 9}, {69, 10}, {54, 15}, {19, 19}, {20, 19}, {21, 19}, - {22, 19}, {23, 19}, {24, 19}, {25, 19}, {26, 19}, {27, 19}, {28, 19}, {29, 19}, {30, 19}, {31, 19}, {32, 19}, - {33, 19}, {34, 19}, {17, 19}, {36, 19}, {37, 19}, {38, 19}, {39, 19}, {40, 19}, {41, 19}, {42, 19}, {43, 19}, - {44, 19}, {45, 19}, {46, 19}, {47, 19}, {48, 19}, {49, 19}, {50, 19}, {51, 19}, {52, 19}, {15, 19}, {16, 19}, - {14, 19}, {13, 19}, {12, 19}, {11, 19}, {10, 19}, {0, 19}, {9, 19}, {8, 19}, {7, 19}, {6, 19}, {5, 19}, {4, 19}, - {55, 13}, {70, 13}, {3, 19}, {2, 19}, {1, 19}, {35, 19}, {71, 19}, {72, 19}, {73, 19}, {74, 19}, {75, 19}, - {76, 19}, {77, 19}, {78, 19}, {79, 19}, {80, 19}, {81, 19}, {82, 19}, {83, 19}, {84, 19}, {85, 19}, {86, 19}, - {87, 19}, {88, 19}, {89, 19}, {90, 19}, {91, 19}, {92, 19}, {93, 19}, {94, 19}, {95, 19}, {96, 19}, {97, 19}, - {98, 19}, {99, 19}, {100, 19}, {101, 19}, {102, 19}, {103, 19}, {104, 19}, {105, 19}, {106, 19}, {107, 19}, - {108, 19}, {109, 19}, {110, 19}, {111, 19}, {112, 19}, {113, 19}, {114, 19}, {115, 19}, {116, 19}, {117, 19}, - {118, 19}, {119, 19}, {120, 19}, {18, 18}, {53, 16}, {56, 11}, {57, 8}, {67, 7}, {61, 3}, {59, 2}, {60, 1}, -}; - -constexpr SymbolLength kScaleRl[120] = { - {103, 7}, {80, 11}, {60, 11}, {18, 10}, {56, 10}, {21, 12}, {90, 12}, {58, 11}, {27, 11}, {69, 12}, {84, 15}, - {48, 15}, {86, 14}, {47, 13}, {19, 10}, {32, 9}, {78, 6}, {5, 5}, {28, 4}, {53, 5}, {9, 7}, {31, 8}, {38, 8}, - {10, 7}, {88, 11}, {25, 12}, {105, 12}, {118, 11}, {23, 12}, {82, 14}, {98, 16}, {110, 16}, {108, 15}, {93, 13}, - {68, 10}, {72, 12}, {97, 12}, {81, 12}, {42, 12}, {64, 8}, {4, 4}, {1, 2}, {7, 6}, {14, 7}, {0, 9}, {55, 9}, - {61, 9}, {117, 10}, {24, 12}, {44, 12}, {67, 12}, {70, 16}, {99, 18}, {96, 21}, {95, 21}, {2, 21}, {77, 21}, - {52, 21}, {111, 21}, {102, 20}, {101, 17}, {46, 15}, {73, 15}, {109, 15}, {51, 14}, {92, 14}, {30, 7}, {11, 7}, - {66, 7}, {15, 8}, {16, 8}, {116, 9}, {65, 9}, {57, 10}, {59, 10}, {115, 9}, {12, 7}, {35, 9}, {17, 9}, {41, 9}, - {20, 11}, {91, 11}, {26, 12}, {75, 15}, {45, 15}, {107, 14}, {83, 14}, {100, 15}, {89, 15}, {43, 11}, {62, 9}, - {37, 9}, {104, 8}, {6, 5}, {39, 8}, {40, 9}, {34, 9}, {79, 7}, {8, 6}, {63, 6}, {87, 12}, {94, 14}, {49, 14}, - {50, 13}, {22, 11}, {119, 10}, {33, 9}, {36, 9}, {113, 11}, {106, 12}, {112, 13}, {71, 15}, {85, 15}, {74, 14}, - {76, 10}, {114, 7}, {29, 5}, {54, 6}, {13, 6}, {3, 2}, -}; - -constexpr uint8_t kScaleRlRun[120] = { - 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 0, 1, 2, 3, - 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, - 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, 24, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 1, 0, 1, 0, 1, -}; - -constexpr uint8_t kScaleRlLevel[120] = { - 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, - 6, 6, 6, 7, 7, 8, 8, 9, 9, -}; - -constexpr uint8_t kCoef0Lens[272] = { - 2, 9, 14, 14, 13, 12, 13, 14, 15, 15, 12, 10, 10, 10, 13, 14, 15, 15, 12, 11, 13, 14, 14, 13, 15, 15, 14, 12, - 12, 8, 10, 10, 15, 15, 14, 13, 14, 14, 13, 15, 20, 20, 19, 21, 21, 20, 19, 17, 17, 18, 18, 15, 15, 13, 12, 14, - 15, 15, 14, 15, 15, 12, 11, 6, 7, 8, 9, 13, 13, 13, 14, 14, 11, 10, 7, 8, 14, 14, 14, 14, 12, 13, 13, 12, 12, - 12, 11, 9, 13, 14, 14, 12, 11, 11, 11, 9, 8, 7, 14, 15, 15, 14, 14, 12, 13, 15, 16, 17, 17, 14, 12, 12, 12, 15, - 15, 14, 14, 14, 13, 13, 9, 9, 11, 11, 10, 7, 6, 13, 15, 15, 14, 14, 14, 13, 14, 15, 15, 13, 14, 14, 14, 14, 10, - 9, 10, 10, 11, 11, 10, 8, 9, 13, 14, 14, 12, 11, 14, 15, 15, 13, 12, 14, 14, 14, 14, 13, 14, 14, 3, 5, 8, 10, - 10, 15, 15, 14, 14, 16, 16, 15, 12, 11, 11, 11, 7, 8, 8, 9, 12, 13, 13, 12, 14, 15, 15, 13, 10, 11, 11, 13, 14, - 14, 13, 14, 14, 11, 10, 13, 15, 15, 14, 12, 11, 4, 6, 6, 8, 12, 12, 12, 13, 13, 12, 13, 13, 14, 14, 13, 13, 13, - 9, 7, 9, 11, 14, 14, 13, 14, 14, 13, 10, 8, 7, 5, 9, 12, 13, 14, 15, 15, 12, 12, 10, 14, 14, 13, 12, 13, 14, 14, - 12, 13, 13, 12, 12, 12, 9, 7, 6, 3, 4, 4, -}; - -constexpr uint16_t kCoef0Syms[272] = { - 2, 25, 111, 94, 69, 58, 87, 93, 136, 135, 59, 37, 34, 36, 82, 182, 120, 138, 195, 45, 168, 216, 178, 86, 140, - 219, 186, 162, 239, 18, 156, 35, 127, 236, 109, 85, 180, 253, 88, 147, 268, 264, 256, 266, 270, 262, 260, 248, - 246, 252, 258, 137, 189, 230, 64, 179, 146, 208, 101, 118, 238, 163, 46, 9, 153, 0, 26, 247, 169, 76, 202, 131, - 194, 38, 13, 19, 132, 106, 191, 97, 65, 198, 77, 62, 66, 164, 48, 27, 81, 183, 102, 60, 47, 49, 159, 227, 20, - 14, 112, 263, 144, 217, 104, 63, 79, 209, 269, 250, 254, 203, 241, 196, 61, 220, 148, 124, 185, 100, 80, 78, - 193, 28, 50, 235, 41, 1, 10, 171, 226, 150, 103, 114, 115, 170, 105, 211, 149, 249, 108, 188, 107, 255, 231, - 155, 42, 40, 55, 160, 39, 21, 29, 215, 234, 184, 228, 51, 116, 142, 145, 172, 165, 181, 130, 113, 117, 89, 128, - 204, 3, 7, 154, 157, 43, 141, 265, 133, 225, 271, 244, 221, 74, 54, 56, 52, 15, 222, 22, 30, 83, 199, 173, 73, - 123, 210, 143, 175, 44, 53, 237, 174, 139, 134, 110, 218, 129, 161, 213, 177, 267, 151, 125, 67, 223, 5, 11, - 192, 23, 214, 243, 166, 200, 176, 68, 224, 187, 257, 261, 232, 96, 251, 31, 16, 32, 57, 207, 121, 91, 126, 119, - 99, 158, 24, 212, 8, 33, 70, 92, 205, 240, 242, 75, 197, 233, 259, 190, 98, 71, 201, 122, 206, 72, 90, 95, 84, - 167, 245, 229, 17, 12, 4, 152, 6, -}; - -constexpr SymbolLength kCoef1[244] = { - {2, 2}, {3, 3}, {102, 3}, {4, 4}, {148, 6}, {134, 9}, {171, 10}, {18, 10}, {11, 8}, {159, 8}, {14, 9}, - {156, 14}, {235, 15}, {61, 15}, {38, 13}, {153, 13}, {48, 14}, {49, 14}, {23, 11}, {203, 13}, {208, 19}, - {204, 19}, {129, 18}, {94, 17}, {87, 16}, {62, 15}, {174, 15}, {147, 15}, {29, 12}, {191, 12}, {64, 15}, - {65, 15}, {146, 14}, {164, 13}, {142, 5}, {132, 4}, {103, 5}, {154, 7}, {165, 9}, {181, 11}, {109, 12}, - {30, 12}, {86, 16}, {92, 16}, {239, 15}, {138, 14}, {39, 13}, {50, 14}, {115, 15}, {238, 21}, {228, 21}, - {236, 21}, {222, 21}, {216, 20}, {226, 20}, {196, 18}, {192, 17}, {120, 16}, {221, 14}, {51, 14}, {24, 11}, - {143, 8}, {7, 6}, {9, 7}, {152, 10}, {136, 12}, {160, 12}, {241, 15}, {66, 15}, {168, 14}, {219, 14}, {113, 14}, - {193, 12}, {19, 10}, {173, 10}, {105, 8}, {149, 9}, {15, 9}, {205, 13}, {207, 13}, {125, 17}, {190, 17}, - {182, 16}, {68, 15}, {70, 15}, {67, 15}, {137, 13}, {31, 12}, {223, 14}, {116, 15}, {210, 19}, {220, 19}, - {198, 18}, {126, 17}, {88, 16}, {41, 13}, {25, 11}, {40, 13}, {73, 15}, {243, 15}, {53, 14}, {195, 12}, - {183, 11}, {225, 14}, {52, 14}, {71, 15}, {121, 16}, {89, 16}, {170, 14}, {55, 14}, {69, 15}, {83, 15}, - {209, 13}, {108, 11}, {32, 12}, {54, 14}, {122, 16}, {184, 16}, {176, 15}, {42, 13}, {12, 8}, {161, 8}, {6, 5}, - {167, 9}, {106, 9}, {20, 10}, {145, 12}, {111, 13}, {43, 13}, {26, 11}, {175, 10}, {107, 10}, {34, 12}, - {33, 12}, {197, 12}, {74, 15}, {128, 17}, {232, 20}, {212, 20}, {224, 19}, {202, 18}, {90, 16}, {57, 14}, - {227, 14}, {97, 16}, {93, 16}, {140, 15}, {185, 11}, {27, 11}, {16, 9}, {158, 11}, {211, 13}, {56, 14}, - {117, 15}, {72, 15}, {166, 13}, {91, 16}, {95, 16}, {80, 15}, {101, 16}, {194, 17}, {127, 17}, {82, 15}, - {21, 10}, {144, 10}, {177, 10}, {151, 6}, {10, 7}, {157, 7}, {8, 6}, {5, 4}, {13, 8}, {0, 9}, {213, 13}, - {46, 13}, {199, 12}, {35, 12}, {162, 12}, {135, 10}, {169, 9}, {45, 13}, {59, 14}, {114, 14}, {44, 13}, - {188, 16}, {186, 16}, {75, 15}, {79, 15}, {118, 15}, {187, 11}, {112, 13}, {139, 14}, {178, 15}, {81, 15}, - {110, 12}, {28, 11}, {163, 8}, {133, 6}, {104, 6}, {17, 9}, {22, 10}, {229, 14}, {172, 14}, {217, 13}, - {201, 12}, {36, 12}, {218, 20}, {242, 22}, {240, 22}, {234, 21}, {230, 19}, {206, 18}, {200, 18}, {214, 18}, - {130, 17}, {131, 17}, {141, 15}, {84, 15}, {76, 15}, {215, 13}, {58, 14}, {231, 14}, {233, 14}, {180, 15}, - {77, 15}, {37, 12}, {189, 11}, {179, 10}, {155, 10}, {47, 13}, {96, 16}, {99, 16}, {119, 15}, {63, 14}, - {237, 14}, {78, 15}, {85, 15}, {60, 14}, {98, 16}, {100, 16}, {124, 16}, {123, 16}, {150, 11}, {1, 7}, -}; - -constexpr uint16_t kCoef0Run[272] = { - 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, - 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, - 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, - 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, - 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, - 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 0, 1, 2, 3, 4, 5, 6, - 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, - 36, 37, 38, 39, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 0, 1, 2, 3, 4, 5, 6, 7, 8, - 9, 0, 1, 2, 3, 4, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, -}; - -constexpr float kCoef0Level[272] = { - 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, - 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, - 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, - 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 4.0f, 4.0f, 4.0f, 4.0f, - 4.0f, 4.0f, 4.0f, 4.0f, 4.0f, 4.0f, 5.0f, 5.0f, 5.0f, 5.0f, 5.0f, 6.0f, 6.0f, 7.0f, 7.0f, 8.0f, 8.0f, 9.0f, - 9.0f, 10.0f, 10.0f, 11.0f, 11.0f, 12.0f, 12.0f, 13.0f, 13.0f, 14.0f, 14.0f, 15.0f, 15.0f, 16.0f, 16.0f, 17.0f, - 17.0f, 18.0f, 18.0f, 19.0f, 19.0f, 20.0f, 20.0f, 21.0f, 21.0f, 22.0f, 22.0f, 23.0f, 23.0f, 24.0f, 24.0f, 25.0f, - 25.0f, 26.0f, 26.0f, 27.0f, 27.0f, 28.0f, -}; - -constexpr uint16_t kCoef1Run[244] = { - 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, - 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, - 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, - 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 0, - 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, - 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, -}; - -constexpr float kCoef1Level[244] = { - 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, - 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, - 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 4.0f, 4.0f, - 4.0f, 4.0f, 4.0f, 4.0f, 5.0f, 5.0f, 5.0f, 6.0f, 6.0f, 6.0f, 7.0f, 7.0f, 7.0f, 8.0f, 8.0f, 9.0f, 9.0f, 10.0f, - 10.0f, 11.0f, 11.0f, 12.0f, 12.0f, 13.0f, 13.0f, 14.0f, 14.0f, 15.0f, 15.0f, 16.0f, 16.0f, 17.0f, 17.0f, 18.0f, - 18.0f, 19.0f, 19.0f, 20.0f, 20.0f, 21.0f, 21.0f, 22.0f, 22.0f, 23.0f, 23.0f, 24.0f, 24.0f, 25.0f, 25.0f, 26.0f, - 26.0f, 27.0f, 27.0f, 28.0f, 28.0f, 29.0f, 29.0f, 30.0f, 30.0f, 31.0f, 31.0f, 32.0f, 32.0f, 33.0f, 33.0f, 34.0f, - 34.0f, 35.0f, 35.0f, 36.0f, 36.0f, 37.0f, 37.0f, 38.0f, 38.0f, 39.0f, 39.0f, 40.0f, 40.0f, 41.0f, 41.0f, 42.0f, - 42.0f, 43.0f, 43.0f, 44.0f, 44.0f, 45.0f, 45.0f, 46.0f, 46.0f, 47.0f, 47.0f, 48.0f, 48.0f, 49.0f, 49.0f, 50.0f, - 51.0f, 52.0f, -}; - -constexpr uint8_t kVec4Lens[127] = { - 1, 6, 8, 10, 10, 10, 10, 8, 8, 10, 10, 9, 8, 8, 9, 12, 12, 11, 12, 12, 11, 9, 9, 8, 8, 9, 9, 8, 8, 9, 9, 12, 12, - 12, 14, 14, 13, 11, 11, 9, 8, 9, 9, 11, 11, 10, 9, 8, 6, 6, 6, 6, 6, 6, 11, 11, 10, 11, 11, 10, 10, 11, 11, 9, - 7, 6, 7, 7, 6, 6, 6, 5, 7, 11, 11, 10, 9, 8, 6, 9, 9, 10, 10, 9, 8, 8, 6, 6, 6, 8, 8, 9, 12, 12, 11, 10, 8, 8, - 8, 10, 10, 10, 10, 9, 9, 8, 10, 11, 11, 9, 8, 8, 8, 9, 9, 10, 11, 12, 12, 9, 9, 9, 8, 8, 7, 7, 7, -}; - -constexpr uint16_t kVec4Syms[127] = { - 0, 4370, 275, 8195, 4146, 12545, 8225, 290, 4625, 515, 20, 8706, 8210, 4355, 4131, 16385, 5121, 8961, 321, 1041, - 51, 4641, 546, 4610, 530, 513, 8451, 4385, 4130, 33, 8211, 5, 66, 4161, 1281, 81, 6, 801, 8196, 8481, 8449, - 4611, 531, 561, 769, 12290, 8226, 19, 4097, 2, 4369, 274, 4354, 4114, 12291, 16641, 12305, 49, 12321, 260, 4100, - 516, 21, 12546, 8466, 4353, 4371, 4626, 257, 18, 17, 1, 4386, 8241, 771, 4865, 8705, 8194, 4098, 12561, 276, 50, - 785, 4116, 8209, 4099, 273, 4113, 258, 259, 4609, 35, 1026, 1025, 16401, 305, 34, 529, 289, 770, 12289, 4, 4145, - 4356, 12306, 8193, 12801, 261, 16386, 4881, 3, 514, 4129, 545, 306, 36, 4101, 65, 20481, 786, 4401, 4866, 8721, - 291, 8450, 8465, 4115, -}; - -constexpr SymbolLength kVec2[137] = { - {19, 5}, {165, 10}, {211, 11}, {46, 11}, {75, 10}, {177, 11}, {12, 11}, {86, 8}, {83, 7}, {38, 7}, {133, 9}, - {178, 10}, {28, 10}, {104, 9}, {73, 9}, {35, 5}, {52, 6}, {113, 9}, {8, 9}, {101, 8}, {69, 7}, {0, 3}, {71, 8}, - {119, 9}, {91, 10}, {179, 10}, {114, 8}, {166, 10}, {10, 10}, {44, 10}, {145, 10}, {66, 6}, {21, 6}, {24, 8}, - {146, 9}, {26, 9}, {65, 7}, {5, 7}, {226, 11}, {225, 12}, {15, 12}, {180, 10}, {147, 9}, {115, 8}, {40, 8}, - {89, 9}, {134, 9}, {84, 7}, {54, 7}, {42, 9}, {60, 10}, {31, 11}, {193, 11}, {181, 10}, {76, 10}, {148, 9}, - {37, 6}, {67, 6}, {33, 6}, {3, 6}, {17, 6}, {2, 6}, {102, 8}, {87, 8}, {116, 8}, {56, 8}, {50, 5}, {20, 5}, - {120, 9}, {58, 9}, {29, 10}, {194, 10}, {135, 9}, {97, 8}, {7, 8}, {105, 9}, {13, 11}, {241, 12}, {16, 12}, - {45, 10}, {149, 9}, {74, 9}, {98, 7}, {23, 7}, {85, 7}, {70, 7}, {195, 10}, {161, 10}, {129, 9}, {72, 8}, - {51, 5}, {36, 5}, {117, 8}, {61, 10}, {11, 10}, {162, 9}, {1, 7}, {4, 6}, {49, 6}, {68, 6}, {9, 9}, {27, 9}, - {130, 8}, {39, 7}, {53, 6}, {99, 7}, {25, 8}, {150, 9}, {90, 9}, {103, 8}, {163, 9}, {196, 10}, {210, 10}, - {136, 9}, {121, 9}, {41, 8}, {131, 8}, {43, 9}, {164, 9}, {118, 8}, {88, 8}, {81, 7}, {6, 7}, {55, 7}, {59, 9}, - {30, 10}, {209, 11}, {14, 11}, {151, 9}, {106, 9}, {82, 6}, {22, 6}, {100, 7}, {132, 8}, {57, 8}, {18, 4}, - {34, 4}, -}; - -constexpr SymbolLength kVec1[101] = { - {7, 5}, {32, 8}, {59, 10}, {60, 10}, {83, 11}, {82, 11}, {62, 10}, {33, 8}, {45, 9}, {61, 10}, {84, 11}, - {85, 11}, {1, 6}, {13, 5}, {19, 6}, {25, 7}, {34, 8}, {46, 9}, {47, 9}, {14, 5}, {6, 5}, {64, 10}, {87, 11}, - {86, 11}, {63, 10}, {88, 11}, {90, 11}, {35, 8}, {26, 7}, {0, 7}, {48, 9}, {65, 10}, {66, 10}, {36, 8}, {15, 5}, - {20, 6}, {91, 11}, {89, 11}, {67, 10}, {49, 9}, {50, 9}, {69, 10}, {92, 11}, {93, 11}, {27, 7}, {5, 5}, {37, 8}, - {68, 10}, {71, 10}, {51, 9}, {52, 9}, {70, 10}, {94, 11}, {96, 11}, {38, 8}, {21, 6}, {16, 5}, {4, 5}, {28, 7}, - {53, 9}, {95, 11}, {97, 11}, {73, 10}, {39, 8}, {29, 7}, {72, 10}, {98, 11}, {99, 11}, {54, 9}, {40, 8}, - {22, 6}, {30, 7}, {55, 9}, {74, 10}, {76, 10}, {56, 9}, {75, 10}, {77, 10}, {17, 5}, {3, 5}, {23, 6}, {41, 8}, - {57, 9}, {78, 10}, {79, 10}, {31, 7}, {10, 4}, {9, 4}, {100, 5}, {2, 5}, {11, 4}, {8, 4}, {18, 5}, {42, 8}, - {58, 9}, {80, 10}, {81, 10}, {43, 8}, {44, 8}, {24, 6}, {12, 4}, -}; - -} // namespace rt::xma::tables diff --git a/runtime/test/app_state_test.cpp b/runtime/test/app_state_test.cpp deleted file mode 100644 index 120b6bd3a..000000000 --- a/runtime/test/app_state_test.cpp +++ /dev/null @@ -1,68 +0,0 @@ -// app_state (shims/app_state.cpp): the title's suspend routines are kept and run with Quiesced = TRUE, on a thread -// of their own, within a deadline. end_title() ends the process, so it is not called here. No game files. -#include - -#include -#include - -#include "shims.h" - -namespace { - -int g_failures = 0; -void check(bool condition, const char* what) { - std::printf("%s: %s\n", condition ? "ok" : "FAIL", what); - if (!condition) ++g_failures; -} - -std::atomic g_calls{0}; -std::atomic g_quiesced{0}; -std::atomic g_thread{0}; -void CALLBACK routine(BOOLEAN quiesced, void* context) { - g_calls += *static_cast(context); - if (quiesced) ++g_quiesced; - g_thread = GetCurrentThreadId(); -} -void CALLBACK slow_routine(BOOLEAN, void*) { Sleep(2000); } - -} // namespace - -int main() { - using Register = DWORD(WINAPI*)(void*, void*, void**); - using Unregister = void(WINAPI*)(void*); - const auto reg = reinterpret_cast( - rt::shims::find("api-ms-win-core-psm-appnotify-l1-1-0.dll", "RegisterAppStateChangeNotification")); - const auto unreg = reinterpret_cast( - rt::shims::find("api-ms-win-core-psm-appnotify-l1-1-0.dll", "UnregisterAppStateChangeNotification")); - check(reg && unreg, "RegisterAppStateChangeNotification and its Unregister are served"); - if (!reg || !unreg) return 1; - - int one = 1, ten = 10; - void* a = nullptr; - void* b = nullptr; - check(reg(reinterpret_cast(&routine), &one, &a) == ERROR_SUCCESS && a && - reg(reinterpret_cast(&routine), &ten, &b) == ERROR_SUCCESS && b && a != b, - "two routines registered, two registrations"); - check(reg(nullptr, &one, &a) == ERROR_INVALID_PARAMETER && reg(reinterpret_cast(&routine), &one, nullptr) == - ERROR_INVALID_PARAMETER, - "a null routine or registration pointer is ERROR_INVALID_PARAMETER"); - check(rt::shims::app_state::registered_routines() == 2, "both are kept"); - - check(rt::shims::app_state::run_suspend_routines(5000) && g_calls == 11 && g_quiesced == 2 && - g_thread != GetCurrentThreadId(), - "a suspend runs every routine with Quiesced = TRUE, on another thread"); - unreg(b); - g_calls = 0; - check(rt::shims::app_state::registered_routines() == 1 && rt::shims::app_state::run_suspend_routines(5000) && - g_calls == 1, - "an unregistered routine no longer runs"); - unreg(a); - - void* slow = nullptr; - reg(reinterpret_cast(&slow_routine), nullptr, &slow); - check(!rt::shims::app_state::run_suspend_routines(100), "a suspend that outlives the deadline is reported late"); - unreg(slow); - - std::printf("%s\n", g_failures ? "FAILED" : "PASSED"); - return g_failures ? 1 : 0; -} diff --git a/runtime/test/aspect_fit_test.cpp b/runtime/test/aspect_fit_test.cpp deleted file mode 100644 index 373dcfa97..000000000 --- a/runtime/test/aspect_fit_test.cpp +++ /dev/null @@ -1,127 +0,0 @@ -// src/aspect_fit.h: LEONIDA_ASPECT's and LEONIDA_PRESENT_SCALE's parsers, the widened display mode, and where a frame -// goes in a window of another shape (pillarbox, letterbox, fill). No window, no GPU, no game data. -#include "../src/aspect_fit.h" - -#include -#include - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -namespace a = leonida::aspect; - -static bool near(double x, double y) { return std::fabs(x - y) < 1e-9; } -static bool box_is(const a::Box& b, int l, int t, int r, int bottom) { - return b.left == l && b.top == t && b.right == r && b.bottom == bottom; -} - -int main() { - // LEONIDA_ASPECT. - a::Request r; - EXPECT(a::parse_request("21:9", &r) && r.kind == a::Kind::ratio && near(r.ratio, 21.0 / 9.0)); - EXPECT(a::parse_request(" 32:9 ", &r) && r.kind == a::Kind::ratio && near(r.ratio, 32.0 / 9.0)); - EXPECT(a::parse_request("43/18", &r) && near(r.ratio, 43.0 / 18.0)); - EXPECT(a::parse_request("2.39", &r) && near(r.ratio, 2.39)); - EXPECT(a::parse_request("2.39:1", &r) && near(r.ratio, 2.39)); - EXPECT(a::parse_request("16:9", &r) && near(r.ratio, 16.0 / 9.0)); - EXPECT(a::parse_request("AUTO", &r) && r.kind == a::Kind::automatic); - EXPECT(a::parse_request("off", &r) && r.kind == a::Kind::none); - EXPECT(a::parse_request("", &r) && r.kind == a::Kind::none); - r = {a::Kind::ratio, 3.0}; - for (const char* bad : {"wide", "21:", ":9", "21:0", "1:2", "5:1", "2,39", "-2", "21x9", "1..2", "."}) - EXPECT(!a::parse_request(bad, &r) && r.kind == a::Kind::ratio && r.ratio == 3.0); // untouched - - EXPECT(near(a::resolve({a::Kind::ratio, 2.0}), 2.0)); - EXPECT(a::resolve({a::Kind::none, 0.0}, 3440, 1440) == 0.0); - EXPECT(near(a::resolve({a::Kind::automatic, 0.0}, 3440, 1440), 3440.0 / 1440.0)); - EXPECT(a::resolve({a::Kind::automatic, 0.0}, 0, 0) == 0.0); - EXPECT(a::resolve({a::Kind::automatic, 0.0}, 1080, 1920) == 0.0); // a portrait monitor is not widened to - - // The widened display mode: the height kept, the width even. - const leonida::DisplayMode uhd; // 3840x2160 - leonida::DisplayMode m = a::widen_display_mode(uhd, 21.0 / 9.0); - EXPECT(m.width == 5040 && m.height == 2160 && m.refresh_hz == 60); - m = a::widen_display_mode(uhd, 32.0 / 9.0); - EXPECT(m.width == 7680 && m.height == 2160); - m = a::widen_display_mode({2560, 1440, 60}, 21.0 / 9.0); - EXPECT(m.width == 3360 && m.height == 1440); - m = a::widen_display_mode({2560, 1440, 60}, 3440.0 / 1440.0); - EXPECT(m.width == 3440 && m.height == 1440); - m = a::widen_display_mode({2560, 1440, 60}, 32.0 / 9.0); - EXPECT(m.width == 5120 && m.height == 1440); - m = a::widen_display_mode({1920, 1080, 60}, 64.0 / 27.0); - EXPECT(m.width == 2560 && m.height == 1080); - m = a::widen_display_mode(uhd, 16.0 / 9.0); // not wider: unchanged - EXPECT(m.width == 3840 && m.height == 2160); - m = a::widen_display_mode(uhd, 1.5); // narrower: unchanged (only widened) - EXPECT(m.width == 3840 && m.height == 2160); - m = a::widen_display_mode({7680, 4320, 60}, 21.0 / 9.0); // past 7680: the height gives way - EXPECT(m.width == 7680 && m.height == 3292); - EXPECT(leonida::parse_display_mode("7680x3292", nullptr)); // still a mode the parser's range holds - m = a::widen_display_mode(uhd, 0.0); - EXPECT(m.width == 3840 && m.height == 2160); - - const a::Size window = a::widen({2560, 1440}, 21.0 / 9.0); - EXPECT(window.width == 3360 && window.height == 1440); - EXPECT(a::widen({0, 1440}, 3.0).width == 0); - - // LEONIDA_PRESENT_SCALE, and its default from LEONIDA_ASPECT. - a::Scaling s = a::Scaling::fit; - EXPECT(a::parse_scaling("Stretch", &s) && s == a::Scaling::stretch); - EXPECT(a::parse_scaling("fit", &s) && s == a::Scaling::fit); - EXPECT(!a::parse_scaling("zoom", &s) && s == a::Scaling::fit); - EXPECT(a::scaling_from(nullptr, nullptr) == a::Scaling::stretch); - EXPECT(a::scaling_from(nullptr, "21:9") == a::Scaling::fit); - EXPECT(a::scaling_from(nullptr, "auto") == a::Scaling::fit); - EXPECT(a::scaling_from(nullptr, "off") == a::Scaling::stretch); - EXPECT(a::scaling_from(nullptr, "nonsense") == a::Scaling::stretch); - EXPECT(a::scaling_from("stretch", "21:9") == a::Scaling::stretch); - EXPECT(a::scaling_from("fit", nullptr) == a::Scaling::fit); - EXPECT(a::scaling_from("bogus", "32:9") == a::Scaling::fit); - - // Where a frame goes. 16:9 in 21:9 (3440x1440): pillarboxed, 2560 wide, centred. - const double sixteen_nine = 16.0 / 9.0; - EXPECT(box_is(a::fit_box(sixteen_nine, 3440, 1440), 440, 0, 3000, 1440)); - // 16:9 in 32:9 (5120x1440): half the width, a quarter each side. - EXPECT(box_is(a::fit_box(sixteen_nine, 5120, 1440), 1280, 0, 3840, 1440)); - // 16:9 in 16:9 at another size: the whole window. - EXPECT(box_is(a::fit_box(sixteen_nine, 1920, 1080), 0, 0, 1920, 1080)); - EXPECT(a::is_whole(a::fit_box(3840.0 / 2160.0, 2560, 1440), 2560, 1440)); - // A frame rendered wide fills a window of its shape (and one that rounds within a pixel of it). - EXPECT(box_is(a::fit_box(3440.0 / 1440.0, 3440, 1440), 0, 0, 3440, 1440)); - EXPECT(box_is(a::fit_box(21.0 / 9.0, 3440, 1474), 0, 0, 3440, 1474)); - // A frame wider than the window: letterboxed. - EXPECT(box_is(a::fit_box(32.0 / 9.0, 1920, 1080), 0, 270, 1920, 810)); - // A window shrunk to fit a work area (3440x1400): the box keeps 16:9 and is centred. - const a::Box shrunk = a::fit_box(sixteen_nine, 3440, 1400); - EXPECT(shrunk.top == 0 && shrunk.bottom == 1400 && shrunk.width() == 2489 && shrunk.left == (3440 - 2489) / 2); - // Nothing to fit: the whole output. - EXPECT(box_is(a::fit_box(0.0, 800, 600), 0, 0, 800, 600)); - EXPECT(box_is(a::fit_box(NAN, 800, 600), 0, 0, 800, 600)); - EXPECT(box_is(a::fit_box(sixteen_nine, 0, 0), 0, 0, 0, 0)); - // Extreme shapes never give an empty box. - EXPECT(a::fit_box(1e-6, 1000, 10).width() == 1 && a::fit_box(1e6, 10, 1000).height() == 1); - - // The output a plane was composed for: its source shape over its placement's. - const float whole[4] = {0.0f, 0.0f, 1.0f, 1.0f}; - EXPECT(near(a::content_aspect(3840, 2160, whole), sixteen_nine)); - const float left_half[4] = {0.0f, 0.0f, 0.5f, 1.0f}; // 8:9 shown in the left half of a 16:9 output - EXPECT(near(a::content_aspect(1920, 2160, left_half), sixteen_nine)); - const float empty[4] = {0.5f, 0.0f, 0.5f, 1.0f}; - EXPECT(a::content_aspect(1920, 2160, empty) == 0.0); - EXPECT(a::content_aspect(0, 2160, whole) == 0.0); - - // Placements into the box: the whole output is the box, a half is half of it. - float px[4]; - const a::Box pillar = a::fit_box(sixteen_nine, 3440, 1440); - a::place(whole, pillar, px); - EXPECT(px[0] == 440.0f && px[1] == 0.0f && px[2] == 3000.0f && px[3] == 1440.0f); - a::place(left_half, pillar, px); - EXPECT(px[0] == 440.0f && px[2] == 1720.0f); - a::place(whole, a::Box{0, 0, 3440, 1440}, px); // stretch: the fractions times the window, as before - EXPECT(px[0] == 0.0f && px[2] == 3440.0f && px[3] == 1440.0f); - - std::printf("aspect_fit: ok\n"); - return 0; -} diff --git a/runtime/test/bcpack_test.cpp b/runtime/test/bcpack_test.cpp deleted file mode 100644 index ff95037e7..000000000 --- a/runtime/test/bcpack_test.cpp +++ /dev/null @@ -1,673 +0,0 @@ -// rt::bcpack (runtime/src/bcpack.h), the BCPack decoder ported from VIctory's victory-formats (GPL-3.0-or-later, -// Marvisak and contributors): SHA-256, table parsing and loading, and decodes of streams this test encodes itself. The -// tables, the encoder and the expected blocks follow VIctory's own tests in victory-formats/src/bcpack.rs and -// victory-hle/src/modules/dstorage.rs. No game data. -// -// bcpack_test tables the test makes (uniform models); needs nothing -// bcpack_test --tables the real format tables: LEONIDA_BCPACK_TABLES, else bcpack-tables.bin next to this -// executable; prints SKIP and exits 77 without them -// bcpack_test --tables --dump DIR -// also writes the streams it built as DIR/.bc with this decoder's output as -// DIR/.out, the layout VIctory's ignored reference_chunks test reads, so that its -// decoder can check them (VICTORY_BCPACK_TABLES, VICTORY_BCPACK_CASES=DIR). Keep DIR outside -// the repository: the blocks can quote dictionary entries of the tables. -#include "bcpack.h" - -#include "bcpack_decode.h" -#include "test_temp_dir.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef _WIN32 -#ifndef NOMINMAX -#define NOMINMAX -#endif -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif -#include -#endif - -namespace { - -namespace bcpack = rt::bcpack; -using Bytes = std::vector; -using Records = std::vector; - -int g_failures = 0; - -void expect(bool ok, const std::string& what) { - if (!ok) { - std::fprintf(stderr, "FAIL: %s\n", what.c_str()); - ++g_failures; - } -} - -bool contains(const std::string& text, const char* part) { - return text.find(part) != std::string::npos; -} - -std::string hex(const std::uint8_t* p, std::size_t n) { - static constexpr char kHex[] = "0123456789abcdef"; - std::string s; - for (std::size_t k = 0; k < n; ++k) { - s += kHex[p[k] >> 4]; - s += kHex[p[k] & 15]; - } - return s; -} - -std::string sha256_hex(const void* data, std::size_t size) { - std::uint8_t digest[32]; - bcpack::sha256(data, size, digest); - return hex(digest, 32); -} - -bool write_file(const std::filesystem::path& path, const Bytes& bytes) { - std::ofstream out(path, std::ios::binary | std::ios::trunc); - out.write(reinterpret_cast(bytes.data()), static_cast(bytes.size())); - return static_cast(out); -} - -Bytes read_file(const std::filesystem::path& path) { - std::ifstream in(path, std::ios::binary); - return Bytes(std::istreambuf_iterator(in), std::istreambuf_iterator()); -} - -void set_env(const char* name, const std::string& value) { -#ifdef _WIN32 - SetEnvironmentVariableA(name, value.c_str()); -#else - setenv(name, value.c_str(), 1); -#endif -} - -// xorshift64, as VIctory's tests use. -struct Random { - std::uint64_t seed; - std::uint64_t next() { - seed ^= seed << 13; - seed ^= seed >> 7; - seed ^= seed << 17; - return seed; - } -}; - -void put16(Bytes& t, unsigned v) { - t.push_back(static_cast(v)); - t.push_back(static_cast(v >> 8)); -} - -void uniform_models(Bytes& t) { - for (unsigned m = 0; m < 128; ++m) { - const unsigned g = m / 16; - for (unsigned b = 0; b < 9; ++b) put16(t, b < g + 2 ? 1u << (15 - g) : 0); - } -} - -// Tables we made: uniform models (model 16 g + shape: g + 2 buckets of 2^(15 - g)), rank tables that pass the -// residual bits through, one BC7 control code (0: mode 6, one subset) and empty dictionaries. VIctory's tables(). -Bytes synthetic_tables() { - Bytes t; - uniform_models(t); - for (unsigned v = 0; v < 256; ++v) t.push_back(static_cast(v & 0x77)); // rank1 - for (unsigned v = 0; v < 64; ++v) t.push_back(static_cast(v)); // rank3a - for (unsigned v = 0; v < 256; ++v) t.push_back(static_cast(v)); // rank3c - for (unsigned v = 0; v < 64; ++v) t.push_back(static_cast((v & 7) | (v >> 3) << 4)); // rank4 - for (unsigned v = 0; v < 64; ++v) t.push_back(static_cast(v)); // rank5 - for (unsigned code = 0; code < 512; ++code) put16(t, code == 0 ? 0x46 : 0); - t.resize(bcpack::kTablesSize, 0); - return t; -} - -// The tables of VIctory's DirectStorage tests: the same models, BC4 index pairs (low 3 bits, next 3 bits), nothing -// else. -Bytes dstorage_tables() { - Bytes t; - uniform_models(t); - t.resize(t.size() + 256 + 64 + 256, 0); - for (unsigned v = 0; v < 64; ++v) t.push_back(static_cast((v & 7) | (v >> 3) << 4)); - t.resize(bcpack::kTablesSize, 0); - return t; -} - -// The test encoder. A model's slots, from the table bytes: symbol 0 owns slots 1 .. f0 - 1, bucket b > 0 holds -// 2^(b-1) symbols of frequency f[b] each. Frequency 0: the model cannot code the symbol. -void slots_of(const Bytes& table, unsigned model, unsigned sym, std::uint32_t* freq, std::uint32_t* start) { - std::uint32_t f[9]; - for (unsigned b = 0; b < 9; ++b) - f[b] = std::uint32_t{table[(model * 9 + b) * 2]} | std::uint32_t{table[(model * 9 + b) * 2 + 1]} << 8; - const unsigned used = model / 16 + 2; - if (sym == 0) { - *freq = f[0] - 1; - *start = 1; - return; - } - const auto k = static_cast(std::bit_width(sym)); - if (k >= used) { - *freq = 0; - *start = 0; - return; - } - std::uint32_t at = f[0]; - for (unsigned b = 1; b < k; ++b) at += f[b] << (b - 1); - *freq = f[k]; - *start = at + (sym - (1u << (k - 1))) * f[k]; -} - -// A lane's symbols as one fragment: header byte `header` (model width * 16 + header), rANS from 2^24, no reset, so the -// lane keeps 2^24 when it ends. VIctory's fragment(), for any model. -Bytes fragment(const Bytes& table, unsigned width, unsigned header, const Bytes& symbols, bool* ok) { - const unsigned model = width * 16 + header; - std::uint32_t x = 1u << 24; - Bytes bytes; - for (auto it = symbols.rbegin(); it != symbols.rend(); ++it) { - std::uint32_t freq = 0, start = 0; - slots_of(table, model, *it, &freq, &start); - if (freq == 0) { - *ok = false; - return {}; - } - while (x >= (freq << 16)) { - bytes.push_back(static_cast(x)); - x >>= 8; - } - x = ((x / freq) << 16) + x % freq + start; - } - for (unsigned k = 0; k < 4; ++k) bytes.push_back(static_cast(x >> (8 * k))); - std::reverse(bytes.begin(), bytes.end()); - if (bytes.size() > 65792) { - *ok = false; - return {}; - } - Bytes out{static_cast(header)}; - if (bytes.size() > 256) { - out[0] |= 0x20; - const std::size_t n = bytes.size() - 257; - out.push_back(static_cast(n)); - out.push_back(static_cast(n >> 8)); - } else { - out.push_back(static_cast(bytes.size() - 1)); - } - out.insert(out.end(), bytes.begin(), bytes.end()); - return out; -} - -struct Queues { - std::deque lane[16]; - Bytes out; - bool starved = false; -}; - -int queue_fetch(void* context, unsigned lane) { - auto* q = static_cast(context); - if (q->lane[lane].empty()) { - q->starved = true; // a parked lane asked for input - return -1; - } - const std::uint8_t b = q->lane[lane].front(); - q->lane[lane].pop_front(); - q->out.push_back(b); - return b; -} - -Bytes concat(const Records& records) { - Bytes all; - for (const Bytes& r : records) all.insert(all.end(), r.begin(), r.end()); - return all; -} - -// Interleaves per-lane fragments the way the decoder takes bytes. A lane that has finished still asks: a filler -// fragment (two payload bytes) brings its state to 2^24 with a byte latched, which parks it for good. Checks that the -// lanes give the records back. VIctory's stream(); `headers` picks each lane's model (nullptr: shape 0). -Bytes stream(const bcpack::Tables& t, const Bytes& table, unsigned bc, const Records& records, - const unsigned* headers = nullptr) { - bcpack::Layout l{}; - if (!bcpack::layout(bc, &l)) { - expect(false, "stream: a layout for BC" + std::to_string(bc)); - return {}; - } - Queues q; - for (unsigned j = 0; j < l.lanes; ++j) { - Bytes symbols; - for (const Bytes& r : records) - for (unsigned h = 0; h < l.per; ++h) symbols.push_back(r[j * l.per + h]); - bool ok = true; - Bytes bytes = fragment(table, l.widths[j], headers ? headers[j] : 0, symbols, &ok); - if (!ok) { - expect(false, "stream: lane " + std::to_string(j) + " fits one fragment of its model"); - return {}; - } - bytes.insert(bytes.end(), {0, 1, 0, 0}); - q.lane[j].assign(bytes.begin(), bytes.end()); - } - Bytes check(records.size() * l.lanes * l.per); - const bcpack::Error error = bcpack::unpack_records(bc, t, records.size(), &queue_fetch, &q, check.data()); - expect(!error, std::string("stream: the lanes decode (") + (error ? error : "") + ")"); - expect(!q.starved, "stream: no parked lane asks for input"); - expect(check == concat(records), "stream: the lanes give the records back, BC" + std::to_string(bc)); - return q.out; -} - -std::uint8_t zigzag(int v) { - return static_cast(v >= 0 ? 2 * v : -2 * v - 1); -} - -constexpr std::uint64_t kBc4Code[8] = {0, 2, 3, 4, 5, 6, 7, 1}; - -// A BC4 block: endpoints as stored, pixel p -> code[(p + add) & 7]. -Bytes bc4_block(unsigned e0, unsigned e1, unsigned add) { - std::uint64_t v = e0 | std::uint64_t{e1} << 8; - for (unsigned p = 0; p < 16; ++p) v |= kBc4Code[(p + add) & 7] << (16 + 3 * p); - Bytes out(8); - for (unsigned k = 0; k < 8; ++k) out[k] = static_cast(v >> (8 * k)); - return out; -} - -// Pseudo-random records that fit each lane's alphabet. -Records random_records(unsigned bc, std::size_t blocks, std::uint64_t seed) { - bcpack::Layout l{}; - bcpack::layout(bc, &l); - Random r{seed}; - Records records(blocks); - for (Bytes& rec : records) { - rec.resize(l.lanes * l.per); - for (unsigned k = 0; k < rec.size(); ++k) - rec[k] = static_cast(r.next() % (std::uint64_t{1} << (l.widths[k / l.per] + 1))); - } - return records; -} - -bcpack::TablesPtr parse(const Bytes& bytes) { - bcpack::Error error = nullptr; - bcpack::TablesPtr t = bcpack::parse_tables(bytes.data(), bytes.size(), &error); - expect(t != nullptr, std::string("synthetic tables parse (") + (error ? error : "") + ")"); - return t; -} - -std::string error_of(bcpack::Error e) { - return e ? e : ""; -} - -void test_sha256() { - const auto check = [](const std::string& message, const char* want) { - expect(sha256_hex(message.data(), message.size()) == want, "SHA-256 of a " + std::to_string(message.size()) + - "-byte message"); - }; - check("", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); - check("abc", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); - // 56 bytes: the length no longer fits the first padding block. - check("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", - "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"); - check("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn" - "hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", - "cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1"); - check(std::string(1000000, 'a'), "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"); -} - -void test_parse() { - bcpack::Error error = nullptr; - const Bytes zeros(16, 0); - expect(!bcpack::parse_tables(zeros.data(), zeros.size(), &error) && contains(error_of(error), "wrong size"), - "16 bytes are refused (wrong size)"); - expect(!bcpack::parse_tables(nullptr, bcpack::kTablesSize, &error), "no bytes are refused"); - Bytes t = synthetic_tables(); - expect(!bcpack::parse_tables(t.data(), t.size() - 1, &error), "one byte short is refused"); - expect(bcpack::parse_tables(t.data(), t.size(), &error) != nullptr, "the synthetic tables parse"); - Bytes no_tiling = t; - no_tiling[0] = 1; - expect(!bcpack::parse_tables(no_tiling.data(), no_tiling.size(), &error) && - contains(error_of(error), "tile 65536"), - "a model that does not tile 65536 is refused"); - Bytes empty_bucket = t; - empty_bucket[2] = 0; // model 0, bucket 1 - empty_bucket[3] = 0; - expect(!bcpack::parse_tables(empty_bucket.data(), empty_bucket.size(), &error) && - contains(error_of(error), "empty bucket"), - "a model with an empty bucket is refused"); - // One-slot buckets where they fit, bucket 0 takes the rest (the narrowest windows); VIctory's narrow tables. - Bytes narrow = t; - for (unsigned m = 0; m < 128; ++m) { - const unsigned used = m / 16 + 2; - unsigned rest = 1u << 16; - for (unsigned b = 1; b < used; ++b) rest -= 1u << (b - 1); - for (unsigned b = 0; b < used; ++b) { - const unsigned f = b == 0 ? rest : 1; - narrow[(m * 9 + b) * 2] = static_cast(f); - narrow[(m * 9 + b) * 2 + 1] = static_cast(f >> 8); - } - } - expect(bcpack::parse_tables(narrow.data(), narrow.size(), &error) != nullptr, "one-slot buckets parse"); -} - -void test_layouts() { - const struct { - unsigned bc, lanes, per, block; - } want[] = {{1, 12, 1, 8}, {3, 12, 2, 16}, {4, 12, 1, 8}, {5, 12, 2, 16}, {6, 16, 2, 16}, {7, 16, 2, 16}}; - for (const auto& w : want) { - bcpack::Layout l{}; - expect(bcpack::layout(w.bc, &l) && l.lanes == w.lanes && l.per == w.per && l.block_bytes == w.block, - "the BC" + std::to_string(w.bc) + " layout"); - } - bcpack::Layout l{}; - expect(!bcpack::layout(2, &l) && !bcpack::layout(0, &l) && !bcpack::layout(8, &l), "no layout for BC2, 0 or 8"); -} - -// Two BC4 blocks from VIctory's test encoder, as its DirectStorage tests keep them: endpoints 10, -3 with indices -// p -> p & 7, then the same block plus 1 everywhere. Fixed bytes, so this checks the decoder without the encoder here. -void test_fixed_bc4_stream() { - static constexpr std::uint8_t kStream[88] = { - 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 4, 4, 4, 4, 1, 1, 1, 1, 0x10, 0x10, 0x10, 0x10, 2, 1, - 0, 0, 0, 0, 0, 0, 0, 0, 0x14, 5, 0x20, 0x68, 0xb0, 0xf8, 3, 3, 2, 2, 0x24, 0x24, 0x24, - 0x24, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 4, 0x10, 0x10, 0x10, 0x10, 0, 0, 0, 0, - 0x20, 0x68, 0xb0, 0xf8, 0x24, 0x24, 0x24, 0x24, 0, 0, 0, 0, 0, 0, 0, 0, - }; - const bcpack::TablesPtr t = parse(dstorage_tables()); - if (!t) return; - Bytes want = bc4_block(138, 125, 0); - const Bytes second = bc4_block(139, 126, 1); - want.insert(want.end(), second.begin(), second.end()); - Bytes dst(16, 0xcc); - const bcpack::Error error = bcpack::decode(4, kStream, sizeof kStream, dst.data(), dst.size(), *t); - expect(!error && dst == want, "VIctory's fixed two-block BC4 stream (" + error_of(error) + ")"); - // Bytes after the last one the lanes need are ignored. - Bytes longer(kStream, kStream + sizeof kStream); - longer.resize(longer.size() + 100, 0xee); - std::fill(dst.begin(), dst.end(), std::uint8_t{0}); - expect(!bcpack::decode(4, longer.data(), longer.size(), dst.data(), dst.size(), *t) && dst == want, - "trailing bytes are ignored"); -} - -void test_bc4_references() { - const Bytes table = synthetic_tables(); - const bcpack::TablesPtr t = parse(table); - if (!t) return; - // Block 0: endpoints 10, -3 (+128 stored), indices p -> p & 7. - Bytes b0 = {0, 0, zigzag(10), zigzag(-3)}; - for (unsigned k = 0; k < 8; ++k) b0.push_back(static_cast(((2 * k) & 7) | ((2 * k + 1) & 7) << 3)); - // Block 1 refers to block 0 for both: residual endpoints +1, +1; indices +1. - Bytes b1 = {0, 1, zigzag(1), zigzag(1)}; - for (unsigned k = 0; k < 8; ++k) b1.push_back(1 | 1 << 3); - const Bytes src = stream(*t, table, 4, {b0, b1}); - Bytes dst(16); - const bcpack::Error error = bcpack::decode(4, src.data(), src.size(), dst.data(), dst.size(), *t); - expect(!error, "BC4 blocks with and without references decode (" + error_of(error) + ")"); - expect(Bytes(dst.begin(), dst.begin() + 8) == bc4_block(138, 125, 0), "BC4 block 0"); - expect(Bytes(dst.begin() + 8, dst.end()) == bc4_block(139, 126, 1), "BC4 block 1 builds on block 0"); -} - -void test_round_trips() { - const Bytes table = synthetic_tables(); - const bcpack::TablesPtr t = parse(table); - if (!t) return; - // Long fragments (over 256 payload bytes) on the wide lanes, with VIctory's records. - Records records; - for (unsigned i = 0; i < 400; ++i) { - Bytes r = {0, 0, static_cast(i * 7), static_cast(i * 13)}; - for (unsigned k = 0; k < 8; ++k) r.push_back(static_cast((i + k) * 5 % 64)); - records.push_back(r); - } - stream(*t, table, 4, records); - // Every layout, short and long fragments. - for (const unsigned bc : {1u, 3u, 4u, 5u, 6u, 7u}) - for (const std::size_t blocks : {1u, 2u, 17u, 300u, 1000u}) - stream(*t, table, bc, random_records(bc, blocks, 0x9e3779b97f4a7c15ull)); - Bytes none; - expect(bcpack::unpack_records(1, *t, 0, &queue_fetch, nullptr, none.data()) == nullptr, "no blocks, no input"); -} - -void test_bc7_mode6() { - const Bytes table = synthetic_tables(); - const bcpack::TablesPtr t = parse(table); - if (!t) return; - // Control code 0 -> mode 6; endpoints R 8 bits (p-bit low), G B A 7 bits. - Bytes s(32, 0); - s[4] = zigzag(0x55); // R0 = 0x55: field 0x2a, p-bit 1 - s[5] = zigzag(-1); // R1 = 0xff (8 bits) - s[6] = zigzag(3); - s[10] = zigzag(0x7f >> 1); - const Bytes src = stream(*t, table, 7, {s}); - Bytes dst(16); - const bcpack::Error error = bcpack::decode(7, src.data(), src.size(), dst.data(), dst.size(), *t); - // Mode 6 (7 bits), R0 R1 G0 G1 B0 B1 A0 A1 at 7 bits each, then the two p-bits; the indices are all 0. - std::uint64_t lo = 0, hi = 0; - unsigned at = 0; - const auto put = [&](std::uint64_t v, unsigned n) { - for (unsigned k = 0; k < n; ++k, ++at) - if (v >> k & 1) (at < 64 ? lo : hi) |= std::uint64_t{1} << (at & 63); - }; - put(1 << 6, 7); - for (const unsigned v : {0x2au, 0x7fu, 3u, 0u, 0u, 0u, 0x3fu, 0u}) put(v, 7); - put(1, 1); - put(1, 1); - Bytes want(16); - for (unsigned k = 0; k < 8; ++k) { - want[k] = static_cast(lo >> (8 * k)); - want[8 + k] = static_cast(hi >> (8 * k)); - } - expect(!error && dst == want, "a BC7 mode 6 block (" + error_of(error) + ")"); -} - -void test_malformed() { - const Bytes table = synthetic_tables(); - const bcpack::TablesPtr t = parse(table); - if (!t) return; - Records records; - for (unsigned i = 0; i < 64; ++i) - records.push_back({0, 0, static_cast(i), static_cast(i), 1, 2, 3, 4, 5, 6, 7, 8}); - const Bytes src = stream(*t, table, 4, records); - Bytes dst(64 * 8); - expect(!bcpack::decode(4, src.data(), src.size(), dst.data(), dst.size(), *t), "64 BC4 blocks decode"); - expect(bcpack::decode(4, src.data(), src.size() / 2, dst.data(), dst.size(), *t) != nullptr, "truncated: error"); - // Headers promising more payload than the stream holds. (Other corrupt headers decode to garbage: the format has - // no redundancy.) - Bytes headers(8, 0x30); - headers.resize(16, 0xff); - expect(bcpack::decode(4, headers.data(), headers.size(), dst.data(), 8, *t) != nullptr, "headers only: error"); - expect(bcpack::decode(4, nullptr, 0, dst.data(), dst.size(), *t) != nullptr, "no input: error"); - // Destination not a whole number of blocks, empty, more blocks than coded, missing. - expect(bcpack::decode(4, src.data(), src.size(), dst.data(), 12, *t) != nullptr, "12 bytes of BC4: error"); - expect(bcpack::decode(4, src.data(), src.size(), dst.data(), 0, *t) != nullptr, "no blocks: error"); - Bytes more(65 * 8); - expect(bcpack::decode(4, src.data(), src.size(), more.data(), more.size(), *t) != nullptr, - "more blocks than coded: error"); - expect(bcpack::decode(4, src.data(), src.size(), nullptr, dst.size(), *t) != nullptr, "no destination: error"); - expect(bcpack::decode(4, nullptr, src.size(), dst.data(), dst.size(), *t) != nullptr, "no source: error"); - expect(bcpack::decode(7, src.data(), src.size(), dst.data(), 24, *t) != nullptr, "24 bytes of BC7: error"); - // Unsupported formats. - for (const unsigned bc : {0u, 2u, 8u, 0x104u}) - expect(contains(error_of(bcpack::decode(bc, src.data(), src.size(), dst.data(), dst.size(), *t)), - "unsupported"), - "BC" + std::to_string(bc) + " is unsupported"); - // A BC7 block whose control code the tables leave unused, and a BC6H block whose mode is out of range. - Bytes s(32, 0); - s[30] = 1; - const Bytes bad7 = stream(*t, table, 7, {s}); - expect(contains(error_of(bcpack::decode(7, bad7.data(), bad7.size(), dst.data(), 16, *t)), "control code"), - "an unused BC7 control code is an error"); - s[30] = 14; - const Bytes bad6 = stream(*t, table, 6, {s}); - expect(contains(error_of(bcpack::decode(6, bad6.data(), bad6.size(), dst.data(), 16, *t)), "mode"), - "BC6H mode 15 is an error"); -} - -// Noise must never crash, whatever it decodes to. -void test_noise(const bcpack::Tables& t) { - Random r{0x2545f4914f6cdd1dull}; - Bytes dst(16 * 40); - unsigned decoded = 0; - for (unsigned round = 0; round < 300; ++round) { - Bytes src(round * 7 % 900); - for (std::uint8_t& b : src) b = static_cast(r.next()); - for (const unsigned bc : {1u, 3u, 4u, 5u, 6u, 7u}) - decoded += bcpack::decode(bc, src.data(), src.size(), dst.data(), 16 * (1 + round % 40), t) ? 0 : 1; - } - std::printf("noise: %u of 1800 random streams decoded without an error\n", decoded); -} - -void test_load(const std::filesystem::path& dir) { - std::string why; - expect(!bcpack::load_tables(dir / "missing.bin", &why) && contains(why, "cannot open"), "a missing file: " + why); - write_file(dir / "synthetic.bin", synthetic_tables()); - expect(!bcpack::load_tables(dir / "synthetic.bin", &why) && contains(why, "SHA-256") && - contains(why, bcpack::kTablesSha256), - "tables of the right size but another SHA-256 are refused: " + why); - write_file(dir / "short.bin", Bytes(100, 0)); - expect(!bcpack::load_tables(dir / "short.bin", &why) && contains(why, "100 bytes"), "a 100-byte file: " + why); - write_file(dir / "long.bin", Bytes(bcpack::kTablesSize + 1, 0)); - expect(!bcpack::load_tables(dir / "long.bin", &why) && contains(why, "larger than"), "a longer file: " + why); -} - -// Without tables the entry point refuses every request (VIctory: every BCPack request fails). -void test_entry_point_without_tables(const std::filesystem::path& dir) { - set_env(bcpack::kTablesVariable, (dir / "missing.bin").string()); - expect(bcpack::tables_path() == dir / "missing.bin", "LEONIDA_BCPACK_TABLES names the table file"); - std::uint8_t dst[8] = {}; - const std::uint8_t src[4] = {}; - expect(!leonida_bcpack_decode(4, src, sizeof src, dst, sizeof dst), "no tables: leonida_bcpack_decode is false"); - expect(bcpack::process_tables() == nullptr, "no tables: process_tables is null"); -} - -// Records the real tables accept: BC6H modes 1-14, BC7 control codes the tables define. -Records real_records(const Bytes& table, unsigned bc, std::size_t blocks, std::uint64_t seed) { - Records records = random_records(bc, blocks, seed); - Random r{seed ^ 0x5bd1e995}; - constexpr std::size_t kCtrl = 128 * 9 * 2 + 256 + 64 + 256 + 64 + 64; - for (Bytes& s : records) { - if (bc == 6) s[30] = static_cast(r.next() % 14); - if (bc == 7) { - for (;;) { - s[30] = static_cast(r.next() % 32); - s[31] = static_cast(r.next() % 32); - const std::size_t at = kCtrl + 2 * (((s[31] & 15u) << 5) | (s[30] & 31u)); - if (table[at] | table[at + 1]) break; - } - } - } - return records; -} - -// SHA-256 of the blocks VIctory's decoder makes of the streams below (2000 blocks per format, built against the real -// tables): its reference_chunks test passes on the files --dump writes. -struct Golden { - unsigned bc; - const char* sha256; -}; -constexpr Golden kGolden[] = { - {1, "dfef7317a1b0f3db05575b1f6ed75dcb7bd1aae2c5c587c364501818d4e7752f"}, - {3, "685ba5fe566f870497ca8d024ad243c75cf2c626df80fe8fe7abbd2063385c79"}, - {4, "5e9c1b2dcce6f8b8e3b6c2801b353829e082c9be107a75b6407db7324f745758"}, - {5, "7287431529fad53f6611bbebee3b35fb36bc50ee37df8f2aa4eb946a0e5c39ed"}, - {6, "f2d6ff19566b79492df0e9fc600386059552444db1e99e18592fdcbcaee604cc"}, - {7, "75a9d7370d55872d24573a2a6a993f5a4a46d9d1648f4e3fb7db6c8b3aef0817"}, -}; - -int run_with_real_tables(const std::filesystem::path& scratch, const char* dump) { - const std::filesystem::path path = bcpack::tables_path(); - std::error_code ec; - if (path.empty() || !std::filesystem::is_regular_file(path, ec)) { - std::printf("SKIP (no BCPack format tables: set %s or put %s next to the test)\n", bcpack::kTablesVariable, - bcpack::kTablesFile); - return 77; - } - std::string why; - const bcpack::TablesPtr t = bcpack::load_tables(path, &why); - expect(t != nullptr, "the format tables load: " + why); - if (!t) return 1; - const Bytes table = read_file(path); - expect(sha256_hex(table.data(), table.size()) == [] { - std::string s = bcpack::kTablesSha256; - for (char& c : s) c = static_cast(c >= 'A' && c <= 'F' ? c - 'A' + 'a' : c); - return s; - }(), "the file hashes to the pinned SHA-256"); - // A changed byte or a shorter file is refused. - Bytes changed = table; - changed[changed.size() / 2] ^= 1; - write_file(scratch / "changed.bin", changed); - expect(!bcpack::load_tables(scratch / "changed.bin", &why) && contains(why, "SHA-256"), - "one changed byte is refused: " + why); - write_file(scratch / "short.bin", Bytes(table.begin(), table.end() - 1)); - expect(!bcpack::load_tables(scratch / "short.bin", &why), "one byte short is refused: " + why); - const bcpack::Tables* process = bcpack::process_tables(); - expect(process != nullptr, "process_tables loads them"); - // Streams built against the real models: every lane on its own model shape. - unsigned headers[16]; - for (unsigned j = 0; j < 16; ++j) headers[j] = (j * 5 + 3) & 15; - for (const Golden& g : kGolden) { - bcpack::Layout l{}; - bcpack::layout(g.bc, &l); - const Records records = real_records(table, g.bc, 2000, 0x9e3779b97f4a7c15ull + g.bc); - const Bytes src = stream(*t, table, g.bc, records, headers); - Bytes dst(2000 * l.block_bytes), entry(dst.size()); - const bcpack::Error error = bcpack::decode(g.bc, src.data(), src.size(), dst.data(), dst.size(), *t); - expect(!error, "BC" + std::to_string(g.bc) + " against the real tables decodes (" + error_of(error) + ")"); - expect(process && leonida_bcpack_decode(g.bc, src.data(), src.size(), entry.data(), entry.size()) && - entry == dst, - "leonida_bcpack_decode gives the same blocks, BC" + std::to_string(g.bc)); - expect(bcpack::decode(g.bc, src.data(), src.size() - 64, dst.data(), dst.size(), *t) != nullptr, - "a truncated BC" + std::to_string(g.bc) + " stream is an error"); - bcpack::decode(g.bc, src.data(), src.size(), dst.data(), dst.size(), *t); - const std::string got = sha256_hex(dst.data(), dst.size()); - std::printf("BC%u: %zu bytes packed, blocks %s\n", g.bc, src.size(), got.c_str()); - if (*g.sha256) expect(got == g.sha256, "BC" + std::to_string(g.bc) + " blocks are VIctory's"); - if (dump) { - const std::string name = "synthetic_bc" + std::to_string(g.bc); - write_file(std::filesystem::path(dump) / (name + ".bc" + std::to_string(g.bc)), src); - write_file(std::filesystem::path(dump) / (name + ".out"), dst); - } - } - test_noise(*t); - return 0; -} - -} // namespace - -int main(int argc, char** argv) { - bool tables = false; - const char* dump = nullptr; - for (int k = 1; k < argc; ++k) { - if (std::strcmp(argv[k], "--tables") == 0) { - tables = true; - } else if (std::strcmp(argv[k], "--dump") == 0 && k + 1 < argc) { - dump = argv[++k]; - } else { - std::fprintf(stderr, "usage: bcpack_test [--tables [--dump DIR]]\n"); - return 2; - } - } - const testfiles::ScratchDir scratch("leonida_bcpack_test"); - int result = 0; - if (tables) { - result = run_with_real_tables(scratch.path(), dump); - if (result == 77) return result; - } else { - test_sha256(); - test_parse(); - test_layouts(); - test_fixed_bc4_stream(); - test_bc4_references(); - test_round_trips(); - test_bc7_mode6(); - test_malformed(); - if (const bcpack::TablesPtr t = parse(synthetic_tables())) test_noise(*t); - test_load(scratch.path()); - test_entry_point_without_tables(scratch.path()); - } - if (g_failures || result) { - std::fprintf(stderr, "%d failure(s)\n", g_failures); - return 1; - } - std::printf("bcpack_test%s: all passed\n", tables ? " --tables" : ""); - return 0; -} diff --git a/runtime/test/chad_dsp_test.cpp b/runtime/test/chad_dsp_test.cpp deleted file mode 100644 index cd5efd79e..000000000 --- a/runtime/test/chad_dsp_test.cpp +++ /dev/null @@ -1,150 +0,0 @@ -// chad.dll through the registry: connect limits, stream shapes, the stream limit, and the status block a submitted -// command completes. The flow follows VIctory's test (crates/victory-hle/src/modules/dsp.rs, -// convolution_stream_as_the_title_drives_it), GPL-3.0-or-later, by Marvisak and contributors (DexNom fork); Leonida is -// GPL-3.0-or-later. No game data. -#include - -#include -#include -#include -#include - -#include "shims.h" - -namespace { - -int g_checks = 0; -int g_failures = 0; - -void check(bool condition, const char* what) { - ++g_checks; - std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); - if (!condition) ++g_failures; -} - -constexpr HRESULT kPointer = static_cast(0x80004003u); -constexpr HRESULT kOutOfMemory = static_cast(0x8007000Eu); -constexpr HRESULT kInvalidArg = static_cast(0x80070057u); - -// Test mirrors of the measured layouts (VIctory dsp.rs). -#pragma pack(push, 1) -struct StreamDesc { - uint32_t kind, options, frames, channels, ir_floats; - const float* ir; -}; -#pragma pack(pop) -struct Status { - uint32_t submitted, completed, reserved; - HRESULT result; -}; -struct Command { - float gains[2]; - const float* input; - float* output; - uint64_t reserved; -}; -static_assert(sizeof(StreamDesc) == 0x1c && sizeof(Status) == 16 && sizeof(Command) == 0x20); - -using ConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t, uint32_t, uint32_t, void**); -using DisconnectFn = HRESULT(__stdcall*)(void*); -using ActivateFn = HRESULT(__stdcall*)(void*, const StreamDesc*, const Status**, void**); -using DeactivateFn = HRESULT(__stdcall*)(void*); -using SubmitFn = HRESULT(__stdcall*)(void*, const Command*, uint32_t*); - -} // namespace - -int main() { - std::printf("chad_dsp_test: registered chad.dll shim\n"); - const auto connect = reinterpret_cast(rt::shims::find("chad.dll", "XDspConnectWithMaximumStreamLimit")); - const auto disconnect = reinterpret_cast(rt::shims::find("chad.dll", "XDspDisconnect")); - const auto activate = reinterpret_cast(rt::shims::find("chad.dll", "XDspActivate")); - const auto deactivate = reinterpret_cast(rt::shims::find("chad.dll", "XDspDeactivate")); - const auto submit = reinterpret_cast(rt::shims::find("chad.dll", "XDspSubmitCommand")); - check(connect && disconnect && activate && deactivate && submit, "all five exports are registered"); - check(rt::shims::owns_dll("chad.dll"), "the registry owns chad.dll"); - if (!connect || !disconnect || !activate || !deactivate || !submit) return 1; - - std::vector base(0x100000); - void* dsp = nullptr; - check(connect(nullptr, 0x100000, 24, 0x80, 1, &dsp) == kInvalidArg, "connect: no memory"); - check(connect(base.data(), 0xffff, 24, 0x80, 1, &dsp) == kInvalidArg, "connect: under 64 KiB"); - check(connect(base.data(), 0x1F400001, 24, 0x80, 1, &dsp) == kInvalidArg, "connect: over 500 MiB"); - check(connect(base.data(), 0x100000, 0x81, 0x80, 1, &dsp) == kInvalidArg, "connect: over 128 s of response"); - check(connect(base.data(), 0x100000, 24, 0x101, 1, &dsp) == kInvalidArg, "connect: over 256 streams"); - check(connect(base.data(), 0x100000, 24, 0x80, 3, &dsp) == kInvalidArg, "connect: over two channels"); - check(connect(base.data(), 0x100000, 24, 0x80, 1, nullptr) == kPointer, "connect: no out pointer"); - check(connect(base.data(), 0x100000, 24, 0x80, 1, &dsp) == S_OK && dsp, "connect as VIctory's test does"); - - // Stereo convolution with option 2, as the title asks for. - std::vector ir(0x800); - const StreamDesc desc{1, 2, 0x400, 2, 0x800, ir.data()}; - const Status* status = nullptr; - void* stream = nullptr; - check(activate(dsp, &desc, nullptr, &stream) == kPointer, "activate: no status pointer"); - check(activate(dsp, &desc, &status, nullptr) == kPointer, "activate: no stream pointer"); - check(activate(nullptr, &desc, &status, &stream) == kInvalidArg, "activate: no connection"); - check(activate(dsp, nullptr, &status, &stream) == kInvalidArg, "activate: no description"); - check(activate(dsp, &desc, &status, &stream) == S_OK && status && stream, "activate a stereo convolution"); - check(status->submitted == 0 && status->completed == 0 && status->result == S_OK, "a fresh status block"); - - std::vector output(0x800 + 16, 1.0f); - const std::vector input(0x800, 0.5f); - const Command command{{1.0f, 1.0f}, input.data(), output.data(), 0}; - uint32_t ticket = 0; - check(submit(stream, &command, &ticket) == S_OK && ticket == 1, "submit: ticket 1"); - check(status->completed == ticket && status->submitted == ticket && status->result == S_OK, - "completed at once: the status names the ticket"); - bool silent = true, guarded = true; - for (size_t i = 0; i < 0x800; ++i) silent &= output[i] == 0.0f; - for (size_t i = 0x800; i < output.size(); ++i) guarded &= output[i] == 1.0f; - check(silent, "the output block is silence (placeholder transform)"); - check(guarded, "only one block of the stream written"); - check(submit(stream, &command, nullptr) == S_OK && status->completed == 2, "a second command, no ticket asked"); - const Command no_output{{1.0f, 1.0f}, input.data(), nullptr, 0}; - check(submit(stream, &no_output, &ticket) == S_OK && ticket == 3 && status->completed == 3, "a command without output"); - check(submit(nullptr, &command, &ticket) == kInvalidArg && submit(stream, nullptr, &ticket) == kInvalidArg, - "submit: null stream or command"); - check(deactivate(stream) == S_OK, "deactivate"); - check(deactivate(nullptr) == kInvalidArg, "deactivate: null"); - - // Mono streams refuse stereo options; convolutions take 512 or 1024 frames and not option 4; other transforms are - // mono only, of 512 to 2048 frames. - const auto shape = [&](uint32_t kind, uint32_t options, uint32_t frames, uint32_t channels) { - const StreamDesc d{kind, options, frames, channels, 0, nullptr}; - void* s = nullptr; - const HRESULT hr = activate(dsp, &d, &status, &s); - if (hr == S_OK) deactivate(s); - return hr; - }; - check(shape(1, 2, 0x400, 1) == kInvalidArg, "a mono convolution with option 2"); - check(shape(1, 8, 0x400, 1) == kInvalidArg, "a mono convolution with option 8"); - check(shape(1, 0, 0x400, 1) == S_OK, "a mono convolution"); - check(shape(1, 0, 0x200, 2) == S_OK, "a stereo convolution of 512 frames"); - check(shape(1, 0, 0x800, 2) == kInvalidArg, "a convolution of 2048 frames"); - check(shape(1, 4, 0x400, 2) == kInvalidArg, "a convolution with option 4"); - check(shape(1, 0, 0x400, 3) == kInvalidArg, "three channels"); - check(shape(2, 0, 0x400, 1) == S_OK, "a mono transform"); - check(shape(2, 4, 0x800, 1) == S_OK, "a transform of 2048 frames with option 4"); - check(shape(2, 0, 0x400, 2) == kInvalidArg, "a stereo transform"); - check(shape(2, 0, 0x100, 1) == kInvalidArg, "a transform of 256 frames"); - - // The stream limit, and a stream freed for another. - void* limited = nullptr; - check(connect(base.data(), 0x10000, 0, 2, 2, &limited) == S_OK, "connect for two streams"); - const StreamDesc mono{2, 0, 0x200, 1, 0, nullptr}; - void* a = nullptr; - void* b = nullptr; - void* c = nullptr; - check(activate(limited, &mono, &status, &a) == S_OK && activate(limited, &mono, &status, &b) == S_OK, - "two streams"); - check(activate(limited, &mono, &status, &c) == kOutOfMemory, "a third: out of memory"); - check(deactivate(a) == S_OK && activate(limited, &mono, &status, &c) == S_OK, "one freed, another activated"); - deactivate(b); - deactivate(c); - check(disconnect(limited) == S_OK, "disconnect the limited connection"); - check(disconnect(dsp) == S_OK, "disconnect"); - check(disconnect(nullptr) == kInvalidArg, "disconnect: null"); - - std::printf("chad_dsp_test complete: %d checks, %d failures\n", g_checks, g_failures); - return g_failures ? 1 : 0; -} diff --git a/runtime/test/check_tiny_present.py b/runtime/test/check_tiny_present.py deleted file mode 100644 index d043d893b..000000000 --- a/runtime/test/check_tiny_present.py +++ /dev/null @@ -1,183 +0,0 @@ -"""Run tiny_present under `gta6rt --run` on the Vulkan D3D12 device and check, from outside, what it presented. - - python -I check_tiny_present.py [--probe d3d12_com_test.exe] [--title-window] - -The stand-in title (test/fixtures/tiny_present.cpp) asks the console output for the display mode, makes a back buffer -of that size, and presents three-coloured frames through the console queue's PresentX, paced by the device's frame -clock. This sets LEONIDA_DISPLAY_MODE (so the mode is a known one), LEONIDA_CAPTURE_DIR to a new folder and writes 1 -into its request.txt before the run, so the runtime saves one presented frame as capture-1.png from its own thread. -Then it checks the guest's verdict, that the display mode the guest got is the one set, that every PresentX of the -d3d12 trace was shown, that the runtime says the frames went to the window (the title's own with --title-window, where -the guest makes one through the API set a title imports CreateWindowExA from, and the shim fits it to the screen), and -the screenshot's pixels: a PNG of the window's client size whose top-left quarter, bottom-left quarter and right half -have the guest's three colours. Exits 77 (ctest: skipped) without a usable Vulkan device or without a desktop to show -a window on. A window shows on the desktop for a few seconds. -""" - -import argparse -import os -import re -import shutil -import struct -import subprocess -import sys -import tempfile -import zlib - -SKIP = 77 -DISPLAY_MODE = (1280, 720) -COLOURS = {"top-left": (255, 0, 0), "bottom-left": (64, 128, 191), "right": (0, 200, 0)} - - -def decode_png(data): - """(width, height, rows of RGB bytes) of an 8-bit RGB PNG; raises ValueError otherwise.""" - if data[:8] != b"\x89PNG\r\n\x1a\n": - raise ValueError("not a PNG") - at, idat, header = 8, b"", None - while at < len(data): - length, kind = struct.unpack(">I4s", data[at:at + 8]) - body = data[at + 8:at + 8 + length] - (crc,) = struct.unpack(">I", data[at + 8 + length:at + 12 + length]) - if zlib.crc32(kind + body) & 0xFFFFFFFF != crc: - raise ValueError(f"bad CRC in {kind!r}") - if kind == b"IHDR": - header = struct.unpack(">IIBBBBB", body) - elif kind == b"IDAT": - idat += body - elif kind == b"IEND": - break - at += 12 + length - if not header or header[2:] != (8, 2, 0, 0, 0): - raise ValueError(f"not 8-bit RGB: {header}") - width, height = header[0], header[1] - raw = zlib.decompress(idat) - stride = width * 3 - if len(raw) != (stride + 1) * height: - raise ValueError("wrong amount of image data") - rows, previous = [], bytearray(stride) - for y in range(height): - kind = raw[y * (stride + 1)] - line = bytearray(raw[y * (stride + 1) + 1:(y + 1) * (stride + 1)]) - for i in range(stride): - a = line[i - 3] if i >= 3 else 0 - b = previous[i] - c = previous[i - 3] if i >= 3 else 0 - if kind == 1: - line[i] = (line[i] + a) & 0xFF - elif kind == 2: - line[i] = (line[i] + b) & 0xFF - elif kind == 3: - line[i] = (line[i] + (a + b) // 2) & 0xFF - elif kind == 4: - p = a + b - c - pa, pb, pc = abs(p - a), abs(p - b), abs(p - c) - line[i] = (line[i] + (a if pa <= pb and pa <= pc else b if pb <= pc else c)) & 0xFF - elif kind != 0: - raise ValueError(f"unknown filter {kind}") - rows.append(bytes(line)) - previous = line - return width, height, rows - - -def check_screenshot(path, window_size): - """Problems with the saved frame: its size and the three regions' colours (at the middle of each region).""" - try: - with open(path, "rb") as f: - width, height, rows = decode_png(f.read()) - except (OSError, ValueError, zlib.error) as error: - return [f"the screenshot {path} does not decode: {error}"] - problems = [] - if window_size and (width, height) != window_size: - problems.append(f"the screenshot is {width}x{height}, the window's client area {window_size[0]}x{window_size[1]}") - points = {"top-left": (width // 4, height // 4), "bottom-left": (width // 4, 3 * height // 4), - "right": (3 * width // 4, height // 2)} - for name, (x, y) in points.items(): - got = tuple(rows[y][x * 3:x * 3 + 3]) - want = COLOURS[name] - if any(abs(g - w) > 2 for g, w in zip(got, want)): - problems.append(f"the {name} region at {x},{y} is {got}, not {want}") - return problems - - -def check_run(code, output, title_window): - problems = [] - lines = output.replace("\r\n", "\n").split("\n") - if code != 0: - problems.append(f"exit code {code}") - if "tiny_present: OK" not in lines: - problems.append("the guest did not print `tiny_present: OK`") - if any(line.startswith("tiny_present: FAIL") for line in lines): - problems.append("the guest reported a failed check") - mode = next((m for m in (re.fullmatch(r"tiny_present: display mode (\d+)x(\d+) at 60/1 Hz", line) for line in lines) - if m), None) - if not mode or (int(mode[1]), int(mode[2])) != DISPLAY_MODE: - problems.append(f"the guest was not told the display mode {DISPLAY_MODE[0]}x{DISPLAY_MODE[1]}") - presents = [line for line in lines if re.fullmatch(r"\[d3d12-trace\] #\d+ XboxPresentation::PresentX \w+", line)] - shown = [line for line in presents if line.endswith(" ok")] - if len(shown) < 90 or len(shown) != len(presents): - problems.append(f"{len(shown)} of {len(presents)} PresentX calls were shown (90 or more, all of them, expected)") - if not any(line.startswith("[rt] present: the title's frames go to its window") for line in lines): - problems.append("the runtime did not say the frames go to the window") - own = any(line.startswith("[rt] window: the title's own window shows its frames") for line in lines) - if own != title_window: - problems.append("the frames went to the " + ("runtime's window, not the title's" if title_window - else "title's window, not the runtime's")) - saved = next((m for m in (re.match(r"\[rt\] capture: request 1: frame \d+ \((\d+)x(\d+)\) saved as ", line) - for line in lines) if m), None) - if not saved: - problems.append("the runtime did not save request 1") - client = next((m for m in (re.fullmatch(r"tiny_present: window client area (\d+)x(\d+)", line) for line in lines) - if m), None) - return problems, (int(client[1]), int(client[2])) if client else None - - -def main(): - parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument("loader") - parser.add_argument("guest") - parser.add_argument("--probe", help="a Vulkan device test; its exit code 77 skips this test") - parser.add_argument("--title-window", action="store_true", help="the guest makes its own window first") - options = parser.parse_args() - - if options.probe: - probe = subprocess.run([options.probe], capture_output=True, timeout=120) - if probe.returncode == SKIP: - print("SKIP: no usable Vulkan device (the probe test skipped)") - return SKIP - - folder = tempfile.mkdtemp(prefix="leonida_tiny_present_") - try: - with open(os.path.join(folder, "request.txt"), "w", encoding="utf-8", newline="\n") as f: - f.write("1\n") - environment = dict(os.environ, LEONIDA_D3D12="vulkan", LEONIDA_CAPTURE_DIR=folder, - LEONIDA_DISPLAY_MODE=f"{DISPLAY_MODE[0]}x{DISPLAY_MODE[1]}") - environment.pop("LEONIDA_CAPTURE_REQUEST", None) - command = [options.loader, "--run", os.path.basename(options.guest), "--trace-d3d12"] - if options.title_window: - command += ["--", "--title-window"] - run = subprocess.run(command, cwd=os.path.dirname(os.path.abspath(options.guest)), env=environment, - capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=120) - output = run.stdout + run.stderr - if "tiny_present: SKIP" in output: - print("SKIP: no interactive window station (no desktop to show a window on)") - return SKIP - problems, client = check_run(run.returncode, output, options.title_window) - screenshot = os.path.join(folder, "capture-1.png") - if os.path.exists(screenshot): - problems += check_screenshot(screenshot, client) - else: - problems.append("no capture-1.png in the capture folder") - if problems: - print("\n".join(line for line in output.split("\n") if not line.startswith("[d3d12-trace]"))) - for problem in problems: - print(f"FAIL: {problem}") - return 1 - print(f"tiny_present under gta6rt --run ({'the title' if options.title_window else 'the runtime'}'s window): " - f"OK, screenshot {client[0] if client else '?'}x{client[1] if client else '?'} checked") - return 0 - finally: - shutil.rmtree(folder, ignore_errors=True) - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/runtime/test/console_insn_test.cpp b/runtime/test/console_insn_test.cpp deleted file mode 100644 index bc827ef42..000000000 --- a/runtime/test/console_insn_test.cpp +++ /dev/null @@ -1,166 +0,0 @@ -// Console-only CPU instructions (src/console_insn.*): the decoder against AMD's encodings, the SSE4a bit fields, and -// on Windows the handler's emulation on a hand-made CONTEXT (the code bytes are written here; nothing is executed, -// so the test means the same on an AMD host that has these instructions and an Intel one that lacks them). -#include "console_insn.h" - -#include -#include -#include - -#if defined(_WIN32) -#include -#endif - -namespace { - -int g_failures = 0; -void check(bool condition, const char* what) { - std::printf("%s: %s\n", condition ? "ok" : "FAIL", what); - if (!condition) ++g_failures; -} - -using rt::console_insn::Decoded; -using rt::console_insn::Kind; - -Decoded dec(std::initializer_list bytes) { - const std::vector v(bytes); - return rt::console_insn::decode(v.data(), v.size()); -} -bool is(const Decoded& d, Kind k, unsigned length) { return d.kind == k && d.length == length; } - -} // namespace - -int main() { - // ---- decoder ---- - check(is(dec({0x0F, 0x01, 0xFC}), Kind::Clzero, 3), "CLZERO is 0F 01 FC"); - const Decoded a32 = dec({0x67, 0x0F, 0x01, 0xFC}); - check(is(a32, Kind::Clzero, 4) && a32.address32, "with a 67 prefix CLZERO addresses EAX"); - const Decoded loop = dec({0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x4C, 0x39, 0xC8, 0x72, 0xF4}); - check(is(loop, Kind::ClzeroLoop, 12) && loop.reg == 9, "clzero; add rax,40h; cmp rax,r9; jb: one loop to r9"); - check(is(dec({0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD9, 0x72, 0xF4}), Kind::Clzero, 3), - "a cmp whose first operand is not rax is no such loop"); - check(is(dec({0x0F, 0x01, 0xFD}), Kind::Rdpru, 3) && is(dec({0x0F, 0x01, 0xFA}), Kind::Monitorx, 3) && - is(dec({0x0F, 0x01, 0xFB}), Kind::Mwaitx, 3), - "RDPRU, MONITORX, MWAITX"); - check(is(dec({0x0F, 0x0B}), Kind::Ud2, 2), "UD2 is recognised (and never emulated)"); - check(is(dec({0x66, 0x0F, 0xAE, 0x33}), Kind::Clwb, 4), "CLWB [rbx]"); - check(is(dec({0x66, 0x0F, 0xAE, 0x74, 0x8B, 0x10}), Kind::Clwb, 6), "CLWB [rbx+rcx*4+10h]"); - check(is(dec({0x66, 0x0F, 0xAE, 0x35, 0, 0, 0, 0}), Kind::Clwb, 8), "CLWB [rip+disp32]"); - check(is(dec({0x66, 0x0F, 0xAE, 0xB0, 0, 1, 0, 0}), Kind::Clwb, 8), "CLWB [rax+disp32]"); - check(is(dec({0x66, 0x49, 0x0F, 0xAE, 0x34, 0x24}), Kind::Clwb, 6), "CLWB [r12] (REX.B, SIB)"); - check(dec({0x0F, 0xAE, 0x33}).kind == Kind::None, "without 66 it is XSAVEOPT, not ours"); - check(dec({0x66, 0x0F, 0xAE, 0x3B}).kind == Kind::None, "66 0F AE /7 is CLFLUSHOPT, not ours"); - check(dec({0x66, 0x0F, 0xAE, 0x74, 0x8B}).kind == Kind::None, "a truncated operand is not decoded"); - const Decoded rdpid = dec({0xF3, 0x49, 0x0F, 0xC7, 0xFB}); - check(is(rdpid, Kind::Rdpid, 5) && rdpid.reg == 11, "RDPID r11"); - check(dec({0xF3, 0x0F, 0xC7, 0x3B}).kind == Kind::None, "F3 0F C7 /7 with memory is not RDPID"); - - const Decoded ext = dec({0x66, 0x0F, 0x78, 0xC3, 0x10, 0x08}); - check(is(ext, Kind::Extrq, 6) && ext.reg == 3 && !ext.from_register && ext.field_length == 16 && - ext.field_index == 8, - "EXTRQ xmm3, 16, 8"); - check(dec({0x66, 0x0F, 0x78, 0xCB, 0x10, 0x08}).kind == Kind::None, "EXTRQ's immediate form is /0 only"); - const Decoded ext_r = dec({0x66, 0x45, 0x0F, 0x79, 0xCA}); - check(is(ext_r, Kind::Extrq, 5) && ext_r.reg == 9 && ext_r.src == 10 && ext_r.from_register, - "EXTRQ xmm9, xmm10 (REX.R, REX.B)"); - const Decoded ins = dec({0xF2, 0x0F, 0x78, 0xCA, 0x04, 0x3C}); - check(is(ins, Kind::Insertq, 6) && ins.reg == 1 && ins.src == 2 && ins.field_length == 4 && ins.field_index == 60, - "INSERTQ xmm1, xmm2, 4, 60"); - const Decoded ins_r = dec({0xF2, 0x0F, 0x79, 0xC1}); - check(is(ins_r, Kind::Insertq, 4) && ins_r.reg == 0 && ins_r.src == 1 && ins_r.from_register, "INSERTQ xmm0, xmm1"); - check(dec({0xF2, 0x0F, 0x78, 0xCA, 0x04}).kind == Kind::None, "INSERTQ with an immediate missing"); - check(dec({0x0F, 0x78, 0xC1, 0x08, 0x10}).kind == Kind::None, "0F 78 without a prefix is VMREAD, not SSE4a"); - check(is(dec({0x66, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10}), Kind::Insertq, 7) && - is(dec({0xF3, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10}), Kind::Insertq, 7) && - dec({0xF2, 0xF3, 0x0F, 0x78, 0xC1, 0x10, 0x10}).kind == Kind::None, - "the last of F2/F3 decides, and 66 beside F2 does not"); - check(is(dec({0x41, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10}), Kind::Insertq, 7) && - dec({0x41, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10}).reg == 0, - "a REX before a legacy prefix counts for nothing"); - check(dec({0x48, 0x8B, 0x01}).kind == Kind::None && dec({0x0F}).kind == Kind::None && dec({}).kind == Kind::None, - "anything else, and too few bytes, is not ours"); - - // ---- SSE4a fields (AMD APM vol. 4: a length of 0 is 64) ---- - using rt::console_insn::extrq; - using rt::console_insn::insertq; - check(extrq(0x0123456789ABCDEFull, 8, 4) == 0xDE && extrq(0x0123456789ABCDEFull, 0, 0) == 0x0123456789ABCDEFull && - extrq(0x8000000000000000ull, 1, 63) == 1, - "EXTRQ takes the field and zero-extends it"); - check(insertq(~0ull, 0x12, 8, 8) == 0xFFFFFFFFFFFF12FFull && insertq(0, 0xFF, 4, 60) == 0xF000000000000000ull && - insertq(0x55, 0xAAAAull, 0, 0) == 0xAAAAull, - "INSERTQ puts the source's low bits in the field"); - -#if defined(_WIN32) - // ---- the handler's emulation on a context ---- - using rt::console_insn::emulate; - CONTEXT ctx{}; - alignas(64) static unsigned char block[4096 + 128]; - std::memset(block, 0xCC, sizeof(block)); - const uint8_t clzero[] = {0x0F, 0x01, 0xFC}; - ctx.Rax = reinterpret_cast(block + 64 + 5); - ctx.Rip = 0x1000; - check(emulate(&ctx, clzero, sizeof(clzero)) && ctx.Rip == 0x1003 && block[64] == 0 && block[127] == 0 && - block[63] == 0xCC && block[128] == 0xCC, - "CLZERO zeroes the 64-byte line rAX is in and steps over"); - - std::memset(block, 0xCC, sizeof(block)); - const uint8_t loop_code[] = {0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4}; - ctx.Rax = reinterpret_cast(block); - ctx.Rdx = reinterpret_cast(block + 4096); - ctx.Rip = 0x2000; - ctx.EFlags = 0x1; - check(emulate(&ctx, loop_code, sizeof(loop_code)) && ctx.Rip == 0x200C && ctx.Rax == ctx.Rdx && - (ctx.EFlags & 1) == 0 && block[4096] == 0xCC, - "a CLZERO loop is done at once: rAX at the end, the jb not taken"); - bool zero = true; - for (size_t i = 0; i < 4096; ++i) zero = zero && block[i] == 0; - check(zero, "and every line up to the end is zeroed"); - - void* page = VirtualAlloc(nullptr, 4096, MEM_COMMIT | MEM_RESERVE, PAGE_READONLY); - ctx.Rax = reinterpret_cast(page); - ctx.Rip = 0x3000; - check(!emulate(&ctx, clzero, sizeof(clzero)) && ctx.Rip == 0x3000, - "CLZERO on memory it cannot write is not emulated (the real one faults too)"); - VirtualFree(page, 0, MEM_RELEASE); - - const uint8_t rdpid_code[] = {0xF3, 0x0F, 0xC7, 0xF9}; // rdpid rcx - ctx.Rcx = ~0ull; - ctx.Rip = 0x4000; - check(emulate(&ctx, rdpid_code, sizeof(rdpid_code)) && ctx.Rcx < 4096 && ctx.Rip == 0x4004, - "RDPID writes the processor number"); - - const uint8_t ins_code[] = {0xF2, 0x0F, 0x78, 0xCA, 0x08, 0x10}; // insertq xmm1, xmm2, 8, 16 - ctx.FltSave.XmmRegisters[1].Low = 0; - ctx.FltSave.XmmRegisters[1].High = 77; - ctx.FltSave.XmmRegisters[2].Low = 0xAB; - ctx.Rip = 0x5000; - check(emulate(&ctx, ins_code, sizeof(ins_code)) && ctx.FltSave.XmmRegisters[1].Low == 0xAB0000 && - ctx.FltSave.XmmRegisters[1].High == 0 && ctx.Rip == 0x5006, - "INSERTQ on the context's XMM registers, the high quadword zeroed"); - const uint8_t ext_code[] = {0x66, 0x0F, 0x79, 0xCA}; // extrq xmm1, xmm2 - ctx.FltSave.XmmRegisters[2].Low = 0x0808; // length 8, index 8 - ctx.FltSave.XmmRegisters[1].Low = 0x123456; - check(emulate(&ctx, ext_code, sizeof(ext_code)) && ctx.FltSave.XmmRegisters[1].Low == 0x34, - "EXTRQ with the field in a register"); - - unsigned char* code = static_cast( - VirtualAlloc(nullptr, 4096, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); - const uint8_t clwb[] = {0x66, 0x0F, 0xAE, 0x30}; // clwb [rax] - std::memcpy(code, clwb, sizeof(clwb)); - DWORD old = 0; - VirtualProtect(code, 4096, PAGE_EXECUTE_READ, &old); - ctx.Rip = reinterpret_cast(code); - check(emulate(&ctx, code, sizeof(clwb)) && ctx.Rip == reinterpret_cast(code) + 4 && code[0] == 0x90 && - code[3] == 0x90, - "CLWB is stepped over and patched to NOPs in read-only code"); - VirtualFree(code, 0, MEM_RELEASE); - - const uint8_t ud2[] = {0x0F, 0x0B}; - ctx.Rip = 0x6000; - check(!emulate(&ctx, ud2, sizeof(ud2)) && ctx.Rip == 0x6000, "UD2 is left to the title's handlers"); - check(rt::console_insn::emulated_count() >= 6, "the emulations are counted"); -#endif - - std::printf("%s\n", g_failures ? "FAILED" : "PASSED"); - return g_failures ? 1 : 0; -} diff --git a/runtime/test/d3d12_async_pipeline_test.cpp b/runtime/test/d3d12_async_pipeline_test.cpp deleted file mode 100644 index 3dc3cbc27..000000000 --- a/runtime/test/d3d12_async_pipeline_test.cpp +++ /dev/null @@ -1,487 +0,0 @@ -// GPU test of pipelines made off the creating thread (src/pipeline_queue.h, after VIctory's pipeline/make.rs and -// pipeline/library.rs): -// 1. Before the frame clock's first frame (as through the PC interface) a bind waits for its pipeline, so a draw -// right after creation runs. -// 2. Once frames run: many PSOs are created at once and none is made at creation; with the builder held, each bind -// waits within the frame's budget (one window per frame and kind) and every draw and dispatch is dropped and -// counted, the list staying valid; once they are made, the next frame's draws all run. -// 3. The early list: the PSOs a run bound are written to the list; read back as the next run reads it, the same -// descriptions are started at creation without a bind, and one that was not bound is not. -// 4. Console device slot 86 (CreatePipelineState from a stream) reaches the layer's stream PSO. -// Shaders: the draw test's VS/PS and the compute test's CS, under synthetic FSSM keys. No game data. -#include "shader_fixture_path.h" -#include "test_temp_dir.h" -#include "vk_test_device.h" -#include "d3d12_test_shaders.h" -#include "../shims/d3d12_com.h" -#include "../shims/d3d12_xs_device.h" -#include "../src/pipeline_queue.h" -#include "../src/shader_library.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#if !defined(LEONIDA_TEST_CS_SPV) || !defined(LEONIDA_TEST_VS_SPV) || !defined(LEONIDA_TEST_PS_SPV) -#error "LEONIDA_TEST_CS_SPV, LEONIDA_TEST_VS_SPV and LEONIDA_TEST_PS_SPV must be defined" -#endif - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "d3d12_async_pipeline_test line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -using namespace d3d12test; -using namespace std::chrono_literals; -namespace pipelines = leonida::pipelines; - -namespace { - -struct Vertex { - float x, y; - std::uint8_t r, g, b, a; -}; - -D3D12_RESOURCE_DESC tex2d_desc(UINT w, UINT h, DXGI_FORMAT fmt, D3D12_RESOURCE_FLAGS flags) { - D3D12_RESOURCE_DESC d{}; - d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - d.Width = w; - d.Height = h; - d.DepthOrArraySize = 1; - d.MipLevels = 1; - d.Format = fmt; - d.SampleDesc = {1, 0}; - d.Flags = flags; - return d; -} - -double ms_since(std::chrono::steady_clock::time_point t) { - return std::chrono::duration(std::chrono::steady_clock::now() - t).count(); -} - -// A subobject of a pipeline state stream as d3dx12 lays it out: its type, the description at its own alignment, the -// next subobject at pointer alignment. -template -void append(std::vector& stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type, const T& value) { - const auto round = [](std::size_t v, std::size_t a) { return (v + a - 1) / a * a; }; - const std::size_t at = stream.size(); - const std::size_t payload = round(at + sizeof(type), alignof(T)); - stream.resize(round(payload + sizeof(T), sizeof(void*)), 0); - std::memcpy(stream.data() + at, &type, sizeof(type)); - std::memcpy(stream.data() + payload, &value, sizeof(T)); -} - -std::size_t count_draws(ID3D12GraphicsCommandList* list, bool dispatch) { - std::vector commands; - if (!rt::d3d12::recorded_commands(list, commands)) return ~std::size_t(0); - std::size_t n = 0; - for (const auto& c : commands) n += dispatch ? std::holds_alternative(c) : std::holds_alternative(c); - return n; -} - -} // namespace - -int main() { - vktest::Device d; - const auto status = d.initialize(); - if (status == vktest::DeviceStatus::unavailable) { - std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n"); - return 77; - } - EXPECT(status == vktest::DeviceStatus::ready); - - const auto cs_prog = fssm_program({0x43532001, 0xbf810000}); - const auto vs_prog = fssm_program({0x56532001, 0xbf810000}); - const auto ps_prog = fssm_program({0x50532001, 0xbf810000}); - const auto cs_dxbc = shader_container(cs_prog); - const auto vs_dxbc = shader_container(vs_prog); - const auto ps_dxbc = shader_container(ps_prog); - - const testfiles::ScratchDir scratch("leonida_async_pipeline_test"); - const auto& lib_dir = scratch.path(); - EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), lib_dir / "cs.spv")); - EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_SPV), lib_dir / "vs.spv")); - EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_PS_SPV), lib_dir / "ps.spv")); - { - std::ofstream idx(lib_dir / "index.json", std::ios::binary); - idx << "{\"cs\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(cs_prog) - << "\", \"bindings\": [], \"push_constant_bytes\": 144},\n" - " \"vs\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_prog) - << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": [" - "{\"semantic\": \"COLOR\", \"semantic_index\": 0, \"register\": 0, \"mask\": 15, \"rw_mask\": 15, " - "\"system_value\": 0, \"component_type\": \"float\"}, " - "{\"semantic\": \"POSITION\", \"semantic_index\": 0, \"register\": 1, \"mask\": 3, \"rw_mask\": 3, " - "\"system_value\": 0, \"component_type\": \"float\"}]},\n" - " \"ps\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_prog) - << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0]}}"; - } - // Before any PSO: the list goes to the scratch folder, written whatever the frame clock does. - const std::filesystem::path early_file = lib_dir / "early-pipelines.txt"; - pipelines::EarlyList::get().configure(early_file, true, true); - - rt::d3d12::VulkanDeviceInfo info{}; - info.get_instance_proc = d.instance_proc; - info.instance = d.instance; - info.physical = d.physical; - info.device = d.device; - info.queue = d.queue; - info.queue_family = d.family; - info.buffer_device_address = true; - info.shader_dir = lib_dir.string(); - info.features = d.enabled; // as the runtime's own device: the store features where the GPU has them - Ref device; - EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p)))); - if (rt::d3d12::device_push_constants_need_fallback(device.p)) { - std::printf("d3d12_async_pipeline_test: skipped, the PSOs need 144 push-constant bytes\n"); - return 77; - } - - D3D12_DESCRIPTOR_RANGE uav_range{D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 1, 0, 0}; - D3D12_ROOT_PARAMETER cs_params[3]{}; - cs_params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; - cs_params[0].Constants = {0, 0, 1}; - cs_params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; - cs_params[1].Descriptor = {0, 0}; - cs_params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - cs_params[2].DescriptorTable = {1, &uav_range}; - D3D12_VERSIONED_ROOT_SIGNATURE_DESC cs_rs_desc{}; - cs_rs_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; - cs_rs_desc.Desc_1_0 = {3, cs_params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; - const auto cs_rs_blob = serialize_root_signature(cs_rs_desc); - Ref cs_rs; - EXPECT(SUCCEEDED(device->CreateRootSignature(0, cs_rs_blob.data(), cs_rs_blob.size(), IID_PPV_ARGS(&cs_rs.p)))); - D3D12_COMPUTE_PIPELINE_STATE_DESC cs_desc{}; - cs_desc.pRootSignature = cs_rs.p; - cs_desc.CS = {cs_dxbc.data(), cs_dxbc.size()}; - - D3D12_ROOT_PARAMETER gfx_params[2]{}; - gfx_params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; - gfx_params[0].Constants = {0, 0, 2}; - gfx_params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; - gfx_params[1].Descriptor = {1, 0}; - D3D12_VERSIONED_ROOT_SIGNATURE_DESC gfx_rs_desc{}; - gfx_rs_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; - gfx_rs_desc.Desc_1_0 = {2, gfx_params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT}; - const auto gfx_rs_blob = serialize_root_signature(gfx_rs_desc); - Ref gfx_rs; - EXPECT(SUCCEEDED(device->CreateRootSignature(0, gfx_rs_blob.data(), gfx_rs_blob.size(), IID_PPV_ARGS(&gfx_rs.p)))); - const D3D12_INPUT_ELEMENT_DESC input_elems[2] = { - {"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, - {"COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, D3D12_APPEND_ALIGNED_ELEMENT, - D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, - }; - D3D12_GRAPHICS_PIPELINE_STATE_DESC gfx_desc{}; - gfx_desc.pRootSignature = gfx_rs.p; - gfx_desc.VS = {vs_dxbc.data(), vs_dxbc.size()}; - gfx_desc.PS = {ps_dxbc.data(), ps_dxbc.size()}; - gfx_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; - gfx_desc.SampleMask = 0xFFFFFFFFu; - gfx_desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; - gfx_desc.RasterizerState.CullMode = D3D12_CULL_MODE_BACK; - gfx_desc.RasterizerState.DepthClipEnable = TRUE; - gfx_desc.InputLayout = {input_elems, 2}; - gfx_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; - gfx_desc.NumRenderTargets = 1; - gfx_desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; - gfx_desc.SampleDesc = {1, 0}; - // PSO number i: its own description (a depth bias, which changes nothing without a depth target), so its own - // pipeline and its own key. - const auto make_pso = [&](int i, ID3D12PipelineState** out) { - D3D12_GRAPHICS_PIPELINE_STATE_DESC desc = gfx_desc; - desc.RasterizerState.DepthBias = i; - return device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(out)); - }; - - Ref queue; - const D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, D3D12_COMMAND_QUEUE_FLAG_NONE, 0}; - EXPECT(SUCCEEDED(device->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue.p)))); - Ref alloc; - EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc.p)))); - Ref list; - EXPECT(SUCCEEDED( - device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.p, nullptr, IID_PPV_ARGS(&list.p)))); - EXPECT(SUCCEEDED(list->Close())); - Ref fence; - EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); - UINT64 fence_value = 0; - - constexpr UINT W = 16, H = 16; - const D3D12_HEAP_PROPERTIES hp_def{D3D12_HEAP_TYPE_DEFAULT}; - const D3D12_HEAP_PROPERTIES hp_up{D3D12_HEAP_TYPE_UPLOAD}; - const D3D12_HEAP_PROPERTIES hp_rb{D3D12_HEAP_TYPE_READBACK}; - const auto rtd = tex2d_desc(W, H, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); - const Vertex verts[4] = {{-1.0f, 1.0f, 255, 0, 0, 255}, {0.0f, 1.0f, 255, 0, 0, 255}, - {0.0f, 0.0f, 255, 0, 0, 255}, {-1.0f, 0.0f, 255, 0, 0, 255}}; - const std::uint16_t indices[6] = {0, 1, 2, 0, 2, 3}; - const float tint[4] = {1.0f, 0.0f, 1.0f, 1.0f}; - const auto vbd = buffer_desc(sizeof(verts)); - const auto ibd = buffer_desc(sizeof(indices)); - const auto cbd = buffer_desc(256); - Ref rt, vb, ib, cb, rb; - EXPECT(SUCCEEDED(device->CreateCommittedResource(&hp_def, D3D12_HEAP_FLAG_NONE, &rtd, - D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr, IID_PPV_ARGS(&rt.p)))); - EXPECT(SUCCEEDED(device->CreateCommittedResource(&hp_up, D3D12_HEAP_FLAG_NONE, &vbd, - D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&vb.p)))); - EXPECT(SUCCEEDED(device->CreateCommittedResource(&hp_up, D3D12_HEAP_FLAG_NONE, &ibd, - D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&ib.p)))); - EXPECT(SUCCEEDED(device->CreateCommittedResource(&hp_up, D3D12_HEAP_FLAG_NONE, &cbd, - D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&cb.p)))); - void* p = nullptr; - EXPECT(SUCCEEDED(vb->Map(0, nullptr, &p))); - std::memcpy(p, verts, sizeof(verts)); - vb->Unmap(0, nullptr); - EXPECT(SUCCEEDED(ib->Map(0, nullptr, &p))); - std::memcpy(p, indices, sizeof(indices)); - ib->Unmap(0, nullptr); - EXPECT(SUCCEEDED(cb->Map(0, nullptr, &p))); - std::memcpy(p, tint, sizeof(tint)); - cb->Unmap(0, nullptr); - D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{}; - UINT64 total_bytes = 0; - device->GetCopyableFootprints(&rtd, 0, 1, 0, &fp, nullptr, nullptr, &total_bytes); - const auto rbd = buffer_desc(total_bytes); - EXPECT(SUCCEEDED(device->CreateCommittedResource(&hp_rb, D3D12_HEAP_FLAG_NONE, &rbd, - D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&rb.p)))); - Ref rtv_heap; - const D3D12_DESCRIPTOR_HEAP_DESC rhd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; - EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&rhd, IID_PPV_ARGS(&rtv_heap.p)))); - const auto rtv = rtv_heap->GetCPUDescriptorHandleForHeapStart(); - device->CreateRenderTargetView(rt.p, nullptr, rtv); - - // One frame's list: a blue clear, then a red quad with each PSO; the colour at the quad comes back. - const auto draw_with = [&](const std::vector& psos, std::uint32_t& colour, - std::size_t& recorded) -> bool { - if (FAILED(alloc->Reset()) || FAILED(list->Reset(alloc.p, nullptr))) return false; - const float blue[4] = {0.0f, 0.0f, 1.0f, 1.0f}; - list->ClearRenderTargetView(rtv, blue, 0, nullptr); - list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); - const D3D12_VIEWPORT vp{0, 0, float(W), float(H), 0.0f, 1.0f}; - const D3D12_RECT sc{0, 0, LONG(W), LONG(H)}; - list->RSSetViewports(1, &vp); - list->RSSetScissorRects(1, &sc); - list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - const D3D12_VERTEX_BUFFER_VIEW vbv{vb->GetGPUVirtualAddress(), sizeof(verts), sizeof(Vertex)}; - const D3D12_INDEX_BUFFER_VIEW ibv{ib->GetGPUVirtualAddress(), sizeof(indices), DXGI_FORMAT_R16_UINT}; - list->IASetVertexBuffers(0, 1, &vbv); - list->IASetIndexBuffer(&ibv); - list->SetGraphicsRootSignature(gfx_rs.p); - const float offset[2] = {0.0f, 0.0f}; - list->SetGraphicsRoot32BitConstants(0, 2, offset, 0); - list->SetGraphicsRootConstantBufferView(1, cb->GetGPUVirtualAddress()); - for (ID3D12PipelineState* pso : psos) { - list->SetPipelineState(pso); - list->DrawIndexedInstanced(6, 1, 0, 0, 0); - } - recorded = count_draws(list.p, false); - const auto to_src = transition(rt.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); - const auto to_rt = transition(rt.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET); - list->ResourceBarrier(1, &to_src); - D3D12_TEXTURE_COPY_LOCATION src_loc{rt.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; - D3D12_TEXTURE_COPY_LOCATION dst_loc{rb.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}}; - dst_loc.PlacedFootprint = fp; - list->CopyTextureRegion(&dst_loc, 0, 0, 0, &src_loc, nullptr); - list->ResourceBarrier(1, &to_rt); - if (FAILED(list->Close())) return false; - ID3D12CommandList* lists[] = {list.p}; - queue->ExecuteCommandLists(1, lists); - if (rt::d3d12::last_execute_result(queue.p) != leonida::ReplayResult::success) return false; - if (FAILED(queue->Signal(fence.p, ++fence_value)) || FAILED(fence->SetEventOnCompletion(fence_value, nullptr))) - return false; - void* mapped = nullptr; - if (FAILED(rb->Map(0, nullptr, &mapped))) return false; - std::memcpy(&colour, static_cast(mapped) + 2 * fp.Footprint.RowPitch + 2 * 4, 4); - rb->Unmap(0, nullptr); - return true; - }; - constexpr std::uint32_t kRed = 0xFF0000FFu, kBlue = 0xFFFF0000u; - std::uint32_t colour = 0; - std::size_t recorded = 0; - - // 1. No frame yet: creation returns without the pipeline, the bind waits for it, the draw runs. - EXPECT(pipelines::current_frame() == 0); - { - Ref pso; - const auto t = std::chrono::steady_clock::now(); - EXPECT(SUCCEEDED(make_pso(0, &pso.p))); - const double created = ms_since(t); - const pipelines::Job* job = rt::d3d12::pipeline_job(pso.p); - EXPECT(job && job->queue_state() == pipelines::kNotQueued && !job->finished()); - const pipelines::DropCounts before = pipelines::Drops::get().counts(); - EXPECT(draw_with({pso.p}, colour, recorded)); - EXPECT(recorded == 1 && colour == kRed && job->ready()); - EXPECT(pipelines::Drops::get().counts().draws == before.draws); - std::printf("d3d12_async_pipeline_test: before the first frame, creation took %.2f ms, the bind waited for the " - "pipeline (made in %.1f ms) and the draw ran\n", created, - std::chrono::duration(job->took()).count()); - } - - // 2. Frames run: many PSOs at once, all dropped while they are being made, all drawn once made. - constexpr int kMany = 192; - pipelines::begin_frame(); - pipelines::set_loading_allowance(std::chrono::seconds(0)); // the frame budget alone - pipelines::set_wait_budget(40ms); - pipelines::Builder::get().hold(true); - std::vector> many(kMany); - std::vector raw; - auto t = std::chrono::steady_clock::now(); - for (int i = 0; i < kMany; ++i) EXPECT(SUCCEEDED(make_pso(i + 1, &many[i].p))); - const double created_ms = ms_since(t); - for (auto& pso : many) { - raw.push_back(pso.p); - EXPECT(!rt::d3d12::pipeline_job(pso.p)->finished()); - } - Ref cs_pso; - EXPECT(SUCCEEDED(device->CreateComputePipelineState(&cs_desc, IID_PPV_ARGS(&cs_pso.p)))); - const pipelines::DropCounts before = pipelines::Drops::get().counts(); - t = std::chrono::steady_clock::now(); - EXPECT(draw_with(raw, colour, recorded)); - const double frame_ms = ms_since(t); - EXPECT(recorded == 0 && colour == kBlue); - pipelines::DropCounts after = pipelines::Drops::get().counts(); - EXPECT(after.draws == before.draws + kMany); - // The frame's graphics window is used up; a compute bind has its own, and its dispatch is dropped too. - EXPECT(SUCCEEDED(alloc->Reset()) && SUCCEEDED(list->Reset(alloc.p, nullptr))); - list->SetComputeRootSignature(cs_rs.p); - t = std::chrono::steady_clock::now(); - list->SetPipelineState(cs_pso.p); - const double compute_wait_ms = ms_since(t); - list->Dispatch(1, 1, 1); - EXPECT(count_draws(list.p, true) == 0 && SUCCEEDED(list->Close())); - after = pipelines::Drops::get().counts(); - EXPECT(after.dispatches == before.dispatches + 1); - std::printf("d3d12_async_pipeline_test: %d graphics PSOs created in %.1f ms (%.0f us each), none made; their frame " - "took %.0f ms with the builder held (budget 40 ms per frame and kind), all %d draws dropped; a compute " - "bind then waited %.0f ms and its dispatch was dropped\n", - kMany, created_ms, 1000.0 * created_ms / kMany, frame_ms, kMany, compute_wait_ms); - EXPECT(frame_ms < 2000.0); - EXPECT(compute_wait_ms >= 30.0); - pipelines::Builder::get().hold(false); - t = std::chrono::steady_clock::now(); - for (ID3D12PipelineState* pso : raw) EXPECT(const_cast(rt::d3d12::pipeline_job(pso))->wait_finished_for(60s)); - const double made_ms = ms_since(t); - for (ID3D12PipelineState* pso : raw) EXPECT(rt::d3d12::pipeline_job(pso)->ready()); - EXPECT(const_cast(rt::d3d12::pipeline_job(cs_pso.p))->wait_finished_for(60s)); - pipelines::begin_frame(); - EXPECT(draw_with(raw, colour, recorded)); - EXPECT(recorded == std::size_t(kMany) && colour == kRed); - EXPECT(pipelines::Drops::get().counts().draws == after.draws); - EXPECT(SUCCEEDED(alloc->Reset()) && SUCCEEDED(list->Reset(alloc.p, nullptr))); - list->SetComputeRootSignature(cs_rs.p); - list->SetPipelineState(cs_pso.p); // waits within the new frame's compute window, then records - list->Dispatch(1, 1, 1); - EXPECT(count_draws(list.p, true) == 1 && SUCCEEDED(list->Close())); - std::printf("d3d12_async_pipeline_test: the %d pipelines were made in %.0f ms on the workers; the next frame drew " - "all %d\n", kMany, made_ms, kMany); - - // 3. The early list: what this run bound is written; the next run starts it at creation, and not what it did not - // bind. - std::string keys[3]; - pipelines::begin_frame(); - pipelines::set_wait_budget(10s); // the binds wait for these, so their draws run - { - Ref a, b, c; - EXPECT(SUCCEEDED(make_pso(1001, &a.p)) && SUCCEEDED(make_pso(1002, &b.p)) && SUCCEEDED(make_pso(1003, &c.p))); - keys[0] = rt::d3d12::pipeline_early_key(a.p); - keys[1] = rt::d3d12::pipeline_early_key(b.p); - keys[2] = rt::d3d12::pipeline_early_key(c.p); - EXPECT(keys[0].size() == 32 && keys[0] != keys[1] && keys[1] != keys[2]); - EXPECT(draw_with({a.p, b.p}, colour, recorded) && recorded == 2 && colour == kRed); - } - EXPECT(pipelines::EarlyList::get().save(true) || std::filesystem::exists(early_file)); - std::set listed; - { - std::ifstream in(early_file, std::ios::binary); - std::string line; - while (std::getline(in, line)) listed.insert(line); - } - EXPECT(listed.count(keys[0]) && listed.count(keys[1]) && !listed.count(keys[2])); - EXPECT(listed.count(rt::d3d12::pipeline_early_key(raw.front()))); - std::printf("d3d12_async_pipeline_test: the early list holds %zu pipelines this run bound\n", listed.size()); - many.clear(); - raw.clear(); - pipelines::EarlyList::get().reload(); // as the next run reads it - pipelines::Builder::get().hold(true); - const std::uint64_t early_before = pipelines::Builder::get().stats().started_early; - { - Ref a, b, c; - EXPECT(SUCCEEDED(make_pso(1001, &a.p)) && SUCCEEDED(make_pso(1002, &b.p)) && SUCCEEDED(make_pso(1003, &c.p))); - const pipelines::Job* ja = rt::d3d12::pipeline_job(a.p); - const pipelines::Job* jb = rt::d3d12::pipeline_job(b.p); - const pipelines::Job* jc = rt::d3d12::pipeline_job(c.p); - const bool workers = pipelines::worker_count() > 0; - if (workers) { - EXPECT(ja->queue_state() == pipelines::kEarly && jb->queue_state() == pipelines::kEarly); - EXPECT(pipelines::Builder::get().stats().started_early == early_before + 2); - } - EXPECT(jc->queue_state() == pipelines::kNotQueued); - pipelines::Builder::get().hold(false); - EXPECT(const_cast(ja)->wait_finished_for(60s) && ja->ready()); - EXPECT(const_cast(jb)->wait_finished_for(60s) && jb->ready()); - EXPECT(jc->queue_state() == pipelines::kNotQueued && !jc->finished()); // never bound, so not started - std::printf("d3d12_async_pipeline_test: read back, the 2 listed PSOs were made at creation without a bind; the " - "unlisted one was not started\n"); - } - - // 4. Console device slot 86: a stream reaches the layer's stream PSO, the same as ID3D12Device2's. - { - std::vector stream; - append(stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, gfx_rs.p); - append(stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, gfx_desc.VS); - append(stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, gfx_desc.PS); - append(stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, gfx_desc.InputLayout); - append(stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, gfx_desc.PrimitiveTopologyType); - D3D12_RT_FORMAT_ARRAY formats{}; - formats.NumRenderTargets = 1; - formats.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; - append(stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, formats); - const D3D12_PIPELINE_STATE_STREAM_DESC stream_desc{stream.size(), stream.data()}; - Ref pc; - EXPECT(SUCCEEDED(device->CreatePipelineState(&stream_desc, IID_PPV_ARGS(&pc.p)))); - device->AddRef(); // the proxy takes this reference - void* proxy = nullptr; - EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(device.p, __uuidof(ID3D12Device11), &proxy)) && proxy); - EXPECT(rt::d3d12_xs::device_proxy_console_layout(proxy)); - using CreateStreamFn = HRESULT(WINAPI*)(void*, const D3D12_PIPELINE_STATE_STREAM_DESC*, const IID*, void**); - const IID iid = __uuidof(ID3D12PipelineState); - void* console = nullptr; - EXPECT(SUCCEEDED(reinterpret_cast(slot(proxy, 86))(proxy, &stream_desc, &iid, &console)) && - console); - auto* console_pso = static_cast(console); - EXPECT(rt::d3d12::pipeline_job(console_pso) != nullptr); - EXPECT(rt::d3d12::pipeline_early_key(console_pso) == rt::d3d12::pipeline_early_key(pc.p)); - EXPECT(rt::d3d12::make_pipeline_now(console_pso)); - console_pso->Release(); - // A console stream with no shader (the title makes such streams): the layer refuses it, the title still gets - // a pipeline, and a draw with it is dropped and counted as refused. - std::vector empty; - append(empty, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, gfx_rs.p); - append(empty, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, D3D12_SHADER_BYTECODE{}); - append(empty, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, D3D12_SHADER_BYTECODE{}); - append(empty, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, formats); - const D3D12_PIPELINE_STATE_STREAM_DESC empty_desc{empty.size(), empty.data()}; - Ref refused_pc; - EXPECT(device->CreatePipelineState(&empty_desc, IID_PPV_ARGS(&refused_pc.p)) == E_INVALIDARG && !refused_pc.p); - void* refused = nullptr; - EXPECT(SUCCEEDED(reinterpret_cast(slot(proxy, 86))(proxy, &empty_desc, &iid, &refused)) && - refused); - auto* refused_pso = static_cast(refused); - const pipelines::Job* refused_job = rt::d3d12::pipeline_job(refused_pso); - EXPECT(refused_job && refused_job->finished() && !refused_job->ready()); - const std::uint64_t refused_before = pipelines::Drops::get().counts().refused; - EXPECT(draw_with({refused_pso}, colour, recorded) && recorded == 0 && colour == kBlue); - EXPECT(pipelines::Drops::get().counts().refused == refused_before + 1); - refused_pso->Release(); - static_cast(proxy)->Release(); - std::printf("d3d12_async_pipeline_test: console slot 86 made the stream PSO, and handed a pipeline that is never " - "made for a stream without shaders (its draw dropped as refused)\n"); - } - - pipelines::set_wait_budget(std::chrono::milliseconds(pipelines::kDefaultWaitMs)); - EXPECT(d.validation_errors() == 0); - std::printf("d3d12_async_pipeline_test: ok\n"); - return 0; -} diff --git a/runtime/test/d3d12_depth_twin_test.cpp b/runtime/test/d3d12_depth_twin_test.cpp deleted file mode 100644 index d6669cdc7..000000000 --- a/runtime/test/d3d12_depth_twin_test.cpp +++ /dev/null @@ -1,345 +0,0 @@ -// Depth textures that also allow unordered access, through the Xbox-ABI proxy over the Vulkan device. The console -// lets a texture be ALLOW_DEPTH_STENCIL | ALLOW_UNORDERED_ACCESS (the title makes a 2560x1440 R32G8X24_TYPELESS one, -// flags 0x6, and its tiled lighting writes each pixel's material class into the stencil plane through a UAV); the PC -// runtime and Vulkan do not. The layer gives such a texture colour twins that carry its UAVs (VIctory's, victory-gpu -// resource.rs twin_texture): R32 for the depth plane, R8_UINT for the stencil plane, and copies one side into the -// other where the title switches between them (docs/d3d12_vulkan.md, "Depth textures with unordered access"). -// -// 1. Console slot 76 makes a 64x64 R32G8X24_TYPELESS texture with flags 0x6; the PC CreateCommittedResource of the -// same description is refused, as the PC runtime refuses it. -// 2. Its UAV of plane 1 is an 8_UINT T#, of plane 0 a 32_FLOAT one: views of the twins. -// 3. List A clears the depth to 0.25 and the stencil to 0x11, moves the texture to UNORDERED_ACCESS and runs a -// dispatch that writes a pattern into the left half of the stencil plane through its UAV. List B (executed after -// it, in a second ExecuteCommandLists) writes the left three quarters of the depth plane through its UAV, moves the -// texture to COPY_SOURCE and copies both planes into a readback buffer: the shaders' texels where they wrote, -// the clear values elsewhere (the twins were given the depth texture when it entered UNORDERED_ACCESS, and the -// depth texture was given the twins when it left). -// 4. List C clears to 0.75 / 0x22, writes another stencil pattern into the left quarter and copies both planes out -// again: the twins were given the new clear before the dispatch, and nothing of list A's pattern is left. -// Run with LEONIDA_DEPTH_TWIN_COPY=buffer, the copies go through a buffer instead of vkCmdCopyImage between the -// depth and colour images (VK_KHR_maintenance8); the results must be the same. -// No game data: the program is a few marker words and the module is GLSL written to the translator's contract. -// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (0 errors required). -#include "shader_fixture_path.h" -#include "test_temp_dir.h" -#include "vk_test_device.h" -#include "d3d12_test_shaders.h" -#include "../shims/d3d12_com.h" -#include "../shims/d3d12_xs_device.h" -#include "../src/gfx10_descriptors.h" -#include "../src/shader_library.h" -#include "../src/vulkan_replay.h" - -#include -#include -#include -#include -#include -#include - -#ifndef LEONIDA_TEST_CS_DEPTH_TWIN_SPV -#error "LEONIDA_TEST_CS_DEPTH_TWIN_SPV must name the compiled test shader" -#endif - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -using namespace d3d12test; -using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX -using XboxCreateResourceFn = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS, - const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES, - const D3D12_CLEAR_VALUE*, const IID*, void**); - -namespace { - -namespace g = leonida::gfx10; - -constexpr UINT kSize = 64, kPitch = 256, kDepthOffset = kPitch * kSize, kReadbackBytes = 2 * kPitch * kSize; - -std::uint8_t stencil_pattern(UINT x, UINT y, UINT seed) { return std::uint8_t((x * 7 + y * 13 + seed) & 255); } -float depth_pattern(UINT x, UINT y) { return float((x + 64 * y) % 997) / 1024.0f; } - -// GFX10 T# word 1 bits 20..28: the FORMAT field. -std::uint32_t tsharp_format(std::uint64_t descriptor) { - std::uint32_t words[8] = {}; - std::memcpy(words, reinterpret_cast(descriptor), sizeof(words)); - return (words[1] >> 20) & 0x1ff; -} - -// The readback of one round: stencil bytes at 0, depth floats at kDepthOffset, both with a 256-byte pitch. -unsigned check(const std::uint8_t* bytes, const char* round, UINT stencil_columns, UINT seed, std::uint8_t stencil_clear, - UINT depth_columns, float depth_clear) { - unsigned wrong = 0; - for (UINT y = 0; y < kSize; ++y) { - for (UINT x = 0; x < kSize; ++x) { - const std::uint8_t stencil = bytes[y * kPitch + x]; - const std::uint8_t want_stencil = x < stencil_columns ? stencil_pattern(x, y, seed) : stencil_clear; - if (stencil != want_stencil && wrong++ < 8) - std::fprintf(stderr, "%s: stencil (%u, %u) = 0x%02x, want 0x%02x\n", round, x, y, stencil, want_stencil); - float depth = 0; - std::memcpy(&depth, bytes + kDepthOffset + y * kPitch + x * 4, sizeof(depth)); - const float want_depth = x < depth_columns ? depth_pattern(x, y) : depth_clear; - if (depth != want_depth && wrong++ < 8) - std::fprintf(stderr, "%s: depth (%u, %u) = %.6f, want %.6f\n", round, x, y, depth, want_depth); - } - } - return wrong; -} - -} // namespace - -int main() { - vktest::Device d; - d.request_maintenance8 = true; - const auto device_status = d.initialize(); - if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips - if (device_status != vktest::DeviceStatus::ready) return 1; - if (!d.bindless) { - std::printf("SKIP: the device lacks the descriptor indexing features of the bindless set 0\n"); - return 77; - } - const char* copy_mode = std::getenv("LEONIDA_DEPTH_TWIN_COPY"); - const bool through_buffer = !d.maintenance8 || (copy_mode && std::strcmp(copy_mode, "buffer") == 0); - - const auto program = fssm_program({0x43530004, 0xbf810000, 0x0d0e0f10}); - const auto container = shader_container(program); - const testfiles::ScratchDir scratch("leonida_depth_twin_test"); - const auto& library = scratch.path(); - EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_DEPTH_TWIN_SPV), - library / "cs_depth_twin.spv")); - { - std::ofstream index(library / "index.json", std::ios::binary); - index << "{\"cs_depth_twin\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(program) - << "\", \"bindings\": [2, 8, 9], \"push_constant_bytes\": 144, \"local_size\": [8, 8, 1], " - "\"uses_code_base\": false, \"wave64\": false}}"; - } - - std::vector round1(kReadbackBytes), round2(kReadbackBytes); - const leonida::DepthTwinCounts before = leonida::depth_twin_counts(); - leonida::DepthTwinCounts after_round1{}; - { - rt::d3d12::VulkanDeviceInfo info{}; - info.get_instance_proc = d.instance_proc; - info.instance = d.instance; - info.physical = d.physical; - info.device = d.device; - info.queue = d.queue; - info.queue_family = d.family; - info.buffer_device_address = true; - info.bindless = d.bindless; - info.bindless_partially_bound = d.partially_bound; - info.image_view_min_lod = d.image_view_min_lod; - info.maintenance8 = d.maintenance8; - info.shader_dir = library.string(); - ID3D12Device* inner = nullptr; - EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); - Ref device; - EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); - rt::d3d12::set_device_outer(inner, device.p); - if (rt::d3d12::device_push_constants_need_fallback(inner)) { - std::printf("d3d12_depth_twin_test: skipped, the PSOs need 144 push-constant bytes and this GPU has %u\n", - rt::d3d12::device_max_push_constants_size(inner)); - return 77; - } - - // 1. The texture through console slot 76; the PC method refuses the same description. - D3D12_RESOURCE_DESC desc{}; - desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - desc.Width = desc.Height = kSize; - desc.DepthOrArraySize = 1; - desc.MipLevels = 1; - desc.Format = DXGI_FORMAT_R32G8X24_TYPELESS; - desc.SampleDesc.Count = 1; - desc.Flags = static_cast(D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | - D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); - const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; - const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; - Ref refused; - EXPECT(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, - D3D12_RESOURCE_STATE_DEPTH_WRITE, nullptr, - IID_PPV_ARGS(&refused.p)) == E_INVALIDARG && !refused.p); - D3D12_RESOURCE_DESC xbox_desc = desc; - xbox_desc.Layout = static_cast(0x101); // the Xbox tiled layout word - const IID resource_iid = __uuidof(ID3D12Resource); - Ref depth, readback; - EXPECT(SUCCEEDED(reinterpret_cast(slot(device.p, 76))( - device.p, &default_heap, D3D12_HEAP_FLAG_NONE, &xbox_desc, D3D12_RESOURCE_STATE_DEPTH_WRITE, nullptr, - &resource_iid, reinterpret_cast(&depth.p)))); - EXPECT(depth->GetDesc().Flags == desc.Flags); - const auto readback_desc = buffer_desc(kReadbackBytes); - EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, - D3D12_RESOURCE_STATE_COPY_DEST, nullptr, - IID_PPV_ARGS(&readback.p)))); - - // Root signature, in the console compute layout: [0] four constants (s4..s7), [1] the table of views (s8). - D3D12_DESCRIPTOR_RANGE view_range{D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 2, 0, 0, 0}; - D3D12_ROOT_PARAMETER params[2] = {}; - params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; - params[0].Constants = {0, 0, 4}; - params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - params[1].DescriptorTable = {1, &view_range}; - D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; - root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; - root_desc.Desc_1_0 = {2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; - const auto root_blob = serialize_root_signature(root_desc); - EXPECT(!root_blob.empty()); - Ref root; - EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p)))); - D3D12_COMPUTE_PIPELINE_STATE_DESC pso_desc{}; - pso_desc.pRootSignature = root.p; - pso_desc.CS = {container.data(), container.size()}; - Ref pso; - EXPECT(SUCCEEDED(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&pso.p)))); - - // The views: the two UAVs in a shader-visible heap (slot 0 the stencil plane, slot 1 the depth plane) and a - // DSV. Heap starts come back in RAX (heap slots 9 and 10). - const D3D12_DESCRIPTOR_HEAP_DESC view_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2, - D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; - const D3D12_DESCRIPTOR_HEAP_DESC dsv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, - 0}; - Ref view_heap, dsv_heap; - EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&view_heap_desc, IID_PPV_ARGS(&view_heap.p)))); - EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&dsv_heap_desc, IID_PPV_ARGS(&dsv_heap.p)))); - const std::uint64_t view_cpu = reinterpret_cast(slot(view_heap.p, 9))(view_heap.p); - const std::uint64_t view_gpu = reinterpret_cast(slot(view_heap.p, 10))(view_heap.p); - const std::uint64_t dsv_cpu = reinterpret_cast(slot(dsv_heap.p, 9))(dsv_heap.p); - const UINT view_step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); - EXPECT(view_cpu && dsv_cpu && view_gpu >= 0x10000 && view_gpu < (1ull << 32) && view_step % 4 == 0); - - // 2. The UAVs: of the twins, in their colour formats. - D3D12_UNORDERED_ACCESS_VIEW_DESC stencil_uav{}; - stencil_uav.Format = DXGI_FORMAT_X32_TYPELESS_G8X24_UINT; - stencil_uav.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; - stencil_uav.Texture2D = {0, 1}; - D3D12_UNORDERED_ACCESS_VIEW_DESC depth_uav{}; - depth_uav.Format = DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS; - depth_uav.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; - depth_uav.Texture2D = {0, 0}; - device->CreateUnorderedAccessView(depth.p, nullptr, &stencil_uav, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(view_cpu)}); - device->CreateUnorderedAccessView(depth.p, nullptr, &depth_uav, - D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(view_cpu + view_step)}); - EXPECT(tsharp_format(view_cpu) == g::format_from_vulkan(VK_FORMAT_R8_UINT)); - EXPECT(tsharp_format(view_cpu + view_step) == g::format_from_vulkan(VK_FORMAT_R32_SFLOAT)); - D3D12_DEPTH_STENCIL_VIEW_DESC dsv{}; - dsv.Format = DXGI_FORMAT_D32_FLOAT_S8X24_UINT; - dsv.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; - const D3D12_CPU_DESCRIPTOR_HANDLE dsv_handle{SIZE_T(dsv_cpu)}; - device->CreateDepthStencilView(depth.p, &dsv, dsv_handle); - - D3D12_COMMAND_QUEUE_DESC queue_desc{}; - Ref queue; - Ref allocator; - Ref list; - Ref fence; - EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); - EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); - EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, - IID_PPV_ARGS(&list.p)))); - EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); - UINT64 fence_value = 0; - const auto execute = [&]() -> bool { - if (list->Close() != S_OK) return false; - ID3D12CommandList* lists[] = {list.p}; - queue->ExecuteCommandLists(1, lists); - if (rt::d3d12::last_execute_result(queue.p) != leonida::ReplayResult::success) return false; - if (FAILED(queue->Signal(fence.p, ++fence_value)) || FAILED(fence->SetEventOnCompletion(fence_value, nullptr))) - return false; - return SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, nullptr)); - }; - ID3D12DescriptorHeap* heaps[] = {view_heap.p}; - const auto bind = [&] { - list->SetDescriptorHeaps(1, heaps); - list->SetComputeRootSignature(root.p); - list->SetPipelineState(pso.p); - list->SetComputeRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{view_gpu}); - }; - const auto dispatch = [&](UINT view, UINT plane_mode, UINT columns, UINT seed) { - const std::uint32_t constants[4] = {view * view_step / 4, plane_mode, columns, seed}; - list->SetComputeRoot32BitConstants(0, 4, constants, 0); - list->Dispatch(kSize / 8, kSize / 8, 1); - }; - const auto copy_out = [&] { - for (UINT plane = 0; plane < 2; ++plane) { - D3D12_TEXTURE_COPY_LOCATION dst{readback.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; - dst.PlacedFootprint = {plane ? 0u : kDepthOffset, - {plane ? DXGI_FORMAT_R8_TYPELESS : DXGI_FORMAT_R32_TYPELESS, kSize, kSize, 1, - kPitch}}; - D3D12_TEXTURE_COPY_LOCATION src{depth.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; - src.SubresourceIndex = plane; - list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); - } - }; - const auto read = [&](std::vector& out) -> bool { - void* mapped = nullptr; - if (FAILED(readback->Map(0, nullptr, &mapped))) return false; - std::memcpy(out.data(), mapped, out.size()); - readback->Unmap(0, nullptr); - return true; - }; - const D3D12_CLEAR_FLAGS both = D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL; - - // 3. List A: clear, into unordered access, the stencil plane's left half. List B: the depth plane's left - // three quarters, out of unordered access, both planes copied out. - list->ClearDepthStencilView(dsv_handle, both, 0.25f, 0x11, 0, nullptr); - D3D12_RESOURCE_BARRIER to_uav = - transition(depth.p, D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); - list->ResourceBarrier(1, &to_uav); - bind(); - dispatch(0, 0, kSize / 2, 5); - EXPECT(execute()); - bind(); - dispatch(1, 1, kSize * 3 / 4, 0); - D3D12_RESOURCE_BARRIER to_copy = - transition(depth.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); - list->ResourceBarrier(1, &to_copy); - copy_out(); - EXPECT(execute()); - EXPECT(read(round1)); - after_round1 = leonida::depth_twin_counts(); - - // 4. List C: a new clear, the stencil plane's left quarter, both planes copied out again. - D3D12_RESOURCE_BARRIER to_depth = - transition(depth.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_DEPTH_WRITE); - list->ResourceBarrier(1, &to_depth); - list->ClearDepthStencilView(dsv_handle, both, 0.75f, 0x22, 0, nullptr); - list->ResourceBarrier(1, &to_uav); - bind(); - dispatch(0, 0, kSize / 4, 9); - list->ResourceBarrier(1, &to_copy); - copy_out(); - EXPECT(execute()); - EXPECT(read(round2)); - - depth.reset(); - readback.reset(); - pso.reset(); - root.reset(); - view_heap.reset(); - dsv_heap.reset(); - list.reset(); - allocator.reset(); - queue.reset(); - fence.reset(); - EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); - } - const leonida::DepthTwinCounts after = leonida::depth_twin_counts(); - - EXPECT(check(round1.data(), "lists A and B", kSize / 2, 5, 0x11, kSize * 3 / 4, 0.25f) == 0); - EXPECT(check(round2.data(), "list C", kSize / 4, 9, 0x22, 0, 0.75f) == 0); - // Each round copied the depth texture into its twins once (into unordered access, after the clear) and the twins - // back once (out of it), both planes each time. - EXPECT(after_round1.to_twin - before.to_twin == 1 && after_round1.to_depth - before.to_depth == 1); - EXPECT(after.to_twin - before.to_twin == 2 && after.to_depth - before.to_depth == 2); - const std::uint64_t buffered = after.through_buffer - before.through_buffer; - EXPECT(buffered == (through_buffer ? 4u : 0u)); - if (d.validation_errors()) { - std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); - return 1; - } - std::printf("d3d12_depth_twin_test: OK, a 64x64 R32G8X24 depth texture's stencil and depth planes written " - "through UAVs (its twins) and read back by copies, two rounds; 2 copies into the twins and 2 back, %s\n", - through_buffer ? "through a buffer" : "with vkCmdCopyImage (VK_KHR_maintenance8)"); - return 0; -} diff --git a/runtime/test/d3d12_sampler2_test.cpp b/runtime/test/d3d12_sampler2_test.cpp index de3b88cd2..0dcc38b2e 100644 --- a/runtime/test/d3d12_sampler2_test.cpp +++ b/runtime/test/d3d12_sampler2_test.cpp @@ -396,87 +396,6 @@ int main() { const D3D12_SAMPLER_DESC2 any = desc2(border); device->CreateSampler2(&any, D3D12_CPU_DESCRIPTOR_HANDLE{0}); - // Sampler slots are one S# each, 16 bytes, as on the console (VIctory descriptor.rs:1-7); views stay 32. A - // sampler written into a slot leaves its neighbours as they were, and a copy moves whole S#s. - EXPECT(device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) == 16); - EXPECT(device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) == 32); - EXPECT(slots.size == 16); - { - const D3D12_CPU_DESCRIPTOR_HANDLE a = slots.take(), b = slots.take(), c = slots.take(); - EXPECT(b.ptr == a.ptr + 16 && c.ptr == b.ptr + 16); - device->CreateSampler(®ular, b); - EXPECT(slots.unwritten(a) && slots.unwritten(c) && words_of(slots.bytes(b)) == regular_words); - const D3D12_CPU_DESCRIPTOR_HANDLE d2 = slots.take(), e = slots.take(), f = slots.take(); - device->CopyDescriptorsSimple(2, d2, a, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER); - EXPECT(slots.unwritten(d2) && words_of(slots.bytes(e)) == regular_words && slots.unwritten(f)); - } - - // Xbox device slot 61, CreateSamplerX: the console's 27-word description (VIctory sampler.rs), whose filter - // words are the S#'s own fields. Where D3D12 can say the same, the S# is CreateSampler's. - { - namespace g = leonida::gfx10; - const auto bits = [](float v) { - std::uint32_t u = 0; - std::memcpy(&u, &v, sizeof(u)); - return u; - }; - bool written = true; - const auto via_x = [&](const std::array& words) { - const D3D12_CPU_DESCRIPTOR_HANDLE h = slots.take(); - written = rt::d3d12::create_sampler_x(device.p, words.data(), h.ptr) && written; - return slots.bytes(h); - }; - std::array x{}; - x[1] = 1; // bilinear magnification - x[2] = 1; // bilinear minification - x[3] = 2; // linear mips - x[6] = x[7] = x[8] = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; - x[10] = bits(1000.0f); - x[16] = D3D12_COMPARISON_FUNC_NEVER; - const D3D12_SAMPLER_DESC linear_clamp = sampler(D3D12_FILTER_MIN_MAG_MIP_LINEAR, - D3D12_TEXTURE_ADDRESS_MODE_CLAMP); - EXPECT(via_x(x) == via1(linear_clamp)); - // A real test makes a comparison sampler (LESS_EQUAL: compare 3 in the S#). - x[16] = D3D12_COMPARISON_FUNC_LESS_EQUAL; - auto compared = linear_clamp; - compared.Filter = D3D12_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR; - compared.ComparisonFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL; - EXPECT(via_x(x) == via1(compared)); - EXPECT(g::decode(words_of(via_x(x))).compare == g::CompareFunction::less_equal); - // ALWAYS is no test: a plain sampler, with no NEVER mark. - x[16] = D3D12_COMPARISON_FUNC_ALWAYS; - const g::Sampler always = g::decode(words_of(via_x(x))); - EXPECT(always.compare == g::CompareFunction::never && !always.compare_never && - !g::vulkan_sampler(always).compareEnable); - // What D3D12 cannot say: anisotropic point minification under bilinear magnification, no mip filter, a - // maximum filter, wrap/mirror/border, a bias and an opaque white border. - x[1] = 1; - x[2] = 2; - x[3] = 0; - x[5] = 2; - x[6] = D3D12_TEXTURE_ADDRESS_MODE_WRAP; - x[7] = D3D12_TEXTURE_ADDRESS_MODE_MIRROR; - x[8] = D3D12_TEXTURE_ADDRESS_MODE_BORDER; - x[9] = bits(1.5f); - x[10] = bits(7.0f); - x[11] = bits(-2.0f); - x[13] = 8; - x[16] = 0; - for (int i = 17; i < 21; ++i) x[i] = bits(1.0f); - const g::Sampler s = g::decode(words_of(via_x(x))); - EXPECT(s.mag_filter == g::Filter::bilinear && s.min_filter == g::Filter::aniso_point && - s.mip_filter == g::MipFilter::none && s.filter_mode == g::FilterMode::maximum); - EXPECT(s.max_anisotropy == 8 && s.address_u == g::AddressMode::wrap && s.address_v == g::AddressMode::mirror && - s.address_w == g::AddressMode::clamp_border && s.border_color == g::BorderColor::opaque_white); - EXPECT(s.min_lod == 1.5f && s.max_lod == 7.0f && s.lod_bias == -2.0f && s.compare == g::CompareFunction::never); - const VkSamplerCreateInfo vk = g::vulkan_sampler(s); - EXPECT(vk.anisotropyEnable && vk.maxAnisotropy == 8.0f && vk.magFilter == VK_FILTER_LINEAR && - vk.minFilter == VK_FILTER_NEAREST && vk.maxLod == 0.25f); - EXPECT(written); - // Not a Vulkan device: false, nothing written. - EXPECT(!rt::d3d12::create_sampler_x(nullptr, x.data(), slots.take().ptr)); - } - // D3D12_OPTIONS17: non-normalized samplers, no manual write tracking. D3D12_FEATURE_DATA_D3D12_OPTIONS17 ours17{}; EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS17, &ours17, sizeof(ours17)))); diff --git a/runtime/test/d3d12_title_memory_test.cpp b/runtime/test/d3d12_title_memory_test.cpp deleted file mode 100644 index 351e0b8a1..000000000 --- a/runtime/test/d3d12_title_memory_test.cpp +++ /dev/null @@ -1,1056 +0,0 @@ -// Title memory as GPU memory (src/title_memory.h): a GPU address is the title's CPU address, on the RTX 4060 Ti's -// capture-replay device addresses. Through the Xbox-ABI proxy over the standalone Vulkan device, with xmem connected -// to the layer as gta6rt connects it (rt::xmem::set_graphics_listener): -// - heap_base is title_memory::kHeapBase, xmem places graphics memory in [4 GiB, 512 GiB) and 32-bit graphics -// memory in [1 GiB, 4 GiB), and both are imported at heap_base + their addresses; -// - device slot 70 writes a V# whose base is the title address into a console descriptor heap that lies in the -// title's 32-bit memory, and a compute shader written to the translator's contract (test/glsl/cs_user_data.comp) -// reads the title's bytes through it and writes them into title memory through a root UAV at a title address, -// which the CPU reads back with no copy; -// - device slot 70 makes a texture from title memory, detiled from SW_64KB_D, whose image reads back as the -// linear texels; and whole textures in the console's layout (a SW_4KB_S 2D array with a mip tail, a SW_64KB_D -// BC1 chain, a thick 3D chain), every subresource; -// - console list slots 62 (CopyMemoryToMemoryX), 71/72 (Write32/Write64), 73 (WaitValue32, recorded) and 148 -// (AllocateUploadMemory) on title addresses; -// - list slots 73/74 hold the rest of their list until the value is in memory: a later submission's Write32 on -// another queue, a fence's value word after a Signal, or PresentX forcing it; Write64's GPU timestamp (written -// when the GPU gets there) and system timestamp (when the submission has run); -// - queue slot 31 (CopyPageMappingsBatchX) maps page-pool pages into another window, where the CPU and the GPU -// read them; -// - device slot 133 on mapped xmem physical pages: the buffer is bound to their import, at heap_base + its address; -// - the title's VirtualFree takes the imports off the GPU first; -// - with the title's allocator (its __XMemAllocationHooks__ through xmem, rt::d3d12::set_title_allocator), a slot-127 -// texture and committed buffers take their memory from it with VIctory's attributes, zeroed; the buffers sit on -// that title memory at heap_base + the address (a GPU copy lands in the title's pages), the texture reports the -// address, and each goes back through the title's free routine when released. -// 77 when the GPU has no bufferDeviceAddressCaptureReplay or VK_EXT_external_memory_host (title memory off). No game -// data. Set LEONIDA_VK_VALIDATION=1 for the validation layer. -#include "shader_fixture_path.h" -#include "test_temp_dir.h" -#include "../shims/d3d12_com.h" -#include "../shims/d3d12_xs_device.h" -#include "../shims/shims.h" -#include "../shims/xmem.h" -#include "../src/gfx10_descriptors.h" -#include "../src/gfx10_tiling.h" -#include "../src/shader_library.h" -#include "../src/title_memory.h" - -#include -#include -#include -#include -#include -#include -#include - -#ifndef LEONIDA_TEST_CS_SPV -#error "LEONIDA_TEST_CS_SPV must name the compiled test shader" -#endif - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "title memory line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -namespace { - -namespace tm = leonida::title_memory; - -template -struct Ref { - T* p = nullptr; - ~Ref() { reset(); } - void reset() { - if (p) p->Release(); - p = nullptr; - } - T* operator->() const { return p; } -}; - -using SerializeFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**); -using XMemAllocFn = void*(__stdcall*)(std::size_t, std::uint64_t); -using XMemFreeFn = void(__stdcall*)(void*, std::uint64_t); -using XMemVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, ULONGLONG, DWORD); -using XMemAllocatePhysicalPagesFn = BOOL(WINAPI*)(std::uint64_t, std::uint64_t*, std::uint64_t*); -using XMemFreePhysicalPagesFn = BOOL(WINAPI*)(std::uint64_t, const std::uint64_t*); -using XMemMapPhysicalPagesFn = void*(WINAPI*)(void*, std::uint64_t, const std::uint64_t*); -using VirtualFreeFn = BOOL(WINAPI*)(void*, SIZE_T, DWORD); -using Slot = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t); - -// ID3D12Device11, which gives the proxy the console layouts (d3d12_xs_slots.h). -constexpr GUID kDevice11{0x5405c344, 0xd457, 0x444e, {0xb4, 0xdd, 0x23, 0x66, 0xe4, 0x5a, 0xee, 0x39}}; -constexpr DWORD kXmem64kPages = 0x20400000; -constexpr std::uint64_t kGraphics = 0x183, kGraphics32 = 0x7; // the retail title's attribute words - -std::uint64_t call(void* object, unsigned slot, std::uint64_t a1 = 0, std::uint64_t a2 = 0, std::uint64_t a3 = 0, - std::uint64_t a4 = 0, std::uint64_t a5 = 0, std::uint64_t a6 = 0) { - return reinterpret_cast((*static_cast(object))[slot])(object, a1, a2, a3, a4, a5, a6); -} -template -std::uint64_t word(T* p) { return reinterpret_cast(p); } -HRESULT hr_from(std::uint64_t r) { return static_cast(static_cast(r)); } - -void put32(std::vector& out, std::uint32_t v) { - for (int i = 0; i < 4; ++i) out.push_back(std::uint8_t(v >> (8 * i))); -} - -std::vector zlib_stored(const std::vector& data) { - std::vector out = {0x78, 0x01, 0x01}; - const auto length = std::uint16_t(data.size()); - out.insert(out.end(), {std::uint8_t(length), std::uint8_t(length >> 8), std::uint8_t(~length), - std::uint8_t(~length >> 8)}); - out.insert(out.end(), data.begin(), data.end()); - std::uint32_t a = 1, b = 0; - for (const std::uint8_t x : data) { - a = (a + x) % 65521; - b = (b + a) % 65521; - } - const std::uint32_t adler = (b << 16) | a; - out.insert(out.end(), {std::uint8_t(adler >> 24), std::uint8_t(adler >> 16), std::uint8_t(adler >> 8), - std::uint8_t(adler)}); - return out; -} - -// DXBC { DXIL { stub, XDAT { 0x0D: XBCH + zlib(fssm) } } } (d3d12_compute_test's container). -std::vector shader_container(const std::vector& fssm) { - const auto stream = zlib_stored(fssm); - std::vector xbch = {'X', 'B', 'C', 'H'}; - for (const std::uint32_t v : {1u, std::uint32_t(stream.size()), 0u, std::uint32_t(fssm.size()), 0u}) put32(xbch, v); - xbch.insert(xbch.end(), stream.begin(), stream.end()); - std::vector dxil(16, 0); - dxil.insert(dxil.end(), {'X', 'D', 'A', 'T'}); - put32(dxil, 1); - put32(dxil, 12); - put32(dxil, 0x0d); - put32(dxil, 16 + 12 + 12); - put32(dxil, std::uint32_t(xbch.size())); - dxil.insert(dxil.end(), xbch.begin(), xbch.end()); - std::vector out = {'D', 'X', 'B', 'C'}; - out.resize(28, 0); - put32(out, 1); - put32(out, 36); - out.insert(out.end(), {'D', 'X', 'I', 'L'}); - put32(out, std::uint32_t(dxil.size())); - out.insert(out.end(), dxil.begin(), dxil.end()); - return out; -} - -std::vector serialize(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& desc) { - const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); - const auto fn = d3d12 ? reinterpret_cast( - reinterpret_cast(GetProcAddress(d3d12, "D3D12SerializeVersionedRootSignature"))) - : nullptr; - std::vector out; - ID3DBlob* blob = nullptr; - if (fn && SUCCEEDED(fn(&desc, &blob, nullptr)) && blob) { - const auto* p = static_cast(blob->GetBufferPointer()); - out.assign(p, p + blob->GetBufferSize()); - blob->Release(); - } - return out; -} - -D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes) { - D3D12_RESOURCE_DESC desc{}; - desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - desc.Width = bytes; - desc.Height = 1; - desc.DepthOrArraySize = 1; - desc.MipLevels = 1; - desc.SampleDesc.Count = 1; - desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - return desc; -} - -// The device's queue, a fence, and a submission waited for. -struct Runner { - Ref queue; - Ref fence; - UINT64 value = 0; - bool init(ID3D12Device* device) { - D3D12_COMMAND_QUEUE_DESC desc{}; - return SUCCEEDED(device->CreateCommandQueue(&desc, IID_PPV_ARGS(&queue.p))) && - SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))); - } - bool run(ID3D12GraphicsCommandList* list) { - ID3D12CommandList* lists[] = {list}; - queue->ExecuteCommandLists(1, lists); - if (FAILED(queue->Signal(fence.p, ++value))) return false; - const HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr); - const bool ok = SUCCEEDED(fence->SetEventOnCompletion(value, done)) && WaitForSingleObject(done, 10000) == 0; - CloseHandle(done); - return ok && rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success; - } -}; - -// A title's __XMemAllocationHooks__ (rt::xmem::set_allocation_hooks), as the retail title's render-target pool does -// it: the first allocation takes a 64 MiB pool from XMemAllocDefault with the D3D runtime's attributes, the rest are -// handed out of it in order (each 64 KiB-aligned). The pool's bytes are dirtied first: a committed resource must start -// zeroed whatever the allocator gives. -struct TitleAllocatorLog { - XMemAllocFn alloc_default = nullptr; - XMemFreeFn free_default = nullptr; - std::uint8_t* pool = nullptr; - std::uint64_t used = 0; - int allocs = 0, frees = 0; - std::vector> given; // (address, attributes) - std::vector> freed; - std::vector sizes; -}; -TitleAllocatorLog g_title; -constexpr std::uint64_t kTitlePool = 64 << 20; - -void* __stdcall title_pool_alloc(std::size_t size, std::uint64_t attributes) { - ++g_title.allocs; - if (!g_title.pool) { - g_title.pool = static_cast(g_title.alloc_default(kTitlePool, attributes)); - if (!g_title.pool) return nullptr; - std::memset(g_title.pool, 0xcd, kTitlePool); - } - const std::uint64_t at = (g_title.used + 0xffff) & ~std::uint64_t(0xffff); - if (at + size > kTitlePool) return nullptr; - g_title.used = at + size; - void* const p = g_title.pool + at; - g_title.given.emplace_back(reinterpret_cast(p), attributes); - g_title.sizes.push_back(size); - return p; -} - -void __stdcall title_pool_free(void* p, std::uint64_t attributes) { - ++g_title.frees; - g_title.freed.emplace_back(reinterpret_cast(p), attributes); -} - -void* g_title_hooks[2] = {reinterpret_cast(&title_pool_alloc), reinterpret_cast(&title_pool_free)}; - -// Whether `done` comes true within `ms` milliseconds. -template -bool within(unsigned ms, F&& done) { - const ULONGLONG until = GetTickCount64() + ms; - while (!done()) { - if (GetTickCount64() > until) return false; - Sleep(1); - } - return true; -} - -// A console queue, allocator and list of the proxy device; the list is open. -struct ConsoleQueue { - void* queue = nullptr; - void* allocator = nullptr; - void* list = nullptr; - bool make(void* device, D3D12_COMMAND_LIST_TYPE type) { - const D3D12_COMMAND_QUEUE_DESC desc{type, 0, D3D12_COMMAND_QUEUE_FLAG_NONE, 0}; - const IID queue_iid = __uuidof(ID3D12CommandQueue), allocator_iid = __uuidof(ID3D12CommandAllocator), - list_iid = __uuidof(ID3D12GraphicsCommandList); - struct { - std::uint32_t type, node_mask; - std::uint64_t reserved[2]; - } list_desc{std::uint32_t(type), 0, {0, 0}}; - return call(device, 8, word(&desc), word(&queue_iid), word(&queue)) == S_OK && - call(device, 9, type, word(&allocator_iid), word(&allocator)) == S_OK && - call(device, 73, word(&list_desc), word(allocator), 0, word(&list_iid), word(&list)) == S_OK; - } - // Close, ExecuteX (queue slot 35) and Reset for the next recording. - bool execute() { - if (hr_from(call(list, 9)) != S_OK) return false; - void* lists[] = {list}; - call(queue, 35, 1, word(lists), 0, 0); - return hr_from(call(list, 10, word(allocator), 0)) == S_OK; - } - ~ConsoleQueue() { - for (void* object : {list, allocator, queue}) - if (object) static_cast(object)->Release(); - } -}; - -std::uint64_t completed(void* fence) { return rt::d3d12_xs::fence_proxy_real_fence(fence)->GetCompletedValue(); } - -// Waits for memory values on the console queues: 0 when every check holds. -int waits_hold(void* device, std::uint64_t A) { - ConsoleQueue graphics, compute; - EXPECT(graphics.make(device, D3D12_COMMAND_LIST_TYPE_DIRECT) && compute.make(device, D3D12_COMMAND_LIST_TYPE_COMPUTE)); - const IID fence_iid = __uuidof(ID3D12Fence); - void* done = nullptr; - void* gate = nullptr; - EXPECT(call(device, 36, 0, 0, word(&fence_iid), word(&done)) == S_OK && - call(device, 36, 0, 0, word(&fence_iid), word(&gate)) == S_OK); - auto* const v = reinterpret_cast(A + 0x3C0000); // v[0] the gate value, v[1..] marks - for (int i = 0; i < 16; ++i) v[i] = 0; - - // 1. The compute queue's list: a mark, a wait for v[0] == 7, a second mark. The part before the wait runs; the - // part after it waits for the graphics queue's Write32, submitted later. - call(compute.list, 71, A + 0x3C0004, 0x11, 0, 0); - call(compute.list, 73, A + 0x3C0000, 3, 7); // WaitValue32: equal - call(compute.list, 71, A + 0x3C0008, 0x22, 0, 0); - EXPECT(compute.execute()); - EXPECT(call(compute.queue, 16, word(done), 1) == S_OK); // Signal behind the held part - EXPECT(within(5000, [&] { return v[1] == 0x11; })); - Sleep(50); - EXPECT(v[2] == 0 && completed(done) == 0); - call(graphics.list, 71, A + 0x3C0000, 7, 0, 0); - EXPECT(graphics.execute()); - EXPECT(within(5000, [&] { return v[2] == 0x22 && completed(done) == 1; })); - std::printf("title memory: a WaitValue32 held the rest of its compute list until a later graphics submission's " - "Write32 put the value in memory\n"); - - // 2. A WaitValue64 on a console fence's value word (fence slot 12): met when another queue's Signal reaches it. - const auto gate_word = call(gate, 12); - EXPECT(gate_word); - call(compute.list, 74, gate_word, 7, 5); // WaitValue64: greater-equal 5 - call(compute.list, 71, A + 0x3C000C, 0x33, 0, 0); - EXPECT(compute.execute()); - EXPECT(call(compute.queue, 16, word(done), 2) == S_OK); - Sleep(50); - EXPECT(v[3] == 0 && completed(done) == 1); - EXPECT(call(graphics.queue, 16, word(gate), 5) == S_OK); // the graphics queue signals the gate fence - EXPECT(within(5000, [&] { return v[3] == 0x33 && completed(done) == 2; })); - std::printf("title memory: a WaitValue64 on a fence's value word ran on once another queue signalled the fence\n"); - - // 3. A wait nothing meets runs at the next present (PresentX, queue slot 32), as VIctory's queues do. - call(compute.list, 73, A + 0x3C0010, 3, 99); - call(compute.list, 71, A + 0x3C0014, 0x44, 0, 0); - EXPECT(compute.execute()); - EXPECT(call(compute.queue, 16, word(done), 3) == S_OK); - Sleep(50); - EXPECT(v[5] == 0 && completed(done) == 2); - EXPECT(hr_from(call(graphics.queue, 32, 0, 0, 0)) == S_OK); - EXPECT(within(5000, [&] { return v[5] == 0x44 && completed(done) == 3; })); - std::printf("title memory: a wait nothing met ran on at the next PresentX\n"); - - // 5. Write64 timestamps: flag 1 the GPU's clock when the GPU gets there (a timestamp query resolved into the - // address), flag 2 QueryPerformanceCounter once the submission has run. Both are later than a calibration - // taken after the list was recorded and before it was executed. - { - auto* const stamps = reinterpret_cast(A + 0x3C0040); - stamps[0] = stamps[1] = 0; - call(graphics.list, 72, A + 0x3C0040, 0, 0, 1); // GPU timestamp - call(graphics.list, 72, A + 0x3C0048, 0, 0, 2); // system timestamp - call(graphics.list, 72, A + 0x3C0050, 0x1122334455667788ull, 0, 0); // a plain value beside them - EXPECT(hr_from(call(graphics.list, 9)) == S_OK); - Sleep(30); - ID3D12CommandQueue* const real = rt::d3d12_xs::queue_proxy_real_queue(graphics.queue); - UINT64 gpu0 = 0, cpu0 = 0, gpu1 = 0, cpu1 = 0; - EXPECT(SUCCEEDED(real->GetClockCalibration(&gpu0, &cpu0))); - void* lists[] = {graphics.list}; - call(graphics.queue, 35, 1, word(lists), 0, 0); - EXPECT(hr_from(call(graphics.list, 10, word(graphics.allocator), 0)) == S_OK); - EXPECT(call(graphics.queue, 16, word(done), 5) == S_OK); - EXPECT(within(5000, [&] { return completed(done) == 5 && stamps[1] != 0; })); - EXPECT(SUCCEEDED(real->GetClockCalibration(&gpu1, &cpu1))); - std::printf("title memory: GPU timestamp %llu in [%llu, %llu], system timestamp %llu in [%llu, %llu]\n", - static_cast(stamps[0]), static_cast(gpu0), - static_cast(gpu1), static_cast(stamps[1]), - static_cast(cpu0), static_cast(cpu1)); - EXPECT(stamps[0] >= gpu0 && stamps[0] <= gpu1); - EXPECT(stamps[1] >= cpu0 && stamps[1] <= cpu1); - EXPECT(stamps[2] == 0x1122334455667788ull); - std::printf("title memory: Write64 timestamps are written when the GPU gets there (flag 1) and when the " - "submission has run (flag 2)\n"); - } - - // 4. A wait whose value is there already holds nothing; one of a list without waits after it is not cut. - call(compute.list, 73, A + 0x3C0004, 3, 0x11); - call(compute.list, 71, A + 0x3C0018, 0x55, 0, 0); - EXPECT(compute.execute()); - EXPECT(call(compute.queue, 16, word(done), 6) == S_OK); - EXPECT(within(5000, [&] { return v[6] == 0x55 && completed(done) == 6; })); - static_cast(gate)->Release(); - static_cast(done)->Release(); - return 0; -} - -// As gta6rt connects it (src/main.cpp): with LEONIDA_TITLE_MEMORY=sparse xmem also reports physical pages as such. -const rt::xmem::GraphicsListener kListener{ - [](std::uintptr_t start, std::size_t size) { rt::d3d12::title_memory_visible(start, size); }, - [](std::uintptr_t start, std::size_t size) { rt::d3d12::title_memory_gone(start, size); }}; -const rt::xmem::GraphicsListener kSparseListener{ - [](std::uintptr_t start, std::size_t size) { rt::d3d12::title_memory_visible(start, size); }, - [](std::uintptr_t start, std::size_t size) { rt::d3d12::title_memory_gone(start, size); }, - [](std::uintptr_t start, std::size_t size, const void* backing) { - rt::d3d12::title_memory_mapped(start, size, backing); - }, - [](const void* backing, std::size_t size, bool alive) { rt::d3d12::title_memory_pool(backing, size, alive); }}; -bool sparse_wanted() { - char mode[16] = {}; - const DWORD n = GetEnvironmentVariableA("LEONIDA_TITLE_MEMORY", mode, sizeof(mode)); - return n && n < sizeof(mode) && std::strcmp(mode, "sparse") == 0; -} - -int run(ID3D12Device* inner, void* device, const std::vector& container) { - const auto virtual_alloc = reinterpret_cast(rt::shims::find("xmem.dll", "XMemVirtualAlloc")); - const auto allocate_pages = - reinterpret_cast(rt::shims::find("xmem.dll", "XMemAllocatePhysicalPages")); - const auto free_pages = reinterpret_cast(rt::shims::find("xmem.dll", "XMemFreePhysicalPages")); - const auto map_pages = reinterpret_cast(rt::shims::find("xmem.dll", "XMemMapPhysicalPages")); - const auto title_free = reinterpret_cast(rt::shims::find("kernel32.dll", "VirtualFree")); - EXPECT(virtual_alloc && allocate_pages && free_pages && map_pages && title_free); - - // ---- Placement and imports. - constexpr SIZE_T kPool = 4 << 20; - auto* pool = static_cast(virtual_alloc(nullptr, kPool, MEM_RESERVE | MEM_COMMIT, kGraphics, - PAGE_READWRITE)); - auto* low = static_cast(virtual_alloc(nullptr, 1 << 20, MEM_RESERVE | MEM_COMMIT, kGraphics32, - PAGE_READWRITE)); - EXPECT(pool && low); - const auto A = reinterpret_cast(pool), T = reinterpret_cast(low); - EXPECT(A >= tm::kWindowStart && A + kPool <= tm::kWindowEnd); - EXPECT(T >= tm::kLow32Start && T + (1 << 20) <= tm::kLow32End); - const rt::d3d12::TitleMemoryStats stats = rt::d3d12::title_memory_stats(inner); - EXPECT(stats.enabled && stats.heap_base == tm::kHeapBase && stats.imports >= 2 && !stats.failed); - EXPECT(rt::d3d12::title_memory_device_address(inner, A) == tm::kHeapBase + A); - EXPECT(rt::d3d12::title_memory_device_address(inner, A + kPool - 4) == tm::kHeapBase + A + kPool - 4); - EXPECT(rt::d3d12::title_memory_device_address(inner, T + 0x40) == tm::kHeapBase + T + 0x40); - std::printf("title memory: heap base 0x%llx, graphics memory at 0x%llx, 32-bit memory at 0x%llx, %llu imports\n", - static_cast(stats.heap_base), static_cast(A), - static_cast(T), static_cast(stats.imports)); - - // ---- Slot 70, a buffer: the V# is in a console heap in the 32-bit memory, its base the title address. - auto* words = reinterpret_cast(pool); - for (std::uint32_t i = 0; i < 64; ++i) words[i] = 0x5eed0000u + i * 7u; - std::uint32_t resource_words[14] = {}; - { - const D3D12_RESOURCE_DESC rd = buffer_desc(kPool); - std::memcpy(resource_words, &rd, sizeof(rd)); - resource_words[11] = 1; // the Xbox row-major layout word - resource_words[1] = 0xdeadbeef; // the padding, which the title leaves as its stack had it - } - std::uint32_t view_words[16] = {}; - { - D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; - srv.Format = DXGI_FORMAT_R32_TYPELESS; - srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; - srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - srv.Buffer.NumElements = 64; - srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; - std::memcpy(view_words, &srv, sizeof(srv)); - view_words[10] = static_cast(A); - view_words[11] = static_cast(A >> 32); - } - EXPECT(call(device, 70, word(resource_words), word(view_words), T) == 0); - leonida::gfx10::BufferWords vsharp{}; - std::memcpy(vsharp.data(), low, sizeof(vsharp)); - leonida::gfx10::Buffer decoded{}; - EXPECT(leonida::gfx10::decode(vsharp, decoded)); - EXPECT(decoded.address == A && decoded.num_records == 256); - - // A compute dispatch that reads it: s4 = 0, s5 = ~0 (V# mode), s6:s7 = a root UAV at title address A + 2 MiB, - // s8 = the table at T (cs_user_data.comp). - D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; - D3D12_ROOT_PARAMETER params[3] = {}; - params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; - params[0].Constants = {0, 0, 2}; - params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; - params[1].Descriptor = {0, 0}; - params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - params[2].DescriptorTable = {1, &range}; - D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; - root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; - root_desc.Desc_1_0 = {3, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; - const auto root_blob = serialize(root_desc); - EXPECT(!root_blob.empty()); - Ref root; - EXPECT(SUCCEEDED(inner->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p)))); - D3D12_COMPUTE_PIPELINE_STATE_DESC pso_desc{}; - pso_desc.pRootSignature = root.p; - pso_desc.CS = {container.data(), container.size()}; - Ref pso; - EXPECT(SUCCEEDED(inner->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&pso.p)))); - const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 64, - D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; - Ref heap; - EXPECT(SUCCEEDED(rt::d3d12::create_console_descriptor_heap(inner, &heap_desc, T, 64 * 32, - IID_PPV_ARGS(&heap.p)))); - Runner runner; - EXPECT(runner.init(inner)); - Ref allocator; - Ref list; - EXPECT(SUCCEEDED(inner->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); - EXPECT(SUCCEEDED(inner->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, - IID_PPV_ARGS(&list.p)))); - std::memset(pool + (2 << 20), 0, 256); - ID3D12DescriptorHeap* heaps[] = {heap.p}; - list->SetDescriptorHeaps(1, heaps); - list->SetComputeRootSignature(root.p); - list->SetPipelineState(pso.p); - const std::uint32_t srv_mode[2] = {0u, 0xFFFFFFFFu}; - list->SetComputeRoot32BitConstants(0, 2, srv_mode, 0); - list->SetComputeRootUnorderedAccessView(1, A + (2 << 20)); - list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{T}); - list->Dispatch(1, 1, 1); - EXPECT(SUCCEEDED(list->Close())); - EXPECT(runner.run(list.p)); - EXPECT(std::memcmp(pool + (2 << 20), pool, 256) == 0); - std::printf("title memory: a shader read 256 bytes through a slot-70 V# at title address 0x%llx in a heap at " - "0x%llx and wrote them through a root UAV at 0x%llx; the CPU sees them in place\n", - static_cast(A), static_cast(T), - static_cast(A + (2 << 20))); - - // ---- Slot 70, a texture: 64x64 RGBA8 in SW_64KB_D at A + 1 MiB, detiled into the texture it makes. - constexpr UINT kSide = 64; - std::vector linear(kSide * kSide * 4); - for (std::size_t i = 0; i < linear.size(); ++i) linear[i] = std::byte(i * 13 + (i >> 8)); - leonida::gfx10::TiledSurface2D surface; - EXPECT(leonida::gfx10::TiledSurface2D::make(leonida::gfx10::TileMode::sw_64kb_d, 4, kSide, kSide, surface)); - EXPECT(surface.tile(linear, std::span(reinterpret_cast(pool + (1 << 20)), - surface.tiled_size()), kSide * 4)); - std::uint32_t texture_words[14] = {}; - { - D3D12_RESOURCE_DESC td{}; - td.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - td.Width = kSide; - td.Height = kSide; - td.DepthOrArraySize = 1; - td.MipLevels = 1; - td.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - td.SampleDesc.Count = 1; - std::memcpy(texture_words, &td, sizeof(td)); - texture_words[11] = 0x10a; // 0x100 | SW_64KB_D - } - std::uint32_t texture_view[16] = {}; - { - D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; - srv.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; - srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - srv.Texture2D.MipLevels = 1; - std::memcpy(texture_view, &srv, sizeof(srv)); - const std::uint64_t at = A + (1 << 20); - texture_view[10] = static_cast(at); - texture_view[11] = static_cast(at >> 32); - } - EXPECT(call(device, 70, word(texture_words), word(texture_view), T + 32) == 0); - std::uint32_t tsharp[8] = {}; - std::memcpy(tsharp, low + 32, sizeof(tsharp)); - EXPECT(rt::d3d12::bindless_hash_lookup(inner, tsharp) != 0); - texture_words[13] = 0x1234; // other padding: the same texture (V resource.rs:2383-2396) - Ref texture; - texture.p = rt::d3d12::title_placed_texture(inner, A + (1 << 20), texture_words); - EXPECT(texture.p); - { - const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; - const auto readback_desc = buffer_desc(linear.size()); - Ref readback; - EXPECT(SUCCEEDED(inner->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, - D3D12_RESOURCE_STATE_COPY_DEST, nullptr, - IID_PPV_ARGS(&readback.p)))); - EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, nullptr))); - D3D12_TEXTURE_COPY_LOCATION src{texture.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}}; - D3D12_TEXTURE_COPY_LOCATION dst{readback.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}}; - dst.PlacedFootprint.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, kSide, kSide, 1, kSide * 4}; - list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); - EXPECT(SUCCEEDED(list->Close())); - EXPECT(runner.run(list.p)); - void* mapped = nullptr; - EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); - const bool same = std::memcmp(mapped, linear.data(), linear.size()) == 0; - readback->Unmap(0, nullptr); - EXPECT(same); - } - std::printf("title memory: a slot-70 texture view of a 64x64 SW_64KB_D texture in title memory reads back as " - "its linear texels\n"); - - // ---- Slot 70, whole textures in the console's layout (gfx10::ConsoleTexture, VIctory texture.rs): a 2D array - // with a mip chain and tail in SW_4KB_S, a BC1 chain in SW_64KB_D and a 3D chain in thick SW_4KB_S, every - // subresource read back as its linear texels. - { - namespace g = leonida::gfx10; - struct Case { - D3D12_RESOURCE_DIMENSION dimension; - UINT width, height, depth_or_array, mips; - DXGI_FORMAT format; - std::uint32_t layout_word; - std::uint64_t at; - } const cases[] = { - {D3D12_RESOURCE_DIMENSION_TEXTURE2D, 64, 32, 3, 4, DXGI_FORMAT_R8G8B8A8_UNORM, 0x105, A + 0x110000}, - {D3D12_RESOURCE_DIMENSION_TEXTURE2D, 256, 256, 1, 9, DXGI_FORMAT_BC1_UNORM, 0x10a, A + 0x140000}, - {D3D12_RESOURCE_DIMENSION_TEXTURE3D, 32, 16, 8, 3, DXGI_FORMAT_R8G8B8A8_UNORM, 0, A + 0x180000}, - }; - for (const Case& c : cases) { - g::ConsoleTextureDesc cd; - cd.dimension = c.dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? g::Dimension::tex3d : g::Dimension::tex2d; - cd.width = c.width; - cd.height = c.height; - cd.depth_or_array = c.depth_or_array; - cd.mips = c.mips; - cd.format = c.format; - cd.swizzle = c.layout_word ? (c.layout_word & 0xff) : g::swizzle::sw_4kb_s; - g::ConsoleTexture console; - EXPECT(g::ConsoleTexture::make(cd, false, console) && console.planes.size() == 1); - const g::TextureLayout& layout = console.planes[0].layout; - EXPECT(layout.addressable() && c.at + layout.size() <= A + (2 << 20)); - const bool three_d = cd.dimension == g::Dimension::tex3d; - const UINT slices = three_d ? 1 : c.depth_or_array; - const std::size_t n = layout.desc().element_bytes; - auto* const tiled = reinterpret_cast(c.at); - std::memset(tiled, 0, std::size_t(layout.size())); - std::vector> expected; // per subresource, rows packed - for (UINT slice = 0; slice < slices; ++slice) - for (UINT mip = 0; mip < c.mips; ++mip) { - const g::MipLayout& m = layout.mips()[mip]; - const std::size_t row = m.width * n, plane = row * m.height; - std::vector rows(plane * m.depth); - for (std::size_t i = 0; i < rows.size(); ++i) - rows[i] = std::byte(i * 29 + (i >> 7) + mip * 61 + slice * 17 + 1); - EXPECT(layout.tile(std::span(tiled, std::size_t(layout.size())), mip, slice, rows, - row, plane)); - expected.push_back(std::move(rows)); - } - std::uint32_t words14[14] = {}; - D3D12_RESOURCE_DESC td{}; - td.Dimension = c.dimension; - td.Width = c.width; - td.Height = c.height; - td.DepthOrArraySize = UINT16(c.depth_or_array); - td.MipLevels = UINT16(c.mips); - td.Format = c.format; - td.SampleDesc.Count = 1; - std::memcpy(words14, &td, sizeof(td)); - words14[11] = c.layout_word; - std::uint32_t view16[16] = {}; - D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; - srv.Format = c.format; - srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - if (three_d) { - srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; - srv.Texture3D.MipLevels = c.mips; - } else { - srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; - srv.Texture2DArray.MipLevels = c.mips; - srv.Texture2DArray.ArraySize = c.depth_or_array; - } - std::memcpy(view16, &srv, sizeof(srv)); - view16[10] = static_cast(c.at); - view16[11] = static_cast(c.at >> 32); - EXPECT(call(device, 70, word(words14), word(view16), T + 128) == 0); - Ref made; - made.p = rt::d3d12::title_placed_texture(inner, c.at, words14); - EXPECT(made.p); - const UINT subresources = slices * c.mips; - std::vector footprints(subresources); - std::vector row_counts(subresources); - std::vector row_bytes(subresources); - UINT64 total = 0; - const D3D12_RESOURCE_DESC made_desc = made->GetDesc(); - inner->GetCopyableFootprints(&made_desc, 0, subresources, 0, footprints.data(), row_counts.data(), - row_bytes.data(), &total); - const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; - const auto readback_desc = buffer_desc(total); - Ref readback; - EXPECT(SUCCEEDED(inner->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, - D3D12_RESOURCE_STATE_COPY_DEST, nullptr, - IID_PPV_ARGS(&readback.p)))); - EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, nullptr))); - for (UINT s = 0; s < subresources; ++s) { - D3D12_TEXTURE_COPY_LOCATION src{made.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}}; - src.SubresourceIndex = s; - D3D12_TEXTURE_COPY_LOCATION dst{readback.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}}; - dst.PlacedFootprint = footprints[s]; - list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); - } - EXPECT(SUCCEEDED(list->Close())); - EXPECT(runner.run(list.p)); - void* mapped = nullptr; - EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); - bool same = true; - for (UINT s = 0; s < subresources && same; ++s) { - const g::MipLayout& m = layout.mips()[s % c.mips]; - const std::size_t row = m.width * n; - const auto& f = footprints[s]; - for (UINT z = 0; z < m.depth && same; ++z) - for (UINT y = 0; y < m.height && same; ++y) - same = std::memcmp(static_cast(mapped) + f.Offset + - (std::size_t(z) * row_counts[s] + y) * f.Footprint.RowPitch, - expected[s].data() + (std::size_t(z) * m.height + y) * row, row) == 0; - if (!same) std::fprintf(stderr, "subresource %u of a %ux%u layout-0x%x texture differs\n", s, c.width, - c.height, c.layout_word); - } - readback->Unmap(0, nullptr); - EXPECT(same); - } - } - std::printf("title memory: slot-70 textures in the console's layout (a SW_4KB_S 2D array with a mip tail, a " - "SW_64KB_D BC1 chain, a thick 3D chain) read back as their linear texels, every subresource\n"); - - // ---- Slot 71: a structured buffer UAV (a V# at the title address plus the first element) and a texture UAV. - { - std::uint32_t uav_resource[14] = {}; - D3D12_RESOURCE_DESC rd = buffer_desc(kPool); - rd.Flags = static_cast(0x20004); // ALLOW_UNORDERED_ACCESS and an Xbox bit, as slot 133's - std::memcpy(uav_resource, &rd, sizeof(rd)); - std::uint32_t uav_view[16] = {}; - D3D12_UNORDERED_ACCESS_VIEW_DESC uav{}; - uav.Format = DXGI_FORMAT_UNKNOWN; - uav.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; - uav.Buffer.FirstElement = 16; - uav.Buffer.NumElements = 32; - uav.Buffer.StructureByteStride = 16; - std::memcpy(uav_view, &uav, sizeof(uav)); - uav_view[10] = static_cast(A); - uav_view[11] = static_cast(A >> 32); - EXPECT(call(device, 71, word(uav_resource), word(uav_view), T + 64) == 0); - leonida::gfx10::BufferWords uav_words{}; - std::memcpy(uav_words.data(), low + 64, sizeof(uav_words)); - leonida::gfx10::Buffer uav_buffer{}; - EXPECT(leonida::gfx10::decode(uav_words, uav_buffer)); - EXPECT(uav_buffer.address == A + 16 * 16 && uav_buffer.stride == 16 && uav_buffer.num_records == 32); - - std::uint32_t uav_texture[14] = {}; - std::memcpy(uav_texture, texture_words, sizeof(uav_texture)); - uav_texture[12] = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; - std::uint32_t texture_uav_view[16] = {}; - D3D12_UNORDERED_ACCESS_VIEW_DESC tuav{}; - tuav.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - tuav.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; - std::memcpy(texture_uav_view, &tuav, sizeof(tuav)); - texture_uav_view[10] = texture_view[10]; - texture_uav_view[11] = texture_view[11]; - EXPECT(call(device, 71, word(uav_texture), word(texture_uav_view), T + 96) == 0); - std::uint32_t uav_tsharp[8] = {}; - std::memcpy(uav_tsharp, low + 96, sizeof(uav_tsharp)); - EXPECT(rt::d3d12::bindless_hash_lookup(inner, uav_tsharp) != 0); - } - std::printf("title memory: slot 71 writes a structured V# at the title address and a texture UAV's T#\n"); - - // ---- Console list slots on title addresses, on a list from device slot 73. - void* console_allocator = nullptr; - const IID allocator_iid = __uuidof(ID3D12CommandAllocator); - EXPECT(call(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, word(&allocator_iid), word(&console_allocator)) == S_OK); - struct { - std::uint32_t type, node_mask; - std::uint64_t reserved[2]; - } list_desc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, {0, 0}}; - void* console_list = nullptr; - const IID list_iid = __uuidof(ID3D12GraphicsCommandList); - EXPECT(call(device, 73, word(&list_desc), word(console_allocator), 0, word(&list_iid), word(&console_list)) == S_OK); - EXPECT(rt::d3d12_xs::is_command_list_proxy(console_list)); - for (std::uint32_t i = 0; i < 1024; ++i) words[(3 << 20) / 4 + i] = 0; - call(console_list, 62, A + (3 << 20), A, 4096, 0); // CopyMemoryToMemoryX - call(console_list, 71, A + 0x3F0000, 0xCAFEF00Du, 0, 0); // Write32 - call(console_list, 72, A + 0x3F0008, 0x0123456789ABCDEFull, 0, 0); // Write64 - call(console_list, 73, A + 0x3F0000, 3, 0xCAFEF00Du); // WaitValue32: equal - auto* upload = reinterpret_cast(call(console_list, 148, 256, 256)); - EXPECT(upload && reinterpret_cast(upload) % 256 == 0); - EXPECT(call(console_list, 148, 8, 48) == 0); // not a power of two - const auto U = reinterpret_cast(upload); - EXPECT(U >= tm::kWindowStart && U + 256 <= tm::kWindowEnd); - EXPECT(rt::d3d12::title_memory_device_address(inner, U) == tm::kHeapBase + U); - for (int i = 0; i < 256; ++i) upload[i] = std::uint8_t(255 - i); - call(console_list, 62, A + 0x3E0000, U, 256, 0); // from the list's upload memory - rt::d3d12_xs::ValueWait waits[2] = {}; - EXPECT(rt::d3d12_xs::command_list_value_waits(console_list, waits, 2) == 1); - EXPECT(waits[0].address == A + 0x3F0000 && waits[0].comparison == 3 && !waits[0].wide); - EXPECT(!waits[0].met_by(0) && waits[0].met_by(0xCAFEF00Du) && waits[0].met_by(0x1CAFEF00Dull)); - EXPECT(hr_from(call(console_list, 9)) == S_OK); // Close - EXPECT(runner.run(rt::d3d12_xs::command_list_proxy_real_list(console_list))); - EXPECT(std::memcmp(pool + (3 << 20), pool, 4096) == 0); - EXPECT(words[0x3F0000 / 4] == 0xCAFEF00Du); - EXPECT(words[0x3F0008 / 4] == 0x89ABCDEFu && words[0x3F000C / 4] == 0x01234567u); - for (int i = 0; i < 256; ++i) EXPECT(pool[0x3E0000 + i] == std::uint8_t(255 - i)); - EXPECT(waits[0].met_by(words[0x3F0000 / 4])); - // Reset gives the upload memory back and forgets the waits. - EXPECT(hr_from(call(console_list, 10, word(console_allocator), 0)) == S_OK); - EXPECT(rt::d3d12_xs::command_list_value_waits(console_list, waits, 2) == 0); - std::printf("title memory: list slots 62, 71, 72 and 148 on title addresses, 73 recorded for the queue\n"); - EXPECT(hr_from(call(console_list, 9)) == S_OK); - static_cast(console_list)->Release(); - static_cast(console_allocator)->Release(); - - // ---- List slots 73/74 hold the rest of their list until the value is in memory (VIctory's cut): a later - // submission's Write32 on another queue, a fence's value word after a Signal, or a present that forces it. - { - EXPECT(waits_hold(device, A) == 0); - } - - // ---- Slot 133 on mapped physical pages: bound to their import. - constexpr std::uint64_t kPages = 4; - auto* window = static_cast(virtual_alloc(nullptr, kPages << 16, MEM_RESERVE | kXmem64kPages, 0x23, - PAGE_READWRITE)); - EXPECT(window); - std::uint64_t pages[kPages]{}; - std::uint64_t count = kPages; - EXPECT(allocate_pages(0x280, &count, pages) && count == kPages); - EXPECT(map_pages(window, kPages, pages) == window); - const auto W = reinterpret_cast(window); - EXPECT(rt::d3d12::title_memory_device_address(inner, W + 0x20000) == tm::kHeapBase + W + 0x20000); - { - D3D12_RESOURCE_DESC desc = buffer_desc(kPages << 16); - desc.Layout = static_cast(1); - const GUID resource_iid = __uuidof(ID3D12Resource); - Ref placed; - EXPECT(call(device, 133, W, word(&desc), 0xFFFFFFFFull, 0, word(&resource_iid), word(&placed.p)) == S_OK); - EXPECT(placed.p && placed->GetGPUVirtualAddress() == W); - // Remapping the pages takes the import off the GPU; the buffer keeps its memory until it goes. - } - EXPECT(map_pages(window, kPages, nullptr) == window); - EXPECT(rt::d3d12::title_memory_device_address(inner, W) == 0); - EXPECT(free_pages(count, pages)); - - // ---- Queue slot 31, CopyPageMappingsBatchX: a page pool's pages mapped again into another window (VIctory's page - // mapper, rt::xmem::map_alias). The CPU and the GPU see the pool's bytes there, and a kind-2 range unmaps it. - { - rt::d3d12_xs::set_page_mapper(&rt::xmem::map_alias); - constexpr std::uint64_t kPoolPages = 4, P = 0x10000; - auto* pool_window = static_cast( - virtual_alloc(nullptr, kPoolPages * P, MEM_RESERVE | kXmem64kPages, 0x23, PAGE_READWRITE)); - auto* tiled = static_cast( - virtual_alloc(nullptr, 4 * P, MEM_RESERVE | kXmem64kPages, 0x23, PAGE_READWRITE)); - EXPECT(pool_window && tiled); - std::uint64_t pool_pages[kPoolPages]{}; - std::uint64_t pool_count = kPoolPages; - EXPECT(allocate_pages(0x280, &pool_count, pool_pages) && pool_count == kPoolPages); - EXPECT(map_pages(pool_window, kPoolPages, pool_pages) == pool_window); - for (std::uint64_t p = 0; p < kPoolPages; ++p) - for (std::uint64_t i = 0; i < P; ++i) pool_window[p * P + i] = std::uint8_t(0x40 * p + i % 61); - const auto PW = reinterpret_cast(pool_window), D = reinterpret_cast(tiled); - std::uint64_t pool_handle = 0; - EXPECT(call(device, 74, PW, kPoolPages, word(&pool_handle)) == S_OK && pool_handle); - struct Range { - std::uint32_t kind, start, count; - }; - struct Batch { - std::uint64_t destination; - std::uint32_t count; - const Range* ranges; - }; - // Pool pages 2 and 3 at D and D + 64 KiB; pool page 0 at D + 128 KiB and D + 192 KiB. - const Range ranges[] = {{0, 2, 2}, {1, 0, 2}}; - const Batch batch{D, 2, ranges}; - ConsoleQueue gq; - EXPECT(gq.make(device, D3D12_COMMAND_LIST_TYPE_DIRECT)); - EXPECT(call(gq.queue, 31, 1, word(&batch), PW, kPoolPages, 0) == S_OK); - EXPECT(std::memcmp(tiled, pool_window + 2 * P, 2 * P) == 0); - EXPECT(std::memcmp(tiled + 2 * P, pool_window, P) == 0 && std::memcmp(tiled + 3 * P, pool_window, P) == 0); - tiled[3 * P + 5] = 0x77; // the same physical page as pool page 0 - EXPECT(pool_window[5] == 0x77 && tiled[2 * P + 5] == 0x77); - EXPECT(rt::d3d12::title_memory_device_address(inner, D + P) == tm::kHeapBase + D + P); - // The GPU reads the alias: CopyMemoryToMemoryX from D + 64 KiB (pool page 3) into the graphics memory at A. - const IID fence_iid = __uuidof(ID3D12Fence); - void* copied = nullptr; - EXPECT(call(device, 36, 0, 0, word(&fence_iid), word(&copied)) == S_OK); - std::memset(pool + (3 << 20), 0, P); - call(gq.list, 62, A + (3 << 20), D + P, P, 0); - EXPECT(gq.execute() && call(gq.queue, 16, word(copied), 1) == S_OK); - EXPECT(within(5000, [&] { return completed(copied) == 1; })); - EXPECT(std::memcmp(pool + (3 << 20), pool_window + 3 * P, P) == 0); - static_cast(copied)->Release(); - // Kind 2 unmaps the window's pages: its title memory leaves the GPU, and the pool keeps its pages. - const Range unmap{2, 0, 4}; - const Batch unmap_batch{D, 1, &unmap}; - EXPECT(call(gq.queue, 31, 1, word(&unmap_batch), PW, kPoolPages, 0) == S_OK); - EXPECT(rt::d3d12::title_memory_device_address(inner, D) == 0 && - rt::d3d12::title_memory_device_address(inner, D + 3 * P) == 0); - MEMORY_BASIC_INFORMATION region{}; - EXPECT(VirtualQuery(tiled, ®ion, sizeof(region)) && region.State == MEM_RESERVE); - EXPECT(pool_window[5] == 0x77 && rt::d3d12::title_memory_device_address(inner, PW) == tm::kHeapBase + PW); - EXPECT(call(device, 75, pool_handle) == S_OK); - EXPECT(map_pages(pool_window, kPoolPages, nullptr) == pool_window && free_pages(pool_count, pool_pages)); - rt::d3d12_xs::set_page_mapper(nullptr); - std::printf("title memory: queue slot 31 mapped page-pool pages into another window (in order and one page " - "twice); the CPU and a GPU copy read them there, and an unmap range took them off the GPU\n"); - } - - // ---- The title's VirtualFree takes the pool's imports off the GPU first. - const std::uint64_t before = rt::d3d12::title_memory_stats(inner).imports; - EXPECT(title_free(pool, 0, MEM_RELEASE)); - EXPECT(rt::d3d12::title_memory_device_address(inner, A) == 0); - EXPECT(rt::d3d12::title_memory_stats(inner).imports < before); - EXPECT(title_free(low, 0, MEM_RELEASE)); - EXPECT(rt::d3d12::title_memory_device_address(inner, T) == 0); - std::printf("title memory: slot 133 on mapped physical pages shares their import; unmapping and the title's " - "VirtualFree release the imports\n"); - return 0; -} - -// Committed resources from the title's allocator (rt::d3d12::set_title_allocator), wired as gta6rt wires it: xmem's -// XMemAlloc/XMemFree, which call the title's __XMemAllocationHooks__ routines (title_pool_alloc above). -int run_title_allocator(ID3D12Device* inner, void* device) { - g_title = TitleAllocatorLog{}; - g_title.alloc_default = reinterpret_cast(rt::shims::find("xmem.dll", "XMemAllocDefault")); - g_title.free_default = reinterpret_cast(rt::shims::find("xmem.dll", "XMemFreeDefault")); - EXPECT(g_title.alloc_default && g_title.free_default); - const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; - const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; - const D3D12_RESOURCE_DESC one_block = buffer_desc(1 << 16); - - // Without an allocator a committed buffer is the layer's own, in the arena, as before. - { - Ref before_hooks; - EXPECT(SUCCEEDED(inner->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &one_block, - D3D12_RESOURCE_STATE_COMMON, nullptr, - IID_PPV_ARGS(&before_hooks.p)))); - EXPECT(before_hooks->GetGPUVirtualAddress() < tm::kLow32Start && g_title.allocs == 0); - } - - rt::xmem::set_allocation_hooks(g_title_hooks); - rt::d3d12::set_title_allocator(&rt::xmem::title_alloc, &rt::xmem::title_free); - - // A back buffer through the console's slot 127 (CreateCommittedResource3), with the title's arguments: heap flag - // ALLOW_DISPLAY, flags RENDER_TARGET | UNORDERED_ACCESS, barrier layout 3. - D3D12_RESOURCE_DESC1 target{}; - target.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - target.Width = 256; - target.Height = 256; - target.DepthOrArraySize = 1; - target.MipLevels = 1; - target.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - target.SampleDesc.Count = 1; - target.Flags = static_cast(0x5); - D3D12_RESOURCE_DESC plain{}; - std::memcpy(&plain, &target, sizeof(plain)); - const D3D12_RESOURCE_ALLOCATION_INFO target_info = inner->GetResourceAllocationInfo(0, 1, &plain); - using Slot127 = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t); - const GUID resource_iid = __uuidof(ID3D12Resource); - Ref back_buffer; - EXPECT(hr_from(reinterpret_cast((*static_cast(device))[127])( - device, word(&default_heap), D3D12_HEAP_FLAG_ALLOW_DISPLAY, word(&target), 3, 0, 0, 0, 0, - word(&resource_iid), word(&back_buffer.p))) == S_OK); - EXPECT(back_buffer.p && g_title.allocs == 1 && g_title.given.size() == 1); - const std::uint64_t texture_at = g_title.given[0].first; - EXPECT(g_title.sizes[0] == target_info.SizeInBytes); - EXPECT(g_title.given[0].second == - tm::resource_attributes(target_info.SizeInBytes, target_info.Alignment, true)); - EXPECT(back_buffer->GetGPUVirtualAddress() == texture_at); - EXPECT(rt::d3d12::vulkan_image(back_buffer.p) != VK_NULL_HANDLE); - const auto pool = reinterpret_cast(g_title.pool); - EXPECT(pool && (pool & 0xffff) == 0 && tm::addressable(pool, kTitlePool)); // 64 KiB pages: under 2 MiB - for (std::uint64_t i = 0; i < target_info.SizeInBytes; i += 4096) - EXPECT(g_title.pool[texture_at - pool + i] == 0); // zeroed over the pool's 0xcd - - // Buffers: on their title memory, at heap_base + the title address. The upload buffer maps at its title address; - // a copy into the default-heap buffer lands in the title's pages. - constexpr UINT64 kBytes = 1 << 16; - const D3D12_RESOURCE_DESC upload_desc = buffer_desc(kBytes); - D3D12_RESOURCE_DESC uav = buffer_desc(kBytes); - uav.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; - Ref source, destination; - EXPECT(SUCCEEDED(inner->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc, - D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, - IID_PPV_ARGS(&source.p)))); - EXPECT(SUCCEEDED(inner->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &uav, - D3D12_RESOURCE_STATE_COMMON, nullptr, - IID_PPV_ARGS(&destination.p)))); - EXPECT(g_title.allocs == 3 && g_title.given.size() == 3); - const std::uint64_t S = g_title.given[1].first, D = g_title.given[2].first; - EXPECT(g_title.given[1].second == tm::resource_attributes(kBytes, 0x10000, false)); - EXPECT(g_title.given[2].second == tm::resource_attributes(kBytes, 0x10000, true)); - EXPECT(source->GetGPUVirtualAddress() == S && destination->GetGPUVirtualAddress() == D); - EXPECT(rt::d3d12::title_memory_device_address(inner, S) == tm::kHeapBase + S); - EXPECT(rt::d3d12::title_memory_device_address(inner, D + kBytes - 4) == tm::kHeapBase + D + kBytes - 4); - void* mapped = nullptr; - EXPECT(SUCCEEDED(source->Map(0, nullptr, &mapped)) && reinterpret_cast(mapped) == S); - // A default heap: the import path refuses it as the PC does; sparse title memory maps it at its title address, - // as the console (one memory) does, since the title maps such buffers (create_title_span). - { - void* default_mapped = nullptr; - const HRESULT hr = destination->Map(0, nullptr, &default_mapped); - EXPECT(hr == E_INVALIDARG || (SUCCEEDED(hr) && reinterpret_cast(default_mapped) == D)); - } - auto* src = reinterpret_cast(S); - auto* dst = reinterpret_cast(D); - for (UINT64 i = 0; i < kBytes; ++i) EXPECT(src[i] == 0 && dst[i] == 0); - for (UINT64 i = 0; i < kBytes; ++i) src[i] = std::uint8_t(i * 7 + 3); - { - Runner runner; - EXPECT(runner.init(inner)); - Ref allocator; - Ref list; - EXPECT(SUCCEEDED(inner->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); - EXPECT(SUCCEEDED(inner->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, - IID_PPV_ARGS(&list.p)))); - list->CopyBufferRegion(destination.p, 0, source.p, 0, kBytes); - EXPECT(SUCCEEDED(list->Close())); - EXPECT(runner.run(list.p)); - } - EXPECT(std::memcmp(dst, src, kBytes) == 0); - std::printf("title memory: committed resources from the title's allocator: a slot-127 texture reports 0x%llx, " - "buffers sit at 0x%llx and 0x%llx on their title memory; a GPU copy lands in the title's pages\n", - static_cast(texture_at), static_cast(S), - static_cast(D)); - - // Released: each goes back through the title's free routine with its address and attributes. - EXPECT(g_title.frees == 0); - back_buffer.reset(); - EXPECT(g_title.frees == 1 && g_title.freed[0] == g_title.given[0]); - destination.reset(); - source.reset(); - EXPECT(g_title.frees == 3 && g_title.freed[1] == g_title.given[2] && g_title.freed[2] == g_title.given[1]); - - // A refusal from the allocator is E_OUTOFMEMORY, with nothing made. - const D3D12_RESOURCE_DESC too_big_desc = buffer_desc(kTitlePool * 2); - Ref too_big; - EXPECT(inner->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &too_big_desc, - D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&too_big.p)) == - E_OUTOFMEMORY); - EXPECT(!too_big.p && g_title.frees == 3); - - rt::d3d12::set_title_allocator(nullptr, nullptr); - rt::xmem::set_allocation_hooks(nullptr); - { - Ref after_hooks; - EXPECT(SUCCEEDED(inner->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &one_block, - D3D12_RESOURCE_STATE_COMMON, nullptr, - IID_PPV_ARGS(&after_hooks.p)))); - EXPECT(after_hooks->GetGPUVirtualAddress() < tm::kLow32Start && g_title.allocs == 4); - } - g_title.free_default(g_title.pool, 0); - EXPECT(rt::d3d12::title_memory_device_address(inner, pool) == 0); - std::printf("title memory: released committed resources went back through the title's free routine\n"); - return 0; -} - -} // namespace - -int main() { - // The translator-style library cs_user_data.comp comes from, as d3d12_compute_test makes it. - constexpr std::uint32_t code_word = 7000; - std::vector fssm = {'F', 'S', 'S', 'M'}; - put32(fssm, code_word); - for (std::uint32_t i = 0; i < 14; ++i) put32(fssm, 0xbf810000u + i); - const auto container = shader_container(fssm); - const testfiles::ScratchDir scratch("leonida_title_memory_test"); - const auto& library = scratch.path(); - EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "cs_user_data.spv")); - { - std::ofstream index(library / "index.json", std::ios::binary); - index << "{\"cs_user_data\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(fssm) - << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"local_size\": [64, 1, 1], " - "\"uses_code_base\": true, \"wave64\": false}}"; - } - SetEnvironmentVariableW(L"LEONIDA_SHADERS", library.wstring().c_str()); - - ID3D12Device* inner = nullptr; - if (FAILED(rt::d3d12::create_vulkan_device_standalone(__uuidof(ID3D12Device), reinterpret_cast(&inner)))) { - std::printf("SKIP: no Vulkan device\n"); - return 77; - } - if (!rt::d3d12::title_memory_stats(inner).enabled) { - std::printf("SKIP: title memory is off on this GPU (no bufferDeviceAddressCaptureReplay or " - "VK_EXT_external_memory_host, or the driver refused the heap base)\n"); - inner->Release(); - return 77; - } - void* device = nullptr; - if (FAILED(rt::d3d12_xs::create_device_proxy(inner, kDevice11, &device))) { - inner->Release(); - return 1; - } - rt::d3d12::set_device_outer(inner, static_cast(device)); - // LEONIDA_TITLE_MEMORY=sparse (the ctest entry d3d12_title_memory_sparse): the same checks on sparse title memory, - // which must have taken (its self-test passed), or the run is skipped where the driver cannot. - if (sparse_wanted() && !rt::d3d12::title_memory_stats(inner).sparse) { - std::printf("SKIP: LEONIDA_TITLE_MEMORY=sparse did not take on this GPU (see the title memory line above)\n"); - static_cast(device)->Release(); - return 77; - } - rt::xmem::set_graphics_listener(sparse_wanted() ? &kSparseListener : &kListener); - int failures = run(inner, device, container); - if (!failures) failures = run_title_allocator(inner, device); - rt::xmem::set_graphics_listener(nullptr); - static_cast(device)->Release(); - if (!failures) std::printf("d3d12_title_memory_test: PASS\n"); - return failures ? 1 : 0; -} diff --git a/runtime/test/d3d12_xs_exports_test.cpp b/runtime/test/d3d12_xs_exports_test.cpp deleted file mode 100644 index e18a7f03e..000000000 --- a/runtime/test/d3d12_xs_exports_test.cpp +++ /dev/null @@ -1,55 +0,0 @@ -// d3d12_xs.dll's data and memory-setup exports, through the shim registry as the loader binds them, with no device -// and no GPU (ported behaviour from VIctory, victory-hle d3d12x.rs and victory-gpu device.rs, GPL-3.0-or-later): -// - IID_ID3D12Device is a data import: the registry entry is the address of the 16-byte id the title reads; -// - D3D12ConfigureVirtualMemoryX writes the range graphics addresses fall in (the process's user space) into the -// second half of the title's 32-byte block, keeps its policy words, and refuses a null block. -// No game data. -#include -#include - -#include -#include -#include - -#include "d3d12_xs_device.h" -#include "shims.h" - -namespace { - -int g_failures = 0; - -void check(bool condition, const char* what) { - std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); - if (!condition) ++g_failures; -} - -} // namespace - -int main() { - const void* iid = rt::shims::find("d3d12_xs.dll", "IID_ID3D12Device"); - check(iid && std::memcmp(iid, &__uuidof(ID3D12Device), sizeof(GUID)) == 0, - "IID_ID3D12Device is bound to the device's interface id"); - - using ConfigureFn = HRESULT(WINAPI*)(void*); - const auto configure = reinterpret_cast(rt::shims::find("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX")); - check(configure != nullptr, "D3D12ConfigureVirtualMemoryX is a shim"); - if (!configure) return 1; - rt::d3d12_xs::VirtualMemoryConfig config{}; - config.page_table_pages = 7; // the title zeroes the block and sets +4 - check(configure(&config) == S_OK, "the title's configuration is accepted"); - check(config.page_table_pages == 7 && config.flags == 0 && config.preserved_bytes == 0, - "the policy words are left as the title set them"); - check(config.lowest > 0 && config.lowest < config.highest, "a range is written"); - int local = 0; - const auto stack = reinterpret_cast(&local); - const auto heap = reinterpret_cast(GetProcessHeap()); - check(config.lowest <= stack && stack <= config.highest && config.lowest <= heap && heap <= config.highest, - "the range holds the process's own memory"); - std::uint64_t lowest = 0, highest = 0; - rt::d3d12_xs::user_address_range(lowest, highest); - check(lowest == config.lowest && highest == config.highest, "the range is the user address space"); - check(configure(nullptr) == E_INVALIDARG, "a null block is refused"); - - std::printf("d3d12_xs_exports_test: %s\n", g_failures ? "FAIL" : "PASS"); - return g_failures ? 1 : 0; -} diff --git a/runtime/test/dstorage_xs_test.cpp b/runtime/test/dstorage_xs_test.cpp deleted file mode 100644 index c7376aef5..000000000 --- a/runtime/test/dstorage_xs_test.cpp +++ /dev/null @@ -1,746 +0,0 @@ -// The DirectStorage shim (XCRDAPI.dll, shims/dstorage_xs.cpp) without game files: a synthetic file opened as a GAME: -// path and read through a queue, zlib streams compressed here, status arrays and the order they complete in, failed -// requests, the scheduler's choices (no workers), and destinations in xmem's physical pages. -// -// Ported with the shim from VIctory's crates/victory-hle/src/modules/dstorage.rs (GPL-3.0-or-later; Marvisak and -// contributors, DexNom fork); most cases are VIctory's own tests. Leonida is GPL-3.0-or-later too. -// -// Everything the title calls is reached the way it reaches it: DStorageGetFactory through rt::shims::find, then the -// method tables by byte offset. -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "dstorage_xs.h" -#include "file_system.h" -#include "shims.h" -#include "test_temp_dir.h" - -namespace { - -namespace ds = rt::dstorage; - -int g_checks = 0; -int g_failures = 0; - -void check(bool condition, const char* what) { - ++g_checks; - std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); - if (!condition) ++g_failures; -} - -std::string hex(HRESULT hr) { - char b[12]; - std::snprintf(b, sizeof b, "0x%08lx", static_cast(hr)); - return b; -} - -void check_hr(HRESULT got, std::int32_t want, const char* what) { - const bool ok = got == want; - if (!ok) std::printf(" got %s, want %s\n", hex(got).c_str(), hex(want).c_str()); - check(ok, what); -} - -// ---- Calling the shim as title code does - -using GetFactoryFn = HRESULT(__stdcall*)(const GUID*, void**); -using RefFn = ULONG(__stdcall*)(void*); -using OpenFileFn = HRESULT(__stdcall*)(void*, const wchar_t*, const GUID*, void**); -using CreateStatusArrayFn = HRESULT(__stdcall*)(void*, std::uint32_t, const char*, const GUID*, void**); -using SetStagingFn = HRESULT(__stdcall*)(void*, std::uint32_t); -using CreateQueueFn = HRESULT(__stdcall*)(void*, const ds::QueueDesc*, const GUID*, void**); -using EnqueueRequestFn = void(__stdcall*)(void*, const ds::Request*); -using EnqueueStatusFn = void(__stdcall*)(void*, void*, std::uint32_t); -using VoidFn = void(__stdcall*)(void*); -using IsCompleteFn = bool(__stdcall*)(void*, std::uint32_t); -using ResultFn = HRESULT(__stdcall*)(void*, std::uint32_t); - -// Method `slot` (a byte offset) of `object`. -template -F method(void* object, std::size_t slot) { - const void* const* table = *static_cast(object); - return reinterpret_cast(const_cast(table[slot / 8])); -} - -const GUID& factory_iid() { return *reinterpret_cast(&ds::kFactoryIid); } - -void* factory() { - static void* const f = [] { - const auto get = reinterpret_cast(rt::shims::find("xcrdapi.dll", "DStorageGetFactory")); - void* out = nullptr; - if (get) get(&factory_iid(), &out); - return out; - }(); - return f; -} - -HRESULT open(const wchar_t* path, void** file) { - *file = nullptr; - return method(factory(), ds::slot::kOpenFile)(factory(), path, nullptr, file); -} - -void* status_array(std::uint32_t capacity) { - void* array = nullptr; - method(factory(), ds::slot::kCreateStatusArray)(factory(), capacity, "test", nullptr, &array); - return array; -} - -void* new_queue(std::uint64_t source_type, std::uint16_t capacity = 0x80, std::int8_t priority = 0) { - const ds::QueueDesc desc{source_type, capacity, priority, "test", 1}; - void* queue = nullptr; - method(factory(), ds::slot::kCreateQueue)(factory(), &desc, nullptr, &queue); - return queue; -} - -ds::Request request(std::uint64_t options, void* destination, std::size_t destination_size, const void* source, - std::uint64_t offset, std::size_t source_size) { - ds::Request r{}; - r.options = options; - r.destination = destination; - r.destination_size = static_cast(destination_size); - r.source = source; - r.offset = offset; - r.source_size = static_cast(source_size); - return r; -} - -void enqueue(void* queue, const ds::Request& r) { - method(queue, ds::slot::kEnqueueRequest)(queue, &r); -} -void enqueue_status(void* queue, void* array, std::uint32_t index) { - method(queue, ds::slot::kEnqueueStatus)(queue, array, index); -} -void submit(void* queue) { method(queue, ds::slot::kSubmit)(queue); } -void close(void* queue) { method(queue, ds::slot::kClose)(queue); } -ULONG release(void* object) { return method(object, ds::slot::kRelease)(object); } - -HRESULT result(void* array, std::uint32_t index) { - return method(array, ds::slot::kGetResult)(array, index); -} - -// Polls as the title does, then gives the entry's result. -HRESULT wait(void* array, std::uint32_t index) { - const auto done = method(array, ds::slot::kIsComplete); - const auto start = std::chrono::steady_clock::now(); - while (!done(array, index)) { - if (std::chrono::steady_clock::now() - start > std::chrono::seconds(10)) { - std::printf(" status entry %u never completed\n", index); - return ds::kPending; - } - Sleep(1); - } - return result(array, index); -} - -std::vector pattern(std::size_t n) { - std::vector out(n); - for (std::size_t i = 0; i < n; ++i) out[i] = static_cast(i * 7 + i / 251); - return out; -} - -void write_file(const std::filesystem::path& path, const std::vector& bytes) { - std::filesystem::create_directories(path.parent_path()); - std::ofstream(path, std::ios::binary).write(reinterpret_cast(bytes.data()), - static_cast(bytes.size())); -} - -// ---- A zlib stream (RFC 1950) of one fixed-Huffman deflate block (RFC 1951 3.2.6), with greedy LZ77 matches from a -// 3-byte hash: literals, lengths and distances, for the shim's inflate to undo. - -class BitWriter { -public: - void bits(std::uint32_t value, int count) { // header fields and extra bits: least significant bit first - for (int i = 0; i < count; ++i) put((value >> i) & 1u); - } - void code(std::uint32_t value, int length) { // Huffman codes: most significant bit first - for (int i = length - 1; i >= 0; --i) put((value >> i) & 1u); - } - void byte(std::uint8_t b) { - used_ = 0; - bytes.push_back(b); - } - std::vector bytes; - -private: - void put(std::uint32_t bit) { - if (used_ == 0) bytes.push_back(0); - bytes.back() = static_cast(bytes.back() | (bit << used_)); - used_ = (used_ + 1) & 7u; - } - unsigned used_ = 0; -}; - -void fixed_symbol(BitWriter& w, unsigned symbol) { - if (symbol < 144) w.code(0x30 + symbol, 8); - else if (symbol < 256) w.code(0x190 + symbol - 144, 9); - else if (symbol < 280) w.code(symbol - 256, 7); - else w.code(0xc0 + symbol - 280, 8); -} - -void fixed_match(BitWriter& w, std::size_t length, std::size_t distance) { - static constexpr std::uint16_t length_base[29] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, - 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258}; - static constexpr std::uint8_t length_extra[29] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, - 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0}; - static constexpr std::uint16_t distance_base[30] = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, - 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, - 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577}; - static constexpr std::uint8_t distance_extra[30] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, - 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; - int l = 28; - while (length_base[l] > length) --l; - fixed_symbol(w, 257 + static_cast(l)); - w.bits(static_cast(length - length_base[l]), length_extra[l]); - int d = 29; - while (distance_base[d] > distance) --d; - w.code(static_cast(d), 5); - w.bits(static_cast(distance - distance_base[d]), distance_extra[d]); -} - -std::vector compress_zlib(const std::vector& plain) { - BitWriter w; - w.byte(0x78); // deflate, 32 KiB window - w.byte(0x01); // no dictionary; 0x7801 is a multiple of 31 - w.bits(1, 1); // the last block - w.bits(1, 2); // fixed Huffman codes - std::vector head(std::size_t(1) << 15, -1); - std::size_t i = 0; - while (i < plain.size()) { - std::size_t best = 0, distance = 0; - if (i + 3 <= plain.size()) { - const std::size_t h = ((std::size_t(plain[i]) << 10) ^ (std::size_t(plain[i + 1]) << 5) ^ plain[i + 2]) & - (head.size() - 1); - const std::int64_t candidate = head[h]; - head[h] = static_cast(i); - if (candidate >= 0 && i - static_cast(candidate) <= 32768) { - const std::size_t from = static_cast(candidate); - std::size_t n = 0; - while (n < 258 && i + n < plain.size() && plain[from + n] == plain[i + n]) ++n; - if (n >= 3) { - best = n; - distance = i - from; - } - } - } - if (best) { - fixed_match(w, best, distance); - i += best; - } else { - fixed_symbol(w, plain[i]); - ++i; - } - } - fixed_symbol(w, 256); - std::uint32_t a = 1, b = 0; - for (const std::uint8_t x : plain) { - a = (a + x) % 65521; - b = (b + a) % 65521; - } - const std::uint32_t adler = (b << 16) | a; - for (int s = 24; s >= 0; s -= 8) w.byte(static_cast(adler >> s)); - return w.bytes; -} - -// ---- xmem's physical pages, as the title gets them - -using XMemAllocatePhysicalPagesFn = BOOL(WINAPI*)(std::uint64_t, std::uint64_t*, std::uint64_t*); -using XMemFreePhysicalPagesFn = BOOL(WINAPI*)(std::uint64_t, const std::uint64_t*); -using XMemVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, ULONGLONG, DWORD); -using XMemMapPhysicalPagesFn = void*(WINAPI*)(void*, std::uint64_t, const std::uint64_t*); -constexpr DWORD kXmem64kPages = 0x20400000; - -struct Xmem { - XMemAllocatePhysicalPagesFn allocate = nullptr; - XMemFreePhysicalPagesFn free = nullptr; - XMemVirtualAllocFn virtual_alloc = nullptr; - XMemMapPhysicalPagesFn map = nullptr; - bool ok() const { return allocate && free && virtual_alloc && map; } - - std::vector pages(std::uint64_t n) const { - std::vector out(n); - std::uint64_t given = n; - if (!allocate(0, &given, out.data()) || given != n) out.clear(); - return out; - } - // A reserve-only window of 64 KiB pages with `pages` mapped in it, where the title would see them. - std::uint8_t* window(const std::vector& pages) const { - void* const at = virtual_alloc(nullptr, pages.size() * ds::kPage, MEM_RESERVE | kXmem64kPages, 0x21, - PAGE_READWRITE); - if (!at || map(at, pages.size(), pages.data()) != at) return nullptr; - return static_cast(at); - } - void unmap(std::uint8_t* at, std::size_t pages) const { - map(at, pages, nullptr); - VirtualFree(at, 0, MEM_RELEASE); - } -}; - -Xmem xmem() { - Xmem x; - x.allocate = reinterpret_cast(rt::shims::find("xmem.dll", "XMemAllocatePhysicalPages")); - x.free = reinterpret_cast(rt::shims::find("xmem.dll", "XMemFreePhysicalPages")); - x.virtual_alloc = reinterpret_cast(rt::shims::find("xmem.dll", "XMemVirtualAlloc")); - x.map = reinterpret_cast(rt::shims::find("xmem.dll", "XMemMapPhysicalPages")); - return x; -} - -// ---- The cases - -void factory_and_its_slots() { - const auto get = reinterpret_cast(rt::shims::find("xcrdapi.dll", "DStorageGetFactory")); - check(get != nullptr, "the registry serves xcrdapi.dll!DStorageGetFactory"); - if (!get) return; - void* out = nullptr; - check_hr(get(&factory_iid(), &out), ds::kOk, "DStorageGetFactory with the factory's interface id"); - check(out != nullptr && out == factory(), "the factory is one static object"); - GUID other = factory_iid(); - other.Data1 ^= 1; - void* none = nullptr; - check_hr(get(&other, &none), ds::kNoInterface, "another interface id is E_NOINTERFACE"); - check(none == nullptr, "and nothing is written for it"); - check_hr(get(&factory_iid(), nullptr), ds::kInvalidArg, "a null out pointer is E_INVALIDARG"); - check(method(out, ds::slot::kAddRef)(out) == 1 && method(out, ds::slot::kRelease)(out) == 1, - "the factory's AddRef and Release count nothing"); - check_hr(method(out, ds::slot::kSetStagingBufferSize)(out, 32u << 20), ds::kOk, - "a 32 MiB staging buffer is accepted (the title stops if not)"); - // A slot nobody has called answers E_NOTIMPL (and logs its offset once). - check_hr(method(out, 0x30)(out, 0), ds::kNotImpl, "an unknown factory slot is E_NOTIMPL"); -} - -void raw_and_zlib_reads_from_a_game_file(const std::filesystem::path& package) { - const std::vector plain = pattern(300000); - const std::vector packed = compress_zlib(plain); - std::vector contents = plain; - contents.insert(contents.end(), packed.begin(), packed.end()); - write_file(package / "data" / "stream.bin", contents); - - void* missing = nullptr; - check_hr(open(L"GAME:\\data\\absent.bin", &missing), static_cast(0x80070002u), - "opening a missing GAME: file is HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)"); - void* file = nullptr; - check_hr(open(L"GAME:\\data\\stream.bin", &file), ds::kOk, "a GAME: file opens through the file system shim"); - if (!file) return; - - void* const queue = new_queue(0); - void* const array = status_array(1); - check(queue && array, "a queue and a status array"); - std::vector raw(1000), inflated(plain.size()); - enqueue(queue, request(0, raw.data(), raw.size(), file, 5000, raw.size())); - enqueue(queue, request(ds::kZlib, inflated.data(), inflated.size(), file, plain.size(), packed.size())); - enqueue_status(queue, array, 0); - check_hr(result(array, 0), ds::kPending, "the status is pending until its requests are done"); - submit(queue); - check_hr(wait(array, 0), ds::kOk, "both requests complete with S_OK"); - check(std::equal(raw.begin(), raw.end(), plain.begin() + 5000), "the raw read holds the file's bytes"); - check(inflated == plain, "the zlib request inflates the stream the test compressed"); - check(packed.size() < plain.size() / 4, "and the stream was compressed, not stored"); - close(queue); - // Not the array: the worker drops its reference just after writing the entry, so it may still hold one here. - check(release(queue) == 0 && release(file) == 0, "a queue and a file go with their last Release"); - release(array); -} - -void memory_sources_inflate_too() { - const std::vector plain = pattern(70000); - const std::vector packed = compress_zlib(plain); - void* const queue = new_queue(1); - void* const array = status_array(1); - std::vector out(plain.size()); - enqueue(queue, request(ds::kZlib | ds::kMemorySource, out.data(), out.size(), packed.data(), 0, packed.size())); - enqueue_status(queue, array, 0); - submit(queue); - check_hr(wait(array, 0), ds::kOk, "a zlib request from memory completes"); - check(out == plain, "and inflates into its destination"); - release(queue); - release(array); -} - -// The title asks for the first bytes of a longer stream (8192 of a 16384-byte chunk after the start screen): the -// request succeeds with the stream's first destination_size bytes, and nothing past the destination is written. -void a_longer_stream_gives_its_first_bytes() { - const std::vector plain = pattern(16384); - const std::vector packed = compress_zlib(plain); - void* const queue = new_queue(1); - void* const array = status_array(1); - std::vector out(8192 + 64, std::uint8_t(0xcd)); - enqueue(queue, request(ds::kZlib | ds::kMemorySource, out.data(), 8192, packed.data(), 0, packed.size())); - enqueue_status(queue, array, 0); - submit(queue); - check_hr(wait(array, 0), ds::kOk, "a zlib stream longer than its destination completes"); - check(std::equal(out.begin(), out.begin() + 8192, plain.begin()), "with the stream's first bytes"); - check(std::all_of(out.begin() + 8192, out.end(), [](std::uint8_t b) { return b == 0xcd; }), - "and nothing past its destination"); - release(queue); - release(array); -} - -void statuses_complete_in_order_with_the_first_failure(const std::filesystem::path& package) { - const std::vector contents = pattern(4096); - write_file(package / "small.bin", contents); - void* file = nullptr; - open(L"GAME:\\small.bin", &file); - check(file != nullptr, "a second GAME: file opens"); - if (!file) return; - void* const queue = new_queue(0); - void* const array = status_array(5); - // Requests in flight together run in any order, so none of them shares a destination (failed ones leave theirs - // undefined). - std::array, 9> buffers{}; - auto at = [&](std::size_t i) { return static_cast(buffers[i].data()); }; - - // Segment 0: a read past the end, then a bad zlib stream; the first in queue order wins. - enqueue(queue, request(0, at(0), 16, file, 4090, 16)); - enqueue(queue, request(ds::kZlib, at(1), 16, file, 0, 16)); - enqueue_status(queue, array, 0); - // Segment 1: two reads. - enqueue(queue, request(0, at(2), 16, file, 0, 16)); - enqueue(queue, request(0, at(3), 16, file, 100, 16)); - enqueue_status(queue, array, 1); - submit(queue); - // Segment 2: BCPack (BC7) from the file, and zlib then BCPack (BC4) from memory: no decoder is linked - // (bcpack_decode_stub.cpp), so both fail as a stream the decoder rejects. - enqueue(queue, request(7 << 1, at(4), 16, file, 0, 16)); - const std::vector blocks = pattern(64); - const std::vector packed = compress_zlib(blocks); - ds::Request two_stages = request(ds::kZlib | (4 << 1) | ds::kMemorySource, at(5), 16, packed.data(), 0, - packed.size()); - two_stages.intermediate_size = static_cast(blocks.size()); - enqueue(queue, two_stages); - enqueue_status(queue, array, 2); - // Segment 3: an option bit no title package uses (bit 5, a further transform). - enqueue(queue, request(std::uint64_t{1} << 5, at(6), 16, file, 0, 16)); - enqueue_status(queue, array, 3); - // Segment 4: a raw read larger than its destination. - enqueue(queue, request(0, at(7), 8, file, 0, 16)); - enqueue_status(queue, array, 4); - submit(queue); - - check_hr(wait(array, 4), ds::kInvalidArg, "a raw read larger than its destination is E_INVALIDARG"); - check_hr(result(array, 3), ds::kNotImpl, "an unsupported option is E_NOTIMPL"); - check_hr(result(array, 2), ds::kInvalidData, - "a BCPack request the decoder refuses is HRESULT_FROM_WIN32(ERROR_INVALID_DATA)"); - check_hr(result(array, 0), ds::kEndOfFile, - "the first failure in queue order: a read past the end is HRESULT_FROM_WIN32(ERROR_HANDLE_EOF)"); - check_hr(result(array, 1), ds::kOk, "the next segment's status is S_OK"); - check(std::equal(buffers[2].begin(), buffers[2].end(), contents.begin()) && - std::equal(buffers[3].begin(), buffers[3].end(), contents.begin() + 100), - "the successful reads hold the file's bytes"); - check_hr(result(array, 5), ds::kInvalidArg, "an entry past the array's end is E_INVALIDARG"); - check(method(array, ds::slot::kIsComplete)(array, 5), "and counts as complete"); - release(queue); - release(array); - release(file); -} - -void half_a_queue_submits_itself(const std::filesystem::path& package) { - write_file(package / "tiny.bin", pattern(64)); - void* file = nullptr; - open(L"GAME:\\tiny.bin", &file); - void* const queue = new_queue(0, 4, 1); - void* const array = status_array(1); - std::array out{}; - enqueue(queue, request(0, out.data(), out.size(), file, 8, 16)); - enqueue_status(queue, array, 0); // the second of four: no submit needed - check_hr(wait(array, 0), ds::kOk, "half a queue's capacity enqueued submits without Submit"); - const std::vector want = pattern(64); - check(std::equal(out.begin(), out.end(), want.begin() + 8), "and the read lands"); - release(queue); - release(array); - if (file) release(file); -} - -void a_closed_queue_completes_nothing(const std::filesystem::path& package) { - write_file(package / "closed.bin", pattern(64)); - void* file = nullptr; - open(L"GAME:\\closed.bin", &file); - void* const queue = new_queue(0); - void* const array = status_array(1); - std::array out{}; - enqueue(queue, request(0, out.data(), out.size(), file, 0, 16)); - enqueue_status(queue, array, 0); - close(queue); - submit(queue); - Sleep(50); - check_hr(result(array, 0), ds::kPending, "a closed queue's status never completes"); - check(std::all_of(out.begin(), out.end(), [](std::uint8_t b) { return b == 0; }), - "and its request is not run"); - release(queue); - release(array); - if (file) release(file); -} - -// ---- The scheduler without workers: what `start` picks, and when statuses land. - -void read(ds::detail::Lanes& l, std::uint64_t id, std::uint64_t options, std::uint32_t size) { - ds::Request r{}; - r.options = options; - r.destination_size = size; - r.source_size = size; - l.lanes.at(id).unsubmitted.emplace_back(std::in_place_type, r); -} - -void priorities_share_by_bytes_about_tenfold() { - ds::detail::Lanes l; - l.lanes.emplace(0, ds::detail::Lane(0, 4096)); - l.lanes.emplace(1, ds::detail::Lane(1, 4096)); - l.lanes.emplace(2, ds::detail::Lane(2, 4096)); // real-time: as high - for (int i = 0; i < 400; ++i) - for (std::uint64_t id = 0; id < 3; ++id) read(l, id, 0, 4096); - for (std::uint64_t id = 0; id < 3; ++id) l.submit(id); - std::array started{}; - for (int i = 0; i < 330; ++i) { - const auto job = l.start(); - if (!job) break; - ++started[job->lane]; - l.finish(*job, ds::kOk); - } - std::printf(" started per lane: normal %d, high %d, real-time %d\n", started[0], started[1], started[2]); - check(started[1] + started[2] == 300 && started[0] == 30, - "normal gets about a tenth of what high and real-time get together"); - check(std::abs(started[1] - started[2]) <= 1, "high and real-time share one class"); -} - -void staging_bounds_compressed_bytes_in_flight() { - ds::detail::Lanes l; - l.staging = 100; - l.lanes.emplace(0, ds::detail::Lane(0, 64)); - read(l, 0, ds::kZlib, 60); - read(l, 0, ds::kZlib, 60); - read(l, 0, 0, 1000); // raw: straight to its destination - l.submit(0); - const auto first = l.start(); - check(first.has_value(), "the first compressed read starts"); - check(!l.start().has_value() && l.starved, "60 + 60 > 100: the second waits for staging"); - l.finish(*first, ds::kOk); - const auto second = l.start(); - const auto raw = l.start(); - check(second && raw && second->staging == 60 && raw->staging == 0, "then it starts, and the raw read beside it"); - // Alone, a request larger than the buffer still runs. - read(l, 0, ds::kZlib, 500); - l.submit(0); - check(!l.start().has_value(), "a 500-byte source waits while 60 are staged"); - l.finish(*second, ds::kOk); - check(l.start().has_value(), "and runs alone once nothing else is staged"); -} - -void a_status_waits_for_every_earlier_read() { - ds::detail::Lanes l; - l.lanes.emplace(0, ds::detail::Lane(0, 64)); - auto* const array = static_cast(status_array(2)); - for (std::uint32_t i = 0; i < 2; ++i) ds::detail::entry(array, i).store(ds::kPending); - const auto status = [&](std::uint32_t index) { - ds::detail::add_ref(array); - l.lanes.at(0).unsubmitted.emplace_back(std::in_place_type, array, index); - }; - read(l, 0, 0, 16); - read(l, 0, 0, 16); - status(0); - read(l, 0, 0, 16); - status(1); - l.submit(0); - std::vector jobs; - for (int i = 0; i < 3; ++i) - if (auto job = l.start()) jobs.push_back(*job); - check(jobs.size() == 3, "three reads start at once"); - if (jobs.size() != 3) return; - // The last read and the first finish; the second then fails. - l.finish(jobs[2], ds::kOk); - l.finish(jobs[0], ds::kOk); - check(result(array, 0) == ds::kPending && result(array, 1) == ds::kPending, - "no status lands while an earlier read runs"); - l.finish(jobs[1], ds::kInvalidData); - check_hr(result(array, 0), ds::kInvalidData, "the first status gets the failure before it"); - check_hr(result(array, 1), ds::kOk, "the second, with none since, S_OK"); - release(array); -} - -// ---- Destinations in physical pages - -void physical_page_destinations(const Xmem& x) { - std::vector pages = x.pages(2); - std::uint8_t* const mapped = pages.empty() ? nullptr : x.window(pages); - check(mapped != nullptr, "two physical pages mapped where the title would see them"); - if (!mapped) return; - const std::vector plain = pattern(100); - void* const queue = new_queue(1); - void* const array = status_array(1); - ds::Request r = request(ds::kPageDestination | ds::kMemorySource, pages.data(), plain.size(), plain.data(), 0, - plain.size()); - r.page_offset = ds::kPage - 40; // across the page boundary - enqueue(queue, r); - enqueue_status(queue, array, 0); - submit(queue); - check_hr(wait(array, 0), ds::kOk, "a request into physical pages completes"); - check(std::memcmp(mapped + ds::kPage - 40, plain.data(), plain.size()) == 0, - "and the title sees the bytes across the page boundary"); - release(queue); - release(array); - x.unmap(mapped, 2); - x.free(pages.size(), pages.data()); -} - -void zlib_into_pages_in_place_and_across_allocations(const Xmem& x) { - const std::vector a = x.pages(3), b = x.pages(1); - check(a.size() == 3 && b.size() == 1, "two allocations of physical pages"); - if (a.size() != 3 || b.size() != 1) return; - const std::vector plain = pattern(2 * ds::kPage + 100); - const std::vector packed = compress_zlib(plain); - // One allocation's pages in order (written in place), then pages of two (through a buffer), both from 50 bytes - // into the first. - std::array, 2> destinations = {a, std::vector{a[0], a[1], b[0]}}; - void* const queue = new_queue(1); - void* const array = status_array(1); - for (auto& pages : destinations) { - ds::Request r = request(ds::kZlib | ds::kPageDestination | ds::kMemorySource, pages.data(), plain.size(), - packed.data(), 0, packed.size()); - r.page_offset = 50; - enqueue(queue, r); - } - enqueue_status(queue, array, 0); - submit(queue); - check_hr(wait(array, 0), ds::kOk, "zlib into one allocation's pages and into pages of two completes"); - for (const auto& pages : destinations) { - std::uint8_t* const seen = x.window(pages); - check(seen && std::all_of(seen, seen + 50, [](std::uint8_t v) { return v == 0; }) && - std::memcmp(seen + 50, plain.data(), plain.size()) == 0, - "the inflated bytes are in the pages, from 50 bytes into the first"); - if (seen) x.unmap(seen, 3); - } - release(queue); - release(array); - x.free(a.size(), a.data()); - x.free(b.size(), b.data()); -} - -void a_page_array_filled_late_is_waited_for(const Xmem& x) { - const std::vector pages = x.pages(2); - check(pages.size() == 2, "two pages for a late page array"); - if (pages.size() != 2) return; - // The title fills the array after it enqueued the request; the request reads it when it runs. - static std::atomic late_array[2]; - late_array[0].store(pages[0]); - late_array[1].store(0); - static_assert(sizeof(std::atomic) == sizeof(std::uint64_t)); - const std::vector plain = pattern(2 * ds::kPage); - void* const queue = new_queue(1); - void* const array = status_array(1); - enqueue(queue, request(ds::kPageDestination | ds::kMemorySource, late_array, plain.size(), plain.data(), 0, - plain.size())); - enqueue_status(queue, array, 0); - submit(queue); - std::thread title([&] { - Sleep(10); - late_array[1].store(pages[1], std::memory_order_release); - }); - title.join(); - check_hr(wait(array, 0), ds::kOk, "a request whose page array is filled after it was submitted completes"); - std::uint8_t* const seen = x.window(pages); - check(seen && std::memcmp(seen, plain.data(), plain.size()) == 0, "and writes the pages the title put there"); - if (seen) x.unmap(seen, 2); - release(queue); - release(array); - x.free(pages.size(), pages.data()); -} - -void an_unknown_page_fails_its_request() { - // LEONIDA_DSTORAGE_RETRIES is 1 for this process (main), so the one retry takes 2 ms. - std::uint64_t unknown[1] = {0xfffff0}; - const std::vector plain = pattern(100); - void* const queue = new_queue(1); - void* const array = status_array(1); - enqueue(queue, request(ds::kPageDestination | ds::kMemorySource, unknown, plain.size(), plain.data(), 0, - plain.size())); - enqueue_status(queue, array, 0); - submit(queue); - check_hr(wait(array, 0), ds::kInvalidArg, "a destination page nobody allocated fails its request"); - release(queue); - release(array); -} - -// The read-beside-then-copy fix: a raw file read into title memory the kernel cannot write. Untouched physical pages -// are reserved until xmem's handler commits them on the first user-mode touch, which the kernel's write never makes. -void a_raw_read_into_untouched_pages(const Xmem& x, const std::filesystem::path& package) { - const std::vector contents = pattern(4096); - write_file(package / "pages.bin", contents); - std::vector pages = x.pages(2); - std::uint8_t* const mapped = pages.empty() ? nullptr : x.window(pages); - check(mapped != nullptr, "two untouched physical pages mapped"); - if (!mapped) return; - - // What the kernel does with them (for the log; the host decides): ReadFile straight into the second page. - const std::wstring host_path = (package / "pages.bin").wstring(); - const HANDLE h = CreateFileW(host_path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); - if (h != INVALID_HANDLE_VALUE) { - DWORD got = 0; - const BOOL ok = ReadFile(h, mapped + ds::kPage, 512, &got, nullptr); - std::printf(" note: ReadFile into an untouched mapped physical page %s (error %lu)\n", - ok ? "succeeded" : "failed", ok ? 0ul : GetLastError()); - CloseHandle(h); - } - - void* file = nullptr; - open(L"GAME:\\pages.bin", &file); - void* const queue = new_queue(0); - void* const array = status_array(1); - enqueue(queue, request(0, mapped + 123, 1000, file, 7, 1000)); - enqueue_status(queue, array, 0); - submit(queue); - check_hr(wait(array, 0), ds::kOk, "a raw read into untouched physical pages completes"); - check(std::memcmp(mapped + 123, contents.data() + 7, 1000) == 0, "and the title sees the file's bytes"); - release(queue); - release(array); - if (file) release(file); - x.unmap(mapped, 2); - x.free(pages.size(), pages.data()); -} - -} // namespace - -int main() { - // Read once per process by the shim, before the first request into physical pages. - SetEnvironmentVariableW(L"LEONIDA_DSTORAGE_RETRIES", L"1"); - testfiles::ScratchDir scratch("leonida_dstorage_test"); - const std::filesystem::path package = scratch.path() / "package"; - std::filesystem::create_directories(package); - rt::fs::configure(package, scratch.path() / "overlay"); - - factory_and_its_slots(); - if (!factory()) { - std::printf("FAIL no factory: %d of %d checks failed\n", g_failures + 1, g_checks + 1); - return 1; - } - raw_and_zlib_reads_from_a_game_file(package); - memory_sources_inflate_too(); - a_longer_stream_gives_its_first_bytes(); - statuses_complete_in_order_with_the_first_failure(package); - half_a_queue_submits_itself(package); - a_closed_queue_completes_nothing(package); - priorities_share_by_bytes_about_tenfold(); - staging_bounds_compressed_bytes_in_flight(); - a_status_waits_for_every_earlier_read(); - const Xmem x = xmem(); - check(x.ok(), "the registry serves the xmem.dll physical-page exports"); - if (x.ok()) { - physical_page_destinations(x); - zlib_into_pages_in_place_and_across_allocations(x); - a_page_array_filled_late_is_waited_for(x); - an_unknown_page_fails_its_request(); - a_raw_read_into_untouched_pages(x, package); - } - rt::fs::configure({}, {}); - std::printf("%d of %d checks failed\n", g_failures, g_checks); - return g_failures == 0 ? 0 : 1; -} diff --git a/runtime/test/file_system_test.cpp b/runtime/test/file_system_test.cpp index db8a8f8fb..af37935f6 100644 --- a/runtime/test/file_system_test.cpp +++ b/runtime/test/file_system_test.cpp @@ -1395,32 +1395,6 @@ void run_checks(const std::filesystem::path& root) { if (h != INVALID_HANDLE_VALUE) ::CloseHandle(h); check(attributes_w(L"G:\\data\\sub") != INVALID_FILE_ATTRIBUTES, "GetFileAttributesW stats a G: folder"); - // GetDiskFreeSpace(Ex) and SetCurrentDirectory on a console path ask the folder behind it (VIctory files.rs). - using FreeExW = BOOL(WINAPI*)(LPCWSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER); - using FreeA = BOOL(WINAPI*)(LPCSTR, LPDWORD, LPDWORD, LPDWORD, LPDWORD); - using SetDirW = BOOL(WINAPI*)(LPCWSTR); - const auto free_ex_w = resolve("kernel32.dll", "GetDiskFreeSpaceExW"); - const auto free_a = resolve("kernelbase.dll", "GetDiskFreeSpaceA"); - const auto set_dir_w = resolve("api-ms-win-core-processenvironment-l1-1-0.dll", "SetCurrentDirectoryW"); - ULARGE_INTEGER avail{}, total{}, total_free{}, host_total{}; - ::GetDiskFreeSpaceExW((package.wstring() + L"\\").c_str(), nullptr, &host_total, nullptr); - check(free_ex_w && free_ex_w(L"G:\\", &avail, &total, &total_free) && total.QuadPart == host_total.QuadPart && - total.QuadPart > 0, - "GetDiskFreeSpaceExW(G:\\) answers for the game folder's volume"); - DWORD spc = 0, bps = 0, fc = 0, tc = 0; - check(free_a && free_a("GAME:\\drives\\", &spc, &bps, &fc, &tc) && bps > 0 && tc > 0, - "GetDiskFreeSpaceA on a GAME: folder answers too"); - SetLastError(0); - check(free_ex_w && !free_ex_w(L"G:\\..\\", &avail, nullptr, nullptr) && GetLastError() == ERROR_INVALID_NAME, - "a path that climbs out of the drive is refused"); - wchar_t before[MAX_PATH] = {}; - ::GetCurrentDirectoryW(MAX_PATH, before); - wchar_t now[MAX_PATH] = {}; - check(set_dir_w && set_dir_w(L"G:\\drives\\sub") && ::GetCurrentDirectoryW(MAX_PATH, now) > 0 && - std::filesystem::equivalent(std::filesystem::path(now), package / "drives" / "sub"), - "SetCurrentDirectoryW(G:\\drives\\sub) enters the package folder"); - ::SetCurrentDirectoryW(before); - SetLastError(0); check(create_w(L"G:\\..\\x.txt", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr) == INVALID_HANDLE_VALUE && diff --git a/runtime/test/fixtures/ntuser_window_stub.cpp b/runtime/test/fixtures/ntuser_window_stub.cpp deleted file mode 100644 index a18eb1af7..000000000 --- a/runtime/test/fixtures/ntuser_window_stub.cpp +++ /dev/null @@ -1,10 +0,0 @@ -// Link-time stand-in for the API set a GDKX title imports CreateWindowExA from -// (ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0.dll), so tiny_present.exe gets the import the title has. Under -// `gta6rt --run` the shim registry answers it (shims/title_window.cpp) and this DLL never loads; it is built into a -// folder the loader does not search. Test code, not game content. -#include - -extern "C" void* __stdcall stub_create_window_ex_a(std::uint32_t, const char*, const char*, std::uint32_t, int, int, - int, int, void*, void*, void*, void*) { - return nullptr; -} diff --git a/runtime/test/fixtures/ntuser_window_stub.def b/runtime/test/fixtures/ntuser_window_stub.def deleted file mode 100644 index 56f7fa4b5..000000000 --- a/runtime/test/fixtures/ntuser_window_stub.def +++ /dev/null @@ -1,3 +0,0 @@ -LIBRARY "ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0.dll" -EXPORTS - CreateWindowExA=stub_create_window_ex_a diff --git a/runtime/test/fixtures/tiny_present.cpp b/runtime/test/fixtures/tiny_present.cpp deleted file mode 100644 index ac7a22902..000000000 --- a/runtime/test/fixtures/tiny_present.cpp +++ /dev/null @@ -1,308 +0,0 @@ -// A stand-in title for `gta6rt --run` that presents the way a GDKX title does, on the Vulkan device -// (check_tiny_present.py sets LEONIDA_D3D12=vulkan): D3D12XboxCreateDevice as ID3D12Device11 (the console layouts), -// the display mode from the console output (IDXGIDevice1 -> GetAdapter -> EnumOutputs(0) -> output slot 21), a back -// buffer of that size, the frame clock (device slots 78-80: SetFrameIntervalX at 60 Hz, ScheduleFrameEventX, a blocking -// WaitFrameEventX per frame), and per frame clears into the back buffer, ExecuteCommandLists (queue slot 10), Signal -// (16) and PresentX (32), through the console list and queue slots. The frame has three regions (the top-left quarter, -// the bottom-left quarter, the right half), so the checker can tell a presented frame from a flipped or scaled one. -// -// It presents until the screenshot the checker asked for (LEONIDA_CAPTURE_DIR, request 1) is on disk and at least 90 -// frames are shown, then reads the caption of the window the frames went to ("Leonida | fps ms/frame"). -// With --title-window it first makes a 3840x2160 window of its own through CreateWindowExA imported from the API set a -// title imports it from (the shim fits it to the screen) and pumps its messages, as a title does: the frames must then go -// there. Hand-written test code, public D3D12 and Win32 API only; no game data and no shader. -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -extern "C" __declspec(dllimport) HRESULT __stdcall D3D12XboxCreateDevice(IUnknown* adapter, const void* params, - const IID* riid, void** device); - -namespace { - -int g_failures = 0; - -bool check(bool ok, const char* what) { - std::printf("tiny_present: %s %s\n", ok ? "PASS" : "FAIL", what); - if (!ok) ++g_failures; - return ok; -} - -int finish() { - std::printf("tiny_present: %s\n", g_failures ? "FAILED" : "OK"); - std::fflush(stdout); - return g_failures ? 1 : 0; -} - -void** vtable(void* object) { return *static_cast(object); } - -// The console slots the stand-in calls (runtime/shims/d3d12_xs_slots.h, from VIctory's tables). -using Word = std::uint64_t; -template -Fn slot(void* object, unsigned index) { - return reinterpret_cast(vtable(object)[index]); -} -constexpr unsigned kDeviceSetFrameInterval = 78, kDeviceScheduleFrameEvent = 79, kDeviceWaitFrameEvent = 80; -constexpr unsigned kQueueExecute = 10, kQueueSignal = 16, kQueuePresentX = 32; -constexpr unsigned kListClose = 9, kListReset = 10, kListBarrier = 26, kListClearRtv = 52; -constexpr unsigned kOutputModes = 21; - -// D3D12XBOX_PRESENT_PLANE_PARAMETERS (runtime/shims/xbox_present.h: 0x48 bytes on x64). -struct PresentPlane { - std::uint64_t token; - UINT resource_count; - ID3D12Resource* const* resources; - const D3D12_RECT* source_rects; - const void* placement; - int color_space; - int scale_filter; - UINT extended_count; - const void* extended; - UINT flags; -}; -static_assert(sizeof(PresentPlane) == 0x48, "the console's plane parameters"); - -struct Mode { // the console output's slot-21 entries (runtime/shims/xbox_display.h) - std::uint32_t width, height, refresh_numerator, refresh_denominator, format, scanlines, scaling, flags; -}; - -using HeapStartFn = std::uint64_t(__stdcall*)(void* heap); - -LRESULT CALLBACK title_proc(HWND hwnd, UINT message, WPARAM w, LPARAM l) { - return DefWindowProcA(hwnd, message, w, l); -} - -bool interactive_window_station() { - HWINSTA station = GetProcessWindowStation(); - USEROBJECTFLAGS flags{}; - DWORD bytes = 0; - if (!station || !GetUserObjectInformationW(station, UOI_FLAGS, &flags, sizeof(flags), &bytes)) return true; - return (flags.dwFlags & WSF_VISIBLE) != 0; -} - -void barrier(ID3D12GraphicsCommandList* list, ID3D12Resource* resource, D3D12_RESOURCE_STATES before, - D3D12_RESOURCE_STATES after) { - D3D12_RESOURCE_BARRIER b{}; - b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - b.Transition.pResource = resource; - b.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - b.Transition.StateBefore = before; - b.Transition.StateAfter = after; - slot(list, kListBarrier)(list, 1, &b); -} - -} // namespace - -int main(int argc, char** argv) { - std::setvbuf(stdout, nullptr, _IONBF, 0); - const bool title_window = argc > 1 && !std::strcmp(argv[1], "--title-window"); - if (!interactive_window_station()) { - std::printf("tiny_present: SKIP no interactive window station\n"); - return 77; - } - - HWND own = nullptr; - if (title_window) { - WNDCLASSEXA window_class{sizeof(window_class)}; - window_class.lpfnWndProc = title_proc; - window_class.hInstance = GetModuleHandleA(nullptr); - window_class.lpszClassName = "TinyPresentTitle"; - RegisterClassExA(&window_class); - own = CreateWindowExA(0, "TinyPresentTitle", "tiny_present", WS_OVERLAPPEDWINDOW, 0, 0, 3840, 2160, nullptr, - nullptr, window_class.hInstance, nullptr); - if (!check(own != nullptr, "CreateWindowExA (through the title's API set) makes the title's window")) - return finish(); - ShowWindow(own, SW_SHOW); - } - const auto pump = [] { - MSG message; - while (PeekMessageA(&message, nullptr, 0, 0, PM_REMOVE)) { - TranslateMessage(&message); - DispatchMessageA(&message); - } - }; - - std::uint32_t params[24] = {}; - const IID device_iid = __uuidof(ID3D12Device11); - ID3D12Device* device = nullptr; - HRESULT hr = D3D12XboxCreateDevice(nullptr, params, &device_iid, reinterpret_cast(&device)); - if (!check(hr == S_OK && device, "D3D12XboxCreateDevice returns an ID3D12Device11 (console layouts)")) { - std::printf("tiny_present: hr=0x%08lx\n", static_cast(hr)); - return finish(); - } - - // The display mode, as the title finds it. - UINT width = 0, height = 0; - { - IDXGIDevice1* dxgi = nullptr; - IDXGIAdapter* adapter = nullptr; - IDXGIOutput* output = nullptr; - check(SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&dxgi))) && dxgi, "the device answers IDXGIDevice1"); - if (dxgi) check(SUCCEEDED(dxgi->GetAdapter(&adapter)) && adapter, "GetAdapter"); - if (adapter) check(SUCCEEDED(adapter->EnumOutputs(0, &output)) && output, "EnumOutputs(0)"); - if (output) { - using ModesFn = HRESULT(__stdcall*)(void*, UINT, UINT, UINT*, Mode*); - UINT count = 0; - check(slot(output, kOutputModes)(output, 0, 0, &count, nullptr) == S_OK && count == 1, - "output slot 21 counts one display mode"); - Mode mode{}; - count = 1; - if (check(slot(output, kOutputModes)(output, 0, 0, &count, &mode) == S_OK && count == 1, - "output slot 21 lists it")) { - width = mode.width; - height = mode.height; - std::printf("tiny_present: display mode %ux%u at %u/%u Hz\n", width, height, mode.refresh_numerator, - mode.refresh_denominator); - } - output->Release(); - } - if (adapter) adapter->Release(); - if (dxgi) dxgi->Release(); - } - if (!width || !height) return finish(); - - ID3D12CommandQueue* queue = nullptr; - ID3D12CommandAllocator* allocator = nullptr; - ID3D12GraphicsCommandList* list = nullptr; - ID3D12Fence* fence = nullptr; - ID3D12DescriptorHeap* rtv_heap = nullptr; - D3D12_COMMAND_QUEUE_DESC queue_desc{}; - queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; - check(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue))) && queue, "a direct command queue"); - check(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator))) && - allocator, "a command allocator"); - if (allocator) - check(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator, nullptr, - IID_PPV_ARGS(&list))) && list, "a console command list"); - check(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence))) && fence, "a fence"); - // The console's heap description: the PC one, then the heap's address and size in title memory (0: none). - struct { - D3D12_DESCRIPTOR_HEAP_DESC desc; - std::uint64_t address, size; - } heap_desc{}; - heap_desc.desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; - heap_desc.desc.NumDescriptors = 1; - check(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc.desc, IID_PPV_ARGS(&rtv_heap))) && rtv_heap, - "an RTV heap (console description)"); - if (!queue || !list || !fence || !rtv_heap) return finish(); - const D3D12_CPU_DESCRIPTOR_HANDLE rtv{ - static_cast(reinterpret_cast(vtable(rtv_heap)[9])(rtv_heap))}; - - // The back buffer: the display mode's size, ALLOW_DISPLAY, in PRESENT, as the public samples make them. - D3D12_HEAP_PROPERTIES heap{}; - heap.Type = D3D12_HEAP_TYPE_DEFAULT; - D3D12_RESOURCE_DESC desc{}; - desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - desc.Width = width; - desc.Height = height; - desc.DepthOrArraySize = 1; - desc.MipLevels = 1; - desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; - desc.SampleDesc.Count = 1; - desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; - ID3D12Resource* back = nullptr; - check(SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_ALLOW_DISPLAY, &desc, - D3D12_RESOURCE_STATE_PRESENT, nullptr, IID_PPV_ARGS(&back))) && - back, "a display-sized back buffer"); - if (!back) return finish(); - device->CreateRenderTargetView(back, nullptr, rtv); - - // The frame clock: 60 Hz, the origin event. - using SetIntervalFn = HRESULT(__stdcall*)(void*, void*, UINT, UINT, UINT); - using ScheduleFn = HRESULT(__stdcall*)(void*, UINT, UINT, void*, UINT); - using WaitFn = HRESULT(__stdcall*)(void*, UINT, DWORD, void*, UINT, std::uint64_t*); - check(slot(device, kDeviceSetFrameInterval)(device, nullptr, 16667, 1, 0) == S_OK, - "SetFrameIntervalX at 60 Hz"); - check(slot(device, kDeviceScheduleFrameEvent)(device, 0, 0, nullptr, 0) == S_OK, "ScheduleFrameEventX"); - - using ResetFn = HRESULT(__stdcall*)(void*, ID3D12CommandAllocator*, ID3D12PipelineState*); - using CloseFn = HRESULT(__stdcall*)(void*); - using ClearFn = void(__stdcall*)(void*, D3D12_CPU_DESCRIPTOR_HANDLE, const FLOAT*, UINT, const D3D12_RECT*); - using ExecuteFn = void(__stdcall*)(void*, UINT, ID3D12CommandList* const*); - using SignalFn = HRESULT(__stdcall*)(void*, ID3D12Fence*, UINT64); - using PresentFn = HRESULT(__stdcall*)(void*, UINT, const PresentPlane*, const void*); - slot(list, kListClose)(list); // created open, as on PC - - const FLOAT left[4] = {64 / 255.0f, 128 / 255.0f, 191 / 255.0f, 1.0f}; - const FLOAT corner[4] = {1.0f, 0.0f, 0.0f, 1.0f}; - const FLOAT right[4] = {0.0f, 200 / 255.0f, 0.0f, 1.0f}; - const D3D12_RECT right_half{LONG(width / 2), 0, LONG(width), LONG(height)}; - const D3D12_RECT top_left{0, 0, LONG(width / 2), LONG(height / 2)}; - - HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr); - char capture[MAX_PATH] = {}; - const DWORD capture_length = GetEnvironmentVariableA("LEONIDA_CAPTURE_DIR", capture, MAX_PATH); - const std::string captured = capture_length ? std::string(capture) + "\\capture-1.png" : std::string(); - std::uint64_t last_token = 0; - unsigned presented = 0, waits_ok = 0, tokens_in_order = 0; - bool capture_seen = false; - auto sixty_start = std::chrono::steady_clock::now(); - double sixty_ms = 0.0; - for (unsigned frame = 1; frame <= 900; ++frame) { - if (title_window) pump(); - std::uint64_t token = 0; - if (slot(device, kDeviceWaitFrameEvent)(device, 0, INFINITE, nullptr, 0, &token) == S_OK) ++waits_ok; - if (token == last_token + 1) ++tokens_in_order; - last_token = token; - if (frame == 11) sixty_start = std::chrono::steady_clock::now(); - if (frame == 71) - sixty_ms = std::chrono::duration(std::chrono::steady_clock::now() - sixty_start).count(); - - allocator->Reset(); - slot(list, kListReset)(list, allocator, nullptr); - barrier(list, back, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET); - slot(list, kListClearRtv)(list, rtv, left, 0, nullptr); - slot(list, kListClearRtv)(list, rtv, right, 1, &right_half); - slot(list, kListClearRtv)(list, rtv, corner, 1, &top_left); - barrier(list, back, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT); - slot(list, kListClose)(list); - ID3D12CommandList* lists[] = {list}; - slot(queue, kQueueExecute)(queue, 1, lists); - ID3D12Resource* const resources[] = {back}; - const PresentPlane plane{token, 1, resources, nullptr, nullptr, 0, 0, 0, nullptr, 0}; - if (slot(queue, kQueuePresentX)(queue, 1, &plane, nullptr) == S_OK) ++presented; - slot(queue, kQueueSignal)(queue, fence, frame); - if (fence->GetCompletedValue() < frame) { - fence->SetEventOnCompletion(frame, done); - WaitForSingleObject(done, 10000); - } - if (!capture_seen && !captured.empty() && GetFileAttributesA(captured.c_str()) != INVALID_FILE_ATTRIBUTES) { - capture_seen = true; - std::printf("tiny_present: the screenshot is on disk after %u frames\n", frame); - } - if (capture_seen && frame >= 90) break; - } - check(waits_ok == presented && presented >= 90, "every WaitFrameEventX returned S_OK and every PresentX S_OK"); - check(tokens_in_order == presented, "the frame clock's tokens count the frames (1, 2, 3, ...)"); - std::printf("tiny_present: 60 frames at 60 Hz took %.0f ms\n", sixty_ms); - check(sixty_ms > 800.0 && sixty_ms < 1500.0, "the frame clock paces the frames to about 60 a second"); - check(capture_seen, "the requested screenshot was written while the title presented"); - - // The caption of the window the frames went to. - HWND shown = title_window ? own : FindWindowW(L"LeonidaWindow", nullptr); - check(shown != nullptr, title_window ? "the title's window" : "the runtime's window (class LeonidaWindow)"); - if (shown) { - // The caption thread set it at least once in the 1.5 s of frames above (it sends WM_SETTEXT, which the title's - // own window takes while its thread pumps). - if (title_window) pump(); - char caption[128] = {}; - GetWindowTextA(shown, caption, sizeof(caption)); - std::printf("tiny_present: caption '%s'\n", caption); - double fps = 0, ms = 0; - check(std::sscanf(caption, "Leonida | %lf fps %lf ms/frame", &fps, &ms) == 2 && fps > 20.0 && fps < 120.0 && - ms > 0.0, - "the caption reads Leonida | fps ms/frame, at about 60 fps"); - RECT client{}; - GetClientRect(shown, &client); - std::printf("tiny_present: window client area %ldx%ld\n", client.right, client.bottom); - } - if (done) CloseHandle(done); - return finish(); -} diff --git a/runtime/test/frame_step_test.cpp b/runtime/test/frame_step_test.cpp deleted file mode 100644 index d740e89cd..000000000 --- a/runtime/test/frame_step_test.cpp +++ /dev/null @@ -1,202 +0,0 @@ -// src/frame_step.h on a sparse stand-in for the 1.0.2.1 image: the loads it expects, what it writes, what it leaves -// alone, LEONIDA_TIME_STEP's values, and what the step comes to before and after, by running the title's step formula -// on the floats the (patched) loads read. No game files: the stand-in holds only the bytes the header checks. - -#include "../src/frame_step.h" - -#include -#include -#include -#include -#include -#include -#include - -namespace { - -int failures = 0; - -void check(bool ok, const char* what) { - if (!ok) { - ++failures; - std::fprintf(stderr, "FAIL: %s\n", what); - } -} - -namespace fs = leonida::frame_step; -using Image = std::map>; - -std::vector float_bytes(float f) { - std::vector out(4); - std::memcpy(out.data(), &f, 4); - return out; -} - -// The places the header looks at, as the retail executable has them (and the floats the loads read, at the values the -// timer runs with: its init has written 1/3000 s to the minimum step, the settings 1/30 s to the nominal frame time). -Image stock_image() { - Image image; - image[fs::kTimeSetCapLoadRva] = {0xc5, 0xfa, 0x10, 0x1d, 0x73, 0x3e, 0xf3, 0x03}; - image[fs::kTimeSetFloorLoadRva] = {0xc5, 0xfa, 0x10, 0x25, 0xe2, 0x37, 0x62, 0x04}; - image[fs::kCameraCapLoadRva] = {0xc5, 0xfa, 0x10, 0x05, 0x85, 0x36, 0xf3, 0x03}; - image[fs::kCameraFloorLoadRva] = {0xc5, 0xfa, 0x10, 0x0d, 0xe8, 0x2f, 0x62, 0x04}; - image[fs::kOneRva] = float_bytes(1.0f); - image[fs::kMinStepRva] = float_bytes(1.0f / 30.0f); // the file's value - image[fs::kStockCapRva] = float_bytes(1.0f / 15.0f); - image[fs::kNominalRva] = float_bytes(1.0f / 30.0f); - return image; -} - -auto access(Image& image) { - return [&image](std::uint32_t rva, std::size_t length) -> std::uint8_t* { - const auto found = image.find(rva); - return found != image.end() && found->second.size() >= length ? found->second.data() : nullptr; - }; -} - -// The float a `vmovss xmm, [rip + disp32]` at `rva` reads (NaN when it reads nothing in the stand-in). -float loaded(Image& image, std::uint32_t rva) { - std::int32_t disp = 0; - std::memcpy(&disp, image[rva].data() + 4, 4); - const auto target = std::uint32_t(std::int64_t(rva) + fs::kLoadLength + disp); - const auto found = image.find(target); - if (found == image.end() || found->second.size() < 4) return std::nanf(""); - float f = 0; - std::memcpy(&f, found->second.data(), 4); - return f; -} - -// The time sets' step as the title computes it (clip on, the nominal-floor switch set, scale 1): the floor and cap -// are what the two loads read. -float title_step(Image& image, float measured) { - const float cap = loaded(image, fs::kTimeSetCapLoadRva); - const float floor = loaded(image, fs::kTimeSetFloorLoadRva); - const float x = std::fmin(cap, measured); - return measured < floor ? floor : x; -} - -// Game seconds per wall second at a steady `fps`. -float speed(Image& image, float fps) { return title_step(image, 1.0f / fps) * fps; } - -bool close_to(float a, float b) { return std::fabs(a - b) <= 1e-3f * std::fmax(1.0f, std::fabs(b)); } - -void tests() { - // The plan: four loads (opcode and register kept, only the displacement moves) and two checked-only targets. - const auto plan = fs::plan(); - int loads = 0, checked_only = 0; - for (const fs::Patch& p : plan) { - if (p.bytes.empty()) { - ++checked_only; - continue; - } - ++loads; - check(p.stock.size() == fs::kLoadLength && p.bytes.size() == fs::kLoadLength, "a load is 8 bytes"); - check(std::memcmp(p.stock.data(), p.bytes.data(), 4) == 0, "a load keeps its opcode and register"); - } - check(loads == 4 && checked_only == 2, "four loads, two values checked"); - - // Stock: the step is 1/30 s at 30 fps and above, 1/15 s at 15 fps and below. - Image image = stock_image(); - check(close_to(speed(image, 2.0f), 2.0f / 15.0f), "stock: 2 fps runs at 2/15 of real time"); - check(close_to(speed(image, 15.0f), 1.0f) && close_to(speed(image, 30.0f), 1.0f), "stock: real time at 15 and 30 fps"); - check(close_to(speed(image, 60.0f), 2.0f), "stock: a doubled frame rate doubles the speed"); - check(close_to(speed(image, 120.0f), 4.0f), "stock: 120 fps runs four times too fast"); - - std::string error; - check(fs::apply(access(image), plan, &error), "the patch applies to the stock bytes"); - check(error.empty(), "and says nothing"); - check(image[fs::kOneRva] == float_bytes(1.0f) && image[fs::kMinStepRva] == float_bytes(1.0f / 30.0f) && - image[fs::kStockCapRva] == float_bytes(1.0f / 15.0f) && image[fs::kNominalRva] == float_bytes(1.0f / 30.0f), - "no data is written: only the loads move"); - check(loaded(image, fs::kTimeSetCapLoadRva) == 1.0f && loaded(image, fs::kCameraCapLoadRva) == 1.0f, - "both caps read the timer's 1.0"); - // The minimum step as the timer's init leaves it. - image[fs::kMinStepRva] = float_bytes(1.0f / 3000.0f); - check(loaded(image, fs::kTimeSetFloorLoadRva) == 1.0f / 3000.0f && - loaded(image, fs::kCameraFloorLoadRva) == 1.0f / 3000.0f, - "both floors read the timer's minimum step"); - for (const float fps : {1.0f, 2.0f, 4.0f, 15.0f, 30.0f, 60.0f, 120.0f, 240.0f, 1000.0f}) - check(close_to(speed(image, fps), 1.0f), "patched: real time from 1 to 1000 fps"); - check(close_to(title_step(image, 0.5f), 0.5f), "patched: a 2 fps frame steps its 0.5 s"); - check(close_to(title_step(image, 3.0f), 1.0f), "patched: a hitch steps 1 s at most"); - - // Patched once, the bytes are not stock any more: a second pass writes nothing. - image[fs::kMinStepRva] = float_bytes(1.0f / 30.0f); - const Image patched = image; - check(!fs::apply(access(image), plan, &error) && image == patched && !error.empty(), "a second pass is refused"); - - // Another build: one target value differs, or one load differs. Nothing is written. - Image other = stock_image(); - other[fs::kOneRva] = float_bytes(0.5f); - const Image other_before = other; - check(!fs::apply(access(other), plan, &error) && other == other_before, "another 1.0 constant: nothing written"); - other = stock_image(); - other[fs::kCameraFloorLoadRva][5] ^= 1; - const Image other_load = other; - check(!fs::apply(access(other), plan, &error) && other == other_load, "another camera load: nothing written"); - Image empty; - check(!fs::apply(access(empty), plan, &error), "an image without these places: nothing written"); - - // LEONIDA_TIME_STEP. - bool known = false; - check(fs::wanted(nullptr, &known) && known, "unset: measured"); - check(fs::wanted("", &known) && known, "empty: measured"); - check(fs::wanted("Measured", &known) && known, "measured, any case"); - check(!fs::wanted("stock", &known) && known && !fs::wanted("0") && !fs::wanted("OFF"), "stock, 0, off: the title's own"); - check(fs::wanted("sometimes", &known) && !known, "an unknown value is reported and measured"); -} - -#ifdef _WIN32 -// apply_to_image on memory laid out like the mapped image: the stock bytes at their RVAs in committed pages, the code -// pages execute-read and the data pages read-only, as the loader leaves them. Two loads share a page, so a protection -// put back too early would fault on the next write. -void image_tests() { - const std::uint32_t size = (fs::kNominalRva & ~0xfffu) + 0x2000; - auto* base = static_cast(VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_NOACCESS)); - check(base != nullptr, "the stand-in image is reserved"); - if (!base) return; - const Image stock = stock_image(); - for (const auto& [rva, bytes] : stock) { - std::uint8_t* page = base + (rva & ~0xfffu); - VirtualAlloc(page, 0x2000, MEM_COMMIT, PAGE_READWRITE); - std::memcpy(base + rva, bytes.data(), bytes.size()); - } - const auto protection = [&](std::uint32_t rva) { - MEMORY_BASIC_INFORMATION info{}; - VirtualQuery(base + rva, &info, sizeof info); - return info.Protect; - }; - DWORD old = 0; - for (const auto& [rva, bytes] : stock) - VirtualProtect(base + (rva & ~0xfffu), 0x2000, - rva < fs::kOneRva ? PAGE_EXECUTE_READ : PAGE_READONLY, &old); - std::string error; - check(fs::apply_to_image(base, size, fs::plan(), &error), "the patch applies to the mapped stand-in"); - Image image = stock_image(); - check(fs::apply(access(image), fs::plan(), &error), "the expected bytes"); - bool same = true; - for (const auto& [rva, bytes] : image) same = same && std::memcmp(base + rva, bytes.data(), bytes.size()) == 0; - check(same, "the mapped stand-in holds the patched loads and unchanged data"); - check(protection(fs::kTimeSetCapLoadRva) == PAGE_EXECUTE_READ && protection(fs::kTimeSetFloorLoadRva) == PAGE_EXECUTE_READ && - protection(fs::kCameraCapLoadRva) == PAGE_EXECUTE_READ && protection(fs::kOneRva) == PAGE_READONLY, - "the protections are put back"); - check(!fs::apply_to_image(base, size, fs::plan(), &error), "a second pass is refused"); - check(!fs::apply_to_image(base, fs::kOneRva, fs::plan(), &error), "places past the image are refused"); - VirtualFree(base, 0, MEM_RELEASE); -} -#endif - -} // namespace - -int main() { - tests(); -#ifdef _WIN32 - image_tests(); -#endif - if (failures) { - std::fprintf(stderr, "frame_step_test: %d failure(s)\n", failures); - return 1; - } - std::printf("frame_step_test: OK\n"); - return 0; -} diff --git a/runtime/test/gameinput_xinput_test.cpp b/runtime/test/gameinput_xinput_test.cpp deleted file mode 100644 index 5fd7c0b5c..000000000 --- a/runtime/test/gameinput_xinput_test.cpp +++ /dev/null @@ -1,475 +0,0 @@ -// The GameInput shim without SDL3 (shims/gameinput_xinput.cpp) over a fake host: pads connecting and disconnecting -// with their callbacks, readings and the walk between them, the keyboard and its stand-in pad, the DualSense between -// XInput and the stand-in, asynchronous enumeration, unregistering a running callback, devices by id, rumble, and the -// DualSense report decoder. The cases follow VIctory's tests (crates/victory-hle/src/modules/gameinput.rs and -// gameinput/dualsense.rs), GPL-3.0-or-later, by Marvisak and contributors (DexNom fork); Leonida is -// GPL-3.0-or-later. No game data, no controller, no window. -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "gameinput_xinput.h" -#include "shims.h" - -namespace { - -using namespace rt::gameinput_xinput; -using namespace gi; - -int g_checks = 0; -int g_failures = 0; - -void check(bool condition, const char* what) { - ++g_checks; - std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); - if (!condition) ++g_failures; -} - -struct FakeHost { - std::mutex mu; - bool pads[kPads] = {}; - PadState pad[kPads] = {}; - bool native = false; - PadState native_pad{}; - std::vector keys; - std::vector> rumble; -}; - -class Fake final : public Source { -public: - explicit Fake(std::shared_ptr host) : host_(std::move(host)) {} - bool pad(int slot, PadState* out) override { - std::lock_guard lock(host_->mu); - if (host_->pads[slot]) *out = host_->pad[slot]; - return host_->pads[slot]; - } - bool native_pad(PadState* out) override { - std::lock_guard lock(host_->mu); - if (host_->native) *out = host_->native_pad; - return host_->native; - } - std::vector keys() override { - std::lock_guard lock(host_->mu); - return host_->keys; - } - void rumble(int slot, uint16_t low, uint16_t high) override { - std::lock_guard lock(host_->mu); - host_->rumble.emplace_back(slot, low, high); - } - -private: - std::shared_ptr host_; -}; - -struct Hub { - IGameInput* gi; - std::shared_ptr host; -}; - -Hub fake() { - auto host = std::make_shared(); - return {create_hub(std::make_unique(host)), host}; -} - -KeyState key(uint8_t vk) { - KeyState k; - k.scan_code = vk + 0x100u; - k.virtual_key = vk; - return k; -} - -// By value, as VIctory's PartialEq compares: -0.0 (a centred stick flipped to +Y up) equals 0.0. -bool same(const PadState& a, const PadState& b) { - return a.buttons == b.buttons && a.leftTrigger == b.leftTrigger && a.rightTrigger == b.rightTrigger && - a.leftThumbstickX == b.leftThumbstickX && a.leftThumbstickY == b.leftThumbstickY && - a.rightThumbstickX == b.rightThumbstickX && a.rightThumbstickY == b.rightThumbstickY; -} - -// Device callbacks seen: device, current and previous status. -struct Log { - std::mutex mu; - std::vector> calls; - size_t size() { - std::lock_guard lock(mu); - return calls.size(); - } - std::tuple at(size_t i) { - std::lock_guard lock(mu); - return calls.at(i); - } -}; - -void CALLBACK record(GameInputCallbackToken, void* context, IGameInputDevice* device, uint64_t, uint32_t current, - uint32_t previous) { - auto* log = static_cast(context); - std::lock_guard lock(log->mu); - log->calls.emplace_back(device, current, previous); -} - -constexpr uint32_t kConnected = 3; - -GameInputCallbackToken register_devices(IGameInput* gi, uint32_t kind, GameInputEnumerationKind enumeration, Log* log) { - GameInputCallbackToken token = 0; - const HRESULT hr = gi->RegisterDeviceCallback(nullptr, kind, 1, enumeration, log, record, &token); - check(hr == S_OK && token != 0, "RegisterDeviceCallback succeeds with a token"); - return token; -} - -bool call_is(Log& log, size_t i, IGameInputDevice* device, uint32_t current, uint32_t previous) { - if (log.size() <= i) return false; - return log.at(i) == std::make_tuple(device, current, previous); -} - -HRESULT current(IGameInput* gi, uint32_t kind, int index, IGameInputReading** out) { - *out = reinterpret_cast(1); // must be cleared on failure - return gi->GetCurrentReading(kind, device(gi, index), out); -} - -PadState pad_of(IGameInputReading* r) { - PadState s{}; - check(r->GetGamepadState(&s), "GetGamepadState answers for a pad reading"); - return s; -} - -void pads_connect_report_and_disconnect() { - std::printf("-- pads connect, report and disconnect\n"); - Hub h = fake(); - IGameInput* gi = h.gi; - Log log; - register_devices(gi, GameInputKindGamepad, GameInputBlockingEnumeration, &log); - // Blocking enumeration ran before registration returned: with no host pad the keyboard's stand-in is the only one. - check(log.size() == 1 && call_is(log, 0, device(gi, kStandIn), kConnected, 0), - "blocking enumeration reports the stand-in pad before returning"); - - { - std::lock_guard lock(h.host->mu); - h.host->pads[1] = true; - h.host->pad[1] = PadState{GameInputGamepadA, 0, 0, 0.5f, 0, 0, 0}; - } - poll(gi); - check(log.size() == 3 && call_is(log, 1, device(gi, 1), kConnected, 0) && - call_is(log, 2, device(gi, kStandIn), 0, kConnected), - "a host pad connects and the stand-in leaves"); - - IGameInputReading* first = nullptr; - check(current(gi, GameInputKindGamepad, 1, &first) == S_OK, "the pad has a current reading"); - check(pad_of(first).buttons == GameInputGamepadA && pad_of(first).leftThumbstickX == 0.5f, - "the reading carries the host pad's state"); - poll(gi); // no change, no new reading - IGameInputReading* again = nullptr; - current(gi, GameInputKindGamepad, 1, &again); - check(again == first, "an unchanged pad keeps its reading"); - again->Release(); - - std::this_thread::sleep_for(std::chrono::milliseconds(2)); - { - std::lock_guard lock(h.host->mu); - h.host->pad[1].buttons = GameInputGamepadB; - } - poll(gi); - IGameInputReading* second = nullptr; - current(gi, GameInputKindGamepad, 1, &second); - check(second != first && pad_of(second).buttons == GameInputGamepadB, "a change makes a new reading"); - check(second->GetTimestamp() > first->GetTimestamp() && - second->GetSequenceNumber(GameInputKindGamepad) == first->GetSequenceNumber(GameInputKindGamepad) + 1, - "timestamps and sequence numbers move on"); - check(second->GetTimestamp() <= gi->GetCurrentTimestamp(), "a reading is not from the future"); - check(first->GetSequenceNumber(GameInputKindKeyboard) == 0, "no sequence number for a kind the reading lacks"); - - // The title's edge check: previous of current, and back again. - IGameInputDevice* pad1 = device(gi, 1); - IGameInputReading* walked = nullptr; - check(gi->GetPreviousReading(second, GameInputKindGamepad, pad1, &walked) == S_OK && walked == first, - "GetPreviousReading of the newest is the one before"); - walked->Release(); - check(gi->GetNextReading(first, GameInputKindGamepad, pad1, &walked) == S_OK && walked == second, - "GetNextReading of that is the newest again"); - walked->Release(); - walked = reinterpret_cast(1); - check(gi->GetNextReading(second, GameInputKindGamepad, pad1, &walked) == GAMEINPUT_E_READING_NOT_FOUND && - !walked, - "nothing after the newest"); - check(gi->GetPreviousReading(first, GameInputKindGamepad, pad1, &walked) == GAMEINPUT_E_READING_NOT_FOUND, - "nothing before the first"); - check(gi->GetPreviousReading(first, GameInputKindGamepad, device(gi, 2), &walked) == E_INVALIDARG, - "a device other than the reference's is refused"); - IGameInputReading* temporal = nullptr; - check(gi->GetTemporalReading(first->GetTimestamp(), pad1, &temporal) == S_OK && temporal == first, - "GetTemporalReading finds the reading in force at a time"); - temporal->Release(); - IGameInputDevice* of = nullptr; - first->GetDevice(&of); - check(of == pad1 && first->GetInputKind() == GameInputKindGamepad, "a reading names its device and kind"); - first->Release(); - second->Release(); - - { - std::lock_guard lock(h.host->mu); - h.host->pads[1] = false; - } - poll(gi); - check(log.size() == 5 && call_is(log, 3, device(gi, 1), 0, kConnected) && - call_is(log, 4, device(gi, kStandIn), kConnected, 0), - "the pad leaves and the stand-in comes back"); - IGameInputReading* gone = nullptr; - check(current(gi, GameInputKindGamepad, 1, &gone) == GAMEINPUT_E_DEVICE_DISCONNECTED && !gone, - "a disconnected pad has no current reading"); - check(device(gi, 1)->GetDeviceStatus() == 0 && device(gi, kStandIn)->GetDeviceStatus() == kConnected, - "GetDeviceStatus follows the connection"); - IGameInputReading* rest = nullptr; - check(current(gi, GameInputKindGamepad, kStandIn, &rest) == S_OK && same(pad_of(rest), PadState{}), - "the stand-in is back, at rest"); - rest->Release(); - IGameInputReading* any = nullptr; - check(gi->GetCurrentReading(GameInputKindGamepad, nullptr, &any) == S_OK && any, "any pad: the stand-in's reading"); - any->Release(); -} - -void native_pad_sits_between_xinput_and_keyboard() { - std::printf("-- the DualSense sits between XInput and the stand-in\n"); - Hub h = fake(); - IGameInput* gi = h.gi; - { - std::lock_guard lock(h.host->mu); - h.host->native = true; - h.host->native_pad.buttons = GameInputGamepadA; - } - poll(gi); - IGameInputReading* r = nullptr; - check(current(gi, GameInputKindGamepad, kStandIn, &r) == GAMEINPUT_E_DEVICE_DISCONNECTED, - "a DualSense sends the stand-in away"); - check(current(gi, GameInputKindGamepad, kDualSense, &r) == S_OK && pad_of(r).buttons == GameInputGamepadA, - "the DualSense's reading"); - r->Release(); - { - std::lock_guard lock(h.host->mu); - h.host->pads[0] = true; - } - poll(gi); - check(current(gi, GameInputKindGamepad, kDualSense, &r) == GAMEINPUT_E_DEVICE_DISCONNECTED, - "an XInput pad wins over the DualSense"); - check(current(gi, GameInputKindGamepad, 0, &r) == S_OK, "the XInput pad reads"); - r->Release(); - { - std::lock_guard lock(h.host->mu); - h.host->pads[0] = false; - h.host->native = false; - } - poll(gi); - check(current(gi, GameInputKindGamepad, kStandIn, &r) == S_OK, "with neither, the stand-in is back"); - r->Release(); -} - -void keys_feed_the_keyboard_and_the_stand_in() { - std::printf("-- keys feed the keyboard and the stand-in pad\n"); - Hub h = fake(); - IGameInput* gi = h.gi; - Log log; - register_devices(gi, GameInputKindKeyboard, GameInputBlockingEnumeration, &log); - check(log.size() == 1 && call_is(log, 0, device(gi, kKeyboard), kConnected, 0), "the keyboard is enumerated"); - const std::vector keys = {key('W'), key(0x0D), key('L'), key('C')}; - { - std::lock_guard lock(h.host->mu); - h.host->keys = keys; - } - poll(gi); - IGameInputReading* r = nullptr; - check(current(gi, GameInputKindKeyboard, kKeyboard, &r) == S_OK, "the keyboard has a reading"); - check(r->GetKeyCount() == 4, "GetKeyCount counts the keys held"); - KeyState got[8] = {}; - check(r->GetKeyState(8, got) == 4 && std::memcmp(got, keys.data(), 4 * sizeof(KeyState)) == 0, - "GetKeyState copies them out"); - check(r->GetKeyState(2, got) == 2, "GetKeyState stops at the room given"); - PadState none{}; - check(!r->GetGamepadState(&none), "a keyboard reading has no pad state"); - r->Release(); - - check(current(gi, GameInputKindGamepad, kStandIn, &r) == S_OK, "the stand-in has a reading"); - const PadState expected{GameInputGamepadA, 0, 1.0f, 0, 1.0f, 1.0f, 0}; - check(same(pad_of(r), expected), "W, Enter, L and C: up, A, right stick right, right trigger"); - r->Release(); - check(current(gi, GameInputKindGamepad, kKeyboard, &r) == GAMEINPUT_E_READING_NOT_FOUND, - "a keyboard reading is no gamepad reading"); - check(device(gi, kKeyboard)->GetDeviceInfo()->supportedInput == GameInputKindKeyboard && - device(gi, kStandIn)->GetDeviceInfo()->supportedInput == GameInputKindGamepad, - "the devices say what they are"); -} - -void async_enumeration_and_unregistering() { - std::printf("-- asynchronous enumeration waits for the poll; unregistering stops callbacks\n"); - Hub h = fake(); - IGameInput* gi = h.gi; - Log log; - const GameInputCallbackToken token = register_devices(gi, GameInputKindGamepad, GameInputAsyncEnumeration, &log); - check(log.size() == 0, "nothing before the next poll"); - poll(gi); - check(log.size() == 1 && call_is(log, 0, device(gi, kStandIn), kConnected, 0), "the poll delivers it"); - check(gi->UnregisterCallback(token, 5000), "UnregisterCallback succeeds"); - { - std::lock_guard lock(h.host->mu); - h.host->pads[0] = true; - } - poll(gi); - check(log.size() == 1, "no callback after unregistering"); -} - -std::atomic g_inside{false}, g_leave{false}; -std::atomic g_from_inside{0}; - -void CALLBACK slow(GameInputCallbackToken token, void* context, IGameInputDevice*, uint64_t, uint32_t, uint32_t) { - auto* gi = static_cast(context); - if (!gi->UnregisterCallback(token, 0)) g_from_inside.fetch_add(1); // it cannot wait for itself - g_inside = true; - while (!g_leave) std::this_thread::sleep_for(std::chrono::milliseconds(1)); -} - -void unregistering_waits_for_a_running_callback() { - std::printf("-- unregistering waits for a running callback\n"); - Hub h = fake(); - IGameInput* gi = h.gi; - GameInputCallbackToken token = 0; - check(gi->RegisterDeviceCallback(nullptr, GameInputKindGamepad, 1, GameInputNoEnumeration, gi, slow, &token) == - S_OK, - "register a slow callback"); - { - std::lock_guard lock(h.host->mu); - h.host->pads[1] = true; - } - std::thread poller([gi] { poll(gi); }); - while (!g_inside) std::this_thread::sleep_for(std::chrono::milliseconds(1)); - check(!gi->UnregisterCallback(token, 5000), "times out while it runs"); - std::thread leave([] { - std::this_thread::sleep_for(std::chrono::milliseconds(50)); - g_leave = true; - }); - const auto start = std::chrono::steady_clock::now(); - check(gi->UnregisterCallback(token, UINT64_MAX), "waits for it"); - check(std::chrono::steady_clock::now() - start >= std::chrono::milliseconds(40), "it really waited"); - check(g_from_inside == 1, "from inside its own callback it fails at once"); - poller.join(); - leave.join(); -} - -void devices_by_id_and_rumble() { - std::printf("-- devices are found by id; rumble reaches the host\n"); - Hub h = fake(); - IGameInput* gi = h.gi; - { - std::lock_guard lock(h.host->mu); - h.host->pads[2] = true; - } - poll(gi); - IGameInputDevice* pad = device(gi, 2); - const GameInputDeviceInfo* info = pad->GetDeviceInfo(); - AppLocalDeviceId zero{}; - check(std::memcmp(&info->deviceId, &zero, sizeof zero) != 0, "a device has an id"); - check(reinterpret_cast(&info->deviceId) - reinterpret_cast(info) == 0x20, - "the id the title reads at +0x20"); - check(info->infoSize == sizeof(GameInputDeviceInfo) && - info->supportedRumbleMotors == (GameInputRumbleLowFrequency | GameInputRumbleHighFrequency), - "XInput pads have two motors"); - IGameInputDevice* found = nullptr; - check(gi->FindDeviceFromId(&info->deviceId, &found) == S_OK && found == pad, "FindDeviceFromId finds it"); - AppLocalDeviceId other{}; - std::memset(other.value, 1, sizeof other.value); - check(gi->FindDeviceFromId(&other, &found) == GAMEINPUT_E_DEVICE_NOT_FOUND && !found, "an unknown id is not found"); - - const GameInputRumbleParams half{0.5f, 1.0f, 1.0f, 1.0f}, full{1, 1, 1, 1}; - pad->SetRumbleState(&half); - device(gi, kStandIn)->SetRumbleState(&full); // the stand-in has no motors - pad->SetRumbleState(nullptr); - { - std::lock_guard lock(h.host->mu); - const std::vector> want = { - std::make_tuple(2, uint16_t{32767}, uint16_t{65535}), std::make_tuple(2, uint16_t{0}, uint16_t{0})}; - check(h.host->rumble == want, "the two body motors reach slot 2; null stops them; trigger motors are dropped"); - } - void* effect = reinterpret_cast(1); - check(pad->CreateForceFeedbackEffect(0, nullptr, &effect) == E_NOTIMPL && !effect, - "force feedback is refused with a null effect"); - GameInputBatteryState battery{1, 1, 1, 1, GameInputBatteryCharging}; - pad->GetBatteryState(&battery); - check(battery.status == GameInputBatteryNotPresent, "no battery"); - void* qi = nullptr; - check(gi->QueryInterface(IID_IGameInput, &qi) == S_OK && qi == gi, "IGameInput answers its own IID"); - check(pad->QueryInterface(IID_IGameInputReading, &qi) == E_NOINTERFACE && !qi, "a device is no reading"); - IGameInputDispatcher* dispatcher = reinterpret_cast(1); - check(gi->CreateDispatcher(&dispatcher) == E_NOTIMPL && !dispatcher, "no dispatcher, with a null out pointer"); -} - -void stand_in_can_be_turned_off() { - std::printf("-- the stand-in pad can be left out\n"); - auto host = std::make_shared(); - IGameInput* gi = create_hub(std::make_unique(host), false); - IGameInputReading* r = nullptr; - check(current(gi, GameInputKindGamepad, kStandIn, &r) == GAMEINPUT_E_DEVICE_DISCONNECTED, - "no stand-in when it is off"); - check(current(gi, GameInputKindKeyboard, kKeyboard, &r) == S_OK, "the keyboard is still there"); - r->Release(); -} - -void dualsense_reports_decode() { - std::printf("-- DualSense USB reports\n"); - uint8_t report[64] = {1, 255, 0, 128, 255, 0, 255, 0, 0x21, 0x51}; - PadState s{}; - check(decode_dualsense(report, sizeof report, &s), "a USB input report decodes"); - const PadState want{GameInputGamepadA | GameInputGamepadDPadUp | GameInputGamepadDPadRight | - GameInputGamepadLeftShoulder | GameInputGamepadView | GameInputGamepadLeftThumbstick, - 0, 1.0f, 1.0f, 1.0f, 0, -1.0f}; - check(same(s, want), "buttons, hat and axes as VIctory maps them"); - const uint8_t rest[10] = {1, 128, 128, 128, 128, 0, 0, 0, 8, 0}; - std::memcpy(report, rest, sizeof rest); - check(decode_dualsense(report, sizeof report, &s) && same(s, PadState{}), "hat 8 and centred sticks: at rest"); - check(!decode_dualsense(report, 10, &s), "a short report is refused"); - report[0] = 0x31; - check(!decode_dualsense(report, sizeof report, &s), "a Bluetooth report id is refused"); -} - -void stand_in_mapping() { - std::printf("-- the stand-in pad's keys\n"); - const PadState s = stand_in({key(0x1B), key(0x09), key('A'), key('S'), key('Q'), key('H'), key('Z'), key('J')}); - check(s.buttons == (GameInputGamepadMenu | GameInputGamepadView | GameInputGamepadLeftShoulder | - GameInputGamepadRightThumbstick), - "Esc Menu, Tab View, Q left shoulder, H right stick click"); - check(s.leftThumbstickX == -1.0f && s.leftThumbstickY == -1.0f && s.rightThumbstickX == -1.0f && - s.leftTrigger == 1.0f && s.rightTrigger == 0.0f, - "A and S push the left stick left and down, J the right stick left, Z the left trigger"); - const PadState both = stand_in({key('A'), key('D')}); - check(both.leftThumbstickX == 0.0f, "opposite keys cancel"); -} - -void registered_by_ordinal() { - std::printf("-- registry\n"); - void* by_name = rt::shims::find("gameinput.dll", "GameInputCreate"); - check(by_name && rt::shims::find("gameinput.dll", "#1") == by_name, "GameInputCreate by name and by ordinal 1"); - check(rt::shims::find("xgameruntime.dll", "GameInputCreate") == by_name, "and through xgameruntime.dll"); - using Create = HRESULT(WINAPI*)(IGameInput**); - check(reinterpret_cast(by_name)(nullptr) == E_INVALIDARG, "a null out pointer is refused"); -} - -} // namespace - -int main() { - std::printf("gameinput_xinput_test\n"); - pads_connect_report_and_disconnect(); - native_pad_sits_between_xinput_and_keyboard(); - keys_feed_the_keyboard_and_the_stand_in(); - async_enumeration_and_unregistering(); - unregistering_waits_for_a_running_callback(); - devices_by_id_and_rumble(); - stand_in_can_be_turned_off(); - dualsense_reports_decode(); - stand_in_mapping(); - registered_by_ordinal(); - std::printf("%d checks, %d failed\n", g_checks, g_failures); - return g_failures == 0 ? 0 : 1; -} diff --git a/runtime/test/gfx10_descriptors_test.cpp b/runtime/test/gfx10_descriptors_test.cpp index d5d48c3b3..f30d7f026 100644 --- a/runtime/test/gfx10_descriptors_test.cpp +++ b/runtime/test/gfx10_descriptors_test.cpp @@ -454,18 +454,6 @@ int main() { CHECK(decode(v, read) && read == buffer); buffer = {.address = 0x1000, .num_records = 256, .format = format_from_vulkan(VK_FORMAT_R32_SFLOAT)}; CHECK(decode(encode(buffer), read) && read == buffer && read.stride == 0); - // A constant-buffer view: float4 records, so `buffer_load_dwordx4 ... idxen` with a row number reaches that row - // (row k at address + 16 k, as tools/rdna2spirv.py buffer_address computes it), s_buffer_load is bounded at the - // view's bytes (NUM_RECORDS * STRIDE), and an index past the last row is out of range (OOB_SELECT 1). - const Buffer constants = constant_buffer_descriptor(0x4119b9c0, 1536); - CHECK(constants.address == 0x4119b9c0 && constants.stride == 16 && constants.num_records == 96); - CHECK(constants.format == format_from_vulkan(VK_FORMAT_R32G32B32A32_SFLOAT)); - CHECK(constants.oob_select == OobSelect::structured && constants.swizzle == identity_swizzle); - const BufferWords cbv = encode(constants); - CHECK(get(cbv[1], 16, 14) == 16 && cbv[2] == 96 && get(cbv[3], 28, 2) == 1); - CHECK(std::uint64_t(cbv[2]) * get(cbv[1], 16, 14) == 1536); - CHECK(decode(cbv, read) && read == constants); - CHECK(constant_buffer_descriptor(0x1000, 20).num_records == 2); // a partial last row is kept // TYPE (bits 31:30) is 0 for a buffer; the first four dwords of a T# are refused, and so is a reserved DST_SEL. const Buffer kept = read; BufferWords wrong = v; diff --git a/runtime/test/gfx10_tiling_test.cpp b/runtime/test/gfx10_tiling_test.cpp index 5502c9e88..fd0d14779 100644 --- a/runtime/test/gfx10_tiling_test.cpp +++ b/runtime/test/gfx10_tiling_test.cpp @@ -2,11 +2,8 @@ #include #include -#include #include -#include #include -#include #include #define CHECK(condition) do { \ @@ -103,251 +100,6 @@ int check_surface(TileMode mode, std::size_t bpe, std::size_t width, std::size_t return 0; } -// ---- Whole-texture layouts (TextureLayout, ported from VIctory victory-formats texture.rs, whose tests these are) ---- - -namespace g = leonida::gfx10; - -g::LayoutDesc desc(std::uint32_t w, std::uint32_t h, std::uint32_t mips, std::uint32_t bpe, std::uint32_t swizzle) { - g::LayoutDesc d; - d.width = w; - d.height = h; - d.mips = mips; - d.element_bytes = bpe; - d.swizzle = swizzle; - return d; -} - -g::TextureLayout layout_of(const g::LayoutDesc& d, bool series_s = false) { - g::TextureLayout l; - if (!g::TextureLayout::make(d, series_s, l)) std::fprintf(stderr, "layout refused\n"); - return l; -} - -std::uint64_t offset_of(const g::TextureLayout& l, std::uint32_t mip, std::uint32_t x, std::uint32_t y, - std::uint32_t z = 0) { - std::uint64_t at = ~0ull; - l.offset(mip, x, y, z, at); - return at; -} - -int check_texture_layouts() { - namespace sw = g::swizzle; - // Blocks hold their size in elements. - for (const std::uint32_t log2 : {8u, 12u, 16u}) { - const std::uint32_t mode = log2 == 8 ? sw::sw_256b_s : log2 == 12 ? sw::sw_4kb_s : sw::sw_64kb_d; - for (std::uint32_t e = 0; e < 5; ++e) { - g::TextureLayout l; - CHECK(g::TextureLayout::make(desc(1, 1, 1, 1u << e, mode), false, l)); - const auto& b = l.block(); - CHECK((std::uint64_t(b[0]) * b[1] * b[2] << e) == (std::uint64_t(1) << log2)); - } - } - { - const g::TextureLayout l = layout_of(desc(64, 64, 1, 16, sw::sw_64kb_d)); - CHECK(l.block()[0] == 64 && l.block()[1] == 64 && l.size() == 65536 && l.alignment() == 65536); - } - // One mip of SW_4KB_S and SW_64KB_D is TiledSurface2D's addressing (Mesa's patterns, corpus-checked). - for (const auto mode : {TileMode::sw_4kb_s, TileMode::sw_64kb_d}) - for (const std::uint32_t bpe : {1u, 2u, 4u, 8u, 16u}) { - TiledSurface2D surface; - CHECK(TiledSurface2D::make(mode, bpe, 300, 130, surface)); - const g::TextureLayout l = - layout_of(desc(300, 130, 1, bpe, mode == TileMode::sw_4kb_s ? sw::sw_4kb_s : sw::sw_64kb_d)); - CHECK(l.addressable() && l.size() == surface.tiled_size()); - for (std::uint32_t y = 0; y < 130; y += 7) - for (std::uint32_t x = 0; x < 300; x += 5) { - std::size_t want = 0; - CHECK(surface.element_offset(x, y, want)); - CHECK(offset_of(l, 0, x, y) == want); - } - } - // Hand-checked addresses: 64 KiB D with 4-byte elements; 4 KiB S with 16-byte elements is 16x16, y first. - { - const g::TextureLayout l = layout_of(desc(128, 128, 1, 4, sw::sw_64kb_d)); - CHECK(offset_of(l, 0, 1, 0) == 1u << 2 && offset_of(l, 0, 4, 0) == 1u << 6 && offset_of(l, 0, 0, 4) == 1u << 7); - CHECK(offset_of(l, 0, 0, 8) == 1u << 8 && offset_of(l, 0, 64, 64) == ((1u << 15) | (1u << 14))); - const g::TextureLayout s = layout_of(desc(32, 32, 1, 16, sw::sw_4kb_s)); - CHECK(s.block()[0] == 16 && s.block()[1] == 16); - CHECK(offset_of(s, 0, 0, 1) == 1u << 4 && offset_of(s, 0, 1, 0) == 1u << 6); - CHECK(offset_of(s, 0, 16, 0) == 4096 && offset_of(s, 0, 0, 16) == 8192); - } - // The mip tail comes first: a 256x256 BC7 chain in 64 KiB D has one tail block holding mips 1-8, then mip 0; mip 1 - // sits at x = 32 elements, 32 KiB into the tail. 4 KiB blocks hold fewer tail mips. - { - const g::TextureLayout l = layout_of(desc(64, 64, 9, 16, sw::sw_64kb_d)); - CHECK(l.first_tail_mip() == 1 && l.size() == 2 * 65536 && l.mips()[0].offset == 65536); - const g::MipLayout& m1 = l.mips()[1]; - CHECK(m1.in_tail && m1.tail_offset == 32768 && m1.tail_x == 32 && m1.tail_y == 0); - CHECK(offset_of(l, 1, 0, 0) == 32768); - const g::TextureLayout s = layout_of(desc(64, 64, 9, 16, sw::sw_4kb_s)); - CHECK(s.first_tail_mip() == 3 && s.mips()[2].offset == 4096 && s.mips()[1].offset == 8192 && - s.mips()[0].offset == 8192 + 16384); - } - // Every element of every mip and slice lands on its own address inside the texture, and tiling then detiling - // gives the rows back (padding in the rows untouched). - std::vector cases = {desc(64, 64, 7, 16, sw::sw_64kb_d), desc(100, 60, 7, 4, sw::sw_64kb_d), - desc(250, 175, 8, 8, sw::sw_4kb_s), desc(33, 17, 6, 1, sw::sw_4kb_d), - desc(40, 9, 3, 2, sw::sw_64kb_s), desc(30, 20, 5, 4, sw::linear), - desc(83, 31, 6, 1, sw::sw_256b_s)}; - cases.push_back(desc(109, 71, 6, 16, sw::sw_256b_d)); - cases.back().block = 4; - cases.push_back(desc(70, 70, 4, 16, sw::sw_4kb_s)); - cases.back().depth = 3; - cases.push_back(desc(64, 32, 7, 4, sw::sw_4kb_s)); - cases.back().dimension = g::Dimension::tex3d; - cases.back().depth = 16; - for (const g::LayoutDesc& d : cases) { - g::TextureLayout l; - CHECK(g::TextureLayout::make(d, false, l) && l.addressable()); - std::vector seen(l.size()); - std::vector tiled(l.size()); - const std::size_t n = d.element_bytes; - const std::uint32_t slices = d.dimension == g::Dimension::tex3d ? 1 : d.depth; - for (std::uint32_t slice = 0; slice < slices; ++slice) - for (std::uint32_t mip = 0; mip < d.mips; ++mip) { - const g::MipLayout& m = l.mips()[mip]; - const std::size_t active = m.width * n, row = active + 13, plane = row * m.height + 11; - std::vector linear(plane * m.depth), back(linear.size(), std::byte{0xcc}); - for (std::size_t i = 0; i < linear.size(); ++i) linear[i] = std::byte(i * 7 + mip * 13 + slice); - CHECK(l.tile(tiled, mip, slice, linear, row, plane)); - CHECK(l.detile(tiled, mip, slice, back, row, plane)); - for (std::uint32_t z = 0; z < m.depth; ++z) { - const std::size_t base = z * plane; - for (std::uint32_t y = 0; y < m.height; ++y) { - const std::size_t start = base + y * row; - CHECK(std::equal(back.begin() + start, back.begin() + start + active, linear.begin() + start)); - CHECK(std::all_of(back.begin() + start + active, back.begin() + start + row, - [](std::byte b) { return b == std::byte{0xcc}; })); - for (std::uint32_t x = 0; x < m.width; ++x) { - std::uint64_t at = 0; - CHECK(l.offset(mip, x, y, slice + z, at)); - CHECK(at + n <= seen.size() && at % n == 0 && !seen[at]); - CHECK(std::equal(tiled.begin() + at, tiled.begin() + at + n, - linear.begin() + start + x * n)); - seen[at] = true; - } - } - } - } - } - // The smaller mips need only the start of the texture: 1024x1024 BC1 in 4 KiB blocks. - { - g::LayoutDesc d = desc(1024, 1024, 9, 8, sw::sw_4kb_s); - d.block = 4; - const g::TextureLayout l = layout_of(d); - CHECK(l.bytes_from(0) == l.size() && l.bytes_from(4) == 4096 && l.bytes_from(8) == 4096); - for (std::uint32_t mip = 1; mip < 9; ++mip) CHECK(l.bytes_from(mip - 1) >= l.bytes_from(mip)); - std::vector tiled(l.size()); - for (std::size_t i = 0; i < tiled.size(); ++i) tiled[i] = std::byte((i * 7) >> 3); - for (std::uint32_t mip = 1; mip < 9; ++mip) { - const g::MipLayout& m = l.mips()[mip]; - const std::size_t pitch = m.width * 8; - std::vector whole(pitch * m.height), part(whole.size()); - const std::size_t len = std::size_t(l.bytes_from(mip)); - CHECK(l.detile(tiled, mip, 0, whole, pitch, whole.size())); - CHECK(l.detile(std::span(tiled).first(len), mip, 0, part, pitch, part.size())); - CHECK(whole == part); - CHECK(!l.detile(std::span(tiled).first(len - 1), mip, 0, part, pitch, part.size())); - } - d.depth = 2; - const g::TextureLayout two = layout_of(d); - CHECK(two.bytes_from(4) == two.size()); - } - // Depth/stencil is two planes: 4-byte depth in 128x128 blocks, 1-byte stencil in 256x256 blocks; Z_X has no - // address equation here. - { - g::ConsoleTextureDesc d; - d.width = 1920; - d.height = 1080; - d.format = 20; // D32_FLOAT_S8X24_UINT - d.swizzle = sw::sw_64kb_z_x; - g::ConsoleTexture t; - CHECK(g::ConsoleTexture::make(d, false, t) && t.planes.size() == 2); - CHECK(t.planes[0].layout.size() == 1920ull * 1152 * 4 && t.planes[1].offset == t.planes[0].layout.size()); - CHECK(t.planes[1].layout.size() == 2048ull * 1280 && !t.planes[0].layout.addressable()); - d.format = 28; // R8G8B8A8_UNORM, the full chain - d.mips = 0; - d.swizzle = sw::sw_4kb_s; - CHECK(g::ConsoleTexture::make(d, false, t) && t.planes.size() == 1 && - t.planes[0].layout.mips().size() == 11); - d.format = 6; // R32G32B32_FLOAT: not laid out - CHECK(!g::ConsoleTexture::make(d, false, t)); - } - // SW_64KB_R_X: FNV-1a of the little-endian u32 addresses in row order, as AMD's Addr2ComputeSurfaceAddrFromCoord - // gives them (VIctory's hashes, GFX10.3 PAL c5e8000); odd sizes check the high coordinate bits and a final partial - // run. Tiling then detiling gives the rows back. - struct XorCase { - bool series_s; - std::uint32_t bpe; - std::uint64_t hashes[2]; - }; - constexpr XorCase xor_cases[] = { - {false, 2, {0x10514417061b8725ull, 0x11a55308ad39a7b9ull}}, - {false, 4, {0xd4556429b544c925ull, 0x7a2302116719e58full}}, - {false, 8, {0x30aa25589f795b25ull, 0xb5f483c6ddf11404ull}}, - {true, 8, {0xe107baa89506c525ull, 0x7b7f2a812bdc611bull}}, - {true, 2, {0x67cde4ff6e728f25ull, 0x2eb48d52f015da36ull}}, - {true, 4, {0xce798e86f5ab1d25ull, 0x6cddf048fc97e768ull}}}; - for (const XorCase& c : xor_cases) { - const std::uint32_t sizes[2][2] = {{256, 256}, {513, 357}}; - for (int s = 0; s < 2; ++s) { - const std::uint32_t w = sizes[s][0], h = sizes[s][1]; - g::TextureLayout l; - CHECK(g::TextureLayout::make(desc(w, h, 1, c.bpe, sw::sw_64kb_r_x), c.series_s, l) && l.addressable()); - std::uint64_t hash = 0xcbf29ce484222325ull; - const std::size_t pitch = std::size_t(w) * c.bpe + 32; - std::vector linear(pitch * h, std::byte{0x55}), tiled(l.size(), std::byte{0xee}); - std::vector back(linear.size(), std::byte{0x55}); - for (std::uint32_t y = 0; y < h; ++y) - for (std::uint32_t x = 0; x < w; ++x) { - std::uint64_t at = 0; - CHECK(l.offset(0, x, y, 0, at)); - for (int b = 0; b < 4; ++b) - hash = (hash ^ ((std::uint32_t(at) >> (8 * b)) & 0xffu)) * 0x100000001b3ull; - const std::uint64_t seed = std::uint64_t(x + w * y) * 0x9e3779b97f4a7c15ull; - std::memcpy(linear.data() + y * pitch + x * c.bpe, &seed, c.bpe); - } - CHECK(hash == c.hashes[s]); - CHECK(l.tile(tiled, 0, 0, linear, pitch, 0) && l.detile(tiled, 0, 0, back, pitch, 0) && back == linear); - } - } - // Bad descriptions and buffers are refused. - { - g::TextureLayout l; - CHECK(!g::TextureLayout::make(desc(0, 4, 1, 4, sw::sw_4kb_s), false, l)); - CHECK(!g::TextureLayout::make(desc(4, 4, 1, 12, sw::sw_4kb_s), false, l)); - CHECK(!g::TextureLayout::make(desc(4, 4, 1, 4, 3), false, l)); - CHECK(!g::TextureLayout::make(desc(16385, 1, 1, 4, sw::sw_4kb_s), false, l)); - CHECK(g::TextureLayout::make(desc(64, 64, 1, 4, sw::sw_4kb_s), false, l)); - std::vector small(100), out(64 * 64 * 4); - CHECK(!l.detile(small, 0, 0, out, 256, 0)); - std::uint64_t at = 0; - CHECK(!l.offset(0, 64, 0, 0, at)); - g::TextureLayout lin; - CHECK(g::TextureLayout::make(desc(4, 2, 1, 4, sw::linear), false, lin)); - std::vector t(lin.size()), row(32); - CHECK(!lin.detile(t, 0, 0, row, std::numeric_limits::max(), 0)); - CHECK(!lin.tile(t, 0, 0, row, std::numeric_limits::max(), 0)); - } - // The layout word and the library's suggestion (VIctory xg.rs): 0x100 | mode, 1 linear, 0 the suggestion. - { - std::uint32_t mode = 99; - CHECK(g::suggested_swizzle(g::Dimension::tex2d, false, false) == sw::sw_4kb_s); - CHECK(g::suggested_swizzle(g::Dimension::tex3d, false, true) == sw::sw_64kb_r_x); - CHECK(g::suggested_swizzle(g::Dimension::tex2d, true, true) == sw::sw_64kb_z_x); - CHECK(g::suggested_swizzle(g::Dimension::tex1d, true, true) == sw::linear); - CHECK(g::swizzle_from_layout_word(0x10a, g::Dimension::tex2d, false, false, mode) && mode == sw::sw_64kb_d); - CHECK(g::swizzle_from_layout_word(0x101, g::Dimension::tex2d, false, false, mode) && mode == sw::sw_256b_s); - CHECK(g::swizzle_from_layout_word(1, g::Dimension::tex2d, false, false, mode) && mode == sw::linear); - CHECK(g::swizzle_from_layout_word(0, g::Dimension::tex2d, false, true, mode) && mode == sw::sw_64kb_r_x); - mode = 99; - CHECK(!g::swizzle_from_layout_word(0x205, g::Dimension::tex2d, false, false, mode) && mode == 99); - } - std::puts("gfx10_tiling: whole-texture layouts (mips, tails, slices, 3D, planes, SW_64KB_R_X) as VIctory's tests " - "give them"); - return 0; -} - int main() { // Source byte offsets reconstructed by calling ttpf_mips.detile on synthetic address-labelled bytes, // three passes (address >> 0/8/16). Extent 300x130; points (4,4), (32,16), (299,129). @@ -399,5 +151,5 @@ int main() { CHECK(!surface.tile(linear, tiled, max)); CHECK(!surface.detile(tiled, linear, max)); std::puts("gfx10_tiling: 40 surface round trips, padded bijections, 30 Python offsets and invalid arguments passed"); - return check_texture_layouts(); + return 0; } diff --git a/runtime/test/glsl/cs_depth_twin.comp b/runtime/test/glsl/cs_depth_twin.comp deleted file mode 100644 index d1bff90e7..000000000 --- a/runtime/test/glsl/cs_depth_twin.comp +++ /dev/null @@ -1,64 +0,0 @@ -#version 460 -// A compute shader for d3d12_depth_twin_test, written to the translator's runtime contract (docs/design.md, "User -// data", "Xbox GPU addresses" and "Images"; the lookup is tools/rdna2spirv.py desc_probe), standing in for the -// title's tiled lighting, which writes a depth texture's planes through unordered-access views. Its root arguments, -// in the console compute layout (rt::rootsig::pack_stage: from s4, one dword per table): -// s4 where the UAV to write starts inside the view table, in dwords -// s5 0: the stencil plane's view (an 8_UINT T#, binding 9), 1: the depth plane's (a 32_FLOAT T#, binding 8) -// s6 columns written: x < s6; the others keep what the texture held -// s7 a seed for the stencil pattern -// s8 the table of views (its 32-bit console VA): a T# in the first eight dwords of each slot -// The stencil plane gets (x * 7 + y * 13 + s7) & 255, the depth plane ((x + 64 * y) % 997) / 1024. -#extension GL_EXT_nonuniform_qualifier : require -#extension GL_EXT_buffer_reference : require -#extension GL_EXT_buffer_reference_uvec2 : require - -layout(local_size_x = 8, local_size_y = 8) in; - -layout(buffer_reference, std430, buffer_reference_align = 4) buffer Words { - uint w[]; -}; - -layout(push_constant) uniform UserData { - uint s[32]; - uvec2 heap_base; - uvec2 code_base; -} pc; - -layout(set = 0, binding = 2, std430) readonly buffer DescriptorMap { - uint map[]; // mask, then 10 uints per slot: key[8], index, pad -}; -layout(set = 0, binding = 8) uniform writeonly image2D float_images[]; -layout(set = 0, binding = 9) uniform writeonly uimage2D uint_images[]; - -uvec2 add64(uvec2 a, uvec2 b) { - uint carry; - const uint low = uaddCarry(a.x, b.x, carry); - return uvec2(low, a.y + b.y + carry); -} - -uint lookup(uint key[8]) { - uint h = 2166136261u; - for (int i = 0; i < 8; ++i) h = (h ^ key[i]) * 16777619u; - const uint mask = map[0]; - for (uint k = 0; k < 8; ++k) { - const uint slot = 1 + ((h + k) & mask) * 10; - bool same = true; - for (int i = 0; i < 8; ++i) same = same && map[slot + i] == key[i]; - if (same) return map[slot + 8]; - } - return 0; -} - -void main() { - const uvec2 xy = gl_GlobalInvocationID.xy; - if (xy.x >= pc.s[6]) return; - Words views = Words(add64(pc.heap_base, uvec2(pc.s[8], 0u))); - uint key[8]; - for (int k = 0; k < 8; ++k) key[k] = views.w[pc.s[4] + k]; - const uint image = lookup(key); - if (pc.s[5] == 0u) - imageStore(uint_images[image], ivec2(xy), uvec4((xy.x * 7u + xy.y * 13u + pc.s[7]) & 255u)); - else - imageStore(float_images[image], ivec2(xy), vec4(float((xy.x + 64u * xy.y) % 997u) / 1024.0)); -} diff --git a/runtime/test/glsl/cs_sparse_title_memory.comp b/runtime/test/glsl/cs_sparse_title_memory.comp deleted file mode 100644 index 043d23839..000000000 --- a/runtime/test/glsl/cs_sparse_title_memory.comp +++ /dev/null @@ -1,45 +0,0 @@ -#version 460 -// vk_sparse_title_memory_test: samples the pages of a sparse buffer through its device address (heap_base + VA, as a -// translated shader computes it) and writes one word into one page. -// out[3 * i + 0..2] = page i's words 0, 1 and page_words - 1, for i < pages; -// page write_page's word 1 = write_value (write_page ~0u: no write). The samples are read before the write in the -// same invocation, and no other invocation reads word 1 of that page after it. -#extension GL_EXT_buffer_reference : require -#extension GL_EXT_buffer_reference_uvec2 : require - -layout(local_size_x = 64) in; - -layout(buffer_reference, std430, buffer_reference_align = 4) buffer Words { - uint w[]; -}; - -layout(push_constant) uniform Params { - uvec2 sparse; // device address of page 0 - uvec2 result; // device address of the result words - uint page_words; - uint pages; - uint write_page; - uint write_value; -} p; - -uvec2 add64(uvec2 a, uint bytes) { - uint carry; - const uint low = uaddCarry(a.x, bytes, carry); - return uvec2(low, a.y + carry); -} - -void main() { - const uint i = gl_GlobalInvocationID.x; - if (i < p.pages) { - Words page = Words(add64(p.sparse, i * p.page_words * 4u)); - Words out_words = Words(p.result); - out_words.w[3u * i + 0u] = page.w[0]; - out_words.w[3u * i + 1u] = page.w[1]; - out_words.w[3u * i + 2u] = page.w[p.page_words - 1u]; - } - barrier(); - if (i == 0u && p.write_page != 0xffffffffu) { - Words page = Words(add64(p.sparse, p.write_page * p.page_words * 4u)); - page.w[1] = p.write_value; - } -} diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp index 17cb2d304..6930878a9 100644 --- a/runtime/test/loader_test.cpp +++ b/runtime/test/loader_test.cpp @@ -1534,9 +1534,6 @@ void test_compat_modules() { } // namespace int main() { - // The test loads images Windows refuses on purpose (compat_bad\testcompat.dll, 0xc000012f). Without this the - // loader's hard-error path shows a "Bad Image" dialog for each one on the desktop of whoever runs the suite. - SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); g_dir = work_dir(); std::error_code ec; std::filesystem::remove_all(g_dir, ec); diff --git a/runtime/test/media_foundation_test.cpp b/runtime/test/media_foundation_test.cpp deleted file mode 100644 index 8cd3e8dff..000000000 --- a/runtime/test/media_foundation_test.cpp +++ /dev/null @@ -1,161 +0,0 @@ -// mfplat.dll's source resolver proxy (shims/media_foundation.cpp): the URL rule, and the proxy over a fake host -// resolver that records what reaches it. The URL cases follow VIctory's test (crates/victory-hle/src/modules/media.rs, -// only_local_files_reach_the_host), GPL-3.0-or-later, by Marvisak and contributors (DexNom fork); Leonida is -// GPL-3.0-or-later. No game data, no network, no Media Foundation. -#include - -#include -#include -#include -#include -#include - -#include "file_system.h" -#include "media_foundation.h" -#include "shims.h" - -namespace { - -int g_checks = 0; -int g_failures = 0; - -void check(bool condition, const char* what) { - ++g_checks; - std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); - if (!condition) ++g_failures; -} - -constexpr HRESULT kUnsupportedScheme = static_cast(0xC00D36C3u); - -bool refused(const wchar_t* url, const char* scheme, const char* host) { - std::wstring out; - std::string s, h; - return !rt::media::local_url(url, out, s, h) && s == scheme && h == host; -} - -std::wstring local(const wchar_t* url) { - std::wstring out; - std::string s, h; - return rt::media::local_url(url, out, s, h) ? out : L""; -} - -// A fake IMFSourceResolver: records the URL of CreateObjectFromURL / BeginCreateObjectFromURL and its releases. -struct FakeResolver { - const void* const* vtable; - std::wstring last_url; - int calls = 0; - int released = 0; -}; - -HRESULT STDMETHODCALLTYPE fake_qi(void*, REFIID, void**) { return E_NOINTERFACE; } -ULONG STDMETHODCALLTYPE fake_add_ref(void*) { return 2; } -ULONG STDMETHODCALLTYPE fake_release(void* self) { - ++static_cast(self)->released; - return 0; -} -HRESULT STDMETHODCALLTYPE fake_create(void* self, const wchar_t* url, DWORD, void*, DWORD* type, void** object) { - auto* f = static_cast(self); - f->last_url = url; - ++f->calls; - if (type) *type = 1; - if (object) *object = self; - return S_OK; -} -HRESULT STDMETHODCALLTYPE fake_begin(void* self, const wchar_t* url, DWORD, void*, void**, void*, void*) { - auto* f = static_cast(self); - f->last_url = url; - ++f->calls; - return S_OK; -} -HRESULT STDMETHODCALLTYPE fake_other(void* self) { - ++static_cast(self)->calls; - return S_FALSE; -} - -const void* const kFakeVtable[] = { - reinterpret_cast(&fake_qi), reinterpret_cast(&fake_add_ref), - reinterpret_cast(&fake_release), reinterpret_cast(&fake_create), - reinterpret_cast(&fake_other), reinterpret_cast(&fake_begin), - reinterpret_cast(&fake_other), reinterpret_cast(&fake_other), - reinterpret_cast(&fake_other), reinterpret_cast(&fake_other), -}; - -template -F slot(void* object, size_t n) { - return reinterpret_cast((*static_cast(object))[n]); -} - -} // namespace - -int main() { - std::printf("media_foundation_test\n"); - - // Network schemes and shares are refused, naming scheme and host. - check(refused(L"https://cdn.example.com/a.mp4", "https", "cdn.example.com"), "https is refused, with its host"); - check(refused(L"RTSP://10.0.0.1:554/x", "rtsp", "10.0.0.1:554"), "rtsp in any case is refused"); - check(refused(L"mms://h/x", "mms", "h"), "mms is refused"); - check(refused(L"\\\\server\\share\\a.mp4", "unc", "server"), "a UNC share is refused"); - check(refused(L"\\\\?\\UNC\\server\\share\\a.mp4", "unc", "server"), "a long-path UNC share is refused"); - check(refused(L"file://server/share/a.mp4", "file", "server"), "a file: URL with a host is refused"); - - // Other local files pass as they are, a file: URL becomes its path. - check(local(L"file:///C:/Windows/a.wav") == L"C:\\Windows\\a.wav", "file:///C:/... becomes C:\\..."); - check(local(L"file://localhost/C:/a%20b.wav") == L"C:\\a b.wav", "localhost and %20 are understood"); - check(local(L"file:///C:/%C3%A9.wav") == L"C:\\\u00e9.wav", "percent escapes are UTF-8"); - check(local(L"clip.mp4") == L"clip.mp4", "a relative path passes as it is"); - check(local(L"D:\\movies\\x.mp4") == L"D:\\movies\\x.mp4", "a host path passes as it is"); - - // A console path goes to its host file, also as a file: URL. - const std::filesystem::path root = std::filesystem::temp_directory_path() / L"leonida_media_foundation_test"; - std::error_code ec; - std::filesystem::remove_all(root, ec); - std::filesystem::create_directories(root / L"game" / L"movies"); - { std::ofstream(root / L"game" / L"movies" / L"intro.mp4") << "1"; } - rt::fs::configure(root / L"game", root / L"overlay"); - const std::wstring want = (root / L"game" / L"movies" / L"intro.mp4").wstring(); - const std::wstring got = local(L"GAME:\\movies\\intro.mp4"); - check(std::filesystem::equivalent(got, want, ec), "GAME:\\ goes to the package folder"); - check(std::filesystem::equivalent(local(L"file:///GAME:/movies/intro.mp4"), want, ec), "so does file:///GAME:/"); - check(std::filesystem::equivalent(local(L"G:\\movies\\intro.mp4"), want, ec), "and the G: drive"); - - // The proxy over a fake host resolver. - FakeResolver fake{kFakeVtable}; - void* proxy = nullptr; - check(rt::media::wrap_resolver(&fake, &proxy) == S_OK && proxy, "the proxy wraps a host resolver"); - using CreateFn = HRESULT(STDMETHODCALLTYPE*)(void*, const wchar_t*, DWORD, void*, DWORD*, void**); - using BeginFn = HRESULT(STDMETHODCALLTYPE*)(void*, const wchar_t*, DWORD, void*, void**, void*, void*); - DWORD type = 0; - void* object = reinterpret_cast(1); - check(slot(proxy, 3)(proxy, L"http://example.com/a.mp4", 1, nullptr, &type, &object) == - kUnsupportedScheme && - !object && fake.calls == 0, - "CreateObjectFromURL refuses http before the host sees it, with a null object"); - check(slot(proxy, 3)(proxy, L"GAME:\\movies\\intro.mp4", 1, nullptr, &type, &object) == S_OK && - fake.calls == 1 && std::filesystem::equivalent(fake.last_url, want, ec) && object == &fake && type == 1, - "a console path reaches the host as its host file"); - void* cancel = reinterpret_cast(1); - check(slot(proxy, 5)(proxy, L"rtsp://h/x", 1, nullptr, &cancel, nullptr, nullptr) == kUnsupportedScheme && - !cancel && fake.calls == 1, - "BeginCreateObjectFromURL refuses rtsp"); - check(slot(proxy, 5)(proxy, L"file:///C:/a.mp4", 1, nullptr, &cancel, nullptr, nullptr) == S_OK && - fake.last_url == L"C:\\a.mp4", - "BeginCreateObjectFromURL forwards a local file"); - using CancelFn = HRESULT(STDMETHODCALLTYPE*)(void*, void*); - check(slot(proxy, 9)(proxy, nullptr) == S_FALSE, "CancelObjectCreation reaches the host"); - void* other = nullptr; - constexpr GUID kIMFMediaSource = {0x279a808d, 0xaec7, 0x40c8, {0x9c, 0x6b, 0xa6, 0xb4, 0x92, 0xc7, 0x8a, 0x66}}; - using QiFn = HRESULT(STDMETHODCALLTYPE*)(void*, REFIID, void**); - check(slot(proxy, 0)(proxy, kIMFMediaSource, &other) == E_NOINTERFACE && !other, - "QueryInterface hands out nothing but the resolver"); - using RefFn = ULONG(STDMETHODCALLTYPE*)(void*); - check(slot(proxy, 1)(proxy) == 2 && slot(proxy, 2)(proxy) == 1 && fake.released == 0, - "AddRef and Release count"); - check(slot(proxy, 2)(proxy) == 0 && fake.released == 1, "the last Release releases the host resolver"); - - check(rt::shims::find("mfplat.dll", "MFCreateSourceResolver") != nullptr, "MFCreateSourceResolver is registered"); - check(!rt::shims::owns_dll("mfplat.dll"), "mfplat.dll stays a host module for LoadLibrary"); - - std::filesystem::remove_all(root, ec); - std::printf("%d checks, %d failed\n", g_checks, g_failures); - return g_failures == 0 ? 0 : 1; -} diff --git a/runtime/test/module_identity_test.cpp b/runtime/test/module_identity_test.cpp deleted file mode 100644 index 912acb2d1..000000000 --- a/runtime/test/module_identity_test.cpp +++ /dev/null @@ -1,93 +0,0 @@ -// GetModuleHandle(NULL) and GetModuleFileName in mapped code name the title's image (shims/library_loader.cpp, -// ported from VIctory victory-hle src/modules/kernel.rs). No game files: a stand-in loader answers for one fake image -// base with a made-up path. -#include - -#include -#include -#include - -#include "shims.h" - -namespace { - -int g_failures = 0; -void check(bool condition, const char* what) { - std::printf("%s: %s\n", condition ? "ok" : "FAIL", what); - if (!condition) ++g_failures; -} - -// Any address no host module has; never dereferenced. -alignas(64) unsigned char g_fake_image[16]; -void* const kImage = g_fake_image; -const wchar_t kPath[] = L"C:\\Games\\Title\\title_master.exe"; - -void* find_loaded(void*, const std::string&) { return nullptr; } -void* load_bundled(void*, const std::string&, uint32_t, bool& handled) { - handled = false; - return nullptr; -} -void* get_proc(void*, void* module, const std::string&, bool& owns) { - owns = module == kImage; - return nullptr; -} -bool owns_handle(void*, void* module) { return module == kImage; } -bool module_path(void*, void* module, std::wstring& path) { - if (module != kImage) return false; - path = kPath; - return true; -} -const rt::shims::BundledModuleOps kOps{&find_loaded, &load_bundled, &get_proc, &owns_handle, nullptr, nullptr, - &module_path}; - -} // namespace - -int main() { - using HandleW = HMODULE(WINAPI*)(LPCWSTR); - using HandleA = HMODULE(WINAPI*)(LPCSTR); - using NameW = DWORD(WINAPI*)(HMODULE, LPWSTR, DWORD); - using NameA = DWORD(WINAPI*)(HMODULE, LPSTR, DWORD); - const auto handle_w = reinterpret_cast(rt::shims::find("kernel32.dll", "GetModuleHandleW")); - const auto handle_a = reinterpret_cast(rt::shims::find("kernelbase.dll", "GetModuleHandleA")); - const auto name_w = reinterpret_cast(rt::shims::find("kernel32.dll", "GetModuleFileNameW")); - const auto name_a = - reinterpret_cast(rt::shims::find("api-ms-win-core-libraryloader-l1-2-0.dll", "GetModuleFileNameA")); - check(handle_w && handle_a && name_w && name_a, "the four imports are served"); - if (!(handle_w && handle_a && name_w && name_a)) return 1; - - // Before the main image is set, everything is the host's. - check(handle_w(nullptr) == GetModuleHandleW(nullptr), "no main image yet: GetModuleHandleW(NULL) is the host's"); - wchar_t host[MAX_PATH] = {}, got[MAX_PATH] = {}; - GetModuleFileNameW(nullptr, host, MAX_PATH); - check(name_w(nullptr, got, MAX_PATH) > 0 && std::wcscmp(host, got) == 0, - "no main image yet: GetModuleFileNameW(NULL) is the host's"); - - rt::shims::add_bundled_loader(&g_failures, &kOps); - rt::shims::set_main_image(kImage); - check(handle_w(nullptr) == kImage && handle_a(nullptr) == kImage, "GetModuleHandleA/W(NULL) is the title's image"); - check(handle_w(L"kernel32.dll") == GetModuleHandleW(L"kernel32.dll"), "a named host module is still the host's"); - - const DWORD length = static_cast(std::wcslen(kPath)); - std::memset(got, 0, sizeof(got)); - check(name_w(nullptr, got, MAX_PATH) == length && std::wcscmp(got, kPath) == 0, - "GetModuleFileNameW(NULL) is the title's file, its length without the terminator"); - std::memset(got, 0, sizeof(got)); - check(name_w(static_cast(kImage), got, MAX_PATH) == length && std::wcscmp(got, kPath) == 0, - "GetModuleFileNameW(title base) is the same file"); - char narrow[MAX_PATH] = {}; - check(name_a(nullptr, narrow, MAX_PATH) == length && std::strcmp(narrow, "C:\\Games\\Title\\title_master.exe") == 0, - "GetModuleFileNameA(NULL) is the same file in the ANSI code page"); - wchar_t small[8] = {}; - SetLastError(0); - check(name_w(nullptr, small, 8) == 8 && small[7] == 0 && std::wcsncmp(small, kPath, 7) == 0 && - GetLastError() == ERROR_INSUFFICIENT_BUFFER, - "a short buffer gets the truncated, terminated path, its size and ERROR_INSUFFICIENT_BUFFER"); - const HMODULE k32 = GetModuleHandleW(L"kernel32.dll"); - GetModuleFileNameW(k32, host, MAX_PATH); - check(name_w(k32, got, MAX_PATH) > 0 && std::wcscmp(host, got) == 0, "a host module's file is the host's answer"); - - rt::shims::set_main_image(nullptr); - rt::shims::remove_bundled_loader(&g_failures); - std::printf("%s\n", g_failures ? "FAILED" : "PASSED"); - return g_failures ? 1 : 0; -} diff --git a/runtime/test/pipeline_queue_test.cpp b/runtime/test/pipeline_queue_test.cpp deleted file mode 100644 index 5712daa32..000000000 --- a/runtime/test/pipeline_queue_test.cpp +++ /dev/null @@ -1,224 +0,0 @@ -// src/pipeline_queue.h without a GPU: the frame budget's window (VIctory make.rs loading_tests, ported), the order the -// builder takes pipelines in, a retired job that never runs, drops, and the early list written and read back. -// No game data. -#include "../src/pipeline_queue.h" -#include "test_temp_dir.h" - -#include -#include -#include -#include -#include - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "pipeline_queue_test line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -using namespace leonida::pipelines; -using namespace std::chrono_literals; - -namespace { - -// make.rs two_threads_in_one_frame_both_wait_inside_the_window: two threads waiting in one frame share one window, a -// thread that asks once the window is used up gets nothing, and a new frame has a window of its own. -int frame_window() { - const Sharing sharing = sharing_from(nullptr); - EXPECT(sharing == Sharing::window); - const Clock::duration budget = 12s, ms = 1ms; - const Clock::time_point t0 = Clock::now(); - FrameWait w; - const Clock::duration a = w.begin(sharing, 7, budget, t0); - const Clock::duration b = w.begin(sharing, 7, budget, t0 + ms); - EXPECT(a == budget); - EXPECT(b == budget - ms); - w.end(sharing, 7, a, 2s, t0 + 2s); - w.end(sharing, 7, b, 2s - ms, t0 + 2s); - EXPECT(w.begin(sharing, 7, budget, t0 + 5s) == 10s); - w.end(sharing, 7, 10s, 10s, t0 + 15s); - EXPECT(w.begin(sharing, 7, budget, t0 + 16s) == Clock::duration::zero()); - EXPECT(w.begin(sharing, 8, budget, t0 + 17s) == budget); - // make.rs the_old_ways_of_counting_stay_behind_the_switch. - FrameWait r; - EXPECT(r.begin(Sharing::reserve, 1, budget, t0) == budget); - EXPECT(r.begin(Sharing::reserve, 1, budget, t0) == Clock::duration::zero()); - FrameWait p; - EXPECT(p.begin(Sharing::per_thread, 1, budget, t0) == budget); - EXPECT(p.begin(Sharing::per_thread, 1, budget, t0) == budget); - p.end(Sharing::per_thread, 1, budget, 3s, t0); - EXPECT(p.begin(Sharing::per_thread, 1, budget, t0) == 9s); - EXPECT(sharing_from("0") == Sharing::per_thread && sharing_from(" reserve ") == Sharing::reserve); - // make.rs a_pipeline_held_too_long_is_not_waited_for. - const Clock::duration base = 500ms; - EXPECT(!held_too_long(10s, true, base) && held_too_long(10001ms, true, base)); - EXPECT(!held_too_long(3s, false, base) && held_too_long(3001ms, false, base)); - EXPECT(!held_too_long(60s, true, 12s) && !held_too_long(60s, false, 12s)); - EXPECT(held_too_long(60s, true, 5s) && !held_too_long(60s, false, 5s)); - return 0; -} - -std::shared_ptr job(std::vector& order, std::mutex& mutex, int id, bool depth_only = false) { - auto j = std::make_shared(false, depth_only); - j->set_work([&order, &mutex, id] { - std::lock_guard lock(mutex); - order.push_back(id); - return id >= 0; - }); - return j; -} - -// make.rs draws_promote_early_pipelines_without_claiming_them_twice and early_depth_precedes_other_prewarming: a -// request goes first, then early depth-only pipelines, then the other early ones, and a promoted early job runs once. -int queue_order() { - Builder& builder = Builder::get(); - builder.hold(true); - std::vector order; - std::mutex mutex; - const auto early = job(order, mutex, 1), promoted = job(order, mutex, 2), depth = job(order, mutex, 3, true); - const auto requested = job(order, mutex, 4), refused = job(order, mutex, -5), retired = job(order, mutex, 6); - const BuilderStats before = builder.stats(); - builder.start(early, kEarly); - builder.start(promoted, kEarly); - builder.start(depth, kEarly); - builder.start(retired, kEarly); - builder.start(requested, kRequested); - builder.start(promoted, kRequested); // promoted: queued again as a request, still made once - builder.start(refused, kRequested); - EXPECT(early->queue_state() == kEarly && promoted->queue_state() == kRequested); - retired->retire(); // its pipeline state went away while it was queued: never run - EXPECT(builder.stats().started_early == before.started_early + 4); - if (builder.stats().waiting == before.waiting) { - // LEONIDA_PIPELINE_WORKERS=0: everything ran when started; the order is the starts'. - builder.hold(false); - return 0; - } - builder.hold(false); - for (const auto& j : {early, promoted, depth, requested, refused}) EXPECT(j->wait_finished_for(10s)); - EXPECT(!retired->finished()); - std::lock_guard lock(mutex); - // Workers run in parallel: the order is the order they were taken in only per worker. With one worker it is exact; - // with more, each job still ran exactly once. - EXPECT(order.size() == 5); - for (int id : {1, 2, 3, 4, -5}) EXPECT(std::count(order.begin(), order.end(), id) == 1); - if (worker_count() == 1) EXPECT((order == std::vector{4, 2, -5, 3, 1})); - EXPECT(early->ready() && !refused->ready() && refused->finished()); - return 0; -} - -// The budget: before the first frame a bind waits however long the build takes; after, at most the frame's window, -// then nothing in that frame, and a new frame has a new window. -int budget() { - Builder& builder = Builder::get(); - std::vector order; - std::mutex mutex; - const auto slow = std::make_shared(false, false); - slow->set_work([] { - std::this_thread::sleep_for(100ms); - return true; - }); - EXPECT(current_frame() == 0); - builder.start(slow, kRequested); - EXPECT(builder.wait(*slow) && slow->ready()); // no frame yet: as long as it takes - - begin_frame(); - set_loading_allowance(0s); // the frame budget alone - set_wait_budget(60ms); - builder.hold(true); - const auto held = job(order, mutex, 7); - builder.start(held, kRequested); - Clock::time_point t = Clock::now(); - EXPECT(!builder.wait(*held)); - const auto first = Clock::now() - t; - t = Clock::now(); - EXPECT(!builder.wait(*held)); - const auto second = Clock::now() - t; - begin_frame(); - t = Clock::now(); - EXPECT(!builder.wait(*held)); - const auto third = Clock::now() - t; - std::printf("pipeline_queue_test: waits of %.0f, %.0f and %.0f ms for a held pipeline (budget 60 ms per frame)\n", - std::chrono::duration(first).count(), - std::chrono::duration(second).count(), - std::chrono::duration(third).count()); - EXPECT(first >= 50ms && first < 1s); - EXPECT(second < 20ms); - EXPECT(third >= 50ms && third < 1s); - builder.hold(false); - EXPECT(held->wait_finished_for(10s) && held->ready()); - EXPECT(builder.wait(*held)); - - // Drops are counted by whether the pipeline is still being made. - const DropCounts before = Drops::get().counts(); - const auto pending = std::make_shared(true, false); - Drops::get().note(*pending, true, 1); - Drops::get().note(*held, false, 0); // made: counted as refused only when finished without a pipeline - const DropCounts after = Drops::get().counts(); - EXPECT(after.dispatches == before.dispatches + 1); - EXPECT(after.refused == before.refused + 1); - return 0; -} - -// The early list: written as sorted lines, the keys of earlier runs kept, read back as the next run reads it. -// LEONIDA_PIPELINE_WAIT_MS stays under the title's 30 s hang watchdog. -int budget_cap() { - EXPECT(wait_budget_from_env(0) == 0); - EXPECT(wait_budget_from_env(kDefaultWaitMs) == kDefaultWaitMs); - EXPECT(wait_budget_from_env(kMaxWaitMs) == kMaxWaitMs); - EXPECT(wait_budget_from_env(600000) == kMaxWaitMs); - EXPECT(kMaxWaitMs * 2 < 30000); - // The loading allowance (VIctory make.rs:213-219): a short frame budget grows to 4 s (graphics) or 12 s (compute) - // while the run's allowance lasts, and back to the budget once it is spent. - EXPECT(frame_budget(500ms, false, 120s, 0s) == 4s); - EXPECT(frame_budget(500ms, true, 120s, 0s) == 12s); - EXPECT(frame_budget(500ms, true, 120s, 115s) == 5s); - EXPECT(frame_budget(500ms, true, 120s, 120s) == 500ms); - EXPECT(frame_budget(12s, false, 120s, 0s) == 12s); - EXPECT(frame_budget(500ms, false, 0s, 0s) == 500ms); - return 0; -} - -int early_list() { - const testfiles::ScratchDir scratch("leonida_pipeline_queue_test"); - const std::filesystem::path file = scratch.path() / "early-pipelines.txt"; - { - std::ofstream out(file, std::ios::binary); - out << "from-an-earlier-run\r\n\n"; - } - EarlyList& list = EarlyList::get(); - list.configure(file, true, true); - EXPECT(list.wanted("from-an-earlier-run")); - EXPECT(!list.wanted("b")); - list.note_used("b"); - list.note_used("a"); - list.note_used("a"); - list.note_used(""); - EXPECT(list.size() == 3); - const std::uint64_t saves = list.saves(); - EXPECT(list.save(true) && list.saves() == saves + 1); - EXPECT(!list.save(true)); // nothing changed since - std::stringstream text; - { - std::ifstream in(file, std::ios::binary); // closed before the next save renames over the file - text << in.rdbuf(); - } - EXPECT(text.str() == "a\nb\nfrom-an-earlier-run\n"); - EXPECT(!std::filesystem::exists(file.string() + ".tmp")); - list.reload(); - EXPECT(list.size() == 3 && list.wanted("a") && list.wanted("b")); - list.note_used("c"); - EXPECT(!list.save(false)); // within 20 s of the last save - EXPECT(list.save(true)); - // Without `always`, nothing is written before the first frame; this process has begun frames by now. - list.configure(scratch.path() / "other.txt", false, true); - list.note_used("d"); - EXPECT(current_frame() > 0 && list.save(true) && std::filesystem::exists(scratch.path() / "other.txt")); - list.configure({}, false, true); - return 0; -} - -} // namespace - -int main() { - if (frame_window() || queue_order() || budget() || budget_cap() || early_list()) return 1; - std::printf("pipeline_queue_test: ok\n"); - return 0; -} diff --git a/runtime/test/predication_barrier_test.cpp b/runtime/test/predication_barrier_test.cpp deleted file mode 100644 index 5f22d1aff..000000000 --- a/runtime/test/predication_barrier_test.cpp +++ /dev/null @@ -1,67 +0,0 @@ -// detail::outside_predication (ReplayFunctions::barriers_outside_predication, NVIDIA's driver and barriers inside a -// conditional rendering scope): with the flag set and a scope open on the command buffer, a barrier is recorded between -// an end and a begin of that scope; otherwise it is recorded as it is. Fake Vulkan entry points, no GPU. - -#include "../src/vulkan_replay.h" - -#include -#include - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "predication_barrier_test line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -namespace { - -std::string calls; -const VkConditionalRenderingBeginInfoEXT* begun_with = nullptr; - -VKAPI_ATTR void VKAPI_CALL fake_barrier(VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags, - uint32_t, const VkMemoryBarrier*, uint32_t, const VkBufferMemoryBarrier*, - uint32_t, const VkImageMemoryBarrier*) { - calls += "B"; -} -VKAPI_ATTR void VKAPI_CALL fake_end(VkCommandBuffer) { calls += "E"; } -VKAPI_ATTR void VKAPI_CALL fake_begin(VkCommandBuffer, const VkConditionalRenderingBeginInfoEXT* info) { - calls += "C"; - begun_with = info; -} - -leonida::ReplayFunctions functions(bool outside) { - leonida::ReplayFunctions vk{}; - vk.pipeline_barrier = fake_barrier; - vk.begin_conditional_rendering = fake_begin; - vk.end_conditional_rendering = fake_end; - vk.barriers_outside_predication = outside; - return vk; -} - -VkCommandBuffer handle(std::uintptr_t n) { return reinterpret_cast(n); } - -int run(bool outside, bool open, VkCommandBuffer recorded_on, const char* want) { - calls.clear(); - begun_with = nullptr; - const leonida::ReplayFunctions vk = functions(outside); - VkConditionalRenderingBeginInfoEXT info{VK_STRUCTURE_TYPE_CONDITIONAL_RENDERING_BEGIN_INFO_EXT}; - info.buffer = open ? reinterpret_cast(std::uintptr_t{0x10}) : VK_NULL_HANDLE; - const leonida::detail::ActivePredicate active{handle(1), &info}; - leonida::detail::active_predicate = &active; - leonida::detail::memory_barrier(vk, recorded_on, VK_ACCESS_SHADER_WRITE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); - leonida::detail::active_predicate = nullptr; - EXPECT(calls == want); - if (calls == "EBC") EXPECT(begun_with == &info); // the same predicate begins again - return 0; -} - -} // namespace - -int main() { - if (run(true, true, handle(1), "EBC") || // NVIDIA, a scope open: the barrier goes outside it - run(false, true, handle(1), "B") || // another driver: as it is - run(true, false, handle(1), "B") || // no predicate set - run(true, true, handle(2), "B")) // the scope is another command buffer's - return 1; - std::printf("predication_barrier_test: ok\n"); - return 0; -} diff --git a/runtime/test/present_window_parts_test.cpp b/runtime/test/present_window_parts_test.cpp deleted file mode 100644 index ecf57f3ac..000000000 --- a/runtime/test/present_window_parts_test.cpp +++ /dev/null @@ -1,255 +0,0 @@ -// The title window's pieces that need no window and no GPU: the PNG writer of the screenshots (src/png_write.h), -// checked by decoding its files with the runtime's own inflate (src/shader_library.h) and undoing the row filters; the -// caption's figures (src/frame_meter.h) on made-up present times; and LEONIDA_DISPLAY_MODE's parser -// (src/display_mode.h). Hand-made data only. -#include "../src/display_mode.h" -#include "../src/display_profile.h" -#include "../src/frame_meter.h" -#include "../src/png_write.h" -#include "../src/shader_library.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace { - -int failures = 0; - -void check(bool ok, const char* what) { - if (!ok) { - ++failures; - std::fprintf(stderr, "FAIL: %s\n", what); - } -} - -std::uint32_t be32(const std::uint8_t* p) { - return std::uint32_t(p[0]) << 24 | std::uint32_t(p[1]) << 16 | std::uint32_t(p[2]) << 8 | p[3]; -} - -// A PNG of colour type 2 back to RGB rows; false when a chunk, its CRC, the stream or a filter is wrong. -bool decode_rgb8(const std::vector& png, std::uint32_t* width, std::uint32_t* height, - std::vector* rgb) { - static const std::uint8_t signature[8] = {0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'}; - if (png.size() < 8 || std::memcmp(png.data(), signature, 8) != 0) return false; - std::vector idat; - bool header = false, end = false; - for (std::size_t at = 8; at + 12 <= png.size() && !end;) { - const std::uint32_t length = be32(&png[at]); - if (at + 12 + length > png.size()) return false; - const std::uint8_t* kind = &png[at + 4]; - const std::uint8_t* data = &png[at + 8]; - if (leonida::png::crc32({kind, length + 4}) != be32(data + length)) return false; - if (!std::memcmp(kind, "IHDR", 4)) { - if (length != 13 || data[8] != 8 || data[9] != 2 || data[10] || data[11] || data[12]) return false; - *width = be32(data); - *height = be32(data + 4); - header = true; - } else if (!std::memcmp(kind, "IDAT", 4)) { - idat.insert(idat.end(), data, data + length); - } else if (!std::memcmp(kind, "IEND", 4)) { - end = true; - } - at += 12 + length; - } - if (!header || !end) return false; - std::vector raw; - if (!leonida::zlib_inflate(idat, raw)) return false; - const std::size_t row = std::size_t(*width) * 3; - if (raw.size() != (row + 1) * *height) return false; - rgb->assign(row * *height, 0); - for (std::uint32_t y = 0; y < *height; ++y) { - const std::uint8_t filter = raw[y * (row + 1)]; - const std::uint8_t* in = &raw[y * (row + 1) + 1]; - std::uint8_t* out = &(*rgb)[y * row]; - const std::uint8_t* up = y ? &(*rgb)[(y - 1) * row] : nullptr; - for (std::size_t i = 0; i < row; ++i) { - const int a = i >= 3 ? out[i - 3] : 0, b = up ? up[i] : 0, c = up && i >= 3 ? up[i - 3] : 0; - int predicted = 0; - switch (filter) { - case 0: break; - case 1: predicted = a; break; - case 2: predicted = b; break; - case 3: predicted = (a + b) / 2; break; - case 4: { - const int p = a + b - c, pa = std::abs(p - a), pb = std::abs(p - b), pc = std::abs(p - c); - predicted = pa <= pb && pa <= pc ? a : pb <= pc ? b : c; - break; - } - default: return false; - } - out[i] = std::uint8_t(in[i] + predicted); - } - } - return true; -} - -void png_tests() { - const char* digits = "123456789"; - check(leonida::png::crc32({reinterpret_cast(digits), 9}) == 0xcbf43926u, "CRC-32 check value"); - const char* wiki = "Wikipedia"; - check(leonida::png::adler32({reinterpret_cast(wiki), 9}) == 0x11e60398u, "Adler-32 of Wikipedia"); - - // Deflate round trips: empty, tiny, runs longer than 258, repeats further back than the window, noise. - std::uint32_t seed = 12345; - const auto next = [&seed] { return seed = seed * 1664525u + 1013904223u; }; - std::vector> inputs(6); - inputs[1] = {7}; - inputs[2] = {1, 2, 3, 1, 2, 3, 1, 2, 3, 1}; - inputs[3].assign(100000, 0x42); - for (int i = 0; i < 70000; ++i) inputs[4].push_back(std::uint8_t((i % 50000) * 7 % 251)); - for (int i = 0; i < 50000; ++i) inputs[5].push_back(std::uint8_t(next() >> 24)); - for (const auto& input : inputs) { - const std::vector stream = leonida::png::zlib_compress(input); - std::vector back; - check(leonida::zlib_inflate(stream, back) && back == input, "zlib round trip"); - } - check(leonida::png::zlib_compress(inputs[3]).size() < 2000, "a run of 100000 bytes compresses"); - - // An image with flat regions, gradients and noise, at an odd width. - const std::uint32_t width = 333, height = 77; - std::vector image(std::size_t(width) * height * 3); - for (std::uint32_t y = 0; y < height; ++y) - for (std::uint32_t x = 0; x < width; ++x) { - std::uint8_t* p = &image[(std::size_t(y) * width + x) * 3]; - if (x < width / 3) { - p[0] = 64, p[1] = 128, p[2] = 191; - } else if (x < 2 * width / 3) { - p[0] = std::uint8_t(x), p[1] = std::uint8_t(y * 3), p[2] = std::uint8_t(x + y); - } else { - const std::uint32_t r = next(); - p[0] = std::uint8_t(r), p[1] = std::uint8_t(r >> 8), p[2] = std::uint8_t(r >> 16); - } - } - const std::vector png = leonida::png::encode_rgb8(width, height, image.data(), std::size_t(width) * 3); - std::uint32_t w = 0, h = 0; - std::vector decoded; - check(decode_rgb8(png, &w, &h, &decoded), "the PNG decodes"); - check(w == width && h == height && decoded == image, "the PNG holds the image"); - // A pitch wider than the row: only the row's bytes are read. - std::vector padded(std::size_t(width * 3 + 5) * height, 0xee); - for (std::uint32_t y = 0; y < height; ++y) - std::memcpy(&padded[std::size_t(y) * (width * 3 + 5)], &image[std::size_t(y) * width * 3], width * 3); - check(leonida::png::encode_rgb8(width, height, padded.data(), width * 3 + 5) == png, "the pitch is honoured"); - check(leonida::png::encode_rgb8(0, 10, image.data(), 0).empty(), "an empty image gives no file"); -} - -void meter_tests() { - constexpr std::uint64_t ms = 1'000'000; - { - leonida::FrameMeter meter; - leonida::FrameRateSampler sampler; - leonida::FrameFigures f; - check(!sampler.sample(meter.read(), 1000 * ms, &f), "no figure before a frame"); - for (int i = 0; i <= 60; ++i) meter.presented(std::uint64_t(1000.0 * ms + i * 16.6667 * ms)); - check(sampler.sample(meter.read(), 2010 * ms, &f), "a figure after a second of frames"); - check(std::fabs(f.fps - 60.0) < 0.1 && std::fabs(f.ms - 16.667) < 0.01, "60 frames a second"); - check(leonida::caption_text(f) == "Leonida | 60 fps 16.7 ms/frame", "the caption's words"); - // No frame for three seconds: the wait shows once it is longer than a frame. - check(sampler.sample(meter.read(), 2010 * ms, &f) && std::fabs(f.fps - 60.0) < 0.1, "a short wait keeps them"); - check(sampler.sample(meter.read(), 5000 * ms, &f) && f.fps < 1.0 && std::fabs(f.ms - 3000.0) < 1.0, - "a long wait is shown"); - check(leonida::caption_text(f) == "Leonida | 0 fps 3000.0 ms/frame", "the wait's caption"); - // The frame that ends the wait counts its whole time. - meter.presented(5200 * ms); - check(sampler.sample(meter.read(), 5300 * ms, &f) && std::fabs(f.ms - 3200.0) < 1.0, "the long frame"); - } - { - // Slow frames (V host.rs's test: about 1 fps): each sample spans whole frames. - leonida::FrameMeter meter; - leonida::FrameRateSampler sampler; - leonida::FrameFigures f; - meter.presented(0 + 1); - check(!sampler.sample(meter.read(), 500 * ms, &f), "one frame, half a second: nothing yet"); - meter.presented(953 * ms); - check(sampler.sample(meter.read(), 1000 * ms, &f) && std::fabs(f.ms - 953.0) < 0.01, "953 ms a frame"); - check(leonida::caption_text(f) == "Leonida | 1 fps 953.0 ms/frame", "about one frame a second"); - } -} - -void display_mode_tests() { - leonida::DisplayMode m; - check(m.width == 3840 && m.height == 2160 && m.refresh_hz == 60, "the default is VIctory's: 3840x2160 at 60 Hz"); - check(leonida::parse_display_mode("1920x1080", &m) && m.width == 1920 && m.height == 1080, "1920x1080"); - check(leonida::parse_display_mode(" 2560 X 1440 \r\n", &m) && m.width == 2560 && m.height == 1440, "spaces and X"); - check(leonida::parse_display_mode("640x360", &m) && leonida::parse_display_mode("7680x4320", &m), "the bounds"); - const char* refused[] = {"", "1920", "x1080", "1920x", "1920x1080x", "639x360", "640x359", "7681x4320", - "7680x4321", "abcxdef", "-1920x1080", "123456x1080", "1920 1080", "1920x10 80"}; - m = {}; - for (const char* text : refused) { - const bool parsed = leonida::parse_display_mode(text, &m); - if (parsed) std::fprintf(stderr, "parsed: '%s'\n", text); - check(!parsed, "a value outside the rules is refused"); - } - check(m.width == 3840 && m.height == 2160, "a refused value leaves the mode alone"); -} - -// The display profile on a sparse stand-in for the image: the bytes VIctory's native_1440p.rs expects at each place. -void display_profile_tests() { - namespace dp = leonida::display_profile; - check(dp::scanout_pool_bytes(3840, 2160) == 0x04000000u, "the formula gives the stock reservation for 3840x2160"); - check(dp::scanout_pool_bytes(2560, 1440) == 0x01e00000u, "and 30 MiB for 2560x1440"); - check(dp::plan(leonida::DisplayMode{}).patches.empty() && !dp::plan(leonida::DisplayMode{}).refused, - "the stock mode changes nothing"); - leonida::DisplayMode fhd; - fhd.width = 1920; - fhd.height = 1080; - check(dp::plan(fhd).patches.empty() && dp::plan(fhd).refused, "an output VIctory has not checked is refused"); - check(dp::plan(leonida::DisplayMode{}, 0.5f).patches.empty() && dp::plan(leonida::DisplayMode{}, 0.5f).refused, - "a render scale without the 1440p output is refused"); - - std::map> image; - image[dp::kSdrModeRva] = {0, 15, 0, 0, 112, 8, 0, 0, 60, 0, 0, 0, 1, 0, 0, 0}; - image[dp::kScanoutReservationRva] = {0xb9, 0, 0, 0, 4}; - const float two_thirds = 2.0f / 3.0f; - image[dp::kSceneScaleRva].resize(4); - std::memcpy(image[dp::kSceneScaleRva].data(), &two_thirds, 4); - image[dp::kSettingsViewportLoadRva] = {0xc5, 0xfb, 0x10, 0x0d, 0x10, 0xf0, 0x13, 0x05}; - const auto at = [&image](std::uint32_t rva, std::size_t length) -> std::uint8_t* { - const auto found = image.find(rva); - return found != image.end() && found->second.size() >= length ? found->second.data() : nullptr; - }; - std::string error; - leonida::DisplayMode qhd; - qhd.width = 2560; - qhd.height = 1440; - const dp::Plan plan = dp::plan(qhd); - check(plan.render_width == 2560 && plan.render_height == 1440 && plan.scale == 1.0f, "1440p renders at 1440p"); - check(dp::apply(at, plan, &error), "the profile applies to the stock bytes"); - check(image[dp::kSdrModeRva] == std::vector{0, 10, 0, 0, 160, 5, 0, 0, 60, 0, 0, 0, 1, 0, 0, 0}, - "the SDR mode is 2560x1440 at 60 Hz"); - check(image[dp::kScanoutReservationRva] == std::vector{0xb9, 0, 0, 0xe0, 1}, "30 MiB reserved"); - float scale = 0; - std::memcpy(&scale, image[dp::kSceneScaleRva].data(), 4); - check(scale == 1.0f, "the scene scale is 1"); - std::int32_t displacement = 0; - std::memcpy(&displacement, image[dp::kSettingsViewportLoadRva].data() + 4, 4); - check(std::int64_t(dp::kSettingsViewportLoadRva) + 8 + displacement == dp::kSdrModeRva, - "the Settings viewport reads the SDR mode"); - // V: 1080p rendering inside the 1440p output is a scale of 0.75. - const dp::Plan p1080 = dp::plan(qhd, 0.75f); - check(p1080.render_width == 1920 && p1080.render_height == 1080, "0.75 of 1440p renders 1080p"); - // Patched once, the bytes are not stock any more: a second pass (another build, in effect) writes nothing. - const auto before = image; - check(!dp::apply(at, p1080, &error) && image == before && !error.empty(), "other bytes are left alone"); -} - -} // namespace - -int main() { - png_tests(); - meter_tests(); - display_mode_tests(); - display_profile_tests(); - if (failures) { - std::fprintf(stderr, "present_window_parts_test: %d failure(s)\n", failures); - return 1; - } - std::printf("present_window_parts_test: OK\n"); - return 0; -} diff --git a/runtime/test/process_cmdline_test.cpp b/runtime/test/process_cmdline_test.cpp index a550910b9..bf55821d1 100644 --- a/runtime/test/process_cmdline_test.cpp +++ b/runtime/test/process_cmdline_test.cpp @@ -439,23 +439,6 @@ int main() { SetProcessAffinityMask(GetCurrentProcess(), process_mask); } - // The title's debug output is served (and logged as "[title] ..."); TerminateProcess is served by the shim too. - { - using DebugA = void(WINAPI*)(LPCSTR); - using DebugW = void(WINAPI*)(LPCWSTR); - const auto debug_a = reinterpret_cast(rt::shims::find("kernelbase.dll", "OutputDebugStringA")); - const auto debug_w = - reinterpret_cast(rt::shims::find("api-ms-win-core-debug-l1-1-0.dll", "OutputDebugStringW")); - if (!debug_a || !debug_w || !rt::shims::find("kernel32.dll", "TerminateProcess")) { - std::fprintf(stderr, "FAIL OutputDebugStringA/W and TerminateProcess are not served\n"); - ++failures; - } else { - debug_a("process_cmdline: a narrow debug line\n"); - debug_w(L"process_cmdline: a wide debug line Δ"); - debug_a(nullptr); - } - } - if (failures) return 1; std::printf("process_cmdline: GetCommandLineW parses back to __wargv, non-ASCII arguments intact (code page %u); " "the WinMain line and the kernelbase/API-set names are the game's\n", diff --git a/runtime/test/rect_list_gs_tool.cpp b/runtime/test/rect_list_gs_tool.cpp deleted file mode 100644 index fce14d37c..000000000 --- a/runtime/test/rect_list_gs_tool.cpp +++ /dev/null @@ -1,61 +0,0 @@ -// The rectangle-list geometry stage generator (src/rect_list_gs.h) as a command, for tests/test_rect_list_gs.py: -// -// rect_list_gs_tool [ ...] -// -// Each vertex shader's stage is made through the same cached call the D3D12 layer uses (geometry_shader) and written -// to the file after it. One line per pair on stdout: " ", so a -// caller sees which pairs the cache served the same words. A refused vertex shader prints -// " refused: " and ends the run with exit code 2; a file that cannot be read or written, 1. -// No GPU, no Vulkan loader, no game data. -#include "../src/rect_list_gs.h" - -#include -#include -#include -#include -#include -#include -#include - -int main(int argc, char** argv) { - if (argc < 3 || (argc - 1) % 2) { - std::fprintf(stderr, "usage: rect_list_gs_tool [ ...]\n"); - return 1; - } - std::vector>> made; - for (int pair = 0; 2 * pair + 2 <= argc; ++pair) { - const char* vs_path = argv[1 + 2 * pair]; - const char* gs_path = argv[2 + 2 * pair]; - std::ifstream in(vs_path, std::ios::binary); - if (!in) { - std::fprintf(stderr, "%s: cannot be read\n", vs_path); - return 1; - } - const std::vector bytes{std::istreambuf_iterator(in), std::istreambuf_iterator()}; - std::vector vs(bytes.size() / 4); - if (!vs.empty()) std::memcpy(vs.data(), bytes.data(), vs.size() * 4); - std::string why; - leonida::rect_list::Signature signature; - const bool read = leonida::rect_list::read_signature(vs, signature, why); - const auto words = read ? leonida::rect_list::geometry_shader(vs, why) : nullptr; - if (!words) { - std::printf("%d refused: %s\n", pair, why.c_str()); - return 2; - } - int first = int(made.size()); - for (int i = 0; i < int(made.size()); ++i) - if (made[i] == words) { - first = i; - break; - } - made.push_back(words); - std::ofstream out(gs_path, std::ios::binary); - out.write(reinterpret_cast(words->data()), std::streamsize(words->size() * 4)); - if (!out) { - std::fprintf(stderr, "%s: cannot be written\n", gs_path); - return 1; - } - std::printf("%d %d %s\n", pair, first, signature.key().c_str()); - } - return 0; -} diff --git a/runtime/test/registry_oem_test.cpp b/runtime/test/registry_oem_test.cpp deleted file mode 100644 index e73390852..000000000 --- a/runtime/test/registry_oem_test.cpp +++ /dev/null @@ -1,83 +0,0 @@ -// registry_oem.cpp: the console model the title reads from HKLM\...\OEM\ConsoleMode, through the shim table as the -// loader binds it. CPU only; the real registry is only read for a key that is not ours. -#include "shims.h" - -#include - -#include -#include - -namespace { - -int failures = 0; - -void check(bool ok, const char* what) { - if (!ok) { - std::fprintf(stderr, "FAIL: %s\n", what); - ++failures; - } -} - -template -F shim(const char* name) { - return reinterpret_cast(rt::shims::find("advapi32.dll", name)); -} - -} // namespace - -int main() { - auto open = shim("RegOpenKeyW"); - auto open_ex = shim("RegOpenKeyExW"); - auto query = shim("RegQueryValueExW"); - auto close = shim("RegCloseKey"); - check(open && open_ex && query && close, "all four registry shims are registered"); - if (failures) return 1; - - const wchar_t* path = L"Software\\Microsoft\\Windows NT\\CurrentVersion\\OEM"; - HKEY key = nullptr; - check(open(HKEY_LOCAL_MACHINE, path, &key) == ERROR_SUCCESS && key, "the OEM key opens"); - - DWORD kind = 0, size = sizeof(DWORD), mode = 0; - check(query(key, L"ConsoleMode", nullptr, &kind, reinterpret_cast(&mode), &size) == ERROR_SUCCESS, - "ConsoleMode reads"); - check(kind == REG_DWORD && size == 4 && mode == 0x64, "Series X is 0x64, a DWORD"); - - size = 0; - check(query(key, L"ConsoleMode", nullptr, nullptr, nullptr, &size) == ERROR_SUCCESS && size == 4, - "a size query gives 4 bytes"); - size = 2; - check(query(key, L"ConsoleMode", nullptr, nullptr, reinterpret_cast(&mode), &size) == ERROR_MORE_DATA && - size == 4, - "a short buffer gets ERROR_MORE_DATA and the size"); - check(query(key, L"Other", nullptr, nullptr, nullptr, &size) == ERROR_FILE_NOT_FOUND, "other values are absent"); - - HKEY sub = nullptr; - check(open(key, L"Sub", &sub) == ERROR_FILE_NOT_FOUND, "the OEM key has no subkeys"); - - HKEY key_ex = nullptr; - check(open_ex(HKEY_LOCAL_MACHINE, L"software\\microsoft\\windows nt\\currentversion\\oem", 0, KEY_READ, - &key_ex) == ERROR_SUCCESS && - key_ex == key, - "RegOpenKeyExW opens it too, ignoring case"); - check(close(key) == ERROR_SUCCESS, "the OEM key closes"); - - _putenv_s("LEONIDA_DEVICE_TYPE", "6"); - size = sizeof(DWORD); - check(query(key, L"ConsoleMode", nullptr, nullptr, reinterpret_cast(&mode), &size) == ERROR_SUCCESS && - mode == 0x60, - "LEONIDA_DEVICE_TYPE=6 reads as Series S (0x60)"); - _putenv_s("LEONIDA_DEVICE_TYPE", ""); - - // A key that is not ours reaches the host registry. - HKEY host = nullptr; - check(open(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows NT\\CurrentVersion", &host) == ERROR_SUCCESS && - host && host != key, - "other keys open on the host"); - if (host) check(close(host) == ERROR_SUCCESS, "a host key closes on the host"); - - check(!rt::shims::owns_dll("advapi32.dll"), "advapi32.dll stays a host module for LoadLibrary"); - - if (failures) return 1; - std::printf("registry_oem: all checks passed\n"); - return 0; -} diff --git a/runtime/test/spirv_output_splat_test.cpp b/runtime/test/spirv_output_splat_test.cpp deleted file mode 100644 index 41dbb4b60..000000000 --- a/runtime/test/spirv_output_splat_test.cpp +++ /dev/null @@ -1,117 +0,0 @@ -// leonida::splat_output_alpha (src/spirv_output_splat.h) over hand-built SPIR-V: a fragment output at a Location gets -// each store's value as .wwww (an A8_UNORM target drawn into an R8 attachment), other outputs are left alone, and a -// module without a four-component output there is refused. No Vulkan, no GPU, no shader files. -#include "../src/spirv_output_splat.h" - -#include -#include -#include -#include - -namespace { - -int failures = 0; - -void check(bool ok, const char* what) { - if (!ok) { - std::fprintf(stderr, "spirv_output_splat_test: FAILED: %s\n", what); - ++failures; - } -} - -using Words = std::vector; - -void inst(Words& words, std::uint16_t op, std::initializer_list operands) { - words.push_back((static_cast(operands.size() + 1) << 16) | op); - words.insert(words.end(), operands); -} - -// Opcodes and enumerants, from the SPIR-V specification. -constexpr std::uint16_t op_type_void = 19, op_type_float = 22, op_type_vector = 23, op_type_pointer = 32, - op_type_function = 33, op_constant = 43, op_constant_composite = 44, op_function = 54, - op_function_end = 56, op_variable = 59, op_load = 61, op_store = 62, op_decorate = 71, - op_vector_shuffle = 79, op_label = 248, op_return = 253; -constexpr std::uint32_t decoration_location = 30, class_output = 3; - -// Two vec4 outputs (Location 0 and 1), each stored once; Location 0 is also loaded and stored again, as the -// translator keeps an earlier export. Ids: 1 void, 2 float, 3 vec4, 4 pointer, 5 fn type, 6/7 outputs, 8 one, -// 9 vec4 constant, 10 function, 11 label, 12 load. -Words module(std::uint32_t second_location = 1) { - Words w = {0x07230203, 0x00010600, 0, 13, 0}; - inst(w, op_decorate, {6, decoration_location, 0}); - inst(w, op_decorate, {7, decoration_location, second_location}); - inst(w, op_type_void, {1}); - inst(w, op_type_float, {2, 32}); - inst(w, op_type_vector, {3, 2, 4}); - inst(w, op_type_pointer, {4, class_output, 3}); - inst(w, op_type_function, {5, 1}); - inst(w, op_variable, {4, 6, class_output}); - inst(w, op_variable, {4, 7, class_output}); - inst(w, op_constant, {2, 8, 0x3f800000}); - inst(w, op_constant_composite, {3, 9, 8, 8, 8, 8}); - inst(w, op_function, {1, 10, 0, 5}); - inst(w, op_label, {11}); - inst(w, op_store, {6, 9}); - inst(w, op_store, {7, 9}); - inst(w, op_load, {3, 12, 6}); - inst(w, op_store, {6, 12}); - inst(w, op_return, {}); - inst(w, op_function_end, {}); - return w; -} - -struct Store { - std::uint32_t pointer, value; -}; - -// The stores of a module, and the shuffles that make each value (result id -> its components and source). -void scan(const Words& w, std::vector& stores, std::vector& shuffles) { - for (std::size_t at = 5; at < w.size();) { - const std::uint32_t count = w[at] >> 16; - const std::uint16_t op = w[at] & 0xffff; - if (op == op_store) stores.push_back({w[at + 1], w[at + 2]}); - if (op == op_vector_shuffle) shuffles.push_back(Words(w.begin() + std::ptrdiff_t(at), w.begin() + std::ptrdiff_t(at + count))); - at += count; - } -} - -} // namespace - -int main() { - { - std::string why; - const Words out = leonida::splat_output_alpha(module(), 0, why); - check(!out.empty(), "a vec4 output at Location 0 is patched"); - std::vector stores; - std::vector shuffles; - scan(out, stores, shuffles); - check(shuffles.size() == 2, "each store to Location 0 gets a shuffle (two stores)"); - check(stores.size() == 3, "the store count is unchanged"); - check(out[3] == 15, "the id bound grows by the shuffles"); - bool all_alpha = true; - for (const Words& s : shuffles) - all_alpha &= s.size() == 9 && s[1] == 3 && s[5] == 3 && s[6] == 3 && s[7] == 3 && s[8] == 3; - check(all_alpha, "the shuffles are vec4 .wwww of the stored value"); - bool location0_splatted = true, location1_unchanged = false; - for (const Store& s : stores) { - if (s.pointer == 6) location0_splatted &= s.value >= 13; - if (s.pointer == 7) location1_unchanged = s.value == 9; - } - check(location0_splatted, "Location 0's stores store the shuffles"); - check(location1_unchanged, "Location 1's store is left alone"); - } - { - std::string why; - check(leonida::splat_output_alpha(module(), 3, why).empty() && !why.empty(), - "no output at the Location: refused with a reason"); - } - { - std::string why; - Words broken = module(); - broken.back() = (100u << 16) | op_function_end; // runs past the end - check(leonida::splat_output_alpha(broken, 0, why).empty(), "a malformed module is refused"); - } - if (failures) return 1; - std::printf("spirv_output_splat_test: ok\n"); - return 0; -} diff --git a/runtime/test/vk_pipeline_paths.cpp b/runtime/test/vk_pipeline_paths.cpp deleted file mode 100644 index 14f6f846c..000000000 --- a/runtime/test/vk_pipeline_paths.cpp +++ /dev/null @@ -1,402 +0,0 @@ -// Measures what a pixel-shader pipeline costs to make by each Vulkan path the runtime could take: -// vk_pipeline_paths [count] -// The list file has one translated pixel shader per line: " " (the -// stub is the partner vk_pipeline_check pairs it with, from /stubs/). For each shader: -// monolithic vkCreateGraphicsPipelines, the runtime's path today (dynamic rendering, a stub VS), and the same -// again in this process (what a VkPipelineCache hit costs); -// library VK_EXT_graphics_pipeline_library: the fragment-shader library, the pre-rasterization library (the -// stub VS), vertex input and fragment output interfaces, then a link without and with link-time -// optimisation; -// object VK_EXT_shader_object: vkCreateShadersEXT of the pixel shader alone. -// Every path gets the module under its own entry-point name ("m" and six hex digits), so no path finds what another -// made, nor what an earlier run left in the driver's disk cache. One shader at a time, on one thread. No game data is -// written; the modules are read from the user's work folder. -#include "vulkan_loader.h" -#include "../src/spirv_words.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace { - -PFN_vkGetInstanceProcAddr gipa; -#define LOAD(name) auto name = reinterpret_cast(gdpa(dev, #name)) - -double now_ms() { - return std::chrono::duration(std::chrono::steady_clock::now().time_since_epoch()).count(); -} - -// The module with its entry point renamed to `entry` (7 characters, so the instruction keeps its length). -std::vector renamed(std::vector words, const char* entry) { - for (std::size_t at = 5; at < words.size();) { - const std::uint32_t op = words[at] & 0xffff, length = words[at] >> 16; - if (!length) break; - if (op == 15 && length >= 5) { // OpEntryPoint model id "main" ... - char name[8] = {}; - std::memcpy(name, &words[at + 3], 4); - if (std::strcmp(name, "main") == 0) { - std::memcpy(&words[at + 3], entry, 8); // 7 characters and the terminator: still two words - return words; - } - } - at += length; - } - return {}; -} - -struct Shader { - std::string name, stub; - std::uint32_t outputs = 1; - bool depth = false; -}; - -double median(std::vector v) { - if (v.empty()) return 0; - std::sort(v.begin(), v.end()); - return v[v.size() / 2]; -} - -} // namespace - -int main(int argc, char** argv) { - if (argc < 3) { - std::fprintf(stderr, "usage: vk_pipeline_paths [count]\n"); - return 2; - } - const std::string dir = argv[1]; - std::vector shaders; - { - std::ifstream list(argv[2]); - std::string line; - while (std::getline(list, line)) { - std::istringstream in(line); - Shader s; - int depth = 0; - if (in >> s.name >> s.outputs >> depth >> s.stub) { - s.depth = depth != 0; - shaders.push_back(s); - } - } - } - if (argc > 3) shaders.resize(std::min(shaders.size(), std::strtoul(argv[3], nullptr, 10))); - gipa = load_vulkan(); - if (!gipa) return 1; - auto vkCreateInstance = reinterpret_cast(gipa(nullptr, "vkCreateInstance")); - VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; - app.apiVersion = VK_API_VERSION_1_3; - VkInstanceCreateInfo ici{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; - ici.pApplicationInfo = &app; - VkInstance instance = VK_NULL_HANDLE; - if (vkCreateInstance(&ici, nullptr, &instance) != VK_SUCCESS) return 1; - auto vkEnumeratePhysicalDevices = - reinterpret_cast(gipa(instance, "vkEnumeratePhysicalDevices")); - auto vkGetPhysicalDeviceProperties = - reinterpret_cast(gipa(instance, "vkGetPhysicalDeviceProperties")); - auto vkGetPhysicalDeviceFeatures2 = - reinterpret_cast(gipa(instance, "vkGetPhysicalDeviceFeatures2")); - auto vkCreateDevice = reinterpret_cast(gipa(instance, "vkCreateDevice")); - auto gdpa = reinterpret_cast(gipa(instance, "vkGetDeviceProcAddr")); - std::uint32_t count = 0; - vkEnumeratePhysicalDevices(instance, &count, nullptr); - std::vector physicals(count); - vkEnumeratePhysicalDevices(instance, &count, physicals.data()); - VkPhysicalDevice physical = VK_NULL_HANDLE; - VkPhysicalDeviceProperties props{}; - for (VkPhysicalDevice p : physicals) { - vkGetPhysicalDeviceProperties(p, &props); - if (props.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) { - physical = p; - break; - } - } - if (!physical) return 1; - vkGetPhysicalDeviceProperties(physical, &props); - - // Every feature the device has, and the two extensions measured. - VkPhysicalDeviceShaderObjectFeaturesEXT object_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_OBJECT_FEATURES_EXT}; - VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT library_features{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_GRAPHICS_PIPELINE_LIBRARY_FEATURES_EXT, &object_features}; - VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR bary{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR, &library_features}; - VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT interlock{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_INTERLOCK_FEATURES_EXT, &bary}; - VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES, &interlock}; - VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &f13}; - VkPhysicalDeviceVulkan11Features f11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, &f12}; - VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &f11}; - vkGetPhysicalDeviceFeatures2(physical, &f2); - f2.features.robustBufferAccess = VK_FALSE; // as the runtime: no robustness checks in the code - f13.robustImageAccess = VK_FALSE; - const char* extensions[] = {VK_KHR_PIPELINE_LIBRARY_EXTENSION_NAME, VK_EXT_GRAPHICS_PIPELINE_LIBRARY_EXTENSION_NAME, - VK_EXT_SHADER_OBJECT_EXTENSION_NAME, VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME, - VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME}; - const float priority = 1.0f; - VkDeviceQueueCreateInfo qci{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; - qci.queueCount = 1; - qci.pQueuePriorities = &priority; - VkDeviceCreateInfo dci{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &f2}; - dci.queueCreateInfoCount = 1; - dci.pQueueCreateInfos = &qci; - dci.enabledExtensionCount = std::uint32_t(std::size(extensions)); - dci.ppEnabledExtensionNames = extensions; - VkDevice dev = VK_NULL_HANDLE; - if (vkCreateDevice(physical, &dci, nullptr, &dev) != VK_SUCCESS) { - std::fprintf(stderr, "no device with %s and %s\n", extensions[1], extensions[2]); - return 1; - } - std::printf("device: %s, driver %u.%u; graphicsPipelineLibrary %u, shaderObject %u\n", props.deviceName, - props.driverVersion >> 22, (props.driverVersion >> 14) & 0xff, library_features.graphicsPipelineLibrary, - object_features.shaderObject); - LOAD(vkCreateShaderModule); - LOAD(vkDestroyShaderModule); - LOAD(vkCreateDescriptorSetLayout); - LOAD(vkCreatePipelineLayout); - LOAD(vkCreateGraphicsPipelines); - LOAD(vkDestroyPipeline); - LOAD(vkCreatePipelineCache); - LOAD(vkCreateShadersEXT); - LOAD(vkDestroyShaderEXT); - - // The translator's set 0 (vk_pipeline_check.cpp, docs/design.md) and the 144-byte push constants. - std::vector b; - const auto add = [&](std::uint32_t bind, VkDescriptorType t, std::uint32_t n) { - b.push_back({bind, t, n, VK_SHADER_STAGE_ALL, nullptr}); - }; - add(0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 4096); add(1, VK_DESCRIPTOR_TYPE_SAMPLER, 1024); - add(2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1); add(3, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1024); - add(4, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1024); add(5, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256); - add(6, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256); add(7, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256); - for (std::uint32_t i = 8; i <= 19; i++) add(i, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256); - VkDescriptorSetLayoutCreateInfo dli{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; - dli.bindingCount = std::uint32_t(b.size()); - dli.pBindings = b.data(); - VkDescriptorSetLayout set0 = VK_NULL_HANDLE; - if (vkCreateDescriptorSetLayout(dev, &dli, nullptr, &set0) != VK_SUCCESS) return 1; - const VkPushConstantRange push{VK_SHADER_STAGE_ALL, 0, 144}; - VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; - pli.setLayoutCount = 1; - pli.pSetLayouts = &set0; - pli.pushConstantRangeCount = 1; - pli.pPushConstantRanges = &push; - VkPipelineLayout layout = VK_NULL_HANDLE; - if (vkCreatePipelineLayout(dev, &pli, nullptr, &layout) != VK_SUCCESS) return 1; - pli.flags = VK_PIPELINE_LAYOUT_CREATE_INDEPENDENT_SETS_BIT_EXT; - VkPipelineLayout library_layout = VK_NULL_HANDLE; - if (vkCreatePipelineLayout(dev, &pli, nullptr, &library_layout) != VK_SUCCESS) return 1; - VkPipelineCacheCreateInfo cci{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; - VkPipelineCache cache = VK_NULL_HANDLE; - vkCreatePipelineCache(dev, &cci, nullptr, &cache); - - std::mt19937 nonce_source(std::random_device{}()); - const auto entry_name = [&] { - static char name[8]; - std::snprintf(name, sizeof(name), "m%06x", unsigned(nonce_source() & 0xffffff)); - return std::string(name); - }; - const auto module_of = [&](const std::vector& words) { - VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - smi.codeSize = words.size() * 4; - smi.pCode = words.data(); - VkShaderModule m = VK_NULL_HANDLE; - vkCreateShaderModule(dev, &smi, nullptr, &m); - return m; - }; - const auto read = [&](const std::string& path) { - std::ifstream f(path, std::ios::binary | std::ios::ate); - return leonida::read_spirv_words(f, f.tellg()); - }; - - // State the runtime's pipelines have (PipelineState::build): dynamic viewport, scissor, topology, restart, - // stencil reference, blend constants. - static constexpr VkDynamicState dynamic_states[] = { - VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, VK_DYNAMIC_STATE_PRIMITIVE_TOPOLOGY, - VK_DYNAMIC_STATE_PRIMITIVE_RESTART_ENABLE, VK_DYNAMIC_STATE_STENCIL_REFERENCE, VK_DYNAMIC_STATE_BLEND_CONSTANTS}; - VkPipelineDynamicStateCreateInfo dynamic{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO}; - dynamic.dynamicStateCount = std::uint32_t(std::size(dynamic_states)); - dynamic.pDynamicStates = dynamic_states; - VkPipelineVertexInputStateCreateInfo vertex_input{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO}; - VkPipelineInputAssemblyStateCreateInfo assembly{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; - assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; - VkPipelineViewportStateCreateInfo viewport{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO}; - viewport.viewportCount = viewport.scissorCount = 1; - VkPipelineRasterizationStateCreateInfo raster{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO}; - raster.cullMode = VK_CULL_MODE_BACK_BIT; - raster.lineWidth = 1.0f; - VkPipelineMultisampleStateCreateInfo multisample{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO}; - multisample.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; - - std::vector mono, mono_hit, frag, pre, link_fast, link_lto, object; - std::size_t index = 0; - for (const Shader& s : shaders) { - ++index; - const std::vector ps = read(dir + "/" + s.name + ".spv"); - const std::vector vs = read(dir + "/stubs/" + s.stub); - if (ps.empty() || vs.empty()) continue; - std::vector colors(s.outputs, VK_FORMAT_R16G16B16A16_SFLOAT); - std::vector blends(s.outputs); - for (auto& a : blends) a.colorWriteMask = 0xf; - VkPipelineColorBlendStateCreateInfo blend{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}; - blend.attachmentCount = s.outputs; - blend.pAttachments = blends.data(); - VkPipelineDepthStencilStateCreateInfo depth{VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO}; - depth.depthTestEnable = depth.depthWriteEnable = VK_TRUE; - depth.depthCompareOp = VK_COMPARE_OP_GREATER_OR_EQUAL; - VkPipelineRenderingCreateInfo rendering{VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO}; - rendering.colorAttachmentCount = s.outputs; - rendering.pColorAttachmentFormats = colors.data(); - rendering.depthAttachmentFormat = VK_FORMAT_D32_SFLOAT; - const VkShaderModule vs_module = module_of(vs); - - // Monolithic, cold, then again. - std::string name = entry_name(); - std::vector words = renamed(ps, name.c_str()); - if (words.empty()) continue; - VkShaderModule ps_module = module_of(words); - VkPipelineShaderStageCreateInfo stages[2] = {{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}, - {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}}; - stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT; - stages[0].module = vs_module; - stages[0].pName = "main"; - stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; - stages[1].module = ps_module; - stages[1].pName = name.c_str(); - VkGraphicsPipelineCreateInfo full{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &rendering}; - full.stageCount = 2; - full.pStages = stages; - full.pVertexInputState = &vertex_input; - full.pInputAssemblyState = &assembly; - full.pViewportState = &viewport; - full.pRasterizationState = &raster; - full.pMultisampleState = &multisample; - full.pDepthStencilState = &depth; - full.pColorBlendState = &blend; - full.pDynamicState = &dynamic; - full.layout = layout; - VkPipeline pipeline = VK_NULL_HANDLE; - double t = now_ms(); - if (vkCreateGraphicsPipelines(dev, cache, 1, &full, nullptr, &pipeline) != VK_SUCCESS) { - std::printf("%s: monolithic refused; skipped\n", s.name.c_str()); - continue; - } - const double t_mono = now_ms() - t; - vkDestroyPipeline(dev, pipeline, nullptr); - t = now_ms(); - vkCreateGraphicsPipelines(dev, cache, 1, &full, nullptr, &pipeline); - const double t_hit = now_ms() - t; - vkDestroyPipeline(dev, pipeline, nullptr); - vkDestroyShaderModule(dev, ps_module, nullptr); - - // Graphics pipeline library: four parts, then the links. - name = entry_name(); - words = renamed(ps, name.c_str()); - ps_module = module_of(words); - stages[1].module = ps_module; - stages[1].pName = name.c_str(); - const auto part = [&](VkGraphicsPipelineLibraryFlagsEXT flags, VkGraphicsPipelineCreateInfo info, - VkPipeline& out) { - VkGraphicsPipelineLibraryCreateInfoEXT library{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_LIBRARY_CREATE_INFO_EXT, - info.pNext, flags}; - info.pNext = &library; - info.flags |= VK_PIPELINE_CREATE_LIBRARY_BIT_KHR | VK_PIPELINE_CREATE_RETAIN_LINK_TIME_OPTIMIZATION_INFO_BIT_EXT; - const double begun = now_ms(); - const VkResult r = vkCreateGraphicsPipelines(dev, cache, 1, &info, nullptr, &out); - return r == VK_SUCCESS ? now_ms() - begun : -1.0; - }; - VkGraphicsPipelineCreateInfo frag_info{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &rendering}; - frag_info.stageCount = 1; - frag_info.pStages = &stages[1]; - frag_info.pMultisampleState = &multisample; - frag_info.pDepthStencilState = &depth; - frag_info.layout = library_layout; - VkGraphicsPipelineCreateInfo pre_info{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &rendering}; - pre_info.stageCount = 1; - pre_info.pStages = &stages[0]; - pre_info.pViewportState = &viewport; - pre_info.pRasterizationState = &raster; - pre_info.pDynamicState = &dynamic; - pre_info.layout = library_layout; - VkGraphicsPipelineCreateInfo input_info{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO}; - input_info.pVertexInputState = &vertex_input; - input_info.pInputAssemblyState = &assembly; - input_info.pDynamicState = &dynamic; - VkGraphicsPipelineCreateInfo output_info{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &rendering}; - output_info.pColorBlendState = &blend; - output_info.pMultisampleState = &multisample; - output_info.pDynamicState = &dynamic; - VkPipeline parts[4] = {}; - const double t_frag = part(VK_GRAPHICS_PIPELINE_LIBRARY_FRAGMENT_SHADER_BIT_EXT, frag_info, parts[0]); - const double t_pre = part(VK_GRAPHICS_PIPELINE_LIBRARY_PRE_RASTERIZATION_SHADERS_BIT_EXT, pre_info, parts[1]); - part(VK_GRAPHICS_PIPELINE_LIBRARY_VERTEX_INPUT_INTERFACE_BIT_EXT, input_info, parts[2]); - part(VK_GRAPHICS_PIPELINE_LIBRARY_FRAGMENT_OUTPUT_INTERFACE_BIT_EXT, output_info, parts[3]); - double t_fast = -1, t_lto = -1; - if (t_frag >= 0 && t_pre >= 0 && parts[2] && parts[3]) { - VkPipelineLibraryCreateInfoKHR linked{VK_STRUCTURE_TYPE_PIPELINE_LIBRARY_CREATE_INFO_KHR, nullptr, 4, parts}; - VkGraphicsPipelineCreateInfo link{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &linked}; - link.layout = library_layout; - t = now_ms(); - if (vkCreateGraphicsPipelines(dev, cache, 1, &link, nullptr, &pipeline) == VK_SUCCESS) { - t_fast = now_ms() - t; - vkDestroyPipeline(dev, pipeline, nullptr); - } - link.flags = VK_PIPELINE_CREATE_LINK_TIME_OPTIMIZATION_BIT_EXT; - t = now_ms(); - if (vkCreateGraphicsPipelines(dev, cache, 1, &link, nullptr, &pipeline) == VK_SUCCESS) { - t_lto = now_ms() - t; - vkDestroyPipeline(dev, pipeline, nullptr); - } - } - for (VkPipeline p : parts) - if (p) vkDestroyPipeline(dev, p, nullptr); - vkDestroyShaderModule(dev, ps_module, nullptr); - - // Shader object: the pixel shader alone. - name = entry_name(); - words = renamed(ps, name.c_str()); - VkShaderCreateInfoEXT sci{VK_STRUCTURE_TYPE_SHADER_CREATE_INFO_EXT}; - sci.stage = VK_SHADER_STAGE_FRAGMENT_BIT; - sci.codeType = VK_SHADER_CODE_TYPE_SPIRV_EXT; - sci.codeSize = words.size() * 4; - sci.pCode = words.data(); - sci.pName = name.c_str(); - sci.setLayoutCount = 1; - sci.pSetLayouts = &set0; - sci.pushConstantRangeCount = 1; - sci.pPushConstantRanges = &push; - VkShaderEXT shader = VK_NULL_HANDLE; - t = now_ms(); - const VkResult so = vkCreateShadersEXT(dev, 1, &sci, nullptr, &shader); - const double t_object = so == VK_SUCCESS ? now_ms() - t : -1.0; - if (shader) vkDestroyShaderEXT(dev, shader, nullptr); - vkDestroyShaderModule(dev, vs_module, nullptr); - - std::printf("%3zu %-60s %6zu KiB: monolithic %8.1f ms (again %6.2f); library fragment %8.1f, pre-raster %6.1f, " - "link %6.2f, optimised link %8.1f; shader object %8.1f ms\n", - index, s.name.c_str(), ps.size() * 4 / 1024, t_mono, t_hit, t_frag, t_pre, t_fast, t_lto, t_object); - std::fflush(stdout); - mono.push_back(t_mono); - mono_hit.push_back(t_hit); - if (t_frag >= 0) frag.push_back(t_frag); - if (t_pre >= 0) pre.push_back(t_pre); - if (t_fast >= 0) link_fast.push_back(t_fast); - if (t_lto >= 0) link_lto.push_back(t_lto); - if (t_object >= 0) object.push_back(t_object); - } - const auto mean = [](const std::vector& v) { - return v.empty() ? 0.0 : std::accumulate(v.begin(), v.end(), 0.0) / double(v.size()); - }; - std::printf("\n%zu pixel shaders. mean / median ms:\n monolithic %.1f / %.1f, again in-process %.2f / %.2f\n" - " library: fragment %.1f / %.1f, pre-raster %.1f / %.1f, link %.2f / %.2f, optimised link %.1f / %.1f\n" - " shader object %.1f / %.1f\n", - mono.size(), mean(mono), median(mono), mean(mono_hit), median(mono_hit), mean(frag), median(frag), - mean(pre), median(pre), mean(link_fast), median(link_fast), mean(link_lto), median(link_lto), - mean(object), median(object)); - return 0; -} diff --git a/runtime/test/vk_sparse_title_memory_test.cpp b/runtime/test/vk_sparse_title_memory_test.cpp deleted file mode 100644 index b52ee9b48..000000000 --- a/runtime/test/vk_sparse_title_memory_test.cpp +++ /dev/null @@ -1,663 +0,0 @@ -// Can title memory be one sparse buffer over imported host memory (src/title_memory.h, "Sparse title memory")? -// -// The console maps a GPU VA to a physical page and reads zero where nothing is mapped. The D3D12 layer can do the same -// on Vulkan if a sparse buffer at the capture-replay device address heap_base + VA can have pages of imported host -// memory (VK_EXT_external_memory_host: the CPU's view of the physical page pool) bound into it. This test asks the -// driver, then does it: -// 1. reports the memory types an imported host pointer may have (vkGetMemoryHostPointerPropertiesEXT) and the ones a -// sparse buffer takes (its memoryTypeBits), with and without residency, capture replay and -// VkExternalMemoryBufferCreateInfo, and what vkGetPhysicalDeviceExternalBufferProperties says of a sparse buffer -// with host-allocation memory; -// 2. imports a pool of host pages (on Windows a pagefile-backed section, as xmem's XMemAllocatePhysicalPages makes -// it), binds some of them into a sparse buffer at heap_base + VA with vkQueueBindSparse, one page at two VAs; -// 3. reads every page and writes one from a compute shader through the device address; checks the bound pages -// show the pool's bytes, the GPU's write reaches the CPU, and the unbound pages read zero; -// 4. rebinds a page to another frame, unbinds one, writes a frame from the CPU, and checks again. Binds and -// dispatches are ordered by one timeline semaphore, as the layer orders them. -// Exit 0 when all of that works, 77 when the device cannot do it (step 1's answer, or a missing feature), 1 when a step -// that the driver accepted gives wrong results. --force-bind binds the host pages even when step 1 says the memory -// type is not allowed (invalid usage: only to see what the driver does; never what the runtime relies on). -// LEONIDA_VK_DEVICE picks the GPU (docs/testing.md, "Choosing the GPU"); LEONIDA_VK_VALIDATION=1 runs it under the -// Khronos validation layer. -// -// No game data. The shader is test/glsl/cs_sparse_title_memory.comp. -#include "vulkan_loader.h" -#include "vk_device_pick.h" -#include "vk_validation.h" -#include "../src/title_memory.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifndef _WIN32 -#include -#endif - -#ifndef LEONIDA_TEST_CS_SPARSE_SPV -#error "LEONIDA_TEST_CS_SPARSE_SPV must name the compiled cs_sparse_title_memory.comp" -#endif - -namespace { - -PFN_vkGetInstanceProcAddr gipa; -int failures = 0; - -#define CHECK(x) \ - do { \ - const VkResult r_ = (x); \ - if (r_ != VK_SUCCESS) { \ - std::fprintf(stderr, "FAILED %s -> %d (line %d)\n", #x, static_cast(r_), __LINE__); \ - return 1; \ - } \ - } while (0) - -void expect(bool ok, const char* what) { - if (!ok) { - std::fprintf(stderr, "FAIL: %s\n", what); - ++failures; - } -} - -std::string type_list(std::uint32_t bits) { - std::string out; - for (std::uint32_t i = 0; i < 32; ++i) - if (bits >> i & 1) out += (out.empty() ? "" : ",") + std::to_string(i); - return out.empty() ? "none" : out; -} - -std::string property_names(VkMemoryPropertyFlags f) { - std::string out; - const auto add = [&](VkMemoryPropertyFlags bit, const char* name) { - if (f & bit) out += (out.empty() ? "" : "|") + std::string(name); - }; - add(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, "device-local"); - add(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, "host-visible"); - add(VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, "coherent"); - add(VK_MEMORY_PROPERTY_HOST_CACHED_BIT, "cached"); - add(VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT, "lazy"); - add(VK_MEMORY_PROPERTY_PROTECTED_BIT, "protected"); - return out.empty() ? "0" : out; -} - -// A pool of host pages: what xmem's XMemAllocatePhysicalPages gives (a pagefile-backed section of reserved pages, -// committed through its whole-section view) on Windows; anonymous memory elsewhere. -struct HostPool { - void* base = nullptr; - std::size_t bytes = 0; -#ifdef _WIN32 - HANDLE section = nullptr; -#endif - bool create(std::size_t size) { - bytes = size; -#ifdef _WIN32 - section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE | SEC_RESERVE, - static_cast(std::uint64_t(size) >> 32), static_cast(size), nullptr); - if (!section) return false; - base = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 0); - return base && VirtualAlloc(base, size, MEM_COMMIT, PAGE_READWRITE); -#else - base = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); - if (base == MAP_FAILED) base = nullptr; - return base != nullptr; -#endif - } - ~HostPool() { -#ifdef _WIN32 - if (base) UnmapViewOfFile(base); - if (section) CloseHandle(section); -#else - if (base) munmap(base, bytes); -#endif - } - std::uint32_t* words() const { return static_cast(base); } -}; - -std::vector read_file(const char* path) { - std::ifstream f(path, std::ios::binary); - return {std::istreambuf_iterator(f), {}}; -} - -struct Pc { - std::uint32_t sparse[2]; - std::uint32_t result[2]; - std::uint32_t page_words; - std::uint32_t pages; - std::uint32_t write_page; - std::uint32_t write_value; -}; - -int run(int argc, char** argv) { - const bool force_bind = argc > 1 && !std::strcmp(argv[1], "--force-bind"); - gipa = load_vulkan(); - if (!gipa) return 77; -#define LOADI(name) const auto name = reinterpret_cast(gipa(instance, #name)) -#define LOADD(name) const auto name = reinterpret_cast(vkGetDeviceProcAddr(device, #name)) - VkInstance instance = VK_NULL_HANDLE; - LOADI(vkCreateInstance); - VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; - app.apiVersion = VK_API_VERSION_1_3; - VkInstanceCreateInfo ici{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; - ici.pApplicationInfo = &app; - leonida::vk_test::OptInValidation validation; - if (!validation.prepare(gipa, ici)) return 1; - if (vkCreateInstance(&ici, nullptr, &instance) != VK_SUCCESS) { - std::fprintf(stderr, "no Vulkan 1.3 instance\n"); - return 77; - } - CHECK(validation.attach(gipa, instance)); - LOADI(vkEnumeratePhysicalDevices); - LOADI(vkGetPhysicalDeviceProperties); - LOADI(vkGetPhysicalDeviceFeatures2); - LOADI(vkGetPhysicalDeviceMemoryProperties); - LOADI(vkGetPhysicalDeviceQueueFamilyProperties); - LOADI(vkGetPhysicalDeviceProperties2); - LOADI(vkGetPhysicalDeviceExternalBufferProperties); - LOADI(vkEnumerateDeviceExtensionProperties); - LOADI(vkCreateDevice); - LOADI(vkGetDeviceProcAddr); - - std::uint32_t count = 0; - vkEnumeratePhysicalDevices(instance, &count, nullptr); - std::vector gpus(count); - vkEnumeratePhysicalDevices(instance, &count, gpus.data()); - std::vector candidates(count); - for (std::uint32_t i = 0; i < count; ++i) vkGetPhysicalDeviceProperties(gpus[i], &candidates[i]); - const std::size_t chosen = leonida::vk_test::pick_device(candidates); - if (chosen == candidates.size()) { - leonida::vk_test::report_no_device(); - return 77; - } - const VkPhysicalDevice gpu = gpus[chosen]; - const VkPhysicalDeviceProperties& props = candidates[chosen]; - - VkPhysicalDeviceExternalMemoryHostPropertiesEXT host_props{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT}; - VkPhysicalDeviceDriverProperties driver{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES, &host_props}; - VkPhysicalDeviceProperties2 props2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &driver}; - vkGetPhysicalDeviceProperties2(gpu, &props2); - std::printf("device: %s (%s %s), sparseAddressSpaceSize 0x%" PRIx64 ", residencyNonResidentStrict %u, " - "minImportedHostPointerAlignment 0x%" PRIx64 "\n", - props.deviceName, driver.driverName, driver.driverInfo, - static_cast(props.limits.sparseAddressSpaceSize), - props.sparseProperties.residencyNonResidentStrict, - static_cast(host_props.minImportedHostPointerAlignment)); - - VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; - VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &f12}; - vkGetPhysicalDeviceFeatures2(gpu, &f2); - std::uint32_t ext_count = 0; - vkEnumerateDeviceExtensionProperties(gpu, nullptr, &ext_count, nullptr); - std::vector exts(ext_count); - vkEnumerateDeviceExtensionProperties(gpu, nullptr, &ext_count, exts.data()); - bool has_host = false; - for (const auto& e : exts) has_host |= !std::strcmp(e.extensionName, VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME); - // Without capture replay the sparse buffer gets the driver's address: everything else is still checked, and the - // run ends 77 (the layer needs heap_base + VA). - const bool replay = f12.bufferDeviceAddressCaptureReplay != VK_FALSE; - if (!replay) std::printf("no bufferDeviceAddressCaptureReplay: the sparse buffer takes the driver's address\n"); - if (!f2.features.sparseBinding || !f2.features.sparseResidencyBuffer || !f12.bufferDeviceAddress || - !f12.timelineSemaphore || !has_host) { - std::printf("not supported: sparseBinding %u, sparseResidencyBuffer %u, bufferDeviceAddress %u, " - "bufferDeviceAddressCaptureReplay %u, timelineSemaphore %u, VK_EXT_external_memory_host %u\n", - f2.features.sparseBinding, f2.features.sparseResidencyBuffer, f12.bufferDeviceAddress, - f12.bufferDeviceAddressCaptureReplay, f12.timelineSemaphore, has_host ? 1u : 0u); - return 77; - } - - // A queue that binds sparse memory and runs compute work (the layer binds on its own queue of such a family). - std::uint32_t family_count = 0; - vkGetPhysicalDeviceQueueFamilyProperties(gpu, &family_count, nullptr); - std::vector families(family_count); - vkGetPhysicalDeviceQueueFamilyProperties(gpu, &family_count, families.data()); - std::uint32_t family = family_count; - for (std::uint32_t i = 0; i < family_count && family == family_count; ++i) - if ((families[i].queueFlags & (VK_QUEUE_SPARSE_BINDING_BIT | VK_QUEUE_COMPUTE_BIT)) == - (VK_QUEUE_SPARSE_BINDING_BIT | VK_QUEUE_COMPUTE_BIT)) - family = i; - if (family == family_count) { - std::printf("not supported: no queue family with sparse binding and compute\n"); - return 77; - } - - VkPhysicalDeviceMemoryProperties memory{}; - vkGetPhysicalDeviceMemoryProperties(gpu, &memory); - for (std::uint32_t i = 0; i < memory.memoryTypeCount; ++i) - std::printf("memory type %u: heap %u, %s\n", i, memory.memoryTypes[i].heapIndex, - property_names(memory.memoryTypes[i].propertyFlags).c_str()); - - // What the driver says of a sparse buffer with host-allocation memory. - const VkBufferUsageFlags usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | - VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; - const VkBufferCreateFlags sparse_flags = VK_BUFFER_CREATE_SPARSE_BINDING_BIT | VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT; - { - VkPhysicalDeviceExternalBufferInfo info{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_BUFFER_INFO}; - info.flags = sparse_flags; - info.usage = usage; - info.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; - VkExternalBufferProperties out{VK_STRUCTURE_TYPE_EXTERNAL_BUFFER_PROPERTIES}; - vkGetPhysicalDeviceExternalBufferProperties(gpu, &info, &out); - std::printf("external buffer properties (sparse, host allocation): features 0x%x, compatible 0x%x\n", - out.externalMemoryProperties.externalMemoryFeatures, - out.externalMemoryProperties.compatibleHandleTypes); - } - - const char* device_exts[] = {VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME}; - const float priority = 1.0f; - VkDeviceQueueCreateInfo qci{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; - qci.queueFamilyIndex = family; - qci.queueCount = 1; - qci.pQueuePriorities = &priority; - VkPhysicalDeviceVulkan12Features want12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; - want12.bufferDeviceAddress = VK_TRUE; - want12.bufferDeviceAddressCaptureReplay = replay ? VK_TRUE : VK_FALSE; - want12.timelineSemaphore = VK_TRUE; - VkPhysicalDeviceFeatures2 want_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &want12}; - want_features.features.sparseBinding = VK_TRUE; - want_features.features.sparseResidencyBuffer = VK_TRUE; - VkDeviceCreateInfo dci{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &want_features}; - dci.queueCreateInfoCount = 1; - dci.pQueueCreateInfos = &qci; - dci.enabledExtensionCount = 1; - dci.ppEnabledExtensionNames = device_exts; - VkDevice device = VK_NULL_HANDLE; - CHECK(vkCreateDevice(gpu, &dci, nullptr, &device)); - LOADD(vkGetDeviceQueue); - LOADD(vkCreateBuffer); - LOADD(vkDestroyBuffer); - LOADD(vkGetBufferMemoryRequirements); - LOADD(vkGetBufferDeviceAddress); - LOADD(vkAllocateMemory); - LOADD(vkFreeMemory); - LOADD(vkBindBufferMemory); - LOADD(vkMapMemory); - LOADD(vkGetMemoryHostPointerPropertiesEXT); - LOADD(vkQueueBindSparse); - LOADD(vkQueueSubmit); - LOADD(vkCreateSemaphore); - LOADD(vkDestroySemaphore); - LOADD(vkWaitSemaphores); - LOADD(vkCreateShaderModule); - LOADD(vkDestroyShaderModule); - LOADD(vkCreatePipelineLayout); - LOADD(vkDestroyPipelineLayout); - LOADD(vkCreateComputePipelines); - LOADD(vkDestroyPipeline); - LOADD(vkCreateCommandPool); - LOADD(vkDestroyCommandPool); - LOADD(vkAllocateCommandBuffers); - LOADD(vkBeginCommandBuffer); - LOADD(vkEndCommandBuffer); - LOADD(vkResetCommandBuffer); - LOADD(vkCmdBindPipeline); - LOADD(vkCmdPushConstants); - LOADD(vkCmdDispatch); - LOADD(vkCmdFillBuffer); - LOADD(vkCmdPipelineBarrier); - LOADD(vkDeviceWaitIdle); - LOADD(vkDestroyDevice); - VkQueue queue = VK_NULL_HANDLE; - vkGetDeviceQueue(device, family, 0, &queue); - - // The sparse buffer's memory types, for the flag sets the layer could use. - const auto sparse_bits = [&](VkBufferCreateFlags flags, bool external, VkDeviceSize* alignment) -> std::uint32_t { - VkExternalMemoryBufferCreateInfo ext{VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO}; - ext.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; - VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, external ? &ext : nullptr}; - info.flags = flags; - info.size = std::uint64_t(64) << 20; - info.usage = usage; - VkBuffer b = VK_NULL_HANDLE; - if (vkCreateBuffer(device, &info, nullptr, &b) != VK_SUCCESS) return 0xffffffffu; - VkMemoryRequirements req{}; - vkGetBufferMemoryRequirements(device, b, &req); - vkDestroyBuffer(device, b, nullptr); - if (alignment) *alignment = req.alignment; - return req.memoryTypeBits; - }; - VkDeviceSize page = 0; - struct Variant { - const char* name; - VkBufferCreateFlags flags; - bool external; - } const variants[] = { - {"plain buffer", 0, false}, - {"plain buffer, external host allocation", 0, true}, - {"sparse binding", VK_BUFFER_CREATE_SPARSE_BINDING_BIT, false}, - {"sparse binding + residency", sparse_flags, false}, - {"sparse binding + residency + capture replay", - replay ? sparse_flags | VK_BUFFER_CREATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT : sparse_flags, false}, - {"sparse binding + residency, external host allocation", sparse_flags, true}, - {"sparse binding, external host allocation", VK_BUFFER_CREATE_SPARSE_BINDING_BIT, true}, - }; - std::uint32_t sparse_types = 0; - for (const auto& v : variants) { - VkDeviceSize alignment = 0; - const std::uint32_t bits = sparse_bits(v.flags, v.external, &alignment); - if (bits == 0xffffffffu) { - std::printf("%s: vkCreateBuffer refused\n", v.name); - continue; - } - std::printf("%s: memory types %s, alignment 0x%" PRIx64 "\n", v.name, type_list(bits).c_str(), - static_cast(alignment)); - if (v.flags == sparse_flags) { - sparse_types |= bits; - if (!page) page = alignment; - } - } - if (!page) { - std::printf("not supported: no sparse residency buffer\n"); - vkDestroyDevice(device, nullptr); - return 77; - } - - // The pool: 4 frames of one sparse page each. - constexpr std::uint32_t kFrames = 4, kPages = 8; - const std::size_t frame_bytes = static_cast(page); - const std::uint32_t page_words = static_cast(frame_bytes / 4); - HostPool pool; - if (!pool.create(kFrames * frame_bytes)) { - std::fprintf(stderr, "FAILED: host pool of %zu bytes\n", kFrames * frame_bytes); - return 1; - } - for (std::uint32_t f = 0; f < kFrames; ++f) { - pool.words()[f * page_words] = 0xA000 + f; - pool.words()[f * page_words + 1] = 0xD000 + f; - pool.words()[f * page_words + page_words - 1] = 0xB000 + f; - } - VkMemoryHostPointerPropertiesEXT pointer{VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT}; - CHECK(vkGetMemoryHostPointerPropertiesEXT(device, VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, pool.base, - &pointer)); - std::printf("host pointer memory types: %s; sparse residency buffer memory types: %s\n", - type_list(pointer.memoryTypeBits).c_str(), type_list(sparse_types).c_str()); - const std::uint32_t usable = pointer.memoryTypeBits & sparse_types; - if (!usable && !force_bind) { - std::printf("not supported: imported host memory cannot be bound into a sparse buffer on this device (no " - "memory type in both sets)\n"); - vkDestroyDevice(device, nullptr); - return 77; - } - std::uint32_t pool_type = 0; - const std::uint32_t pick = usable ? usable : pointer.memoryTypeBits; - while (!(pick >> pool_type & 1)) ++pool_type; - if (!usable) std::printf("--force-bind: binding memory type %u, which the sparse buffer does not list\n", pool_type); - - VkImportMemoryHostPointerInfoEXT import{VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT}; - import.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; - import.pHostPointer = pool.base; - VkMemoryAllocateFlagsInfo pool_flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, &import}; - pool_flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; - VkMemoryAllocateInfo pool_alloc{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &pool_flags}; - pool_alloc.allocationSize = kFrames * frame_bytes; - pool_alloc.memoryTypeIndex = pool_type; - VkDeviceMemory pool_memory = VK_NULL_HANDLE; - CHECK(vkAllocateMemory(device, &pool_alloc, nullptr, &pool_memory)); - - // The sparse buffer at heap_base + a VA in the title window, for host-allocation memory. - const std::uint64_t va = leonida::title_memory::kWindowStart; - const VkDeviceAddress want_address = leonida::title_memory::device_address(va); - VkExternalMemoryBufferCreateInfo sparse_external{VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO}; - sparse_external.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; - VkBufferOpaqueCaptureAddressCreateInfo opaque{VK_STRUCTURE_TYPE_BUFFER_OPAQUE_CAPTURE_ADDRESS_CREATE_INFO, - &sparse_external}; - opaque.opaqueCaptureAddress = want_address; - VkBufferCreateInfo sparse_info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, - replay ? static_cast(&opaque) : &sparse_external}; - sparse_info.flags = sparse_flags | (replay ? VK_BUFFER_CREATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT : 0); - sparse_info.size = kPages * page; - sparse_info.usage = usage; - VkBuffer sparse = VK_NULL_HANDLE; - CHECK(vkCreateBuffer(device, &sparse_info, nullptr, &sparse)); - VkBufferDeviceAddressInfo address_info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; - address_info.buffer = sparse; - const VkDeviceAddress sparse_address = vkGetBufferDeviceAddress(device, &address_info); - std::printf("sparse buffer: asked 0x%" PRIx64 ", got 0x%" PRIx64 "\n", static_cast(want_address), - static_cast(sparse_address)); - if (replay) expect(sparse_address == want_address, "the sparse buffer has the capture-replay address heap_base + VA"); - - // The result words: host-visible memory. - VkBufferCreateInfo result_info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - result_info.size = 3 * kPages * 4; - result_info.usage = usage; - VkBuffer result = VK_NULL_HANDLE; - CHECK(vkCreateBuffer(device, &result_info, nullptr, &result)); - VkMemoryRequirements result_req{}; - vkGetBufferMemoryRequirements(device, result, &result_req); - std::uint32_t result_type = memory.memoryTypeCount; - for (std::uint32_t i = 0; i < memory.memoryTypeCount && result_type == memory.memoryTypeCount; ++i) - if ((result_req.memoryTypeBits >> i & 1) && - (memory.memoryTypes[i].propertyFlags & (VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) == - (VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) - result_type = i; - VkMemoryAllocateFlagsInfo result_flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; - result_flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; - VkMemoryAllocateInfo result_alloc{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &result_flags}; - result_alloc.allocationSize = result_req.size; - result_alloc.memoryTypeIndex = result_type; - VkDeviceMemory result_memory = VK_NULL_HANDLE; - CHECK(vkAllocateMemory(device, &result_alloc, nullptr, &result_memory)); - CHECK(vkBindBufferMemory(device, result, result_memory, 0)); - void* mapped = nullptr; - CHECK(vkMapMemory(device, result_memory, 0, VK_WHOLE_SIZE, 0, &mapped)); - auto* out = static_cast(mapped); - address_info.buffer = result; - const VkDeviceAddress result_address = vkGetBufferDeviceAddress(device, &address_info); - - // Pipeline. - const std::vector code = read_file(LEONIDA_TEST_CS_SPARSE_SPV); - if (code.empty() || code.size() % 4) { - std::fprintf(stderr, "FAILED: cannot read %s\n", LEONIDA_TEST_CS_SPARSE_SPV); - return 1; - } - VkShaderModuleCreateInfo smci{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - smci.codeSize = code.size(); - smci.pCode = reinterpret_cast(code.data()); - VkShaderModule module = VK_NULL_HANDLE; - CHECK(vkCreateShaderModule(device, &smci, nullptr, &module)); - VkPushConstantRange range{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Pc)}; - VkPipelineLayoutCreateInfo plci{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; - plci.pushConstantRangeCount = 1; - plci.pPushConstantRanges = ⦥ - VkPipelineLayout layout = VK_NULL_HANDLE; - CHECK(vkCreatePipelineLayout(device, &plci, nullptr, &layout)); - VkComputePipelineCreateInfo cpci{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; - cpci.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; - cpci.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; - cpci.stage.module = module; - cpci.stage.pName = "main"; - cpci.layout = layout; - VkPipeline pipeline = VK_NULL_HANDLE; - CHECK(vkCreateComputePipelines(device, VK_NULL_HANDLE, 1, &cpci, nullptr, &pipeline)); - - VkCommandPoolCreateInfo pool_info{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; - pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; - pool_info.queueFamilyIndex = family; - VkCommandPool command_pool = VK_NULL_HANDLE; - CHECK(vkCreateCommandPool(device, &pool_info, nullptr, &command_pool)); - VkCommandBufferAllocateInfo cbai{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; - cbai.commandPool = command_pool; - cbai.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; - cbai.commandBufferCount = 1; - VkCommandBuffer cmd = VK_NULL_HANDLE; - CHECK(vkAllocateCommandBuffers(device, &cbai, &cmd)); - - VkSemaphoreTypeCreateInfo timeline_type{VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO}; - timeline_type.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE; - VkSemaphoreCreateInfo sci{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &timeline_type}; - VkSemaphore timeline = VK_NULL_HANDLE; - CHECK(vkCreateSemaphore(device, &sci, nullptr, &timeline)); - std::uint64_t point = 0; - - // Binds sparse page p to pool frame f (f < 0: unbinds it), ordered after everything so far. - struct Bind { - std::uint32_t page; - int frame; - }; - const auto bind = [&](std::initializer_list binds) -> VkResult { - std::vector list; - for (const Bind& b : binds) { - VkSparseMemoryBind m{}; - m.resourceOffset = b.page * page; - m.size = page; - m.memory = b.frame < 0 ? VK_NULL_HANDLE : pool_memory; - m.memoryOffset = b.frame < 0 ? 0 : b.frame * page; - list.push_back(m); - } - VkSparseBufferMemoryBindInfo buffer_bind{sparse, static_cast(list.size()), list.data()}; - const std::uint64_t wait = point, signal = ++point; - VkTimelineSemaphoreSubmitInfo values{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO}; - values.waitSemaphoreValueCount = 1; - values.pWaitSemaphoreValues = &wait; - values.signalSemaphoreValueCount = 1; - values.pSignalSemaphoreValues = &signal; - VkBindSparseInfo info{VK_STRUCTURE_TYPE_BIND_SPARSE_INFO, &values}; - info.waitSemaphoreCount = 1; - info.pWaitSemaphores = &timeline; - info.signalSemaphoreCount = 1; - info.pSignalSemaphores = &timeline; - info.bufferBindCount = 1; - info.pBufferBinds = &buffer_bind; - return vkQueueBindSparse(queue, 1, &info, VK_NULL_HANDLE); - }; - // One dispatch after the binds so far; waits for it on the CPU. - const auto dispatch = [&](std::uint32_t write_page, std::uint32_t write_value) -> VkResult { - vkResetCommandBuffer(cmd, 0); - VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; - begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - vkBeginCommandBuffer(cmd, &begin); - vkCmdFillBuffer(cmd, result, 0, VK_WHOLE_SIZE, 0xEEEEEEEEu); - VkMemoryBarrier barrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - barrier.dstAccessMask = VK_ACCESS_SHADER_WRITE_BIT; - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &barrier, - 0, nullptr, 0, nullptr); - vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline); - Pc pc{}; - pc.sparse[0] = static_cast(sparse_address); - pc.sparse[1] = static_cast(sparse_address >> 32); - pc.result[0] = static_cast(result_address); - pc.result[1] = static_cast(result_address >> 32); - pc.page_words = page_words; - pc.pages = kPages; - pc.write_page = write_page; - pc.write_value = write_value; - vkCmdPushConstants(cmd, layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(pc), &pc); - vkCmdDispatch(cmd, 1, 1, 1); - barrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; - barrier.dstAccessMask = VK_ACCESS_HOST_READ_BIT; - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &barrier, 0, - nullptr, 0, nullptr); - vkEndCommandBuffer(cmd); - const std::uint64_t wait = point, signal = ++point; - VkTimelineSemaphoreSubmitInfo values{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO}; - values.waitSemaphoreValueCount = 1; - values.pWaitSemaphoreValues = &wait; - values.signalSemaphoreValueCount = 1; - values.pSignalSemaphoreValues = &signal; - const VkPipelineStageFlags stage = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; - VkSubmitInfo submit{VK_STRUCTURE_TYPE_SUBMIT_INFO, &values}; - submit.waitSemaphoreCount = 1; - submit.pWaitSemaphores = &timeline; - submit.pWaitDstStageMask = &stage; - submit.commandBufferCount = 1; - submit.pCommandBuffers = &cmd; - submit.signalSemaphoreCount = 1; - submit.pSignalSemaphores = &timeline; - const VkResult r = vkQueueSubmit(queue, 1, &submit, VK_NULL_HANDLE); - if (r != VK_SUCCESS) return r; - VkSemaphoreWaitInfo wait_info{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO}; - wait_info.semaphoreCount = 1; - wait_info.pSemaphores = &timeline; - wait_info.pValues = &signal; - return vkWaitSemaphores(device, &wait_info, std::uint64_t(10) * 1000 * 1000 * 1000); - }; - // Page i's three samples: words 0, 1 and last, or zero for an unbound page. - struct Sample { - std::uint32_t w0, w1, last; - }; - const auto check = [&](const char* when, const Sample (&want)[kPages]) { - for (std::uint32_t i = 0; i < kPages; ++i) { - const Sample got{out[3 * i], out[3 * i + 1], out[3 * i + 2]}; - const bool ok = got.w0 == want[i].w0 && got.w1 == want[i].w1 && got.last == want[i].last; - std::printf(" %s page %u: 0x%x 0x%x 0x%x%s\n", when, i, got.w0, got.w1, got.last, - ok ? "" : " (wrong)"); - if (!ok) { - char what[160]; - std::snprintf(what, sizeof(what), "%s: page %u reads 0x%x 0x%x 0x%x, not 0x%x 0x%x 0x%x", when, i, - got.w0, got.w1, got.last, want[i].w0, want[i].w1, want[i].last); - expect(false, what); - } - } - }; - const auto frame = [](std::uint32_t f, std::uint32_t w1) { return Sample{0xA000 + f, w1, 0xB000 + f}; }; - const Sample zero{0, 0, 0}; - - // Step 2: pages 0, 1, 3, 5 bound (5 to the same frame as 0), the others not. - CHECK(bind({{0, 0}, {1, 2}, {3, 1}, {5, 0}})); - // Step 3: read all, write page 0's word 1 (frame 0, which page 5 shows too), and write to unbound page 2. - CHECK(dispatch(0, 0x5EED)); - { - const Sample want[kPages] = {frame(0, 0xD000), frame(2, 0xD002), zero, frame(1, 0xD001), - zero, frame(0, 0xD000), zero, zero}; - check("first bind", want); - } - expect(pool.words()[1] == 0x5EED, "the GPU's write through page 0 reaches frame 0 on the CPU"); - CHECK(dispatch(2, 0xBAD)); // a write to an unbound page goes nowhere - { - const Sample want[kPages] = {frame(0, 0x5EED), frame(2, 0xD002), zero, frame(1, 0xD001), - zero, frame(0, 0x5EED), zero, zero}; - check("after the GPU write", want); - } - - // Step 4: page 3 to frame 3, page 1 unbound, page 6 to frame 2; the CPU writes frame 3. - CHECK(bind({{3, 3}, {1, -1}, {6, 2}})); - pool.words()[3 * page_words + 1] = 0xC0DE; - CHECK(dispatch(0xffffffffu, 0)); - { - const Sample want[kPages] = {frame(0, 0x5EED), zero, zero, frame(3, 0xC0DE), - zero, frame(0, 0x5EED), frame(2, 0xD002), zero}; - check("after the rebind", want); - } - for (std::uint32_t f = 0; f < kFrames; ++f) - expect(f == 0 || pool.words()[f * page_words + 1] != 0xBAD, "the write to an unbound page reached a frame"); - - // The pool can go while the sparse buffer stays: unbind everything, then free it. - CHECK(bind({{0, -1}, {3, -1}, {5, -1}, {6, -1}})); - CHECK(dispatch(0xffffffffu, 0)); - { - const Sample want[kPages] = {zero, zero, zero, zero, zero, zero, zero, zero}; - check("after unbinding all", want); - } - - vkDeviceWaitIdle(device); - vkDestroySemaphore(device, timeline, nullptr); - vkDestroyCommandPool(device, command_pool, nullptr); - vkDestroyPipeline(device, pipeline, nullptr); - vkDestroyPipelineLayout(device, layout, nullptr); - vkDestroyShaderModule(device, module, nullptr); - vkDestroyBuffer(device, result, nullptr); - vkFreeMemory(device, result_memory, nullptr); - vkDestroyBuffer(device, sparse, nullptr); - vkFreeMemory(device, pool_memory, nullptr); - vkDestroyDevice(device, nullptr); - if (failures) { - std::fprintf(stderr, "%d checks failed\n", failures); - return 1; - } - std::printf("ok: imported host memory binds into a sparse buffer%s%s\n", replay ? " at heap_base + VA" : "", - usable ? "" : " (forced: the memory type is not one the buffer lists)"); - if (!usable) return 1; - return replay ? 0 : 77; -} - -} // namespace - -int main(int argc, char** argv) { - return leonida::vk_test::OptInValidation::exit_status(run(argc, argv)); -} diff --git a/runtime/test/winsock_offline_test.cpp b/runtime/test/winsock_offline_test.cpp deleted file mode 100644 index 5224ce81d..000000000 --- a/runtime/test/winsock_offline_test.cpp +++ /dev/null @@ -1,134 +0,0 @@ -// winsock_offline (shims/winsock_offline.cpp): Winsock as a mapped title sees it reaches loopback only. Every -// refused call is refused before the host is called, so nothing here leaves the machine; the sockets it opens are -// loopback ones. 192.0.2.1 is TEST-NET-1 (RFC 5737) and .invalid a reserved name (RFC 2606). -#include -#include -#include -#include - -#include -#include - -#include "shims.h" - -namespace { - -int g_failures = 0; -void check(bool condition, const char* what) { - std::printf("%s: %s\n", condition ? "ok" : "FAIL", what); - if (!condition) ++g_failures; -} - -template F get(const char* name) { return reinterpret_cast(rt::shims::find("ws2_32.dll", name)); } - -sockaddr_in v4(const char* ip, uint16_t port) { - sockaddr_in a{}; - a.sin_family = AF_INET; - a.sin_port = htons(port); - inet_pton(AF_INET, ip, &a.sin_addr); - return a; -} - -} // namespace - -int main() { - WSADATA wsa{}; - if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) { - std::printf("SKIP: no Winsock\n"); - return 0; - } - using Connect = int(WSAAPI*)(SOCKET, const sockaddr*, int); - using SendTo = int(WSAAPI*)(SOCKET, const char*, int, int, const sockaddr*, int); - using Bind = int(WSAAPI*)(SOCKET, const sockaddr*, int); - using GetAddrInfo = INT(WSAAPI*)(PCSTR, PCSTR, const ADDRINFOA*, PADDRINFOA*); - using GetHostByName = hostent*(WSAAPI*)(const char*); - using GetNameInfo = INT(WSAAPI*)(const SOCKADDR*, socklen_t, PCHAR, DWORD, PCHAR, DWORD, INT); - using Ioctl = int(WSAAPI*)(SOCKET, DWORD, LPVOID, DWORD, LPVOID, DWORD, LPDWORD, LPWSAOVERLAPPED, - LPWSAOVERLAPPED_COMPLETION_ROUTINE); - const auto connect_ = get("connect"); - const auto sendto_ = get("sendto"); - const auto bind_ = get("bind"); - const auto getaddrinfo_ = get("getaddrinfo"); - const auto gethostbyname_ = get("gethostbyname"); - const auto getnameinfo_ = get("getnameinfo"); - const auto ioctl_ = get("WSAIoctl"); - check(connect_ && sendto_ && bind_ && getaddrinfo_ && gethostbyname_ && getnameinfo_ && ioctl_, - "the vetted imports are served"); - check(get("#4") == connect_ && get("#20") == sendto_ && get("#2") == bind_ && - get("#52") == gethostbyname_ && rt::shims::find("ws2_32.dll", "#51"), - "the classic ordinals the retail executable imports name the same functions"); - check(!rt::shims::owns_dll("ws2_32.dll"), "ws2_32.dll stays a host module: the rest of it is the host's"); - if (!(connect_ && sendto_ && bind_ && getaddrinfo_ && gethostbyname_ && getnameinfo_ && ioctl_)) return 1; - - // Connects and datagrams leave loopback only. - SOCKET tcp = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - sockaddr_in remote = v4("192.0.2.1", 80); - check(connect_(tcp, reinterpret_cast(&remote), sizeof(remote)) == SOCKET_ERROR && - WSAGetLastError() == WSAENETUNREACH, - "a connect to a network address fails with WSAENETUNREACH"); - sockaddr_in6 mapped{}; - mapped.sin6_family = AF_INET6; - mapped.sin6_port = htons(80); - inet_pton(AF_INET6, "::ffff:192.0.2.1", &mapped.sin6_addr); - SOCKET tcp6 = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP); - check(connect_(tcp6, reinterpret_cast(&mapped), sizeof(mapped)) == SOCKET_ERROR && - WSAGetLastError() == WSAENETUNREACH, - "so does one to an IPv4-mapped IPv6 network address"); - closesocket(tcp6); - - SOCKET udp = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); - sockaddr_in any = v4("0.0.0.0", 0); - check(bind_(udp, reinterpret_cast(&any), sizeof(any)) == 0, "a bind to all interfaces succeeds"); - sockaddr_in bound{}; - int bound_len = sizeof(bound); - getsockname(udp, reinterpret_cast(&bound), &bound_len); - check(bound.sin_addr.s_addr == htonl(INADDR_LOOPBACK), "and is narrowed to loopback"); - sockaddr_in dns = v4("192.0.2.1", 53); - check(sendto_(udp, "x", 1, 0, reinterpret_cast(&dns), sizeof(dns)) == SOCKET_ERROR && - WSAGetLastError() == WSAENETUNREACH, - "a datagram to a network address fails with WSAENETUNREACH"); - sockaddr_in self{}; - int self_len = sizeof(self); - getsockname(udp, reinterpret_cast(&self), &self_len); - check(sendto_(udp, "x", 1, 0, reinterpret_cast(&self), sizeof(self)) == 1, - "a datagram to a loopback address is sent"); - check(connect_(udp, reinterpret_cast(&self), sizeof(self)) == 0, "a connect to loopback succeeds"); - - // ConnectEx from WSAIoctl is ours, and vets the destination too. - GUID connect_ex_id = WSAID_CONNECTEX; - LPFN_CONNECTEX connect_ex = nullptr; - DWORD returned = 0; - check(ioctl_(tcp, SIO_GET_EXTENSION_FUNCTION_POINTER, &connect_ex_id, sizeof(connect_ex_id), &connect_ex, - sizeof(connect_ex), &returned, nullptr, nullptr) == 0 && connect_ex, - "WSAIoctl hands out ConnectEx"); - if (connect_ex) - check(!connect_ex(tcp, reinterpret_cast(&remote), sizeof(remote), nullptr, 0, nullptr, nullptr) && - WSAGetLastError() == WSAENETUNREACH, - "its ConnectEx refuses a network address"); - - // Lookups: localhost and literals only. - ADDRINFOA* result = reinterpret_cast(1); - check(getaddrinfo_("example.invalid", "80", nullptr, &result) == WSAHOST_NOT_FOUND && !result, - "getaddrinfo of a network name fails with WSAHOST_NOT_FOUND"); - result = nullptr; - check(getaddrinfo_("127.0.0.1", "80", nullptr, &result) == 0 && result, "getaddrinfo of a literal is the host's"); - if (result) freeaddrinfo(result); - result = nullptr; - check(getaddrinfo_("localhost", "80", nullptr, &result) == 0 && result, "getaddrinfo of localhost is the host's"); - if (result) freeaddrinfo(result); - check(gethostbyname_("example.invalid") == nullptr && WSAGetLastError() == WSAHOST_NOT_FOUND, - "gethostbyname of a network name fails"); - char host[NI_MAXHOST] = {}; - check(getnameinfo_(reinterpret_cast(&remote), sizeof(remote), host, sizeof(host), nullptr, 0, 0) == 0 && - std::strcmp(host, "192.0.2.1") == 0, - "getnameinfo of a network address comes back numeric"); - check(getnameinfo_(reinterpret_cast(&remote), sizeof(remote), host, sizeof(host), nullptr, 0, - NI_NAMEREQD) == WSAHOST_NOT_FOUND, - "and fails when a name is required"); - - closesocket(udp); - closesocket(tcp); - WSACleanup(); - std::printf("%s\n", g_failures ? "FAILED" : "PASSED"); - return g_failures ? 1 : 0; -} diff --git a/runtime/test/xgameruntime_store_test.cpp b/runtime/test/xgameruntime_store_test.cpp index f4eaadfac..d33146361 100644 --- a/runtime/test/xgameruntime_store_test.cpp +++ b/runtime/test/xgameruntime_store_test.cpp @@ -159,15 +159,6 @@ int main() { at(store, 23)(store, package_license); check(!at(store, 22)(store, package_license), "a closed license is not valid"); - // ---- durables: the user owns none (VIctory xstore.rs) ---- - async = XAsyncBlock{}; - Handle durable_license = nullptr; - check(at(store, 71)(store, context, "9DURABLE0001", &async) == S_OK && finished(&async) && - at(store, 72)(store, &async, &durable_license) == S_OK && durable_license, - "XStoreAcquireLicenseForDurables completes with a license handle"); - check(!at(store, 22)(store, durable_license), "a durable's license is not valid: the user owns none"); - at(store, 23)(store, durable_license); - // ---- product queries are empty ---- async = XAsyncBlock{}; Handle products = nullptr; diff --git a/runtime/test/xgameruntime_user_test.cpp b/runtime/test/xgameruntime_user_test.cpp index e1c5289d8..54e38a248 100644 --- a/runtime/test/xgameruntime_user_test.cpp +++ b/runtime/test/xgameruntime_user_test.cpp @@ -245,14 +245,11 @@ int main(int argc, char** argv) { using IsStore = bool(STDMETHODCALLTYPE*)(void*, XUserHandle); check(at(user, 42)(user, h) && at(user, 42)(user, nullptr), "XUserIsStoreUser: true, also for a null handle (_In_opt_; always true on console)"); - // Slot 15 is the older XUserGetGamertag (VIctory xuser.rs, measured on the retail title): the same arguments - // and answer as the gamertag interface's slot 3. - using OldTag = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, uint32_t, size_t, char*, size_t*); - char probe[101] = "untouched"; + using Unknown = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, size_t, char*, size_t*); + char probe[16] = "untouched"; size_t probe_used = 42; - check(at(user, 15)(user, h, 0, sizeof(probe), probe, &probe_used) == S_OK && - std::strcmp(probe, expect_tag) == 0 && probe_used == std::strlen(expect_tag) + 1, - "slot 15 (the older XUserGetGamertag slot) gives the gamertag"); + check(at(user, 15)(user, h, sizeof(probe), probe, &probe_used) == E_NOTIMPL, + "slot 15 (no public signature) answers E_NOTIMPL rather than S_OK with nothing written"); // ---- IXUserGamertagImpl: XUserGetGamertag (3) ---- using GetTag = HRESULT(STDMETHODCALLTYPE*)(void*, XUserHandle, uint32_t, size_t, char*, size_t*); diff --git a/runtime/test/xma_test.cpp b/runtime/test/xma_test.cpp deleted file mode 100644 index c0e1a233c..000000000 --- a/runtime/test/xma_test.cpp +++ /dev/null @@ -1,768 +0,0 @@ -// The XMA2 frame decoder (src/xma_decode.h) and the SHAPE XMA context machine (src/xma_context.h). Most cases are -// ported with the code from VIctory's tests (crates/victory-formats/src/xma.rs and -// crates/victory-hle/src/modules/audio.rs), GPL-3.0-or-later, by Marvisak and contributors (DexNom fork); Leonida is -// GPL-3.0-or-later. Every stream is built in memory: no game data, no files. -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "xma_context.h" -#include "xma_decode.h" -#include "xma_tables.h" - -using namespace rt::xma; - -namespace { - -int g_checks = 0; -int g_failures = 0; - -template -void check(bool ok, const char* format, Args... args) { - ++g_checks; - if (ok) return; - ++g_failures; - std::fputs("FAIL ", stdout); - if constexpr (sizeof...(Args) == 0) std::fputs(format, stdout); - else std::printf(format, args...); - std::fputs("\n", stdout); -} - -void run(const char* name, void (*test)()) { - const int before = g_failures; - test(); - std::printf("%s %s\n", g_failures == before ? "PASS" : "FAIL", name); -} - -constexpr double kPi = std::numbers::pi; - -// Writes `value` as `n` bits, MSB first, at bit `pos`, over what is there. -void set_bits(std::vector& data, size_t pos, uint32_t n, uint32_t value) { - for (uint32_t i = 0; i < n; ++i) { - const size_t p = pos + i; - const unsigned bit = (value >> (n - 1 - i)) & 1u; - data[p / 8] = static_cast((data[p / 8] & ~(0x80u >> (p % 8))) | (bit << (7 - p % 8))); - } -} - -// Appends bits MSB first. -struct BitWriter { - std::vector data; - size_t bits = 0; - void put(uint32_t value, uint32_t n) { - for (uint32_t i = 0; i < n; ++i) { - if (bits % 8 == 0) data.push_back(0); - if ((value >> (n - 1 - i)) & 1u) data[bits / 8] |= static_cast(0x80u >> (bits % 8)); - ++bits; - } - } -}; - -// ---- The inverse transform ---- - -// The direct sum imdct_half stands for (FFmpeg's naive inverse MDCT: the standard formula, negated). -std::vector imdct_reference(const std::vector& input) { - const size_t n = input.size(); - std::vector out(n); - for (size_t j = 0; j < n; ++j) { - const double t = static_cast(j + n / 2) + 0.5 + static_cast(n) / 2.0; - double sum = 0; - for (size_t k = 0; k < n; ++k) - sum += input[k] * std::cos(kPi / static_cast(n) * t * (static_cast(k) + 0.5)); - out[j] = -sum; - } - return out; -} - -void fast_imdct_matches_the_direct_sum() { - for (const size_t n : {size_t{128}, size_t{256}, size_t{512}, size_t{64}}) { - std::vector input(n); - for (size_t i = 0; i < n; ++i) input[i] = static_cast((i * 7919) % 97) - 48.0f; - std::vector fast(n); - imdct_half(input, fast, 1.0f); - const auto reference = imdct_reference(input); - for (size_t j = 0; j < n; ++j) - check(std::fabs(fast[j] - reference[j]) < 1e-2 * (1.0 + std::fabs(reference[j])), "n %zu, %zu: %f vs %f", n, - j, fast[j], reference[j]); - } -} - -// Windowed MDCT blocks of a signal, put back together the way the decoder does (half IMDCT, then window and overlap), -// give the signal. -void imdct_and_window_reconstruct_a_signal() { - const size_t n = 256; - std::vector signal(n * 6); - for (size_t i = 0; i < signal.size(); ++i) signal[i] = std::sin(static_cast(i) * 0.05f) * 0.3f; - // The 2n-sample sine window; its rising half is sine_window(n). - const auto window = [n](size_t i) { return std::sin((static_cast(i) + 0.5) * kPi / (2.0 * n)); }; - std::vector out(n * 7); - const auto rising = sine_window(n); - for (size_t block = 0; block < 5; ++block) { - const size_t base = block * n; - std::vector coeffs(n); - for (size_t k = 0; k < n; ++k) { - double sum = 0; - for (size_t i = 0; i < 2 * n; ++i) { - const double t = static_cast(i) + 0.5 + static_cast(n) / 2.0; - // FFmpeg's forward MDCT pairs with its inverse by sign. - sum += -static_cast(signal[base + i]) * window(i) * - std::cos(kPi / static_cast(n) * t * (static_cast(k) + 0.5)); - } - coeffs[k] = static_cast(sum); - } - // The half output is the middle of the 2n window. - const size_t at = base + n / 2; - imdct_half(coeffs, std::span(out.data() + at, n), 2.0f / static_cast(n)); - if (block > 0) window_overlap(std::span(out.data() + at - n / 2, n), rising); - } - for (size_t i = n; i < 5 * n; ++i) - check(std::fabs(out[i] - signal[i]) < 1e-3, "%zu: %f vs %f", i, out[i], signal[i]); -} - -// ---- Packets and frames ---- - -void packet_rejects_out_of_range_indices_and_partial_headers() { - const std::vector four(4), three(3); - check(!packet(four, SIZE_MAX / kPacketBytes + 1), "an index past size_t"); - check(!packet(three, 0), "a partial header"); - check(packet(four, 0).has_value(), "a whole header"); -} - -void packet_headers_and_frame_walk() { - // Two packets: frame A (100 bits) and B (16300 bits, crossing into packet 1 by 48 bits), then C (60 bits) in - // packet 1; the rest is padding. - std::vector data(2 * kPacketBytes, 0xff); - const auto header = [](uint32_t frames, uint32_t first) { return frames << 26 | first << 11; }; - set_bits(data, 0, 32, header(2, 0)); - set_bits(data, kPacketBits, 32, header(1, 48)); - set_bits(data, 32, 15, 100); - set_bits(data, 132, 15, 16300); - const size_t c_start = kPacketBits + 32 + 48; - set_bits(data, c_start, 15, 60); - const auto a = read_frame(data, 32); - check(a && a->bits == 100 && a->next == size_t{132}, "frame A and the next"); - const auto b = read_frame(data, 132); - check(b && b->bits == 16300 && b->next == c_start, "frame B and the next"); - // Its last bits come from after packet 1's header; the last byte's unused bits stay zero. - check(b && b->data.size() == (16300 + 7) / 8 && b->data.back() == 0xf0, "frame B's bytes"); - const auto c = read_frame(data, c_start); - // C was packet 1's only frame: the next would be in packet 2. - check(c && c->bits == 60 && !c->next, "frame C is the last"); -} - -// A damaged packet whose first frame says it is 0 bits long: finding the frame after a later one must give up, not -// walk in place forever (found by random-input testing). -void a_zero_length_frame_before_the_start_ends_the_search() { - std::vector data(kPacketBytes, 0); - set_bits(data, 0, 32, 2u << 26); // two frames, the first at payload bit 0; its 15-bit length stays 0 - const size_t start = kHeaderBits + 100; - set_bits(data, start, kLengthBits, 200); - const auto frame = read_frame(data, start); - check(frame && frame->bits == 200 && !frame->next, "the frame at start reads; the walk gives up"); -} - -// A frame that crosses a packet where no frame begins (a full continuation) and ends in another such packet, followed -// by padding: the next frame is the first one of the next packet that has frames, not the padding the frame ended in. -void the_frame_after_continuation_packets_starts_in_the_next_packet_with_frames() { - std::vector data(4 * kPacketBytes, 0); - const auto header = [](uint32_t frames, uint32_t first) { return frames << 26 | first << 11; }; - set_bits(data, 0, 32, header(2, 0)); - // Packet 1 is all of one frame; packet 2 holds only its last 64 bits. - set_bits(data, kPacketBits, 32, header(0, 0x7fff)); - set_bits(data, 2 * kPacketBits, 32, header(0, 64)); - set_bits(data, 3 * kPacketBits, 32, header(1, 0)); - // A first frame of 16000 bits, then one from the end of its payload through packets 1 and 2. - const size_t second = kHeaderBits + 16000; - set_bits(data, kHeaderBits, kLengthBits, 16000); - const size_t tail = kPacketBits - second; - const size_t bits = tail + (kPacketBits - kHeaderBits) + 64; - set_bits(data, second, kLengthBits, static_cast(bits)); - set_bits(data, 3 * kPacketBits + kHeaderBits, kLengthBits, 100); - const auto first = read_frame(data, kHeaderBits); - check(first && first->next == second, "the first frame's next"); - const auto frame = read_frame(data, second); - check(frame && frame->bits == bits && frame->next == 3 * kPacketBits + kHeaderBits, "after the continuation"); - const auto last = read_frame(data, 3 * kPacketBits + kHeaderBits); - check(last && !last->next, "the last frame"); -} - -// Two packets of three silent mono frames each: a fixed one-subframe layout, no transmitted coefficients -// (VIctory audio.rs, silent_stream). -std::vector silent_stream() { - std::vector data(2 * kPacketBytes, 0xff); - for (size_t p = 0; p < 2; ++p) { - const size_t base = p * kPacketBits; - set_bits(data, base, 32, 3u << 26); - for (size_t frame = 0; frame < 3; ++frame) { - const size_t at = base + 32 + frame * 31; - set_bits(data, at, 15, 31); // length - set_bits(data, at + 15, 2, 0b10); // fixed layout, one 512-sample subframe - set_bits(data, at + 17, 8 + 1 + 3 + 2, 0); // gain, no trim, empty subframe - } - } - return data; -} - -void silent_frames_decode_to_silence() { - const auto data = silent_stream(); - Decoder decoder(1, 48000); - std::vector pcm; - size_t frames = 0; - std::optional at = kHeaderBits + packet(data, 0)->first_frame_bit; - while (at && frames < 16) { - const auto frame = read_frame(data, *at); - if (!frame) break; - const char* error = decoder.decode(frame->data, frame->bits, pcm); - check(error == nullptr, "silent frame %zu: %s", frames, error ? error : ""); - ++frames; - at = frame->next; - } - decoder.flush(pcm); - check(frames == 6, "six frames walked (%zu)", frames); - check(pcm.size() == 6 * kFrameSamples + kFrameSamples / 2, "a frame of samples each, half a frame flushed"); - check(std::all_of(pcm.begin(), pcm.end(), [](int16_t s) { return s == 0; }), "all silence"); - - // A frame of zeros after its length and a fixed layout decodes, mono and stereo (no coefficients, an empty - // channel transform for stereo). - for (const size_t channels : {size_t{1}, size_t{2}}) { - BitWriter w; - w.put(100, 15); - w.put(1, 1); - w.put(0, 100 - 16); - Decoder d(channels, 44100); - std::vector out; - const char* error = d.decode(w.data, w.bits, out); - check(error == nullptr && out.size() == kFrameSamples * channels, "a zero frame, %zu channels: %s", channels, - error ? error : ""); - } -} - -// The canonical code of `symbol` in a table of (symbol, length) entries in code order, as ff_vlc_init_from_lengths -// assigns them. -struct Code { - uint32_t bits = 0; - uint32_t length = 0; -}; - -template -Code canonical_code(size_t count, Symbol symbol_at, Length length_at, int32_t symbol) { - uint64_t code = 0; - for (size_t i = 0; i < count; ++i) { - const uint32_t length = length_at(i); - if (symbol_at(i) == symbol) return {static_cast(code >> (32 - length)), length}; - code += uint64_t{1} << (32 - length); - } - return {}; -} - -// The scale factor bands of a 512-sample subframe at 48 kHz, worked out again here. -size_t bands_512_at_48k() { - size_t offsets[Decoder::kMaxBands + 1] = {}; - size_t band = 1; - for (size_t f = 0; f < Decoder::kMaxBands - 1; ++f) { - if (offsets[band - 1] >= 512) break; - const size_t offset = ((512 * 2 * rt::xma::tables::kCriticalFreq[f]) / 48000 + 2) & ~size_t{3}; - if (offset > offsets[band - 1]) offsets[band++] = offset; - if (offset >= 512) break; - } - return band - 1; -} - -// A mono frame with one coefficient, +1 at frequency 0, every scale factor equal and quantisation step 90: the -// decoder's samples are that coefficient through the inverse MDCT and the sine window, worked out here from the -// direct sum. Then a frame without coefficients gives the windowed overlap of the first. -void a_coded_frame_decodes_to_its_transform() { - namespace t = rt::xma::tables; - const Code scale_zero = canonical_code( - std::size(t::kScale), [](size_t i) { return static_cast(t::kScale[i].symbol) - 60; }, - [](size_t i) { return static_cast(t::kScale[i].length); }, 0); - const auto coef0_symbol = [](size_t i) { return static_cast(t::kCoef0Syms[i]); }; - const auto coef0_length = [](size_t i) { return static_cast(t::kCoef0Lens[i]); }; - const Code level_one = canonical_code(std::size(t::kCoef0Syms), coef0_symbol, coef0_length, 2); // run 0, level 1 - const Code end = canonical_code(std::size(t::kCoef0Syms), coef0_symbol, coef0_length, 1); - check(scale_zero.length > 0 && level_one.length > 0 && end.length > 0, "codes found"); - check(t::kCoef0Run[2] == 0 && t::kCoef0Level[2] == 1.0f, "symbol 2 is run 0, level 1"); - - const auto build = [&](uint32_t length) { - BitWriter w; - w.put(length, 15); - w.put(1, 1); // fixed layout - w.put(0, 1); // one subframe of 512 - w.put(0, 8); // gain - w.put(0, 1); // no trim - w.put(0, 1); // no fill - w.put(0, 1); // reserved - w.put(1, 1); // transmit coefficients - w.put(1, 1); // transmit the vector coefficient count - w.put(0, 8); // of 0: run-level coding from the first coefficient - w.put(0, 6); // quantisation step 90 + 0 - w.put(0, 2); // scale factor step 1 - for (size_t band = 0; band < bands_512_at_48k(); ++band) w.put(scale_zero.bits, scale_zero.length); - w.put(0, 1); // coefficient table 0 - w.put(level_one.bits, level_one.length); - w.put(1, 1); // positive - w.put(end.bits, end.length); - w.put(0, 1); // no more frames - return w; - }; - const BitWriter first = build(static_cast(build(0).bits)); - check(first.bits < 0x7fff, "the frame fits a length field"); - - Decoder decoder(1, 48000); - std::vector pcm; - const char* error = decoder.decode(first.data, first.bits, pcm); - check(error == nullptr, "the coded frame decodes: %s", error ? error : ""); - - // The reference: y = the scaled inverse transform of the one coefficient; the frame's output is the window's - // overlap of silence with y's first half. - const size_t n = 512; - const float quant = std::pow(10.0f, 90.0f / 20.0f); - const double scale = 2.0 / 512.0 / 32768.0; - std::vector y(n); - for (size_t j = 0; j < n; ++j) - y[j] = -scale * quant * std::cos(kPi / static_cast(n) * (static_cast(j) + n + 0.5) * 0.5); - const auto w = [n](size_t i) { return std::sin((static_cast(i) + 0.5) * kPi / (2.0 * n)); }; - const auto i16 = [](double v) { return std::clamp(std::round(v * 32768.0), -32768.0, 32767.0); }; - std::vector expected(n); - for (size_t k = 0; k < n / 2; ++k) { - expected[k] = i16(-y[n / 2 - 1 - k] * w(k)); - expected[n - 1 - k] = i16(y[n / 2 - 1 - k] * w(n - 1 - k)); - } - int peak = 0; - size_t off = 0; - for (size_t i = 0; i < n && i < pcm.size(); ++i) { - peak = std::max(peak, std::abs(static_cast(pcm[i]))); - off += std::fabs(pcm[i] - expected[i]) > 1.0 ? 1 : 0; - } - check(pcm.size() == n && off == 0 && peak > 50, "the first frame is the windowed transform (%zu off, peak %d)", - off, peak); - - // A frame without coefficients: its output is the first frame's second half, windowed out. - BitWriter second; - second.put(100, 15); - second.put(1, 1); - second.put(0, 100 - 16); - pcm.clear(); - error = decoder.decode(second.data, second.bits, pcm); - off = 0; - for (size_t i = 0; i < n / 2 && pcm.size() == n; ++i) { - off += std::fabs(pcm[i] - i16(y[n / 2 + i] * w(n - 1 - i))) > 1.0 ? 1 : 0; - off += std::fabs(pcm[n - 1 - i] - i16(y[n / 2 + i] * w(i))) > 1.0 ? 1 : 0; - } - check(error == nullptr && pcm.size() == n && off == 0, "the next frame overlaps the first (%zu off)", off); -} - -// ---- Noise (VIctory's noise tests) ---- - -// Deterministic noise: xorshift64. -struct Noise { - uint64_t state; - - uint64_t next() { - state ^= state << 13; - state ^= state >> 7; - state ^= state << 17; - return state; - } - - // A number below `n`. - size_t below(size_t n) { return static_cast(next() % n); } - - // `len` bytes of even noise, or of mostly zeros (`density` 1) or mostly ones (2), which take other paths through a - // frame. - std::vector bytes(size_t len, int density) { - std::vector out(len); - for (auto& byte : out) { - const uint64_t r = next(); - const uint8_t a = static_cast(r), b = static_cast(r >> 8), c = static_cast(r >> 16); - byte = density == 0 ? a : density == 1 ? static_cast(a & b & c) : static_cast(a | b | c); - } - return out; - } -}; - -constexpr int kDensities[4] = {0, 0, 1, 2}; - -// `packets` packets of one stream: back-to-back frames of noise after their length fields, 300 to 4299 bits long (so -// every packet but the last has a frame start, and at most 55 do), then padding of ones. The headers count the frames -// that begin in each packet. Also gives the number of frames. -std::vector noise_stream(Noise& noise, size_t packets, int density, size_t& frames) { - const size_t payload = kPacketBits - kHeaderBits; - std::vector data = noise.bytes(packets * kPacketBytes, density); - const auto at = [payload](size_t q) { return q / payload * kPacketBits + kHeaderBits + q % payload; }; - std::vector> headers(packets, {0, 0}); - size_t q = 0; - frames = 0; - for (;;) { - const size_t len = 300 + noise.below(4000); - if (q + len > packets * payload) break; - auto& header = headers[q / payload]; - if (header.first == 0) header.second = static_cast(q % payload); - ++header.first; - for (uint32_t i = 0; i < kLengthBits; ++i) - set_bits(data, at(q + i), 1, static_cast(len >> (kLengthBits - 1 - i)) & 1u); - q += len; - ++frames; - } - for (size_t padding = q; padding < packets * payload; ++padding) set_bits(data, at(padding), 1, 1); - for (size_t p = 0; p < packets; ++p) - set_bits(data, p * kPacketBits, 32, headers[p].first << 26 | headers[p].second << 11); - return data; -} - -// Packets of noise, streams of frames of noise, and such streams with headers and bits damaged: walking the frames -// from the first packet and decoding each, mono and stereo, gives a frame of samples per frame and ends within the -// frames the buffer can hold (each is over 15 bits and the walk only moves on). -void noise_packets_walk_and_decode() { - Noise noise{0x2545f4914f6cdd1dull}; - for (size_t round = 0; round < 60; ++round) { - const size_t packets = 1 + round % 4; - const int density = kDensities[round / 3 % 4]; - size_t written = 0; - std::vector data = round % 3 == 0 ? noise.bytes(packets * kPacketBytes, density) - : noise_stream(noise, packets, density, written); - if (round % 3 == 2) { - const size_t headers = 1 + noise.below(3); - for (size_t i = 0; i < headers; ++i) { - const size_t p = noise.below(packets); - set_bits(data, p * kPacketBits, 32, static_cast(noise.next())); - } - const size_t flips = noise.below(16); - for (size_t i = 0; i < flips; ++i) { - const size_t bit = noise.below(data.size() * 8); - data[bit / 8] ^= static_cast(0x80u >> (bit % 8)); - } - } - const size_t budget = data.size() * 8 / 16; - for (const size_t channels : {size_t{1}, size_t{2}}) { - Decoder decoder(channels, 48000); - const size_t per_frame = kFrameSamples * channels; - std::vector pcm; - size_t frames = 0; - std::optional at; - if (const auto first = packet(data, 0)) at = kHeaderBits + first->first_frame_bit; - while (at) { - const auto frame = read_frame(data, *at); - if (!frame) break; - ++frames; - const bool moves_on = !frame->next || *frame->next > frame->start; - check(frames <= budget && moves_on, "round %zu: the walk moves on within its budget", round); - if (frames > budget || !moves_on) break; - decoder.decode(frame->data, frame->bits, pcm); - check(pcm.size() == frames * per_frame, "round %zu: a frame of samples per frame", round); - at = frame->next; - } - // A clean stream: every frame is walked. - if (round % 3 == 1) check(frames == written, "round %zu: %zu of %zu frames walked", round, frames, written); - decoder.flush(pcm); - check(pcm.size() == frames * per_frame + per_frame / 2, "round %zu: the flush", round); - } - } -} - -// Frames of noise, mono and stereo at each sample rate, with bit counts up to the end of the data: every decode gives -// one frame of samples, whether the frame decodes or not. -void noise_frames_decode_to_a_frame_of_samples() { - Noise noise{0x9e3779b97f4a7c15ull}; - for (const size_t channels : {size_t{1}, size_t{2}}) { - for (const uint32_t rate : {24000u, 32000u, 44100u, 48000u}) { - Decoder decoder(channels, rate); - std::vector pcm; - for (size_t round = 0; round < 48; ++round) { - const auto data = noise.bytes(round * 89 % 4096, kDensities[round % 4]); - const size_t bits = round % 2 == 0 ? data.size() * 8 : noise.below(data.size() * 8 + 1); - pcm.clear(); - decoder.decode(data, bits, pcm); - check(pcm.size() == kFrameSamples * channels, "%zu channels, %u Hz, round %zu", channels, rate, round); - if (round % 16 == 15) decoder.reset(); - } - pcm.clear(); - decoder.flush(pcm); - check(pcm.size() == kFrameSamples / 2 * channels, "%zu channels, %u Hz: the flush", channels, rate); - } - } -} - -// Bit counts past the end of a frame's data, up to SIZE_MAX: the decoding ends, with a frame of samples. A stereo tile -// header that ran out of data used to loop on the zeros past it for good (found by this test in VIctory). -void noise_frames_with_bit_counts_past_the_data() { - Noise noise{0xd1b54a32d192ed03ull}; - constexpr size_t kLengths[8] = {0, 1, 2, 3, 5, 8, 40, 300}; - for (const size_t channels : {size_t{1}, size_t{2}}) { - Decoder decoder(channels, 48000); - std::vector pcm; - for (size_t round = 0; round < 48; ++round) { - const auto data = noise.bytes(kLengths[round % 8], kDensities[round / 8 % 4]); - size_t bits = SIZE_MAX; - if (round % 3 == 0) bits = data.size() * 8 + 1 + noise.below(size_t{1} << 16); - else if (round % 3 == 1) bits = SIZE_MAX / 2 + noise.below(size_t{1} << 20); - pcm.clear(); - decoder.decode(data, bits, pcm); - check(pcm.size() == kFrameSamples * channels, "%zu channels, round %zu", channels, round); - } - } -} - -// read_frame from any bit of a buffer of noise and past it, and packet at any index: a frame read stays inside its -// limits. -void noise_offsets_read_a_frame_or_nothing() { - Noise noise{0x6a09e667f3bcc908ull}; - for (size_t round = 0; round < 24; ++round) { - const size_t packets = 1 + round % 3; - const auto data = noise.bytes(packets * kPacketBytes, kDensities[round % 4]); - const size_t all = data.size() * 8; - std::vector starts = {0, 1, kHeaderBits - 1, kHeaderBits, - kPacketBits - kLengthBits, kPacketBits - 1, kPacketBits, all - 1, - all, all + 1, SIZE_MAX / 2, SIZE_MAX - kPacketBits + 1, - SIZE_MAX}; - for (int i = 0; i < 32; ++i) starts.push_back(noise.below(all)); - for (const size_t start : starts) { - const auto frame = read_frame(data, start); - if (!frame) continue; - check(frame->bits > kLengthBits && frame->bits < 0x7fff, "start %zu: the length", start); - check(frame->data.size() == (frame->bits + 7) / 8, "start %zu: the bytes", start); - if (frame->next) check(*frame->next > start && *frame->next / 8 < data.size(), "start %zu: the next", start); - } - const size_t far = SIZE_MAX / kPacketBytes; - for (const size_t index : {size_t{0}, packets - 1, packets, far, SIZE_MAX}) - check(packet(data, index).has_value() == (index < packets), "round %zu: packet %zu", round, index); - } -} - -// ---- The XMA contexts (VIctory audio.rs) ---- - -// APU memory for the context tests: blocks with device addresses. -struct Block { - uint32_t apu; - std::vector bytes; -}; -std::vector g_blocks; - -uint8_t* test_memory(uint32_t apu, size_t len) { - for (Block* b : g_blocks) { - if (apu < b->apu) continue; - const size_t offset = apu - b->apu; - if (offset <= b->bytes.size() && len <= b->bytes.size() - offset) return b->bytes.data() + offset; - } - return nullptr; -} - -struct Fixture { - Block input{0x10000, {}}; - Block output{0x20000, {}}; - uint32_t array[4 * 16] = {}; - Engine engine{&test_memory}; - - explicit Fixture(size_t output_bytes) { - input.bytes = silent_stream(); - input.bytes.resize(0x1000, 0); - output.bytes.assign(output_bytes, 0x55); - g_blocks = {&input, &output}; - engine.attach(array, 4); - } - ~Fixture() { - engine.detach(); - g_blocks.clear(); - } - Context context(uint32_t index) { return Context(array + index * 16); } - void submit(uint32_t command, std::initializer_list words) { - const std::vector data(words); - check(engine.command(command, data.data()), "command %u is an XMA command", command); - } - // A pass on a thread of its own, so one that never ends fails the test instead of hanging it. - bool pump_within(std::chrono::seconds limit, Context context) { - std::atomic done{false}; - std::thread pass([&] { - engine.pump(); - done = true; - }); - const auto until = std::chrono::steady_clock::now() + limit; - while (!done && std::chrono::steady_clock::now() < until) std::this_thread::sleep_for(std::chrono::milliseconds(1)); - const bool ended = done; - if (!ended) context.set_field(1, 31, 1, 0); // end it as a full ring would - pass.join(); - return ended; - } -}; - -void xma_contexts_decode_into_their_output_rings() { - Fixture f(0x400); - const Context context = f.context(1); - // As the title sets one up: two packets, input 0 valid, a ring of four blocks, writable, 48 kHz mono, reading from - // the first frame. - context.set(0, 2 | 1u << 20 | 4u << 22); - context.set(1, 1u << 31 | 3u << 27); - context.set(2, 32); - context.set(5, f.input.apu); - context.set(7, f.output.apu); - f.submit(kEnableXma, {1}); - f.engine.pump(); - // Full: all four blocks written (silence), the write block wrapped onto the read block, and the ring no longer - // writable. - check(context.field(0, 27, 5) == 0 && context.field(1, 31, 1) == 0, "a full ring"); - check(std::all_of(f.output.bytes.begin(), f.output.bytes.end(), [](uint8_t b) { return b == 0; }), "silence"); - - // Read four blocks at a time until the input has run out and the ring keeps room. - for (int i = 0; i < 20; ++i) { - f.submit(kAdvanceXmaRead, {1, 4}); - f.engine.pump(); - if (context.field(2, 31, 1) == 1 && context.field(1, 31, 1) == 1) break; - } - // Six frames and the flushed tail: 3,328 samples, 26 blocks. - const auto trace = f.engine.trace(1); - check(trace && trace->produced == 26 * kSamplesPerBlock && trace->input_ended, "26 blocks produced (%zu samples)", - trace ? trace->produced : 0); - check(trace && trace->frames == 6 && trace->bad_frames == 0, "six good frames"); - check(context.field(0, 20, 2) == 0, "input used up"); - check(context.field(2, 26, 5) == kInputInvalid, "input invalid status"); - check(context.field(0, 27, 5) == 26 % 4, "the write block after 26 blocks"); - - // A count near UINT32_MAX wraps the read block like any other (3 + 0xffffffff blocks on a ring of four is block - // 2); the sum used to overflow. - context.set_field(9, 0, 5, 3); - f.submit(kAdvanceXmaRead, {1, UINT32_MAX}); - check(context.field(9, 0, 5) == 2, "the read block wraps"); - - f.submit(kDisableXma, {1}); - check(!f.engine.trace(1), "disabled"); -} - -// A read block past the end of the ring (6 on a ring of four) is block 2 of it: a stream that loops forever fills -// blocks 0 and 1 and the pass ends. It used to fill the ring for good, holding the voice. -void xma_read_blocks_past_the_ring_end_wrap() { - Fixture f(0x400); - const Context context = f.context(1); - context.set(0, 2 | 255u << 12 | 1u << 20 | 4u << 22); - context.set(1, 1u << 31 | 3u << 27); - context.set(2, 32); - context.set(3, 32); - context.set(4, static_cast(kPacketBits + 32 + 2 * 31)); - context.set(5, f.input.apu); - context.set(7, f.output.apu); - context.set(9, 6); - f.submit(kEnableXma, {1}); - const bool ended = f.pump_within(std::chrono::seconds(5), context); - check(ended, "the XMA pass ended"); - check(context.field(0, 27, 5) == 2 && context.field(1, 31, 1) == 0, "blocks 0 and 1 written, the ring full"); - check(std::all_of(f.output.bytes.begin(), f.output.bytes.begin() + 0x200, [](uint8_t b) { return b == 0; }) && - std::all_of(f.output.bytes.begin() + 0x200, f.output.bytes.end(), [](uint8_t b) { return b == 0x55; }), - "blocks 2 and 3 left for the title"); -} - -// A write block past the end of the ring (6 on a ring of four) is block 2 of it: blocks 2, 3 and 0 are filled, up to -// the read block (1). It used to write block 6 first, past the ring's end. -void xma_write_blocks_past_the_ring_end_wrap() { - Fixture f(0x800); // the ring (four blocks) and a guard area after it, which the pass must not touch - const Context context = f.context(1); - context.set(0, 2 | 255u << 12 | 1u << 20 | 4u << 22 | 6u << 27); - context.set(1, 1u << 31 | 3u << 27); - context.set(2, 32); - context.set(3, 32); - context.set(4, static_cast(kPacketBits + 32 + 2 * 31)); - context.set(5, f.input.apu); - context.set(7, f.output.apu); - context.set(9, 1); - f.submit(kEnableXma, {1}); - const bool ended = f.pump_within(std::chrono::seconds(5), context); - check(ended, "the XMA pass ended"); - check(context.field(0, 27, 5) == 1 && context.field(1, 31, 1) == 0, "up to the read block"); - const auto& ring = f.output.bytes; - const auto all = [&ring](size_t from, size_t to, uint8_t v) { - return std::all_of(ring.begin() + static_cast(from), ring.begin() + static_cast(to), - [v](uint8_t b) { return b == v; }); - }; - check(all(0x400, 0x800, 0x55), "nothing written past the ring"); - check(all(0, 0x100, 0) && all(0x200, 0x400, 0) && all(0x100, 0x200, 0x55), "blocks 2, 3 and 0 written, 1 left"); -} - -// A loop over the first two frames, which ends after the second frame's second subframe and starts two subframes into -// the first. Each end of the loop is cut in its own frame. -void a_loop_skips_subframes_of_its_first_frame() { - Block input{0x10000, silent_stream()}; - g_blocks = {&input}; - // Frames start at bits 32, 63 and 94 of each packet. - const uint32_t first = 32, second = 63, third = 94; - const uint32_t end_subframe = 1, skip_subframes = 2; - uint32_t words[16] = {}; - const Context context(words); - // Two packets, one loop, input 0 valid; 48 kHz mono. - context.set(0, 2 | 1u << 12 | 1u << 20 | 4u << 22); - context.set(1, 1u << 31 | 3u << 27 | end_subframe << 12 | skip_subframes << 17); - context.set(2, first); - context.set(3, first); - context.set(4, second); - context.set(5, input.apu); - Voice voice; - const auto step = [&](uint32_t expect_next) { - const size_t before = voice.pcm.size(); - const bool decoded = decode(context, voice, &test_memory); - check(decoded && context.field(2, 0, 26) == expect_next, "the read position after a frame: %u, not %u", - context.field(2, 0, 26), expect_next); - return voice.pcm.size() - before; - }; - const size_t subframe = kSubframeSamples; - // Before the loop: the first frame whole. - check(step(second) == 4 * subframe, "the first frame whole"); - // The loop's last frame: its first two subframes, then back. - check(step(first) == 2 * subframe, "the loop's last frame"); - check(context.field(0, 12, 8) == 0, "one loop, taken"); - // The loop's first frame again: without its first two subframes. - check(step(second) == 2 * subframe, "the loop's first frame"); - // No loops left: both frames whole, and on to the third. - check(step(third) == 4 * subframe, "the second frame whole"); - g_blocks.clear(); -} - -void xma_commands_select_contexts() { - Fixture f(0x400); - for (uint32_t i = 0; i < 4; ++i) f.context(i).set(2, 0xfc000000u); // error status and error set - f.submit(kEnableXmas, {0b101}); - check(f.engine.trace(0) && !f.engine.trace(1) && f.engine.trace(2) && !f.engine.trace(3), "contexts 0 and 2"); - check(f.context(0).field(2, 26, 6) == 0 && f.context(1).field(2, 26, 6) == 0x3f, "enabling clears the error"); - f.submit(kDisableXmas, {0b100}); - check(f.engine.trace(0) && !f.engine.trace(2), "context 2 disabled"); - f.submit(kEnableXma, {4}); // past the array: nothing - f.submit(kAdvanceXmaRead, {9, 1}); - check(!f.engine.command(12, nullptr), "another command is not the decoder's"); - check(f.engine.command(kEnableXma, nullptr), "without data: no context"); - f.engine.detach(); - f.submit(kEnableXma, {0}); - check(!f.engine.trace(0), "detached: no voices"); -} - -} // namespace - -int main() { - std::printf("xma_test: XMA2 frames and SHAPE XMA contexts, built in memory\n"); - run("fast_imdct_matches_the_direct_sum", fast_imdct_matches_the_direct_sum); - run("imdct_and_window_reconstruct_a_signal", imdct_and_window_reconstruct_a_signal); - run("packet_rejects_out_of_range_indices_and_partial_headers", - packet_rejects_out_of_range_indices_and_partial_headers); - run("packet_headers_and_frame_walk", packet_headers_and_frame_walk); - run("a_zero_length_frame_before_the_start_ends_the_search", a_zero_length_frame_before_the_start_ends_the_search); - run("the_frame_after_continuation_packets_starts_in_the_next_packet_with_frames", - the_frame_after_continuation_packets_starts_in_the_next_packet_with_frames); - run("silent_frames_decode_to_silence", silent_frames_decode_to_silence); - run("a_coded_frame_decodes_to_its_transform", a_coded_frame_decodes_to_its_transform); - run("noise_packets_walk_and_decode", noise_packets_walk_and_decode); - run("noise_frames_decode_to_a_frame_of_samples", noise_frames_decode_to_a_frame_of_samples); - run("noise_frames_with_bit_counts_past_the_data", noise_frames_with_bit_counts_past_the_data); - run("noise_offsets_read_a_frame_or_nothing", noise_offsets_read_a_frame_or_nothing); - run("xma_contexts_decode_into_their_output_rings", xma_contexts_decode_into_their_output_rings); - run("xma_read_blocks_past_the_ring_end_wrap", xma_read_blocks_past_the_ring_end_wrap); - run("xma_write_blocks_past_the_ring_end_wrap", xma_write_blocks_past_the_ring_end_wrap); - run("a_loop_skips_subframes_of_its_first_frame", a_loop_skips_subframes_of_its_first_frame); - run("xma_commands_select_contexts", xma_commands_select_contexts); - std::printf("xma_test complete: %d checks, %d failures\n", g_checks, g_failures); - return g_failures ? 1 : 0; -} diff --git a/tests/semantic/fixtures/cs_w64_half_local.asm b/tests/semantic/fixtures/cs_w64_half_local.asm deleted file mode 100644 index 252514714..000000000 --- a/tests/semantic/fixtures/cs_w64_half_local.asm +++ /dev/null @@ -1,14 +0,0 @@ -; SHADER-10 compute tier A: a wave64 compute program (64 threads) whose cross-lane reads stay inside 32-lane halves. -; Natively it runs one half per 32-lane subgroup with the thread index relabelled from the subgroup. Lane t stores -; ((t - 1 if t % 16 else 0) << 8) + (t ^ 16) at 4 * t: a DPP row shift right by 1 (bound_ctrl: 0 off the row's start) -; and a ds_swizzle swap of 16-lane groups. -v_mbcnt_lo_u32_b32 v1, -1, 0 -v_mbcnt_hi_u32_b32 v1, -1, v1 -s_mov_b64 s[6:7], exec -v_mov_b32_dpp v2, v1 row_shr:1 row_mask:0xf bank_mask:0xf bound_ctrl:0 -ds_swizzle_b32 v3, v1 offset:swizzle(SWAP,16) -s_waitcnt lgkmcnt(0) -v_lshl_add_u32 v4, v2, 8, v3 -v_lshlrev_b32_e32 v21, 2, v0 -buffer_store_dword v4, v21, s[0:3], 0 offen -s_endpgm \ No newline at end of file diff --git a/tests/semantic/fixtures/cs_w64_lds_swap.asm b/tests/semantic/fixtures/cs_w64_lds_swap.asm deleted file mode 100644 index a50d104d5..000000000 --- a/tests/semantic/fixtures/cs_w64_lds_swap.asm +++ /dev/null @@ -1,16 +0,0 @@ -; SHADER-10 compute tier B: a one-wave group (64 threads) shares LDS without a barrier, as the console compiler emits -; it: lane t writes 100 + t to LDS[t], then reads LDS[t ^ 32], the other half's word. The wave runs both in -; lockstep; in two 32-lane subgroups the read needs a workgroup barrier in front (wave64_halves `sync`). Lane t stores -; 100 + (t ^ 32) at 4 * t. -v_mbcnt_lo_u32_b32 v1, -1, 0 -v_mbcnt_hi_u32_b32 v1, -1, v1 -s_mov_b64 s[6:7], exec -v_lshlrev_b32_e32 v2, 2, v1 -v_add_nc_u32_e32 v5, 100, v1 -ds_write_b32 v2, v5 -v_xor_b32_e32 v3, 0x80, v2 -ds_read_b32 v4, v3 -s_waitcnt lgkmcnt(0) -v_lshlrev_b32_e32 v21, 2, v0 -buffer_store_dword v4, v21, s[0:3], 0 offen -s_endpgm \ No newline at end of file diff --git a/tests/semantic/fixtures/discard_keeps_helper.asm b/tests/semantic/fixtures/discard_keeps_helper.asm deleted file mode 100644 index 82de47115..000000000 --- a/tests/semantic/fixtures/discard_keeps_helper.asm +++ /dev/null @@ -1,21 +0,0 @@ -; A pixel's discard as the console compiles it (tests/semantic/test_quad_helper_lanes.py): the killed lanes leave -; the live mask s2, a wave with no live lane left exits, and whole-quad mode turns the killed lanes of a quad with a -; live lane back on, as helpers for the survivors' quad reads. Quad lane 1 of every quad is killed here; each lane -; then reads quad lane 1's value v1 = 16 * lane + 5, and only the live lanes export it. -v_mbcnt_lo_u32_b32 v0, -1, 0 -v_lshlrev_b32 v1, 4, v0 -v_add_nc_u32 v1, 5, v1 -s_mov_b32 s2, exec_lo -v_and_b32 v8, 3, v0 -v_cmp_eq_u32_e32 vcc_lo, 1, v8 -s_andn2_b32 s2, s2, vcc_lo -s_cbranch_scc0 dead -s_wqm_b32 exec_lo, s2 -v_mov_b32_dpp v2, v1 quad_perm:[1,1,1,1] row_mask:0xf bank_mask:0xf -s_mov_b32 exec_lo, s2 -exp mrt0 v2, v2, v2, v2 done vm -s_endpgm -dead: -s_mov_b32 exec_lo, 0 -exp null off, off, off, off done vm -s_endpgm diff --git a/tests/semantic/fixtures/image_load_tfe.asm b/tests/semantic/fixtures/image_load_tfe.asm deleted file mode 100644 index c135373f8..000000000 --- a/tests/semantic/fixtures/image_load_tfe.asm +++ /dev/null @@ -1,14 +0,0 @@ -; tfe on an image_load (tests/semantic/test_mimg_tfe_status.py): the load returns its data and then one more dword, -; the fetch status, which is 0 for a resident texel. v5 and v9 are seeded with 1000 so a status the translation -; leaves alone shows. The T# is read from s[0:1]; the test's image returns one texel everywhere. -s_load_dwordx8 s[8:15], s[0:1], 0 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v2, 0 -v_mov_b32_e32 v3, 0 -v_mov_b32_e32 v5, 0x3e8 -v_mov_b32_e32 v9, 0x3e8 -image_load v[4:5], v[2:3], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm tfe -image_load v[6:9], v[2:3], s[8:15] dmask:0x7 dim:SQ_RSRC_IMG_2D unorm tfe -s_waitcnt vmcnt(0) -exp mrt0 v4, v5, v6, v9 done vm -s_endpgm diff --git a/tests/semantic/fixtures/loop_limit_back.asm b/tests/semantic/fixtures/loop_limit_back.asm deleted file mode 100644 index f4198ccff..000000000 --- a/tests/semantic/fixtures/loop_limit_back.asm +++ /dev/null @@ -1,12 +0,0 @@ -; --loop-limit, a loop closed by a branch back (tests/semantic/test_loop_limit.py). s4 counts the passes; the -; loop ends when s4 reaches s5, which comes from user data (push-constant dword 5). With s5 = 0 the end never -; comes, as in a loop over data the host has not mirrored yet (it reads as zeros). At the cap the branch back is -; not taken: the code after the loop runs and exports the count. -s_mov_b32 s4, 0 -loop: -s_add_u32 s4, s4, 1 -s_cmp_lg_u32 s4, s5 -s_cbranch_scc1 loop -v_mov_b32 v0, s4 -exp mrt0 v0, v0, v0, v0 done vm -s_endpgm diff --git a/tests/semantic/fixtures/loop_limit_barrier.asm b/tests/semantic/fixtures/loop_limit_barrier.asm deleted file mode 100644 index 4f071e64e..000000000 --- a/tests/semantic/fixtures/loop_limit_barrier.asm +++ /dev/null @@ -1,19 +0,0 @@ -; --loop-limit with a barrier after the loop (tests/semantic/test_loop_limit.py), a compute shader of two waves. -; The first wave (its first thread is thread 0) leaves the loop after 3 passes; the other waits for a count that -; never comes (s7 = 0) and ends with a jump back, so at the cap it leaves the program. It must not hold the first -; wave at s_barrier: a wave that has ended no longer counts (RDNA), and the barrier rounds count it done. -v_readfirstlane_b32 s6, v0 -s_cmp_eq_u32 s6, 0 -s_cselect_b32 s7, 3, 0 -s_mov_b32 s4, 0 -loop: -s_add_u32 s4, s4, 1 -s_cmp_eq_u32 s4, s7 -s_cbranch_scc1 done -s_branch loop -done: -s_barrier -v_mov_b32 v2, s4 -v_lshlrev_b32 v3, 2, v0 -buffer_store_dword v2, v3, s[0:3], 0 offen -s_endpgm diff --git a/tests/semantic/fixtures/loop_limit_jump.asm b/tests/semantic/fixtures/loop_limit_jump.asm deleted file mode 100644 index 18c440bf2..000000000 --- a/tests/semantic/fixtures/loop_limit_jump.asm +++ /dev/null @@ -1,13 +0,0 @@ -; --loop-limit, a loop that leaves from the middle and ends with a jump back (tests/semantic/test_loop_limit.py). -; s4 counts the passes; the exit is taken when s4 reaches s5 (push-constant dword 5). With s5 = 0 it never is. -; At the cap the jump back has no other way: the program ends there, and a pixel is discarded. -s_mov_b32 s4, 0 -loop: -s_add_u32 s4, s4, 1 -s_cmp_eq_u32 s4, s5 -s_cbranch_scc1 done -s_branch loop -done: -v_mov_b32 v0, s4 -exp mrt0 v0, v0, v0, v0 done vm -s_endpgm diff --git a/tests/semantic/fixtures/ms_w64_skeleton.asm b/tests/semantic/fixtures/ms_w64_skeleton.asm deleted file mode 100644 index c03925ed4..000000000 --- a/tests/semantic/fixtures/ms_w64_skeleton.asm +++ /dev/null @@ -1,50 +0,0 @@ -; SHADER-10 mesh tier B, shaped like the corpus' mesh entry (128 threads, two waves): the group index is the first -; lane's v5 >> 7 (v5 = group * 128 + thread), the thread index the wave id from s3[27:24] * 64 + the lane id; thread 0 -; sends the allocation (3 vertices, 1 primitive) under an s_cbranch_execz skip, where a vccnz on an all-or-none mask -; guards the null-primitive path and its s_barrier; then a barrier and the exports (threads 0..2: vertex t at -; x = t). No memory write: natively the barriers are left out. -s_mov_b64 exec, -1 -v_mbcnt_lo_u32_b32 v0, -1, 0 -v_readfirstlane_b32 s0, v5 -s_bfe_u32 s1, s3, 0x40018 -v_mbcnt_hi_u32_b32 v0, -1, v0 -s_lshr_b32 s10, s0, 7 -v_lshl_add_u32 v0, s1, 6, v0 -s_mov_b32 s32, 3 -s_mov_b32 s14, 1 -s_cmp_eq_u32 s10, 99 -s_cselect_b64 s[2:3], exec, 0 -v_cvt_f32_u32_e32 v1, v0 -v_mov_b32_e32 v2, 0 -v_mov_b32_e32 v3, 0.5 -v_mov_b32_e32 v4, 1.0 -v_mov_b32_e32 v10, 0x200400 -s_mov_b64 s[0:1], exec -v_cmpx_eq_u32_e32 0, v0 -s_cbranch_execz alloc_done -s_lshl_b32 s7, s14, 12 -s_or_b32 s6, s7, s32 -s_mov_b32 m0, s6 -s_sendmsg sendmsg(MSG_GS_ALLOC_REQ) -s_andn2_b64 vcc, exec, s[2:3] -s_cbranch_vccnz alloc_done -s_barrier -v_bfrev_b32_e32 v11, 1 -exp pos0 off, off, off, off done -exp prim v11, off, off, off done -alloc_done: -s_mov_b64 exec, s[0:1] -s_barrier -v_cmp_gt_u32_e32 vcc_lo, s14, v0 -s_and_saveexec_b64 s[6:7], vcc -s_cbranch_execz prims_done -exp prim v10, off, off, off done -prims_done: -s_mov_b64 exec, s[6:7] -v_cmp_gt_u32_e32 vcc_lo, s32, v0 -s_and_saveexec_b64 s[8:9], vcc -s_cbranch_execz verts_done -exp pos0 v1, v2, v3, v4 done -exp param0 v1, v10, v3, v4 -verts_done: -s_endpgm \ No newline at end of file diff --git a/tests/semantic/fixtures/quad_helper_reads.asm b/tests/semantic/fixtures/quad_helper_reads.asm deleted file mode 100644 index ca0a59871..000000000 --- a/tests/semantic/fixtures/quad_helper_reads.asm +++ /dev/null @@ -1,32 +0,0 @@ -; Quad reads and a waterfall in a wave32 pixel shader whose helper lanes (pixels of a quad outside the triangle) -; a driver may leave out of ballots and shuffles (tests/semantic/test_quad_helper_lanes.py). v1 = 16 * lane + 5, -; a value in every lane, helpers included: a helper computes what its pixel would. -v_mbcnt_lo_u32_b32 v0, -1, 0 -v_lshlrev_b32 v1, 4, v0 -v_add_nc_u32 v1, 5, v1 -s_wqm_b32 exec_lo, exec_lo -; Quad reads: a DPP broadcast of quad lane 1, a DPP8 reverse that stays in each quad, a ds_swizzle swap of the rows. -v_mov_b32_dpp v2, v1 quad_perm:[1,1,1,1] row_mask:0xf bank_mask:0xf -v_mov_b32_dpp v3, v1 dpp8:[3,2,1,0,7,6,5,4] -ds_swizzle_b32 v4, v1 offset:swizzle(QUAD_PERM,2,3,0,1) -s_waitcnt lgkmcnt(0) -; A waterfall over the lane number: each pass reads the first lane's value and runs the lanes that hold it, until -; EXEC is empty. v5 = the value a lane was run with. -s_mov_b32 s5, exec_lo -loop: -v_readfirstlane_b32 s4, v0 -v_cmp_eq_u32_e64 s6, s4, v0 -s_and_saveexec_b32 s7, s6 -v_mov_b32 v5, s4 -s_xor_b32 exec_lo, exec_lo, s7 -s_cbranch_execnz loop -s_mov_b32 exec_lo, s5 -; What quad lane 1 was run with, read by every lane of its quad. -v_mov_b32_dpp v6, v5 quad_perm:[1,1,1,1] row_mask:0xf bank_mask:0xf -v_lshlrev_b32 v7, 4, v0 -buffer_store_dword v2, v7, s[0:3], 0 offen -buffer_store_dword v3, v7, s[0:3], 0 offen offset:4 -buffer_store_dword v4, v7, s[0:3], 0 offen offset:8 -buffer_store_dword v6, v7, s[0:3], 0 offen offset:12 -exp mrt0 v1, v1, v1, v1 done vm -s_endpgm diff --git a/tests/semantic/fixtures/wave64_cmp_sgpr_pair.asm b/tests/semantic/fixtures/wave64_cmp_sgpr_pair.asm deleted file mode 100644 index 84c187eac..000000000 --- a/tests/semantic/fixtures/wave64_cmp_sgpr_pair.asm +++ /dev/null @@ -1,26 +0,0 @@ -; A wave64 compute program printed in wave32 syntax, as llvm-mc's gfx10 default prints the corpus: a VOP3 lane-mask -; destination or source is one SGPR (s4, s8, s12) where the wave64 hardware reads and writes the pair (s[4:5]). -; s5, s9 and s13 hold data first, which the 64-bit writes must replace. Lane l stores three words at 12 * l: -; +0: 1 where l < 40 (v_cmp_gt_u32_e64 s4, 40, l; then s[4:5] as a 64-bit SALU operand) -; +4: 9 where l is odd (v_cmp_e64 s8; v_cndmask_b32_e64 with the mask printed as s8) -; +8: carry of l + 0xffffffd0 (l >= 48), from v_add_co_u32_e64's carry printed as s12, read as the pair -s_mov_b64 s[6:7], exec -v_mbcnt_lo_u32_b32 v1, -1, 0 -v_mbcnt_hi_u32_b32 v1, -1, v1 -s_mov_b32 s5, 0 -s_mov_b32 s9, 0 -s_mov_b32 s13, 0 -v_cmp_gt_u32_e64 s4, 40, v1 -s_and_b64 vcc, exec, s[4:5] -v_cndmask_b32_e64 v2, 0, 1, vcc -v_and_b32_e32 v3, 1, v1 -v_cmp_eq_u32_e64 s8, 1, v3 -v_cndmask_b32_e64 v4, 0, 9, s8 -v_add_co_u32_e64 v5, s12, 0xffffffd0, v1 -s_and_b64 vcc, exec, s[12:13] -v_cndmask_b32_e64 v6, 0, 1, vcc -v_mul_u32_u24_e32 v7, 12, v1 -buffer_store_dword v2, v7, s[0:3], 0 offen -buffer_store_dword v4, v7, s[0:3], 0 offen offset:4 -buffer_store_dword v6, v7, s[0:3], 0 offen offset:8 -s_endpgm diff --git a/tests/semantic/support.py b/tests/semantic/support.py index e91cfa3b8..950890271 100644 --- a/tests/semantic/support.py +++ b/tests/semantic/support.py @@ -41,32 +41,6 @@ def translate_lines(name, lines, dxbc=STUB_DXBC, fssm=None): return translate_listing(name, text.encode("utf-8"), dxbc, fssm) -def asm_fixture(name): - """The instruction and label lines of the hand-written tests/semantic/fixtures/.asm (comments dropped).""" - with open(os.path.join(HERE, "fixtures", name + ".asm"), encoding="utf-8") as f: - return [ln.strip() for ln in f if ln.strip() and not ln.lstrip().startswith(";")] - - -def resolve_labels(lines, size=4): - """Instruction lines with `name:` labels, in the form translate_lines takes: every instruction gets a `size`-byte - placeholder encoding (the translator places instructions by their encodings) and a branch to a label gets its - signed dword offset from the next instruction (RDNA2 SOPP: target = PC + 4 + 4 * SIMM16).""" - labels, placed, pc = {}, [], 0 - for line in lines: - if line.endswith(":"): - labels[line[:-1]] = pc - continue - placed.append((line, pc)) - pc += size - out = [] - for line, at in placed: - words = line.split() - if words[0].startswith(("s_branch", "s_cbranch_")) and len(words) == 2 and words[1] in labels: - line = f"{words[0]} {(labels[words[1]] - at - size) // 4}" - out.append(f"{line} ; encoding: [{','.join(['0x00'] * size)}]") - return out - - def translate_listing(name, data, dxbc=STUB_DXBC, fssm=None): """SPIR-V assembly text for a listing in the translator's input format (bytes of a .s file).""" with tempfile.TemporaryDirectory() as tmp: diff --git a/tests/semantic/test_console_stage_wave32.py b/tests/semantic/test_console_stage_wave32.py deleted file mode 100644 index 91bb72fb3..000000000 --- a/tests/semantic/test_console_stage_wave32.py +++ /dev/null @@ -1,68 +0,0 @@ -"""The wave size of a console pipeline stage (device slot 57), which no header gives. - -Its wave32 code moves vcc as an SGPR pair with _b64 ops, which the loose code test reads as wave64, but its -*_saveexec_b32 exist only in wave32 code and it has none of the strict wave64 markers: such a vertex or pixel program -with an FSPX code file beside it is wave32, so its compare masks in vcc_hi translate. Hand-written program, no game -data. - - python -I tests/semantic/test_console_stage_wave32.py -v -""" -import gc -import os -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -from support import STUB_DXBC, rdna2spirv # noqa: E402 - -PROGRAM = [ - "s_mov_b64 vcc, 0", # vcc as a pair: the loose wave64 test - "s_or_saveexec_b32 s0, -1", # a wave32-only op: every lane stays on - "v_mov_b32_e32 v1, 1.0", - "v_mov_b32_e32 v2, 2.0", - "v_cmp_lt_f32_e64 vcc_hi, v1, v2", - "v_cndmask_b32_e64 v3, 0, 1.0, vcc_hi", - "v_mov_b32_e32 v4, 0", - "exp mrt0 v3, v4, v4, v4 done vm", - "s_endpgm", -] - - -def translate(name, lines, with_code): - text = f"; {name} hand-written test program\n" + "".join("\t" + ln + "\n" for ln in lines) - with tempfile.TemporaryDirectory() as tmp: - os.mkdir(os.path.join(tmp, "disasm")) - with open(os.path.join(tmp, "disasm", name + ".s"), "w", encoding="utf-8", newline="\n") as f: - f.write(text) - with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - if with_code: # the console stage's kind-6 bytes beside it, as tools/fspx_unpack.py writes them - os.mkdir(os.path.join(tmp, "fspx")) - with open(os.path.join(tmp, "fspx", name + ".code"), "wb") as f: - f.write(b"\0" * 64) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - result = rdna2spirv.translate(os.path.join(tmp, "disasm", name + ".s")) - gc.collect() - return result - - -class ConsoleStageWave32(unittest.TestCase): - def test_console_stage_is_wave32(self): - # Translated as wave32: its vcc_hi compare mask is accepted (as wave64 it is refused, the test below). The - # value through vcc_hi is test_vcmp_vcc_hi.py's; the saveexec here needs a subgroup this runner does not model. - spvasm = translate("ps_console_wave32", PROGRAM, with_code=True) - self.assertIn("%vcc_hi", spvasm) - - def test_without_a_code_file_it_stays_refused(self): - with self.assertRaises(rdna2spirv.Unsupported): - translate("ps_console_wave64", PROGRAM, with_code=False) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_ds_permute.py b/tests/semantic/test_ds_permute.py index 9924f382e..751c81ea6 100644 --- a/tests/semantic/test_ds_permute.py +++ b/tests/semantic/test_ds_permute.py @@ -83,16 +83,12 @@ class SwizzleExecTests(unittest.TestCase): for pattern in ("QUAD_PERM,1,0,3,2", "SWAP,1"): lines = [line.replace("QUAD_PERM,1,0,3,2", pattern) for line in instructions] spv = support.translate_lines("ps_swizzle_exec", lines) - # Both stay in the quad, so in a pixel shader they are quad operations (docs/design.md, "Quad-confined - # DPP and ds_swizzle in pixel shaders"). A pixel wave holds whole quads (Vulkan starts helpers for the - # uncovered pixels of one), so the partial waves run here have whole quads too; a lane absent from its - # quad, which only a compute shader has, is test_ds_swizzle_b32.py's case. - self.assertIn("OpGroupNonUniformQuadSwap", spv) - self.assertNotIn("OpGroupNonUniformShuffle", spv) - for lanes in (32, 8): + for lanes in (32, 7): with self.subTest(pattern=pattern, lanes=lanes): # Lane 0 reads disabled lane 1. Lane 1 keeps its destination. Lanes 2/3 exchange active data. expected = [0, 0x3f000000, 0x3f400000, 0x3f400000] * 8 + if lanes == 7: + expected[6] = 0 # translator's model for absent lane 7; unverified on hardware self.assertEqual(run(spv, lanes, 32), expected[:lanes]) diff --git a/tests/semantic/test_exec_computed.py b/tests/semantic/test_exec_computed.py index 88aa67f04..2c1a3a629 100644 --- a/tests/semantic/test_exec_computed.py +++ b/tests/semantic/test_exec_computed.py @@ -42,25 +42,6 @@ class ExecComputed(unittest.TestCase): old = self.OLD_PREFIX[name] self.assertNotEqual(got[:len(old)], old) - def test_wave64_emulated_words(self): - # --wave64-emulate takes the same EXEC write (exec_half_write), with no subgroup operation. - from test_wave64_emulate_opt import run_emulated_workgroup - sys.path.insert(0, os.path.join(support.ROOT, "runtime", "test", "shaders")) - from compute_fixture import compute_header - name = "cs_w64_exec_computed" - header = compute_header(os.path.join(support.ROOT, "runtime", "test", "shaders", name + ".asm")) - saved = support.rdna2spirv.WAVE64_EMULATE - support.rdna2spirv.WAVE64_EMULATE = True - try: - spv = support.translate_fixture(name, fssm=bytes(header)) - self.assertTrue(support.rdna2spirv.translate.last_gen.emulate) - finally: - support.rdna2spirv.WAVE64_EMULATE = saved - memory = {a: 0xEEEEEEEE for a in range(0, 0x100, 4)} - memory, _ = run_emulated_workgroup(spv, (64, 1, 1), push_constants=[0, 0, 0xFFFFFFFF, 0x31016FAC] + [0] * 28, - memory=memory) - self.assertEqual([memory[4 * i] for i in range(8)], self.WANT[name][1]) - def test_words_follow_from_the_masks(self): # Plain-Python reference: word = set lanes << 8 | lowest lane of each case's resulting EXEC. def word(m): diff --git a/tests/semantic/test_interp.py b/tests/semantic/test_interp.py index 0290c5914..f38fe2681 100644 --- a/tests/semantic/test_interp.py +++ b/tests/semantic/test_interp.py @@ -692,8 +692,7 @@ OpStore %f32_control %control "%res = OpLoad %uint %q\n"), 0xFFFFFFF0) def test_unsupported_constructs_are_rejected(self): - for body in ("%res = OpSDiv %uint %c2 %c1\n", # opcode not modelled - "%res = OpUDiv %uint %c2 %c0\n", # division by zero + for body in ("%res = OpUDiv %uint %c2 %c1\n", # opcode not modelled "%res = OpExtInst %uint %glsl Ldexp %c2 %c1\n", # ext inst not modelled "%res = OpBitFieldUExtract %uint %cFF %c32 %c1\n", # undefined per spec "%res = OpShiftLeftLogical %uint %cFF %c32\n", # undefined per spec @@ -708,12 +707,6 @@ OpStore %f32_control %control with self.assertRaises(si.UnsupportedConstruct): run_word(body) - def test_unsigned_division(self): - # OpUDiv / OpUMod (SPIR-V 3.32.13): unsigned quotient and remainder; the relabelled thread index of a - # wave64 compute shader run in halves splits into x, y, z with them (rdna2spirv.relabel_index) - self.assertEqual(run_word("%res = OpUDiv %uint %cFF %c32\n"), 0xFFFFFFFF // 32) - self.assertEqual(run_word("%res = OpUMod %uint %cFF %c32\n"), 0xFFFFFFFF % 32) - def test_store_to_push_constant_is_rejected(self): text = HEADER + "%p = OpAccessChain %_ptr_PC_uint %pc %c0\nOpStore %p %c1\n" + FOOTER with self.assertRaises(si.UnsupportedConstruct): diff --git a/tests/semantic/test_interp_p2_f16_opsel_dst.py b/tests/semantic/test_interp_p2_f16_opsel_dst.py deleted file mode 100644 index d5c83c974..000000000 --- a/tests/semantic/test_interp_p2_f16_opsel_dst.py +++ /dev/null @@ -1,83 +0,0 @@ -"""v_interp_p2_f16 with VOP3 OP_SEL[3]: the f16 result goes to the high half of the destination. - -llvm-mc can neither print nor assemble op_sel on this op (its `high` modifier is word 1 bit 8, the attribute's upper -half), so a listing shows the word without OP_SEL[3] (word 0 bit 14) where the console compiler set it (32 console -pipeline stages were refused on the printed-encoding check). The check now takes that one bit from the stored bytes and -the result is written to the high half, the low half kept. Hand-written program, no game data. - - python -I tests/semantic/test_interp_p2_f16_opsel_dst.py -v -""" -import os -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -from support import rdna2spirv, translate_listing # noqa: E402 - -# llvm-mc -mcpu=gfx1030 -show-encoding -PROGRAM = [ - ("v_mov_b32_e32 v5, 0", "80 02 0a 7e"), - ("v_interp_p1ll_f16 v3, v0, attr0.x", "03 00 42 d7 00 00 02 00"), - ("v_interp_p2_f16 v5, v1, attr0.x, v3", "05 00 5a d7 00 02 0e 04"), - ("exp mrt0 v5, v5, v5, v5 done vm", "0f 18 00 f8 05 05 05 05"), - ("s_endpgm", "00 00 81 bf"), -] -NAME = "ps_interp_p2_f16_opsel" - - -def listing(): - size = sum(len(bytes.fromhex(enc)) for _, enc in PROGRAM) - lines = [f"; {NAME} code 0x0..0x{size:x} (fspx), gfx1030, 0 invalid words"] - for text, enc in PROGRAM: - lines.append(f"\t{text:<40}; encoding: [{','.join(f'0x{b:02x}' for b in bytes.fromhex(enc))}]") - return ("\n".join(lines) + "\n").encode("utf-8") - - -def stored(bit_byte): - """The program's bytes with byte 1 of the v_interp_p2_f16 word set to `bit_byte` (0x40: OP_SEL[3]).""" - raw = b"" - for i, (_, enc) in enumerate(PROGRAM): - b = bytearray(bytes.fromhex(enc)) - if i == 2: - b[1] = bit_byte - raw += bytes(b) - return raw - - -def translate(code): - import tempfile, warnings, gc - with tempfile.TemporaryDirectory() as tmp: - for sub in ("disasm", "fspx"): - os.mkdir(os.path.join(tmp, sub)) - with open(os.path.join(tmp, "disasm", NAME + ".s"), "wb") as f: - f.write(listing()) - with open(os.path.join(tmp, "fspx", NAME + ".code"), "wb") as f: - f.write(code) - from support import STUB_DXBC - with open(os.path.join(tmp, NAME + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - out = rdna2spirv.translate(os.path.join(tmp, "disasm", NAME + ".s")) - gc.collect() - return out - - -class InterpP2F16OpSelDst(unittest.TestCase): - def test_op_sel_3_writes_the_high_half(self): - plain, high = translate(stored(0x00)), translate(stored(0x40)) - # The high-half write shifts the f16 result up by 16 and keeps the low half (mask 0xFFFF); the plain one - # keeps the high half (mask 0xFFFF0000) instead. - self.assertNotEqual(plain, high) - self.assertIn("OpShiftLeftLogical", high) - - def test_another_dropped_bit_is_still_refused(self): - with self.assertRaises(rdna2spirv.Unsupported): - translate(stored(0x20)) # OP_SEL[2]: not the destination bit - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_loop_limit.py b/tests/semantic/test_loop_limit.py deleted file mode 100644 index 7b8a74cc3..000000000 --- a/tests/semantic/test_loop_limit.py +++ /dev/null @@ -1,190 +0,0 @@ -"""--loop-limit (docs/design.md, "Loop iteration cap"): a translated loop runs at most N times per entry into it, -N = 128 in a pixel shader, 256 in a vertex, geometry or mesh shader and 4096 in a compute shader. Then a branch back -takes its other way out, and a loop with no other way (a jump back) leaves the program; a pixel is discarded. -The rule and the numbers are VIctory's (victory/crates/victory-shader/src/emit/lower.rs, LOOP_LIMIT and -count_iteration; commit 15b0091e8, the per-stage values from 570a941e9): loops over data the host had not mirrored -yet read zeros, ran about four billion times and lost the GPU. - -The fixtures are hand-written (tests/semantic/fixtures/loop_limit_*.asm, no game data). Each loop counts its passes -in s4 and ends when s4 reaches s5, a value from user data, so one program shows a loop below the cap (unchanged), -one whose end never comes (s5 = 0, as with data that reads as zeros) and one cut short above the cap. The expected -words follow from the rule alone: the first block of a loop runs at most N times, so a loop closed by a branch -back exports min(s5, N) for s5 >= 1 and N for s5 = 0, and a loop that jumps back exports s5 for 1 <= s5 <= N and -is discarded otherwise. - -The barrier fixture is a compute shader of two waves where only the second one never leaves its loop. That wave -must end at the cap without holding the first one at s_barrier: RDNA counts only waves that have not ended, and -the translation's barrier rounds (native wave32) and wave64 emulation rounds count a wave that left at the cap as -done. spirv_mini_interp.run_workgroup and test_wave64_emulate_opt.run_emulated_workgroup require every invocation -to reach each barrier at the same point, so a stall is an error here, not a hang. - - python -m unittest discover -s tests/semantic -p test_loop_limit.py -""" -import gc -import os -import struct -import tempfile -import unittest -import warnings - -import support -import spirv_mini_interp as si -import spirv_wave_interp as wi -from test_loop_ballot_barrier import run_compute_workgroup -from test_wave64_emulate_opt import run_emulated_workgroup - -rdna2spirv = support.rdna2spirv -VSHARP = [0, 0, 0x10000, 0x31016FAC] # raw buffer V#: base 0, num_records 0x10000 bytes - - -class Limits: - """Set rdna2spirv's --loop-limit (and --dispatch-loop / --wave64-emulate) for one translation.""" - - def __init__(self, structured=True, emulate=False, **limits): - self.want = (structured, emulate, limits) - - def __enter__(self): - self.saved = (rdna2spirv.STRUCTURED, rdna2spirv.WAVE64_EMULATE, dict(rdna2spirv.LOOP_LIMITS)) - structured, emulate, limits = self.want - rdna2spirv.STRUCTURED, rdna2spirv.WAVE64_EMULATE = structured, emulate - rdna2spirv.LOOP_LIMITS.update(limits) - return self - - def __exit__(self, *exc): - rdna2spirv.STRUCTURED, rdna2spirv.WAVE64_EMULATE, limits = self.saved - rdna2spirv.LOOP_LIMITS.clear() - rdna2spirv.LOOP_LIMITS.update(limits) - - -def ps_words(fixture, s5, **limits): - """mrt0 of the pixel-shader fixture with s5 from user data, or None when the pixel is discarded. The - dispatch-loop form (structured=False) has a switch, which spirv_wave_interp runs (lane 0 of a wave32).""" - with Limits(**limits): - spv = support.translate_lines("ps_" + fixture, support.resolve_labels(support.asm_fixture(fixture))) - if not limits.get("structured", True): - out = wi.run_wave(spv, wave=32, push_constants=[0] * 5 + [s5])["outputs"][0] - else: - out = si.run_fragment(spv, push_constants=[0] * 5 + [s5]) - return None if not out else list(out["%out_mrt0"]) - - -def cs_fssm(threads, wave): - """An FSSM header that says the wave size (u32 0xD4 bit 5: wave32) and the group: RSRC2 0x8088, threads x 1 x 1.""" - blob = bytearray(0x148) - blob[:4] = b"FSSM" - struct.pack_into("= 48 else None for lane in range(64)] - self.assertEqual(words, want) - - -class FlbitExec(unittest.TestCase): - def test_last_and_first_lane_of_the_wave(self): - spv, gen = tiers.translate("cs_flbit_exec", FLBIT_EXEC, emulate=False) - self.assertTrue(gen.wave64) - self.assertEqual(tiers.run(spv, 64, 64), [24] * 64) # flbit 63 - 39 = 24, ff1 0 - - -class AppendEmulated(unittest.TestCase): - def translate(self, op): - spv, gen = tiers.translate("cs_append_w64", append_program(op), tiers=False) - self.assertTrue(gen.wave64 and gen.emulate) - return spv - - def test_append_translates_with_one_counted_atomic(self): - spv = self.translate("ds_append") - # The emulation's own scheduler counts with OpAtomicIAdd too: the program adds exactly one. - base, _ = tiers.translate("cs_append_w64", append_program(None), tiers=False) - self.assertEqual(spv.count("OpAtomicIAdd") - base.count("OpAtomicIAdd"), 1) - self.assertIn("OpBitCount", spv) - - def test_consume_subtracts(self): - self.assertIn("OpAtomicISub", self.translate("ds_consume")) - - @unittest.skipUnless(shutil.which("spirv-as") and shutil.which("spirv-val"), "needs spirv-as and spirv-val") - def test_valid(self): - spv = self.translate("ds_append") - with tempfile.TemporaryDirectory() as tmp: - src, out = os.path.join(tmp, "a.spvasm"), os.path.join(tmp, "a.spv") - with open(src, "w", encoding="utf-8", newline="\n") as f: - f.write(spv) - for cmd in (["spirv-as", "--target-env", "vulkan1.3", src, "-o", out], - ["spirv-val", "--target-env", "vulkan1.3", out]): - r = subprocess.run(cmd, capture_output=True, text=True) - self.assertEqual(r.returncode, 0, r.stderr + r.stdout) - - def test_not_emulated_wave64_shuffles_within_the_subgroup(self): - # Upstream's ds_append (Gen.ds_append) also translates a wave64 that is not emulated: the old value reaches - # the other lanes by a subgroup shuffle from the first active lane, right in that lane's half on 32-wide - # subgroups (the cross-half approximation its docstring names). It was refused here before the two were merged. - spv, gen = tiers.translate("cs_append_w64", append_program("ds_append"), tiers=False, emulate=False) - self.assertTrue(gen.wave64 and not gen.emulate) - self.assertIn("OpGroupNonUniformShuffle", spv) - self.assertEqual(spv.count("OpAtomicIAdd"), 1) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_wave64_compute_tiers.py b/tests/semantic/test_wave64_compute_tiers.py deleted file mode 100644 index c9b4a5e91..000000000 --- a/tests/semantic/test_wave64_compute_tiers.py +++ /dev/null @@ -1,338 +0,0 @@ -"""SHADER-10 for compute and mesh: emulate a wave64 CS/MS only when its 32-lane halves are not exact as subgroups. - -With --wave64-emulate the translator runs tools/wave64_halves.py on every wave64 compute and mesh shader -(rdna2spirv.compute_halves, module flag WAVE64_TIERS that main() sets) and keeps the workgroup-memory emulation for -tier C only. Tiers A and B run natively, one console half per subgroup: the thread index comes from the subgroup -(SubgroupId * SubgroupSize + SubgroupLocalInvocationId), LDS or memory accesses the wave's lockstep ordered get a -workgroup barrier in front, and with no memory write at all s_barrier is left out (docs/design.md, "Wave64 compute -and mesh: partition invariance"). Hand-written programs (no game data): - - * Classification: the tier, reasons and idioms in the translator's result, and whether it emulated. - * Execution on spirv_mini_interp.run_workgroup: the native module on 32- and 64-wide subgroups, with invocations - placed in invocation order and in a shuffled order (a host that does not give a subgroup consecutive - LocalInvocationIndex values), and with the subgroups run one after another between barriers - (subgroup_order) instead of in lockstep. Expected words come from the ISA. Negative controls: the old native - translation (no relabelling) under the shuffled order, and the LDS program without its barrier. -""" -import os -import random -import re -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import support # noqa: E402 (path set above) -import spirv_mini_interp as si # noqa: E402 -import rdna2spirv # noqa: E402 - -VSHARP = [0, 0, 0x10000, 0x31016FAC] # a raw buffer at address 0 for s[0:3] -LANE_ID = ["v_mbcnt_lo_u32_b32 v1, -1, 0", "v_mbcnt_hi_u32_b32 v1, -1, v1"] -STORE = ["v_lshlrev_b32_e32 v21, 2, v0", "buffer_store_dword v4, v21, s[0:3], 0 offen"] - - -def fssm(threads): - """A compute FSSM header: RSRC2 with 4 user SGPRs, TGID_X and an LDS allocation of 128 dwords.""" - h = bytearray(0x148) - struct.pack_into("<4I", h, 0x138, 0x8088, threads, 1, 1) - return bytes(h) - - -def mesh_dxbc(threads=128, maxv=128, maxp=128): - psv = bytearray(48) - struct.pack_into("> 7, the thread index from -# the wave id in s3, the allocation by thread 0 under an execz skip with its null-primitive path behind a vccnz and -# an s_barrier, then a barrier and the exports. No memory write: the barriers are left out natively. -MS_SKELETON = support.asm_fixture("ms_w64_skeleton") - -# Tier C: the allocation's counts come from a lane count (each half would send its own). -MS_COUNTED = [ - "s_mov_b64 exec, -1", "v_mbcnt_lo_u32_b32 v0, -1, 0", "s_bfe_u32 s1, s3, 0x40018", - "v_mbcnt_hi_u32_b32 v0, -1, v0", "v_lshl_add_u32 v0, s1, 6, v0", "v_cmp_gt_u32_e32 vcc_lo, 70, v0", - "s_bcnt1_i32_b64 s32, vcc", "s_mov_b64 s[0:1], exec", "v_cmpx_eq_u32_e32 0, v0", "s_cbranch_execz done", - "s_mov_b32 m0, s32", "s_sendmsg sendmsg(MSG_GS_ALLOC_REQ)", "done:", "s_mov_b64 exec, s[0:1]", "s_barrier", - "s_endpgm"] - - -class Classification(unittest.TestCase): - def tier(self, name, lines, tier, reasons=(), idioms=None, threads=64, native=None): - spv, g = translate(name, lines, threads) - w = g.w64c - self.assertIsNotNone(w, name) - self.assertEqual((w["tier"], sorted(w["reasons"])), (tier, sorted(reasons)), f"{name}: {w['sites']}") - if idioms is not None: - self.assertEqual(sorted(w["idioms"]), sorted(idioms), name) - self.assertEqual(g.emulate, tier == "C", name) - self.assertEqual(g.relabel, tier != "C", name) - if tier == "C": - self.assertNotIn("OpGroupNonUniform", spv) - return spv, g - - def test_half_local_cross_lane_is_tier_a(self): - self.tier("cs_half_local", CS_HALF_LOCAL, "A", idioms=[]) - - def test_lds_exchange_in_a_one_wave_group_gets_a_barrier(self): - spv, g = self.tier("cs_lds_swap", CS_LDS_SWAP, "B", idioms=["wave-memory-order"]) - self.assertEqual(len(g.w64_sync), 1) - self.assertEqual(len(barriers(spv)), 1) - - def test_lds_exchange_under_a_lane_branch_is_tier_c(self): - self.tier("cs_lds_branch", CS_LDS_IN_BRANCH, "C", ["lds-in-wave"]) - - def test_readlane_of_varying_data_is_tier_c(self): - self.tier("cs_readlane40", CS_READLANE, "C", ["cross-lane"]) - - def test_wave_base_from_first_lane_thread_id(self): - self.tier("cs_wave_base", CS_WAVE_BASE, "B", idioms=["readfirstlane-wave-base"]) - # bits below 6 are the half's: a shift by 5 keeps the half (2 * wave + half), tier C - lines = [ln.replace("s_lshr_b32 s11, s10, 6", "s_lshr_b32 s11, s10, 5") for ln in CS_WAVE_BASE] - self.tier("cs_wave_half", lines, "C", ["first-lane"]) - # x is D + lane only when the group's x size is a multiple of 64 - spv, g = translate("cs_wave_base32", CS_WAVE_BASE, threads=32) - self.assertEqual(g.w64c["tier"], "C") - - def test_barrier_in_a_scalar_loop_runs_in_rounds(self): - spv, g = self.tier("cs_bar_loop", CS_BARRIER_LOOP, "A", threads=128) - self.assertTrue(g.bar_rounds) - self.assertFalse(g.w64_sync) - - def test_barrier_a_vote_decides_is_tier_c(self): - self.tier("cs_vote_barrier", CS_VOTE_BARRIER, "C", ["vote-barrier"], threads=128) - - def test_scalar_load_of_a_stored_word_is_tier_c(self): - self.tier("cs_store_sload", CS_STORE_SLOAD, "C", ["mem-in-wave"]) - - def test_uniform_compare_under_a_narrowed_exec(self): - self.tier("cs_uniform_exec", CS_UNIFORM_UNDER_EXEC, "A", idioms=[]) - # without the execz in front, a half whose lanes are all off votes no while the wave votes yes - lines = [ln for ln in CS_UNIFORM_UNDER_EXEC if ln != "s_cbranch_execz done"] - self.tier("cs_uniform_noexecz", lines, "C", ["unsafe-vote-branch"]) - - def test_partial_subgroup_group_size_is_tier_c(self): - self.tier("cs_group48", CS_HALF_LOCAL, "C", ["group-size"], threads=48) - - def test_mesh_skeleton(self): - spv, g = self.tier("ms_skeleton", MS_SKELETON, "B", threads=128, - idioms=["readfirstlane-wave-base"]) - self.assertTrue(g.drop_barriers) - self.assertIn("%mli = OpCopyObject %uint %rl_t", spv) - self.assertNotIn("OpLoad %uint %local_index", spv) - self.assertEqual(sum("OpControlBarrier" in ln for ln in spv.splitlines()), 1) # the epilogue's own - - def test_mesh_allocation_from_a_lane_count_is_tier_c(self): - spv, g = translate("ms_counted", MS_COUNTED, 128) - self.assertEqual(g.w64c["tier"], "C") - self.assertIn("tainted-message", g.w64c["reasons"]) - self.assertTrue(g.emulate) - - def test_without_tiers_every_shader_is_emulated(self): - for name, lines in (("cs_half_local_all", CS_HALF_LOCAL), ("ms_skeleton_all", MS_SKELETON)): - with self.subTest(name): - _, g = translate(name, lines, 128 if name.startswith("ms") else 64, tiers=False) - self.assertTrue(g.emulate) - self.assertIsNone(g.w64c) - - -class Execution(unittest.TestCase): - def test_half_local_is_exact_in_halves_and_any_placement(self): - spv, _ = translate("cs_half_local", CS_HALF_LOCAL) - for sg in (64, 32): - for perm in (None, shuffled(64)): - for order in (None, [1, 0]): - with self.subTest(subgroup=sg, shuffled=perm is not None, order=order): - self.assertEqual(run(spv, 64, sg, perm, order), HALF_LOCAL_WORDS) - - def test_relabelling_is_what_makes_the_shuffled_placement_exact(self): - # negative control: the native translation without tiers takes the lane from LocalInvocationIndex and the - # shuffle from the subgroup lane, which disagree once a subgroup is not 32 consecutive threads - spv, g = translate("cs_half_local_native", CS_HALF_LOCAL, emulate=False, tiers=False) - self.assertFalse(g.relabel) - self.assertEqual(run(spv, 64, 32), HALF_LOCAL_WORDS) - self.assertNotEqual(run(spv, 64, 32, shuffled(64)), HALF_LOCAL_WORDS) - - def test_lds_exchange_with_and_without_its_barrier(self): - spv, _ = translate("cs_lds_swap", CS_LDS_SWAP) - for sg in (64, 32): - for order in (None, [1, 0], [0, 1]): - with self.subTest(subgroup=sg, order=order): - self.assertEqual(run(spv, 64, sg, shuffled(64, 3), order), LDS_SWAP_WORDS) - # negative control: drop the barrier; the upper half, run first, reads words the lower half has not written - bare = spv - for ln in barriers(spv): - bare = bare.replace(ln + "\n", "") - self.assertEqual(len(barriers(bare)), 0) - with self.assertRaises((AssertionError, si.UndefinedResult, si.UnsupportedConstruct, TypeError)): - self.assertEqual(run(bare, 64, 32, None, [1, 0]), LDS_SWAP_WORDS) - - def test_uniform_compare_under_exec_is_exact(self): - spv, _ = translate("cs_uniform_exec", CS_UNIFORM_UNDER_EXEC) - for s20 in (3, 9): - want = [7 if t < 40 and s20 >= 5 else 1 for t in range(64)] - push = VSHARP + [0] * 16 + [s20] + [0] * 11 - for sg in (64, 32): - with self.subTest(s20=s20, subgroup=sg): - memory = {} - si.run_workgroup(spv, 64, sg, push_constants=push, memory=memory, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), - "%sg_lane": i % sg, "%sg_id": i // sg, "%sg_size": sg}) - self.assertEqual([memory.get(4 * k) for k in range(64)], want) - - def test_wave_base(self): - spv, _ = translate("cs_wave_base", CS_WAVE_BASE, threads=128) - for sg in (64, 32): - with self.subTest(subgroup=sg): - self.assertEqual(run(spv, 128, sg, shuffled(128, 5)), [t // 64 for t in range(128)]) - - def test_mesh_skeleton_exports(self): - spv, _ = translate("ms_skeleton", MS_SKELETON, 128) - for sg in (64, 32): - for perm in (None, shuffled(128, 7)): - with self.subTest(subgroup=sg, shuffled=perm is not None): - # thread 0's subgroup alone runs the allocation: subgroups in turn, not in lockstep - outs = run(spv, 128, sg, perm, order=list(range(128 // sg)), mesh=True) - self.assertEqual({o["OpSetMeshOutputsEXT"] for o in outs}, {(3, 1)}) - pos = {} - for i, o in enumerate(outs): - t = perm[i] if perm else i # the relabelled thread index of invocation i - words = o["%ms_out_pos"] - if t < 3: - pos[t] = words[4 * t:4 * t + 4] - self.assertEqual(sorted(pos), [0, 1, 2]) - for t, w in pos.items(): - self.assertEqual(struct.unpack("= 48)] for lane in range(64)] - - -class MaskPairs(unittest.TestCase): - def test_wave32_syntax_writes_and_reads_the_pair(self): - self.assertEqual(run(support.asm_fixture("wave64_cmp_sgpr_pair")), WANT) - - def test_same_as_the_pairs_spelled_out(self): - lines = support.asm_fixture("wave64_cmp_sgpr_pair") - spelled = [ln.replace("_e64 s4,", "_e64 s[4:5],").replace("_e64 v4, 0, 9, s8", "_e64 v4, 0, 9, s[8:9]") - .replace("_e64 s8,", "_e64 s[8:9],").replace("v5, s12,", "v5, s[12:13],") for ln in lines] - self.assertNotEqual(spelled, lines) - self.assertEqual(run(spelled), WANT) - - def test_wave32_keeps_one_sgpr(self): - # wave32 (FSSM flag): the same compare writes s4 alone; s5 keeps its 0, read as data by the 64-bit op - lines = [ln for ln in support.asm_fixture("wave64_cmp_sgpr_pair") if not ln.startswith("s_mov_b64")] - lines = [ln.replace("s_and_b64 vcc, exec, s[4:5]", "s_and_b32 vcc_lo, exec_lo, s4") - .replace("s_and_b64 vcc, exec, s[12:13]", "s_and_b32 vcc_lo, exec_lo, s12") - .replace("v_mbcnt_hi_u32_b32 v1, -1, v1", "s_nop 0") for ln in lines] - got = run(lines, threads=32, wave=32) - self.assertEqual(got, WANT[:32]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_acphal_abi.py b/tests/test_acphal_abi.py index 79615c8b7..828b95021 100644 --- a/tests/test_acphal_abi.py +++ b/tests/test_acphal_abi.py @@ -38,9 +38,7 @@ class TestAcpHalAbi(unittest.TestCase): self.assertIn(f'"{exp}"', content, f"acphal.dll SHIM_TABLE must register export {exp}") def test_shape_contexts_layout_matches_gdk_and_retail_offset(self): - """SHAPE_CONTEXTS layout: 6 dwords, 6 pointers with xmaContextArray at +0x38 (retail measurement), then 6 - 32-bit device addresses: 0x60 bytes, as VIctory measured it (victory/crates/victory-hle/src/modules/audio.rs, - ShapeContexts). Device addresses are 32-bit everywhere the executable uses them (docs/audio_hal_exe_calls.md).""" + """SHAPE_CONTEXTS layout: 6 dwords, then 6 pointers, with xmaContextArray at +0x38 (retail measurement).""" # SHAPE_CONTEXTS: # uint32_t numSrcContexts; // offset 0 # uint32_t numEqCompContexts; // offset 4 @@ -54,15 +52,15 @@ class TestAcpHalAbi(unittest.TestCase): # void* dmaContextArray; // offset 48 (0x30) # void* xmaContextArray; // offset 56 (0x38) - 5th pointer, checked at +0x38! # void* pcmContextArray; // offset 64 (0x40) - # APU_ADDRESS apuSrcContextArray; // offset 72 (0x48), 32-bit - # APU_ADDRESS apuEqComp... // offset 76 (0x4c) - # APU_ADDRESS apuFiltVol... // offset 80 (0x50) - # APU_ADDRESS apuDma... // offset 84 (0x54) - # APU_ADDRESS apuXma... // offset 88 (0x58) - # APU_ADDRESS apuPcm... // offset 92 (0x5c) - # Total size: 96 bytes (0x60) - layout_format = "<6I6Q6I" - self.assertEqual(struct.calcsize(layout_format), 0x60) + # APU_ADDRESS apuSrcContextArray; // offset 72 (0x48) + # APU_ADDRESS apuEqComp... // offset 80 (0x50) + # APU_ADDRESS apuFiltVol... // offset 88 (0x58) + # APU_ADDRESS apuDma... // offset 96 (0x60) + # APU_ADDRESS apuXma... // offset 104 (0x68) + # APU_ADDRESS apuPcm... // offset 112 (0x70) + # Total size: 120 bytes (0x78) + layout_format = "<6I6Q6Q" + self.assertEqual(struct.calcsize(layout_format), 120) # Offset of 5th pointer (xmaContextArray): 6 * 4 + 4 * 8 = 24 + 32 = 56 = 0x38 xma_ptr_offset = 6 * 4 + 4 * 8 @@ -72,10 +70,8 @@ class TestAcpHalAbi(unittest.TestCase): with open(self.acphal_cpp, "r", encoding="utf-8") as f: content = f.read() - self.assertIn("static_assert(sizeof(SHAPE_CONTEXTS) == 0x60", content) + self.assertIn("static_assert(sizeof(SHAPE_CONTEXTS) == 120", content) self.assertIn("static_assert(offsetof(SHAPE_CONTEXTS, xmaContextArray) == 0x38", content) - self.assertIn("static_assert(offsetof(SHAPE_CONTEXTS, apuSrcContextArray) == 0x48", content) - self.assertIn("using APU_ADDRESS = uint32_t;", content) self.assertIn("static_assert(sizeof(SHAPE_XMA_CONTEXT) == 64", content) self.assertIn("static_assert(sizeof(SHAPE_SRC_CONTEXT) == 32", content) self.assertIn("static_assert(sizeof(SHAPE_EQCOMP_CONTEXT) == 352", content) @@ -106,19 +102,6 @@ class TestAcpHalAbi(unittest.TestCase): ps1 = f.read() self.assertIn("shims\\acphal.cpp", ps1) - def test_audio_shims_and_decoder_are_in_both_builds(self): - """acphal.cpp needs the XMA decoder sources, and xapu/chad are shims of their own: gta6rt in CMakeLists.txt and - the cl.exe fallback in build_runtime.ps1 must both list them, and CTest must run their tests.""" - with open(self.cmakelists, "r", encoding="utf-8") as f: - cmake = f.read() - with open(self.build_ps1, "r", encoding="utf-8") as f: - ps1 = f.read() - for source in ("shims/xapu.cpp", "shims/chad_dsp.cpp", "src/xma_decode.cpp", "src/xma_context.cpp"): - self.assertIn(source, cmake) - self.assertIn(source.replace("/", "\\"), ps1) - for test in ("acphal", "xapu", "chad_dsp", "xma"): - self.assertIn(f"add_test(NAME {test} COMMAND {test}_test)", cmake) - if __name__ == "__main__": unittest.main() diff --git a/tests/test_anim_glb.py b/tests/test_anim_glb.py index dde629c00..399586737 100644 --- a/tests/test_anim_glb.py +++ b/tests/test_anim_glb.py @@ -673,15 +673,6 @@ class ExportTest(unittest.TestCase): "--part", hex(self.offsets[1]), "--report", self.packs) self.assertEqual(r.returncode, 2) - def test_same_nonexistent_glb_and_report_paths_are_refused(self): - out = os.path.join(self.tmp.name, "not-created", "same.glb") - r = self.run_tool(self.packs, out, "--skeleton", hex(self.offsets[0]), "--part", hex(self.offsets[1]), - "--report", out) - self.assertEqual(r.returncode, 2, r.stderr) - self.assertIn("the GLB and the report are the same path", r.stderr) - self.assertFalse(os.path.exists(out)) - self.assertFalse(os.path.exists(os.path.dirname(out))) - def test_report_directory_is_refused_before_writing_a_glb(self): out = os.path.join(self.tmp.name, "out.glb") report = os.path.join(self.tmp.name, "report") diff --git a/tests/test_audio_wav.py b/tests/test_audio_wav.py index e82f57997..21269cdd8 100644 --- a/tests/test_audio_wav.py +++ b/tests/test_audio_wav.py @@ -378,22 +378,9 @@ class GranuleTest(unittest.TestCase): path = Path(tmp, "sample.ogg") for name, first, last, expected in cases: with self.subTest(name=name): - tags = awc_opus.ogg_page(10, 1, 0, [b"OpusTags" + bytes(8)], 0) - path.write_bytes(first + tags + last) + path.write_bytes(first + last) self.assertEqual(audio_wav.ogg_output_samples(path), expected) - def test_page_sequence_must_be_contiguous_for_explicit_trim(self): - head = b"OpusHead" + struct.pack("", "", ""): - with self.subTest(ignored=ignored): - xml = active.replace("", "" + ignored) - path = self.write(tmp, "list.xml", xml) - self.assertEqual(names_mod.read_mount_lists([path]), ["A.bk2", "C.bk2"]) - def test_name_without_extension_compared(self): # "ab" is a prefix of "ab-1", so it sorts first; with the extension '-' (0x2D) < '.' (0x2E) would flip them self.assertEqual(sorted(["f/ab-1.bk2", "f/ab.bk2"], key=names_mod.sort_key), ["f/ab.bk2", "f/ab-1.bk2"]) @@ -575,24 +565,6 @@ class TestReportErrors(unittest.TestCase): code = names_mod.main([source, "--mount", xml, "--out", out]) return code, err.getvalue(), out - def test_duplicate_stream_locations_are_not_named_twice(self): - with tempfile.TemporaryDirectory() as tmp: - movie = stream(12, source="clips/one.rpf") - other = stream(12, source="clips/two.rpf") - index = self.write(tmp, "index.json", json.dumps({"streams": [other, movie]})) - self.assertEqual(len(names_mod.load_streams(index)), 2) - duplicate = dict(movie, source="clips\\one.rpf", frames=movie["frames"] + 1) - self.write(tmp, "index.json", json.dumps({"streams": [movie, other, duplicate]})) - output = self.write(tmp, "names.csv", "previous report") - xml = self.write(tmp, "list.xml", mount_xml(["a.bk2", "b.bk2", "c.bk2"])) - err = io.StringIO() - with contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()): - rc = names_mod.main([index, "--mount", xml, "--out", output]) - self.assertEqual(rc, 1) - self.assertIn("duplicate stream location", err.getvalue()) - with open(output, encoding="utf-8") as fh: - self.assertEqual(fh.read(), "previous report") - def test_bad_sources_are_rejected(self): # (extension, contents, expected error fragment or None to only require the path) cases = [ diff --git a/tests/test_build_runtime_cmake.py b/tests/test_build_runtime_cmake.py index 64a2f38f3..c7685a521 100644 --- a/tests/test_build_runtime_cmake.py +++ b/tests/test_build_runtime_cmake.py @@ -35,9 +35,7 @@ class Recorder { class CMakeBatchTest(unittest.TestCase): @classmethod def setUpClass(cls): - # A recorder.exe a child has just run can stay locked for a moment on Windows (antivirus, a late handle - # close); a failed cleanup must not replace the result of the case that used it. - cls.temp = tempfile.TemporaryDirectory(prefix="leonida_cmake_", ignore_cleanup_errors=True) + cls.temp = tempfile.TemporaryDirectory(prefix="leonida_cmake_") cls.addClassCleanup(cls.temp.cleanup) cls.base = Path(cls.temp.name) source = cls.base / "recorder.cs" @@ -95,7 +93,7 @@ class CMakeBatchTest(unittest.TestCase): for extension in (".exe", ".cmd", ".bat"): for fail in ("", "configure", "build"): with self.subTest(folder=name, extension=extension, fail=fail): - with tempfile.TemporaryDirectory(dir=self.base, ignore_cleanup_errors=True) as tmp: + with tempfile.TemporaryDirectory(dir=self.base) as tmp: folder = Path(tmp) / name folder.mkdir() result, src, out, ninja = self.run_build(folder, extension, fail) diff --git a/tests/test_bvh_index.py b/tests/test_bvh_index.py index 92386ae69..b4903d88e 100644 --- a/tests/test_bvh_index.py +++ b/tests/test_bvh_index.py @@ -119,17 +119,6 @@ class ClassifyTest(unittest.TestCase): self.assertTrue(row["root_node_invalid"]) self.assertEqual(row["root_node_type_name"], "invalid") - def test_truncated_head_on_208_byte_payload_does_not_crash(self): - for truncated in (b"\0" * 10, instance_payload()[:0x20]): - row = bvh_index.classify(truncated, 208) - self.assertEqual(row["kind"], "raw") - self.assertEqual(row["signature"], "truncated-head") - self.assertTrue(row["truncated_head"]) - # With >= 0x30 bytes, a capped 208-byte instance record falls back to its 48-byte descriptor prefix cleanly. - row = bvh_index.classify(instance_payload()[:128], 208) - self.assertEqual(row["kind"], "descriptor") - self.assertEqual(row["signature"], "desc:0x5000xxxx") - def test_bvh4_chunk(self): b = bytearray(65536) struct.pack_into(" int: return bits & pr.M32 -_SWEEP_WORDS: dict[str, list[int]] = {} - - -def _sweep_words(op: str) -> list[int]: - # expected_sweep_words is exact rational arithmetic over 65,536 inputs and takes over a second; - # FakeOracle needs it for every sweep kernel, so compute it once per op. Callers slice a copy. - if op not in _SWEEP_WORDS: - _SWEEP_WORDS[op] = pr.expected_sweep_words(op) - return _SWEEP_WORDS[op] - - def _eval_f16_src_mod(bits16: int, expr: str) -> int: bits16 &= pr.M16 if "|" in expr: @@ -78,7 +67,7 @@ class FakeOracle: base_word = int(m_sweep.group(1)) m_op = re.search(r"(v_cvt_norm_[iu]16_f16)_e64", joined) assert m_op is not None, joined - res = _sweep_words(m_op.group(1))[base_word : base_word + 16384] + res = pr.expected_sweep_words(m_op.group(1))[base_word : base_word + 16384] if self.bad_word: res[0] ^= 1 if self.wave64_diff and k.wave == 64: diff --git a/tests/test_dds_png.py b/tests/test_dds_png.py index 1e80aa8c9..4d800b25b 100644 --- a/tests/test_dds_png.py +++ b/tests/test_dds_png.py @@ -1268,26 +1268,6 @@ class HalfFloatTests(unittest.TestCase): raw = zlib.decompress(b"".join(p for t, p, _ in chunks if t == b"IDAT")) self.assertEqual(raw[1:], bytes((255, 0, 128, 255, 0, 255, 64, 128))) - def test_cli_cleanup_restores_write_mode_on_replace_failure(self): - payload = halves(0x3C00, 0x0000, 0x3800, 0x3C00, 0x7E00, 0x7C00, 0x3400, 0x3800) - with tempfile.TemporaryDirectory() as tmp: - src = os.path.join(tmp, "in.dds") - dst = os.path.join(tmp, "out.png") - with open(src, "wb") as f: - f.write(dds_buffer(2, 1, payload, pitch=16, dxgi=10, **HALF_FLOAT)) - chmod_calls = [] - real_chmod = os.chmod - - def track_chmod(p, mode, **kwargs): - chmod_calls.append((p, mode)) - return real_chmod(p, mode, **kwargs) - - with mock.patch.object(dds.os, "replace", side_effect=OSError("replace failed")), \ - mock.patch.object(dds.os, "chmod", side_effect=track_chmod): - ret = dds.main([src, dst]) - self.assertEqual(ret, 1) - self.assertTrue(any(mode == 0o600 for p, mode in chmod_calls)) - if __name__ == "__main__": unittest.main() diff --git a/tests/test_f32_fuzz.py b/tests/test_f32_fuzz.py index 1a06fe590..627936938 100644 --- a/tests/test_f32_fuzz.py +++ b/tests/test_f32_fuzz.py @@ -81,18 +81,6 @@ class HarnessTests(unittest.TestCase): status, detail = ff.check(op, vals, [(0, {})], True, mods) self.assertEqual(status, "match", detail) - def test_legacy_mul_omod_turns_an_underflowed_minus_zero_into_plus_zero(self): - # f32_fuzz --programs 1500 --seed 53, program 246: the product underflows to -0 and mul:2 makes it +0 under - # the game MODE, which the translator models for v_mul_legacy_f32 (docs/design.md); the model said -0. - vals = [0] * 9 - vals[1], vals[3] = 0x1DA20776, 0x819D422D - srcs = [(1, {}), (3, {})] - for mods in (["mul:2"], ["mul:4"], ["div:2"]): - with self.subTest(mods=mods): - self.assertEqual(ff.check("v_mul_legacy_f32", vals, srcs, True, mods), ("match", None)) - self.assertEqual(ff.model("v_mul_legacy_f32", vals, srcs, ["mul:2"])[0], 0x80000000) # hw side unchanged - self.assertEqual(ff.check("v_mul_f32", vals, srcs, True, ["mul:2"]), ("match", None)) # keeps -0 - def test_undefined_spirv_is_its_own_class(self): vals = [0] + [0] * 8 # v_rcp_f32 of +0: hardware +inf, OpFDiv by zero status, _ = ff.check("v_rcp_f32", vals, [(0, {})], False, []) diff --git a/tests/test_file_mode.py b/tests/test_file_mode.py index 8ba753ca3..7bc1846d8 100644 --- a/tests/test_file_mode.py +++ b/tests/test_file_mode.py @@ -96,19 +96,6 @@ class NoUmaskFlipTests(unittest.TestCase): os.chmod(path, 0o604) self.assertEqual(file_mode.published_mode(path), 0o604) - def test_new_file_mode_restores_write_permission_before_probe_removal(self): - with tempfile.TemporaryDirectory() as directory: - chmod_calls = [] - real_chmod = os.chmod - - def track_chmod(p, mode, **kwargs): - chmod_calls.append((p, mode)) - return real_chmod(p, mode, **kwargs) - - with mock.patch("file_mode.os.chmod", side_effect=track_chmod): - file_mode.new_file_mode(directory) - self.assertTrue(any(mode == 0o600 for p, mode in chmod_calls)) - if __name__ == "__main__": unittest.main() diff --git a/tests/test_glb_writer.py b/tests/test_glb_writer.py index 322d770d9..89a87ef16 100644 --- a/tests/test_glb_writer.py +++ b/tests/test_glb_writer.py @@ -1148,23 +1148,6 @@ class TestGlbWriterMainCli(unittest.TestCase): with open(obj_path, encoding="utf-8", newline="") as f: self.assertEqual(f.read(), text) - def test_write_glb_cleanup_restores_write_mode_on_replace_failure(self): - with tempfile.TemporaryDirectory() as tmp_dir: - out_glb = os.path.join(tmp_dir, "out.glb") - prim = _simple_triangle_primitive() - chmod_calls = [] - real_chmod = os.chmod - - def track_chmod(p, mode, **kwargs): - chmod_calls.append((p, mode)) - return real_chmod(p, mode, **kwargs) - - with mock.patch("glb_writer._replace", side_effect=OSError("replace failed")), \ - mock.patch("glb_writer.os.chmod", side_effect=track_chmod): - with self.assertRaises(OSError): - glb_writer.write_glb(out_glb, [prim]) - self.assertTrue(any(mode == 0o600 for p, mode in chmod_calls)) - if __name__ == "__main__": unittest.main() diff --git a/tests/test_gpu_test_timeout.py b/tests/test_gpu_test_timeout.py index a0420f925..d290862ee 100644 --- a/tests/test_gpu_test_timeout.py +++ b/tests/test_gpu_test_timeout.py @@ -99,13 +99,9 @@ class HungProgram(unittest.TestCase): self.assertIn("0/1 passed", out.getvalue()) def test_quick_program_is_unaffected(self): - # A limit is still in force, but not the hang cases' 0.5 s: starting a Python child alone can take longer than - # that on a loaded Windows host, which killed the quick program and failed this test for the wrong reason. - with patch.dict(os.environ, {"LEONIDA_GPU_TEST_TIMEOUT": "60"}): - self.assertEqual(check.gpu_test_timeout(), 60) - self.assertEqual(run_gpu_tests.run_cmd(QUICK), (0, "ok")) - rc, out = check.run(*QUICK) - self.assertEqual((rc, out.strip()), (0, "ok")) + self.assertEqual(run_gpu_tests.run_cmd(QUICK), (0, "ok")) + rc, out = check.run(*QUICK) + self.assertEqual((rc, out.strip()), (0, "ok")) def test_translator_step_has_no_limit(self): seen = {} diff --git a/tests/test_instance_lists.py b/tests/test_instance_lists.py index ce7b0251e..1e8f32098 100644 --- a/tests/test_instance_lists.py +++ b/tests/test_instance_lists.py @@ -264,22 +264,6 @@ class ArchiveTests(unittest.TestCase): with open(path, "rb") as fh: self.assertEqual(fh.read(), data) - def test_case_only_spelling_of_a_missing_report_is_one_path(self): - # normcase keeps case on macOS, and samefile cannot see a file that has not been created. - with tempfile.TemporaryDirectory() as tmp: - folder = os.path.join(tmp, "Reports") - os.mkdir(folder) - probe = os.path.join(folder, "Probe.tmp") - with open(probe, "wb"): - pass - insensitive = os.path.exists(os.path.join(folder, "probe.tmp")) - os.remove(probe) - if not insensitive: - self.skipTest("volume keeps case") - first = os.path.join(tmp, "Reports", "out.json") - second = os.path.join(tmp, "reports", "out.json") - self.assertTrue(il.same_output_path(first, second)) - def test_json_that_is_a_directory_is_refused_before_the_scan(self): with tempfile.TemporaryDirectory() as tmp: path, _ = self._archive(tmp) diff --git a/tests/test_leonida_mods.py b/tests/test_leonida_mods.py index 41f3388ec..6204e9c9f 100644 --- a/tests/test_leonida_mods.py +++ b/tests/test_leonida_mods.py @@ -73,32 +73,6 @@ class ManifestTests(unittest.TestCase): bad({"archetype_swaps": "all"}, '"archetype_swaps" must be a list') bad([1, 2], "not a JSON object") - def test_lua_mods_are_listed_without_swaps_and_scripts_stay_in_the_folder(self): - lua = leonida_mods.validate_manifest({"name": "Lua", "script": "main.lua", "enabled": False}, "lua_mod") - self.assertEqual((lua.script, lua.enabled, lua.swaps, lua.warnings), ("main.lua", False, [], [])) - both = leonida_mods.validate_manifest( - {"script": "src/main.lua", "archetype_swaps": [{"from": "cs_mandy", "to": "cs_lucia"}]}, "both") - self.assertEqual((both.script, len(both.swaps)), ("src/main.lua", 1)) - # An asset mod still warns that it changes nothing without swaps. - self.assertTrue(leonida_mods.validate_manifest({}, "plain").warnings) - for script in ("../main.lua", "/main.lua", "C:main.lua", "a" + chr(92) + "b.lua", "main.txt", "", 3): - with self.assertRaises(leonida_mods.ModsError, msg=repr(script)): - leonida_mods.validate_manifest({"script": script}, "bad") - - def test_a_lua_mod_in_the_list_and_the_json_report(self): - with tempfile.TemporaryDirectory() as tmp: - mods = Path(tmp) / "mods" - write_json(mods / "lua_mod" / "mod.json", {"name": "Lua", "script": "main.lua"}) - code, out, err = cli("--dir", str(mods), "list") - self.assertEqual((code, err), (0, "")) - self.assertIn("lua_mod: Lua [enabled; Lua main.lua]", out) - self.assertIn("script main.lua is not in the mod folder", out) - (mods / "lua_mod" / "main.lua").write_text("-- empty" + chr(10), encoding="utf-8", newline="") - code, out, err = cli("--dir", str(mods), "list", "--json") - self.assertEqual(code, 0, err) - report = json.loads(out)["mods"][0] - self.assertEqual((report["script"], report["warnings"]), ("main.lua", [])) - class ManagerTests(unittest.TestCase): def test_new_list_enable_disable_and_uninstall(self): @@ -260,13 +234,6 @@ class SamplesAndGuiTests(unittest.TestCase): active = leonida_mods.active_swaps(mods) self.assertEqual(active, {0xE472B687: by_folder["mandy_prison_intro"].swaps[0]}) - def test_the_lua_example_mod_is_listed_and_disabled(self): - mods, errors = leonida_mods.load_mods(str(ROOT / "mods")) - self.assertEqual(errors, []) - example = {m.folder: m for m in mods}["example_lua"] - self.assertEqual((example.script, example.enabled, example.warnings), ("main.lua", False, [])) - self.assertEqual(leonida_mods.active_swaps(mods).keys(), {0xE472B687}) - def test_gui_is_an_explicit_lazy_tkinter_entry_point(self): source = (ROOT / "tools" / "leonida_mods.py").read_text(encoding="utf-8") self.assertIn('commands.add_parser("gui"', source) diff --git a/tests/test_navmesh_cell_fit.py b/tests/test_navmesh_cell_fit.py index 1a9133fff..f9465714e 100644 --- a/tests/test_navmesh_cell_fit.py +++ b/tests/test_navmesh_cell_fit.py @@ -20,20 +20,6 @@ class CellFit(unittest.TestCase): self.assertGreaterEqual(cf.fit_fraction(q, ext, 0.0325), 0.99) self.assertLess(cf.fit_fraction(q, ext, 0.03125), 0.5) - def test_control_mean_includes_late_tiles_and_weights_duplicates(self): - from unittest.mock import patch - fits = dict.fromkeys(cf.DOC_CELLS + cf.OTHER_CELLS, 1.0) - small = {"ext": (1, 1, 0), "fit": fits} - large = {"ext": (1, 2, 0), "fit": fits} - flat = {"ext": (0, 0, 0), "fit": dict.fromkeys(fits, 0.0)} - tiles = [small] * 20 + [large, flat] - with patch.object(cf, "baseline", side_effect=lambda extent, cell: extent / 4) as baseline: - report = cf.summarise_control(tiles) - self.assertEqual(report["cells"]["0.0625"], {"fit": 21, "baseline_mean": round(5.5 / 21, 4)}) - self.assertEqual(baseline.call_count, 2 * len(fits)) - self.assertEqual(report, cf.summarise_control(list(reversed(tiles)))) - self.assertIsNone(cf.summarise_control([flat])["cells"]["0.0625"]["baseline_mean"]) - def test_baseline_is_small_for_a_fine_step(self): self.assertLess(cf.baseline(2.0625, 0.0625), 0.06) # a 128 m extent's step is 128/65535, a little over 1/512 m: it drifts off a 1/32 m grid, so the static diff --git a/tests/test_navmesh_tile_obj.py b/tests/test_navmesh_tile_obj.py index 9b8208c10..e807cf885 100644 --- a/tests/test_navmesh_tile_obj.py +++ b/tests/test_navmesh_tile_obj.py @@ -1,11 +1,9 @@ """Read back OBJ primitives from a synthetic archive, independently of the writer.""" -import os import struct import subprocess import sys import tempfile import unittest -from unittest import mock from pathlib import Path HERE = Path(__file__).resolve().parent @@ -13,8 +11,6 @@ sys.path.insert(0, str(HERE)) from test_navmesh_decode import build_navmesh, make_rpf, nd TOOL = HERE.parent / "tools" / "navmesh_tile_obj.py" -sys.path.insert(0, str(HERE.parent / "tools")) -import navmesh_tile_obj as tool def read_obj(path): @@ -67,27 +63,6 @@ class ExportTest(unittest.TestCase): self.assertEqual(out.read_bytes(), original) self.assertEqual(run(1, archive).returncode, 2) - def test_stage_cleanup_restores_write_mode_on_replace_failure(self): - head, tail = build_navmesh(n_verts=3, poly_sizes=(3,), tiny_bm_cont=True) - chmod_calls = [] - real_chmod = os.chmod - - def track_chmod(path, mode, *args, **kwargs): - chmod_calls.append((str(path), mode)) - return real_chmod(path, mode, *args, **kwargs) - - with tempfile.TemporaryDirectory() as directory: - archive = Path(directory) / "input.rpf" - out = Path(directory) / "tile.obj" - make_rpf(archive, [head, tail]) - - with mock.patch("os.replace", side_effect=OSError("replace failed")), \ - mock.patch("os.chmod", side_effect=track_chmod): - code = tool.main([str(archive), "--tile", "0", "--out", str(out)]) - self.assertEqual(code, 2) - - self.assertTrue(any(mode == 0o600 for _, mode in chmod_calls), chmod_calls) - if __name__ == "__main__": unittest.main() diff --git a/tests/test_pool_workers.py b/tests/test_pool_workers.py index 2a0f20067..965064744 100644 --- a/tests/test_pool_workers.py +++ b/tests/test_pool_workers.py @@ -94,16 +94,6 @@ class ProcessWorkersTest(unittest.TestCase): with mock.patch.object(pool_workers, "MAX_PROCESS_WORKERS", None): self.assertEqual([pool_workers.process_workers(n) for n in (1, 61, 62, 4096)], [1, 61, 62, 4096]) - def test_none_jobs_respects_platform_limit(self): - with mock.patch.object(pool_workers, "MAX_PROCESS_WORKERS", WINDOWS_LIMIT), \ - mock.patch.object(os, "cpu_count", return_value=128): - self.assertEqual(pool_workers.process_workers(None), WINDOWS_LIMIT) - with mock.patch.object(pool_workers, "MAX_PROCESS_WORKERS", WINDOWS_LIMIT), \ - mock.patch.object(os, "cpu_count", return_value=8): - self.assertEqual(pool_workers.process_workers(None), 8) - with mock.patch.object(pool_workers, "MAX_PROCESS_WORKERS", None): - self.assertIsNone(pool_workers.process_workers(None)) - class ToolPoolSizeTest(unittest.TestCase): """Each tool, asked for more jobs than the limit, creates its pool at the limit and still does the work.""" diff --git a/tests/test_rsc8_audio.py b/tests/test_rsc8_audio.py index cb2cc1860..ebf904662 100644 --- a/tests/test_rsc8_audio.py +++ b/tests/test_rsc8_audio.py @@ -1667,22 +1667,6 @@ class MarkerRegionsTest(unittest.TestCase): "names": {}, "exceptions_total": 0, "exceptions": [], }) - def test_stage_cleanup_restores_write_mode_on_replace_failure(self): - with tempfile.TemporaryDirectory() as tmp: - out_json = os.path.join(tmp, "out.json") - chmod_calls = [] - real_chmod = os.chmod - - def track_chmod(p, mode, **kwargs): - chmod_calls.append((p, mode)) - return real_chmod(p, mode, **kwargs) - - with mock.patch("rsc8_audio.os.replace", side_effect=OSError("replace failed")), \ - mock.patch("rsc8_audio.os.chmod", side_effect=track_chmod): - with self.assertRaises(OSError): - rsc8_audio.write_report(out_json, [], {}) - self.assertTrue(any(mode == 0o600 for p, mode in chmod_calls)) - if __name__ == "__main__": unittest.main() diff --git a/tests/test_rtti_scan.py b/tests/test_rtti_scan.py index cff178b6d..3f1cedc1b 100644 --- a/tests/test_rtti_scan.py +++ b/tests/test_rtti_scan.py @@ -14,7 +14,6 @@ import subprocess import sys import tempfile import unittest -from unittest import mock sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tools")) import rtti_scan @@ -701,28 +700,6 @@ class RttiScanCoreTest(unittest.TestCase): self.assertEqual(p.returncode, 1) self.assertIn("ERROR:", p.stderr) - def test_write_report_cleans_up_staged_file_when_replace_fails_even_if_readonly(self): - report = os.path.join(self.tmp.name, "report.json") - with open(report, "w", encoding="utf-8") as f: - f.write('{"initial": 1}\n') - os.chmod(report, 0o444) - - real_remove = os.remove - - def windows_strict_remove(p): - mode = os.stat(p).st_mode - if not (mode & 0o200): - raise PermissionError(13, f"Access is denied: {p}") - return real_remove(p) - - with mock.patch("os.replace", side_effect=OSError(13, "Permission denied")), \ - mock.patch("os.remove", side_effect=windows_strict_remove): - with self.assertRaises(OSError): - rtti_scan.write_report(report, "{}") - - leftover = [f for f in os.listdir(self.tmp.name) if f.startswith(".rtti-")] - self.assertEqual(leftover, []) - if __name__ == "__main__": unittest.main() diff --git a/tests/test_run_gpu_tests_paths.py b/tests/test_run_gpu_tests_paths.py index 20081aa2a..1c5d77115 100644 --- a/tests/test_run_gpu_tests_paths.py +++ b/tests/test_run_gpu_tests_paths.py @@ -136,12 +136,10 @@ class WorkDirectory(unittest.TestCase): blocker.parent.mkdir(exist_ok=True) blocker.write_text("keep me", encoding="utf-8") - # The error quotes a localized OS message. -I ignores PYTHONUTF8, so without -X utf8 the child - # writes it in the ANSI code page, which a UTF-8 parent cannot decode (stderr comes back None). result = subprocess.run( - [sys.executable, "-I", "-X", "utf8", run_gpu_tests.__file__, "--build", str(build), + [sys.executable, "-I", run_gpu_tests.__file__, "--build", str(build), "--work", str(work), "--filter", "cs_lds"], - capture_output=True, encoding="utf-8", timeout=10, + capture_output=True, text=True, timeout=10, ) self.assertEqual(result.returncode, 2, result.stderr) self.assertIn("error: cannot prepare GPU test directory", result.stderr) diff --git a/tests/test_sandbox_scene.py b/tests/test_sandbox_scene.py index f078bfdc9..96b2effd3 100644 --- a/tests/test_sandbox_scene.py +++ b/tests/test_sandbox_scene.py @@ -154,18 +154,6 @@ class TestCliErrors(unittest.TestCase): self.assertEqual(len(err.strip().splitlines()), 1) self.assertTrue(err.startswith("ERROR:")) - def test_scene_output_cannot_replace_placements(self): - from pathlib import Path - original = Path(self.entities).read_bytes() - alias = os.path.join(self.tmp.name, "scene.bin") - os.link(self.entities, alias) - for out in (alias, self.entities): - with self.subTest(out=out): - rc, err = self._run(self.entities, out) - self.assertEqual(rc, 2) - self.assertIn("--entities", err) - self.assertEqual(Path(self.entities).read_bytes(), original) - def test_missing_entities_is_one_error_line(self): rc, err = self._run(os.path.join(self.tmp.name, "nope.jsonl"), os.path.join(self.tmp.name, "o.bin")) diff --git a/tests/test_shader_link_check.py b/tests/test_shader_link_check.py index 88b472414..08f0ed0d3 100644 --- a/tests/test_shader_link_check.py +++ b/tests/test_shader_link_check.py @@ -577,27 +577,6 @@ class CommandLineTest(unittest.TestCase): self.assertEqual(result, 0) self.assertEqual(reflect.call_count, 2) - def test_write_report_cleans_up_staged_file_when_replace_fails_even_if_readonly(self): - report = self.directory / "readonly_report.json" - report.write_text('{"initial": 1}\n', encoding="utf-8") - os.chmod(report, 0o444) - - real_unlink = os.unlink - - def windows_strict_unlink(p, *args, **kwargs): - mode = os.stat(p).st_mode - if not (mode & 0o200): - raise PermissionError(13, f"Access is denied: {p}") - return real_unlink(p, *args, **kwargs) - - with patch("os.replace", side_effect=OSError(13, "Permission denied")), \ - patch("os.unlink", side_effect=windows_strict_unlink): - with self.assertRaises(OSError): - link.write_report(report, {"new": True}) - - leftover = [p.name for p in self.directory.glob(".shader-link-*")] - self.assertEqual(leftover, []) - if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/test_skin_streams.py b/tests/test_skin_streams.py index c94416898..3d3176ad3 100644 --- a/tests/test_skin_streams.py +++ b/tests/test_skin_streams.py @@ -530,22 +530,6 @@ class TestCli(unittest.TestCase): with open(path, "rb") as fh: self.assertEqual(fh.read(), data) - def test_case_only_spelling_of_a_missing_report_is_one_path(self): - # normcase keeps case on macOS, and samefile cannot see a file that has not been created. - with tempfile.TemporaryDirectory() as tmp: - folder = os.path.join(tmp, "Reports") - os.mkdir(folder) - probe = os.path.join(folder, "Probe.tmp") - with open(probe, "wb"): - pass - insensitive = os.path.exists(os.path.join(folder, "probe.tmp")) - os.remove(probe) - if not insensitive: - self.skipTest("volume keeps case") - first = os.path.join(tmp, "Reports", "out.json") - second = os.path.join(tmp, "reports", "out.json") - self.assertTrue(ss.same_output_path(first, second)) - def test_json_that_is_a_directory_is_refused_before_the_scan(self): with tempfile.TemporaryDirectory() as tmp: path, _ = self._archive(tmp) diff --git a/tests/test_text_tables.py b/tests/test_text_tables.py index 65714ee46..3b601ff57 100644 --- a/tests/test_text_tables.py +++ b/tests/test_text_tables.py @@ -353,31 +353,6 @@ class TestCli(unittest.TestCase): self.assertFalse([f for f in os.listdir(tmp) if f.startswith(".text_tables-")], "staging and backup files must not be left behind") - def test_stage_cleanup_restores_write_mode_on_replace_failure(self): - with tempfile.TemporaryDirectory() as tmp: - src = os.path.join(tmp, "src") - os.mkdir(src) - write(os.path.join(src, "conv.pso"), CONV) - tables = os.path.join(tmp, "tables.csv") - chmod_calls = [] - real_chmod = os.chmod - - def track_chmod(p, mode, **kwargs): - chmod_calls.append((p, mode)) - return real_chmod(p, mode, **kwargs) - - def failing_replace(source, dest): - if ".text_tables-" in source: - raise OSError("replace failed") - return os.replace(source, dest) - - with patch.object(T.os, "replace", side_effect=failing_replace), \ - patch.object(T.os, "chmod", side_effect=track_chmod): - with contextlib.redirect_stderr(io.StringIO()): - rc = T.main([src, "--tables", tables]) - self.assertEqual(rc, 2) - self.assertTrue(any(mode == 0o600 for p, mode in chmod_calls)) - def test_report_cannot_replace_the_carve_index(self): with tempfile.TemporaryDirectory() as tmp: source = os.path.join(tmp, "carve") diff --git a/tests/test_world_build.py b/tests/test_world_build.py index 53de55f5b..7bb6722d0 100644 --- a/tests/test_world_build.py +++ b/tests/test_world_build.py @@ -2068,24 +2068,6 @@ world_build.build_world(assets, output) with open(os.path.join(recovery, "previous", "c_0_0.glb"), "rb") as f: self.assertEqual(f.read(), b"previous chunk") - def test_write_json_atomic_cleanup_restores_write_mode_on_replace_failure(self): - with tempfile.TemporaryDirectory() as tmp: - dest = os.path.join(tmp, "world.json") - chmod_calls = [] - real_chmod = os.chmod - - def track_chmod(p, mode, **kwargs): - chmod_calls.append((p, mode)) - return real_chmod(p, mode, **kwargs) - - def failing_replace(src, dst): - raise OSError("replace failed") - - with unittest.mock.patch("world_build.os.chmod", side_effect=track_chmod): - with self.assertRaises(OSError): - world_build._write_json_atomic(dest, {"test": 1}, replace=failing_replace) - self.assertTrue(any(mode == 0o600 for p, mode in chmod_calls)) - def _write_png_window_assets(assets_dir: str, chunks: int) -> list[str]: """`chunks` single-model chunks along X; model i uses the TTPF textures T_i and T_{i+1} (shared with its diff --git a/tests/test_world_build_output_lock.py b/tests/test_world_build_output_lock.py index 52f11014c..7b461a2f7 100644 --- a/tests/test_world_build_output_lock.py +++ b/tests/test_world_build_output_lock.py @@ -105,20 +105,6 @@ class WorldBuildOutputLockTests(unittest.TestCase): self.assertFalse(os.path.exists(os.path.join(out, "world.json"))) self.assertFalse(os.path.exists(os.path.join(out, "chunks"))) - def test_case_and_unicode_variants_share_a_lock(self): - with tempfile.TemporaryDirectory() as tmp: - out = os.path.join(tmp, "Wörld") - alias = os.path.join(tmp, "wo\u0308RLD") - unrelated = os.path.join(tmp, "other") - with _lock_held_by_child(tmp, out): - with self.assertRaisesRegex(RuntimeError, "another world_build is using"): - with wb._exclusive_output(alias): - pass - with wb._exclusive_output(unrelated): - pass - with wb._exclusive_output(alias): - pass - def test_short_name_spelling_of_a_held_output_is_refused(self): if os.name != "nt": self.skipTest("8.3 short names are Windows only") diff --git a/tests/test_world_census.py b/tests/test_world_census.py index 44f7121c5..d834fadef 100644 --- a/tests/test_world_census.py +++ b/tests/test_world_census.py @@ -1037,28 +1037,6 @@ class CensusSourceTest(unittest.TestCase): self.assertTrue(rebuilt["census_exact"]) self.assertEqual(new_rows, rows) - def test_staged_json_restores_write_mode_on_failure(self): - with tempfile.TemporaryDirectory() as tmp: - dest = os.path.join(tmp, "out.json") - with open(dest, "w", encoding="utf-8") as f: - f.write("{}") - os.chmod(dest, 0o444) - - chmod_calls = [] - real_chmod = os.chmod - - def track_chmod(p, mode, **kwargs): - chmod_calls.append((p, mode)) - return real_chmod(p, mode, **kwargs) - - with mock.patch.object(WC.os, "chmod", side_effect=track_chmod): - try: - with WC._staged_json(dest, {"test": 1}) as staged: - raise RuntimeError("simulated write failure") - except RuntimeError: - pass - self.assertTrue(any(mode == 0o600 for p, mode in chmod_calls)) - def setUpModule(): # The tools' main() prints its summary JSON; keep it out of the test log (tests that check it redirect again). diff --git a/tests/test_world_index.py b/tests/test_world_index.py index 3192b0a4e..577b6e6f4 100644 --- a/tests/test_world_index.py +++ b/tests/test_world_index.py @@ -950,23 +950,6 @@ class WorldIndexTest(unittest.TestCase): # Every resource field emitted by parse_resource() for this map must have a matching CSV column. self.assertEqual(set(json_row) - set(fieldnames), set()) - def test_staged_entity_report_restores_write_mode_on_replace_failure(self): - chmod_calls = [] - real_chmod = os.chmod - - def track_chmod(p, mode, **kwargs): - chmod_calls.append((str(p), mode)) - return real_chmod(p, mode, **kwargs) - - out_path = os.path.join(self.dir, "entities.jsonl") - with mock.patch.object(WI.os, "replace", side_effect=OSError("replace failed")), \ - mock.patch.object(WI.os, "chmod", side_effect=track_chmod): - with self.assertRaisesRegex(OSError, "replace failed"): - with WI._staged_entity_report(out_path): - pass - - self.assertTrue(any(mode == 0o600 for _, mode in chmod_calls), chmod_calls) - def setUpModule(): # The tools' main() prints its summary JSON; keep it out of the test log (tests that check it redirect again). diff --git a/tests/test_world_lights_paths.py b/tests/test_world_lights_paths.py index 0c052ef26..75e34e561 100644 --- a/tests/test_world_lights_paths.py +++ b/tests/test_world_lights_paths.py @@ -599,28 +599,6 @@ class ScanTest(unittest.TestCase): self.assertEqual(len(err.getvalue().strip().splitlines()), 1, err.getvalue()) self.assertNotIn("Traceback", err.getvalue()) - def test_stage_cleanup_restores_write_mode_on_replace_failure(self): - with tempfile.TemporaryDirectory() as tmp: - lights = os.path.join(tmp, "lights.jsonl") - with open(lights, "w", encoding="utf-8") as f: - f.write('{"old": true}\n') - os.chmod(lights, 0o444) - - chmod_calls = [] - real_chmod = os.chmod - - def track_chmod(p, mode, **kwargs): - chmod_calls.append((p, mode)) - return real_chmod(p, mode, **kwargs) - - with mock.patch("world_lights_paths.os.replace", side_effect=OSError("replace failed")), \ - mock.patch("world_lights_paths.os.chmod", side_effect=track_chmod): - with self.assertRaises(OSError): - T.summarize({"lights": {}, "archetype_lights": {}, "resources": 0, "incomplete": 0, - "light_resources": 0, "ranges": {}, "world_lights": []}, - lights_out=lights) - self.assertTrue(any(mode == 0o600 for p, mode in chmod_calls)) - def test_bad_input_is_one_line(self): err = io.StringIO() with contextlib.redirect_stderr(err): diff --git a/tests/test_world_names.py b/tests/test_world_names.py index 9303cad4b..a8b0e6c53 100644 --- a/tests/test_world_names.py +++ b/tests/test_world_names.py @@ -588,22 +588,6 @@ class CliTest(unittest.TestCase): with open(source, "rb") as handle: self.assertEqual(handle.read(), original) - def test_stage_cleanup_restores_write_mode_on_replace_failure(self): - with tempfile.TemporaryDirectory() as tmp: - dest = os.path.join(tmp, "out.json") - chmod_calls = [] - real_chmod = os.chmod - - def track_chmod(p, mode, **kwargs): - chmod_calls.append((p, mode)) - return real_chmod(p, mode, **kwargs) - - with mock.patch.object(WN.os, "replace", side_effect=OSError("replace failed")), \ - mock.patch.object(WN.os, "chmod", side_effect=track_chmod): - with self.assertRaises(OSError): - WN._write_json(dest, {}) - self.assertTrue(any(mode == 0o600 for p, mode in chmod_calls)) - if __name__ == "__main__": unittest.main() diff --git a/tests/test_x64_recomp.py b/tests/test_x64_recomp.py index a24046328..a67726185 100644 --- a/tests/test_x64_recomp.py +++ b/tests/test_x64_recomp.py @@ -14,6 +14,7 @@ The qemu tests skip cleanly when qemu-system-aarch64 is not installed. python -I tests/test_x64_recomp.py """ import os +import shutil import sys import unittest @@ -26,8 +27,12 @@ if TOOLS_DIR not in sys.path: import x64_recomp as x # noqa: E402 -# The binary x64_recomp.run_kernel will start: QEMU_AARCH64, else qemu-system-aarch64 on PATH. -HAS_QEMU = os.path.isfile(x.QEMU_BIN) +QEMU = os.environ.get( + "QEMU_AARCH64", + "/home/nolan/.nix-profile/bin/qemu-system-aarch64" + if os.path.exists("/home/nolan/.nix-profile/bin/qemu-system-aarch64") + else shutil.which("qemu-system-aarch64") or "") +HAS_QEMU = bool(QEMU) and os.path.exists(QEMU) GUEST_VA = 0x46000000 SCRATCH = 0x47100000 # inside the kernel image's RW RAM window, away from ctx/stack diff --git a/tools/anim_clips.py b/tools/anim_clips.py index 63531c547..14783e0cb 100644 --- a/tools/anim_clips.py +++ b/tools/anim_clips.py @@ -42,7 +42,6 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import anim_index # noqa: E402 from pool_workers import process_workers # noqa: E402 -from report_paths import same_report_path # noqa: E402 SYSTEM = 0x50000000 CHANNEL_NAMES = ("static_quat", "static_vec3", "static_float", "raw_float", "quantize_float", @@ -1520,6 +1519,16 @@ def decode_one(path, offset, frames): return d +def same_output_path(first, second): + """True when writing ``second`` would truncate ``first`` (same file, path or hard link).""" + if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)): + return True + try: + return os.path.samefile(first, second) + except OSError: + return False + + def main(): ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("archive", help="anim.rpf") @@ -1545,7 +1554,7 @@ def main(): if a.out: if os.path.isdir(a.out): ap.error(f"{a.out} is a directory, not a .json file") - if same_report_path(a.archive, a.out): + if same_output_path(a.archive, a.out): ap.error("output must not overwrite the input archive") try: if a.decode is not None: diff --git a/tools/anim_glb.py b/tools/anim_glb.py index 618e68db2..d1dc1059b 100644 --- a/tools/anim_glb.py +++ b/tools/anim_glb.py @@ -61,7 +61,6 @@ import anim_index # noqa: E402 from file_mode import published_mode # noqa: E402 import glb_writer # noqa: E402 from pool_workers import process_workers # noqa: E402 -from report_paths import same_report_path # noqa: E402 import skin_streams # noqa: E402 SYSTEM = 0x50000000 @@ -619,6 +618,10 @@ def parse_offset(text): raise argparse.ArgumentTypeError(f"not an offset: {text!r}") from None +def same_path(first, second): + return anim_clips.same_output_path(first, second) + + def export(args): started = time.monotonic() report = {"archive": os.path.basename(args.archive), "parts": [], "clips": [], "counts": collections.Counter()} @@ -769,11 +772,11 @@ def main(argv=None): outputs = [p for p in (args.out, args.report) if p] for o in outputs: for i in inputs: - if os.path.exists(o) and same_report_path(i, o): + if os.path.exists(o) and same_path(i, o): ap.error(f"{o} is an input; refusing to overwrite it") if args.report and os.path.isdir(args.report): ap.error(f"--report is a directory: {args.report}") - if args.out and args.report and same_report_path(args.out, args.report): + if args.out and args.report and same_path(args.out, args.report): ap.error("the GLB and the report are the same path") if args.clip or args.dictionary is not None: if args.coverage: diff --git a/tools/audio_wav.py b/tools/audio_wav.py index cfe920880..c096b9da2 100644 --- a/tools/audio_wav.py +++ b/tools/audio_wav.py @@ -64,8 +64,8 @@ def find_ffmpeg(explicit: str): return found -def _read_opus_id(stream: BinaryIO) -> tuple[bytes, bytes, int] | None: - """Read the Opus ID packet, serial and page number, leaving the stream at the next page.""" +def _read_opus_id(stream: BinaryIO) -> tuple[bytes, bytes] | None: + """Read the Opus ID packet and serial, leaving the stream at the next page.""" header = stream.read(27) if len(header) != 27 or header[:6] != b"OggS\x00\x02": return None @@ -77,7 +77,7 @@ def _read_opus_id(stream: BinaryIO) -> tuple[bytes, bytes, int] | None: packet = stream.read(size) if len(packet) != size or size < 19 or not packet.startswith(b"OpusHead"): return None - return packet, header[14:18], struct.unpack_from(" bool: @@ -97,7 +97,7 @@ def ogg_output_samples(path: str) -> int: identification = _read_opus_id(f) if identification is None: return 0 - head, serial, sequence = identification + head, serial = identification if head[8] >= 16 or head[9] == 0: return 0 pre_skip, = struct.unpack_from(" int: hdr = f.read(27) if len(hdr) != 27 or hdr[:4] != b"OggS" or hdr[4] != 0 or hdr[14:18] != serial: return 0 - sequence = (sequence + 1) & 0xffffffff - if struct.unpack_from(" dict: if os.path.isfile(source): return {os.path.splitext(os.path.basename(source))[0]: bank_ids(source)} out = {} - def scan_failed(error): - raise error - - for root, _dirs, files in os.walk(source, onerror=scan_failed): + for root, _dirs, files in os.walk(source): for name in sorted(files): if name.lower().endswith(".awc"): full = os.path.join(root, name) diff --git a/tools/bink_index.py b/tools/bink_index.py index 0f23ae4e2..db20ed5ec 100644 --- a/tools/bink_index.py +++ b/tools/bink_index.py @@ -43,7 +43,6 @@ import tempfile sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from file_mode import published_mode # noqa: E402 from replace_retry import replace as replace_retry # noqa: E402 -from report_paths import same_report_path as same_output_path # noqa: E402 SIG = re.compile(rb"KB2[a-z]") HDR = 0x2C @@ -368,6 +367,16 @@ def is_rpf_archive(path): return len(header) >= 16 and header[1:4] == b"FPR" +def same_output_path(first, second): + """True when writing ``second`` would truncate ``first`` (same file, path or hard link).""" + if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)): + return True + try: + return os.path.samefile(first, second) + except OSError: + return False + + def target_problem(path): """None when a single named file is something this tool indexes, else a one-line reason. diff --git a/tools/bink_names.py b/tools/bink_names.py index 20ac3e2ad..0e84bd13a 100644 --- a/tools/bink_names.py +++ b/tools/bink_names.py @@ -125,8 +125,7 @@ def read_mount_lists(paths): for data in mount_documents(paths): if LIST_MARKER not in data.lower(): continue - # Filename-shaped text in comments, CDATA or processing instructions is not an element. - text = gamedata_xml.COMMENT_MARKUP.sub(b" ", data).decode("utf-8", errors="replace") + text = data.decode("utf-8", errors="replace") for name in LIST_ENTRY.findall(text): name = name.strip().replace("\\", "/") if name.lower() not in seen: @@ -184,10 +183,6 @@ def load_streams(source, skip_report=None): out[-1]["source"] = out[-1]["source"].replace("\\", "/") # an older Windows index wrote "\" # A directory of carved files sorts by file name; carves name files by archive offset. out.sort(key=lambda r: (r["source"], r["offset"])) - for i in range(1, len(out)): - prev, curr = out[i - 1], out[i] - if prev["source"] == curr["source"] and prev["offset"] == curr["offset"]: - raise ValueError(f"duplicate stream location: {curr['source']} at offset {curr['offset']}") return out diff --git a/tools/bvh_index.py b/tools/bvh_index.py index 272dfc016..0cc363df7 100644 --- a/tools/bvh_index.py +++ b/tools/bvh_index.py @@ -152,7 +152,7 @@ def classify(head, size, tail=None): if printable >= len(probe) * 0.9 and b"<" in probe and b">" in probe: row.update(kind="xml", signature="xml", fragment=True) return row - if size == 208 and len(head) >= 208 and all(struct.unpack_from(" int: f.write(png) if os.path.isfile(output): shutil.copymode(output, pending) - try: - os.replace(pending, output) - except BaseException: - os.chmod(pending, 0o600) - raise + os.replace(pending, output) except (DdsError, OSError) as exc: print(f"ERROR: {exc}", file=sys.stderr) return 1 diff --git a/tools/f32_fuzz.py b/tools/f32_fuzz.py index a29680354..1c0fe63d4 100644 --- a/tools/f32_fuzz.py +++ b/tools/f32_fuzz.py @@ -723,12 +723,6 @@ def same(want, got): return want == got -# Ops whose translation applies the measured omod rule (a -0 result becomes +0 under mul:2/mul:4/div:2 with IEEE off, -# dev_omod_neg_zero below) instead of keeping -0 as OpFMul does: docs/design.md, "`v_mul_legacy_f32` default-mode f32 -# denormal flushing". For them the translator is judged against the hardware word, not the ISA-text model's -0. -TRANSLATOR_OMOD_POS_ZERO = ("v_mul_legacy_f32",) - - def check(op, vals, srcs, e64, out_mods): try: want = model(op, vals, srcs, out_mods) @@ -736,8 +730,6 @@ def check(op, vals, srcs, e64, out_mods): return "skip", f"denormal {e}" except NotModelled as e: return "skip", str(e) - if op in TRANSLATOR_OMOD_POS_ZERO and want[0] == 0x80000000 and any(m in OMOD for m in out_mods): - want = [0, want[1]] text, obs = listing(op, vals, srcs, e64, out_mods) status, got = run_translated(text) if status != "ok": diff --git a/tools/file_mode.py b/tools/file_mode.py index 893b7ed6d..7c7f49812 100644 --- a/tools/file_mode.py +++ b/tools/file_mode.py @@ -27,7 +27,6 @@ def new_file_mode(directory): finally: os.close(fd) try: - os.chmod(probe, 0o600) os.remove(probe) except OSError: pass diff --git a/tools/glb_writer.py b/tools/glb_writer.py index f0aa3dc94..ded546fea 100644 --- a/tools/glb_writer.py +++ b/tools/glb_writer.py @@ -1081,7 +1081,6 @@ def _write_bytes_atomic(path: str, glb_bytes: bytes) -> None: except BaseException: try: if tmp_path is not None: - os.chmod(tmp_path, 0o600) os.remove(tmp_path) except OSError: pass diff --git a/tools/instance_lists.py b/tools/instance_lists.py index 85071ace3..5c0e02331 100644 --- a/tools/instance_lists.py +++ b/tools/instance_lists.py @@ -37,9 +37,6 @@ import zlib sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import world_index as wi # noqa: E402 (same 0x7a header, schema and stream helpers) -from report_paths import same_report_path # noqa: E402 - -same_output_path = same_report_path PROP_LIST, PROP_INST = 0xBA049770, 0xEA6B3A96 GRASS_LIST, GRASS_INST = 0x7C475B5D, 0xED86F522 @@ -330,6 +327,15 @@ def scan(path, T, start=None, limit=None): pos = s + max(used, 1) +def same_output_path(first, second): + if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)): + return True + try: + return os.path.samefile(first, second) + except OSError: + return False + + def _int_arg(text): try: return int(text, 0) diff --git a/tools/leonida_mods.py b/tools/leonida_mods.py index 76829a44e..b851182eb 100644 --- a/tools/leonida_mods.py +++ b/tools/leonida_mods.py @@ -70,7 +70,6 @@ class ModInfo: swaps: list[Swap] = field(default_factory=list) warnings: list[str] = field(default_factory=list) raw: dict = field(default_factory=dict) - script: str = "" def joaat(name: str) -> int: @@ -103,20 +102,6 @@ def parse_model_id(text: str) -> int: return joaat(text) -def check_script(script: object, folder: str, path: str, warnings: list[str]) -> str: - """The "script" of a Lua mod: a .lua file inside the mod's folder (read by leonida.exe, docs/lua-modding.md).""" - if not isinstance(script, str) or not script: - raise ModsError(f'{folder}: "script" must be a file name such as "main.lua"') - parts = PurePosixPath(script).parts - if "\\" in script or ":" in script or not parts or parts[0] == "/" or ".." in parts or "." in parts: - raise ModsError(f'{folder}: "script" must stay inside the mod folder') - if not script.lower().endswith(".lua"): - raise ModsError(f'{folder}: "script" must be a .lua file') - if path and not os.path.isfile(os.path.join(os.path.dirname(path), *parts)): - warnings.append(f'script {script} is not in the mod folder') - return script - - def validate_manifest(data: object, folder: str, path: str = "") -> ModInfo: if not isinstance(data, dict): raise ModsError(f"{folder}: {MANIFEST} is not a JSON object") @@ -135,14 +120,9 @@ def validate_manifest(data: object, folder: str, path: str = "") -> ModInfo: if not isinstance(enabled, bool): raise ModsError(f'{folder}: "enabled" must be true or false') mod.enabled = enabled - script = data.get("script") - if script is not None: - mod.script = check_script(script, folder, path, mod.warnings) swaps = data.get("archetype_swaps") if swaps is None: - # A Lua mod (docs/lua-modding.md) changes things with its script, not with swaps. - if not mod.script: - mod.warnings.append("no archetype_swaps; this mod currently changes nothing") + mod.warnings.append("no archetype_swaps; this mod currently changes nothing") return mod if not isinstance(swaps, list): raise ModsError(f'{folder}: "archetype_swaps" must be a list') @@ -168,7 +148,7 @@ def validate_manifest(data: object, folder: str, path: str = "") -> ModInfo: mod.warnings.append(f'{label} repeats {seen[swap.from_id]}; the later swap wins') seen[swap.from_id] = label mod.swaps.append(swap) - if not mod.swaps and not mod.script: + if not mod.swaps: mod.warnings.append("archetype_swaps is empty; this mod currently changes nothing") return mod @@ -610,8 +590,6 @@ def print_report(mods_dir: str, mods: list[ModInfo], errors: list[str]) -> None: state = "enabled" if mod.enabled else "disabled" version = f", game {mod.game_version}" if mod.game_version else "" swaps = f"{len(mod.swaps)} swap" + ("" if len(mod.swaps) == 1 else "s") - if mod.script: - swaps = f"Lua {mod.script}" + (f", {swaps}" if mod.swaps else "") print(f"{mod.folder}: {mod.name} [{state}; {swaps}{version}]") for warning in mod.warnings: print(f" warning: {warning}") @@ -645,7 +623,6 @@ def report_json(mods_dir: str, mods: list[ModInfo], errors: list[str]) -> str: "name": m.name, "enabled": m.enabled, "game_version": m.game_version, - "script": m.script, "warnings": m.warnings, "archetype_swaps": [swap_entry(m, idx, s) for idx, s in enumerate(m.swaps)], } for m in mods], @@ -873,8 +850,7 @@ def run_gui(args: argparse.Namespace, initial_mods_dir: str | None) -> int: self.mods[mod.folder] = mod self.tree.insert("", "end", iid=mod.folder, values=(mod.folder, mod.name, "enabled" if mod.enabled else "disabled", - "Lua" if mod.script and not mod.swaps else len(mod.swaps), - mod.game_version)) + len(mod.swaps), mod.game_version)) active = len(active_swaps(self.mods_list)) self.status(f"{len(self.mods_list)} mod(s), {active} active swap(s), " f"{len(self.errors)} manifest error(s)") diff --git a/tools/navmesh_cell_fit.py b/tools/navmesh_cell_fit.py index 1b475e386..17da521a3 100644 --- a/tools/navmesh_cell_fit.py +++ b/tools/navmesh_cell_fit.py @@ -26,7 +26,6 @@ import re import struct import sys from collections import Counter -from functools import lru_cache ROOT = os.path.dirname(os.path.abspath(__file__)) if ROOT not in sys.path: @@ -145,14 +144,10 @@ def measure(archive, hashes=None, min_fraction=0.9, static_every=0): def summarise_control(tiles, min_fraction=0.9): """Static tiles: for each cell size, how many fit it and the mean chance baseline of their step.""" out = {"tiles": len(tiles), "cells": {}} - extents = Counter(tuple(e for e in t["ext"][:2] if e > 0) for t in tiles) - extents.pop((), None) # A tile without a measurable horizontal axis has no chance baseline. - measured = sum(extents.values()) - cached_baseline = lru_cache(maxsize=256)(baseline) for c in DOC_CELLS + OTHER_CELLS: - total = sum(count * max(cached_baseline(e, c) for e in axes) for axes, count in extents.items()) + bases = [max(baseline(t["ext"][k], c) for k in (0, 1) if t["ext"][k] > 0) for t in tiles[:20]] out["cells"][str(c)] = {"fit": sum(1 for t in tiles if t["fit"][c] >= min_fraction), - "baseline_mean": round(total / measured, 4) if measured else None} + "baseline_mean": round(sum(bases) / len(bases), 4) if bases else None} return out diff --git a/tools/navmesh_tile_obj.py b/tools/navmesh_tile_obj.py index 189396803..66042a75c 100644 --- a/tools/navmesh_tile_obj.py +++ b/tools/navmesh_tile_obj.py @@ -13,7 +13,6 @@ from contextlib import closing from pathlib import Path sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from file_mode import published_mode from navmesh_nodes import navmesh_resources, tile_geometry from report_paths import same_report_path @@ -62,7 +61,6 @@ def main(argv=None): dir=args.out.parent, delete=False) as out: temp = Path(out.name) write_obj(out, geometry, ordinal) - os.chmod(temp, published_mode(args.out)) os.replace(temp, args.out) temp = None except (OSError, ValueError) as exc: @@ -70,10 +68,6 @@ def main(argv=None): return 2 finally: if temp is not None: - try: - os.chmod(temp, 0o600) - except OSError: - pass temp.unlink(missing_ok=True) return 0 diff --git a/tools/odrp_7a.py b/tools/odrp_7a.py index 1e3055f5a..7777944b5 100644 --- a/tools/odrp_7a.py +++ b/tools/odrp_7a.py @@ -43,7 +43,6 @@ import zlib sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from file_mode import published_mode # noqa: E402 -from report_paths import same_report_path # noqa: E402 SIGNATURE = b"0DRP" VERSION = 0x7A @@ -1180,6 +1179,15 @@ def _positive_bytes_arg(text): return value +def _same_path(first, second): + if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)): + return True + try: + return os.path.samefile(first, second) + except OSError: + return False + + def _is_rpf_file(path): if not os.path.isfile(path) or os.path.getsize(path) < 4: return path.lower().endswith(".rpf") @@ -1210,19 +1218,19 @@ def main(argv=None): parent = os.path.dirname(os.path.abspath(args.out)) if not os.path.isdir(parent): ap.error(f"{parent} is not a folder, so {args.out} cannot be written") - if same_report_path(args.source, args.out): + if _same_path(args.source, args.out): ap.error("output must not overwrite the source") if os.path.isdir(args.source): if args.start is not None or args.limit is not None: ap.error("--start and --limit apply to an .rpf archive, not a directory") manifest = os.path.join(args.source, "index.json") - if os.path.isfile(manifest) and same_report_path(manifest, args.out): + if os.path.isfile(manifest) and _same_path(manifest, args.out): ap.error(f"output would overwrite the carve manifest: {args.out}") if os.path.isfile(args.out): for name in os.listdir(args.source): cand = os.path.join(args.source, name) - if _is_carved_file(cand) and same_report_path(cand, args.out): + if _is_carved_file(cand) and _same_path(cand, args.out): ap.error(f"output would overwrite an input file: {args.out}") elif os.path.isfile(args.source): is_rpf = _is_rpf_file(args.source) diff --git a/tools/pool_workers.py b/tools/pool_workers.py index 41d99a29f..f10dbf916 100644 --- a/tools/pool_workers.py +++ b/tools/pool_workers.py @@ -16,6 +16,4 @@ MAX_PROCESS_WORKERS = 61 if os.name == "nt" else None def process_workers(jobs): """`jobs`, lowered to the most worker processes one pool can have here.""" - if jobs is None: - return None if MAX_PROCESS_WORKERS is None else min(os.cpu_count() or 1, MAX_PROCESS_WORKERS) return jobs if MAX_PROCESS_WORKERS is None else min(jobs, MAX_PROCESS_WORKERS) diff --git a/tools/restofworld_model_join.py b/tools/restofworld_model_join.py index e8c709a4f..47a63efac 100644 --- a/tools/restofworld_model_join.py +++ b/tools/restofworld_model_join.py @@ -46,11 +46,6 @@ import sys import time import zlib -ROOT = os.path.dirname(os.path.abspath(__file__)) -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -from report_paths import same_report_path # noqa: E402 - ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]|KB2[a-z]") SYS_BASE = 0x50000000 GFX_BASE = 0x60000000 @@ -1239,14 +1234,21 @@ def byte_count_arg(text): def _aliases_input(out_path, source_path): - if same_report_path(out_path, source_path): + if os.path.normcase(os.path.realpath(out_path)) == os.path.normcase(os.path.realpath(source_path)): return True + try: + if os.path.samefile(out_path, source_path): + return True + except OSError: + pass if os.path.isdir(source_path): index_path = os.path.join(source_path, "index.json") - if same_report_path(out_path, index_path): + if os.path.normcase(os.path.realpath(out_path)) == os.path.normcase(os.path.realpath(index_path)): return True if not os.path.isfile(out_path): return False + if os.path.isfile(index_path) and os.path.samefile(out_path, index_path): + return True src_root = os.path.normcase(os.path.abspath(source_path)) target = os.path.normcase(os.path.abspath(out_path)) if os.path.dirname(target) == src_root and target.endswith((".bin", ".bk2")): diff --git a/tools/rsc8_audio.py b/tools/rsc8_audio.py index 91cceb6d4..03510c4d1 100644 --- a/tools/rsc8_audio.py +++ b/tools/rsc8_audio.py @@ -1968,7 +1968,6 @@ def _atomic_write_text(path, write_fn): except BaseException: if tmp and os.path.isfile(tmp): try: - os.chmod(tmp, 0o600) os.remove(tmp) except OSError: pass diff --git a/tools/rtti_scan.py b/tools/rtti_scan.py index 207c4ba5e..c2d2ae0b9 100644 --- a/tools/rtti_scan.py +++ b/tools/rtti_scan.py @@ -24,7 +24,6 @@ import tempfile sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from file_mode import published_mode # noqa: E402 -from report_paths import same_report_path # noqa: E402 @@ -500,10 +499,6 @@ def write_report(path, text): os.replace(tmp, path) except BaseException: if tmp is not None: - try: - os.chmod(tmp, 0o600) - except OSError: - pass try: os.remove(tmp) except OSError: @@ -520,7 +515,12 @@ def main(): print(f"ERROR: {a.image}: does not exist", file=sys.stderr) return 2 path = a.out or re.sub(r"\.(exe|dll)$", "", a.image, flags=re.I) + ".rtti.json" - if same_report_path(a.image, path): + same_path = os.path.normcase(os.path.realpath(a.image)) == os.path.normcase(os.path.realpath(path)) + try: + same_path = same_path or os.path.samefile(a.image, path) + except OSError: + pass # A missing or inaccessible path is handled by the normal read/write error path. + if same_path: ap.error("output must not overwrite the source image") try: with open(a.image, "rb") as f: diff --git a/tools/sandbox_scene.py b/tools/sandbox_scene.py index 3ca70374e..6e5941f3c 100644 --- a/tools/sandbox_scene.py +++ b/tools/sandbox_scene.py @@ -25,7 +25,6 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import dds_png # noqa: E402 import glb_writer # noqa: E402 import world_build # noqa: E402 -from report_paths import same_report_path # noqa: E402 DIFFUSE_TEX = "C8E8C282" # joaat("DiffuseTex"), the albedo Param of a material texture reference # Two-layer blend materials have no DiffuseTex; their first layer's albedo sits in this slot (name not known yet; @@ -188,9 +187,6 @@ def main(argv=None): ap.error("--radius must be finite and non-negative") if args.max_props < 0: ap.error("--max-props must be non-negative") - if same_report_path(args.out, args.entities): - print("ERROR: --out would overwrite --entities", file=sys.stderr) - return 2 if os.path.isdir(args.out): print(f"ERROR: --out is a folder, not a scene file: {args.out}", file=sys.stderr) return 2 diff --git a/tools/shader_link_check.py b/tools/shader_link_check.py index 240936d04..37a8aa48c 100644 --- a/tools/shader_link_check.py +++ b/tools/shader_link_check.py @@ -229,10 +229,6 @@ def write_report(path: Path, doc): os.replace(temporary, path) finally: if temporary is not None: - try: - os.chmod(temporary, 0o600) - except OSError: - pass temporary.unlink(missing_ok=True) diff --git a/tools/shader_profile.py b/tools/shader_profile.py index 76fb6b6c5..0f049eee8 100644 --- a/tools/shader_profile.py +++ b/tools/shader_profile.py @@ -24,9 +24,6 @@ import re import sys from collections import Counter, defaultdict -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from report_paths import same_report_path # noqa: E402 - FAMILIES = [("s_buffer_", "smem"), ("s_load", "smem"), ("s_", "scalar"), ("v_", "vector"), ("ds_", "lds"), ("buffer_", "buffer"), ("tbuffer_", "buffer"), ("image_", "image"), ("global_", "global"), ("flat_", "flat"), ("scratch_", "scratch"), ("exp", "export")] @@ -292,10 +289,13 @@ def stage_map(disasm_dir) -> dict: def same_output_path(first, second): - """True when writing ``second`` would truncate ``first``: one name (case-folded on a folding volume) or one - file through a hard link. `tools/report_paths.same_report_path` owns that answer; this keeps the name the rest - of the tool calls.""" - return same_report_path(first, second) + """True when writing ``second`` would truncate ``first`` (same file, path or hard link).""" + if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)): + return True + try: + return os.path.samefile(first, second) + except OSError: + return False def main(): diff --git a/tools/skin_streams.py b/tools/skin_streams.py index 5baf8ff84..13b1dcc24 100644 --- a/tools/skin_streams.py +++ b/tools/skin_streams.py @@ -45,11 +45,6 @@ import sys import time import zlib -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # -I keeps the script directory off sys.path -from report_paths import same_report_path # noqa: E402 - -same_output_path = same_report_path - PAGE = 4096 MAX_SYS = 32 * 1024 * 1024 MAX_GFX = 224 * 1024 * 1024 @@ -455,6 +450,16 @@ def scan_archive(path, sample, log): return stats +def same_output_path(first, second): + """True when writing ``second`` would truncate ``first`` (same file, path or hard link).""" + if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)): + return True + try: + return os.path.samefile(first, second) + except OSError: + return False + + def main(argv=None): ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("inputs", nargs="+", help="RPF9 archives to scan") diff --git a/tools/tex_headers.py b/tools/tex_headers.py index bb6bd211e..4479822a2 100644 --- a/tools/tex_headers.py +++ b/tools/tex_headers.py @@ -23,9 +23,6 @@ import struct import sys from collections import Counter -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from report_paths import same_report_path # noqa: E402 - _UINT64_CODE = "Q" if array.array("Q").itemsize == 8 else None DXGI = { @@ -838,10 +835,13 @@ def scan_archive(carve, arch): def same_output_path(first, second): - """True when writing ``second`` would truncate ``first``: one name (case-folded on a folding volume) or one - file through a hard link. `tools/report_paths.same_report_path` owns that answer; this keeps the name the rest - of the tool calls.""" - return same_report_path(first, second) + """True when writing ``second`` would truncate ``first`` (same file, path or hard link).""" + if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)): + return True + try: + return os.path.samefile(first, second) + except OSError: + return False def input_files(carve, archs): diff --git a/tools/text_tables.py b/tools/text_tables.py index 0e9f82ec9..37638c7d0 100644 --- a/tools/text_tables.py +++ b/tools/text_tables.py @@ -59,7 +59,6 @@ if ROOT not in sys.path: sys.path.insert(0, ROOT) from file_mode import published_mode # noqa: E402 from hashdict import joaat # noqa: E402 -from report_paths import same_report_path # noqa: E402 RESOURCE_MAGIC = b"0DRP" RPF9_MAGIC = b"9FPR" @@ -427,6 +426,15 @@ def _write_csv(path, fields, rows): return n +def _same_output_path(first: str, second: str) -> bool: + if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)): + return True + try: + return os.path.samefile(first, second) + except OSError: + return False + + def main(argv=None) -> int: ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("sources", nargs="+", help="rpf9_carve.py directory, .rpf archive, or resource files/dirs") @@ -440,7 +448,7 @@ def main(argv=None) -> int: outs = [path for _, path in out_flags] seen = [] for flag, p in out_flags: - if any(same_report_path(p, prev) for prev in seen): + if any(_same_output_path(p, prev) for prev in seen): ap.error("outputs must be distinct files") seen.append(p) parent = os.path.dirname(os.path.abspath(p)) @@ -450,11 +458,11 @@ def main(argv=None) -> int: if not os.path.exists(path): print(f"text_tables: error: {path}: no such file or directory", file=sys.stderr) return 2 - if any(same_report_path(path, o) for o in outs): + if any(os.path.exists(o) and os.path.samefile(path, o) for o in outs): ap.error("an output must not overwrite an input") for source in a.sources: index = os.path.join(source, "index.json") - if os.path.isdir(source) and os.path.isfile(index) and any(same_report_path(index, o) for o in outs): + if os.path.isdir(source) and os.path.isfile(index) and any(_same_output_path(index, o) for o in outs): ap.error(f"an output must not overwrite an input: {index}") scan = Scan() @@ -533,7 +541,6 @@ def main(argv=None) -> int: pass for tmp, _ in staged: try: - os.chmod(tmp, 0o600) os.remove(tmp) except OSError: pass @@ -542,7 +549,6 @@ def main(argv=None) -> int: for backup in originals.values(): if backup is not None: try: - os.chmod(backup, 0o600) os.remove(backup) except OSError: pass diff --git a/tools/ttpf_assets.py b/tools/ttpf_assets.py index 0bd093b24..2dd35a1fd 100644 --- a/tools/ttpf_assets.py +++ b/tools/ttpf_assets.py @@ -68,14 +68,9 @@ def publish(path, data): try: with f: f.write(data) - tmp.chmod(published_mode(path)) + if os.name != "nt": + tmp.chmod(published_mode(path)) os.replace(tmp, path) - except BaseException: - try: - tmp.chmod(0o600) - except OSError: - pass - raise finally: tmp.unlink(missing_ok=True) diff --git a/tools/ttpf_mips.py b/tools/ttpf_mips.py index 0212fdea8..ebaa90fd2 100644 --- a/tools/ttpf_mips.py +++ b/tools/ttpf_mips.py @@ -53,7 +53,6 @@ import zlib sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import bcpack # noqa: E402 import bcpack_tables_bptc as _bptc # noqa: E402 -from report_paths import same_report_path # noqa: E402 from tex_headers import ( # noqa: E402 array_surface_layout, compact_surface_layout, cubemap_surface_layout, decode_etpf_chunk_pages, etpf_streaming_padding, gfx10_tile_bytes, @@ -1494,6 +1493,15 @@ def analyze(pool, index, *, allow_bcpack=True): # --- commands -------------------------------------------------------------- +def same_output_path(first, second): + if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)): + return True + try: + return os.path.samefile(first, second) + except OSError: + return False + + def find_pools(arg): """Pools under a game root (data/ttdb and pack/*/data/ttdb), or, for any other folder such as data/ttdb itself or one pack, every .ttpf below it. A file is taken as a pool.""" @@ -2177,7 +2185,7 @@ def main(argv=None): print(f"ERROR: --json {a.json} is a directory", file=sys.stderr) return 2 for p in pools: - if same_report_path(a.json, p): + if same_output_path(a.json, p): print(f"ERROR: --json would overwrite the input {p}", file=sys.stderr) return 2 try: @@ -2197,7 +2205,7 @@ def main(argv=None): continue if label == "--history file" and not os.path.isfile(asset): continue - if same_report_path(a.out, asset): + if same_output_path(a.out, asset): print(f"ERROR: {a.out} would overwrite the {label} {asset}", file=sys.stderr) return 2 try: diff --git a/tools/vertex_types.py b/tools/vertex_types.py index 75bc03950..39b133e70 100644 --- a/tools/vertex_types.py +++ b/tools/vertex_types.py @@ -46,7 +46,7 @@ import zlib sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from meshlet_page import PageError, parse_group # noqa: E402 (same group validation as the 63 30 pages) -from report_paths import path_key, same_report_path # noqa: E402 +from report_paths import path_key # noqa: E402 MAGIC = 0x4042 HEADER = 0x80 @@ -679,6 +679,15 @@ def summarise(T): return out +def same_output_path(first, second): + if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)): + return True + try: + return os.path.samefile(first, second) + except OSError: + return False + + def _walk_error(exc: OSError): # os.walk skips a directory it cannot list unless onerror raises; a scan must not report an # incomplete directory as complete. main() turns the OSError into one error line and exit 2. @@ -720,7 +729,7 @@ def main(argv=None): print(f"error: --json {args.json} is a directory", file=sys.stderr) return 2 for path in archives.values(): - if same_report_path(args.json, path): + if same_output_path(args.json, path): print(f"error: --json would overwrite the input {path}", file=sys.stderr) return 2 rng = random.Random(args.seed) diff --git a/tools/world_build.py b/tools/world_build.py index c6118e017..894c212fc 100644 --- a/tools/world_build.py +++ b/tools/world_build.py @@ -38,7 +38,6 @@ import stat import statistics import sys import tempfile -import unicodedata try: import fcntl @@ -1219,7 +1218,6 @@ def _write_json_atomic(path: str, data: dict, replace=None) -> None: except BaseException: try: if tmp_path is not None: - os.chmod(tmp_path, 0o600) os.remove(tmp_path) except OSError: pass @@ -1274,12 +1272,9 @@ def _exclusive_output(out_dir: str): # and a successful one must contain only chunks/ and world.json. Key it on the resolved # path so every spelling of one folder (8.3 names, junctions, symlinks) shares a lock; for # a folder that does not exist yet, realpath resolves the part that does and appends the rest. - # Fold conservatively on every platform: the output volume may ignore case or - # Unicode normalization even when os.path.normcase does not (APFS, for example). - # Distinct folders that fold alike can contend, but cannot publish concurrently. - resolved = os.path.normcase(os.path.realpath(out_dir)) - lock_name = unicodedata.normalize("NFD", unicodedata.normalize("NFD", resolved).casefold()) - key = hashlib.sha256(lock_name.encode("utf-8", "surrogatepass")).hexdigest()[:20] + key = hashlib.sha256( + os.path.normcase(os.path.realpath(out_dir)).encode("utf-8", "surrogatepass") + ).hexdigest()[:20] lock_path = os.path.join(tempfile.gettempdir(), _WORLD_BUILD_LOCK + key) with open(lock_path, "a+b") as fh: fd = fh.fileno() diff --git a/tools/world_census.py b/tools/world_census.py index 73394b2be..c7a77f00d 100644 --- a/tools/world_census.py +++ b/tools/world_census.py @@ -111,13 +111,7 @@ def _staged_json(path, doc, **options): else: if stat.S_ISREG(mode): os.chmod(tmp, mode & 0o777) - try: - yield tmp - finally: - try: - os.chmod(tmp, 0o600) - except OSError: - pass + yield tmp def _publish_reports(archive, source_id, summary_tmp, summary_path, maps_tmp, maps_path): diff --git a/tools/world_index.py b/tools/world_index.py index ccdd4e57b..f1e542270 100644 --- a/tools/world_index.py +++ b/tools/world_index.py @@ -39,9 +39,6 @@ import tempfile import zlib from contextlib import contextmanager -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from file_mode import published_mode - # -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module. _TOOLS_DIR = os.path.dirname(os.path.abspath(__file__)) if _TOOLS_DIR not in sys.path: @@ -797,22 +794,15 @@ def _staged_entity_report(path): try: with open(staged, "w", encoding="utf-8", newline="\n") as handle: yield EntityRows(handle) - try: - os.chmod(staged, published_mode(destination)) - except OSError: - pass + if mode is not None: + os.chmod(staged, mode & 0o777) os.replace(staged, destination) finally: if os.path.exists(staged): - try: - os.chmod(staged, 0o600) - except OSError: - pass + if os.name == "nt": + os.chmod(staged, stat.S_IWRITE) os.unlink(staged) - try: - os.rmdir(directory) - except OSError: - pass + os.rmdir(directory) def main(argv=None): diff --git a/tools/world_lights_paths.py b/tools/world_lights_paths.py index 349d28b62..27bf329b8 100644 --- a/tools/world_lights_paths.py +++ b/tools/world_lights_paths.py @@ -50,7 +50,6 @@ if _TOOLS_DIR not in sys.path: from pool_workers import process_workers # noqa: E402 from report_paths import same_report_path # noqa: E402 -from file_mode import published_mode # noqa: E402 import world_census as WC # noqa: E402 import world_index as WI # noqa: E402 @@ -778,10 +777,6 @@ def summarize(total, entities=None, lights_out=None): pass out = None if staged is not None and os.path.exists(staged): - try: - os.chmod(staged, 0o600) - except OSError: - pass os.remove(staged) raise finally: @@ -789,15 +784,10 @@ def summarize(total, entities=None, lights_out=None): out.close() if staged is not None: try: - os.chmod(staged, published_mode(lights_out)) os.replace(staged, lights_out) except BaseException: # A destination that is a directory (or read-only) must not leave the staged copy behind. if os.path.exists(staged): - try: - os.chmod(staged, 0o600) - except OSError: - pass os.remove(staged) raise summary["placement"] = dict(placed) diff --git a/tools/world_names.py b/tools/world_names.py index ae600c307..a7b4ca84d 100644 --- a/tools/world_names.py +++ b/tools/world_names.py @@ -38,7 +38,6 @@ import tempfile # -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module. sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from file_mode import published_mode # noqa: E402 from report_paths import same_report_path # noqa: E402 MASK32 = 0xFFFFFFFF @@ -631,12 +630,7 @@ def _write_json(path: str, data: dict) -> None: with open(tmp, "w", encoding="utf-8", newline="\n") as handle: json.dump(data, handle, indent=1, sort_keys=True) handle.write("\n") - os.chmod(tmp, published_mode(path)) - try: - os.replace(tmp, path) - except BaseException: - os.chmod(tmp, 0o600) - raise + os.replace(tmp, path) def main(argv=None) -> int: diff --git a/tools/x64_recomp.py b/tools/x64_recomp.py index 338c369aa..47c3dbd56 100644 --- a/tools/x64_recomp.py +++ b/tools/x64_recomp.py @@ -32,7 +32,6 @@ from __future__ import annotations import argparse import os -import shutil import struct import sys @@ -2597,9 +2596,11 @@ def build_test_kernel(code, guest_va, rw_base=KERNEL_RW, rx_base=KERNEL_BASE): return stub_bytes(entry_va) + img, tr -# QEMU_AARCH64 names a binary that is not on PATH; otherwise the one on PATH, else the bare name for a clear error. -QEMU_BIN = (os.environ.get("QEMU_AARCH64") or shutil.which("qemu-system-aarch64") - or "qemu-system-aarch64") +QEMU_BIN = os.environ.get( + "QEMU_AARCH64", + "/home/nolan/.nix-profile/bin/qemu-system-aarch64" + if os.path.exists("/home/nolan/.nix-profile/bin/qemu-system-aarch64") + else "qemu-system-aarch64") def run_kernel(code, guest_va=0x46000000, timeout=15): -- cgit v1.2.3