mirror of
https://github.com/par274/sharpemu.git
synced 2026-07-30 22:49:53 +08:00
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 commit8f9456229a. * 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 commit31c4db0d38. * 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) The6db095ewipe 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 commitbec77bf083. * 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>
This commit is contained in:
@@ -0,0 +1,330 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using System.Buffers.Binary;
|
||||
using SharpEmu.HLE;
|
||||
using SharpEmu.Libs.Agc;
|
||||
using Xunit;
|
||||
|
||||
namespace SharpEmu.Libs.Tests.Agc;
|
||||
|
||||
// sceAgcGetFusedShaderSize (dolOmWH+huQ) and sceAgcFuseShaderHalves (fd5Bp5tGTgo)
|
||||
// join a GS or HS front/back shader half pair into one shader: the fused header
|
||||
// is the back half retyped, the back half's SH registers become the fused
|
||||
// register image, and the front half contributes its program address
|
||||
// (SPI_SHADER_PGM_LO/HI_ES) and checksum registers.
|
||||
public sealed class AgcFusedShaderTests
|
||||
{
|
||||
private const ulong BaseAddress = 0x1_0000_0000;
|
||||
private const int MemorySize = 0x4000;
|
||||
|
||||
private const ulong FrontShader = BaseAddress + 0x0000;
|
||||
private const ulong BackShader = BaseAddress + 0x0100;
|
||||
private const ulong FusedShader = BaseAddress + 0x0200;
|
||||
private const ulong FrontRegisters = BaseAddress + 0x0300;
|
||||
private const ulong BackRegisters = BaseAddress + 0x0400;
|
||||
private const ulong FrontSpecials = BaseAddress + 0x0500;
|
||||
private const ulong BackSpecials = BaseAddress + 0x0600;
|
||||
private const ulong Scratch = BaseAddress + 0x0700;
|
||||
private const ulong SizeResult = BaseAddress + 0x0800;
|
||||
|
||||
private const ulong ShaderUserDataOffset = 0x08;
|
||||
private const ulong ShaderCodeOffset = 0x10;
|
||||
private const ulong ShaderShRegistersOffset = 0x20;
|
||||
private const ulong ShaderSpecialsOffset = 0x28;
|
||||
private const ulong ShaderTypeOffset = 0x5A;
|
||||
private const ulong ShaderNumShRegistersOffset = 0x5C;
|
||||
|
||||
private const byte GsFront = 4;
|
||||
private const byte HsFront = 5;
|
||||
private const byte GsBack = 6;
|
||||
private const byte HsBack = 7;
|
||||
|
||||
private const ulong FrontCode = 0x0000_1234_5678_9A00;
|
||||
|
||||
[Fact]
|
||||
public void GetFusedShaderSize_GsPair_ReportsBackRegisterBytes()
|
||||
{
|
||||
var (memory, ctx) = CreateGsPair();
|
||||
|
||||
ctx[CpuRegister.Rdi] = SizeResult;
|
||||
ctx[CpuRegister.Rsi] = FrontShader;
|
||||
ctx[CpuRegister.Rdx] = BackShader;
|
||||
var result = AgcExports.GetFusedShaderSize(ctx);
|
||||
|
||||
Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_OK, result);
|
||||
Assert.Equal(5UL * 8UL, ReadUInt64(memory, SizeResult));
|
||||
Assert.Equal(4UL, ReadUInt64(memory, SizeResult + 8));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetFusedShaderSize_MismatchedHalves_Rejects()
|
||||
{
|
||||
var (memory, ctx) = CreateGsPair();
|
||||
WriteByte(memory, BackShader + ShaderTypeOffset, HsBack);
|
||||
|
||||
ctx[CpuRegister.Rdi] = SizeResult;
|
||||
ctx[CpuRegister.Rsi] = FrontShader;
|
||||
ctx[CpuRegister.Rdx] = BackShader;
|
||||
var result = AgcExports.GetFusedShaderSize(ctx);
|
||||
|
||||
Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT, result);
|
||||
Assert.Equal(0UL, ReadUInt64(memory, SizeResult));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FuseShaderHalves_GsPairWithScratch_BuildsFusedShader()
|
||||
{
|
||||
var (memory, ctx) = CreateGsPair();
|
||||
|
||||
ctx[CpuRegister.Rdi] = FusedShader;
|
||||
ctx[CpuRegister.Rsi] = FrontShader;
|
||||
ctx[CpuRegister.Rdx] = BackShader;
|
||||
ctx[CpuRegister.Rcx] = Scratch;
|
||||
var result = AgcExports.FuseShaderHalves(ctx);
|
||||
|
||||
Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_OK, result);
|
||||
|
||||
// Fused header is the back half with type kGs, cleared user data, and
|
||||
// registers relocated to the scratch image.
|
||||
Assert.Equal(2, ReadByte(memory, FusedShader + ShaderTypeOffset));
|
||||
Assert.Equal(0UL, ReadUInt64(memory, FusedShader + ShaderUserDataOffset));
|
||||
Assert.Equal(Scratch, ReadUInt64(memory, FusedShader + ShaderShRegistersOffset));
|
||||
Assert.Equal(5, ReadByte(memory, FusedShader + ShaderNumShRegistersOffset));
|
||||
Assert.Equal(
|
||||
ReadUInt64(memory, BackShader + ShaderCodeOffset),
|
||||
ReadUInt64(memory, FusedShader + ShaderCodeOffset));
|
||||
|
||||
// The back half's own register image is untouched.
|
||||
Assert.Equal(0x1111_1111u, ReadUInt32(memory, BackRegisters + 4));
|
||||
|
||||
// Scratch image: LO_ES points at the front code, HI_ES keeps its upper
|
||||
// bits, both checksum occurrences carry the front half's values.
|
||||
Assert.Equal(0xC8u, ReadUInt32(memory, Scratch + 0));
|
||||
Assert.Equal(0x3456_789Au, ReadUInt32(memory, Scratch + 4));
|
||||
Assert.Equal(0xC9u, ReadUInt32(memory, Scratch + 8));
|
||||
Assert.Equal(0xAABB_CC12u, ReadUInt32(memory, Scratch + 12));
|
||||
Assert.Equal(0xAAAA_0001u, ReadUInt32(memory, Scratch + 20));
|
||||
Assert.Equal(0xBBBB_0002u, ReadUInt32(memory, Scratch + 28));
|
||||
Assert.Equal(0x5555_5555u, ReadUInt32(memory, Scratch + 36));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FuseShaderHalves_NoScratch_PatchesBackRegistersInPlace()
|
||||
{
|
||||
var (memory, ctx) = CreateGsPair();
|
||||
|
||||
ctx[CpuRegister.Rdi] = FusedShader;
|
||||
ctx[CpuRegister.Rsi] = FrontShader;
|
||||
ctx[CpuRegister.Rdx] = BackShader;
|
||||
ctx[CpuRegister.Rcx] = 0;
|
||||
var result = AgcExports.FuseShaderHalves(ctx);
|
||||
|
||||
Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_OK, result);
|
||||
Assert.Equal(BackRegisters, ReadUInt64(memory, FusedShader + ShaderShRegistersOffset));
|
||||
Assert.Equal(0x3456_789Au, ReadUInt32(memory, BackRegisters + 4));
|
||||
Assert.Equal(0xAABB_CC12u, ReadUInt32(memory, BackRegisters + 12));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FuseShaderHalves_WaveSizeMismatch_Rejects()
|
||||
{
|
||||
var (memory, ctx) = CreateGsPair();
|
||||
WriteUInt32(memory, BackSpecials + 0x08 + 4, 0u);
|
||||
|
||||
ctx[CpuRegister.Rdi] = FusedShader;
|
||||
ctx[CpuRegister.Rsi] = FrontShader;
|
||||
ctx[CpuRegister.Rdx] = BackShader;
|
||||
ctx[CpuRegister.Rcx] = Scratch;
|
||||
var result = AgcExports.FuseShaderHalves(ctx);
|
||||
|
||||
Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT, result);
|
||||
Assert.Equal(0, ReadByte(memory, FusedShader + ShaderTypeOffset));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FuseShaderHalves_HsPair_PatchesLoLs()
|
||||
{
|
||||
var (memory, ctx) = CreateGsPair();
|
||||
WriteByte(memory, FrontShader + ShaderTypeOffset, HsFront);
|
||||
WriteByte(memory, BackShader + ShaderTypeOffset, HsBack);
|
||||
WriteUInt32(memory, BackRegisters + 0, 0x148u);
|
||||
WriteUInt32(memory, BackRegisters + 8, 0x149u);
|
||||
|
||||
ctx[CpuRegister.Rdi] = FusedShader;
|
||||
ctx[CpuRegister.Rsi] = FrontShader;
|
||||
ctx[CpuRegister.Rdx] = BackShader;
|
||||
ctx[CpuRegister.Rcx] = Scratch;
|
||||
var result = AgcExports.FuseShaderHalves(ctx);
|
||||
|
||||
Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_OK, result);
|
||||
Assert.Equal(3, ReadByte(memory, FusedShader + ShaderTypeOffset));
|
||||
Assert.Equal(0x3456_789Au, ReadUInt32(memory, Scratch + 4));
|
||||
// Checksum grafting is a geometry-pair behavior; the HS image keeps its own values.
|
||||
Assert.Equal(0x1111_0001u, ReadUInt32(memory, Scratch + 20));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FuseShaderHalves_MissingSpecials_SkipsWaveSizeGate()
|
||||
{
|
||||
var (memory, ctx) = CreateGsPair();
|
||||
// The divergence the mismatch test rejects passes when a half lacks specials.
|
||||
WriteUInt64(memory, FrontShader + ShaderSpecialsOffset, 0);
|
||||
WriteUInt32(memory, BackSpecials + 0x08 + 4, 0u);
|
||||
|
||||
ctx[CpuRegister.Rdi] = FusedShader;
|
||||
ctx[CpuRegister.Rsi] = FrontShader;
|
||||
ctx[CpuRegister.Rdx] = BackShader;
|
||||
ctx[CpuRegister.Rcx] = Scratch;
|
||||
var result = AgcExports.FuseShaderHalves(ctx);
|
||||
|
||||
Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_OK, result);
|
||||
Assert.Equal(2, ReadByte(memory, FusedShader + ShaderTypeOffset));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FuseShaderHalves_ProgramRegisterAbsent_LeavesImageUntouched()
|
||||
{
|
||||
var (memory, ctx) = CreateGsPair();
|
||||
WriteByte(memory, FrontShader + ShaderTypeOffset, HsFront);
|
||||
WriteByte(memory, BackShader + ShaderTypeOffset, HsBack);
|
||||
|
||||
ctx[CpuRegister.Rdi] = FusedShader;
|
||||
ctx[CpuRegister.Rsi] = FrontShader;
|
||||
ctx[CpuRegister.Rdx] = BackShader;
|
||||
ctx[CpuRegister.Rcx] = Scratch;
|
||||
var result = AgcExports.FuseShaderHalves(ctx);
|
||||
|
||||
// No LO_LS entry in the back image: the fuse still succeeds and the
|
||||
// scratch copy stays verbatim.
|
||||
Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_OK, result);
|
||||
Assert.Equal(3, ReadByte(memory, FusedShader + ShaderTypeOffset));
|
||||
Assert.Equal(0x1111_1111u, ReadUInt32(memory, Scratch + 4));
|
||||
Assert.Equal(0xAABB_CC77u, ReadUInt32(memory, Scratch + 12));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FuseShaderHalves_UnpairedProgramRegister_LeavesImageUntouched()
|
||||
{
|
||||
var (memory, ctx) = CreateGsPair();
|
||||
WriteByte(memory, FrontShader + ShaderTypeOffset, HsFront);
|
||||
WriteByte(memory, BackShader + ShaderTypeOffset, HsBack);
|
||||
WriteUInt32(memory, BackRegisters + 0, 0x148u);
|
||||
|
||||
ctx[CpuRegister.Rdi] = FusedShader;
|
||||
ctx[CpuRegister.Rsi] = FrontShader;
|
||||
ctx[CpuRegister.Rdx] = BackShader;
|
||||
ctx[CpuRegister.Rcx] = Scratch;
|
||||
var result = AgcExports.FuseShaderHalves(ctx);
|
||||
|
||||
// LO_LS is present but the next entry is not HI_LS, so the patch is skipped.
|
||||
Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_OK, result);
|
||||
Assert.Equal(0x1111_1111u, ReadUInt32(memory, Scratch + 4));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FuseShaderHalves_ProgramRegisterAtImageEnd_LeavesImageUntouched()
|
||||
{
|
||||
var (memory, ctx) = CreateGsPair();
|
||||
WriteByte(memory, FrontShader + ShaderTypeOffset, HsFront);
|
||||
WriteByte(memory, BackShader + ShaderTypeOffset, HsBack);
|
||||
WriteUInt32(memory, BackRegisters + 4 * 8, 0x148u);
|
||||
|
||||
ctx[CpuRegister.Rdi] = FusedShader;
|
||||
ctx[CpuRegister.Rsi] = FrontShader;
|
||||
ctx[CpuRegister.Rdx] = BackShader;
|
||||
ctx[CpuRegister.Rcx] = Scratch;
|
||||
var result = AgcExports.FuseShaderHalves(ctx);
|
||||
|
||||
// The hi half of the pair would sit past the register image.
|
||||
Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_OK, result);
|
||||
Assert.Equal(0x5555_5555u, ReadUInt32(memory, Scratch + 36));
|
||||
}
|
||||
|
||||
private static (FakeCpuMemory Memory, CpuContext Ctx) CreateGsPair()
|
||||
{
|
||||
var memory = new FakeCpuMemory(BaseAddress, MemorySize);
|
||||
var ctx = new CpuContext(memory, Generation.Gen5);
|
||||
|
||||
WriteByte(memory, FrontShader + ShaderTypeOffset, GsFront);
|
||||
WriteUInt64(memory, FrontShader + ShaderCodeOffset, FrontCode);
|
||||
WriteUInt64(memory, FrontShader + ShaderShRegistersOffset, FrontRegisters);
|
||||
WriteUInt64(memory, FrontShader + ShaderSpecialsOffset, FrontSpecials);
|
||||
WriteByte(memory, FrontShader + ShaderNumShRegistersOffset, 4);
|
||||
|
||||
WriteByte(memory, BackShader + ShaderTypeOffset, GsBack);
|
||||
WriteUInt64(memory, BackShader + ShaderCodeOffset, 0x0000_0BAD_F00D_BE00);
|
||||
WriteUInt64(memory, BackShader + ShaderShRegistersOffset, BackRegisters);
|
||||
WriteUInt64(memory, BackShader + ShaderSpecialsOffset, BackSpecials);
|
||||
WriteUInt64(memory, BackShader + ShaderUserDataOffset, 0xDEAD_BEEF);
|
||||
WriteByte(memory, BackShader + ShaderNumShRegistersOffset, 5);
|
||||
|
||||
// Back image: ES program address pair, two checksum slots, one bystander.
|
||||
WriteRegister(memory, BackRegisters, 0, 0xC8u, 0x1111_1111u);
|
||||
WriteRegister(memory, BackRegisters, 1, 0xC9u, 0xAABB_CC77u);
|
||||
WriteRegister(memory, BackRegisters, 2, 0x80u, 0x1111_0001u);
|
||||
WriteRegister(memory, BackRegisters, 3, 0x80u, 0x1111_0002u);
|
||||
WriteRegister(memory, BackRegisters, 4, 0x10u, 0x5555_5555u);
|
||||
|
||||
// Front image: GS RSRC pair as shipped, then the checksum values to graft.
|
||||
WriteRegister(memory, FrontRegisters, 0, 0x8Au, 0x0123_4567u);
|
||||
WriteRegister(memory, FrontRegisters, 1, 0x8Bu, 0x89AB_CDEFu);
|
||||
WriteRegister(memory, FrontRegisters, 2, 0x80u, 0xAAAA_0001u);
|
||||
WriteRegister(memory, FrontRegisters, 3, 0x80u, 0xBBBB_0002u);
|
||||
|
||||
// VGT_SHADER_STAGES_EN register pairs with the GS wave32 enable bit set on both halves.
|
||||
WriteUInt32(memory, FrontSpecials + 0x08, 0x1F1u);
|
||||
WriteUInt32(memory, FrontSpecials + 0x08 + 4, 1u << 22);
|
||||
WriteUInt32(memory, BackSpecials + 0x08, 0x1F1u);
|
||||
WriteUInt32(memory, BackSpecials + 0x08 + 4, 1u << 22);
|
||||
|
||||
return (memory, ctx);
|
||||
}
|
||||
|
||||
private static void WriteRegister(FakeCpuMemory memory, ulong array, int index, uint offset, uint value)
|
||||
{
|
||||
WriteUInt32(memory, array + (ulong)index * 8, offset);
|
||||
WriteUInt32(memory, array + (ulong)index * 8 + 4, value);
|
||||
}
|
||||
|
||||
private static void WriteByte(FakeCpuMemory memory, ulong address, byte value)
|
||||
{
|
||||
Span<byte> buffer = [value];
|
||||
Assert.True(memory.TryWrite(address, buffer));
|
||||
}
|
||||
|
||||
private static void WriteUInt32(FakeCpuMemory memory, ulong address, uint value)
|
||||
{
|
||||
Span<byte> buffer = stackalloc byte[sizeof(uint)];
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(buffer, value);
|
||||
Assert.True(memory.TryWrite(address, buffer));
|
||||
}
|
||||
|
||||
private static void WriteUInt64(FakeCpuMemory memory, ulong address, ulong value)
|
||||
{
|
||||
Span<byte> buffer = stackalloc byte[sizeof(ulong)];
|
||||
BinaryPrimitives.WriteUInt64LittleEndian(buffer, value);
|
||||
Assert.True(memory.TryWrite(address, buffer));
|
||||
}
|
||||
|
||||
private static byte ReadByte(FakeCpuMemory memory, ulong address)
|
||||
{
|
||||
Span<byte> buffer = stackalloc byte[1];
|
||||
Assert.True(memory.TryRead(address, buffer));
|
||||
return buffer[0];
|
||||
}
|
||||
|
||||
private static uint ReadUInt32(FakeCpuMemory memory, ulong address)
|
||||
{
|
||||
Span<byte> buffer = stackalloc byte[sizeof(uint)];
|
||||
Assert.True(memory.TryRead(address, buffer));
|
||||
return BinaryPrimitives.ReadUInt32LittleEndian(buffer);
|
||||
}
|
||||
|
||||
private static ulong ReadUInt64(FakeCpuMemory memory, ulong address)
|
||||
{
|
||||
Span<byte> buffer = stackalloc byte[sizeof(ulong)];
|
||||
Assert.True(memory.TryRead(address, buffer));
|
||||
return BinaryPrimitives.ReadUInt64LittleEndian(buffer);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using System.Buffers.Binary;
|
||||
using SharpEmu.HLE;
|
||||
using SharpEmu.Libs.Agc;
|
||||
using Xunit;
|
||||
|
||||
namespace SharpEmu.Libs.Tests.Agc;
|
||||
|
||||
public sealed class AgcPrimStateHullVariantTests
|
||||
{
|
||||
private const ulong BaseAddress = 0x1_0000_0000;
|
||||
private const ulong CxRegistersAddress = BaseAddress + 0x100;
|
||||
private const ulong UcRegistersAddress = BaseAddress + 0x200;
|
||||
private const ulong HullStateAddress = BaseAddress + 0x300;
|
||||
private const ulong GeometryShaderAddress = BaseAddress + 0x400;
|
||||
private const ulong SpecialsAddress = BaseAddress + 0x500;
|
||||
|
||||
// Tessellation pipelines pass a non-null hull-state block; the
|
||||
// geometry-derived register writes must still happen instead of an
|
||||
// INVALID_ARGUMENT that leaves the caller's register storage as garbage.
|
||||
[Fact]
|
||||
public void CreatePrimState_AcceptsHullStateBlock()
|
||||
{
|
||||
var memory = new FakeCpuMemory(BaseAddress, 0x1000);
|
||||
var ctx = new CpuContext(memory, Generation.Gen5);
|
||||
|
||||
memory.TryWrite(GeometryShaderAddress + 0x5A, new byte[] { 2 });
|
||||
WriteUInt64(memory, GeometryShaderAddress + 0x28, SpecialsAddress);
|
||||
|
||||
// Specials: {register, value} pairs at GeCntl 0x00, StagesEn 0x08,
|
||||
// GsOutPrimType 0x20, GeUserVgprEn 0x28.
|
||||
WriteUInt64(memory, SpecialsAddress + 0x00, 0x0000_0111_0000_0222UL);
|
||||
WriteUInt64(memory, SpecialsAddress + 0x08, 0x0000_0333_0000_0444UL);
|
||||
WriteUInt64(memory, SpecialsAddress + 0x20, 0x0000_0555_0000_0666UL);
|
||||
WriteUInt64(memory, SpecialsAddress + 0x28, 0x0000_0777_0000_0888UL);
|
||||
|
||||
ctx[CpuRegister.Rdi] = CxRegistersAddress;
|
||||
ctx[CpuRegister.Rsi] = UcRegistersAddress;
|
||||
ctx[CpuRegister.Rdx] = HullStateAddress;
|
||||
ctx[CpuRegister.Rcx] = GeometryShaderAddress;
|
||||
ctx[CpuRegister.R8] = 0x11;
|
||||
|
||||
Assert.Equal(
|
||||
(int)OrbisGen2Result.ORBIS_GEN2_OK,
|
||||
AgcExports.CreatePrimState(ctx));
|
||||
|
||||
Assert.NotEqual(0u, ReadUInt32(memory, CxRegistersAddress));
|
||||
Assert.Equal(0x11u, ReadUInt32(memory, UcRegistersAddress + 20));
|
||||
}
|
||||
|
||||
private static void WriteUInt64(FakeCpuMemory memory, ulong address, ulong value)
|
||||
{
|
||||
Span<byte> bytes = stackalloc byte[sizeof(ulong)];
|
||||
BinaryPrimitives.WriteUInt64LittleEndian(bytes, value);
|
||||
Assert.True(memory.TryWrite(address, bytes));
|
||||
}
|
||||
|
||||
private static uint ReadUInt32(FakeCpuMemory memory, ulong address)
|
||||
{
|
||||
Span<byte> value = stackalloc byte[sizeof(uint)];
|
||||
Assert.True(memory.TryRead(address, value));
|
||||
return BinaryPrimitives.ReadUInt32LittleEndian(value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using System.Buffers.Binary;
|
||||
using SharpEmu.Libs.Agc;
|
||||
using Xunit;
|
||||
|
||||
namespace SharpEmu.Libs.Tests.Agc;
|
||||
|
||||
/// <summary>
|
||||
/// Regression coverage for the AGC UI path: index8 expansion and rect-list
|
||||
/// vertex counts / topology selection.
|
||||
/// </summary>
|
||||
public sealed class AgcRectListIndexHelpersTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(0u, 0u, 2)] // Index16
|
||||
[InlineData(1u, 1u, 4)] // Index32
|
||||
[InlineData(2u, 2u, 1)] // Index8
|
||||
[InlineData(0x402u, 2u, 1)] // UC 0x400|size -> Index8
|
||||
public void IndexType_DecodeAndStride_MatchProspero(uint raw, uint expected, int stride)
|
||||
{
|
||||
var decoded = AgcIndexHelpers.Decode(raw);
|
||||
Assert.Equal((AgcIndexHelpers.ProsperoIndexType)expected, decoded);
|
||||
Assert.Equal(stride, AgcIndexHelpers.GetGuestStrideBytes(decoded));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ExpandIndex8ToU16_PreservesValues()
|
||||
{
|
||||
ReadOnlySpan<byte> source = [0x00, 0x01, 0xFF, 0x7F];
|
||||
Span<byte> destination = stackalloc byte[8];
|
||||
AgcIndexHelpers.ExpandIndex8ToU16(source, destination);
|
||||
Assert.Equal(0, BinaryPrimitives.ReadUInt16LittleEndian(destination[..2]));
|
||||
Assert.Equal(1, BinaryPrimitives.ReadUInt16LittleEndian(destination.Slice(2, 2)));
|
||||
Assert.Equal(255, BinaryPrimitives.ReadUInt16LittleEndian(destination.Slice(4, 2)));
|
||||
Assert.Equal(127, BinaryPrimitives.ReadUInt16LittleEndian(destination.Slice(6, 2)));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
// NGG single-rect UI (DualSense): expand even when VBs are present
|
||||
[InlineData(7u, 3u, false, true, 4u)]
|
||||
[InlineData(7u, 1u, false, false, 4u)]
|
||||
[InlineData(7u, 4u, false, true, 4u)]
|
||||
// Indexed / multi-vert auto: keep guest count (loading video)
|
||||
[InlineData(7u, 3u, true, false, 3u)]
|
||||
[InlineData(7u, 6u, false, true, 6u)]
|
||||
[InlineData(7u, 4u, true, true, 4u)]
|
||||
[InlineData(0x11u, 3u, false, false, 4u)]
|
||||
[InlineData(0x11u, 6u, false, false, 6u)]
|
||||
[InlineData(4u, 3u, false, false, 3u)]
|
||||
public void RectListDrawVertexCount_MatchesExpansion(
|
||||
uint primitiveType,
|
||||
uint vertexCount,
|
||||
bool indexed,
|
||||
bool hasVertexBuffers,
|
||||
uint expected)
|
||||
{
|
||||
Assert.Equal(
|
||||
expected,
|
||||
AgcPrimitiveHelpers.GetRectListDrawVertexCount(
|
||||
primitiveType,
|
||||
vertexCount,
|
||||
indexed,
|
||||
hasVertexBuffers));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(7u, false, 3u, true, true)]
|
||||
[InlineData(7u, false, 6u, true, false)]
|
||||
[InlineData(7u, true, 3u, false, false)]
|
||||
[InlineData(0x11u, false, 3u, true, true)]
|
||||
[InlineData(0x11u, true, 3u, false, false)]
|
||||
public void RectListTriangleStrip_MatchesGuards(
|
||||
uint primitiveType,
|
||||
bool indexed,
|
||||
uint vertexCount,
|
||||
bool hasVertexBuffers,
|
||||
bool expected) =>
|
||||
Assert.Equal(
|
||||
expected,
|
||||
AgcPrimitiveHelpers.ShouldDrawRectListAsTriangleStrip(
|
||||
primitiveType,
|
||||
indexed,
|
||||
vertexCount,
|
||||
hasVertexBuffers));
|
||||
|
||||
[Theory]
|
||||
[InlineData(7u, (uint)AgcPrimitiveHelpers.GsOutputPrimitiveType.Rectangle2D)]
|
||||
[InlineData(0x11u, (uint)AgcPrimitiveHelpers.GsOutputPrimitiveType.RectList)]
|
||||
[InlineData(4u, (uint)AgcPrimitiveHelpers.GsOutputPrimitiveType.Triangles)]
|
||||
[InlineData(1u, (uint)AgcPrimitiveHelpers.GsOutputPrimitiveType.Points)]
|
||||
public void PrimitiveTypeToGsOut_MatchesProspero(uint primitiveType, uint expected) =>
|
||||
Assert.Equal(expected, AgcPrimitiveHelpers.PrimitiveTypeToGsOut(primitiveType));
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using System.Buffers.Binary;
|
||||
using SharpEmu.HLE;
|
||||
using SharpEmu.Libs.Agc;
|
||||
using SharpEmu.ShaderCompiler;
|
||||
using Xunit;
|
||||
|
||||
namespace SharpEmu.Libs.Tests.Agc;
|
||||
|
||||
/// <summary>
|
||||
/// Coverage for AGC attrib-table → BufferFormat merge and semantic indexing.
|
||||
/// </summary>
|
||||
public sealed class AgcVertexMetadataTests
|
||||
{
|
||||
[Fact]
|
||||
public void BuildVertexResources_UsesSemanticNotHardwareMappingAsAttribIndex()
|
||||
{
|
||||
// input_semantics[0]: semantic=1, hardware_mapping=4, size=2
|
||||
// If hardware_mapping were wrongly used as the attrib index, we'd read
|
||||
// attrib[4] instead of attrib[1] and get the wrong format/offset.
|
||||
const ulong memoryBase = 0x1_0000_0000;
|
||||
var memory = new FakeCpuMemory(memoryBase, 0x2000);
|
||||
var ctx = new CpuContext(memory, Generation.Gen5);
|
||||
|
||||
const ulong semanticsAddress = memoryBase + 0x100;
|
||||
const ulong attribTable = memoryBase + 0x200;
|
||||
const ulong bufferTable = memoryBase + 0x300;
|
||||
const ulong sharpBase = memoryBase + 0x800;
|
||||
|
||||
// ShaderSemantic word: semantic=1, hw_mapping=4, size_in_elements=2
|
||||
WriteUInt32(memory, semanticsAddress, 1u | (4u << 8) | (2u << 16));
|
||||
|
||||
// attrib[0] unused garbage
|
||||
WriteUInt32(memory, attribTable, 0xDEAD_BEEFu);
|
||||
// attrib[1]: buffer=0, format=k16_16Float(29), offset=8, fetch=0
|
||||
WriteUInt32(memory, attribTable + 4, 0u | (29u << 5) | (8u << 14));
|
||||
|
||||
// V# at buffer table[0]: base=sharpBase, stride=16
|
||||
WriteUInt32(memory, bufferTable, (uint)(sharpBase & 0xFFFF_FFFFUL));
|
||||
WriteUInt32(
|
||||
memory,
|
||||
bufferTable + 4,
|
||||
(uint)(sharpBase >> 32) | (16u << 16));
|
||||
|
||||
var scalars = new uint[32];
|
||||
scalars[8] = (uint)(attribTable & 0xFFFF_FFFFUL);
|
||||
scalars[9] = (uint)(attribTable >> 32);
|
||||
scalars[10] = (uint)(bufferTable & 0xFFFF_FFFFUL);
|
||||
scalars[11] = (uint)(bufferTable >> 32);
|
||||
|
||||
var tables = new AgcVertexMetadata.VertexTableRegisters(
|
||||
VertexBufferReg: 10,
|
||||
VertexAttribReg: 8,
|
||||
InputSemanticsCount: 1,
|
||||
InputSemanticsAddress: semanticsAddress);
|
||||
|
||||
Assert.True(
|
||||
AgcVertexMetadata.TryBuildVertexResourcesFromMetadata(
|
||||
ctx,
|
||||
scalars,
|
||||
tables,
|
||||
out var resources));
|
||||
Assert.Single(resources);
|
||||
Assert.Equal(1u, resources[0].Semantic);
|
||||
Assert.Equal(4u, resources[0].HardwareMapping);
|
||||
Assert.Equal(8u, resources[0].OffsetBytes);
|
||||
Assert.Equal(5u, resources[0].DataFormat); // R16G16
|
||||
Assert.Equal(7u, resources[0].NumberFormat); // Float
|
||||
Assert.Equal(2u, resources[0].ComponentCount);
|
||||
Assert.Equal(sharpBase, resources[0].SharpBase);
|
||||
Assert.False(resources[0].PerInstance);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MergeVertexInputs_OverlaysFormatWithoutRebasingCapture()
|
||||
{
|
||||
const ulong memoryBase = 0x1_0000_0000;
|
||||
var memory = new FakeCpuMemory(memoryBase, 0x2000);
|
||||
var ctx = new CpuContext(memory, Generation.Gen5);
|
||||
|
||||
const ulong semanticsAddress = memoryBase + 0x100;
|
||||
const ulong attribTable = memoryBase + 0x200;
|
||||
const ulong bufferTable = memoryBase + 0x300;
|
||||
const ulong sharpBase = memoryBase + 0x800;
|
||||
|
||||
WriteUInt32(memory, semanticsAddress, 0u | (0u << 8) | (4u << 16));
|
||||
// format k8_8_8_8UNorm(56), offset=12
|
||||
WriteUInt32(memory, attribTable, 0u | (56u << 5) | (12u << 14));
|
||||
WriteUInt32(memory, bufferTable, (uint)(sharpBase & 0xFFFF_FFFFUL));
|
||||
WriteUInt32(memory, bufferTable + 4, (uint)(sharpBase >> 32) | (16u << 16));
|
||||
|
||||
var scalars = new uint[32];
|
||||
scalars[4] = (uint)(attribTable & 0xFFFF_FFFFUL);
|
||||
scalars[5] = (uint)(attribTable >> 32);
|
||||
scalars[6] = (uint)(bufferTable & 0xFFFF_FFFFUL);
|
||||
scalars[7] = (uint)(bufferTable >> 32);
|
||||
|
||||
var tables = new AgcVertexMetadata.VertexTableRegisters(
|
||||
VertexBufferReg: 6,
|
||||
VertexAttribReg: 4,
|
||||
InputSemanticsCount: 1,
|
||||
InputSemanticsAddress: semanticsAddress);
|
||||
|
||||
var data = new byte[64];
|
||||
var discovered = new[]
|
||||
{
|
||||
new Gen5VertexInputBinding(
|
||||
Pc: 0x40,
|
||||
Location: 0,
|
||||
ComponentCount: 4,
|
||||
DataFormat: 14, // wrong IR guess
|
||||
NumberFormat: 7,
|
||||
BaseAddress: sharpBase,
|
||||
Stride: 16,
|
||||
OffsetBytes: 0,
|
||||
Data: data,
|
||||
DataLength: data.Length,
|
||||
DataPooled: false),
|
||||
};
|
||||
|
||||
var merged = AgcVertexMetadata.MergeVertexInputsFromMetadata(
|
||||
ctx,
|
||||
scalars,
|
||||
tables,
|
||||
discovered);
|
||||
Assert.Single(merged);
|
||||
Assert.Equal(0u, merged[0].Location);
|
||||
Assert.Equal(sharpBase, merged[0].BaseAddress);
|
||||
Assert.Same(data, merged[0].Data);
|
||||
Assert.Equal(10u, merged[0].DataFormat); // RGBA8
|
||||
Assert.Equal(0u, merged[0].NumberFormat); // Unorm
|
||||
Assert.Equal(12u, merged[0].OffsetBytes);
|
||||
Assert.Equal(0x40u, merged[0].Pc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MergeVertexInputs_AcceptsVertexAttribFormatEnums()
|
||||
{
|
||||
// Attrib tables store VertexAttribFormat (227 = rgba8 unorm), not
|
||||
// BufferFormat (56). Without conversion the format patch is a no-op.
|
||||
const ulong memoryBase = 0x1_0000_0000;
|
||||
var memory = new FakeCpuMemory(memoryBase, 0x2000);
|
||||
var ctx = new CpuContext(memory, Generation.Gen5);
|
||||
|
||||
const ulong semanticsAddress = memoryBase + 0x100;
|
||||
const ulong attribTable = memoryBase + 0x200;
|
||||
const ulong bufferTable = memoryBase + 0x300;
|
||||
const ulong sharpBase = memoryBase + 0x800;
|
||||
|
||||
WriteUInt32(memory, semanticsAddress, 0u | (0u << 8) | (4u << 16));
|
||||
WriteUInt32(memory, attribTable, 0u | (227u << 5) | (12u << 14)); // VertexAttribFormat
|
||||
WriteUInt32(memory, bufferTable, (uint)(sharpBase & 0xFFFF_FFFFUL));
|
||||
WriteUInt32(memory, bufferTable + 4, (uint)(sharpBase >> 32) | (16u << 16));
|
||||
|
||||
var scalars = new uint[32];
|
||||
scalars[4] = (uint)(attribTable & 0xFFFF_FFFFUL);
|
||||
scalars[5] = (uint)(attribTable >> 32);
|
||||
scalars[6] = (uint)(bufferTable & 0xFFFF_FFFFUL);
|
||||
scalars[7] = (uint)(bufferTable >> 32);
|
||||
|
||||
var tables = new AgcVertexMetadata.VertexTableRegisters(
|
||||
VertexBufferReg: 6,
|
||||
VertexAttribReg: 4,
|
||||
InputSemanticsCount: 1,
|
||||
InputSemanticsAddress: semanticsAddress);
|
||||
|
||||
var data = new byte[64];
|
||||
var discovered = new[]
|
||||
{
|
||||
new Gen5VertexInputBinding(
|
||||
0x40, 0, 4, 14, 7, sharpBase, 16, 12, data, data.Length, false),
|
||||
};
|
||||
|
||||
var merged = AgcVertexMetadata.MergeVertexInputsFromMetadata(
|
||||
ctx,
|
||||
scalars,
|
||||
tables,
|
||||
discovered);
|
||||
Assert.Equal(10u, merged[0].DataFormat);
|
||||
Assert.Equal(0u, merged[0].NumberFormat);
|
||||
Assert.Equal(12u, merged[0].OffsetBytes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MergeVertexInputs_MatchesInterleavedAttrsByOffsetNotBareBase()
|
||||
{
|
||||
// Both attributes share SharpBase. Matching by base alone would assign
|
||||
// the color format to position (video/UI regression).
|
||||
const ulong memoryBase = 0x1_0000_0000;
|
||||
var memory = new FakeCpuMemory(memoryBase, 0x2000);
|
||||
var ctx = new CpuContext(memory, Generation.Gen5);
|
||||
|
||||
const ulong semanticsAddress = memoryBase + 0x100;
|
||||
const ulong attribTable = memoryBase + 0x200;
|
||||
const ulong bufferTable = memoryBase + 0x300;
|
||||
const ulong sharpBase = memoryBase + 0x800;
|
||||
|
||||
// semantic0 → pos float4 @0; semantic1 → color rgba8 @12
|
||||
WriteUInt32(memory, semanticsAddress, 0u | (0u << 8) | (4u << 16));
|
||||
WriteUInt32(memory, semanticsAddress + 4, 1u | (4u << 8) | (4u << 16));
|
||||
WriteUInt32(memory, attribTable, 0u | (77u << 5) | (0u << 14)); // k32_32_32_32Float
|
||||
WriteUInt32(memory, attribTable + 4, 0u | (56u << 5) | (12u << 14)); // rgba8unorm @12
|
||||
WriteUInt32(memory, bufferTable, (uint)(sharpBase & 0xFFFF_FFFFUL));
|
||||
WriteUInt32(memory, bufferTable + 4, (uint)(sharpBase >> 32) | (16u << 16));
|
||||
|
||||
var scalars = new uint[32];
|
||||
scalars[4] = (uint)(attribTable & 0xFFFF_FFFFUL);
|
||||
scalars[5] = (uint)(attribTable >> 32);
|
||||
scalars[6] = (uint)(bufferTable & 0xFFFF_FFFFUL);
|
||||
scalars[7] = (uint)(bufferTable >> 32);
|
||||
|
||||
var tables = new AgcVertexMetadata.VertexTableRegisters(
|
||||
VertexBufferReg: 6,
|
||||
VertexAttribReg: 4,
|
||||
InputSemanticsCount: 2,
|
||||
InputSemanticsAddress: semanticsAddress);
|
||||
|
||||
var data = new byte[64];
|
||||
var discovered = new[]
|
||||
{
|
||||
new Gen5VertexInputBinding(
|
||||
0x40, 0, 4, 14, 7, sharpBase, 16, 0, data, data.Length, false),
|
||||
new Gen5VertexInputBinding(
|
||||
0x80, 1, 4, 14, 7, sharpBase, 16, 12, data, data.Length, false),
|
||||
};
|
||||
|
||||
var merged = AgcVertexMetadata.MergeVertexInputsFromMetadata(
|
||||
ctx,
|
||||
scalars,
|
||||
tables,
|
||||
discovered);
|
||||
Assert.Equal(2, merged.Count);
|
||||
Assert.Equal(0u, merged[0].OffsetBytes);
|
||||
Assert.Equal(12u, merged[1].OffsetBytes);
|
||||
Assert.Equal(0u, merged[1].NumberFormat); // Unorm color, not float
|
||||
Assert.Equal(10u, merged[1].DataFormat); // RGBA8
|
||||
Assert.Equal(sharpBase, merged[0].BaseAddress);
|
||||
Assert.Equal(sharpBase, merged[1].BaseAddress);
|
||||
Assert.Same(data, merged[0].Data);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CollectFetchPrologPcs_FindsSBufferLoadsFromTableRegisters()
|
||||
{
|
||||
var tables = new AgcVertexMetadata.VertexTableRegisters(
|
||||
VertexBufferReg: 10,
|
||||
VertexAttribReg: 8,
|
||||
InputSemanticsCount: 1,
|
||||
InputSemanticsAddress: 1);
|
||||
|
||||
var program = new Gen5ShaderProgram(
|
||||
0,
|
||||
[
|
||||
new Gen5ShaderInstruction(
|
||||
0x10,
|
||||
Gen5ShaderEncoding.Smem,
|
||||
"SBufferLoadDword",
|
||||
Words: [],
|
||||
Sources: [Gen5Operand.Scalar(8)],
|
||||
Destinations: [Gen5Operand.Scalar(20)],
|
||||
new Gen5ScalarMemoryControl(1, 0, null)),
|
||||
new Gen5ShaderInstruction(
|
||||
0x20,
|
||||
Gen5ShaderEncoding.Smem,
|
||||
"SBufferLoadDword",
|
||||
Words: [],
|
||||
Sources: [Gen5Operand.Scalar(12)],
|
||||
Destinations: [Gen5Operand.Scalar(24)],
|
||||
new Gen5ScalarMemoryControl(1, 0, null)),
|
||||
new Gen5ShaderInstruction(
|
||||
0x30,
|
||||
Gen5ShaderEncoding.Sopp,
|
||||
"SEndpgm",
|
||||
Words: [],
|
||||
Sources: [],
|
||||
Destinations: [],
|
||||
null),
|
||||
]);
|
||||
|
||||
var pcs = AgcVertexMetadata.CollectFetchPrologPcs(program, tables);
|
||||
Assert.Contains(0x10u, pcs);
|
||||
Assert.DoesNotContain(0x20u, pcs);
|
||||
}
|
||||
|
||||
private static void WriteUInt32(FakeCpuMemory memory, ulong address, uint value)
|
||||
{
|
||||
Span<byte> bytes = stackalloc byte[4];
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(bytes, value);
|
||||
Assert.True(memory.TryWrite(address, bytes));
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ using Xunit;
|
||||
|
||||
namespace SharpEmu.Libs.Tests.Agc;
|
||||
|
||||
// TryDetile's exact-XOR fast path (PS5 swizzle modes 5/9/24/27) factors the
|
||||
// TryDetile's exact-XOR fast path (PS5 swizzle modes 1/5/9/24/27) factors the
|
||||
// AddrLib bit-interleave into independent per-column X and per-row Y terms so
|
||||
// the inner loop is one array load and one XOR instead of a 16-bit interleave.
|
||||
// These tests pin that the factored output stays byte-identical to the direct
|
||||
@@ -84,6 +84,50 @@ public sealed class GnmTilingDetileTests
|
||||
}
|
||||
}
|
||||
|
||||
// Gen5 Standard256B (mode 1) uses the 8-bit AddrLib S equation, not the
|
||||
// generic StandardSwizzle bit-interleave. Pin that TryDetile recovers a
|
||||
// known linear fill placed with that equation.
|
||||
private static readonly (uint XMask, uint YMask)[] Standard256_1Bpp =
|
||||
[
|
||||
(1u << 0, 0), (1u << 1, 0), (1u << 2, 0), (1u << 3, 0),
|
||||
(0, 1u << 0), (0, 1u << 1), (0, 1u << 2), (0, 1u << 3),
|
||||
];
|
||||
|
||||
[Theory]
|
||||
[InlineData(32, 32)]
|
||||
[InlineData(64, 48)]
|
||||
public void TryDetile_ExactXorMode1_MatchesReferenceAddressEquation(
|
||||
int elementsWide,
|
||||
int elementsHigh)
|
||||
{
|
||||
const uint swizzleMode = 1; // Standard256B
|
||||
const int bytesPerElement = 1;
|
||||
const int blockBytes = 256;
|
||||
const int blockWidth = 16;
|
||||
const int blockHeight = 16;
|
||||
var blocksPerRow = (elementsWide + blockWidth - 1) / blockWidth;
|
||||
var blocksPerColumn = (elementsHigh + blockHeight - 1) / blockHeight;
|
||||
|
||||
var tiled = new byte[blocksPerRow * blocksPerColumn * blockBytes];
|
||||
for (var y = 0; y < elementsHigh; y++)
|
||||
{
|
||||
for (var x = 0; x < elementsWide; x++)
|
||||
{
|
||||
var blockIndex = (long)(y / blockHeight) * blocksPerRow + (x / blockWidth);
|
||||
var sourceByte = (int)(blockIndex * blockBytes +
|
||||
ReferenceOffset((uint)x, (uint)y, Standard256_1Bpp));
|
||||
tiled[sourceByte] = (byte)(y * elementsWide + x);
|
||||
}
|
||||
}
|
||||
|
||||
var linear = new byte[elementsWide * elementsHigh * bytesPerElement];
|
||||
Assert.True(GnmTiling.TryDetile(tiled, linear, swizzleMode, elementsWide, elementsHigh, bytesPerElement));
|
||||
for (var i = 0; i < elementsWide * elementsHigh; i++)
|
||||
{
|
||||
Assert.Equal((byte)i, linear[i]);
|
||||
}
|
||||
}
|
||||
|
||||
// GetDetileParams must reproduce TryDetile bit-for-bit: the CPU fallback and
|
||||
// the GPU compute kernel both consume these params, so a detile driven purely
|
||||
// by DetileParams (the shared addressing formula the kernel runs) must equal
|
||||
@@ -94,8 +138,8 @@ public sealed class GnmTilingDetileTests
|
||||
[InlineData(9u, 4, 300, 300)] // 64 KiB standard (exact-XOR)
|
||||
[InlineData(24u, 4, 128, 256)] // 64 KiB RB+ Z_X (exact-XOR)
|
||||
[InlineData(5u, 4, 200, 120)] // 4 KiB standard (exact-XOR)
|
||||
[InlineData(1u, 4, 64, 64)] // 256 B standard (exact-XOR)
|
||||
[InlineData(8u, 4, 128, 128)] // 64 KiB Z (block-table path)
|
||||
[InlineData(1u, 4, 64, 64)] // 256 B standard (block-table path)
|
||||
public void GetDetileParams_ReproducesTryDetile(uint mode, int bpp, int w, int h)
|
||||
{
|
||||
var p = GnmTiling.GetDetileParams(mode, bpp, w, h);
|
||||
|
||||
@@ -105,6 +105,92 @@ public sealed class AprStreamingContractTests
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResolveFilepathsWithPrefixToIdsAndFileSizes_CombinesPrefixAndResolvesRealFile()
|
||||
{
|
||||
// Resource streamers call WithPrefix to join a directory prefix with a
|
||||
// relative asset path. Without HLE every call returned NOT_FOUND and no
|
||||
// asset received a real file id/size.
|
||||
const ulong memoryBase = 0x1_0000_0000;
|
||||
const ulong prefixAddress = memoryBase + 0x80;
|
||||
const ulong pathListAddress = memoryBase + 0x100;
|
||||
const ulong pathAddress = memoryBase + 0x200;
|
||||
const ulong idsAddress = memoryBase + 0x800;
|
||||
const ulong sizesAddress = memoryBase + 0x880;
|
||||
byte[] fileContents = [1, 2, 3, 4, 5, 6];
|
||||
var mountRoot = Path.Combine(
|
||||
Path.GetTempPath(),
|
||||
$"sharpemu-apr-prefix-{Guid.NewGuid():N}");
|
||||
Directory.CreateDirectory(mountRoot);
|
||||
var mountPoint = $"/sharpemu_apr_prefix_mnt_{Guid.NewGuid():N}";
|
||||
const string fileName = "asset.bin";
|
||||
var hostPath = Path.Combine(mountRoot, fileName);
|
||||
|
||||
try
|
||||
{
|
||||
File.WriteAllBytes(hostPath, fileContents);
|
||||
KernelMemoryCompatExports.RegisterGuestPathMount(mountPoint, mountRoot);
|
||||
var memory = new FakeCpuMemory(memoryBase, 0x4000);
|
||||
var context = new CpuContext(memory, Generation.Gen5);
|
||||
memory.WriteCString(prefixAddress, mountPoint);
|
||||
memory.WriteCString(pathAddress, fileName);
|
||||
WriteUInt64(memory, pathListAddress, pathAddress);
|
||||
|
||||
context[CpuRegister.Rdi] = prefixAddress;
|
||||
context[CpuRegister.Rsi] = pathListAddress;
|
||||
context[CpuRegister.Rdx] = 1;
|
||||
context[CpuRegister.Rcx] = idsAddress;
|
||||
context[CpuRegister.R8] = sizesAddress;
|
||||
context[CpuRegister.R9] = 0;
|
||||
|
||||
Assert.Equal(
|
||||
(int)OrbisGen2Result.ORBIS_GEN2_OK,
|
||||
KernelMemoryCompatExports.KernelAprResolveFilepathsWithPrefixToIdsAndFileSizes(context));
|
||||
Assert.NotEqual(uint.MaxValue, ReadUInt32(memory, idsAddress));
|
||||
Assert.Equal((ulong)fileContents.Length, ReadUInt64(memory, sizesAddress));
|
||||
}
|
||||
finally
|
||||
{
|
||||
KernelMemoryCompatExports.UnregisterGuestPathMount(mountPoint);
|
||||
if (Directory.Exists(mountRoot))
|
||||
{
|
||||
Directory.Delete(mountRoot, recursive: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResolveFilepathsWithPrefixToIdsAndFileSizes_MissingFile_FailsFastWithErrorIndex()
|
||||
{
|
||||
const ulong memoryBase = 0x1_0000_0000;
|
||||
const ulong prefixAddress = memoryBase + 0x80;
|
||||
const ulong pathListAddress = memoryBase + 0x100;
|
||||
const ulong pathAddress = memoryBase + 0x200;
|
||||
const ulong idsAddress = memoryBase + 0x800;
|
||||
const ulong sizesAddress = memoryBase + 0x880;
|
||||
const ulong errorIndexAddress = memoryBase + 0x8F0;
|
||||
var memory = new FakeCpuMemory(memoryBase, 0x4000);
|
||||
var context = new CpuContext(memory, Generation.Gen5);
|
||||
memory.WriteCString(prefixAddress, "/does-not-exist-prefix");
|
||||
memory.WriteCString(pathAddress, $"missing-{Guid.NewGuid():N}.bin");
|
||||
WriteUInt64(memory, pathListAddress, pathAddress);
|
||||
|
||||
context[CpuRegister.Rdi] = prefixAddress;
|
||||
context[CpuRegister.Rsi] = pathListAddress;
|
||||
context[CpuRegister.Rdx] = 1;
|
||||
context[CpuRegister.Rcx] = idsAddress;
|
||||
context[CpuRegister.R8] = sizesAddress;
|
||||
context[CpuRegister.R9] = errorIndexAddress;
|
||||
|
||||
Assert.Equal(
|
||||
-1,
|
||||
KernelMemoryCompatExports.KernelAprResolveFilepathsWithPrefixToIdsAndFileSizes(context));
|
||||
Assert.Equal(ulong.MaxValue, context[CpuRegister.Rax]);
|
||||
Assert.Equal(uint.MaxValue, ReadUInt32(memory, idsAddress));
|
||||
Assert.Equal(0ul, ReadUInt64(memory, sizesAddress));
|
||||
Assert.Equal(0u, ReadUInt32(memory, errorIndexAddress));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResolveFilepathsToIdsAndFileSizes_MissingFile_FailsFastWithErrorIndex()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using System.Buffers.Binary;
|
||||
using SharpEmu.HLE;
|
||||
using SharpEmu.Libs.Audio;
|
||||
using Xunit;
|
||||
|
||||
namespace SharpEmu.Libs.Tests.Audio;
|
||||
|
||||
public sealed class AudioOut2PortGetStateExportsTests
|
||||
{
|
||||
private const ulong MemoryBase = 0x1_0000_0000;
|
||||
private const ulong StateAddress = MemoryBase + 0x100;
|
||||
|
||||
private static CpuContext CreateContext(out FakeCpuMemory memory)
|
||||
{
|
||||
memory = new FakeCpuMemory(MemoryBase, 0x1000);
|
||||
return new CpuContext(memory, Generation.Gen5);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PortGetState_WritesFixedSizeIgnoringPollutedR9()
|
||||
{
|
||||
var ctx = CreateContext(out var memory);
|
||||
// Paint the buffer so we can see the write footprint.
|
||||
Span<byte> paint = stackalloc byte[0x100];
|
||||
paint.Fill(0xAB);
|
||||
Assert.True(memory.TryWrite(StateAddress, paint));
|
||||
|
||||
ctx[CpuRegister.Rdi] = 0xDE1FF6800001UL;
|
||||
ctx[CpuRegister.Rsi] = StateAddress;
|
||||
ctx[CpuRegister.Rdx] = StateAddress + 0x200;
|
||||
// Polluted GetSize leftover — must NOT enlarge the write.
|
||||
ctx[CpuRegister.R9] = 0x180;
|
||||
|
||||
var result = AudioOut2Exports.AudioOut2PortGetState(ctx);
|
||||
|
||||
Assert.Equal(0, result);
|
||||
Span<byte> state = stackalloc byte[0x100];
|
||||
Assert.True(memory.TryRead(StateAddress, state));
|
||||
Assert.Equal(1, BinaryPrimitives.ReadUInt16LittleEndian(state));
|
||||
Assert.Equal(2, state[2]);
|
||||
// Bytes past the fixed 0x20 header must remain untouched.
|
||||
Assert.Equal(0xAB, state[0x20]);
|
||||
Assert.Equal(0xAB, state[0x7F]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PortGetState_SkipsGuestStackOutBuffer()
|
||||
{
|
||||
var ctx = CreateContext(out _);
|
||||
const ulong stackOut = 0x00007FFFDE1FF688UL;
|
||||
ctx[CpuRegister.Rdi] = 0xDE1FF688004DUL;
|
||||
ctx[CpuRegister.Rsi] = stackOut;
|
||||
ctx[CpuRegister.Rdx] = 0;
|
||||
|
||||
var result = AudioOut2Exports.AudioOut2PortGetState(ctx);
|
||||
|
||||
Assert.Equal(0, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSpeakerInfo_WritesFixedSizeToRdiNotRsiTypeFlag()
|
||||
{
|
||||
var ctx = CreateContext(out var memory);
|
||||
Span<byte> paint = stackalloc byte[0x80];
|
||||
paint.Fill(0xCD);
|
||||
Assert.True(memory.TryWrite(StateAddress, paint));
|
||||
|
||||
ctx[CpuRegister.Rdi] = StateAddress;
|
||||
ctx[CpuRegister.Rsi] = 1;
|
||||
ctx[CpuRegister.Rdx] = StateAddress + 0x200;
|
||||
ctx[CpuRegister.R8] = 0x840;
|
||||
ctx[CpuRegister.R9] = 0x10C;
|
||||
|
||||
var result = AudioOut2Exports.AudioOut2GetSpeakerInfo(ctx);
|
||||
|
||||
Assert.Equal(0, result);
|
||||
Span<byte> info = stackalloc byte[0x80];
|
||||
Assert.True(memory.TryRead(StateAddress, info));
|
||||
Assert.Equal(2u, BinaryPrimitives.ReadUInt32LittleEndian(info));
|
||||
Assert.Equal(48000u, BinaryPrimitives.ReadUInt32LittleEndian(info[4..]));
|
||||
Assert.Equal(0xCD, info[0x20]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using System.Buffers.Binary;
|
||||
using SharpEmu.HLE;
|
||||
using SharpEmu.Libs.Audio;
|
||||
using Xunit;
|
||||
|
||||
namespace SharpEmu.Libs.Tests.Audio;
|
||||
|
||||
public sealed class AudioOut2SpeakerArrayExportsTests
|
||||
{
|
||||
private const ulong MemoryBase = 0x1_0000_0000;
|
||||
private const ulong OutHandleAddress = MemoryBase + 0x100;
|
||||
private const ulong ReservedAddress = MemoryBase + 0x120;
|
||||
private const ulong ParamAddress = MemoryBase + 0x200;
|
||||
private const ulong SpeakerMemoryAddress = MemoryBase + 0x400;
|
||||
|
||||
private static CpuContext CreateContext(out FakeCpuMemory memory)
|
||||
{
|
||||
memory = new FakeCpuMemory(MemoryBase, 0x2000);
|
||||
return new CpuContext(memory, Generation.Gen5);
|
||||
}
|
||||
|
||||
private static void WriteU64(FakeCpuMemory memory, ulong address, ulong value)
|
||||
{
|
||||
Span<byte> bytes = stackalloc byte[8];
|
||||
BinaryPrimitives.WriteUInt64LittleEndian(bytes, value);
|
||||
Assert.True(memory.TryWrite(address, bytes));
|
||||
}
|
||||
|
||||
private static ulong ReadU64(FakeCpuMemory memory, ulong address)
|
||||
{
|
||||
Span<byte> bytes = stackalloc byte[8];
|
||||
Assert.True(memory.TryRead(address, bytes));
|
||||
return BinaryPrimitives.ReadUInt64LittleEndian(bytes);
|
||||
}
|
||||
|
||||
private static uint ReadU32(FakeCpuMemory memory, ulong address)
|
||||
{
|
||||
Span<byte> bytes = stackalloc byte[4];
|
||||
Assert.True(memory.TryRead(address, bytes));
|
||||
return BinaryPrimitives.ReadUInt32LittleEndian(bytes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSpeakerArrayMemorySize_NeverReturnsTheNotFoundSentinel()
|
||||
{
|
||||
var ctx = CreateContext(out _);
|
||||
ctx[CpuRegister.Rdi] = 8;
|
||||
|
||||
var result = AudioOut2Exports.AudioOut2GetSpeakerArrayMemorySize(ctx);
|
||||
|
||||
Assert.NotEqual((int)OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND, result);
|
||||
Assert.Equal(0x40 + 8 * 0x100 + 0x400, result);
|
||||
Assert.Equal((ulong)result, ctx[CpuRegister.Rax]);
|
||||
Assert.True(result < 0x10000);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSpeakerArrayMemorySize_TwoChannelsIsExactChannelScaledSize()
|
||||
{
|
||||
var ctx = CreateContext(out _);
|
||||
ctx[CpuRegister.Rdi] = 2;
|
||||
|
||||
var result = AudioOut2Exports.AudioOut2GetSpeakerArrayMemorySize(ctx);
|
||||
|
||||
Assert.Equal(0x40 + 2 * 0x100 + 0x400, result);
|
||||
Assert.Equal(0x640UL, ctx[CpuRegister.Rax]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SpeakerArrayCreate_PublishesObjectPointerAndLeavesReservedSizeAlone()
|
||||
{
|
||||
var ctx = CreateContext(out var memory);
|
||||
// Stage a size in the reserved slot the way callers do before Create.
|
||||
WriteU64(memory, ReservedAddress, 0x100);
|
||||
ctx[CpuRegister.Rdi] = ParamAddress;
|
||||
ctx[CpuRegister.Rsi] = OutHandleAddress;
|
||||
ctx[CpuRegister.Rdx] = ReservedAddress;
|
||||
ctx[CpuRegister.Rcx] = 2;
|
||||
|
||||
var result = AudioOut2Exports.AudioOut2SpeakerArrayCreate(ctx);
|
||||
|
||||
Assert.Equal(0, result);
|
||||
Assert.NotEqual(0UL, ctx[CpuRegister.Rax]);
|
||||
Assert.NotEqual(0x100UL, ctx[CpuRegister.Rax]);
|
||||
Assert.Equal(ctx[CpuRegister.Rax], ReadU64(memory, OutHandleAddress));
|
||||
// Reserved/size slot must remain untouched — writing it corrupted canaries.
|
||||
Assert.Equal(0x100UL, ReadU64(memory, ReservedAddress));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SpeakerArrayCreate_PublishesHandleForTypicalCallShape()
|
||||
{
|
||||
var ctx = CreateContext(out _);
|
||||
ctx[CpuRegister.Rdi] = ParamAddress;
|
||||
ctx[CpuRegister.Rsi] = OutHandleAddress;
|
||||
ctx[CpuRegister.Rdx] = ReservedAddress;
|
||||
ctx[CpuRegister.Rcx] = 2;
|
||||
|
||||
var result = AudioOut2Exports.AudioOut2SpeakerArrayCreate(ctx);
|
||||
|
||||
Assert.Equal(0, result);
|
||||
Assert.NotEqual(0UL, ctx[CpuRegister.Rax]);
|
||||
Assert.NotEqual(0x10000UL, ctx[CpuRegister.Rax]);
|
||||
Assert.NotEqual((int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SpeakerArrayCreate_IgnoresCorruptedParamBufferFields()
|
||||
{
|
||||
var ctx = CreateContext(out var memory);
|
||||
// Simulate PortGetState having overwritten param+0x18 (size) with a
|
||||
// state blob — Create must NOT adopt that as an in-place buffer.
|
||||
WriteU64(memory, ParamAddress + 0x10, SpeakerMemoryAddress);
|
||||
WriteU64(memory, ParamAddress + 0x18, 0x100);
|
||||
ctx[CpuRegister.Rdi] = ParamAddress;
|
||||
ctx[CpuRegister.Rsi] = OutHandleAddress;
|
||||
ctx[CpuRegister.Rdx] = ReservedAddress;
|
||||
ctx[CpuRegister.Rcx] = 2;
|
||||
|
||||
var result = AudioOut2Exports.AudioOut2SpeakerArrayCreate(ctx);
|
||||
|
||||
Assert.Equal(0, result);
|
||||
Assert.NotEqual(SpeakerMemoryAddress, ctx[CpuRegister.Rax]);
|
||||
Assert.NotEqual(0x100UL, ctx[CpuRegister.Rax]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SpeakerArrayDestroy_UnknownHandleStillSucceeds()
|
||||
{
|
||||
var ctx = CreateContext(out _);
|
||||
ctx[CpuRegister.Rdi] = 0xDEAD_BEEF;
|
||||
|
||||
var result = AudioOut2Exports.AudioOut2SpeakerArrayDestroy(ctx);
|
||||
|
||||
Assert.Equal(0, result);
|
||||
}
|
||||
}
|
||||
@@ -7,15 +7,18 @@ namespace SharpEmu.Libs.Tests;
|
||||
|
||||
// A single contiguous guest region backed by a byte[]. Enough to hand C strings and small
|
||||
// structures to HLE exports under test without a live guest.
|
||||
internal sealed class FakeCpuMemory : ICpuMemory
|
||||
internal sealed class FakeCpuMemory : ICpuMemory, IGuestMemoryAllocator
|
||||
{
|
||||
private readonly ulong _base;
|
||||
private readonly byte[] _storage;
|
||||
private ulong _allocBump;
|
||||
|
||||
public FakeCpuMemory(ulong baseAddress, int size)
|
||||
{
|
||||
_base = baseAddress;
|
||||
_storage = new byte[size];
|
||||
// Bump from the top so test fixtures at low offsets stay intact.
|
||||
_allocBump = baseAddress + (ulong)size;
|
||||
}
|
||||
|
||||
public bool TryRead(ulong virtualAddress, Span<byte> destination)
|
||||
@@ -40,6 +43,33 @@ internal sealed class FakeCpuMemory : ICpuMemory
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool TryAllocateGuestMemory(ulong size, ulong alignment, out ulong address)
|
||||
{
|
||||
address = 0;
|
||||
if (size == 0 || alignment == 0 || (alignment & (alignment - 1)) != 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var alignedSize = (size + alignment - 1) & ~(alignment - 1);
|
||||
if (alignedSize > _allocBump - _base)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var next = (_allocBump - alignedSize) & ~(alignment - 1);
|
||||
if (next < _base)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
_allocBump = next;
|
||||
address = next;
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool TryFreeGuestMemory(ulong address) => false;
|
||||
|
||||
public ulong WriteCString(ulong virtualAddress, string text)
|
||||
{
|
||||
var bytes = System.Text.Encoding.UTF8.GetBytes(text);
|
||||
|
||||
@@ -24,13 +24,53 @@ public sealed unsafe class GuestImageWriteTrackerTests
|
||||
// spilling onto neighbouring heap pages.
|
||||
private const nuint TrackedByteCount = 4096;
|
||||
private const nuint HostPageAlignment = 16384;
|
||||
private const uint MemCommit = 0x1000;
|
||||
private const uint MemReserve = 0x2000;
|
||||
private const uint MemRelease = 0x8000;
|
||||
private const uint PageReadWrite = 0x04;
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern nint VirtualAlloc(
|
||||
nint lpAddress,
|
||||
nuint dwSize,
|
||||
uint flAllocationType,
|
||||
uint flProtect);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern int VirtualFree(nint lpAddress, nuint dwSize, uint dwFreeType);
|
||||
|
||||
private static ulong AllocateTrackedPages(out void* allocation)
|
||||
{
|
||||
// VirtualProtect (Windows) / mprotect (POSIX) must target
|
||||
// VirtualAlloc/mmap pages. Protecting CRT heap pages poisons
|
||||
// neighbouring allocator metadata and crashes the test host.
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
var windowsAllocation = VirtualAlloc(
|
||||
0,
|
||||
HostPageAlignment,
|
||||
MemCommit | MemReserve,
|
||||
PageReadWrite);
|
||||
Assert.NotEqual(nint.Zero, windowsAllocation);
|
||||
allocation = (void*)windowsAllocation;
|
||||
return (ulong)windowsAllocation;
|
||||
}
|
||||
|
||||
allocation = NativeMemory.AlignedAlloc(2 * HostPageAlignment, HostPageAlignment);
|
||||
return (ulong)allocation;
|
||||
}
|
||||
|
||||
private static void FreeTrackedPages(void* allocation)
|
||||
{
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
_ = VirtualFree((nint)allocation, 0, MemRelease);
|
||||
return;
|
||||
}
|
||||
|
||||
NativeMemory.Free(allocation);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GenerationSurvivesDirtyConsume()
|
||||
{
|
||||
@@ -58,7 +98,7 @@ public sealed unsafe class GuestImageWriteTrackerTests
|
||||
finally
|
||||
{
|
||||
GuestImageWriteTracker.Untrack(address);
|
||||
NativeMemory.Free(allocation);
|
||||
FreeTrackedPages(allocation);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,7 +129,7 @@ public sealed unsafe class GuestImageWriteTrackerTests
|
||||
finally
|
||||
{
|
||||
GuestImageWriteTracker.Untrack(address);
|
||||
NativeMemory.Free(allocation);
|
||||
FreeTrackedPages(allocation);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,7 +158,7 @@ public sealed unsafe class GuestImageWriteTrackerTests
|
||||
finally
|
||||
{
|
||||
GuestImageWriteTracker.Untrack(address);
|
||||
NativeMemory.Free(allocation);
|
||||
FreeTrackedPages(allocation);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -132,4 +172,132 @@ public sealed unsafe class GuestImageWriteTrackerTests
|
||||
|
||||
Assert.False(GuestImageWriteTracker.TryGetWriteGeneration(0xDEAD_0000_0000UL, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WatchOnlyTrackDoesNotArmWriteProtection()
|
||||
{
|
||||
if (!GuestImageWriteTracker.Enabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var address = AllocateTrackedPages(out var allocation);
|
||||
try
|
||||
{
|
||||
GuestImageWriteTracker.Track(
|
||||
address,
|
||||
TrackedByteCount,
|
||||
source: "test.watch-only",
|
||||
protect: false);
|
||||
Assert.True(
|
||||
GuestImageWriteTracker.TryGetProtectionState(
|
||||
address,
|
||||
out var protect,
|
||||
out var armed));
|
||||
Assert.False(protect);
|
||||
Assert.False(armed);
|
||||
|
||||
// Pages stay writable: a native store must not require a fault handler.
|
||||
*(byte*)address = 0xAB;
|
||||
Assert.Equal(0xAB, *(byte*)address);
|
||||
}
|
||||
finally
|
||||
{
|
||||
GuestImageWriteTracker.Untrack(address);
|
||||
FreeTrackedPages(allocation);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WatchOnlyRangesAreExcludedFromManagedWriteSnapshot()
|
||||
{
|
||||
if (!GuestImageWriteTracker.Enabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var address = AllocateTrackedPages(out var allocation);
|
||||
try
|
||||
{
|
||||
GuestImageWriteTracker.Track(
|
||||
address,
|
||||
TrackedByteCount,
|
||||
source: "test.watch-only",
|
||||
protect: false);
|
||||
// Watch-only must not widen the NotifyManagedWrite hot path.
|
||||
GuestImageWriteTracker.NotifyManagedWrite(address, sizeof(uint));
|
||||
Assert.False(GuestImageWriteTracker.ConsumeDirty(address));
|
||||
Assert.True(
|
||||
GuestImageWriteTracker.TryGetProtectionState(
|
||||
address,
|
||||
out var protect,
|
||||
out var armed));
|
||||
Assert.False(protect);
|
||||
Assert.False(armed);
|
||||
}
|
||||
finally
|
||||
{
|
||||
GuestImageWriteTracker.Untrack(address);
|
||||
FreeTrackedPages(allocation);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ProtectedTrackArmsWriteProtection()
|
||||
{
|
||||
if (!GuestImageWriteTracker.Enabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var address = AllocateTrackedPages(out var allocation);
|
||||
try
|
||||
{
|
||||
GuestImageWriteTracker.Track(address, TrackedByteCount);
|
||||
Assert.True(
|
||||
GuestImageWriteTracker.TryGetProtectionState(
|
||||
address,
|
||||
out var protect,
|
||||
out var armed));
|
||||
Assert.True(protect);
|
||||
Assert.True(armed);
|
||||
}
|
||||
finally
|
||||
{
|
||||
GuestImageWriteTracker.Untrack(address);
|
||||
FreeTrackedPages(allocation);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WatchOnlyTrackDoesNotDowngradeProtectedRange()
|
||||
{
|
||||
if (!GuestImageWriteTracker.Enabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var address = AllocateTrackedPages(out var allocation);
|
||||
try
|
||||
{
|
||||
GuestImageWriteTracker.Track(address, TrackedByteCount, source: "test.rt");
|
||||
GuestImageWriteTracker.Track(
|
||||
address,
|
||||
TrackedByteCount,
|
||||
source: "test.texture-cache",
|
||||
protect: false);
|
||||
Assert.True(
|
||||
GuestImageWriteTracker.TryGetProtectionState(
|
||||
address,
|
||||
out var protect,
|
||||
out var armed));
|
||||
Assert.True(protect);
|
||||
Assert.True(armed);
|
||||
}
|
||||
finally
|
||||
{
|
||||
GuestImageWriteTracker.Untrack(address);
|
||||
FreeTrackedPages(allocation);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,7 +79,16 @@ public sealed class GuestMemoryAllocatorTests
|
||||
var pointer = memory.GetPointer(address + 0x123);
|
||||
|
||||
Assert.Equal(address + 0x123, (ulong)pointer);
|
||||
Assert.Equal([(address, pageSize, HostPageProtection.ReadWrite)], host.CommitCalls);
|
||||
// GetPointer commits a 32 MiB working-set chunk as 4 KiB pages against
|
||||
// this fake host (Query reports 4 KiB reserved regions). Non-page-
|
||||
// aligned start makes AlignUp(addr + chunk) cover one extra page.
|
||||
const ulong lazyPrimeChunkBytes = 0x0200_0000UL;
|
||||
var endPage = (address + 0x123 + lazyPrimeChunkBytes + pageSize - 1) & ~(pageSize - 1);
|
||||
Assert.Equal((int)((endPage - address) / pageSize), host.CommitCalls.Count);
|
||||
Assert.Equal((address, pageSize, HostPageProtection.ReadWrite), host.CommitCalls[0]);
|
||||
Assert.All(
|
||||
host.CommitCalls,
|
||||
call => Assert.Equal(pageSize, call.Size));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -9,9 +9,10 @@ using Xunit;
|
||||
namespace SharpEmu.Libs.Tests.Memory;
|
||||
|
||||
// PhysicalVirtualMemory is the host-backed (identity-mapped) implementation.
|
||||
// Reserve-only regions (> 4 GiB, non-executable) defer commit until first
|
||||
// access; TryAllocateGuestMemory serves a first-fit free-list with coalescing.
|
||||
// These tests pin that behaviour through fake IHostMemory implementations.
|
||||
// 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
|
||||
@@ -22,7 +23,8 @@ public sealed class PhysicalVirtualMemoryTests
|
||||
using var host = new LazyZeroedHostMemory();
|
||||
using var memory = new PhysicalVirtualMemory(host);
|
||||
|
||||
// > 4 GiB, non-executable -> reserve-only with lazy commit.
|
||||
// > 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);
|
||||
|
||||
@@ -108,8 +110,17 @@ public sealed class PhysicalVirtualMemoryTests
|
||||
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;
|
||||
Assert.Equal([(page, 0x1000UL, HostPageProtection.ReadWrite)], host.CommitCalls);
|
||||
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]
|
||||
@@ -187,7 +198,8 @@ public sealed class PhysicalVirtualMemoryTests
|
||||
|
||||
public int QueryCalls { get; private set; }
|
||||
|
||||
public ulong Allocate(ulong desiredAddress, ulong size, HostPageProtection protection) => _address;
|
||||
// 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;
|
||||
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using SharpEmu.HLE;
|
||||
using SharpEmu.Libs.Remoteplay;
|
||||
using Xunit;
|
||||
|
||||
namespace SharpEmu.Libs.Tests.Remoteplay;
|
||||
|
||||
public sealed class RemoteplayExportsTests
|
||||
{
|
||||
private const ulong MemoryBase = 0x1_0000_0000;
|
||||
private const ulong StatusAddress = MemoryBase + 0x100;
|
||||
|
||||
private static CpuContext CreateContext(out FakeCpuMemory memory)
|
||||
{
|
||||
memory = new FakeCpuMemory(MemoryBase, 0x1000);
|
||||
return new CpuContext(memory, Generation.Gen5);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Initialize_Succeeds()
|
||||
{
|
||||
var ctx = CreateContext(out _);
|
||||
|
||||
var result = RemoteplayExports.RemoteplayInitialize(ctx);
|
||||
|
||||
Assert.Equal(0, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetConnectionStatus_WritesDisconnectedStatus()
|
||||
{
|
||||
var ctx = CreateContext(out var memory);
|
||||
ctx[CpuRegister.Rdi] = 0x1000_0000;
|
||||
ctx[CpuRegister.Rsi] = StatusAddress;
|
||||
memory.TryWrite(StatusAddress, stackalloc byte[] { 0xFF, 0xFF, 0xFF, 0xFF });
|
||||
|
||||
var result = RemoteplayExports.RemoteplayGetConnectionStatus(ctx);
|
||||
|
||||
Assert.Equal(0, result);
|
||||
var status = new byte[4];
|
||||
Assert.True(ctx.Memory.TryRead(StatusAddress, status));
|
||||
Assert.Equal(0, status[0]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetConnectionStatus_NullOutPointerStillSucceeds()
|
||||
{
|
||||
var ctx = CreateContext(out _);
|
||||
ctx[CpuRegister.Rdi] = 0x1000_0000;
|
||||
ctx[CpuRegister.Rsi] = 0;
|
||||
|
||||
var result = RemoteplayExports.RemoteplayGetConnectionStatus(ctx);
|
||||
|
||||
Assert.Equal(0, result);
|
||||
}
|
||||
}
|
||||
@@ -56,4 +56,26 @@ public sealed class VulkanPresentEncodeFormatTests
|
||||
{
|
||||
Assert.False(VulkanVideoPresenter.IsLinearFloatPresentSource(sourceFormat));
|
||||
}
|
||||
|
||||
// GTA V Enhanced early G-buffer color targets observed as COMPAT failures
|
||||
// when missing from TryDecodeRenderTargetFormat (format=2 / format=11).
|
||||
[Theory]
|
||||
[InlineData(2u, 0u, Format.R16Unorm)]
|
||||
[InlineData(2u, 4u, Format.R16Uint)]
|
||||
[InlineData(2u, 7u, Format.R16Sfloat)]
|
||||
[InlineData(11u, 4u, Format.R32G32Uint)]
|
||||
[InlineData(11u, 5u, Format.R32G32Sint)]
|
||||
[InlineData(11u, 7u, Format.R32G32Sfloat)]
|
||||
public void TryDecodeRenderTargetFormat_DecodesGen5R16AndRg32(
|
||||
uint dataFormat,
|
||||
uint numberType,
|
||||
Format expected)
|
||||
{
|
||||
Assert.True(
|
||||
VulkanVideoPresenter.TryDecodeRenderTargetFormat(
|
||||
dataFormat,
|
||||
numberType,
|
||||
out var decoded));
|
||||
Assert.Equal(expected, decoded.Format);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user