Files
sharpemu/tests/SharpEmu.Libs.Tests/Memory/PhysicalVirtualMemoryTests.cs
T
MarcelMediaDev db4339f698 fix(gta): restore wiped GTA foundation and gameplay path (PPSA04264) (#650)
* fix(kernel): implement APR ResolveFilepathsWithPrefixToIdsAndFileSizes

Resource streamers resolve relative paths against a shared prefix; without
this HLE every call returned NOT_FOUND and assets never got real ids/sizes.

* fix(remoteplay): stub Initialize and GetConnectionStatus as disconnected

Titles probe Remote Play during pad/network bring-up; unresolved imports
returned NOT_FOUND. Report initialized + disconnected so callers take the
normal offline path.

* fix(agc): accept Gen5 hull shaders that omit PGM_LO/HI in CreateShader

Type-5 headers can start with RSRC1/RSRC2; rejecting them left null handles
and Main Thread AVs. Scan the SH table and skip PGM patch when absent.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(kernel): reject getdents on file fds and emit . / .. for empty dirs

Returning rax=0 for non-directory or empty listings looked like EOF and
let GTA treat the fd as a pointer (fiWriteAsyncDataWorker AV at 0xB1).

* fix(hle): enable GuestImageWriteTracker CPU sync on Windows

Windows previously hard-disabled the tracker, so CPU-written guest
planes never marked dirty and host textures stayed empty. Arm pages
with VirtualProtect, handle write AVs in VEH, and warm/test on
VirtualAlloc memory so protect cannot poison the CRT heap.

* fix(agc): skip CB metadata draws for EliminateFastClear/Fmask/DCC

CB_COLOR_CONTROL modes 2/5/6 are colour-buffer metadata ops; applying
the bound shader as a normal colour draw corrupts subsequent composites.
Decode MODE from bits [6:4] and return before translate.

* fix(agc): merge Prospero attrib-table formats onto IR vertex inputs

IR-discovered BufferLoadFormat often keeps a stale float sharp format;
patch DataFormat/offset from the AGC attrib table (semantic index),
allow offen fetches, and map quirks 113/121 through NarrowVk for host
vertex input.

* fix(audio): harden AudioOut2 stack out-buffer writes against canary smash

Titles that stack-allocate AudioOut2 outs next to the frame canary were
corrupted by oversized or mistyped HLE writes; keep ContextPush pacing.

* Revert "fix(memory): reserve only large regions (#608)"

This reverts commit 8f9456229a.

* fix(gpu): decode Gen5 R16 and RG32 render-target formats

* fix(audio): AudioOut2 host beds, deeper waveOut queue, AJM MP3

GTA V Enhanced routes intro/menu audio through AudioOut2 and FMOD's AJM
MP3 path. Wire PortCreate/PortSetAttributes/ContextPush to dual host
stereo streams, deepen WinMM queue to 128KiB, and decode AJM codec 0
with a stateful NLayer helper so menu music is not silent.

* fix(agc): map PS interpolants via SPI_PS_INPUT_CNTL semantics

Identity ATTR→param wiring ignored hardware remapping, so UI draws
got wrong (or empty) interpolants. Pack CNTL from matched PS/GS
semantics, thread it into Vulkan/Metal as Location/Flat, and fingerprint
it in the graphics shader cache key.

* fix(agc): rect-list/NGG strips, Index8 expand, and GE_INDX_OFFSET

NGG single-rect UI needs triangle-strip expansion; Prospero Index8 must
expand to host u16; glyphs need base vertex from GE_INDX_OFFSET. Skip
param-less rect-lists instead of inventing colour draws.

* fix(np): report GTA Story Mode addcont entitlements as owned

NpEntitlementAccess was returning an empty add-on list, so GTA V Enhanced offered Buy Story Mode. Publish the installed license labels and stub premium-event registration so offline sessions take the owned path.

* fix(cpu): prefer native workers for all guest entry stubs

Route thread entry, continuation, and main entry through RunGuestEntryStub so guest stubs are not invoked above CLR-managed frames (UnmanagedCallersOnly FailFast). Keep requireNativeWorker for tbb_thead; other paths prefer workers with calli fallback.

* fix(agc): implement Rewind/Jump writers and IT_REWIND waits

GTA Subrender AVs came from AcbJumpGetSize / DcbRewind returning NOT_FOUND as packet sizes. Add IT_REWIND and INDIRECT_BUFFER writers, patch SetRewindState into the GPU wait registry, and nest-parse 4-dword jumps.

* fix(gpu): use AddrLib ExactXor for Gen5 Standard256B (mode 1)

Mode 5 already had Standard4K ExactXor; mode 1 still used the generic StandardSwizzle block table, which mis-detiles Gen5 UI atlases.

* Revert "fix(cpu): prefer native workers for all guest entry stubs"

This reverts commit 31c4db0d38.

* fix(memory): commit-first large maps; reserve only on failure

Replace the #608 always-reserve-only exact-map path with allocate-first and lazy reserve fallback when a huge non-exec commit cannot be satisfied. Prime and widen GetPointer commit so the fallback path is safer for native walkers. Drops the need for a hard #608 revert.

* [Agc] Implement fused shader half exports

* fix(agc): accept optional hull state in CreatePrimState

Port the CreatePrimState hull-optional path from #583 so fused HS pipelines (GTA) are not rejected with INVALID_ARGUMENT. Geometry-derived CX/UC writes are unchanged; hull is traced only.

* fix(videoout): restore thread-safe VulkanHostBufferPool (#564)

The 6db095e wipe dropped CasualcoderDev's lock-ordering-safe pool. Concurrent Return/TryTake without the gate races after the first present and can hang the submit path.

* Revert "fix(agc): implement Rewind/Jump writers and IT_REWIND waits"

This reverts commit bec77bf083.

* test(memory): align lazy-commit expectations with commit-first policy

Fake hosts must reject Allocate so reserve-only paths still run, and GetPointer asserts the 32 MiB prime range including AlignUp spill.

* diag(gpu): log guest-queue backlog breakdown under backpressure

Rate-limit top work types and ordered debugName prefixes when the Vulkan guest work queue stalls, so North Yankton logs show acquire/label vs draw traffic instead of only VulkanOrderedGuestAction.

* perf(agc): coalesce acquire flushes and batch non-DMA label wakes

Flush pending ACQUIRE_MEM invalidation at draw/dispatch/dma/flip boundaries instead of before every packet, and complete release/write-data producers in the same ordered action so load paths enqueue far fewer VulkanOrderedGuestAction items.

* perf(gpu): wait for ordered-action fences and keep draining sync

On Windows/Linux, block briefly for queue-visibility fences instead of deferring the whole logical queue for the tick. Prefer ordered sync/flip heads under backlog pressure, and keep macOS non-blocking defer behavior.

* perf(gpu): raise sync-item ceiling above payload guest-work cap

Apply SHARPEMU_PENDING_GUEST_WORK_ITEMS mainly to compute/draw/image payload work, and allow a higher SHARPEMU_PENDING_GUEST_SYNC_ITEMS ceiling for zero-payload ordered actions and flip markers. Keep the byte budget as the RAM safety valve.

* fix(gta): stub Voice ports and implement sceKernelCheckReachability

Resolve North Yankton-path Voice Create/Delete/Connect/Disconnect/End NIDs and EnumerationThread reachability checks so leftover unresolved imports are not on the critical path.

* diag(gta): arm flip/present/wait probes after North Audio

Rate-limited load_progress TRACE for flip submit, ordered flip enqueue, present taken/not-taken, and GPU wait backlog so North Yankton freezes can be classified without full AGC tracing.

* fix(ampr): restore sequential offset=-1 reads for streamer packs

Re-wire PakDirectoryTracker into sceAmprAprCommandBufferReadFile (dropped in #216) so RAGE sequential pack reads no longer fail while the North Yankton UI keeps flipping. Also rate-limit CheckReachability miss paths for EnumerationThread diagnosis.

* fix(hle/videoout): Windows GuestImage opt-in and keep GTA intro without sync

Default the tracker off on Windows to avoid VirtualProtect thrash, gate AGC
texel-copy skips on Enabled so guest Bink planes keep shipping pixels, and
drain CPU-written images on the present thread when sync is opted in.

* fix(videoout): probe guest content when tracker off so UI can skip copies

Restores upload-known/texture-cache skips for Dead Cells menus, and uses a
sparse guest-memory fingerprint when GuestImageWriteTracker is disabled so
CPU-updated Bink planes still force texel copies for GTA intro.

* fix(audio): keep 128KiB host queue AudioOut2-only

Restore the default 32 KiB (~171 ms) PCM bed for classic AudioOut so
titles like Dreaming Sarah stay in sync; only AudioOut2 opens the deeper
queue needed for bursty FMOD Push on GTA.

---------

Co-authored-by: samto6 <123419830+samto6@users.noreply.github.com>
2026-07-27 01:58:55 +03:00

299 lines
11 KiB
C#

// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using SharpEmu.Core.Memory;
using SharpEmu.Core.Loader;
using SharpEmu.HLE.Host;
using Xunit;
namespace SharpEmu.Libs.Tests.Memory;
// PhysicalVirtualMemory is the host-backed (identity-mapped) implementation.
// Huge non-executable maps (> 4 GiB) prefer commit-first, then fall back to
// reserve-only + lazy commit when Allocate fails. TryAllocateGuestMemory serves
// a first-fit free-list with coalescing. These tests pin that behaviour through
// fake IHostMemory implementations that refuse full Allocate for huge sizes.
public sealed class PhysicalVirtualMemoryTests
{
// 1. Lazy commit: a reserve-only region has its pages committed on demand
// when read; freshly committed pages read as zero.
[Fact]
public void LazyReadCommitsPageOnDemandAndReadsZero()
{
using var host = new LazyZeroedHostMemory();
using var memory = new PhysicalVirtualMemory(host);
// > 4 GiB, non-executable; fake host rejects Allocate so reserve-only
// + lazy commit is used.
var address = memory.AllocateAt(0, (4UL << 30) + 0x1000, executable: false);
Assert.NotEqual(0UL, address);
// Discard the priming commits AllocateAt issues up front; we want to
// observe the on-demand commit triggered by the read itself.
host.CommitCalls.Clear();
var buffer = new byte[1];
Assert.True(memory.TryRead(address, buffer));
Assert.Equal(0, buffer[0]);
// The touched page (page-aligned to `address`) was committed on demand.
var page = address & ~0xFFFUL;
Assert.Equal([(page, 0x1000UL, HostPageProtection.ReadWrite)], host.CommitCalls);
}
[Fact]
public void RepeatedLazyReadUsesCommittedRangeCache()
{
using var host = new LazyZeroedHostMemory();
using var memory = new PhysicalVirtualMemory(host);
var address = memory.AllocateAt(0, (4UL << 30) + 0x1000, executable: false);
host.CommitCalls.Clear();
Span<byte> buffer = stackalloc byte[16];
Assert.True(memory.TryRead(address + 0x100, buffer));
var queryCallsAfterFirstRead = host.QueryCalls;
Assert.True(memory.TryRead(address + 0x108, buffer[..8]));
Assert.Equal(queryCallsAfterFirstRead, host.QueryCalls);
Assert.Single(host.CommitCalls);
}
[Fact]
public void TryCopyHandlesOverlappingIdentityMappedRanges()
{
using var host = new LazyZeroedHostMemory();
using var memory = new PhysicalVirtualMemory(host);
var address = memory.AllocateAt(0, (4UL << 30) + 0x1000, executable: false);
Assert.True(memory.TryWrite(address, new byte[] { 1, 2, 3, 4, 5, 6 }));
Assert.True(memory.TryCopy(address + 2, address, 4));
Span<byte> result = stackalloc byte[6];
Assert.True(memory.TryRead(address, result));
Assert.Equal(new byte[] { 1, 2, 1, 2, 3, 4 }, result.ToArray());
}
[Fact]
public void RepeatedTryCopyKeepsSourceAndDestinationCommitRangesCached()
{
using var host = new LazyZeroedHostMemory();
using var memory = new PhysicalVirtualMemory(host);
var address = memory.AllocateAt(0, (4UL << 30) + 0x1000, executable: false);
var source = address + 0x100;
var destination = address + 0x1100;
Assert.True(memory.TryWrite(source, new byte[] { 1, 2, 3, 4 }));
Assert.True(memory.TryWrite(destination, new byte[4]));
host.CommitCalls.Clear();
Assert.True(memory.TryCopy(destination, source, 4));
var queryCallsAfterFirstCopy = host.QueryCalls;
Assert.True(memory.TryCopy(destination, source, 4));
Assert.Equal(queryCallsAfterFirstCopy, host.QueryCalls);
}
// 2. Reserve-only region: GetPointer commits the page before returning it,
// so callers receive a valid (non-null) pointer. An unmapped address yields null.
[Fact]
public unsafe void GetPointerOnReserveOnlyRegionCommitsAndReturnsValidPointer()
{
using var host = new LazyZeroedHostMemory();
using var memory = new PhysicalVirtualMemory(host);
var address = memory.AllocateAt(0, (4UL << 30) + 0x1000, executable: false);
host.CommitCalls.Clear();
var pointer = memory.GetPointer(address + 0x123);
Assert.NotEqual(0UL, (ulong)pointer);
Assert.Equal(address + 0x123, (ulong)pointer);
// GetPointer primes a 32 MiB working-set chunk (page-sized commits
// against this fake host's 4 KiB Query regions). Non-page-aligned
// start makes AlignUp(addr + chunk) cover one extra page.
const ulong lazyPrimeChunkBytes = 0x0200_0000UL;
var page = (address + 0x123) & ~0xFFFUL;
var endPage = (address + 0x123 + lazyPrimeChunkBytes + 0xFFFUL) & ~0xFFFUL;
Assert.Equal((int)((endPage - page) / 0x1000UL), host.CommitCalls.Count);
Assert.Equal((page, 0x1000UL, HostPageProtection.ReadWrite), host.CommitCalls[0]);
Assert.All(
host.CommitCalls,
call => Assert.Equal(0x1000UL, call.Size));
}
[Fact]
public unsafe void GetPointerOnUnmappedAddressReturnsNull()
{
using var host = new LazyZeroedHostMemory();
using var memory = new PhysicalVirtualMemory(host);
Assert.Equal(0UL, (ulong)memory.GetPointer(0x0001_0000));
}
// 3. Free-list reuse: a freed range is served back by first-fit allocation,
// preferring the lowest fitting free range over the larger trailing span.
[Fact]
public void FreedRangeIsReusedByFirstFitAllocation()
{
using var memory = new PhysicalVirtualMemory(new FakeHostMemory());
Assert.True(memory.TryAllocateGuestMemory(0x4000, 0x1000, out var first));
Assert.True(memory.TryAllocateGuestMemory(0x4000, 0x1000, out var second));
Assert.NotEqual(first, second);
Assert.True(memory.TryFreeGuestMemory(first));
// A smaller allocation must reuse first's freed slot (lowest fitting range),
// not the larger trailing free range.
Assert.True(memory.TryAllocateGuestMemory(0x2000, 0x1000, out var reused));
Assert.Equal(first, reused);
}
// 4. Coalescing: freeing the middle of three adjacent ranges merges both the
// left and right free neighbours in a single TryFreeGuestMemory call,
// restoring the full span for subsequent first-fit reuse.
[Fact]
public void FreeingMiddleRangeCoalescesBothNeighbours()
{
using var memory = new PhysicalVirtualMemory(new FakeHostMemory());
// Three adjacent 0x1000 allocations: offsets 0x1000, 0x2000, 0x3000.
Assert.True(memory.TryAllocateGuestMemory(0x1000, 0x1000, out var first));
Assert.True(memory.TryAllocateGuestMemory(0x1000, 0x1000, out var second));
Assert.True(memory.TryAllocateGuestMemory(0x1000, 0x1000, out var third));
// Free the outer ranges first, leaving two separate free ranges.
Assert.True(memory.TryFreeGuestMemory(first));
Assert.True(memory.TryFreeGuestMemory(third));
// Freeing the middle range must coalesce both neighbours at once.
Assert.True(memory.TryFreeGuestMemory(second));
// The whole arena is now one coalesced free range; a full-arena allocation
// reuses first's base address.
Assert.True(memory.TryAllocateGuestMemory(0x000F_F000, 0x1000, out var coalesced));
Assert.Equal(first, coalesced);
}
/// <summary>
/// Host memory backed by a single real, zero-initialised page. Reserve/Allocate
/// report the page-aligned buffer address so lazy-commit read paths can actually
/// dereference the returned pointer. Query always reports Reserved, so
/// EnsureRangeCommitted issues a Commit on first access.
/// </summary>
private sealed unsafe class LazyZeroedHostMemory : IHostMemory, IDisposable
{
private readonly void* _allocation;
private readonly ulong _address;
private bool _freed;
public LazyZeroedHostMemory()
{
_allocation = System.Runtime.InteropServices.NativeMemory.AllocZeroed(0x3000);
_address = ((ulong)_allocation + 0xFFF) & ~0xFFFUL;
}
public List<(ulong Address, ulong Size, HostPageProtection Protection)> CommitCalls { get; } = [];
public int QueryCalls { get; private set; }
// Force the commit-first → reserve-only fallback for huge maps.
public ulong Allocate(ulong desiredAddress, ulong size, HostPageProtection protection) => 0;
public ulong Reserve(ulong desiredAddress, ulong size, HostPageProtection protection) => _address;
public bool Commit(ulong address, ulong size, HostPageProtection protection)
{
CommitCalls.Add((address, size, protection));
return true;
}
public bool Free(ulong address)
{
// The real buffer is released in Dispose; keep Free a no-op so
// PhysicalVirtualMemory.Clear does not double-free it.
return true;
}
public bool Protect(ulong address, ulong size, HostPageProtection protection, out uint rawOldProtection)
{
rawOldProtection = 0;
return true;
}
public bool ProtectRaw(ulong address, ulong size, uint rawProtection, out uint rawOldProtection)
{
rawOldProtection = 0;
return true;
}
public bool Query(ulong address, out HostRegionInfo info)
{
QueryCalls++;
var pageAddress = address & ~0xFFFUL;
info = new HostRegionInfo(
pageAddress,
pageAddress,
0x1000,
HostRegionState.Reserved,
0,
HostPageProtection.NoAccess,
0,
0);
return true;
}
public void FlushInstructionCache(ulong address, ulong size)
{
}
public void Dispose()
{
if (!_freed)
{
System.Runtime.InteropServices.NativeMemory.Free(_allocation);
_freed = true;
}
}
}
// Minimal host memory for free-list tests: Allocate honours the desired
// address (or a fallback), everything else succeeds as a no-op. The guest
// allocation arena never dereferences, so no real backing is required.
private sealed class FakeHostMemory : IHostMemory
{
public ulong Allocate(ulong desiredAddress, ulong size, HostPageProtection protection) =>
desiredAddress != 0 ? desiredAddress : 0x00007000_0000_0000;
public ulong Reserve(ulong desiredAddress, ulong size, HostPageProtection protection) =>
Allocate(desiredAddress, size, protection);
public bool Commit(ulong address, ulong size, HostPageProtection protection) => true;
public bool Free(ulong address) => true;
public bool Protect(ulong address, ulong size, HostPageProtection protection, out uint rawOldProtection)
{
rawOldProtection = 0;
return true;
}
public bool ProtectRaw(ulong address, ulong size, uint rawProtection, out uint rawOldProtection)
{
rawOldProtection = 0;
return true;
}
public bool Query(ulong address, out HostRegionInfo info)
{
info = default;
return false;
}
public void FlushInstructionCache(ulong address, ulong size)
{
}
}
}