Commit Graph

4163 Commits

Author SHA1 Message Date
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
202786b51e vulkan_replay: a clamped mesh draw's statistics segment is a mesh segment; a batch reads only its own lists
From kevincommits' finding (item 2) in #1608.

- plan_overlapping_statistics_segments: a clamped indirect draw opens a
  segment of its own (the clamp is a helper dispatch), but the planner then
  set the segment's kind to vertex and skipped the draw-kind rule. A clamped
  indirect mesh draw under overlapping statistics queries therefore ran in
  the full 11-counter pool (VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076)
  and had no mesh-primitives query. The clamped call now falls through to
  the same rule as every draw; a dispatch leaves the kind unset. The
  one-query-at-a-time planner already marked it mesh.
- VulkanQueue::execute keeps the PreparedLists of its largest batch, but
  gathered the segment kinds from all of them, so a smaller batch could pick
  up a stale mesh segment and create the mesh pools (or fail as unsupported
  where the device has none). It now gathers from this batch's lists only,
  through batch_statistics_mesh in vulkan_replay.h.

replay_query_predication_test gains case 16b: the clamped mesh draw's segment
is mesh, a mesh draw after it stays in it, a vertex draw splits; the
non-overlapping planner agrees; and batch_statistics_mesh over the first n
lists leaves the stale tail out. 2 checks fail with the old planner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:48:19 -06:00
b5844c443f bcrypt_rng: BCryptCloseAlgorithmProvider waits for a BCryptGenRandom in flight
gen_random() looked the handle up under g_lock (shared), released the
lock, and then called the host BCryptGenRandom with the host handle. A
concurrent close_algorithm_provider() could unlink the wrapper, close the
host handle and free the wrapper while the host call was still using it
(kevincommits' finding in #1608, item 3).

gen_random() now keeps g_lock shared across the lookup and the host call,
and close_algorithm_provider() closes the host handle under the exclusive
lock, so a close waits for calls in flight on any handle and no later
call can find the closed one. Calls still run side by side. The
system-preferred path takes no handle and no lock, and the seeded path
fills after the shared hold ends, since fill_seeded() takes the lock
exclusive.

A test hook, swap_host_functions_for_test(), lets bcrypt_rng_test install
fake host functions: the fake generate call blocks until released, and
the fake close records whether a call was still running. The new case
fails twice with main's bcrypt_rng.cpp (hook only) and passes with the
fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:42:21 -06:00
f06577169c Address guard: share the page-table buffer across queue families
create_address_guard() made the page table that shaders translated with
--address-guard read through its device address with
VK_SHARING_MODE_EXCLUSIVE, though those shaders run on the direct and
the async-compute queue. The other buffers every queue reads are shared
by the device's queue families (DeviceState::share).

The create info now comes from address_guard::table_buffer_info(), which
shares it the same way (concurrent on two or more families, exclusive on
one), with a CPU test.

Found by kevincommits (#1608).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:42:00 -06:00
d1b7d10c76 library_loader: no ".dll" for an empty name; FreeLibrary drops the cached name
Two bugs from kevincommits' finding in #1608 (item 2):

- module_name() and module_name_w() stripped the directory and then
  added ".dll" when no '.' was left, so "" and a path ending in a slash
  came out as ".dll". That passed every `dll.empty()` guard and went to
  the bundled loader's lookups as a module name. Both now return an
  empty name there.
- host_module_name() caches HMODULE -> module name for GetProcAddress on
  host modules, and free_library() never removed the entry. A DLL loaded
  later at the same base was then served the freed module's shims.
  free_library() now erases the entry when FreeLibrary succeeds; a module
  that is still loaded is looked up again on the next call.

New test library_loader_names: a fake bundled loader records the names
it is asked for, and a fixture DLL with no relocations at a fixed base is
loaded as wsock32.dll (a shimmed host module), freed, and loaded again
under a plain name at the same base. Both checks fail on main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:40:30 -06:00
4d3badfa4e vulkan_replay: a dropped indirect dispatch prepares and emits no clamp pass
From kevincommits' finding (item 3) in #1608.

prepare() set up the clamp pass (vulkan_indirect_clamp.h) of an
ExecuteIndirect(DISPATCH) before it resolved the dispatch's compute pipeline.
When that pipeline was dropped (skipped on request, or async_build and still
building), the command was left out after its clamp was prepared and linked
into the list's shared work budget, and emit() then recorded the clamp pass
before skipping the dispatch. The pass claimed scratch and counter slots and
counted the dropped call's records against the list budget that every later
clamped draw and dispatch of the list shares.

The pipeline is now resolved first, so a dropped dispatch leaves prepare()
before any clamp exists. A pipeline left to PipelineCompiles is not dropped
later: a failed deferred build fails the list.

New CPU test replay_dropped_indirect_clamp follows the repro: a dropped
dispatch alone, before and between built ones, for skipped and async_build
pipelines. 10 checks fail on main; all pass with the change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:39:18 -06:00
d411fe9b4a d3d12, process: null barrier arrays, CopyTiles in a bundle, calibration wait, entry thread and getmainargs expand
From kevincommits' finding (item 4) in #1608.

- d3d12_com.cpp:
  - ResourceBarrier: a count with no array fails the list (check(false)) instead
    of reading through null, as WriteBufferImmediate does.
  - Barrier: the same for a null group array, and for a group with barriers but
    no barrier array (the three array pointers are one union).
  - CopyTiles: a bundle is refused for reserved buffers too, not only for sparse
    images; no copy is allowed in a bundle.
  - submitted_calibration: vkGetQueryPoolResults asks VK_QUERY_RESULT_WAIT_BIT,
    so the read cannot answer VK_NOT_READY.
- process.cpp:
  - run_entry passes the entry point itself to the game thread instead of a
    pointer to its own stack: another thread can end the run before the game
    thread first runs, and run_entry's frame is then gone.
  - __getmainargs/__wgetmainargs expand wildcards when `expand` is nonzero
    (mode 2, as _configure_*_argv does) and fail on a null argc or argv.

Tests: d3d12_com_test (null arrays fail Close; counts of 0 and valid calls
do not), d3d12_buffer_tiles_test (CopyTiles of a reserved buffer in a bundle
fails Close), process_cmdline_test (expand 0 and 1, null argc/argv).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:25:47 -06:00
53ea681a07 silent_audio: NaN volumes refused, master volume under the lock, Reset revokes objects (RT-SILENT-AUDIO-VOLUME-AND-SPATIAL)
From kevincommits' finding on #1608 (item 4):

- SimpleVolume::SetMasterVolume, StreamVolume::SetChannelVolume and
  StreamVolume::SetAllVolumes refuse NaN. They tested
  `level < 0.0f || level > 1.0f`, which is false for NaN, and stored it.
  One helper checks `level >= 0.0f && level <= 1.0f`, as
  SpatialObject::SetVolume does.
- ISimpleAudioVolume's master volume and mute are kept under the client's
  lock, like the channel volumes, instead of read and written bare.
- SpatialStream::Reset revokes every active object, as Microsoft's
  reference for ISpatialAudioObjectRenderStreamBase::Reset says: each is
  inactive, its type can be activated again, and queued ends are dropped.
  The stream keeps a list of its live objects (not owned); an object
  leaves it first thing in its destructor.

Not changed: ActivateSpatialAudioObject during an update pass. The
reference lists no SPTLAUDCLNT_E_OUT_OF_ORDER for it, and activating
objects inside a pass is the documented pattern (this file's own test
does it).

6 new checks in silent_audio_test fail on main and pass with the fix.

AI-assisted (Claude Code).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:25:16 -06:00
c030bfd2ed xgameruntime: gifting UI completes its block, speech without used, MountWithUi and TitleId gaps (RT-OFFLINE-GDK-SHIM-GAPS)
Four offline GDK shim gaps from kevincommits' finding on #1608:

- XStoreShowGiftingUIAsync (store slot 82) is offline_failure_async<82, 5>
  like the other offline *Async slots, so a caller waiting on its block gets
  an answer. The block is the 5th argument (storeContextHandle, storeId,
  name, extendedJsonData, async), as in microsoft/XBOX-GDK-dotnet.
- XSpeechSynthesizerGetStreamData forwards a host stream
  (LEONIDA_LOCAL_SPEECH=1) also when `used` is null; it is _Out_opt_. The
  host provider is made once into a namespace-scope atomic instead of a
  block-scope static on a title thread (the Wine guard issue this file
  already avoids elsewhere). A test hook sets a fake host.
- XPackageMountWithUiAsync completes with E_ACCESSDENIED for the game's
  own package, as XPackageMount refuses it, instead of
  E_GAMEPACKAGE_NO_PACKAGE_IDENTIFIER. A block used again before its result
  was read closes the earlier mount's handle; if the new run does not
  start, the earlier mount keeps its place.
- XGameGetXboxTitleId skips a <TitleId> inside an XML comment, as
  package_locales already does (the comment stripping is now shared).

New checks in xgameruntime_test, xgameruntime_store_test and
xgameruntime_offline_test: 5 fail with main's logic, all pass with the fix.

AI-assisted (Claude Code).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:22:59 -06:00
c05dc2ff52 Size read-only console textures in the title's swizzle mode
Slots 25 and 108 size a list from the PC form of its descriptions
(pc_resource_desc), which drops the title's layout word (0x100 | swizzle
mode). console_texture_layout read the layout from that PC form, so a
texture only the CPU fills was sized in XG's default mode instead of the
one the title named: a 64x64 BC7 texture in SW_64KB_S came out 4 KiB
instead of 64 KiB, a 32x32 RGBA8 linear texture 4 KiB instead of 8 KiB.

Pass the title's layout word to console_texture_layout in
console_placement and apply_console_placement, as the unordered-access
rule already does.

Found by kevincommits (#1608).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:09:12 -06:00
b1cd4f2f39 Merge branches 'r21/textures' and 'r21/async' into test/round2 2026-11-27 19:08:19 -05:00
8133156843 d3d12: 256B TitleMirror piece-hash skip and 16 MiB chunked texture watch index
AI-assisted: Antigravity (Gemini 4 Neon).
2026-11-27 19:08:19 -05:00
9e267665ca runtime: skip before_execute on staging queue and fix async submit coalescing barriers
AI-assisted: Antigravity (Gemini 4 Neon).
2026-11-27 19:08:19 -05:00
6e5e82e400 test: use an invalid handle in the existing-heap check 2026-11-28 00:45:21 +01:00
427ec8426b runtime: wire Round 2 fast-paths, atomic batch uploads, and review fixes
AI-assisted: Antigravity (Gemini 4 Neon).
2026-11-27 18:27:12 -05:00
5247709e9a Merge branches 'r2/textures' and 'r2/floor-merge' into test/round2 2026-11-27 17:53:44 -05:00
34173ab04b runtime: Stage 4 same-queue submit merge, async geometry epoch, and O(1) floor 2026-11-27 17:53:44 -05:00
adbf518879 d3d12: Stage 3a fast CPU texture refresh + Stage 3b GPU detile from TitleMirror 2026-11-27 17:53:43 -05:00
3e4d890c56 Merge pull request #2435 from quartz-heron-58/mesh-serial-waves
rdna2spirv: --mesh-serial-waves, an emulated mesh program's waves one after the other (SHADER-W64-MESH-SERIAL-WAVES)
2026-11-27 23:50:27 +01:00
402035db49 runtime(cpu): gate 4-byte VEX fusion behind LEONIDA_ISA_FUSE_4B and scan Clang switch tables
- Gate 4-byte 0xC5 cross-instruction fusion in isa_jit_patch::patch_image behind
  opt-in LEONIDA_ISA_FUSE_4B=1 (off by default) and document LEONIDA_ISA_FUSE_4B
  in runtime/README.md.
- When LEONIDA_ISA_FUSE_4B=1 is enabled and mark_block_targets resolves a
  RIP-relative target inside a non-executable data section, also scan
  consecutive signed 32-bit Clang/LLVM table-relative jump-table entries
  (	arget_rva = tbl_rva + entry) within [beg_rva, end_rva) so fusion never
  crosses a relative switch case boundary.
- Update isa_jit_patch_test to verify default non-fusion of 4-byte 0xC5 sites,
  opt-in fusion under LEONIDA_ISA_FUSE_4B=1, and fusion refusal across both
  image-base RVA tables and negative table-relative int32_t .rdata switch tables.
2026-11-27 18:49:18 -03:00
8b14930b3d runtime(cpu): add ahead-of-time AVX1/SSE4.2 stub compiler for pre-Haswell hosts 2026-11-27 18:49:17 -03:00
b6e51b7376 runtime(cpu): emulate F16C, FMA3 and AVX2 via XSTATE_AVX on AVX1 hosts
Add runtime/src/avx2_emulation.h and wire it into gta6rt so pre-Haswell AVX1 +
SSE4.2 CPUs (Intel Sandy Bridge and Ivy Bridge) can execute the game's vector
Haswell instruction delta using the host's native 256-bit YMM0..YMM15 state:

- Read and write 256-bit YMM registers through CONTEXT::FltSave.XmmRegisters
  (bits [127:0]) and LocateXStateFeature(XSTATE_AVX) (bits [255:128]), zeroing
  YMM[dst][255:128] on every 128-bit VEX register write and zero-initializing
  untouched upper lanes when transitioning XSTATE_MASK_AVX from clean (0).
- Emulate F16C (vcvtph2ps, vcvtps2ph with RN/RD/RU/RZ and MXCSR rounding), all
  60 FMA3 forms (132/213/231 packed 128/256, scalar ss/sd preserving [127:32] /
  [127:64], and alternating fmaddsub/fmsubadd) via single-rounding std::fmaf /
  std::fma, and AVX2 (256-bit integer SIMD promotions, register/memory
  vbroadcastss/sd/i128 and vpbroadcastb/w/d/q, vinserti128, vextracti128,
  vperm2i128, vpermq, vpermpd, vpermd, vpermps, vpblendd/w/vb, vpsllv*/vpsrlv*/
  vpsravd, vpmovsx*/vpmovzx*, vpmovmskb, and per-lane fault-accurate
  vpmaskmovd/vpmaskmovq).
- Add runtime/test/avx2_emulation_test.cpp covering IEEE-754 F16C conversions,
  VEX decoding, XSTATE_AVX + VPMASKMOVD page-boundary semantics, and live
  256-bit YMM execution on hardware.

Depends on: #2190
Claim: https://github.com/ubiquitarianism/leonida/issues/1608#issuecomment-7181466437
AI-assisted: yes (Antigravity, Gemini 4 Carbon)
2026-11-27 18:49:10 -03:00
66ef2bd689 runtime(cpu): emulate BMI1, BMI2, MOVBE and patch LZCNT/TZCNT on AVX1 hosts
Add runtime/src/bmi_emulation.h and wire it into gta6rt and Loader::protect_sections
so pre-Haswell AVX1 + SSE4.2 CPUs (Intel Sandy Bridge and Ivy Bridge) can execute
the game's integer Haswell/ABM instruction delta:

- Decode and emulate VEX-encoded BMI1 (andn, bextr, blsi, blsmsk, blsr), BMI2
  (bzhi, mulx, pdep, pext, rorx, sarx, shlx, shrx), and legacy 16/32/64-bit MOVBE
  on STATUS_ILLEGAL_INSTRUCTION (#UD), using SEH-guarded non-inlined __movsb copies
  so valid pages take zero syscalls while xmem first-touch, write-watched shadow
  pages, read-only faults and unmapped faults behave like native accesses.
- Patch non-faulting legacy TZCNT (F3 0F BC) and LZCNT (F3 0F BD) before executable
  sections are protected by walking .pdata functions and 0xCC-delimited leaf
  routines: >=5-byte 32/64-bit register sites jump to branchless BSF/BSR + CMOV +
  BT stubs within 2 GiB, and 4-byte, 16-bit or memory sites become UD2 (0F 0B)
  backed by a side-table for the #UD handler (configurable via LEONIDA_LZCNT_PATCH).
- Add runtime/test/bmi_emulation_test.cpp covering decoding, synthetic CONTEXT
  application, immediate byte-trap rejection, stub/UD2 flag consumers, and live
  execution on hardware.

Claim: https://github.com/ubiquitarianism/leonida/issues/1608#issuecomment-7181466437
AI-assisted: yes (Antigravity, Gemini 4 Carbon)
2026-11-27 18:49:03 -03:00
db477857ff d3d12_compile_pool_test: submit the demand after the checkpoint's first look (TEST-COMPILE-POOL-LOAD-FLAKE)
test_a_checkpoint_sees_a_demand_that_started_during_it checked its first
look (!has_compile_waiter()) inside the checkpoint job, after log.start.
The test thread woke on that log.start and submitted the demanded build,
so on a loaded machine the build could be queued or running before the
checkpoint's thread reached its first look, and the check failed (seen
1 in 64 runs with 16 copies running at once).

The job now records the first look and opens a gate; the test waits for
that gate (10 s limit, no fixed sleep) before it submits the build, and
checks the recorded look.

AI-assisted (Claude Code).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:43:37 -06:00
ef5620bf60 present_compose: fix premultiplied sRGB and additive alpha plane 1 decoding 2026-11-28 00:34:14 +03:00
a3452751de d3d12_compile_pool_test: the graphics-only worker wakes the general one for a PSO's held-back job
With LEONIDA_COMPILE_THREADS=1, a PSO's job that is not graphics waits while a graphics build of that PSO runs on
the graphics-only worker. The general worker has gone back to sleep by then, so only the graphics-only worker's
wake on return lets it go. Follow-up to #2233 (a test for the case its review named).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 23:21:11 +02:00
e65692ad63 Merge #407 into consolidate/eight-gb-world
# Conflicts:
#	runtime/shims/d3d12_vulkan_device.cpp
2026-11-27 22:17:05 +01:00
bab63563a8 Merge #2012 into consolidate/eight-gb-world
# Conflicts:
#	runtime/CMakeLists.txt
2026-11-27 22:16:46 +01:00
f47ca265bd Merge #2117 into consolidate/eight-gb-world 2026-11-27 22:16:30 +01:00
75151be1da Merge #1705 into consolidate/eight-gb-world 2026-11-27 22:16:29 +01:00
048eeed509 Merge #2465 into consolidate/eight-gb-world 2026-11-27 22:16:28 +01:00
6014cb1c84 Merge #1851 into consolidate/eight-gb-world 2026-11-27 22:16:27 +01:00
00f317f0c7 Merge #2166 into consolidate/eight-gb-world 2026-11-27 22:16:26 +01:00
c20733f622 Merge #2020 into consolidate/eight-gb-world 2026-11-27 22:16:26 +01:00
0db8ddb8c9 xbox_present: the first HDR10 present wakes the SDR white reader at once
display_white_worker() waited out its second with the predicate
"worker_stop_" only, so the notify effective_sdr_white_nits() sends on
the first HDR10 present ended no wait, and the first Windows SDR white
level was read up to a second late (found by djrolfes, #1608). A request
sent before the worker reached its wait was lost the same way.

The worker moves to leonida::DisplayWhiteCache (src/display_white_cache.h)
with a read_now_ flag, set under the lock with the notify and checked
by the wait, so the first get() is read at once. XboxPresentation holds
one, made last in its constructor and dropped first in its destructor,
as the thread was before. display_white_cache_test checks the first
read with a one-hour period, the periodic reads, a failed read keeping
the last value, and a prompt shutdown.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:14:45 -06:00
ac114f163a Merge pull request #2453 from Tyrannys/test-gpu-oob-harness-msg
GPU tests: give cs_pk_mul_lo_const its 128 words, keep the exit message of a dump row (TEST-GPU-OOB-AND-HARNESS-MSG)
2026-11-27 17:47:23 -03:00
e69104f847 Merge pull request #2055 from xel1uz/test/null-descriptor-no-glslang
runtime tests: vk_null_descriptor_test builds without glslangValidator (TEST-NULL-DESCRIPTOR-NO-GLSLANG)
2026-11-27 17:47:08 -03:00
1a49f13757 loader: wide run-time loads are dynamic; set tls_ga_slot before publishing (RT-LOADER-RUNTIME-SCOPE-AND-TLS-SLOT)
Loader::load_runtime_module_w (LoadLibraryW / LoadLibraryExW of a
bundled DLL) did not open a RuntimeLoadScope, unlike the narrow path and
resolve_module_export. The module was mapped as a static load, so its
DllMain(DLL_PROCESS_ATTACH) got a non-NULL lpvReserved. It now opens the
scope too.

Loader::initialize_tls patched an executable's /GA TLS reads and wrote
m.tls_ga_slot after it had published the slot owner and released
ExclusiveTlsLock, while a thread starting then reads m.tls_ga_slot in
install_thread_block under SharedTlsLock. The patch and the write now
happen before the owner is published.

loader_test checks the wide path's lpvReserved (fails on main);
loader_tls_index0_test checks that the noreserve executable gets its
/GA slot.

Found by kevincommits on #1608.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 13:40:23 -06:00
a23273b5c0 d3d12_xs: CreateSamplerX writes through, and mapped heaps take bound tables
Two gaps in mirroring title-backed descriptor heaps on the Xbox console path:

- Xbox device slot 61 (CreateSamplerX) created the sampler in the real heap only. Every other
  descriptor creator and copier also stores the result at the title's address (local_write_through),
  so a title that copies samplers out of its own heap memory read zeros. Slot 61 now writes through
  as slot 22 does.
- local_mirror_table, run when a descriptor table is bound (list slots 35/36), checked the real range
  with VirtualQuery even when it is a mapped range. Wine can report a live vkMapMemory span as
  MEM_FREE, so on Wine the table was never mirrored. It now skips the check for a mapped range, as
  local_write_through does.

From kevincommits' finding in #1608 (item 2). xs_proxy_mock_test gains check_descriptor_mirror, with
the mock's real heap pointed at memory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 13:38:27 -06:00
aeb24285be gameinput: force-feedback kind changes, SetParams features, locked motor reads, no null memcpy
From a review of the shim by kevincommits (#1608):

- ForceFeedbackEffect::SetParams accepted any kind, also one the motor
  does not report, which CreateForceFeedbackEffect refuses. It now
  refuses it the same way.
- A kind change through SetParams was sent to SDL as an update of the
  existing effect, which SDL_UpdateHapticEffect refuses ("Updating
  effect type is illegal"), so the effect stopped. The poll thread now
  destroys the old SDL effect and creates one of the new type. The
  test's fake haptics refuses a type change in an update, as SDL does.
- CreateForceFeedbackEffect and IsForceFeedbackMotorPoweredOn read the
  motor count, features and haptic handle that open_pad and close_pad
  write on the poll thread under g().mu, without the lock. They take
  it now.
- GetControllerAxisState and GetControllerButtonState called memcpy
  with a null buffer for 0 bytes. They copy only when there is
  something to copy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 13:37:20 -06:00
15566d2a86 dxgi_swapchain: retired swapchain, stale buffer count, unsupported surface, blit filter and composite alpha
Four VulkanSwapchain bugs from a mock-driver review (kevincommits, #1608):

- A failed vkCreateSwapchainKHR still retires its oldSwapchain
  (VUID-VkSwapchainCreateInfoKHR-oldSwapchain-01933). The retired
  swapchain was kept, acquired from, and passed as oldSwapchain again.
  It is now destroyed with its buffers, as the host's swap chain has no
  buffers after a failed ResizeBuffers.
- When the off-screen back buffers could not be made, exposed_count_
  kept the old BufferCount while there was no ring, so image() and
  resource_binding() indexed the native images out of bounds. Nothing
  is exposed until the new buffers exist. ResizeBuffers with count 0
  still keeps the last built BufferCount.
- A surface the queue family cannot present to was kept, and the next
  create() skipped the support check. It is destroyed.
- The present blit always used VK_FILTER_LINEAR. It is NEAREST for a
  1:1 blit, and LINEAR only when the format allows linear filtering
  (VUID-vkCmdBlitImage-filter-02001). The composite alpha is the first
  one the surface offers, opaque first.

dxgi_swapchain_count_test gains one case per finding, following the
repros.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 13:15:10 -06:00
455e574b72 d3d12: ExecuteIndirect with DISPATCH_MESH records as DispatchMesh does (RT-INDIRECT-DISPATCH-MESH-PARITY)
GraphicsCommandList::record_indirect for IndirectKind::dispatch_mesh
differed from DispatchMesh and the indirect DRAW/DRAW_INDEXED path in
three ways:

- it tested viewport 0 only, so a call with viewport 0 empty and
  another viewport set recorded nothing; it now uses
  any_nonempty_viewport();
- it did not set draw.viewports, so the replay drew with viewport 0
  and scissor 0 alone; it now sets draw_viewports();
- it had no mesh_ok check, so a root signature larger than a mesh
  shader's 16-dword window recorded; it is now a recording error, as
  for DispatchMesh.

The root-window check and its direct-heap notes move into one helper
that both paths call. d3d12_mesh_test records each case; each check
fails with its part of the fix reverted.

Found by kevincommits on #1608.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 13:13:05 -06:00