Commit Graph

4696 Commits

Author SHA1 Message Date
586970b5ba runtime: dynamic rendering scope batching, no-op LayoutTracker elision, and cached ConsoleHeapGpu procs
Cuts replay CPU and Direct GPU render-pass overhead:
- vulkan_replay.h: merges consecutive draws with matching (colors, depth + depth_aspects, area, layers) into one vkCmdBeginRendering..vkCmdEndRendering scope with coalesced same-layout attachment barriers, closing cleanly on non-draw/glc/indirect_clamp/quad/query/stats/gpu_profile/marker boundaries; elides no-op LayoutTracker::set() journaling; adds per-pass 32-entry PrepareViewCache and lightweight Prepared::reset().
- console_heap_gpu.h: caches all 20 PFN_vk* device proc pointers once in VkFns.
- replay_state_cache_test.cpp: adds scope batching, boundary split, LayoutTracker no-op, PrepareViewCache, and live VVL GPU tests.

AI-assisted: Antigravity (Gemini 4 Neon).
2026-11-28 02:05:03 -05:00
25fd8e4776 Merge remote-tracking branch 'origin/main' into fix/rdna2spirv-f16-interp-computed-ij 2026-11-27 23:02:20 -08:00
cd8b5632b8 Merge branch 'main' of https://github.com/ProjectLeonida/mandy into test/round6 2026-11-28 01:22:20 -05:00
350f84efe6 runtime: fix duplicate readback_pool member and parenthesized std::max syntax on Windows
Renames PageMirror's Phase-1 WorkerPool to readback_hash_pool (avoiding collision with VkCommandPool readback_pool) and replaces invalid (std::max)<std::uint64_t>(...) with (std::max)(std::uint64_t(1), ...) for clang-cl/MSVC.

AI-assisted: Antigravity (Gemini 4 Neon).
2026-11-28 01:12:03 -05:00
80734a849c runtime: wire scoped readback skip masks into batched texture checks and console heaps
Routes page_mirror_check_batch() uploads through note_readback_pieces_uploaded_locked() and console-heap page invalidations through note_readback_frame_invalidated_locked() so unrelated pages never poison readback_invalidated; renames a shadowed parameter in title_texture_watch_test.

AI-assisted: Antigravity (Gemini 4 Neon).
2026-11-28 01:09:18 -05:00
ccd77445fa Merge branch 'r6/textures-watch' into test/round6 2026-11-28 01:08:13 -05:00
6fd734ee84 Merge branch 'r6/queue-contention' into test/round6 2026-11-28 01:08:13 -05:00
f6d3f30c4e runtime: batched mirror texture checks, GPU-fallback mirror_hash skip, and batched tile arming
Eliminates false CPU-staged re-uploads, per-texture page_mirror.mutex churn, and unbatched tile re-arming:
- d3d12_vulkan_device.cpp: replaces per-texture page_mirror_texture_chunk/page_mirror_tiles_unchanged with a single-lock page_mirror_check_batch() snapshotting pending xmem remaps under shared feed_lock (rejecting only overlapping textures) and running one batched parallel TitleMirror::upload(); adds TitleJob::previous_mirror_hash check in hash_title_job() so GPU-uploaded textures falling back to CPU skip unchanged re-uploads; separates lock_wait_ns from collect_ns.
- title_texture_watch.h / title_texture_refresh.h: adds examine_batch() + TitleTextureCells::arm_batch() coalescing pins and contiguous VirtualProtect runs, uses direct Tile*/Texture* pointers in watch indices, and merges write/map ranges before iteration.

AI-assisted: Antigravity (Gemini 4 Neon).
2026-11-28 01:08:13 -05:00
758b98756c runtime: single-flight before_execute coalescing, frame-group async room, and lock/worker telemetry
Eliminates multi-worker global lock convoys, Wait-split async room stalls, and instrumentation blind spots:
- vulkan_backend.h / d3d12_vulkan_device.cpp / d3d12_com.cpp: adds visibility_seq_ & signaled_visibility_seq_ tracking and BeforeExecuteCoalescer so concurrent/back-to-back cross-queue submissions serialize global refresh passes to one leader and skip redundant refreshes when pass_seq >= req_seq (opt-out LEONIDA_BEFORE_EXECUTE_COALESCE=0).
- vulkan_backend.h: replaces Wait-broken pending_submit_groups_locked() with pending_frame_groups_locked() and max_batches = max(16 * depth, 64) for depth >= 2, eliminating mid-frame room_cv_ stalls on Wait-heavy frames.
- vulkan_backend.h / submit_phases.h: includes release_held() and pump_ready() in async_worker() busy time and adds worker_lock_wait_ns reporting.
- d3d12_vulkan_device.cpp / d3d12_com.cpp: lock-free ConsoleHeap::in_place_work_pending fast-skip, FilterPageCache in finish_in_place(), identical-base dedup of mirror_ranges, and cached console-heap fast-path in GraphicsCommandList::address().

AI-assisted: Antigravity (Gemini 4 Neon).
2026-11-28 01:06:40 -05:00
3007ae0d35 runtime: unlocked parallel readback pre-hashing, piece-level skip masks, and single-map CellGuard
Eliminates the async readback page_mirror.mutex convoy and serial fallback, and reduces page-mirror refresh cost:
- title_mirror.h / d3d12_vulkan_device.cpp: lifts WorkerPool for lock-free Phase 1 prehash_readback_slice() outside page_mirror.mutex and single-call Phase 2 write_back_prehashed() under lock (256-page slice: 0.11 ms unlocked, 0.03 ms locked), eliminating the 256x serial single-page fallback and merge_ranges() storm.
- Scopes readback invalidation to readback_slice_frames with per-frame 256-bit readback_slice_skip_masks populated from TitleMirror::upload(on_changed), preventing hot-page retry loops while preserving CPU-wins conflict semantics.
- Coalesces contiguous GPU write-back runs, batches deferred map() initial fills in parallel upload(), and replaces fed_now unordered_set with a flat sorted vector.
- title_mirror_hot_cold.h: consolidates CellGuard maps into a single TrackedCell map and adds a changes_since()-invalidated known_protect cache to halve cold re-arm VirtualQuery syscalls.

AI-assisted: Antigravity (Gemini 4 Neon).
2026-11-28 01:04:24 -05:00
0577e45ee5 runtime: remove unused legacy CPU texture hash helpers
Removes UnalignedWord64, mix_words, hash_bytes, hash_guarded, and hashed_bytes from d3d12_vulkan_device.cpp after CPU texture hashing moved to copy_guarded + mirror_range_sum_bytes().

AI-assisted: Antigravity (Gemini 4 Neon).
2026-11-28 00:22:20 -05:00
a8bafec7c2 runtime: enable x86-64-v3 / AVX2 codegen and drop unused typedef
Enables /arch:AVX2 on x64 MSVC/clang-cl and -march=x86-64-v3 on x86-64 GCC/Clang for C/C++ targets (activating AVX2 shadow_keep::sum_of, descriptor-slot scans, and auto-vectorization while keeping non-x86-64 portable builds untouched), and removes an unused local clock typedef in page_mirror_write_back_ranges.

AI-assisted: Antigravity (Gemini 4 Neon).
2026-11-28 00:15:18 -05:00
faf1ee314c Merge branch 'r5/queue-coalesce' into test/round5 2026-11-28 00:14:11 -05:00
6c3cc1c18d Merge branch 'r5/textures-fast' into test/round5 2026-11-28 00:14:11 -05:00
89fe359ee0 runtime: VulkanQueue execute+signal coalescing, fast heap filtering, and batch-parallel sync compiles
Cuts queue submit overhead, descriptor-heap filtering cost, and synchronous cold pipeline compile latency:
- VulkanQueue: adds pending-wait tracking (has_unsatisfied_waiter), deduplicated submit_multi(), execute+signal coalescing with cross-queue/CPU waiter splits, and coalescing-group-aware async room gating.
- d3d12_com.cpp: caches descriptor heap VAs/counts on SetDescriptorHeaps, pre-tracks command-list barrier/query/indirect/draw flags, single-alloc PinnedObjects, and linear table dedup.
- d3d12_vulkan_device.cpp: AVX2 32-byte slot equality, 8 KiB L1d seen_keys, stack-local FilterPageCache, 64 KiB page-pointer caching, and T# dedup in finish_in_place.
- vulkan_replay.h / d3d12_vulkan_device.cpp: lightweight collect_unbuilt_pipelines() pre-pass and cancel-safe batch-parallel sync compile runner backed by PipelineCompiler.

AI-assisted: Antigravity (Gemini 4 Neon).
2026-11-28 00:14:10 -05:00
184d03eca8 runtime: fast mirror-hashed texture refresh and watermarked passive write-back
Cuts per-submission texture refresh overhead and prevents passive write-back accumulation across overlapping queues:
- title_texture_refresh.h: adds shadow_keep::sum_of-backed mirror_range_sum helpers and PassiveWriteBackTracker with retire_id watermarking so overlapping direct/compute queues promote each passive V# range without re-promoting stale ranges indefinitely.
- title_texture_watch.h: skips hot_tiles() rescans when hot_generation() is unchanged and tracks non_hot_arms to reuse synced shared hot tiles per pass.
- d3d12_title_image_upload.h: reuses detile scratch buffers across sub-batches and skips detile setup when unused.
- d3d12_vulkan_device.cpp: extends TitleMirror range_sum() skip to all 256B-aligned and partially mirrored textures, filters dirty chunk syncs by title_written_ (guarded by !t.stale), caches can_gpu_upload(), pools TitleJob buffers, runs inline single-item reads/hashes, and defers t.pieces commits until upload success.

AI-assisted: Antigravity (Gemini 4 Neon).
2026-11-28 00:06:16 -05:00
ecbdb30d10 runtime: AVX2/SSE2 shadow_keep::sum_of, parallel TitleMirror pool, and batched CellGuard arming
Speeds up shadow page hashing, TitleMirror upload/write-back, and guard re-arming:
- shadow_keep::sum_of: 4x256-bit AVX2 (#if defined(__AVX2__)) and 4x128-bit SSE2 fast paths with portable scalar fallback (2.52x single-core AVX2 speedup).
- TitleMirror: lazy 6-worker thread pool with exception-safe teardown and RAII join guard parallelizing upload() and write_back_batch() for >=16 homes/jobs (4.76x upload, 6.08x write-back) while preserving exact serial aliasing semantics.
- CellGuard::arm_batch(): 1024-page contiguous runs, pin-batching outside mutex, and generation-guarded VirtualQuery cache.

AI-assisted: Antigravity (Gemini 4 Neon).
2026-11-28 00:01:22 -05:00
2836c5f1b1 docs: cs_fma_fused reads 0x7352 in its f16 word on KosmicKrisp at run time
Tauwni measured it in the review of #1724 (Apple M3, Mesa 26.3.1, 20 of 20 runs): with
run-time operands the f16 multiply-add comes out as if the product were rounded first, one
step from 0x7351. With literal operands the constant was folded exactly, so the fixture
passed there before. MoltenVK 1.4.2 and llvmpipe give 0x7351 on the same machine.

A Known problems row and a line in the fixture's header; no instruction changes.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 12:44:48 +08:00
420116dbbc tests: cs_fma_fused takes its f16 operands at run time, like its f32 ones (TEST-FMA-FUSED-F16-RUNTIME)
The fixture reads the operands of its f32 multiply-adds from s4..s7 so that a driver has to
compute them at run time. The three operands of its v_fma_f16 were literals, which made the
whole f16 multiply-add a compile-time constant. MoltenVK 1.4.2 gives the wrong constant: word
7 read 0x0000 on an Apple M5 (0x3c00 in the docs' row) where 0x7351 is expected, the
cs_fma_fused failure listed in docs/testing.md and in the macOS job's EXPECTED_FAILURES. The
same translation with any one of the three operands taken at run time gives 0x7351.

The triple is now the s4 word XOR a literal each, so the test checks the translator's
round-to-odd sequence as the GPU runs it. The translator is not changed.

tests/semantic/test_fma_fused_fixture.py runs the fixture in the interpreter against the eight
words of its header and checks that no multiply-add in it reads a register only literals fed.
The Known problems row says what is left: an f16 multiply-add with only constant operands.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 12:44:48 +08:00
6064cbbb49 tests: build.py and check.py pick the f16 interpolation fallback from the device (TEST-CHECK-F16-FALLBACK)
run_gpu_tests.py and make_game.py translate with --f16-interp-fallback by
themselves where tools/vk_subgroup_info.py reports per_vertex_inputs
false (MoltenVK). build.py and check.py only did so with
LEONIDA_F16_INTERP_FALLBACK=1, so the two-step form on a Mac built
ps_ij_computed and ps_interp_f16_high for PerVertexKHR inputs and
check.py reported both as failed.

Both scripts now ask the device when the variable is unset, the way they
already do for the barycentric fallback, and take 1/0 (true/false, yes/no,
on/off) as run_gpu_tests.py does. On an Apple M5 (MoltenVK 1.4.2) check.py
goes from 175 of 220 pass, 39 skipped, 6 failed to 176 pass, 40 skipped,
4 failed: ps_interp_f16_high passes and ps_ij_computed is a SKIP.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 12:44:46 +08:00
f6ec7480ff library_loader_names: run with Wine's native wsock32, and check the copy is the fixture
Under Wine, loading a wsock32.dll by path gives Wine's builtin wsock32, not the
fixture copy, so the same-base checks failed (Tauwni, Wine 11 on macOS, #2525).
CTest now runs the test with WINEDLLOVERRIDES=wsock32=n,b, which Windows ignores
and scripts/run_wine_tests.py keeps, and the test checks by path that the module
it loaded is its own copy, saying why when it is not.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 22:36:30 -06:00
5d677b7ba2 cpu_emulation: a CLWB #UD on a site another thread rewrote continues at it (RT-CLWB-PATCH)
Threads that fault on the same CLWB site together lost the race: a #UD handled
after another thread rewrote the site decoded CLFLUSHOPT (or the NOP), did not
know it and returned EXCEPTION_CONTINUE_SEARCH, which ends the title.

- The handler continues at a site that already holds the form written on this
  host (or the NOP's halfway state): the CPU runs it.
- One lock around unprotect, re-check, write and protect again, so two threads
  never interleave on a page; a site found rewritten under it is not written.
- The NOP is written opcode first (66 0F 1F /6 in between is a NOP too).
- The sites counter counts each site once, by the thread that wrote it.

cpu_emulation_test calls the handler with a made-up #UD, so it runs on hosts
with CLWB: first #UD, a second one on the rewritten site, and 16 threads on
2048 fresh execute-read sites. Before the fix 27958 of 32768 concurrent #UDs
were passed on, 4810 rewrites were counted for 2048 sites and pages were left
writable; with it all checks pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 05:28:00 +01:00
65acf73246 runtime: remove frame-hot mirror over-copying and measure write-back CPU time
Promoting 1x/frame pages to unguarded hot caused HotColdTracking to copy
~5,000+ pages on every submission (~50 GiB/10 s) and dirtied all textures
sharing those tiles (~119 ms/sub). Restore the submission-hot (6/8)
policy where unguarded copies beat fault+copy cost, and accumulate actual
CPU+wait time in AsyncReadback::cpu_ms instead of async wall-clock span.

AI-assisted: Antigravity (Gemini 4 Neon).
2026-11-27 23:24:53 -05:00
63a73515d1 Merge remote-tracking branch 'origin/main' into fix/clwb-patch-race 2026-11-28 05:22:21 +01:00
f4df7c4797 Merge remote-tracking branch 'mandy/main' into test/round4 2026-11-27 23:03:33 -05:00
5c815be84b Merge the upstream shared BC image fix into per-format staging
Retain staging for shared BC images on devices without host copies and keep the per-image fallback for formats without usable host-transfer backing.

AI-assisted-by: OpenAI Codex (GPT-6)
2026-11-28 14:00:35 +10:00
f77359c5b4 Merge pull request #1565 from Mike7581/rt-compat-dir-runtime-loads
loader: a run-time LoadLibrary takes the LEONIDA_COMPAT_DIR module too (RT-COMPAT-DIR-RUNTIME-LOADS)
2026-11-28 00:48:31 -03:00
477f56cc1a Merge pull request #1564 from Mike7581/rt-crt-quick-exit-tls
process: the game's at_quick_exit handlers and thread-local exit callback are the run's own (RT-CRT-QUICK-EXIT-TLS)
2026-11-28 00:48:27 -03:00
725d223757 Merge pull request #1549 from Mike7581/mvp-gpu-04-stub-pipeline
d3d12: LEONIDA_STUB_PIPELINES builds a real graphics pipeline from built-in stages (MVP-GPU-04)
2026-11-28 00:48:22 -03:00
5651950adb Merge pull request #1517 from Mike7581/docs/runtime-readme-shims
runtime/README: AcpHal, chad, xapu and XCRDAPI have shims; DStorage decodes BCPack (DOC-RUNTIME-README-SHIMS)
2026-11-28 00:48:18 -03:00
e9bd907508 runtime: add ReplayStateCache and two-tier frame-hot TitleWritePolicy
Cache bound pipelines, descriptor sets, dynamic graphics state, and dirty
push-constant sub-ranges across command lists in emit_commands() (with
invalidation across internal compute helpers and rendering boundaries),
and restore the two-tier submission-hot + presented-frame-hot policy in
TitleWritePolicy/HotColdTracking wired to present_serial.

AI-assisted: Antigravity (Gemini 4 Neon).
2026-11-27 22:29:42 -05:00
ef648df8bd Merge remote-tracking branch 'origin/main' into fix/null-descriptor-generated-dir 2026-11-28 03:55:54 +01:00
085cb0cc61 Merge branch 'r3b/glc-writeback' into test/round3
# Conflicts:
#	runtime/src/vulkan_backend.h
2026-11-27 21:16:08 -05:00
072327cfad runtime: tighten TitleMirror/GeometryViews lifetime guards and PR hygiene
Guard GeometryViews retirement with command_list_epochs, defer TitleMirror
freed-home ticket stamping until flush + note_mirror_bind under submit_mutex_
(including TitleImageUpload submits), fix queue lock ordering and lock-free
wait_submitted, remove dead helpers and process labels, and scrub game shader
identifiers from docs/design.md.

AI-assisted: Antigravity (Gemini 4 Neon).
2026-11-27 21:13:23 -05:00
4a70845069 gameinput: SetParams keeps the force-feedback effect's kind
IGameInputForceFeedbackEffect::SetParams updates the parameters of the
effect's own kind; another kind is refused and the effect keeps what it
had (timbot103's review on #2497). SetParams checked only that the motor
reports the new kind, so a constant effect could become a sine. It now
refuses any params->kind other than the effect's.

An effect's SDL type therefore never changes, and the destroy-and-
recreate path this PR added to sync() for a kind change is unreachable,
so it is removed again.

gameinput_test: SetParams refuses both a kind the motor lacks and one it
reports, leaves the parameters and the SDL effect alone, and the sine
and spring checks run on effects of their own made with
CreateForceFeedbackEffect.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 20:11:46 -06:00
59feb165bd d3d12_xs: leave a mapped descriptor range to the queue's pull at submission
From timbot103's review of #2498.

A mapped real range is the Vulkan device's live arena: shaders of lists
already submitted read it, and the queue rewrites the slots it pulls there
in place (title buffer addresses rebased) when it submits. local_mirror_table
copied the title's raw slots into it while a list was being recorded
(SetGraphicsRootDescriptorTable / SetComputeRootDescriptorTable), which could
overwrite a translated slot an earlier submission was still reading. The
first commit of this PR made that happen on Wine as well; on Windows, where
VirtualQuery reports the arena as accessible, main already did it.

local_mirror_table now leaves a mapped range alone. The queue pulls the
title's slots of every bound table itself at submission
(pull_title_descriptors through title_va_aliases), which needs no
VirtualQuery of the arena, so Wine loses nothing.

xs_proxy_mock_test, check_descriptor_mirror case 2: with a translated value
in the real slot, binding a table over it (graphics and compute) leaves the
slot as it was, and the submission-time pull then takes the title's slot.
The previous commit fails the first of these checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 20:11:24 -06:00
181e9dfdda runtime: add GLC barriers, literal sampler specialization, and writes_buffer write-back gating
Enable Vulkan 1.2 vulkanMemoryModel/vulkanMemoryModelDeviceScope and emit
pre-dispatch/pre-rendering barriers for reads_glc_buffer shaders, wire
literal_sampler_spec_base VkSpecializationInfo specialization constants,
and gate passive title buffer write-back on shader writes_buffer metadata
with non-blocking async readback polling.

AI-assisted: Antigravity (Gemini 4 Neon).
2026-11-27 21:10:54 -05:00
450c5e52b3 library_loader: ask Windows for a host module's name on every GetProcAddress
Dropping the HMODULE -> name entry in free_library() after FreeLibrary
left a window (timbot103's review on #2525): between FreeLibrary and the
erase, another thread can load a different DLL at the freed base and
call GetProcAddress, which then found the old name and served the old
module's shims. Holding loader_mutex across FreeLibrary would invite a
lock-order inversion with the loader lock.

So there is no cache any more: host_module_name() calls
GetModuleFileNameW each time, which always answers for the module mapped
at that base now, and free_library() is a plain FreeLibrary again.

library_loader_names_test gains the window itself: the host's
FreeLibrary is called directly, so the shim never sees the unload, and
the plain copy loaded at the same base must not be served the shim. It
fails with the cache-and-erase version and passes now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 20:07:50 -06:00
37163d100f ws2_offline: the host reports an extension lookup's completion; AI_NUMERICHOST keeps localhost a name
From timbot103's review of #2533.

- The ConnectEx and WSASendMsg lookups no longer complete the caller's
  overlapped themselves (complete_now). That posted no packet for a socket on
  an I/O completion port, so a caller waiting in GetQueuedCompletionStatus
  hung, and it signalled an overlapped a socket without WSA_FLAG_OVERLAPPED
  must ignore; its APC record also leaked if the thread never waited
  alertably. The host's WSAIoctl now gets the caller's overlapped and
  completion routine again, so the completion is reported as Winsock reports
  it, but writes its own pointer and byte count into storage of the shim's
  (wrap_extension_lookup): freed when the call completed, kept if the host
  reports it pending. The caller's buffer holds the wrapper before the host
  is called, so a packet another thread dequeues already finds it, and gets
  its old contents back on failure.
- With AI_NUMERICHOST, "localhost" is passed on as the name, so the host
  refuses it with EAI_NONAME instead of the shim answering with a literal.

ws2_offline_test: a completion-port socket gets its packet with the wrapped
pointer; on a socket without WSA_FLAG_OVERLAPPED the overlapped ends as the
host's own WSAIoctl leaves it; getaddrinfo(localhost, AI_NUMERICHOST) is
EAI_NONAME. The event and routine cases follow what Windows 11 does for this
lookup (measured: event set, routine run once, packet posted, 0 bytes in the
OVERLAPPED). The previous commit fails these 3 checks; 87/87 pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 20:07:18 -06:00
842e0f641c xgameruntime_gamesave_test: Case E runs where the host has no CopyFile2
CopyFile2Trap left itself unarmed when kernel32 exports no CopyFile2,
and Case E then failed on Wine 9, the host this PR is for (timbot103's
review on #2532). A missing export is now told apart from a patch that
failed: with no CopyFile2 there is nothing that could be called, so the
overwrite and rollback checks run against the real host, and only an
export that exists but cannot be patched fails the check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 20:06:01 -06:00
27524a5e5b Merge remote-tracking branch 'origin/main' into fix/explicit-lod-bias-moltenvk 2026-11-28 02:57:41 +01:00
9d054cd855 Async callback and handle safety in xgameruntime, gameinput_no_sdl and xapu_queue
kevincommits' Finding 19 in #1608, item 5:

- xgameruntime.cpp (XNetworking): an initial notification's callback
  that unregistered itself with wait=true waited for its own return and
  never came back. The registration now records the thread running its
  callback, and an unregister from that thread returns at once (the
  registration ends when the callback returns). net_register also used a
  throwing new across the ABI; it is new (std::nothrow) now.
- gameinput_no_sdl.cpp: a GameInputBlockingEnumeration report ran
  outside deliver_mu, so UnregisterCallback on another thread returned
  while the callback was still running and the caller could free its
  context mid-call. It now runs under deliver_mu and marked as
  delivering, as deliver() runs callbacks.
- xapu_queue.cpp: handles were never checked, so a second XApuDisconnect
  freed the connection again and closed its event twice. Connections are
  kept in a live set under a shared mutex; every call checks its handle
  and holds the lock shared for the call, and a disconnect takes it
  exclusive. An activate or deactivate changed the stream before the
  result was queued, so running out of memory left it half applied; the
  result's slot is now taken first.

New checks: xgameruntime_test (a callback that unregisters itself with
wait=true returns), gameinput_no_sdl_test (UnregisterCallback waits for a
running blocking callback; a blocking callback can unregister itself),
xapu_chad_test (a second disconnect, a disconnected and a foreign handle
are refused). On main the first two fail and xapu_chad_test crashes with
heap corruption.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 19:40:07 -06:00
e7280be166 xbox_bvh_builder: scan every postbuild description for 0x10; rehydrate scratch regions cannot wrap
From kevincommits' Finding 19 (item 3) in #1608.

- builder_build_batched2x kept 16 postbuild descriptions and then left the
  loop, so an offline-statistics (0x10) description at index 17 or later was
  never seen: the element was built instead of skipped, as the DLL would
  refuse it. The rest past 16 are still dropped (logged once) but scanned.
- builder_rehydrate_batched2x aligned each element's scratch size with
  (size + 255) / 256 * 256 and summed them without a bound, so a size near
  2^64 wrapped to a small region or a small total, making the shared scratch
  buffer too small and the regions overlap. Such an element now gets no
  region (and is skipped as one without scratch, logged once).

Both rules move into shims/xbox_bvh_builder_rules.h (filter_postbuild,
add_scratch_region) with a CPU test, xbox_bvh_builder_rules: 0x10 at indices
0, 5, 16, 17 and 19 of 20, and regions near 2^64. The old loop and
arithmetic fail 5 of its checks. xbox_bvh_builder (GPU) and its BVH check
still pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 19:39:04 -06:00
b04fdc91c0 com_shim: nested CoUninitialize gives its host reference back; check TlsSetValue
Every nested co_initialize_ex() takes a host COM reference
(host_inits_owned), but co_uninitialize() gave them all back only at the
outermost CoUninitialize. A thread with an outer init that runs balanced
inner init/uninit pairs piled up one host reference per pair until the
outer balance (kevincommits' Finding 19 in #1608, item 1).

A nested CoUninitialize now gives back its own reference. The first
init's reference still stays until the guest balances, so host-first
teardown keeps working.

The first init also ignored TlsSetValue's result. When it fails, the
state is not tracked and no CoUninitialize would ever give the host
reference back, so the init now undoes it and fails with the error.

com_shim_test gains a case: 100 balanced nested pairs under an outer
init must leave exactly one host reference. It fails on main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 19:36:14 -06:00
0f43a7804b acphal: power-of-two alignment in ApuIsVirtualAddressValid; ApuAlloc(flags=2) gets the lazy default heap
From kevincommits' finding (batch 18, item 4) in #1608.

- ApuIsVirtualAddressValid and ApuRegion::is_valid_address tested
  (offset & (alignment - 1)) == 0 for any alignment, which is only an
  alignment test for a power of two: with 6, offset 2 passed and offset 6
  failed. An alignment that is not a power of two is now invalid, as ApuAlloc
  already treats it (0 still means 1).
- Before ApuCreateHeap, ApuAlloc with flags 0 or 1 created a 64 MiB default
  cached heap, but flags 2 fell back to the cached heap without creating it
  and returned E_OUTOFMEMORY. The fallback now comes first, so a first
  allocation with flags 2 gets the same lazy default heap. A heap left out by
  an explicit ApuCreateHeap stays unavailable (acphal_noncached_only).

acphal_test: alignment 6 and 3 are refused and powers of two kept (2 checks
fail on main); a new mode --lazy-noncached (ctest acphal_lazy_noncached)
allocates with flags 2 before any ApuCreateHeap (2 checks fail on main).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 19:13:07 -06:00
8bd36f4274 runtime: make oldest_held_seq read-only and bind descriptor in check_mapped_plane_byte
Splits QueueHolds barrier marking into Holder::note_barrier(seq) called only by
after_held(), preventing run_barriers() polls from stamping spurious barrier_after
flags on queued batches. Also adds name_texture() in check_mapped_plane_byte so
TitleTextureWatch tracks the mapped plane like check_mapped_plane.

AI-assisted: Antigravity (Gemini 4 Neon).
2026-11-27 20:12:20 -05:00
11b63a53b0 file_system: T:\ is a drive root for file calls; move and copy hold the folder lock
Three fixes to the GAME:/T: overlay shim:

- The T:\ root parses to its scratch folder's parts, not to an empty
  list, so the parts.empty() root checks in write_target, DeleteFileW,
  the copy destination and SetFileAttributesW let it through: a
  SetFileAttributesW(T:\) reached the host folder. They use
  drive_root(), as RemoveDirectory and MoveFileEx already do, with the
  error each gave for GAME:\.
- MoveFileEx and the CopyFile family did not hold the destination
  folder's lock from the "does the folder exist" check to the host
  move or copy, as a write-open and CreateDirectory do, so a concurrent
  RemoveDirectory of that folder could still be undone. A copy with a
  progress routine does not hold it across the copy, because the
  routine is the title's code.
- CreateDirectory removed a recreated folder's marker without
  win32_io_path(), so a marker beyond MAX_PATH could not be removed on a
  host without long path support, and the folder was not recreated.

Found by kevincommits (#1608).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 19:10:56 -06:00
c3cf8a042d ws2_offline: refuse the local computer's name, answer localhost with loopback literals, keep WSAIoctl synchronous
From kevincommits' finding (batch 18, item 3) in #1608.

- An empty name ("") passed is_loopback_node_a, so getaddrinfo, GetAddrInfoW,
  GetAddrInfoExA/W, gethostbyname and WSAAsyncGetHostByName forwarded it to the
  host, which answers with every address of the local computer (its LAN and
  external adapters). A null name did the same for gethostbyname and
  WSAAsyncGetHostByName. Both are refused now; a null getaddrinfo node (a
  service-only lookup: loopback, or the wildcard that bind narrows) is still
  answered.
- "localhost" went to the host as a name, so its hosts file could map it off
  loopback. The lookups now hand the host a loopback literal for it (::1 for an
  AF_INET6 lookup, else 127.0.0.1), as WSAConnectByNameA/W already do.
- WSAIoctl(SIO_GET_EXTENSION_FUNCTION_POINTER) for ConnectEx and WSASendMsg
  passed the caller's overlapped and completion routine to the host along with
  pointers into its own stack frame. The host lookup is now synchronous, as in
  host_extension, and an overlapped request is reported as completed at once:
  status and byte count in the OVERLAPPED, its event set or its routine queued.

ws2_offline_test gains section 9 for each case. With main's shim the test
fails at gethostbyname(NULL) and then crashes; 83/83 checks pass with the fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 19:10:03 -06:00
03d17a395e xgameruntime_gamesave: copy blobs with CopyFileW, not CopyFile2
copy_blob() backs up a blob before a commit overwrites it and copies it
back when an update is rolled back. It used std::filesystem::copy_file,
which in MSVC calls CopyFile2. Wine 9 and the Protons built on it do not
implement CopyFile2, and the call aborts the process (kevincommits'
finding in #1608, batch 18 item 1). file_system.cpp already avoids it
for the same reason.

copy_blob() now calls CopyFileW(from, to, FALSE). On Windows it copies
the same way: contents, attributes and last-write time, replacing an
existing file.

xgameruntime_gamesave_test gains a case that patches this process's
CopyFile2 to fail and count calls, as Wine's stub would, then runs an
update that overwrites a blob and one that is rolled back. Its 3 checks
fail with main's copy_blob and pass with the fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 19:08:34 -06:00
de8604c3dc Merge ProjectLeonida/mandy main (431ceba4f) into test/round2
Preserves all Round 1/2/2.1 CPU/GPU runtime optimizations alongside upstream
mandy/main changes, resolves all 10 conflicted files, and fixes arena_window
accounting on retired/dropped title windows.

AI-assisted: Antigravity (Gemini 4 Neon).
2026-11-27 19:57:44 -05:00