PS2 games in the browser: static recompilation to WebAssembly with a native runtime
C++
Add experimental GT3 runtime and porting prerequisites
Bryan Ward00fc9c0c93e7
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 6765f07..8b39f64 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -83,6 +83,21 @@ if(EMSCRIPTEN OR EXISTS "${PS2_WGPU_DIR}/lib/libwgpu_native.a")endif()endif()+option(PS2_BUILD_TESTS "Build native synthetic runtime tests (no game data required)" OFF)+if(PS2_BUILD_TESTS AND NOT EMSCRIPTEN)+ enable_testing()+ foreach(name IN ITEMS sif_scratchpad kernel_exit_delete_thread gt3_initialization gt3_state)+ add_executable(${name}_test tests/${name}_test.cpp)+ target_include_directories(${name}_test PRIVATE runtime/src)+ target_link_libraries(${name}_test PRIVATE ps2runtime)+ add_test(NAME ${name} COMMAND ${name}_test)+ endforeach()+ find_package(Python3 COMPONENTS Interpreter QUIET)+ if(Python3_Interpreter_FOUND)+ add_test(NAME gt3_core COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/gt3_core_test.py")+ endif()+endif()+if(PS2_GENERATED)file(GLOB PS2_UNITS CONFIGURE_DEPENDS "${PS2_GENERATED}/*.cpp")add_library(ps2game STATIC ${PS2_UNITS})diff --git a/README.md b/README.mdindex 606a26b..be6fbdd 100644--- a/README.md+++ b/README.md@@ -105,6 +105,12 @@ This repository contains only original code and third-party code under its own lThe VLC tables of the MPEG decoder are adapted from [Play!](https://github.com/jpd002/Play-) (BSD 2-clause, notice in `runtime/src/ipu/NOTICE`). PCSX2, Play! and the ps2sdk headers were the references for much of the hardware and system behavior emulated here. wgpu-native and Dawn provide WebGPU natively and in the browser, and Emscripten builds the WebAssembly.+## Experimental GT3 bring-up++See [the GT3 bring-up notes](docs/gt3.md) for the focused runtime/tooling changes,+synthetic and game-backed checks, snapshot compatibility and current validation limits.+This is not a claim of complete GT3 compatibility.+## LicenseThe code in this repository is available under the MIT License, see [LICENSE](LICENSE). `runtime/src/ipu/tables.hpp` keeps the BSD 2-clause notice of Play!.diff --git a/docs/gt3.md b/docs/gt3.mdnew file mode 100644index 0000000..2538dcf--- /dev/null+++ b/docs/gt3.md@@ -0,0 +1,153 @@+# Gran Turismo 3 bring-up (experimental)++This work builds on **snuri00/ps2-web-recomp**, retaining its history, MIT+license and attribution. It contributes runtime/tooling prerequisites identified+while bringing up Gran Turismo 3; it is not a separate graphics implementation+or a claim of complete GT3 compatibility.++## Scope++- Recognize `CORE.GT3` as well as `CORE.GT4` in the port pipeline, using the+ existing CORE-to-ELF converter. Cached `core.elf` and ordinary BOOT2 executable+ fallback behavior are preserved. Selection consumes the full directory listing+ to avoid producer SIGPIPE under `set -o pipefail`.+- Read SIF EE descriptor words through the memory resolver, including scratchpad.+ This does not implement scratchpad DMA payload sources.+- Enter idle and unwind when `ExitDeleteThread` leaves no runnable thread.+- Minimal local i.Link identification, serial-clock-ready and PHY-access+ completion/register storage, completion status/interrupt and write-one-to-clear+ behavior. This is sufficient to exercise initialization with no attached peer;+ it is **not** complete IEEE 1394 hardware, packet transfer or GT3 network play.+- Regression coverage for the existing upstream guest-visible INTC latch. Current+ upstream already retains status after HLE handler delivery; that behavior is+ preserved, not replaced. The retained latch is additionally saved/restored.+- Zero-length snapshot reader/writer guards for empty container data pointers.++No projection/FOV patch, independent render scaling, camera override, SIMD+optimization, benchmark harness or LAN streaming code is included. Stock+rendering, controls and launch defaults otherwise remain in place.++## Snapshot compatibility++Runtime snapshot **version 7** adds the retained INTC latch and i.Link PHY+registers on top of upstream version 6. Upstream versions 2–6 remain loadable;+fields absent from those layouts reset to zero. Versions 0, 1 and newer than 7+are rejected at the header gate before CPU/RAM mutation. Older builds cannot+load version 7 snapshots. Preserve old snapshots before upgrading. This does+not change or delete memory-card `.ps2` files, disc images or previous builds.+Snapshot formats from separate experimental forks (including the original+PR's version 3 layout) are not interchangeable merely because their version+numbers happen to match.++## Validation and limits++Rebased onto upstream `e026b97`. Five native CTest groups pass on Linux x86-64,+Clang 23.1.3, in Release and Debug with ASan/UBSan (leak detection and+halt-on-UB enabled). The existing tail-call discovery, executable BSS and+codegen fallthrough regressions also pass:++1. SIF scratchpad descriptor list, conflicting RAM descriptors and five RAM aliases.+2. Deleted-thread idle/unwind, dormant-thread and ready-worker control cases.+3. INTC polling/delivery/W1C, latch restoration, local i.Link initialization,+ masked/enabled completion IRQs, PHY register restoration and reset, and+ hardware-section compatibility/defaults for upstream snapshot versions 2–6.+4. Full **synthetic** runtime snapshot round-trip, version gate and zero-length+ serialization. Generated temporary files contain no game data and are removed.+5. Synthetic GT3/GT4 CORE conversion, actual port-script selection, cached-core+ precedence, normal-executable fallback and a long directory listing.++Tests added to unmodified upstream fail in the corresponding missing behaviors.+The existing live INTC polling behavior already passes upstream; its **snapshot+retention** is the new fix. Full snapshot sanitizer testing also exposed the+previous zero-length/null `memcpy` issue. A separate full synthetic snapshot+written by an unmodified upstream-v6 runtime also loads successfully here:+CPU, RAM and pending interrupts restore, while the newly added latch and PHY+storage reset to zero. This checks an actual old layout, not a new snapshot+with its version header relabeled.++Fresh native validation on this rebased branch, using a local GT3 USA v1.10+disc image and newly generated game code, reached boot, the title screen,+Arcade Single Race menus, track/car selection, countdown and driving through+4,800 frames. Captures were inspected: the car accelerates through 42, 67 and+85 mph, and R1 switches from bumper to chase camera while driving. A version 7 race snapshot saved at frame 4,200 resumes successfully;+frames 4,500 and 4,800 match the uninterrupted run byte-for-byte.++A fresh `port.sh --native-only` run from the original disc detects `CORE.GT3`,+translates the executable, explores 3,600 frames with zero missing entry points,+records/compiles 91 VU1 programs and produces the final native runner. That+runner also loads the frame-4,200 race snapshot and advances 600 frames;+its frame-4,500 and frame-4,800 captures match the uninterrupted run byte-for-byte.++Browser validation uses Chrome for Testing 156.0.8078.4 on Linux with an AMD+RDNA 4 WebGPU adapter and cross-origin isolation enabled. Both direct WebGPU+presentation and the existing `?copy` fallback reach boot, menus and driving+through 4,800 frames. Canvas captures pass nonblank-pixel checks and were+inspected visually. Both paths save/load a version 7 snapshot and advance at+least 120 more frames after loading.++For headless Chromium checks, use `--enable-unsafe-webgpu+--enable-features=Vulkan --use-angle=vulkan` without+`--disable-vulkan-surface`. The latter caused blank captures/timeouts even on a+standalone solid-color WebGPU probe; this was a harness issue, not a GT3 fix.++GT4 gameplay, other revisions/regions and universal black-screen fixes are not+claimed. GCC remains blocked by pre-existing Clang-specific vector builtins+upstream. These checks do not establish complete game compatibility.++## Reproduce the synthetic tests++No game, generated translation, SDL window or GPU setup is needed in a fresh+clone. Tests default OFF and are native-only. Python 3 and Bash are needed for+CORE/tooling tests; CMake registers that group when Python is available.++```bash+cmake -S . -B build/gt3-tests -G Ninja \+ -DCMAKE_CXX_COMPILER=clang++ -DCMAKE_BUILD_TYPE=Release -DPS2_BUILD_TESTS=ON+cmake --build build/gt3-tests --target \+ sif_scratchpad_test kernel_exit_delete_thread_test gt3_initialization_test gt3_state_test+ctest --test-dir build/gt3-tests --output-on-failure+```++## Try with a disc you own++Follow the repository's existing toolchain setup instructions, then:++```bash+bash scripts/port.sh gt3 /path/to/your/gt3.iso --native-only+build/native-gt3/ps2run games/gt3/core.elf --disc games/gt3/disc.iso --ntsc --window+# Browser build (requires the documented Emscripten setup):+bash scripts/port.sh gt3 /path/to/your/gt3.iso+python3 scripts/serve.py build/web-gt3 games/gt3/disc.iso+```++For a repeatable native race/snapshot check after building, run the following+from Bash. This uses the USA disc's NTSC rate and stores private artifacts under+`build/gt3-check`; inspect captures as well as the exit status.++```bash+mkdir -p build/gt3-check/continuous build/gt3-check/resumed+presses=(--press 300:start)+for ((f = 600; f <= 3300; f += 300)); do presses+=(--press "$f:cross"); done+build/native-gt3/ps2run games/gt3/core.elf --disc games/gt3/disc.iso --ntsc \+ --memcard build/gt3-check/card.ps2 --frames 4800 "${presses[@]}" \+ --press 3600:cross:1200 --press 4000:select \+ --save-state 4200:build/gt3-check/race.state \+ --frames-dir build/gt3-check/continuous --frame-every 300+build/native-gt3/ps2run games/gt3/core.elf --disc games/gt3/disc.iso --ntsc \+ --load-state build/gt3-check/race.state --run 600 --press 4200:cross:600 \+ --frames-dir build/gt3-check/resumed --frame-every 300+for f in 04500 04800; do+ cmp "build/gt3-check/continuous/frame_$f.ppm" "build/gt3-check/resumed/frame_$f.ppm"+done+```++The window command requires an SDL-enabled native build; omit `--window` for+headless diagnostics. Use the appropriate region's video standard, rather than+forcing NTSC for a PAL disc. Exploration reaching its frame limit is not proof+that boot or rendering succeeded: inspect the exploration log and frames.+These are reproduction entry points, not guarantees of a complete port.++Keep disc contents, CORE/ELF files, generated game C++, built game libraries and+binaries, snapshots, memory dumps, game-derived assembly/decompilation and+captures local. None are shipped here. Prefer sanitized runtime diagnostics+rather than posting game material in issues or PRs.diff --git a/runtime/include/ps2/state.hpp b/runtime/include/ps2/state.hppindex 801accb..2ed65e2 100644--- a/runtime/include/ps2/state.hpp+++ b/runtime/include/ps2/state.hpp@@ -155,6 +155,7 @@ class Writer : public Stream {public:Writer() : Stream(true) {}void bytes(void *data, std::size_t size) override {+ if (!size) return; // Empty containers may have a null data() pointer.const auto *p = static_cast<const std::uint8_t *>(data);out.insert(out.end(), p, p + size);}@@ -165,6 +166,7 @@ class Reader : public Stream {public:Reader(const std::uint8_t *data, std::size_t size) : Stream(false), at_(data), end_(data + size) {}void bytes(void *data, std::size_t size) override {+ if (!size) return;if (static_cast<std::size_t>(end_ - at_) < size) throw std::runtime_error("state file is truncated");std::memcpy(data, at_, size);at_ += size;diff --git a/runtime/src/hw.cpp b/runtime/src/hw.cppindex e56369b..3f68162 100644--- a/runtime/src/hw.cpp+++ b/runtime/src/hw.cpp@@ -302,6 +302,8 @@ std::function<void()> event_action(int id, std::uint64_t at) {void state(ps2::state::Stream &s) {s.tag("eehw");s.pod(g_intc_stat);+ if (s.version() >= 7) s.pod(g_intc_latched);+ else if (s.loading()) g_intc_latched = 0;s.pod(g_intc_mask);s.pod(g_dmac_stat);s.map(g_regs);diff --git a/runtime/src/iop/hw.cpp b/runtime/src/iop/hw.cppindex 4505e58..347f9ce 100644--- a/runtime/src/iop/hw.cpp+++ b/runtime/src/iop/hw.cpp@@ -83,6 +83,7 @@ struct Dma {};Dma g_dma[14];std::uint32_t g_ohci[0x18];+std::uint8_t g_ilink_phy[16];int dma_channel(std::uint32_t a, std::uint32_t ®) {if (a >= 0x1F801080u && a < 0x1F8010F0u) {@@ -129,6 +130,7 @@ void reset() {spu2::reset();sio2::reset();std::memset(g_ohci, 0, sizeof g_ohci);+ std::memset(g_ilink_phy, 0, sizeof g_ilink_phy);}void raise_interrupt(unsigned line) {@@ -210,6 +212,8 @@ void ohci_write(std::uint32_t a, std::uint32_t v) {}std::uint32_t read(std::uint32_t a, unsigned size) {+ if (a == 0x1F808400u) return 0xFFC00001u;+ if (a == 0x1F80847Cu) return 0x10000001u;if (a >= 0x1F900000u && a < 0x1F900800u) return spu2::read(a, size);if (a >= 0x1F801600u && a < 0x1F801660u) return ohci_read(a);if (a >= 0x1F808200u && a < 0x1F808280u) return sio2::read(a);@@ -238,6 +242,26 @@ std::uint32_t read(std::uint32_t a, unsigned size) {}void write(std::uint32_t a, std::uint32_t v, unsigned size) {+ // Minimal local i.Link initialization with no attached peers. Complete+ // PHY accesses and report a ready serial clock; no link traffic is modeled.+ if (a == 0x1F808410u) { g_regs[a] = (v & 2u) | 8u; return; }+ if (a == 0x1F808408u) { g_regs[a] = v & ~0x00800000u; return; }+ if (a == 0x1F808420u || a == 0x1F808428u || a == 0x1F808430u) {+ g_regs[a] &= ~v;+ return;+ }+ if (a == 0x1F808414u) {+ if (v & 0x40000000u) {+ g_ilink_phy[(v >> 8) & 15u] = static_cast<std::uint8_t>(v);+ g_regs[a] = v & ~0x4000FFFFu;+ } else if (v & 0x80000000u) {+ const std::uint32_t reg = (v >> 24) & 15u;+ g_regs[a] = (v & ~0x8000FFFFu) | (reg << 8) | g_ilink_phy[reg];+ g_regs[0x1F808420u] |= 0x40000000u;+ if (g_regs[0x1F808424u] & 0x40000000u) raise_interrupt(24);+ } else g_regs[a] = v;+ return;+ }if (a >= 0x1F900000u && a < 0x1F900800u) { spu2::write(a, v, size); return; }if (a >= 0x1F801600u && a < 0x1F801660u) { ohci_write(a, v); return; }if (a >= 0x1F808200u && a < 0x1F808280u) { sio2::write(a, v); return; }@@ -287,6 +311,8 @@ void state(ps2::state::Stream &s) {s.map(g_regs);s.pod(g_dma);s.pod(g_ohci);+ if (s.version() >= 7) s.pod(g_ilink_phy);+ else if (s.loading()) std::memset(g_ilink_phy, 0, sizeof g_ilink_phy);s.pod(g_scratchpad);}diff --git a/runtime/src/iop/sif.cpp b/runtime/src/iop/sif.cppindex 710e6b3..884986e 100644--- a/runtime/src/iop/sif.cpp+++ b/runtime/src/iop/sif.cpp@@ -89,9 +89,9 @@ std::uint64_t g_ee_dma_done = 0;template <typename T>T ee_read(std::uint32_t a) {- T v;- std::memcpy(&v, g_ram + (a & (kRamSize - 1)), sizeof v);- return v;+ // EE words may reside in scratchpad, not just main RAM.+ static_assert(sizeof(T) == sizeof(std::uint32_t));+ return static_cast<T>(ld32(a));}void send(const void *packet, std::uint32_t size) {diff --git a/runtime/src/kernel.cpp b/runtime/src/kernel.cppindex 3024df3..e9c5433 100644--- a/runtime/src/kernel.cpp+++ b/runtime/src/kernel.cpp@@ -140,7 +140,9 @@ Thread *best_ready() {void switch_to(Cpu &c, Thread *next) {Thread *cur = current();- if (cur == next) return;+ // After ExitDeleteThread, both pointers can be null. Still enter idle+ // and unwind instead of continuing the deleted thread's guest code.+ if (cur && cur == next) return;if (cur && (cur->status == kRun || cur->status == kReady || cur->status == kWait || cur->status == kSuspend || cur->status == kWaitSuspend)) {save_context(c, cur->context);if (cur->status == kRun) cur->status = kReady;diff --git a/runtime/src/system.cpp b/runtime/src/system.cppindex 86f8ca9..a7b9126 100644--- a/runtime/src/system.cpp+++ b/runtime/src/system.cpp@@ -268,7 +268,8 @@ std::uint32_t video_options() { return g_video_options.load(std::memory_order_renamespace {constexpr char kStateMagic[8] = {'P', 'S', '2', 'S', 'T', 'A', 'T', 'E'};-constexpr std::uint32_t kStateVersion = 6;+// Version 7 adds the retained INTC latch and i.Link PHY register state.+constexpr std::uint32_t kStateVersion = 7;std::function<void()> event_action(int id, std::uint64_t at) {if (id == hw::kEventVblank) return vblank;diff --git a/scripts/gt4_core.py b/scripts/gt4_core.pyindex c3ccb39..7814207 100644--- a/scripts/gt4_core.py+++ b/scripts/gt4_core.py@@ -67,7 +67,7 @@ def elf(entry, segments):def main():- parser = argparse.ArgumentParser(description="Turn Gran Turismo 4's CORE.GT4 into an ELF the recompiler can read.")+ parser = argparse.ArgumentParser(description="Turn Gran Turismo 3/4's CORE.GT3/CORE.GT4 into an ELF the recompiler can read.")parser.add_argument('core')parser.add_argument('output')args = parser.parse_args()diff --git a/scripts/port.sh b/scripts/port.shindex 6370a3a..d7c5e49 100755--- a/scripts/port.sh+++ b/scripts/port.sh@@ -85,10 +85,13 @@ echo "== [2/6] executable"elf="$game/disc/$program"if [ -f "$game/core.elf" ]; thenelf="$game/core.elf"-elif python3 -I "$here/disc.py" list "$iso" | awk '{print $4}' | grep -qx CORE.GT4; then- python3 -I "$here/disc.py" extract "$iso" "$game/disc" CORE.GT4 > /dev/null- python3 -I "$here/gt4_core.py" "$game/disc/CORE.GT4" "$game/core.elf" > /dev/null- elf="$game/core.elf"+else+ core=$(python3 -I "$here/disc.py" list "$iso" | awk '($4 == "CORE.GT3" || $4 == "CORE.GT4") && !core { core = $4 } END { if (core) print core }')+ if [ -n "$core" ]; then+ python3 -I "$here/disc.py" extract "$iso" "$game/disc" "$core" > /dev/null+ python3 -I "$here/gt4_core.py" "$game/disc/$core" "$game/core.elf" > /dev/null+ elf="$game/core.elf"+ fifirm -rf "$game/patched" "$game/patches.txt"if [ ${#pnach[@]} -gt 0 ]; thendiff --git a/tests/gt3_core_test.py b/tests/gt3_core_test.pynew file mode 100644index 0000000..c430d2b--- /dev/null+++ b/tests/gt3_core_test.py@@ -0,0 +1,110 @@+"""Game-free CORE wrapper/conversion and port-script selection regressions."""+import importlib.util+import os+import struct+import subprocess+import sys+import tempfile+import unittest+import zlib+from pathlib import Path++sys.dont_write_bytecode = True+ROOT = Path(__file__).resolve().parents[1]+SPEC = importlib.util.spec_from_file_location('core', ROOT / 'scripts/gt4_core.py')+assert SPEC is not None and SPEC.loader is not None+CORE = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(CORE)+++class CoreTests(unittest.TestCase):+ def test_gt3_and_gt4_synthetic_containers(self):+ # Metadata and payloads are invented; no game executable is embedded.+ parts = [(0x10000, b'synthetic-first'), (0x12000, b'synthetic-second')]+ image = b''+ for name in (b'synthetic', b'fixture'):+ image += struct.pack('<H', len(name)) + name+ image += struct.pack('<iI', len(parts), 0x10000)+ for address, data in parts:+ image += struct.pack('<II', address, len(data)) + data+ compressor = zlib.compressobj(wbits=-15)+ packed = struct.pack('<HI', 0, len(image)) + compressor.compress(image) + compressor.flush()+ self.assertEqual(CORE.sections(CORE.unpack(packed)), (0x10000, parts))+ for name in ('CORE.GT3', 'CORE.GT4'):+ with self.subTest(name=name), tempfile.TemporaryDirectory() as tmp:+ src, out = Path(tmp) / name, Path(tmp) / 'synthetic.elf'+ src.write_bytes(packed)+ subprocess.run([sys.executable, '-I', str(ROOT / 'scripts/gt4_core.py'), str(src), str(out)],+ check=True, capture_output=True, text=True)+ elf = out.read_bytes()+ self.assertEqual(elf[:7], b'\x7fELF\x01\x01\x01')+ self.assertEqual(struct.unpack_from('<I', elf, 24)[0], 0x10000)+ self.assertEqual(struct.unpack_from('<I', elf, 36)[0], CORE.R5900_FLAGS)+ self.assertEqual(struct.unpack_from('<H', elf, 44)[0], len(parts))+ for i, (address, data) in enumerate(parts):+ header = struct.unpack_from('<8I', elf, 52 + i * 32)+ self.assertEqual(header[0], 1)+ self.assertEqual(header[2:6], (address, address, len(data), len(data)))+ self.assertEqual(elf[header[1]:header[1] + header[4]], data)++ def selection(self, listing, cached=False):+ # Exercise the actual executable-selection block, not a copy of its awk.+ script = (ROOT / 'scripts/port.sh').read_text()+ stage = script.split('echo "== [2/6] executable"', 1)[1].split('rm -rf "$game/patched"', 1)[0]+ with tempfile.TemporaryDirectory() as tmp:+ game = Path(tmp) / 'game'+ (game / 'disc').mkdir(parents=True)+ if cached:+ (game / 'core.elf').write_bytes(b'synthetic-cache')+ listing_file = Path(tmp) / 'listing'+ listing_file.write_text(listing)+ calls = Path(tmp) / 'calls'+ env = dict(os.environ, ROOT=str(ROOT), here=str(ROOT / 'scripts'), game=str(game),+ iso='unused-synthetic.iso', program='BOOT.ELF', LISTING_FILE=str(listing_file), CALLS=str(calls))+ mock = r'''+python3() {+ printf '%s\n' "$*" >> "$CALLS"+ if [[ "$2" == "$here/disc.py" ]]; then+ if [[ "$3" == list ]]; then+ while IFS= read -r line; do printf '%s\n' "$line"; done < "$LISTING_FILE"+ elif [[ "$3" == extract ]]; then+ touch "$5/$6"+ else return 1; fi+ elif [[ "$2" == "$here/gt4_core.py" ]]; then+ touch "$4"+ else return 1; fi+}+'''+ result = subprocess.run(['bash', '-euo', 'pipefail', '-c', mock + stage + '\nprintf "%s\\n" "$elf"'],+ env=env, text=True, capture_output=True, check=True)+ return Path(result.stdout.strip()).name, calls.read_text() if calls.exists() else ''++ def test_gt3_selection(self):+ selected, calls = self.selection('1 2 3 CORE.GT3\n')+ self.assertEqual(selected, 'core.elf')+ self.assertIn('extract', calls)+ self.assertIn('CORE.GT3', calls)++ def test_gt4_selection(self):+ selected, calls = self.selection('1 2 3 CORE.GT4\n')+ self.assertEqual(selected, 'core.elf')+ self.assertIn('CORE.GT4', calls)++ def test_normal_boot_fallback(self):+ selected, calls = self.selection('1 2 3 OTHER.DAT\n')+ self.assertEqual(selected, 'BOOT.ELF')+ self.assertNotIn('extract', calls)++ def test_cached_core_precedence(self):+ selected, calls = self.selection('1 2 3 CORE.GT3\n', cached=True)+ self.assertEqual(selected, 'core.elf')+ self.assertEqual(calls, '')++ def test_selection_consumes_long_listing(self):+ # Early awk exit would SIGPIPE a long producer under set -o pipefail.+ selected, _ = self.selection('1 2 3 CORE.GT3\n' + '1 2 3 SYNTHETIC.DAT\n' * 10000)+ self.assertEqual(selected, 'core.elf')+++if __name__ == '__main__':+ unittest.main()diff --git a/tests/gt3_initialization_test.cpp b/tests/gt3_initialization_test.cppnew file mode 100644index 0000000..e08f512--- /dev/null+++ b/tests/gt3_initialization_test.cpp@@ -0,0 +1,123 @@+#include "hw.hpp"+#include "iop/hw.hpp"+#include "kernel.hpp"+#include "ps2/state.hpp"++#include <cstdint>+#include <cstdio>++namespace {+int failures = 0;+void check(bool ok, const char *message) {+ if (!ok) { std::fprintf(stderr, "FAIL: %s\n", message); ++failures; }+}++void interrupt_latch() {+ using namespace ps2;+ hw::reset();+ kernel::reset();+ kernel::start_main_thread(0x10000, 0, 0, 0);+ hw::intc_set_mask(2, true);+ hw::intc_set_mask(3, true);+ hw::intc_raise(2);+ check(hw::intc_pending() == 4, "vblank is pending");+ hw::intc_ack(2);+ check(hw::intc_pending() == 0, "delivered interrupt is not repeatedly dispatched");+ check(hw::read32(0x1000F000) == 4, "guest can still poll the delivered interrupt");+ hw::intc_raise(3);+ state::Writer saved;+ saved.set_version(7);+ hw::state(saved);+ saved.tag("done");+ hw::reset();+ state::Reader restored(saved.out.data(), saved.out.size());+ restored.set_version(7);+ hw::state(restored);+ restored.tag("done");+ check(hw::read32(0x1000F000) == 12, "snapshot retains delivered and pending interrupt latches");+ check(hw::intc_pending() == 8, "restoring a delivered latch does not redeliver its handler");+ hw::write32(0x1000F000, 4);+ check(hw::read32(0x1000F000) == 8, "write-one-to-clear preserves unrelated status");+ check(hw::intc_pending() == 8, "write-one-to-clear preserves unrelated pending delivery");+ hw::intc_raise(2);+ check(hw::intc_pending() == 12, "a new vblank can be delivered again");+}++void ilink_initialization() {+ using namespace ps2;+ iop::hw::reset();+ check(iop::hw::read(0x1F808400, 4) == 0xFFC00001, "local i.Link identification stub");+ check(iop::hw::read(0x1F80847C, 4) == 0x10000001, "local i.Link capability stub");+ iop::hw::write(0x1F808410, 2, 4);+ check((iop::hw::read(0x1F808410, 4) & 10) == 10, "link initialization reports serial clock ready");+ iop::hw::write(0x1F808408, 0x00800000, 4);+ check((iop::hw::read(0x1F808408, 4) & 0x00800000) == 0, "local initialization request completes");+ iop::hw::write(0x1F808414, 0x400004A5, 4);+ check((iop::hw::read(0x1F808414, 4) & 0x40000000) == 0, "PHY write completes");+ iop::hw::write(0x1F808414, 0x84000000, 4);+ check((iop::hw::read(0x1F808414, 4) & 0x8000FFFF) == 0x04A5, "PHY read completes and returns its register");+ iop::hw::set_interrupt_mask(24, true);+ check(iop::hw::next_pending_interrupt() != 24, "masked PHY completion does not raise the device IRQ");+ iop::hw::write(0x1F808424, 0x40000000, 4);+ iop::hw::write(0x1F808414, 0x84000000, 4);+ check(iop::hw::next_pending_interrupt() == 24, "enabled PHY completion raises i.Link IRQ");+ check((iop::hw::read(0x1F808420, 4) & 0x40000000) != 0, "PHY completion sets status");+ iop::hw::write(0x1F808420, 0x40000000, 4);+ check(iop::hw::read(0x1F808420, 4) == 0, "PHY status is write-one-to-clear");+ iop::hw::write(0x1F808414, 0x4000053C, 4);+ state::Writer saved;+ saved.set_version(7);+ iop::hw::state(saved);+ saved.tag("done");+ iop::hw::reset();+ state::Reader restored(saved.out.data(), saved.out.size());+ restored.set_version(7);+ iop::hw::state(restored);+ restored.tag("done");+ iop::hw::write(0x1F808414, 0x84000000, 4);+ check((iop::hw::read(0x1F808414, 4) & 0xFFFF) == 0x04A5, "snapshot restores PHY register 4");+ iop::hw::write(0x1F808414, 0x85000000, 4);+ check((iop::hw::read(0x1F808414, 4) & 0xFFFF) == 0x053C, "snapshot restores a distinct PHY register");+ iop::hw::reset();+ iop::hw::write(0x1F808414, 0x84000000, 4);+ check((iop::hw::read(0x1F808414, 4) & 0xFF) == 0, "reset clears PHY register storage");+}++void legacy_hardware_states() {+ using namespace ps2;+ for (std::uint32_t version = 2; version <= 6; ++version) {+ hw::reset();+ iop::hw::reset();+ hw::intc_set_mask(2, true);+ hw::intc_raise(2);+ iop::hw::write(0x1F808414, 0x400004A5, 4);+ state::Writer saved;+ saved.set_version(version);+ hw::state(saved);+ iop::hw::state(saved);+ saved.tag("done");+ // Poison the new fields: old snapshots must reset, not retain them.+ hw::intc_raise(3);+ iop::hw::write(0x1F808414, 0x400004CC, 4);+ state::Reader restored(saved.out.data(), saved.out.size());+ restored.set_version(version);+ hw::state(restored);+ iop::hw::state(restored);+ restored.tag("done");+ check(hw::intc_pending() == 4, "legacy snapshot retains pending interrupt and mask");+ hw::intc_ack(2);+ check(hw::read32(0x1000F000) == 0, "legacy snapshot clears unsaved retained latch");+ iop::hw::write(0x1F808414, 0x84000000, 4);+ check((iop::hw::read(0x1F808414, 4) & 0xFF) == 0, "legacy snapshot clears unsaved PHY storage");+ }+}+}++int main() {+ interrupt_latch();+ ilink_initialization();+ legacy_hardware_states();+ if (failures) return 1;+ std::puts("GT3 initialization regression PASS");+ return 0;+}diff --git a/tests/gt3_state_test.cpp b/tests/gt3_state_test.cppnew file mode 100644index 0000000..ec6fb41--- /dev/null+++ b/tests/gt3_state_test.cpp@@ -0,0 +1,76 @@+#include "hw.hpp"+#include "iop/hw.hpp"+#include "iop/iop.hpp"+#include "kernel.hpp"+#include "ps2/memory.hpp"+#include "ps2/state.hpp"+#include "ps2/system.hpp"++#include <chrono>+#include <cstdio>+#include <cstring>+#include <filesystem>+#include <fstream>+#include <iterator>+#include <vector>++int main() {+ using namespace ps2;+ const auto dir = std::filesystem::temp_directory_path() /+ ("ps2-state-test-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));+ if (!std::filesystem::create_directory(dir)) return 1;+ struct Cleanup {+ std::filesystem::path path;+ ~Cleanup() { std::error_code ec; std::filesystem::remove_all(path, ec); }+ } cleanup{dir};+ int failures = 0;+ const auto check = [&](bool ok, const char *message) {+ if (!ok) { std::fprintf(stderr, "FAIL: %s\n", message); ++failures; }+ };+ state::Writer empty;+ empty.bytes(nullptr, 0);+ check(empty.out.empty(), "zero-length write accepts a null pointer");+ const std::uint8_t sentinel = 0xA5;+ state::Reader zero(&sentinel, 1);+ zero.bytes(nullptr, 0);+ std::uint8_t value = 0;+ zero.pod(value);+ check(value == sentinel, "zero-length read accepts null and does not advance");+ hw::reset();+ iop::reset();+ kernel::reset();+ kernel::start_main_thread(0x10000, 0, 0, 0);+ hw::intc_set_mask(2, true);+ hw::intc_raise(2);+ hw::intc_ack(2);+ iop::hw::write(0x1F808414, 0x400004A5, 4);+ const auto path = (dir / "synthetic.state").string();+ if (!save_state(path)) return 1;+ std::ifstream input(path, std::ios::binary);+ std::vector<std::uint8_t> bytes{std::istreambuf_iterator<char>(input), {}};+ if (bytes.size() < 12) return 1;+ std::uint32_t version;+ std::memcpy(&version, bytes.data() + 8, sizeof version);+ check(version == 7, "new snapshot layout uses version 7");+ hw::reset();+ iop::hw::reset();+ g_cpu.pc = 0x20000;+ check(load_state(bytes.data(), bytes.size()), "new snapshot loads successfully");+ check(g_cpu.pc == 0x10000, "snapshot restores the CPU");+ check((hw::read32(0x1000F000) & 4) != 0, "snapshot restores the guest-visible delivered latch");+ check(hw::intc_pending() == 0, "snapshot does not redeliver that interrupt");+ iop::hw::write(0x1F808414, 0x84000000, 4);+ check((iop::hw::read(0x1F808414, 4) & 0xFFFF) == 0x04A5, "snapshot restores the PHY register");+ // Unsupported versions must fail at the header, not after mutating RAM.+ for (const std::uint32_t unsupported : {0u, 1u, 8u}) {+ std::memcpy(bytes.data() + 8, &unsupported, sizeof unsupported);+ g_cpu.pc = 0x30000;+ st32(0x9000, 0x12345678);+ check(!load_state(bytes.data(), bytes.size()), "unsupported version is explicitly rejected");+ check(g_cpu.pc == 0x30000 && ld32(0x9000) == 0x12345678,+ "version rejection happens before CPU or RAM mutation");+ }+ if (failures) return 1;+ std::puts("GT3 snapshot schema regression PASS");+ return 0;+}diff --git a/tests/kernel_exit_delete_thread_test.cpp b/tests/kernel_exit_delete_thread_test.cppnew file mode 100644index 0000000..95e3312--- /dev/null+++ b/tests/kernel_exit_delete_thread_test.cpp@@ -0,0 +1,96 @@+#include "kernel.hpp"+#include "ps2/generated.hpp"+#include "ps2/memory.hpp"+#include "ps2/system.hpp"++#include <cstdint>+#include <cstdio>++namespace {+constexpr std::uint32_t kMainEntry = 0x10000;+constexpr std::uint32_t kWorkerEntry = 0x12000;+int failures = 0;++void check(bool ok, const char *message) {+ if (!ok) {+ std::fprintf(stderr, "FAIL: %s\n", message);+ ++failures;+ }+}++void start() {+ ps2::kernel::reset();+ ps2::kernel::start_main_thread(kMainEntry, 0, 0, 0);+ ps2::g_cpu.pc = kMainEntry + 4;+}++void syscall(std::uint32_t number) {+ ps2::g_cpu.r[3].w[0] = number;+ ps2::kernel::handle_syscall(ps2::g_cpu, kMainEntry);+}++void check_idle(const char *message) {+ check(ps2::kernel::current_thread() == 0, "no thread is running after the last runnable thread exits");+ check((ps2::g_cpu.pc & ~ps2::kUnwind) == ps2::kIdle, message);+ check((ps2::g_cpu.pc & ps2::kUnwind) != 0, "idle transition requests unwind of the translated call stack");+ ps2::kernel::service(ps2::g_cpu);+ check(ps2::g_cpu.pc == ps2::kIdle, "kernel service clears unwind and remains idle with no ready thread");+}++int create_worker() {+ constexpr std::uint32_t descriptor = 0x3000;+ for (unsigned i = 0; i < 36; i += 4) ps2::st32(descriptor + i, 0);+ ps2::st32(descriptor + 4, kWorkerEntry);+ ps2::st32(descriptor + 8, 0x20000);+ ps2::st32(descriptor + 12, 0x1000);+ ps2::st32(descriptor + 20, 16); // Lower priority than the main thread (0).+ ps2::g_cpu.r[4].w[0] = descriptor;+ syscall(0x20); // CreateThread+ const int id = static_cast<int>(ps2::g_cpu.r[2].w[0]);+ check(id > 1, "a dormant worker thread is created");+ return id;+}++void exit_without_delete() {+ start();+ syscall(0x23); // ExitThread: current thread remains in the table, dormant.+ check_idle("ExitThread of the only runnable thread enters idle");+}++void delete_last_thread() {+ start();+ syscall(0x24); // ExitDeleteThread: both current() and best_ready() become null.+ check_idle("ExitDeleteThread enters idle instead of continuing deleted guest code");+}++void delete_with_dormant_worker() {+ start();+ create_worker();+ syscall(0x24);+ check_idle("a dormant thread must not prevent ExitDeleteThread from entering idle");+}++void delete_with_ready_worker() {+ start();+ const int id = create_worker();+ ps2::g_cpu.r[4].w[0] = static_cast<std::uint32_t>(id);+ ps2::g_cpu.r[5].w[0] = 0x1234;+ syscall(0x22); // StartThread: ready, but it should not preempt main's priority.+ check(ps2::kernel::current_thread() == 1, "starting a lower-priority worker keeps the main thread running");+ syscall(0x24);+ check(ps2::kernel::current_thread() == id, "deleting main schedules the ready worker");+ check((ps2::g_cpu.pc & ~ps2::kUnwind) == kWorkerEntry, "ready worker's entry PC is restored");+ check((ps2::g_cpu.pc & ps2::kUnwind) != 0, "switching to the worker requests unwind");+ check(ps2::g_cpu.r[4].w[0] == 0x1234, "ready worker's argument is restored");+}+}++int main() {+ exit_without_delete();+ delete_last_thread();+ delete_with_dormant_worker();+ delete_with_ready_worker();+ if (failures) return 1;+ std::puts("ExitDeleteThread idle regression PASS");+ return 0;+}diff --git a/tests/sif_scratchpad_test.cpp b/tests/sif_scratchpad_test.cppnew file mode 100644index 0000000..7e9728d--- /dev/null+++ b/tests/sif_scratchpad_test.cpp@@ -0,0 +1,75 @@+#include "iop/iop.hpp"+#include "iop/sif.hpp"+#include "ps2/memory.hpp"++#include <cstdint>+#include <cstdio>+#include <initializer_list>++namespace {+int failures = 0;++void check(bool ok, const char *message) {+ if (!ok) {+ std::fprintf(stderr, "FAIL: %s\n", message);+ ++failures;+ }+}++void descriptor(std::uint32_t at, std::uint32_t source, std::uint32_t dest, std::uint32_t size) {+ ps2::st32(at, source);+ ps2::st32(at + 4, dest);+ ps2::st32(at + 8, size);+ ps2::st32(at + 12, 0);+}++void payload(std::uint32_t at, unsigned size, std::uint8_t first) {+ for (unsigned i = 0; i < size; ++i) ps2::st8(at + i, static_cast<std::uint8_t>(first + i));+}++bool copied(std::uint32_t at, unsigned size, std::uint8_t first) {+ for (unsigned i = 0; i < size; ++i)+ if (ps2::iop::read8(at + i) != static_cast<std::uint8_t>(first + i)) return false;+ return true;+}++void ram_descriptors() {+ // All these EE addresses resolve to the same main-RAM descriptor.+ for (const std::uint32_t address : {0x00001000u, 0x80001000u, 0xA0001000u, 0x20001000u, 0x30001000u}) {+ ps2::sif::reset();+ descriptor(0x1000, 0x2000, 0x8000, 16);+ payload(0x2000, 16, 0x40);+ for (unsigned i = 0; i < 16; ++i) ps2::iop::write8(0x8000 + i, 0);+ check(ps2::sif::set_dma(address, 1) != 0, "RAM descriptor returns a DMA ID");+ check(copied(0x8000, 16, 0x40), "main-RAM descriptor and its aliases copy the expected payload");+ }+}++void scratchpad_descriptors() {+ ps2::sif::reset();+ constexpr std::uint32_t list = ps2::kScratchpadBase + 0x1000;+ descriptor(list, 0x2000, 0x8000, 16);+ descriptor(list + 16, 0x2100, 0x8010, 12);+ payload(0x2000, 16, 0xA0);+ payload(0x2100, 16, 0xC0);+ payload(0x2200, 16, 0x10);+ // Conflicting, valid descriptors at the addresses obtained by masking the+ // scratchpad list into RAM. The old reader will copy these instead.+ descriptor(0x1000, 0x2200, 0x8000, 16);+ descriptor(0x1010, 0x2200, 0x8010, 12);+ for (unsigned i = 0; i < 33; ++i) ps2::iop::write8(0x8000 + i, 0xEE);+ check(ps2::sif::set_dma(list, 2) != 0, "scratchpad descriptor list returns a DMA ID");+ check(copied(0x8000, 16, 0xA0), "first descriptor is read from scratchpad, not its RAM alias");+ check(copied(0x8010, 12, 0xC0), "second descriptor is read from scratchpad, not its RAM alias");+ check(copied(0x801C, 4, 0xCC), "partial quadword includes trailing source bytes");+ check(ps2::iop::read8(0x8020) == 0xEE, "bytes beyond the rounded transfers remain untouched");+}+}++int main() {+ ram_descriptors();+ scratchpad_descriptors();+ if (failures) return 1;+ std::puts("SIF scratchpad descriptor regression PASS");+ return 0;+}