Compare commits

..

13 Commits

Author SHA1 Message Date
José Luis Caravaca Carretero e604fb606d Fix pak size-collision that crashed Quake right after the intro demo (#187)
* [Tests] Add SharpEmu.Libs.Tests project

Introduce an xunit project for the HLE libs with a minimal ICpuMemory fake,
so library-level exports and helpers can be exercised without a live guest.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* [Ampr] Disambiguate pak size-collisions by read locality

PakDirectoryTracker resolves a sequential AMPR read (offset -1) back to an
absolute pak offset by matching the requested byte count against the PACK
directory. When several files share that byte count it took the first
unconsumed match in directory order, which mis-resolves out-of-order reads:
progs/h_ogre.mdl and bots/navigation/death32c.nav are both 0x3A34 bytes, and
death32c.nav sits earlier in the directory and is never read during Quake's
intro demo, so requesting h_ogre.mdl returned the nav file's bytes. The engine
then parsed "NAV2" as a brush model, failed the version check and aborted.

Pick the unconsumed same-size entry nearest the running read cursor instead.
id archives cluster related assets and the guest streams them with locality,
so this lands on the intended file; contiguous same-size runs (the
gfx/weapons/ww_*.lmp icons) still resolve in packed order.

Verified against a Quake dump: the abort is gone, h_ogre.mdl reads correctly,
and the intro demo reaches its main loop and renders instead of dying at the
error dialog.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-15 01:49:41 +03:00
José Luis Caravaca Carretero df53ff59d9 [Json] Implement sce::Json::Value and String (construct / set / destroy) (#169)
* [Json] Implement sce::Json::Value and Json::String construct/set/destroy

libSceJson previously only had the Initializer/MemAllocator setup path.
The Value and String classes themselves were entirely absent, so a
Prospero title that builds a JSON tree (Quake PPSA01880 does, to shape
a web-API request) hit unresolved imports and faulted on the call. The
imports it left unresolved right before its access violation are exactly
these Value ctors/setters and String ctor/dtor.

Model the Value/String payload host-side (JsonObjectHeap), keyed by the
guest `this` pointer, following the handle-shadow pattern already used
by Ngs2Exports. The guest object bytes are deliberately not written:
these objects are usually stack-allocated with an unknown real layout,
and writing a guessed layout risks smashing an adjacent stack canary
(the same hazard the AudioOut2 context-param note in this tree records).
Constructors and setters follow the Itanium ABI and return `this` in rax,
which is correct whether the real setter returns void or Value&.

Covered NIDs (complete-object C1/D1 variants, matching the observed
imports): Value(default/bool/long/ulong/double/ValueType/char*/String),
Value::~Value, Value::set(bool/long/ulong/double/ValueType/char*/String),
Value::clear, String(char*/default/copy), String::~String.

Only the payload the guest can reach through library methods is modelled;
direct guest reads of the object bytes are out of scope and would need
observed layout evidence.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* [Tests] Add SharpEmu.Libs.Tests covering the Json Value/String exports

First test project for SharpEmu.Libs (xunit), the SharpEmu.Libs.Tests
layout the maintainer already agreed to in issue #36.

- A FakeCpuMemory (single contiguous region) drives the exports at the
  CpuContext level with no live guest.
- Direct-call tests: ctor/setter round-trips for bool/int/uint/double
  (read from xmm0)/char*/String/ValueType, destructor cleanup, and the
  graceful-degradation paths (missing String shadow and a faulting char*
  pointer both fall back to the empty string instead of throwing).
- Registration test: a real ModuleManager scans SharpEmu.Libs and the
  nine NIDs Quake left unresolved now resolve to the libSceJson exports
  and dispatch cleanly (returns `this` in rax).

InternalsVisibleTo exposes JsonObjectHeap to the test assembly. The test
project's packages.lock.json is committed for CI locked-mode restore;
CI does not run tests yet, left as a maintainer decision.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* [Json] Add Initializer::setGlobalNullAccessCallback

Quake calls it during kexPSNWebAPI::Initialize and treats the
not-found error as fatal for the whole Np Web API bring-up. Store the
guest hook (never invoked by this HLE: shadows degrade to defaults
instead of dereferencing missing members) and return success.

Verified against the dump: the "setGlobalNullAccessCallback failed
(0x80020002)" line is gone and kexPSNWebAPI::Initialize now logs
"Np Web API Initialized"; the next blockers are sceNpAuthCreateRequest
and sceUserServiceInitialize ordering, outside libSceJson.

Also pins both Json test classes to one xunit collection: they share
JsonObjectHeap statics and parallel class execution raced ResetForTests
against a running test.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-15 01:49:33 +03:00
Randomuser8219 4c35831cb8 Add code -1073741819 as an emulation error (#188)
There's currently games that crash on this code due to emulation errors, so it'd make sense to add this error code as an emulation error.
2026-07-15 01:47:44 +03:00
miles 90fdd20f9a Create nl.json (#186) 2026-07-15 01:36:38 +03:00
Mike Saito ae5ef0abe7 Add SaveData transaction and NP UDS layout HLE stubs (#168)
* Add SaveData transaction and NP UDS layout HLE stubs

Wire Prepare, Commit, and Umount2 for implicit save transactions,
unregister guest mounts on Umount2, and add NP UDS CreateEvent,
DestroyEvent, and EventPropertyObjectSetString for layout-load imports.

* Add NP UDS SetArray and PostEvent layout HLE stubs

Add sceNpUniversalDataSystemEventPropertyObjectSetArray and
sceNpUniversalDataSystemPostEvent for layout-load imports on PPSA02929.
2026-07-15 01:34:59 +03:00
Mike Saito 5e2c21edf1 Fix historic SysAbi exports bound to wrong symbol names (#167)
Move KMcEa+rHsIo from libKernel MapMemory mislabel to sceAvPlayerAddSource.
Align WV1GwM32NgY ExportName with sceNpWebApi2PushEventCreateHandle. Behavior unchanged.
2026-07-15 01:34:27 +03:00
Deeptanshu Lal 3fb9d4db1c [Tools] Fix ShaderDump reflection invoke against new optional parameters (#166)
TryCompileVertexShader gained an optional scalarRegisterBufferIndex
parameter (#156), and reflection Invoke does not apply C# default
parameter values, so ShaderDump crashed with
TargetParameterCountException. Pad trailing optional parameters with
Type.Missing under BindingFlags.OptionalParamBinding so the declared
defaults are used; only a new required parameter now needs a tool
update, and that fails with a named error instead of a crash.

Verified: all five programs behave as expected (exit 0), all eight
emitted blobs pass spirv-val --target-env vulkan1.3.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-15 01:34:08 +03:00
José Luis Caravaca Carretero de13735972 [CommonDialog] Fix dialog state machine and add MsgDialog progress-bar exports (#163)
Rework the sceMsgDialog and sceSaveDataDialog HLE state machines so the full
Initialize -> Open -> poll -> GetResult -> Close/Terminate lifecycle honors the
common-dialog contract, and add the three missing sceMsgDialogProgressBar* exports.

- Fix an unreachable close path: sceSaveDataDialogClose already did a
  RUNNING -> FINISHED compare-exchange, but Open jumped straight to FINISHED, so
  RUNNING never existed and Close could only return NOT_RUNNING. Open now enters
  RUNNING and the first status poll advances it to FINISHED. Same model applied to
  sceMsgDialog.
- Return the real SCE_COMMON_DIALOG_ERROR_* codes (0x80B8xxxx) from sceMsgDialog*
  instead of emulator-internal result codes, with the missing argument/state guards
  (ARG_NULL, NOT_INITIALIZED, BUSY, NOT_FINISHED, NOT_RUNNING).
- GetResult reports buttonId = 1 (affirmative) instead of 0, the invalid sentinel a
  yes/no prompt could mis-branch on.
- Add sceMsgDialogProgressBarSetValue, sceMsgDialogProgressBarInc and
  sceMsgDialogProgressBarSetMsg (NIDs wTpfglkmv34, Gc5k1qcK4fs, 6H-71OdrpXM), gated
  on the service being initialized.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-15 01:33:48 +03:00
AlexC fc0efca297 Fixed deutch language file, it had invalid syntax (#162) 2026-07-15 01:31:54 +03:00
anesr5 2a9a261913 loader: support ps5 SELF and validate ELF signatures (#157)
Co-authored-by: anes <anesrachedi@outlook.fr>
2026-07-15 01:31:16 +03:00
Mike Saito 290f5fd3d7 Add SysAbi ExportName name2nid check script (#152)
* Add SysAbi ExportName name2nid check script

* Make SysAbi ExportName check green on tip with catalog skips and one Np rename
2026-07-15 01:29:23 +03:00
tensorcrush c06c70cad7 [Aerolib] Add ulobjmgr and NpEAAccess symbol names (#150)
Resolves _sceUlobjmgrRegisterObject (BG26hBGiNlw) and
_sceUlobjmgrUnregisterObject (Smf+fUNblPc), reported as unresolved by
testers, plus four sceNpEAAccess exports. Names taken from shadPS4's
NID tables and each verified by recomputing the NID with the repo's
name2nid derivation before inclusion. aerolib.bin regenerated with
scripts/generate_aerolib_binary.py.

Co-authored-by: tensorcrush <tensorcrush@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-15 01:28:17 +03:00
Deeptanshu Lal 5e54250752 [Tools] Add GPU conformance executor for dumped shader blobs (#127)
SharpEmu.Tools.GpuConformance executes the exec-cs.spv blob produced by
SharpEmu.Tools.ShaderDump on a real Vulkan device (preferring a discrete
GPU) and compares every word of the 64-byte storage buffer against
CPU-computed expectations, bit for bit. Creating the compute pipeline
doubles as a driver-acceptance check for SharpEmu's emitted SPIR-V.

The checks cover the three ALU results, the store attempted with EXEC=0
(its destination must keep the sentinel), the store after EXEC is
restored, and all trailing sentinel words. Any mismatch counts toward the
failure total and makes the tool exit non-zero.

Verified on an RTX 3060 Laptop GPU (NVIDIA) with all values matching, and
the failure path verified to exit 1 by running a non-storing blob.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-15 01:26:18 +03:00
31 changed files with 2262 additions and 74 deletions
+3
View File
@@ -12,11 +12,14 @@ SPDX-License-Identifier: GPL-2.0-or-later
<PackageVersion Include="Avalonia.Fonts.Inter" Version="11.3.18" />
<PackageVersion Include="Avalonia.Themes.Fluent" Version="11.3.18" />
<PackageVersion Include="Iced" Version="1.21.0" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageVersion Include="Silk.NET.Vulkan" Version="2.23.0" />
<PackageVersion Include="Silk.NET.Vulkan.Extensions.EXT" Version="2.23.0" />
<PackageVersion Include="Silk.NET.Vulkan.Extensions.KHR" Version="2.23.0" />
<PackageVersion Include="Silk.NET.Windowing" Version="2.23.0" />
<!-- Transitive of Avalonia.Desktop; pinned to fix GHSA-xrw6-gwf8-vvr9 -->
<PackageVersion Include="Tmds.DBus.Protocol" Version="0.21.3" />
<PackageVersion Include="xunit" Version="2.9.3" />
<PackageVersion Include="xunit.runner.visualstudio" Version="3.1.1" />
</ItemGroup>
</Project>
+3
View File
@@ -12,4 +12,7 @@ SPDX-License-Identifier: GPL-2.0-or-later
<Project Path="src/SharpEmu.Libs/SharpEmu.Libs.csproj" />
<Project Path="src/SharpEmu.Logging/SharpEmu.Logging.csproj" />
</Folder>
<Folder Name="/tests/">
<Project Path="tests/SharpEmu.Libs.Tests/SharpEmu.Libs.Tests.csproj" />
</Folder>
</Solution>
+172
View File
@@ -0,0 +1,172 @@
# Copyright (C) 2026 SharpEmu Emulator Project
# SPDX-License-Identifier: GPL-2.0-or-later
#!/usr/bin/env python3
"""Offline check: SysAbiExport ExportName must hash to its Nid (name2nid).
NIDs absent from aerolib.bin are skipped (unknown/unresolved symbols).
Known historic mislabels may be allowlisted with a one-line reason.
Run from the repository root:
python scripts/check_sysabi_aerolib.py
python scripts/check_sysabi_aerolib.py --strict
"""
from __future__ import annotations
import argparse
import hashlib
import re
import struct
import sys
from base64 import b64encode as base64enc
from binascii import unhexlify as uhx
from pathlib import Path
SRC_ROOT = Path("src")
AEROLIB_BIN = Path("src/SharpEmu.HLE/Aerolib/aerolib.bin")
SYSABI_EXPORT_RE = re.compile(r"\[SysAbiExport\((.*?)\)\]", re.DOTALL)
NID_RE = re.compile(r'Nid\s*=\s*"([^"]+)"')
EXPORT_NAME_RE = re.compile(r'ExportName\s*=\s*"([^"]+)"')
# NID -> reason. Keep minimal; fix ExportName when safe instead of growing this list.
ALLOWLISTED_NIDS: dict[str, str] = {
"KMcEa+rHsIo": "Historic kernel MapMemory stub bound to sceAvPlayerAddSource NID; API rewrite deferred.",
"WV1GwM32NgY": "Historic WebApi2 init alias for PushEventCreateHandle NID; ABI rewrite deferred.",
}
def name2nid(name: str) -> str:
symbol = hashlib.sha1(name.encode() + uhx("518D64A635DED8C1E6B039B1C3E55230")).digest()
id_val = struct.unpack("<Q", symbol[:8])[0]
nid = base64enc(uhx("%016x" % id_val), b"+-").rstrip(b"=")
return nid.decode("utf-8")
def find_repo_root() -> Path:
cwd = Path.cwd()
if (cwd / SRC_ROOT).is_dir() and (cwd / "scripts").is_dir():
return cwd
script_root = Path(__file__).resolve().parent.parent
if (script_root / SRC_ROOT).is_dir():
return script_root
raise SystemExit("Run from the repository root (src/ and scripts/ expected).")
def load_aerolib_nids(aerolib_path: Path) -> set[str]:
data = aerolib_path.read_bytes()
if len(data) < 4:
raise SystemExit(f"Aerolib binary too small: {aerolib_path}")
count = struct.unpack_from("<I", data, 0)[0]
offset = 4
nids: set[str] = set()
for _ in range(count):
if offset >= len(data):
raise SystemExit(f"Truncated aerolib.bin while reading NIDs: {aerolib_path}")
nid_len = data[offset]
offset += 1
nid = data[offset : offset + nid_len].decode("utf-8")
offset += nid_len
if offset + 2 > len(data):
raise SystemExit(f"Truncated aerolib.bin name length: {aerolib_path}")
name_len = struct.unpack_from("<H", data, offset)[0]
offset += 2 + name_len
nids.add(nid)
return nids
def iter_sysabi_exports(cs_path: Path, text: str):
for match in SYSABI_EXPORT_RE.finditer(text):
block = match.group(1)
nid_match = NID_RE.search(block)
export_match = EXPORT_NAME_RE.search(block)
if nid_match is None or export_match is None:
continue
nid = nid_match.group(1)
export_name = export_match.group(1)
nid_attr = f'Nid = "{nid}"'
abs_pos = text.find(nid_attr, match.start(), match.end())
if abs_pos < 0:
abs_pos = match.start()
line = text.count("\n", 0, abs_pos) + 1
yield cs_path, line, nid, export_name
def scan(src_root: Path, catalog_nids: set[str]):
checked = 0
mismatches = []
skipped_no_catalog = 0
allowlisted = 0
for cs_path in sorted(src_root.rglob("*.cs")):
text = cs_path.read_text(encoding="utf-8")
for path, line, nid, export_name in iter_sysabi_exports(cs_path, text):
checked += 1
computed = name2nid(export_name)
if computed == nid:
continue
if nid not in catalog_nids:
skipped_no_catalog += 1
continue
if nid in ALLOWLISTED_NIDS:
allowlisted += 1
continue
mismatches.append((path, line, nid, export_name, computed))
return checked, mismatches, skipped_no_catalog, allowlisted
def main() -> int:
parser = argparse.ArgumentParser(
description="Check that SysAbiExport ExportName values hash to their Nid via name2nid."
)
parser.add_argument(
"--strict",
action="store_true",
help="Exit 1 when any non-skipped/non-allowlisted ExportName does not hash to its Nid.",
)
parser.add_argument(
"--quiet",
action="store_true",
help="Print only the summary line.",
)
args = parser.parse_args()
repo_root = find_repo_root()
aerolib_path = repo_root / AEROLIB_BIN
if not aerolib_path.is_file():
raise SystemExit(f"Missing Aerolib catalog: {aerolib_path.as_posix()}")
catalog_nids = load_aerolib_nids(aerolib_path)
checked, mismatches, skipped_no_catalog, allowlisted = scan(
repo_root / SRC_ROOT, catalog_nids
)
ok = checked - len(mismatches) - skipped_no_catalog - allowlisted
if not args.quiet:
for path, line, nid, export_name, computed in mismatches:
rel = path.relative_to(repo_root).as_posix()
print(
f"{rel}:{line}: NID={nid} ExportName={export_name!r} "
f"computed={computed}"
)
print(
f"checked={checked} ok={ok} fail={len(mismatches)} "
f"skipped_no_catalog={skipped_no_catalog} allowlisted={allowlisted} "
f"allowlist_size={len(ALLOWLISTED_NIDS)}"
)
if args.strict and mismatches:
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
+6
View File
@@ -154449,3 +154449,9 @@ vector_str_substr
WTFAnnotateBenignRaceSized
WTFAnnotateHappensAfter
WTFAnnotateHappensBefore
_sceUlobjmgrRegisterObject
_sceUlobjmgrUnregisterObject
sceNpEAAccessInitialize
sceNpEAAccessTerminate
sceNpHasEAAccessSubscription
sceNpHasEAAccessSubscriptionAbortRequest
+19 -6
View File
@@ -17,7 +17,9 @@ namespace SharpEmu.Core.Loader;
public sealed class SelfLoader : ISelfLoader
{
private static readonly SharpEmuLogger Log = SharpEmuLog.For("Loader");
private const uint SelfMagic = 0x4F153D1D;
private const uint ElfMagic = 0x7F454C46;
private const uint Ps4SelfMagic = 0x4F153D1D;
private const uint Ps5SelfMagic = 0x5414F5EE;
private const ulong SelfSegmentFlag = 0x800;
private const int PageSize = 0x1000;
private const ulong ImportStubBaseAddress = 0x0000_7000_0000_0000UL;
@@ -323,7 +325,8 @@ public sealed class SelfLoader : ISelfLoader
throw new InvalidDataException("Input image is too small to contain an ELF header.");
}
if (imageData.Length >= sizeof(uint) && BinaryPrimitives.ReadUInt32BigEndian(imageData[..sizeof(uint)]) == SelfMagic)
var magic = BinaryPrimitives.ReadUInt32BigEndian(imageData[..sizeof(uint)]);
if (magic is Ps4SelfMagic or Ps5SelfMagic)
{
var selfHeader = ReadUnmanaged<SelfHeader>(imageData, 0);
if (!selfHeader.HasKnownLayout || selfHeader.Unknown != 0x22)
@@ -345,6 +348,12 @@ public sealed class SelfLoader : ISelfLoader
return new LoadContext(IsSelf: true, elfOffset, selfHeader.FileSize, segments);
}
if (magic != ElfMagic)
{
throw new InvalidDataException(
$"Unsupported executable signature 0x{magic:X8}");
}
return new LoadContext(IsSelf: false, ElfOffset: 0, SelfFileSize: 0, Array.Empty<SelfSegment>());
}
@@ -2380,10 +2389,14 @@ public sealed class SelfLoader : ISelfLoader
public ulong FileSize => _fileSize;
public bool HasKnownLayout =>
_ident0 == 0x4F &&
_ident1 == 0x15 &&
_ident2 == 0x3D &&
_ident3 == 0x1D &&
((_ident0 == 0x4F &&
_ident1 == 0x15 &&
_ident2 == 0x3D &&
_ident3 == 0x1D) ||
(_ident0 == 0x54 &&
_ident1 == 0x14 &&
_ident2 == 0xF5 &&
_ident3 == 0xEE)) &&
_ident4 == 0x00 &&
_ident5 == 0x01 &&
_ident6 == 0x01 &&
+2 -2
View File
@@ -20,7 +20,7 @@
"Library.Empty.Title": "Deine Bibliothek ist leer",
"Library.Empty.Hint": "Füge einen Ordner mit deinen Spielen hinzu, um zu beginnen.",
"Library.Empty.SearchTitle": "Keine Spiele gefunden",
"Library.Empty.SearchHint": "Nichts in der Bibliothek entspricht "{0}".",
"Library.Empty.SearchHint": "Nichts in der Bibliothek entspricht “{0}”.",
"Library.Empty.AddFolder": " Spielordner hinzufügen",
"Library.Loading": "Bibliothek wird geladen…",
@@ -109,7 +109,7 @@
"Status.LibraryScanned": "Bibliothek gescannt: {0} Spiel(e) in {1} Ordner(n).",
"Status.CouldNotOpenFolder": "Ordner konnte nicht geöffnet werden: {0}",
"Status.CopiedToClipboard": "{0} in die Zwischenablage kopiert.",
"Status.RemovedFromLibrary": ""{0}" wurde aus der Bibliothek entfernt. Füge den Ordner erneut hinzu, um es wiederherzustellen.",
"Status.RemovedFromLibrary": "“{0}” wurde aus der Bibliothek entfernt. Füge den Ordner erneut hinzu, um es wiederherzustellen.",
"Status.Running": "Läuft {0}",
"Status.Stopping": "Wird gestoppt…",
"Status.Idle": "Bereit",
+129
View File
@@ -0,0 +1,129 @@
{
"_languageName": "Nederlands",
"Page.Library": "Bibliotheek",
"Page.Options": "Opties",
"Page.GameCount.One": "1 game",
"Page.GameCount.Other": "{0} games",
"Library.SearchWatermark": "Zoeken in bibliotheek…",
"Library.AddFolder": " Map toevoegen",
"Library.Rescan": "⟳ Opnieuw scannen",
"Library.OpenFile": "Bestand openen…",
"Library.Context.Launch": "Starten",
"Library.Context.OpenFolder": "Gamemap openen",
"Library.Context.CopyPath": "Pad kopiëren",
"Library.Context.CopyTitleId": "Titel-ID kopiëren",
"Library.Context.Remove": "Verwijderen uit bibliotheek",
"Library.Empty.Title": "Je bibliotheek is leeg",
"Library.Empty.Hint": "Voeg een map met je games toe om te beginnen.",
"Library.Empty.SearchTitle": "Geen games komen overeen met je zoekopdracht",
"Library.Empty.SearchHint": "Niets in de bibliotheek komt overeen met “{0}”.",
"Library.Empty.AddFolder": " Gamemap toevoegen",
"Library.Loading": "Bibliotheek laden…",
"Options.General": "Algemeen",
"Options.Section.Emulation": "EMULATIE",
"Options.Section.Logging": "LOGGING",
"Options.Section.Launcher": "LAUNCHER",
"Options.CpuEngine.Label": "CPU-engine",
"Options.CpuEngine.Desc": "Engine die wordt gebruikt om gamecode uit te voeren.",
"Options.CpuEngine.Native": "Native",
"Options.Strict.Label": "Strikte dynlib-resolutie",
"Options.Strict.Desc": "Laat het opstarten mislukken wanneer een geïmporteerd symbool niet kan worden opgelost.",
"Options.LogLevel.Label": "Logniveau",
"Options.LogLevel.Desc": "Uitgebreidheid van de console-uitvoer van de emulator.",
"Options.LogLevel.Trace": "Trace",
"Options.LogLevel.Debug": "Debug",
"Options.LogLevel.Info": "Info",
"Options.LogLevel.Warning": "Waarschuwing",
"Options.LogLevel.Error": "Fout",
"Options.LogLevel.Critical": "Kritiek",
"Options.TraceImports.Label": "Tracelimiet voor imports",
"Options.TraceImports.Desc": "Traceer de eerste N imports per module (0 = uit).",
"Options.LogToFile.Label": "Loggen naar bestand",
"Options.LogToFile.Desc": "Stuur de uitvoer van de emulator ook naar een logbestand.",
"Options.LogFilePath.Label": "Pad naar logbestand",
"Options.LogFilePath.Default": "Geen aangepast pad — logs komen terecht in user/logs naast de emulator.",
"Options.LogFilePath.Select": "Selecteren…",
"Options.OverrideLogFile.Label": "Logbestand overschrijven",
"Options.OverrideLogFile.Desc": "Gebruik het exacte bestandspad in plaats van de titel-ID en tijdstempel toe te voegen.",
"Options.TitleMusic.Label": "Titelmuziek",
"Options.TitleMusic.Desc": "Herhaal de voorbeeldmuziek van de geselecteerde game in de bibliotheek.",
"Options.Discord.Label": "Discord-aanwezigheid",
"Options.Discord.Desc": "Toon de actieve game op je Discord-profiel.",
"Options.Language.Label": "Taal van de emulator",
"Options.Language.Desc": "Taal die in de hele launcher wordt gebruikt. Wordt direct toegepast.",
"Common.On": "Aan",
"Common.Off": "Uit",
"Console.Title": "CONSOLE",
"Console.SearchWatermark": "Zoeken...",
"Console.AutoScroll": "Automatisch scrollen",
"Console.Split": "Splitsen",
"Console.Copy": "Kopiëren",
"Console.Clear": "Wissen",
"Console.WindowTitle": "SharpEmu-console",
"Launch.NoGameSelected": "Geen game geselecteerd",
"Launch.NoGameHint": "Kies een game uit de bibliotheek, of open direct een eboot.bin-bestand.",
"Launch.Idle": "Inactief",
"Launch.Console": "≡ Console",
"Launch.Launch": "▶ Starten",
"Launch.Stop": "■ Stoppen",
"Launch.Running": "Actief — {0}",
"Launch.Stopping": "Stoppen…",
"Launch.Exited": "Afgesloten met code {0} ({1})",
"Launch.ExeNotFound": "SharpEmu-uitvoerbaar bestand niet gevonden. Bouw eerst het SharpEmu.CLI-project (dotnet build).",
"Launch.LogFile": "Logbestand: {0}",
"Launch.Command": "$ SharpEmu {0}",
"Launch.StartFailed": "Starten van de emulator mislukt: {0}",
"Launch.ProcessExited": "Proces afgesloten met code {0} ({1}).",
"Exit.Ok": "OK",
"Exit.InvalidArguments": "ongeldige argumenten",
"Exit.EbootNotFound": "eboot niet gevonden",
"Exit.RuntimeException": "runtime-uitzondering",
"Exit.EmulationError": "emulatiefout",
"Exit.Unknown": "onbekend",
"Status.EmulatorLocating": "Emulator: zoeken…",
"Status.EmulatorPath": "Emulator: {0}",
"Status.EmulatorNotFound": "Emulator: SharpEmu-uitvoerbaar bestand niet gevonden — bouw eerst SharpEmu.CLI.",
"Status.ScanningLibrary": "Bibliotheek scannen…",
"Status.AddFolderPrompt": "Voeg een gamemap toe om de bibliotheek te vullen.",
"Status.LibraryScanned": "Bibliotheek gescand: {0} game(s) in {1} map(pen).",
"Status.CouldNotOpenFolder": "Kan map niet openen: {0}",
"Status.CopiedToClipboard": "{0} gekopieerd naar klembord.",
"Status.RemovedFromLibrary": "“{0}” verwijderd uit de bibliotheek. Voeg de map opnieuw toe om dit te herstellen.",
"Status.Running": "Actief {0}",
"Status.Stopping": "Stoppen…",
"Status.Idle": "Inactief",
"Clipboard.Path": "Pad",
"Clipboard.TitleId": "Titel-ID",
"Discord.Playing": "Speelt {0}",
"Discord.Browsing": "Bladert door de bibliotheek",
"Dialog.ChooseGameFolder": "Kies een map met games",
"Dialog.OpenExecutable": "Open een uitvoerbaar bestand om te starten",
"Dialog.PsExecutables": "PS-uitvoerbare bestanden",
"Dialog.SaveLogFile": "Selecteer waar het logbestand moet worden opgeslagen",
"Dialog.PlainTextFiles": "Platte tekstbestanden",
"Dialog.LogFiles": "Logbestanden"
}
+1
View File
@@ -1499,6 +1499,7 @@ public partial class MainWindow : Window
2 => "Exit.EbootNotFound",
3 => "Exit.RuntimeException",
4 => "Exit.EmulationError",
-1073741819 => "Exit.EmulationError",
_ => "Exit.Unknown",
};
var meaning = Localization.Instance.Get(meaningKey);
Binary file not shown.
+31 -10
View File
@@ -54,20 +54,41 @@ internal static class PakDirectoryTracker
if (state.Directory is { } entries)
{
// Several unrelated archived files can share a byte count (e.g. a head model and a bot
// navigation file both 0x3A34 bytes). Directory order alone then picks whichever comes
// first, which is wrong when the game reads them out of order. id archives cluster
// related assets, and the guest streams them with locality, so disambiguate collisions
// by choosing the unconsumed match nearest the running read cursor.
DirectoryEntry? best = null;
var bestDistance = ulong.MaxValue;
foreach (var entry in entries)
{
if (!entry.Consumed && entry.FileLen == requestedSize)
if (entry.Consumed || entry.FileLen != requestedSize)
{
entry.Consumed = true;
if (_trace)
{
Console.Error.WriteLine(
$"[LOADER][TRACE] pak.directory_match: id=0x{fileId:X8} name='{entry.Name}' " +
$"filepos=0x{entry.FilePos:X8} filelen=0x{entry.FileLen:X8}");
}
return entry.FilePos;
continue;
}
var distance = entry.FilePos >= state.NextOffset
? entry.FilePos - state.NextOffset
: state.NextOffset - entry.FilePos;
if (distance < bestDistance)
{
bestDistance = distance;
best = entry;
}
}
if (best is not null)
{
best.Consumed = true;
if (_trace)
{
Console.Error.WriteLine(
$"[LOADER][TRACE] pak.directory_match: id=0x{fileId:X8} name='{best.Name}' " +
$"filepos=0x{best.FilePos:X8} filelen=0x{best.FileLen:X8}");
}
return best.FilePos;
}
}
@@ -35,6 +35,17 @@ public static class AvPlayerExports
return unchecked((int)handle);
}
[SysAbiExport(
Nid = "KMcEa+rHsIo",
ExportName = "sceAvPlayerAddSource",
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libSceAvPlayer")]
public static int AvPlayerAddSource(CpuContext ctx)
{
ctx[CpuRegister.Rax] = 0;
return (int)OrbisGen2Result.ORBIS_GEN2_OK;
}
[SysAbiExport(
Nid = "JdksQu8pNdQ",
ExportName = "sceAvPlayerGetVideoDataEx",
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: GPL-2.0-or-later
using SharpEmu.HLE;
using System.Buffers.Binary;
using System.Threading;
namespace SharpEmu.Libs.CommonDialog;
@@ -10,10 +11,21 @@ public static class MsgDialogExports
{
private const int StatusNone = 0;
private const int StatusInitialized = 1;
private const int StatusRunning = 2;
private const int StatusFinished = 3;
private const int ResultSize = 0x20;
private static int _initialized;
private const int ErrorOk = 0;
private const int ErrorNotInitialized = unchecked((int)0x80B80003);
private const int ErrorNotFinished = unchecked((int)0x80B80005);
private const int ErrorBusy = unchecked((int)0x80B80007);
private const int ErrorNotRunning = unchecked((int)0x80B8000B);
private const int ErrorArgNull = unchecked((int)0x80B8000D);
// Result buffer layout follows the common dialog convention: mode at +0x00,
// result at +0x04, buttonId at +0x08. The affirmative button (OK/YES) is 1.
private const int ResultSize = 0x20;
private const int ButtonIdAffirmative = 1;
private static int _status;
[SysAbiExport(
@@ -24,11 +36,10 @@ public static class MsgDialogExports
public static int MsgDialogInitialize(CpuContext ctx)
{
// Treat repeated initialization as success. The dialog service is process-global in
// this HLE implementation and has no per-call resources to recreate.
Interlocked.Exchange(ref _initialized, 1);
Interlocked.Exchange(ref _status, StatusInitialized);
ctx[CpuRegister.Rax] = 0;
return (int)OrbisGen2Result.ORBIS_GEN2_OK;
// this HLE implementation and has no per-call resources to recreate. Only promote
// from NONE so re-initializing mid-flow cannot clobber a running/finished dialog.
Interlocked.CompareExchange(ref _status, StatusInitialized, StatusNone);
return ctx.SetReturn(ErrorOk);
}
[SysAbiExport(
@@ -38,9 +49,12 @@ public static class MsgDialogExports
LibraryName = "libSceMsgDialog")]
public static int MsgDialogTerminate(CpuContext ctx)
{
Interlocked.Exchange(ref _initialized, 0);
Interlocked.Exchange(ref _status, StatusNone);
return SetReturn(ctx, (int)OrbisGen2Result.ORBIS_GEN2_OK);
if (Interlocked.Exchange(ref _status, StatusNone) == StatusNone)
{
return ctx.SetReturn(ErrorNotInitialized);
}
return ctx.SetReturn(ErrorOk);
}
[SysAbiExport(
@@ -50,13 +64,29 @@ public static class MsgDialogExports
LibraryName = "libSceMsgDialog")]
public static int MsgDialogOpen(CpuContext ctx)
{
LogDialogMessage(ctx, ctx[CpuRegister.Rdi]);
var paramAddress = ctx[CpuRegister.Rdi];
if (paramAddress == 0)
{
return ctx.SetReturn(ErrorArgNull);
}
// There is no host popup to actually show. Complete immediately with "finished" so a
// guest polling loop (GetStatus/UpdateStatus -> GetResult -> Close) sees a dismissed
// dialog on its very first poll instead of spinning forever waiting for user input.
Interlocked.Exchange(ref _status, StatusFinished);
return SetReturn(ctx, (int)OrbisGen2Result.ORBIS_GEN2_OK);
var status = Volatile.Read(ref _status);
if (status == StatusNone)
{
return ctx.SetReturn(ErrorNotInitialized);
}
if (status == StatusRunning)
{
return ctx.SetReturn(ErrorBusy);
}
LogDialogMessage(ctx, paramAddress);
// There is no host popup to actually show. Enter RUNNING so close/cancel paths see
// a live dialog; the guest's next status poll auto-dismisses it (see PollStatus).
Interlocked.Exchange(ref _status, StatusRunning);
return ctx.SetReturn(ErrorOk);
}
// Best-effort extraction of the dialog text so fatal-error popups are visible in the
@@ -65,12 +95,6 @@ public static class MsgDialogExports
// level deep, then a second level for nested sub-param structs.
private static void LogDialogMessage(CpuContext ctx, ulong paramAddress)
{
if (paramAddress == 0)
{
Console.Error.WriteLine("[LOADER][INFO] sceMsgDialogOpen: param=NULL");
return;
}
Console.Error.WriteLine($"[LOADER][INFO] sceMsgDialogOpen: param=0x{paramAddress:X12}");
Span<byte> head = stackalloc byte[0xA0];
@@ -134,14 +158,24 @@ public static class MsgDialogExports
ExportName = "sceMsgDialogGetStatus",
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libSceMsgDialog")]
public static int MsgDialogGetStatus(CpuContext ctx) => SetReturn(ctx, Volatile.Read(ref _status));
public static int MsgDialogGetStatus(CpuContext ctx) => ctx.SetReturn(PollStatus());
[SysAbiExport(
Nid = "6fIC3XKt2k0",
ExportName = "sceMsgDialogUpdateStatus",
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libSceMsgDialog")]
public static int MsgDialogUpdateStatus(CpuContext ctx) => SetReturn(ctx, Volatile.Read(ref _status));
public static int MsgDialogUpdateStatus(CpuContext ctx) => ctx.SetReturn(PollStatus());
// With no host UI the dialog cannot wait for user input: the first status poll after
// Open observes the dialog as already dismissed. Advancing on both UpdateStatus and
// GetStatus keeps every guest polling pattern free of infinite RUNNING loops, while
// an Open -> Close sequence with no poll in between still exercises the close path.
private static int PollStatus()
{
Interlocked.CompareExchange(ref _status, StatusFinished, StatusRunning);
return Volatile.Read(ref _status);
}
[SysAbiExport(
Nid = "Lr8ovHH9l6A",
@@ -153,17 +187,27 @@ public static class MsgDialogExports
var resultAddress = ctx[CpuRegister.Rdi];
if (resultAddress == 0)
{
return SetReturn(ctx, (int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT);
return ctx.SetReturn(ErrorArgNull);
}
if (Volatile.Read(ref _status) != StatusFinished)
{
return ctx.SetReturn(ErrorNotFinished);
}
// Report the affirmative button so yes/no prompts take the confirming branch;
// buttonId 0 is the "invalid" sentinel and games may treat it as an error.
Span<byte> result = stackalloc byte[ResultSize];
result.Clear();
BinaryPrimitives.WriteInt32LittleEndian(result[0x04..], 0);
BinaryPrimitives.WriteInt32LittleEndian(result[0x08..], ButtonIdAffirmative);
if (!ctx.Memory.TryWrite(resultAddress, result))
{
return SetReturn(ctx, (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT);
return ctx.SetReturn((int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT);
}
return SetReturn(ctx, (int)OrbisGen2Result.ORBIS_GEN2_OK);
return ctx.SetReturn(ErrorOk);
}
[SysAbiExport(
@@ -173,13 +217,44 @@ public static class MsgDialogExports
LibraryName = "libSceMsgDialog")]
public static int MsgDialogClose(CpuContext ctx)
{
Interlocked.Exchange(ref _status, StatusFinished);
return SetReturn(ctx, (int)OrbisGen2Result.ORBIS_GEN2_OK);
if (Interlocked.CompareExchange(ref _status, StatusFinished, StatusRunning) != StatusRunning)
{
return ctx.SetReturn(ErrorNotRunning);
}
return ctx.SetReturn(ErrorOk);
}
private static int SetReturn(CpuContext ctx, int result)
[SysAbiExport(
Nid = "wTpfglkmv34",
ExportName = "sceMsgDialogProgressBarSetValue",
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libSceMsgDialog")]
public static int MsgDialogProgressBarSetValue(CpuContext ctx) => ProgressBarNoOp(ctx);
[SysAbiExport(
Nid = "Gc5k1qcK4fs",
ExportName = "sceMsgDialogProgressBarInc",
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libSceMsgDialog")]
public static int MsgDialogProgressBarInc(CpuContext ctx) => ProgressBarNoOp(ctx);
[SysAbiExport(
Nid = "6H-71OdrpXM",
ExportName = "sceMsgDialogProgressBarSetMsg",
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libSceMsgDialog")]
public static int MsgDialogProgressBarSetMsg(CpuContext ctx) => ProgressBarNoOp(ctx);
// There is no visible bar to update. Accept the call whenever the service is alive so
// save/install loops that report progress do not abort on an unexpected error.
private static int ProgressBarNoOp(CpuContext ctx)
{
ctx[CpuRegister.Rax] = unchecked((ulong)result);
return result;
if (Volatile.Read(ref _status) == StatusNone)
{
return ctx.SetReturn(ErrorNotInitialized);
}
return ctx.SetReturn(ErrorOk);
}
}
+24
View File
@@ -78,6 +78,30 @@ public static class JsonExports
return (int)OrbisGen2Result.ORBIS_GEN2_OK;
}
// sce::Json::Initializer::setGlobalNullAccessCallback(const Value& (*)(ValueType, const Value*, void*), void*)
// Registers the guest hook invoked when a Value is accessed as the wrong type. Quake calls it
// during kexPSNWebAPI::Initialize and treats a non-zero return as a fatal init failure.
[SysAbiExport(
Nid = "+drDFyAS6u4",
ExportName = "_ZN3sce4Json11Initializer27setGlobalNullAccessCallbackEPFRKNS0_5ValueENS0_9ValueTypeEPS3_PvES7_",
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libSceJson")]
public static int InitializerSetGlobalNullAccessCallback(CpuContext ctx)
{
var thisAddress = ctx[CpuRegister.Rdi];
if (thisAddress == 0)
{
ctx[CpuRegister.Rax] = unchecked((ulong)(int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT);
return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT;
}
JsonObjectHeap.GlobalNullAccessCallback = ctx[CpuRegister.Rsi];
JsonObjectHeap.GlobalNullAccessCallbackContext = ctx[CpuRegister.Rdx];
TraceJson("Initializer.setGlobalNullAccessCallback", thisAddress, ctx[CpuRegister.Rsi]);
ctx[CpuRegister.Rax] = 0;
return (int)OrbisGen2Result.ORBIS_GEN2_OK;
}
[SysAbiExport(
Nid = "WSOuge5IsCg",
ExportName = "_ZN3sce4Json14InitParameter2C1Ev",
+234
View File
@@ -0,0 +1,234 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using SharpEmu.HLE;
namespace SharpEmu.Libs.Json;
// sce::Json::Value and sce::Json::String constructors, setters and destructors. Prospero titles
// (Quake among them) build a Value tree and populate it through these before serializing it for a
// web request; without them the imports resolve to nothing and the guest faults on the call. The
// payload is modelled in JsonObjectHeap; here we only translate the C++ ABI (registers in, `this`
// back out) and never write the guest object, so a stack-allocated Value/String is left intact.
//
// Only the complete-object variants (C1/D1) are bound — those are what standalone locals emit and
// what the observed Prospero imports use. The base-object variants (C2/D2) are left for a title
// that actually imports them.
public static class JsonValueExports
{
private const int MaxStringLength = 0x10000;
private static int ReturnThis(CpuContext ctx, ulong thisAddress)
{
ctx[CpuRegister.Rax] = thisAddress;
return (int)OrbisGen2Result.ORBIS_GEN2_OK;
}
private static int ReturnVoid(CpuContext ctx)
{
ctx[CpuRegister.Rax] = 0;
return (int)OrbisGen2Result.ORBIS_GEN2_OK;
}
private static double ReadDoubleArg(CpuContext ctx)
{
ctx.GetXmmRegister(0, out var low, out _);
return BitConverter.Int64BitsToDouble(unchecked((long)low));
}
private static string ReadCString(CpuContext ctx, ulong address) =>
ctx.TryReadNullTerminatedUtf8(address, MaxStringLength, out var text) ? text : string.Empty;
// ---- sce::Json::Value constructors ----
[SysAbiExport(Nid = "qBMjqyBn3OM", ExportName = "_ZN3sce4Json5ValueC1Ev",
Target = Generation.Gen4 | Generation.Gen5, LibraryName = "libSceJson")]
public static int ValueDefaultConstructor(CpuContext ctx)
{
var thisAddress = ctx[CpuRegister.Rdi];
JsonObjectHeap.SetValue(thisAddress, JsonValueState.Null);
return ReturnThis(ctx, thisAddress);
}
[SysAbiExport(Nid = "UeuWT+yNdCQ", ExportName = "_ZN3sce4Json5ValueC1Eb",
Target = Generation.Gen4 | Generation.Gen5, LibraryName = "libSceJson")]
public static int ValueBooleanConstructor(CpuContext ctx)
{
var thisAddress = ctx[CpuRegister.Rdi];
JsonObjectHeap.SetValue(thisAddress, JsonValueState.FromBoolean((ctx[CpuRegister.Rsi] & 0xFF) != 0));
return ReturnThis(ctx, thisAddress);
}
[SysAbiExport(Nid = "0lLK8+kDqmE", ExportName = "_ZN3sce4Json5ValueC1El",
Target = Generation.Gen4 | Generation.Gen5, LibraryName = "libSceJson")]
public static int ValueIntegerConstructor(CpuContext ctx)
{
var thisAddress = ctx[CpuRegister.Rdi];
JsonObjectHeap.SetValue(thisAddress, JsonValueState.FromInteger(unchecked((long)ctx[CpuRegister.Rsi])));
return ReturnThis(ctx, thisAddress);
}
[SysAbiExport(Nid = "x4AUdbhpRB0", ExportName = "_ZN3sce4Json5ValueC1Em",
Target = Generation.Gen4 | Generation.Gen5, LibraryName = "libSceJson")]
public static int ValueUnsignedConstructor(CpuContext ctx)
{
var thisAddress = ctx[CpuRegister.Rdi];
JsonObjectHeap.SetValue(thisAddress, JsonValueState.FromUnsignedInteger(ctx[CpuRegister.Rsi]));
return ReturnThis(ctx, thisAddress);
}
[SysAbiExport(Nid = "sOmU4vnx3s0", ExportName = "_ZN3sce4Json5ValueC1Ed",
Target = Generation.Gen4 | Generation.Gen5, LibraryName = "libSceJson")]
public static int ValueRealConstructor(CpuContext ctx)
{
var thisAddress = ctx[CpuRegister.Rdi];
JsonObjectHeap.SetValue(thisAddress, JsonValueState.FromReal(ReadDoubleArg(ctx)));
return ReturnThis(ctx, thisAddress);
}
[SysAbiExport(Nid = "b9V6fmppLXY", ExportName = "_ZN3sce4Json5ValueC1EPKc",
Target = Generation.Gen4 | Generation.Gen5, LibraryName = "libSceJson")]
public static int ValueCStringConstructor(CpuContext ctx)
{
var thisAddress = ctx[CpuRegister.Rdi];
JsonObjectHeap.SetValue(thisAddress, JsonValueState.FromString(ReadCString(ctx, ctx[CpuRegister.Rsi])));
return ReturnThis(ctx, thisAddress);
}
[SysAbiExport(Nid = "CbrT3dwDILo", ExportName = "_ZN3sce4Json5ValueC1ENS0_9ValueTypeE",
Target = Generation.Gen4 | Generation.Gen5, LibraryName = "libSceJson")]
public static int ValueTypeConstructor(CpuContext ctx)
{
var thisAddress = ctx[CpuRegister.Rdi];
JsonObjectHeap.SetValue(thisAddress, JsonValueState.FromExplicitType(unchecked((uint)ctx[CpuRegister.Rsi])));
return ReturnThis(ctx, thisAddress);
}
[SysAbiExport(Nid = "sZIoMRGO+jk", ExportName = "_ZN3sce4Json5ValueC1ERKNS0_6StringE",
Target = Generation.Gen4 | Generation.Gen5, LibraryName = "libSceJson")]
public static int ValueStringConstructor(CpuContext ctx)
{
var thisAddress = ctx[CpuRegister.Rdi];
JsonObjectHeap.SetValue(thisAddress, JsonValueState.FromString(JsonObjectHeap.GetStringOrEmpty(ctx[CpuRegister.Rsi])));
return ReturnThis(ctx, thisAddress);
}
[SysAbiExport(Nid = "WTtYf+cNnXI", ExportName = "_ZN3sce4Json5ValueD1Ev",
Target = Generation.Gen4 | Generation.Gen5, LibraryName = "libSceJson")]
public static int ValueDestructor(CpuContext ctx)
{
JsonObjectHeap.RemoveValue(ctx[CpuRegister.Rdi]);
return ReturnVoid(ctx);
}
// ---- sce::Json::Value setters (return Value&, i.e. `this`) ----
[SysAbiExport(Nid = "5yHuiWXo2gg", ExportName = "_ZN3sce4Json5Value3setEb",
Target = Generation.Gen4 | Generation.Gen5, LibraryName = "libSceJson")]
public static int ValueSetBoolean(CpuContext ctx)
{
var thisAddress = ctx[CpuRegister.Rdi];
JsonObjectHeap.SetValue(thisAddress, JsonValueState.FromBoolean((ctx[CpuRegister.Rsi] & 0xFF) != 0));
return ReturnThis(ctx, thisAddress);
}
[SysAbiExport(Nid = "QxVVYhP-mvg", ExportName = "_ZN3sce4Json5Value3setEl",
Target = Generation.Gen4 | Generation.Gen5, LibraryName = "libSceJson")]
public static int ValueSetInteger(CpuContext ctx)
{
var thisAddress = ctx[CpuRegister.Rdi];
JsonObjectHeap.SetValue(thisAddress, JsonValueState.FromInteger(unchecked((long)ctx[CpuRegister.Rsi])));
return ReturnThis(ctx, thisAddress);
}
[SysAbiExport(Nid = "SIe1ZmW7e7s", ExportName = "_ZN3sce4Json5Value3setEm",
Target = Generation.Gen4 | Generation.Gen5, LibraryName = "libSceJson")]
public static int ValueSetUnsigned(CpuContext ctx)
{
var thisAddress = ctx[CpuRegister.Rdi];
JsonObjectHeap.SetValue(thisAddress, JsonValueState.FromUnsignedInteger(ctx[CpuRegister.Rsi]));
return ReturnThis(ctx, thisAddress);
}
[SysAbiExport(Nid = "BSmWDIkV4w4", ExportName = "_ZN3sce4Json5Value3setEd",
Target = Generation.Gen4 | Generation.Gen5, LibraryName = "libSceJson")]
public static int ValueSetReal(CpuContext ctx)
{
var thisAddress = ctx[CpuRegister.Rdi];
JsonObjectHeap.SetValue(thisAddress, JsonValueState.FromReal(ReadDoubleArg(ctx)));
return ReturnThis(ctx, thisAddress);
}
[SysAbiExport(Nid = "IKQimvG9Wqs", ExportName = "_ZN3sce4Json5Value3setENS0_9ValueTypeE",
Target = Generation.Gen4 | Generation.Gen5, LibraryName = "libSceJson")]
public static int ValueSetType(CpuContext ctx)
{
var thisAddress = ctx[CpuRegister.Rdi];
JsonObjectHeap.SetValue(thisAddress, JsonValueState.FromExplicitType(unchecked((uint)ctx[CpuRegister.Rsi])));
return ReturnThis(ctx, thisAddress);
}
[SysAbiExport(Nid = "n6FC+l9DU70", ExportName = "_ZN3sce4Json5Value3setEPKc",
Target = Generation.Gen4 | Generation.Gen5, LibraryName = "libSceJson")]
public static int ValueSetCString(CpuContext ctx)
{
var thisAddress = ctx[CpuRegister.Rdi];
JsonObjectHeap.SetValue(thisAddress, JsonValueState.FromString(ReadCString(ctx, ctx[CpuRegister.Rsi])));
return ReturnThis(ctx, thisAddress);
}
[SysAbiExport(Nid = "6l3Bv2gysNc", ExportName = "_ZN3sce4Json5Value3setERKNS0_6StringE",
Target = Generation.Gen4 | Generation.Gen5, LibraryName = "libSceJson")]
public static int ValueSetString(CpuContext ctx)
{
var thisAddress = ctx[CpuRegister.Rdi];
JsonObjectHeap.SetValue(thisAddress, JsonValueState.FromString(JsonObjectHeap.GetStringOrEmpty(ctx[CpuRegister.Rsi])));
return ReturnThis(ctx, thisAddress);
}
[SysAbiExport(Nid = "FIjXN2TkuTs", ExportName = "_ZN3sce4Json5Value5clearEv",
Target = Generation.Gen4 | Generation.Gen5, LibraryName = "libSceJson")]
public static int ValueClear(CpuContext ctx)
{
var thisAddress = ctx[CpuRegister.Rdi];
JsonObjectHeap.SetValue(thisAddress, JsonValueState.Null);
return ReturnThis(ctx, thisAddress);
}
// ---- sce::Json::String ----
[SysAbiExport(Nid = "9KUZFjI1IxA", ExportName = "_ZN3sce4Json6StringC1EPKc",
Target = Generation.Gen4 | Generation.Gen5, LibraryName = "libSceJson")]
public static int StringCStringConstructor(CpuContext ctx)
{
var thisAddress = ctx[CpuRegister.Rdi];
JsonObjectHeap.SetString(thisAddress, ReadCString(ctx, ctx[CpuRegister.Rsi]));
return ReturnThis(ctx, thisAddress);
}
[SysAbiExport(Nid = "qSmqLXXCPas", ExportName = "_ZN3sce4Json6StringC1Ev",
Target = Generation.Gen4 | Generation.Gen5, LibraryName = "libSceJson")]
public static int StringDefaultConstructor(CpuContext ctx)
{
var thisAddress = ctx[CpuRegister.Rdi];
JsonObjectHeap.SetString(thisAddress, string.Empty);
return ReturnThis(ctx, thisAddress);
}
[SysAbiExport(Nid = "0CAesfH963Q", ExportName = "_ZN3sce4Json6StringC1ERKS1_",
Target = Generation.Gen4 | Generation.Gen5, LibraryName = "libSceJson")]
public static int StringCopyConstructor(CpuContext ctx)
{
var thisAddress = ctx[CpuRegister.Rdi];
JsonObjectHeap.SetString(thisAddress, JsonObjectHeap.GetStringOrEmpty(ctx[CpuRegister.Rsi]));
return ReturnThis(ctx, thisAddress);
}
[SysAbiExport(Nid = "cG1VE2HMl6c", ExportName = "_ZN3sce4Json6StringD1Ev",
Target = Generation.Gen4 | Generation.Gen5, LibraryName = "libSceJson")]
public static int StringDestructor(CpuContext ctx)
{
JsonObjectHeap.RemoveString(ctx[CpuRegister.Rdi]);
return ReturnVoid(ctx);
}
}
+110
View File
@@ -0,0 +1,110 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Collections.Concurrent;
namespace SharpEmu.Libs.Json;
// sce::Json::Value is an opaque variant type (null / bool / signed / unsigned / real / string /
// array / object). Games build one, populate it through set()/ctors and later serialize it. We
// model the payload host-side keyed by the guest `this` pointer instead of writing into the guest
// object: the object is often stack-allocated and its real byte layout is unknown, so writing a
// guessed layout risks smashing an adjacent stack canary (the same failure the AudioOut2 context
// param sizing note in this project already ran into). The guest reaches the payload only through
// libSceJson methods, so shadowing by address is enough for the build path.
internal enum JsonValueKind : byte
{
Null = 0,
Boolean = 1,
Integer = 2,
UInteger = 3,
Real = 4,
String = 5,
// set(ValueType) / Value(ValueType): the guest chose the type itself. We keep its raw enum
// value verbatim rather than mapping it, because the canonical ValueType constants are not
// known from clean-room evidence and round-tripping the guest's own value is what matters.
ExplicitType = 6,
}
internal readonly struct JsonValueState
{
private JsonValueState(
JsonValueKind kind,
bool boolean = false,
long integer = 0,
ulong unsignedInteger = 0,
double real = 0,
string? text = null,
uint explicitType = 0)
{
Kind = kind;
Boolean = boolean;
Integer = integer;
UnsignedInteger = unsignedInteger;
Real = real;
Text = text;
ExplicitType = explicitType;
}
public JsonValueKind Kind { get; }
public bool Boolean { get; }
public long Integer { get; }
public ulong UnsignedInteger { get; }
public double Real { get; }
public string? Text { get; }
public uint ExplicitType { get; }
public static JsonValueState Null { get; } = new(JsonValueKind.Null);
public static JsonValueState FromBoolean(bool value) => new(JsonValueKind.Boolean, boolean: value);
public static JsonValueState FromInteger(long value) => new(JsonValueKind.Integer, integer: value);
public static JsonValueState FromUnsignedInteger(ulong value) =>
new(JsonValueKind.UInteger, unsignedInteger: value);
public static JsonValueState FromReal(double value) => new(JsonValueKind.Real, real: value);
public static JsonValueState FromString(string value) => new(JsonValueKind.String, text: value);
public static JsonValueState FromExplicitType(uint value) =>
new(JsonValueKind.ExplicitType, explicitType: value);
}
// Shared host-side heap for the libSceJson object shadows. Keyed by the guest object address;
// constructors overwrite and destructors remove, so guest stack-address reuse stays correct.
internal static class JsonObjectHeap
{
public static ConcurrentDictionary<ulong, JsonValueState> Values { get; } = new();
public static ConcurrentDictionary<ulong, string> Strings { get; } = new();
// Guest function the library should call when a Value is read as the wrong type. This HLE
// never dereferences missing members (shadows degrade to defaults), so the hook is stored for
// fidelity but not invoked.
public static ulong GlobalNullAccessCallback;
public static ulong GlobalNullAccessCallbackContext;
public static void SetValue(ulong address, JsonValueState state) => Values[address] = state;
public static void RemoveValue(ulong address) => Values.TryRemove(address, out _);
public static void SetString(ulong address, string text) => Strings[address] = text;
public static void RemoveString(ulong address) => Strings.TryRemove(address, out _);
// A missing shadow (temporary the compiler built without an out-of-line ctor, or a copy we did
// not track) degrades to the empty string rather than faulting.
public static string GetStringOrEmpty(ulong address) =>
Strings.TryGetValue(address, out var text) ? text : string.Empty;
internal static void ResetForTests()
{
Values.Clear();
Strings.Clear();
GlobalNullAccessCallback = 0;
GlobalNullAccessCallbackContext = 0;
}
}
@@ -200,6 +200,40 @@ public static class KernelMemoryCompatExports
}
}
public static bool TryUnregisterGuestPathMount(string guestMountPoint)
{
if (string.IsNullOrWhiteSpace(guestMountPoint))
{
return false;
}
var normalizedMountPoint = NormalizeGuestStatCachePath(guestMountPoint);
if (normalizedMountPoint is null || normalizedMountPoint == "/")
{
return false;
}
var removed = false;
lock (_guestMountGate)
{
removed = _guestMounts.Remove(normalizedMountPoint);
}
if (!removed)
{
return false;
}
lock (_statCacheGate)
{
_negativeStatCache.RemoveWhere(path =>
string.Equals(path, normalizedMountPoint, StringComparison.OrdinalIgnoreCase) ||
path.StartsWith(normalizedMountPoint + "/", StringComparison.OrdinalIgnoreCase));
}
return true;
}
internal static bool TryAllocateHleData(
CpuContext ctx,
ulong length,
@@ -6947,15 +6981,4 @@ public static class KernelMemoryCompatExports
sum = left + right;
return sum >= left;
}
[SysAbiExport(
Nid = "KMcEa+rHsIo",
ExportName = "sceKernelMapMemory",
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libKernel")]
public static int KernelMapMemory(CpuContext ctx)
{
ctx[CpuRegister.Rax] = 0;
return (int)OrbisGen2Result.ORBIS_GEN2_OK;
}
}
+1 -1
View File
@@ -59,7 +59,7 @@ public static class NpManagerExports
[SysAbiExport(
Nid = "rbknaUjpqWo",
ExportName = "sceNpGetOnlineIdA",
ExportName = "sceNpGetAccountIdA",
Target = Generation.Gen5,
LibraryName = "libSceNpManager")]
public static int NpGetOnlineIdA(CpuContext ctx)
@@ -9,7 +9,10 @@ namespace SharpEmu.Libs.Np;
public static class NpUniversalDataSystemExports
{
private const int NpUniversalDataSystemErrorInvalidArgument = unchecked((int)0x80553102);
private static readonly object _eventGate = new();
private static readonly HashSet<int> _createdEvents = [];
private static int _nextHandle = 1;
private static int _nextEvent = 1;
[SysAbiExport(
Nid = "sjaobBgqeB4",
@@ -67,6 +70,114 @@ public static class NpUniversalDataSystemExports
return ctx.SetReturn((int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT, typeof(long));
}
[SysAbiExport(
Nid = "p+GcLqwpL9M",
ExportName = "sceNpUniversalDataSystemCreateEvent",
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libSceNpUniversalDataSystem")]
public static int NpUniversalDataSystemCreateEvent(CpuContext ctx)
{
var parameterAddress = ctx[CpuRegister.Rdi];
if (parameterAddress == 0)
{
return ctx.SetReturn(NpUniversalDataSystemErrorInvalidArgument, typeof(long));
}
var eventId = Interlocked.Increment(ref _nextEvent);
lock (_eventGate)
{
_createdEvents.Add(eventId);
}
if (ctx.TryWriteInt32(ctx[CpuRegister.Rdx], eventId, checkNil: true) ||
ctx.TryWriteInt32(ctx[CpuRegister.Rcx], eventId, checkNil: true))
{
return ctx.SetReturn(0, typeof(long));
}
lock (_eventGate)
{
_createdEvents.Remove(eventId);
}
return ctx.SetReturn((int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT, typeof(long));
}
[SysAbiExport(
Nid = "wG+84pnNIuo",
ExportName = "sceNpUniversalDataSystemDestroyEvent",
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libSceNpUniversalDataSystem")]
public static int NpUniversalDataSystemDestroyEvent(CpuContext ctx)
{
var eventId = unchecked((int)ctx[CpuRegister.Rdi]);
lock (_eventGate)
{
_createdEvents.Remove(eventId);
}
return ctx.SetReturn(0, typeof(long));
}
[SysAbiExport(
Nid = "MfDb+4Nln64",
ExportName = "sceNpUniversalDataSystemEventPropertyObjectSetString",
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libSceNpUniversalDataSystem")]
public static int NpUniversalDataSystemEventPropertyObjectSetString(CpuContext ctx)
{
var propertyObjectAddress = ctx[CpuRegister.Rsi];
var valueAddress = ctx[CpuRegister.Rdx];
if (propertyObjectAddress == 0 || valueAddress == 0)
{
return ctx.SetReturn(NpUniversalDataSystemErrorInvalidArgument, typeof(long));
}
Span<byte> probe = stackalloc byte[1];
return ctx.Memory.TryRead(propertyObjectAddress, probe) &&
ctx.Memory.TryRead(valueAddress, probe)
? ctx.SetReturn(0, typeof(long))
: ctx.SetReturn((int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT, typeof(long));
}
[SysAbiExport(
Nid = "Wxbg5x3pTXA",
ExportName = "sceNpUniversalDataSystemEventPropertyObjectSetArray",
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libSceNpUniversalDataSystem")]
public static int NpUniversalDataSystemEventPropertyObjectSetArray(CpuContext ctx)
{
var propertyObjectAddress = ctx[CpuRegister.Rsi];
var valueAddress = ctx[CpuRegister.Rdx];
if (propertyObjectAddress == 0)
{
return ctx.SetReturn(NpUniversalDataSystemErrorInvalidArgument, typeof(long));
}
Span<byte> probe = stackalloc byte[1];
if (!ctx.Memory.TryRead(propertyObjectAddress, probe))
{
return ctx.SetReturn((int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT, typeof(long));
}
if (valueAddress != 0 && !ctx.Memory.TryRead(valueAddress, probe))
{
return ctx.SetReturn((int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT, typeof(long));
}
return ctx.SetReturn(0, typeof(long));
}
[SysAbiExport(
Nid = "CzkKf7ahIyU",
ExportName = "sceNpUniversalDataSystemPostEvent",
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libSceNpUniversalDataSystem")]
public static int NpUniversalDataSystemPostEvent(CpuContext ctx)
{
return ctx.SetReturn(0, typeof(long));
}
[SysAbiExport(
Nid = "tpFJ8LIKvPw",
ExportName = "sceNpUniversalDataSystemRegisterContext",
+1 -1
View File
@@ -33,7 +33,7 @@ public static class NpWebApi2Exports
[SysAbiExport(
Nid = "WV1GwM32NgY",
ExportName = "sceNpWebApi2InitializeForToolkit",
ExportName = "sceNpWebApi2PushEventCreateHandle",
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libSceNpWebApi2")]
public static int NpWebApi2InitializeAlt(CpuContext ctx)
@@ -21,6 +21,7 @@ public static class SaveDataDialogExports
private const int ErrorArgNull = unchecked((int)0x80B8000D);
private const int ResultSize = 0x48;
private const int ButtonIdAffirmative = 1;
private static int _status;
private static int _lastMode;
private static ulong _lastUserData;
@@ -61,10 +62,10 @@ public static class SaveDataDialogExports
_lastMode = TryReadInt32(ctx, paramAddress, out var mode) ? mode : 0;
_lastUserData = ctx.TryReadUInt64(paramAddress + 0xC8, out var userData) ? userData : 0;
// There is no host save dialog yet. Complete immediately with OK so
// guest polling sees a finished dialog instead of spinning forever.
Interlocked.Exchange(ref _status, StatusFinished);
TraceSaveDataDialog($"open mode={_lastMode} userData=0x{_lastUserData:X16} -> finished");
// There is no host save dialog yet. Enter RUNNING so the close path sees a live
// dialog; the guest's next status poll auto-dismisses it (see PollStatus).
Interlocked.Exchange(ref _status, StatusRunning);
TraceSaveDataDialog($"open mode={_lastMode} userData=0x{_lastUserData:X16} -> running");
return ctx.SetReturn(ErrorOk);
}
@@ -73,14 +74,24 @@ public static class SaveDataDialogExports
ExportName = "sceSaveDataDialogGetStatus",
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libSceSaveDataDialog")]
public static int SaveDataDialogGetStatus(CpuContext ctx) => ctx.SetReturn(Volatile.Read(ref _status));
public static int SaveDataDialogGetStatus(CpuContext ctx) => ctx.SetReturn(PollStatus());
[SysAbiExport(
Nid = "KK3Bdg1RWK0",
ExportName = "sceSaveDataDialogUpdateStatus",
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libSceSaveDataDialog")]
public static int SaveDataDialogUpdateStatus(CpuContext ctx) => ctx.SetReturn(Volatile.Read(ref _status));
public static int SaveDataDialogUpdateStatus(CpuContext ctx) => ctx.SetReturn(PollStatus());
// With no host UI the dialog cannot wait for user input: the first status poll after
// Open observes the dialog as already dismissed. Advancing on both UpdateStatus and
// GetStatus keeps every guest polling pattern free of infinite RUNNING loops, while
// an Open -> Close sequence with no poll in between still exercises the close path.
private static int PollStatus()
{
Interlocked.CompareExchange(ref _status, StatusFinished, StatusRunning);
return Volatile.Read(ref _status);
}
[SysAbiExport(
Nid = "en7gNVnh878",
@@ -107,11 +118,13 @@ public static class SaveDataDialogExports
return ctx.SetReturn(ErrorNotFinished);
}
// Report the affirmative button so save prompts take the confirming branch;
// buttonId 0 is the "invalid" sentinel and games may treat it as an error.
Span<byte> result = stackalloc byte[ResultSize];
result.Clear();
BinaryPrimitives.WriteInt32LittleEndian(result[0x00..], _lastMode);
BinaryPrimitives.WriteInt32LittleEndian(result[0x04..], 0);
BinaryPrimitives.WriteInt32LittleEndian(result[0x08..], 0);
BinaryPrimitives.WriteInt32LittleEndian(result[0x08..], ButtonIdAffirmative);
BinaryPrimitives.WriteUInt64LittleEndian(result[0x20..], _lastUserData);
if (!ctx.Memory.TryWrite(resultAddress, result))
@@ -31,6 +31,7 @@ public static class SaveDataExports
private const int MountResultSize = 0x40;
private static readonly object _stateGate = new();
private static readonly HashSet<int> _transactionResources = [];
private static readonly HashSet<int> _preparedTransactionResources = [];
private static string? _titleId;
private static int _nextTransactionResource;
@@ -40,6 +41,7 @@ public static class SaveDataExports
{
_titleId = string.IsNullOrWhiteSpace(titleId) ? null : SanitizePathSegment(titleId.Trim());
_transactionResources.Clear();
_preparedTransactionResources.Clear();
_nextTransactionResource = 0;
}
}
@@ -278,12 +280,104 @@ public static class SaveDataExports
lock (_stateGate)
{
_transactionResources.Remove(resource);
_preparedTransactionResources.Remove(resource);
}
TraceSaveData($"delete_transaction_resource resource={resource}");
return ctx.SetReturn(0);
}
[SysAbiExport(
Nid = "sDCBrmc61XU",
ExportName = "sceSaveDataPrepare",
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libSceSaveData")]
public static int SaveDataPrepare(CpuContext ctx)
{
var mountPointAddress = ctx[CpuRegister.Rdi];
var resource = unchecked((int)ctx[CpuRegister.Rdx]);
if (mountPointAddress == 0)
{
return ctx.SetReturn(OrbisSaveDataErrorParameter);
}
if (!TryReadFixedAscii(ctx, mountPointAddress, 16, out var mountPoint))
{
return ctx.SetReturn((int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT);
}
if (string.IsNullOrWhiteSpace(mountPoint))
{
return ctx.SetReturn(OrbisSaveDataErrorParameter);
}
lock (_stateGate)
{
if (resource != 0)
{
_preparedTransactionResources.Add(resource);
}
}
TraceSaveData($"prepare mount_point={mountPoint} resource={resource}");
return ctx.SetReturn(0);
}
[SysAbiExport(
Nid = "ie7qhZ4X0Cc",
ExportName = "sceSaveDataCommit",
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libSceSaveData")]
public static int SaveDataCommit(CpuContext ctx)
{
var commitAddress = ctx[CpuRegister.Rdi];
if (commitAddress == 0)
{
return ctx.SetReturn(OrbisSaveDataErrorParameter);
}
lock (_stateGate)
{
_preparedTransactionResources.Clear();
}
TraceSaveData($"commit commit=0x{commitAddress:X16}");
return ctx.SetReturn(0);
}
[SysAbiExport(
Nid = "uW4vfTwMQVo",
ExportName = "sceSaveDataUmount2",
Target = Generation.Gen4 | Generation.Gen5,
LibraryName = "libSceSaveData")]
public static int SaveDataUmount2(CpuContext ctx)
{
var mountPointAddress = ctx[CpuRegister.Rdi];
if (mountPointAddress == 0)
{
mountPointAddress = ctx[CpuRegister.Rsi];
}
if (mountPointAddress == 0)
{
return ctx.SetReturn(OrbisSaveDataErrorParameter);
}
if (!TryReadFixedAscii(ctx, mountPointAddress, 16, out var mountPoint))
{
return ctx.SetReturn((int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT);
}
if (string.IsNullOrWhiteSpace(mountPoint))
{
return ctx.SetReturn(OrbisSaveDataErrorParameter);
}
var unmounted = KernelMemoryCompatExports.TryUnregisterGuestPathMount(mountPoint);
TraceSaveData($"umount2 mount_point={mountPoint} unregistered={unmounted}");
return ctx.SetReturn(0);
}
private static bool TryReadSearchCond(CpuContext ctx, ulong address, out SearchCond cond)
{
cond = default;
+4
View File
@@ -8,6 +8,10 @@ SPDX-License-Identifier: GPL-2.0-or-later
<ProjectReference Include="..\SharpEmu.HLE\SharpEmu.HLE.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="SharpEmu.Libs.Tests" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Silk.NET.Vulkan" />
<PackageReference Include="Silk.NET.Vulkan.Extensions.EXT" />
@@ -0,0 +1,108 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Buffers.Binary;
using System.Text;
using SharpEmu.HLE;
using SharpEmu.Libs.Ampr;
using Xunit;
namespace SharpEmu.Libs.Tests.Ampr;
// PakDirectoryTracker reconstructs the absolute pak offset for a "next sequential chunk" read
// (offset -1) from the requested byte count. When several archived files share that byte count,
// picking by directory order alone mis-resolves out-of-order reads: Quake requested progs/h_ogre.mdl
// (0x3A34 bytes) but the tracker returned bots/navigation/death32c.nav, which shares the size and
// sits earlier in the directory, so the guest parsed NAV2 data as a brush model and aborted.
public sealed class PakDirectoryTrackerTests
{
private const int EntrySize = 64;
private const int NameLength = 56;
private readonly record struct PakEntry(string Name, uint FilePos, uint FileLen);
[Fact]
public void ResolveSequentialOffset_SizeCollision_PicksEntryNearestReadCursor()
{
const uint fileId = 0x5AA5_0001;
const uint collidingLen = 0x3A34;
var memory = new FakeCpuMemory(0x1_0000_0000, 0x1000);
var ctx = new CpuContext(memory, Generation.Gen5);
// "far" collides in size but lives early in the pak; "near" is what the guest actually wants.
LoadDirectory(ctx, fileId, memory, 0x1_0000_0000, dirFileOffset: 0x400, new[]
{
new PakEntry("far.dat", FilePos: 0x1000, FileLen: collidingLen),
new PakEntry("near.dat", FilePos: 0x9000, FileLen: collidingLen),
});
// Advance the read cursor next to the "near" entry, mimicking a burst of nearby asset reads.
PakDirectoryTracker.OnReadCompleted(ctx, fileId, destination: 0x1_0000_0000, fileOffset: 0x8800, bytesRead: 0x400);
Assert.Equal(0x9000UL, PakDirectoryTracker.ResolveSequentialOffset(fileId, collidingLen));
// Once the near entry is consumed, the same size resolves to the remaining match.
Assert.Equal(0x1000UL, PakDirectoryTracker.ResolveSequentialOffset(fileId, collidingLen));
}
[Fact]
public void ResolveSequentialOffset_ContiguousSameSizeRun_StaysInOrder()
{
const uint fileId = 0x5AA5_0002;
const uint runLen = 0x608;
var memory = new FakeCpuMemory(0x1_0000_0000, 0x1000);
var ctx = new CpuContext(memory, Generation.Gen5);
// A contiguous run of equal-size lumps (like Quake's gfx/weapons/ww_*.lmp) must still resolve
// in packed order when the guest streams them sequentially.
LoadDirectory(ctx, fileId, memory, 0x1_0000_0000, dirFileOffset: 0x400, new[]
{
new PakEntry("lump_a", FilePos: 0x1000, FileLen: runLen),
new PakEntry("lump_b", FilePos: 0x1000 + runLen, FileLen: runLen),
new PakEntry("lump_c", FilePos: 0x1000 + (runLen * 2), FileLen: runLen),
});
var first = PakDirectoryTracker.ResolveSequentialOffset(fileId, runLen);
PakDirectoryTracker.OnReadCompleted(ctx, fileId, destination: 0x1_0000_0000, fileOffset: first, bytesRead: runLen);
var second = PakDirectoryTracker.ResolveSequentialOffset(fileId, runLen);
PakDirectoryTracker.OnReadCompleted(ctx, fileId, destination: 0x1_0000_0000, fileOffset: second, bytesRead: runLen);
var third = PakDirectoryTracker.ResolveSequentialOffset(fileId, runLen);
Assert.Equal(0x1000UL, first);
Assert.Equal(0x1000UL + runLen, second);
Assert.Equal(0x1000UL + (runLen * 2), third);
}
// Feeds the tracker a synthetic PACK header + directory table exactly as the AMPR read path does:
// first the 12-byte header (which arms directory parsing), then the directory records themselves.
private static void LoadDirectory(
CpuContext ctx,
uint fileId,
FakeCpuMemory memory,
ulong destination,
ulong dirFileOffset,
PakEntry[] entries)
{
Span<byte> header = stackalloc byte[12];
header[0] = (byte)'P';
header[1] = (byte)'A';
header[2] = (byte)'C';
header[3] = (byte)'K';
BinaryPrimitives.WriteUInt32LittleEndian(header[4..8], (uint)dirFileOffset);
BinaryPrimitives.WriteUInt32LittleEndian(header[8..12], (uint)(entries.Length * EntrySize));
memory.TryWrite(destination, header);
PakDirectoryTracker.OnReadCompleted(ctx, fileId, destination, fileOffset: 0, bytesRead: 12);
var table = new byte[entries.Length * EntrySize];
for (var i = 0; i < entries.Length; i++)
{
var record = table.AsSpan(i * EntrySize, EntrySize);
var name = Encoding.ASCII.GetBytes(entries[i].Name);
name.AsSpan(0, Math.Min(name.Length, NameLength)).CopyTo(record);
BinaryPrimitives.WriteUInt32LittleEndian(record.Slice(56, 4), entries[i].FilePos);
BinaryPrimitives.WriteUInt32LittleEndian(record.Slice(60, 4), entries[i].FileLen);
}
memory.TryWrite(destination, table);
PakDirectoryTracker.OnReadCompleted(ctx, fileId, destination, dirFileOffset, (ulong)table.Length);
}
}
@@ -0,0 +1,68 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using SharpEmu.HLE;
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
{
private readonly ulong _base;
private readonly byte[] _storage;
public FakeCpuMemory(ulong baseAddress, int size)
{
_base = baseAddress;
_storage = new byte[size];
}
public bool TryRead(ulong virtualAddress, Span<byte> destination)
{
if (!TryResolve(virtualAddress, destination.Length, out var offset))
{
return false;
}
_storage.AsSpan(offset, destination.Length).CopyTo(destination);
return true;
}
public bool TryWrite(ulong virtualAddress, ReadOnlySpan<byte> source)
{
if (!TryResolve(virtualAddress, source.Length, out var offset))
{
return false;
}
source.CopyTo(_storage.AsSpan(offset, source.Length));
return true;
}
public ulong WriteCString(ulong virtualAddress, string text)
{
var bytes = System.Text.Encoding.UTF8.GetBytes(text);
TryWrite(virtualAddress, bytes);
TryWrite(virtualAddress + (ulong)bytes.Length, stackalloc byte[] { 0 });
return virtualAddress;
}
private bool TryResolve(ulong virtualAddress, int length, out int offset)
{
offset = 0;
if (virtualAddress < _base)
{
return false;
}
var relative = virtualAddress - _base;
if (relative + (ulong)length > (ulong)_storage.Length)
{
return false;
}
offset = (int)relative;
return true;
}
}
@@ -0,0 +1,80 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using SharpEmu.HLE;
using SharpEmu.Libs.Json;
using Xunit;
namespace SharpEmu.Libs.Tests.Json;
// These NIDs came back "unresolved" in the Quake (PPSA01880) import log right before its
// access violation. This asserts they now resolve to the Json handlers and dispatch cleanly,
// which is the plumbing the direct-call tests cannot cover.
[Collection("JsonObjectHeap")]
public sealed class JsonExportRegistrationTests
{
private static readonly (string Nid, string Name)[] ExpectedExports =
{
("qBMjqyBn3OM", "_ZN3sce4Json5ValueC1Ev"),
("5yHuiWXo2gg", "_ZN3sce4Json5Value3setEb"),
("QxVVYhP-mvg", "_ZN3sce4Json5Value3setEl"),
("SIe1ZmW7e7s", "_ZN3sce4Json5Value3setEm"),
("BSmWDIkV4w4", "_ZN3sce4Json5Value3setEd"),
("IKQimvG9Wqs", "_ZN3sce4Json5Value3setENS0_9ValueTypeE"),
("6l3Bv2gysNc", "_ZN3sce4Json5Value3setERKNS0_6StringE"),
("9KUZFjI1IxA", "_ZN3sce4Json6StringC1EPKc"),
("cG1VE2HMl6c", "_ZN3sce4Json6StringD1Ev"),
("+drDFyAS6u4", "_ZN3sce4Json11Initializer27setGlobalNullAccessCallbackEPFRKNS0_5ValueENS0_9ValueTypeEPS3_PvES7_"),
};
private static ModuleManager CreateRegisteredManager()
{
var manager = new ModuleManager();
manager.RegisterFromAssembly(typeof(JsonValueExports).Assembly, Generation.Gen5);
return manager;
}
[Fact]
public void QuakeUnresolvedJsonNids_ResolveToJsonExports()
{
var manager = CreateRegisteredManager();
foreach (var (nid, name) in ExpectedExports)
{
Assert.True(manager.TryGetExport(nid, out var export), $"NID {nid} did not register.");
Assert.Equal(name, export.Name);
Assert.Equal("libSceJson", export.LibraryName);
}
}
[Fact]
public void SetGlobalNullAccessCallback_StoresHookAndReturnsOk()
{
JsonObjectHeap.ResetForTests();
var manager = CreateRegisteredManager();
var ctx = new CpuContext(new FakeCpuMemory(0x1_0000_0000, 0x1000), Generation.Gen5);
ctx[CpuRegister.Rdi] = 0x1_0000_0000; // Initializer instance
ctx[CpuRegister.Rsi] = 0x8_0012_3456; // guest callback
ctx[CpuRegister.Rdx] = 0x1_0000_0800; // user context
Assert.True(manager.TryDispatch("+drDFyAS6u4", ctx, out var result));
Assert.Equal(OrbisGen2Result.ORBIS_GEN2_OK, result);
Assert.Equal(0UL, ctx[CpuRegister.Rax]);
Assert.Equal(0x8_0012_3456UL, JsonObjectHeap.GlobalNullAccessCallback);
Assert.Equal(0x1_0000_0800UL, JsonObjectHeap.GlobalNullAccessCallbackContext);
}
[Fact]
public void DispatchValueConstructor_RunsHandlerAndReturnsThis()
{
JsonObjectHeap.ResetForTests();
var manager = CreateRegisteredManager();
var ctx = new CpuContext(new FakeCpuMemory(0x1_0000_0000, 0x1000), Generation.Gen5);
ctx[CpuRegister.Rdi] = 0x1_0000_0000;
Assert.True(manager.TryDispatch("qBMjqyBn3OM", ctx, out var result));
Assert.Equal(OrbisGen2Result.ORBIS_GEN2_OK, result);
Assert.Equal(0x1_0000_0000UL, ctx[CpuRegister.Rax]);
Assert.Equal(JsonValueKind.Null, JsonObjectHeap.Values[0x1_0000_0000].Kind);
}
}
@@ -0,0 +1,188 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using SharpEmu.HLE;
using SharpEmu.Libs.Json;
using Xunit;
namespace SharpEmu.Libs.Tests.Json;
// JsonObjectHeap is shared static state; both Json test classes join one collection so xUnit
// does not run them in parallel against it.
[Collection("JsonObjectHeap")]
public sealed class JsonValueExportsTests
{
private const ulong ThisAddress = 0x1_0000_0000;
private const ulong StringAddress = 0x1_0000_1000;
private const ulong TextAddress = 0x1_0000_2000;
private readonly FakeCpuMemory _memory = new(0x1_0000_0000, 0x10000);
private readonly CpuContext _ctx;
public JsonValueExportsTests()
{
JsonObjectHeap.ResetForTests();
_ctx = new CpuContext(_memory, Generation.Gen5);
}
[Fact]
public void ValueDefaultConstructor_RegistersNullAndReturnsThis()
{
_ctx[CpuRegister.Rdi] = ThisAddress;
JsonValueExports.ValueDefaultConstructor(_ctx);
Assert.Equal(ThisAddress, _ctx[CpuRegister.Rax]);
Assert.Equal(JsonValueKind.Null, JsonObjectHeap.Values[ThisAddress].Kind);
}
[Theory]
[InlineData(0UL, false)]
[InlineData(1UL, true)]
[InlineData(0xFFFF_FF00UL, false)] // only the low byte is the bool; 0x00 low byte => false
public void ValueSetBoolean_StoresLowByte(ulong raw, bool expected)
{
_ctx[CpuRegister.Rdi] = ThisAddress;
_ctx[CpuRegister.Rsi] = raw;
JsonValueExports.ValueSetBoolean(_ctx);
var state = JsonObjectHeap.Values[ThisAddress];
Assert.Equal(JsonValueKind.Boolean, state.Kind);
Assert.Equal(expected, state.Boolean);
Assert.Equal(ThisAddress, _ctx[CpuRegister.Rax]);
}
[Fact]
public void ValueSetInteger_RoundTripsSignedValue()
{
_ctx[CpuRegister.Rdi] = ThisAddress;
_ctx[CpuRegister.Rsi] = unchecked((ulong)-42L);
JsonValueExports.ValueSetInteger(_ctx);
var state = JsonObjectHeap.Values[ThisAddress];
Assert.Equal(JsonValueKind.Integer, state.Kind);
Assert.Equal(-42L, state.Integer);
}
[Fact]
public void ValueSetUnsigned_RoundTripsFullWidth()
{
_ctx[CpuRegister.Rdi] = ThisAddress;
_ctx[CpuRegister.Rsi] = ulong.MaxValue;
JsonValueExports.ValueSetUnsigned(_ctx);
var state = JsonObjectHeap.Values[ThisAddress];
Assert.Equal(JsonValueKind.UInteger, state.Kind);
Assert.Equal(ulong.MaxValue, state.UnsignedInteger);
}
[Fact]
public void ValueSetReal_ReadsDoubleFromXmm0()
{
_ctx[CpuRegister.Rdi] = ThisAddress;
_ctx.SetXmmRegister(0, unchecked((ulong)BitConverter.DoubleToInt64Bits(3.14159)), 0);
JsonValueExports.ValueSetReal(_ctx);
var state = JsonObjectHeap.Values[ThisAddress];
Assert.Equal(JsonValueKind.Real, state.Kind);
Assert.Equal(3.14159, state.Real, precision: 10);
}
[Fact]
public void ValueSetCString_ReadsGuestString()
{
_memory.WriteCString(TextAddress, "hello json");
_ctx[CpuRegister.Rdi] = ThisAddress;
_ctx[CpuRegister.Rsi] = TextAddress;
JsonValueExports.ValueSetCString(_ctx);
var state = JsonObjectHeap.Values[ThisAddress];
Assert.Equal(JsonValueKind.String, state.Kind);
Assert.Equal("hello json", state.Text);
}
[Fact]
public void ValueSetType_KeepsRawGuestEnumValue()
{
_ctx[CpuRegister.Rdi] = ThisAddress;
_ctx[CpuRegister.Rsi] = 7;
JsonValueExports.ValueSetType(_ctx);
var state = JsonObjectHeap.Values[ThisAddress];
Assert.Equal(JsonValueKind.ExplicitType, state.Kind);
Assert.Equal(7u, state.ExplicitType);
}
[Fact]
public void StringConstructThenValueSetString_CopiesText()
{
_memory.WriteCString(TextAddress, "from string object");
_ctx[CpuRegister.Rdi] = StringAddress;
_ctx[CpuRegister.Rsi] = TextAddress;
JsonValueExports.StringCStringConstructor(_ctx);
Assert.Equal("from string object", JsonObjectHeap.Strings[StringAddress]);
Assert.Equal(StringAddress, _ctx[CpuRegister.Rax]);
_ctx[CpuRegister.Rdi] = ThisAddress;
_ctx[CpuRegister.Rsi] = StringAddress;
JsonValueExports.ValueSetString(_ctx);
var state = JsonObjectHeap.Values[ThisAddress];
Assert.Equal(JsonValueKind.String, state.Kind);
Assert.Equal("from string object", state.Text);
}
[Fact]
public void ValueSetString_MissingStringShadow_DegradesToEmpty()
{
_ctx[CpuRegister.Rdi] = ThisAddress;
_ctx[CpuRegister.Rsi] = StringAddress; // never constructed
JsonValueExports.ValueSetString(_ctx);
var state = JsonObjectHeap.Values[ThisAddress];
Assert.Equal(JsonValueKind.String, state.Kind);
Assert.Equal(string.Empty, state.Text);
}
[Fact]
public void Destructors_RemoveShadowState()
{
_ctx[CpuRegister.Rdi] = ThisAddress;
JsonValueExports.ValueDefaultConstructor(_ctx);
_ctx[CpuRegister.Rdi] = StringAddress;
JsonValueExports.StringDefaultConstructor(_ctx);
Assert.True(JsonObjectHeap.Values.ContainsKey(ThisAddress));
Assert.True(JsonObjectHeap.Strings.ContainsKey(StringAddress));
_ctx[CpuRegister.Rdi] = ThisAddress;
JsonValueExports.ValueDestructor(_ctx);
_ctx[CpuRegister.Rdi] = StringAddress;
JsonValueExports.StringDestructor(_ctx);
Assert.False(JsonObjectHeap.Values.ContainsKey(ThisAddress));
Assert.False(JsonObjectHeap.Strings.ContainsKey(StringAddress));
Assert.Equal(0UL, _ctx[CpuRegister.Rax]);
}
[Fact]
public void ValueSetCString_FaultingPointer_DegradesToEmptyString()
{
_ctx[CpuRegister.Rdi] = ThisAddress;
_ctx[CpuRegister.Rsi] = 0xDEAD_0000_0000; // outside the mapped region
JsonValueExports.ValueSetCString(_ctx);
var state = JsonObjectHeap.Values[ThisAddress];
Assert.Equal(JsonValueKind.String, state.Kind);
Assert.Equal(string.Empty, state.Text);
}
}
@@ -0,0 +1,22 @@
<!--
Copyright (C) 2026 SharpEmu Emulator Project
SPDX-License-Identifier: GPL-2.0-or-later
-->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<IsPackable>false</IsPackable>
<GenerateDocumentationFile>false</GenerateDocumentationFile>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\SharpEmu.Libs\SharpEmu.Libs.csproj" />
<ProjectReference Include="..\..\src\SharpEmu.HLE\SharpEmu.HLE.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio" />
</ItemGroup>
</Project>
@@ -0,0 +1,212 @@
{
"version": 2,
"dependencies": {
"net10.0": {
"Microsoft.NET.Test.Sdk": {
"type": "Direct",
"requested": "[17.14.1, )",
"resolved": "17.14.1",
"contentHash": "HJKqKOE+vshXra2aEHpi2TlxYX7Z9VFYkr+E5rwEvHC8eIXiyO+K9kNm8vmNom3e2rA56WqxU+/N9NJlLGXsJQ==",
"dependencies": {
"Microsoft.CodeCoverage": "17.14.1",
"Microsoft.TestPlatform.TestHost": "17.14.1"
}
},
"xunit": {
"type": "Direct",
"requested": "[2.9.3, )",
"resolved": "2.9.3",
"contentHash": "TlXQBinK35LpOPKHAqbLY4xlEen9TBafjs0V5KnA4wZsoQLQJiirCR4CbIXvOH8NzkW4YeJKP5P/Bnrodm0h9Q==",
"dependencies": {
"xunit.analyzers": "1.18.0",
"xunit.assert": "2.9.3",
"xunit.core": "[2.9.3]"
}
},
"xunit.runner.visualstudio": {
"type": "Direct",
"requested": "[3.1.1, )",
"resolved": "3.1.1",
"contentHash": "gNu2zhnuwjq5vQlU4S7yK/lfaKZDLmtcu+vTjnhfTlMAUYn+Hmgu8IIX0UCwWepYkk+Szx03DHx1bDnc9Fd+9w=="
},
"Microsoft.CodeCoverage": {
"type": "Transitive",
"resolved": "17.14.1",
"contentHash": "pmTrhfFIoplzFVbhVwUquT+77CbGH+h4/3mBpdmIlYtBi9nAB+kKI6dN3A/nV4DFi3wLLx/BlHIPK+MkbQ6Tpg=="
},
"Microsoft.DotNet.PlatformAbstractions": {
"type": "Transitive",
"resolved": "3.1.6",
"contentHash": "jek4XYaQ/PGUwDKKhwR8K47Uh1189PFzMeLqO83mXrXQVIpARZCcfuDedH50YDTepBkfijCZN5U/vZi++erxtg=="
},
"Microsoft.Extensions.DependencyModel": {
"type": "Transitive",
"resolved": "9.0.9",
"contentHash": "fNGvKct2De8ghm0Bpfq0iWthtzIWabgOTi+gJhNOPhNJIowXNEUE2eZNW/zNCzrHVA3PXg2yZ+3cWZndC2IqYA=="
},
"Microsoft.TestPlatform.ObjectModel": {
"type": "Transitive",
"resolved": "17.14.1",
"contentHash": "xTP1W6Mi6SWmuxd3a+jj9G9UoC850WGwZUps1Wah9r1ZxgXhdJfj1QqDLJkFjHDCvN42qDL2Ps5KjQYWUU0zcQ=="
},
"Microsoft.TestPlatform.TestHost": {
"type": "Transitive",
"resolved": "17.14.1",
"contentHash": "d78LPzGKkJwsJXAQwsbJJ7LE7D1wB+rAyhHHAaODF+RDSQ0NgMjDFkSA1Djw18VrxO76GlKAjRUhl+H8NL8Z+Q==",
"dependencies": {
"Microsoft.TestPlatform.ObjectModel": "17.14.1",
"Newtonsoft.Json": "13.0.3"
}
},
"Newtonsoft.Json": {
"type": "Transitive",
"resolved": "13.0.3",
"contentHash": "HrC5BXdl00IP9zeV+0Z848QWPAoCr9P3bDEZguI+gkLcBKAOxix/tLEAAHC+UvDNPv4a2d18lOReHMOagPa+zQ=="
},
"Silk.NET.Core": {
"type": "Transitive",
"resolved": "2.23.0",
"contentHash": "D7AT/nnwlB+4RZ84XY8QNGBZMJI5z9l4CSSETIJ1wCfRJzRt/341y3MRZ4HbnFz4r/IGaWOEZr86iE+0/65yyQ==",
"dependencies": {
"Microsoft.DotNet.PlatformAbstractions": "3.1.6",
"Microsoft.Extensions.DependencyModel": "9.0.9"
}
},
"Silk.NET.GLFW": {
"type": "Transitive",
"resolved": "2.23.0",
"contentHash": "UIs4sH57xlPUNHQ/1bt9rymPWlGy8IMDCNv86h0iM4TOA1CkIx0XM/n/tA4AReh1zQkNrvkxPEdZ3Blvy1dyXg==",
"dependencies": {
"Silk.NET.Core": "2.23.0",
"Ultz.Native.GLFW": "3.4.0"
}
},
"Silk.NET.Maths": {
"type": "Transitive",
"resolved": "2.23.0",
"contentHash": "r8PdIVzME8EH0qAgbmRPO87I4GfgR2j8TofT7EMuRJDf1QluoQwnVypDoFJjQ2ZBSRsGYk5unYxxogI05Ogsmw=="
},
"Silk.NET.Windowing.Common": {
"type": "Transitive",
"resolved": "2.23.0",
"contentHash": "ThStSinmY9KQI8DGiF5XEhkLJVnBcgRTBTzL9ijg1wMZAYuckz7ykrNw04fjRm2Gryh6tCNGbvz2XaY0efeFzg==",
"dependencies": {
"Silk.NET.Core": "2.23.0",
"Silk.NET.Maths": "2.23.0"
}
},
"Silk.NET.Windowing.Glfw": {
"type": "Transitive",
"resolved": "2.23.0",
"contentHash": "aYBudKmENmvLRn9p15HbdvlQTnnXskcDfTfbYwSb/4fr263rGLwYuDw/txUEc2jihHJiWCp5+75Y7z5wTJWl7g==",
"dependencies": {
"Silk.NET.GLFW": "2.23.0",
"Silk.NET.Windowing.Common": "2.23.0"
}
},
"Ultz.Native.GLFW": {
"type": "Transitive",
"resolved": "3.4.0",
"contentHash": "Iy22JopynbOJ32vA0lBhFEzGi65GQJBuJHYBYRBpydrDpNoTiHnjIXfA65Gu+8qsOr/ZEoIF8r9aHCgAXuO6DA=="
},
"xunit.abstractions": {
"type": "Transitive",
"resolved": "2.0.3",
"contentHash": "pot1I4YOxlWjIb5jmwvvQNbTrZ3lJQ+jUGkGjWE3hEFM0l5gOnBWS+H3qsex68s5cO52g+44vpGzhAt+42vwKg=="
},
"xunit.analyzers": {
"type": "Transitive",
"resolved": "1.18.0",
"contentHash": "OtFMHN8yqIcYP9wcVIgJrq01AfTxijjAqVDy/WeQVSyrDC1RzBWeQPztL49DN2syXRah8TYnfvk035s7L95EZQ=="
},
"xunit.assert": {
"type": "Transitive",
"resolved": "2.9.3",
"contentHash": "/Kq28fCE7MjOV42YLVRAJzRF0WmEqsmflm0cfpMjGtzQ2lR5mYVj1/i0Y8uDAOLczkL3/jArrwehfMD0YogMAA=="
},
"xunit.core": {
"type": "Transitive",
"resolved": "2.9.3",
"contentHash": "BiAEvqGvyme19wE0wTKdADH+NloYqikiU0mcnmiNyXaF9HyHmE6sr/3DC5vnBkgsWaE6yPyWszKSPSApWdRVeQ==",
"dependencies": {
"xunit.extensibility.core": "[2.9.3]",
"xunit.extensibility.execution": "[2.9.3]"
}
},
"xunit.extensibility.core": {
"type": "Transitive",
"resolved": "2.9.3",
"contentHash": "kf3si0YTn2a8J8eZNb+zFpwfoyvIrQ7ivNk5ZYA5yuYk1bEtMe4DxJ2CF/qsRgmEnDr7MnW1mxylBaHTZ4qErA==",
"dependencies": {
"xunit.abstractions": "2.0.3"
}
},
"xunit.extensibility.execution": {
"type": "Transitive",
"resolved": "2.9.3",
"contentHash": "yMb6vMESlSrE3Wfj7V6cjQ3S4TXdXpRqYeNEI3zsX31uTsGMJjEw6oD5F5u1cHnMptjhEECnmZSsPxB6ChZHDQ==",
"dependencies": {
"xunit.extensibility.core": "[2.9.3]"
}
},
"sharpemu.hle": {
"type": "Project",
"dependencies": {
"SharpEmu.Logging": "[1.0.0, )"
}
},
"sharpemu.libs": {
"type": "Project",
"dependencies": {
"SharpEmu.HLE": "[1.0.0, )",
"Silk.NET.Vulkan": "[2.23.0, )",
"Silk.NET.Vulkan.Extensions.EXT": "[2.23.0, )",
"Silk.NET.Vulkan.Extensions.KHR": "[2.23.0, )",
"Silk.NET.Windowing": "[2.23.0, )"
}
},
"sharpemu.logging": {
"type": "Project"
},
"Silk.NET.Vulkan": {
"type": "CentralTransitive",
"requested": "[2.23.0, )",
"resolved": "2.23.0",
"contentHash": "3/irtlSWXZ3eTi8N6nelI6L34NTB8ZJHpqVMNzZx2aX7Ek9YEQ34NoQW8/Tljrtmkg8KRhHW8hKTEzZaKV8PgA==",
"dependencies": {
"Silk.NET.Core": "2.23.0"
}
},
"Silk.NET.Vulkan.Extensions.EXT": {
"type": "CentralTransitive",
"requested": "[2.23.0, )",
"resolved": "2.23.0",
"contentHash": "+Oth189ksRiL6HvGCwIdnsYHawqrbO8y49u1H61z3wsfcHhQZeVDYe/wF5LD7fk3NcdgDvwFD3mLm1QWhdZySw==",
"dependencies": {
"Silk.NET.Core": "2.23.0",
"Silk.NET.Vulkan": "2.23.0"
}
},
"Silk.NET.Vulkan.Extensions.KHR": {
"type": "CentralTransitive",
"requested": "[2.23.0, )",
"resolved": "2.23.0",
"contentHash": "uRaf4j+SmH3DumjSSSUbFg33BnsGZUyXGj93O9NgGKZSJN3OTmNmQDxRew+/KiVLcgH6qzbto8aNGZ++j9GFWg==",
"dependencies": {
"Silk.NET.Core": "2.23.0",
"Silk.NET.Vulkan": "2.23.0"
}
},
"Silk.NET.Windowing": {
"type": "CentralTransitive",
"requested": "[2.23.0, )",
"resolved": "2.23.0",
"contentHash": "OPNPmt/lRyUKVYrFLQXVxyATqD3MKLc1iY1oKx1/2GppgmZxVZPwN12tekrQ4C7408kgB1L5JD1Wnirqqeb2kg==",
"dependencies": {
"Silk.NET.Windowing.Common": "2.23.0",
"Silk.NET.Windowing.Glfw": "2.23.0"
}
}
}
}
}
@@ -0,0 +1,412 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
// Executes the SharpEmu-emitted "exec" conformance shader on a real Vulkan
// device and compares the buffer results against CPU-computed expected values.
//
// The shader (exec-cs.spv, produced by SharpEmu.Tools.ShaderDump) was
// translated by SharpEmu from hand-assembled Gen5 instruction words and stores
// results to guestBuffers[0]:
// [0] v_fmac_f32 -> fma(1.5f, 2.25f, 10.0f)
// [1] v_mul_hi_i32 -> high 32 bits of (int)0x7FFFFFFF * (int)0x00010003
// [2] v_mul_lo_i32 -> low 32 bits of the same product
// [3] store attempted with EXEC=0 -> must NOT land (sentinel remains)
// [4] store after EXEC restored -> 1.5f (0x3FC00000)
// Every other word of the buffer must still hold the sentinel afterwards.
//
// Creating the compute pipeline doubles as a driver-acceptance check for the
// emitted SPIR-V; the dispatch then verifies the arithmetic numerically.
//
// Usage: SharpEmu.Tools.GpuConformance <path-to-exec-cs.spv>
using Silk.NET.Core.Native;
using Silk.NET.Vulkan;
const uint Sentinel = 0xCAFEBABE;
// Must match the 64-byte global-memory binding ShaderDump constructs for the
// exec program.
const ulong BufferSize = 64;
var expectedFma = BitConverter.SingleToUInt32Bits(
MathF.FusedMultiplyAdd(1.5f, 2.25f, 10.0f));
var product = (long)0x7FFFFFFF * 0x00010003;
var expectedHi = (uint)(product >> 32);
var expectedLo = (uint)product;
var expectedRestored = BitConverter.SingleToUInt32Bits(1.5f);
unsafe
{
var spvPath = args.Length > 0
? args[0]
: throw new InvalidOperationException(
"usage: SharpEmu.Tools.GpuConformance <path-to-exec-cs.spv>");
var code = File.ReadAllBytes(spvPath);
var vk = Vk.GetApi();
var appName = (byte*)SilkMarshal.StringToPtr("SharpEmuGpuConformance");
var appInfo = new ApplicationInfo
{
SType = StructureType.ApplicationInfo,
PApplicationName = appName,
ApiVersion = Vk.Version13,
};
var instanceInfo = new InstanceCreateInfo
{
SType = StructureType.InstanceCreateInfo,
PApplicationInfo = &appInfo,
};
Check(vk.CreateInstance(in instanceInfo, null, out var instance), "vkCreateInstance");
uint deviceCount = 0;
vk.EnumeratePhysicalDevices(instance, &deviceCount, null);
if (deviceCount == 0)
{
Console.WriteLine("no Vulkan devices found");
return;
}
var physicalDevices = new PhysicalDevice[deviceCount];
fixed (PhysicalDevice* pDevices = physicalDevices)
{
vk.EnumeratePhysicalDevices(instance, &deviceCount, pDevices);
}
// Prefer the first discrete GPU; fall back to the first device.
var physical = physicalDevices[0];
foreach (var candidate in physicalDevices)
{
vk.GetPhysicalDeviceProperties(candidate, out var props);
if (props.DeviceType == PhysicalDeviceType.DiscreteGpu)
{
physical = candidate;
break;
}
}
vk.GetPhysicalDeviceProperties(physical, out var chosenProps);
Console.WriteLine(
$"executing on: {SilkMarshal.PtrToString((nint)chosenProps.DeviceName)}");
uint familyCount = 0;
vk.GetPhysicalDeviceQueueFamilyProperties(physical, &familyCount, null);
var families = new QueueFamilyProperties[familyCount];
fixed (QueueFamilyProperties* pFamilies = families)
{
vk.GetPhysicalDeviceQueueFamilyProperties(physical, &familyCount, pFamilies);
}
uint? computeFamilyFound = null;
for (uint index = 0; index < familyCount; index++)
{
if (families[index].QueueFlags.HasFlag(QueueFlags.ComputeBit))
{
computeFamilyFound = index;
break;
}
}
var computeFamily = computeFamilyFound
?? throw new InvalidOperationException("device has no compute-capable queue family");
// The emitted SPIR-V declares the Int64 capability.
vk.GetPhysicalDeviceFeatures(physical, out var supportedFeatures);
if (!supportedFeatures.ShaderInt64)
{
throw new InvalidOperationException(
"device does not support shaderInt64, which the emitted SPIR-V requires");
}
var priority = 1f;
var queueInfo = new DeviceQueueCreateInfo
{
SType = StructureType.DeviceQueueCreateInfo,
QueueFamilyIndex = computeFamily,
QueueCount = 1,
PQueuePriorities = &priority,
};
var features = new PhysicalDeviceFeatures { ShaderInt64 = true };
var deviceInfo = new DeviceCreateInfo
{
SType = StructureType.DeviceCreateInfo,
QueueCreateInfoCount = 1,
PQueueCreateInfos = &queueInfo,
PEnabledFeatures = &features,
};
Check(vk.CreateDevice(physical, in deviceInfo, null, out var device), "vkCreateDevice");
vk.GetDeviceQueue(device, computeFamily, 0, out var queue);
// Storage buffer, host-visible so the CPU can prefill and read back.
var bufferInfo = new BufferCreateInfo
{
SType = StructureType.BufferCreateInfo,
Size = BufferSize,
Usage = BufferUsageFlags.StorageBufferBit,
SharingMode = SharingMode.Exclusive,
};
Check(vk.CreateBuffer(device, in bufferInfo, null, out var buffer), "vkCreateBuffer");
vk.GetBufferMemoryRequirements(device, buffer, out var requirements);
vk.GetPhysicalDeviceMemoryProperties(physical, out var memoryProperties);
uint memoryType = uint.MaxValue;
for (var index = 0; index < memoryProperties.MemoryTypeCount; index++)
{
var flags = memoryProperties.MemoryTypes[index].PropertyFlags;
if ((requirements.MemoryTypeBits & (1u << index)) != 0 &&
flags.HasFlag(MemoryPropertyFlags.HostVisibleBit) &&
flags.HasFlag(MemoryPropertyFlags.HostCoherentBit))
{
memoryType = (uint)index;
break;
}
}
if (memoryType == uint.MaxValue)
{
throw new InvalidOperationException(
"no host-visible, host-coherent memory type available for the readback buffer");
}
var allocateInfo = new MemoryAllocateInfo
{
SType = StructureType.MemoryAllocateInfo,
AllocationSize = requirements.Size,
MemoryTypeIndex = memoryType,
};
Check(vk.AllocateMemory(device, in allocateInfo, null, out var memory), "vkAllocateMemory");
Check(vk.BindBufferMemory(device, buffer, memory, 0), "vkBindBufferMemory");
void* mapped;
Check(vk.MapMemory(device, memory, 0, BufferSize, 0, &mapped), "vkMapMemory");
var words = (uint*)mapped;
for (var index = 0; index < (int)(BufferSize / sizeof(uint)); index++)
{
words[index] = Sentinel;
}
// SharpEmu emits all guest buffers as one descriptor array at set 0,
// binding 0; this conformance shader uses a single buffer.
ShaderModule module;
fixed (byte* pCode = code)
{
var moduleInfo = new ShaderModuleCreateInfo
{
SType = StructureType.ShaderModuleCreateInfo,
CodeSize = (nuint)code.Length,
PCode = (uint*)pCode,
};
Check(vk.CreateShaderModule(device, in moduleInfo, null, out module), "vkCreateShaderModule");
}
var layoutBinding = new DescriptorSetLayoutBinding
{
Binding = 0,
DescriptorType = DescriptorType.StorageBuffer,
DescriptorCount = 1,
StageFlags = ShaderStageFlags.ComputeBit,
};
var setLayoutInfo = new DescriptorSetLayoutCreateInfo
{
SType = StructureType.DescriptorSetLayoutCreateInfo,
BindingCount = 1,
PBindings = &layoutBinding,
};
Check(
vk.CreateDescriptorSetLayout(device, in setLayoutInfo, null, out var setLayout),
"vkCreateDescriptorSetLayout");
var pipelineLayoutInfo = new PipelineLayoutCreateInfo
{
SType = StructureType.PipelineLayoutCreateInfo,
SetLayoutCount = 1,
PSetLayouts = &setLayout,
};
Check(
vk.CreatePipelineLayout(device, in pipelineLayoutInfo, null, out var pipelineLayout),
"vkCreatePipelineLayout");
var entryName = (byte*)SilkMarshal.StringToPtr("main");
var pipelineInfo = new ComputePipelineCreateInfo
{
SType = StructureType.ComputePipelineCreateInfo,
Stage = new PipelineShaderStageCreateInfo
{
SType = StructureType.PipelineShaderStageCreateInfo,
Stage = ShaderStageFlags.ComputeBit,
Module = module,
PName = entryName,
},
Layout = pipelineLayout,
};
Check(
vk.CreateComputePipelines(device, default, 1, in pipelineInfo, null, out var pipeline),
"vkCreateComputePipelines");
Console.WriteLine("driver accepted the SPIR-V (pipeline created)");
var poolSize = new DescriptorPoolSize
{
Type = DescriptorType.StorageBuffer,
DescriptorCount = 1,
};
var poolInfo = new DescriptorPoolCreateInfo
{
SType = StructureType.DescriptorPoolCreateInfo,
MaxSets = 1,
PoolSizeCount = 1,
PPoolSizes = &poolSize,
};
Check(vk.CreateDescriptorPool(device, in poolInfo, null, out var pool), "vkCreateDescriptorPool");
var setAllocateInfo = new DescriptorSetAllocateInfo
{
SType = StructureType.DescriptorSetAllocateInfo,
DescriptorPool = pool,
DescriptorSetCount = 1,
PSetLayouts = &setLayout,
};
Check(vk.AllocateDescriptorSets(device, in setAllocateInfo, out var descriptorSet), "vkAllocateDescriptorSets");
var descriptorBuffer = new DescriptorBufferInfo
{
Buffer = buffer,
Offset = 0,
Range = BufferSize,
};
var write = new WriteDescriptorSet
{
SType = StructureType.WriteDescriptorSet,
DstSet = descriptorSet,
DstBinding = 0,
DstArrayElement = 0,
DescriptorCount = 1,
DescriptorType = DescriptorType.StorageBuffer,
PBufferInfo = &descriptorBuffer,
};
vk.UpdateDescriptorSets(device, 1, in write, 0, null);
var commandPoolInfo = new CommandPoolCreateInfo
{
SType = StructureType.CommandPoolCreateInfo,
QueueFamilyIndex = computeFamily,
};
Check(vk.CreateCommandPool(device, in commandPoolInfo, null, out var commandPool), "vkCreateCommandPool");
var commandBufferInfo = new CommandBufferAllocateInfo
{
SType = StructureType.CommandBufferAllocateInfo,
CommandPool = commandPool,
Level = CommandBufferLevel.Primary,
CommandBufferCount = 1,
};
Check(vk.AllocateCommandBuffers(device, in commandBufferInfo, out var commandBuffer), "vkAllocateCommandBuffers");
var beginInfo = new CommandBufferBeginInfo
{
SType = StructureType.CommandBufferBeginInfo,
};
Check(vk.BeginCommandBuffer(commandBuffer, in beginInfo), "vkBeginCommandBuffer");
vk.CmdBindPipeline(commandBuffer, PipelineBindPoint.Compute, pipeline);
vk.CmdBindDescriptorSets(
commandBuffer,
PipelineBindPoint.Compute,
pipelineLayout,
0,
1,
in descriptorSet,
0,
null);
vk.CmdDispatch(commandBuffer, 1, 1, 1);
var barrier = new MemoryBarrier
{
SType = StructureType.MemoryBarrier,
SrcAccessMask = AccessFlags.ShaderWriteBit,
DstAccessMask = AccessFlags.HostReadBit,
};
vk.CmdPipelineBarrier(
commandBuffer,
PipelineStageFlags.ComputeShaderBit,
PipelineStageFlags.HostBit,
0,
1,
in barrier,
0,
null,
0,
null);
Check(vk.EndCommandBuffer(commandBuffer), "vkEndCommandBuffer");
var submitInfo = new SubmitInfo
{
SType = StructureType.SubmitInfo,
CommandBufferCount = 1,
PCommandBuffers = &commandBuffer,
};
Check(vk.QueueSubmit(queue, 1, in submitInfo, default), "vkQueueSubmit");
Check(vk.QueueWaitIdle(queue), "vkQueueWaitIdle");
var results = new (string Name, uint Actual, uint Expected)[]
{
("v_fmac_f32 fma(1.5, 2.25, 10.0)", words[0], expectedFma),
("v_mul_hi_i32 hi(0x7FFFFFFF*0x10003)", words[1], expectedHi),
("v_mul_lo_i32 lo(0x7FFFFFFF*0x10003)", words[2], expectedLo),
("exec=0 store suppressed (offset 12 sentinel)", words[3], Sentinel),
("store after exec restore (offset 16)", words[4], expectedRestored),
};
var failures = 0;
foreach (var (name, actual, expected) in results)
{
var status = actual == expected ? "PASS" : "FAIL";
if (actual != expected)
{
failures++;
}
Console.WriteLine($"{status} {name}: gpu=0x{actual:X8} expected=0x{expected:X8}");
}
var totalWords = (int)(BufferSize / sizeof(uint));
var trailingClobbered = 0;
for (var index = results.Length; index < totalWords; index++)
{
if (words[index] != Sentinel)
{
trailingClobbered++;
Console.WriteLine(
$"FAIL trailing word [{index}] clobbered: gpu=0x{words[index]:X8} expected=0x{Sentinel:X8}");
}
}
failures += trailingClobbered;
if (trailingClobbered == 0)
{
Console.WriteLine(
$"PASS trailing words [{results.Length}..{totalWords - 1}] intact (sentinel)");
}
Console.WriteLine(failures == 0
? "RESULT: all values match"
: $"RESULT: {failures} mismatch(es)");
vk.DestroyCommandPool(device, commandPool, null);
vk.DestroyDescriptorPool(device, pool, null);
vk.DestroyPipeline(device, pipeline, null);
vk.DestroyPipelineLayout(device, pipelineLayout, null);
vk.DestroyDescriptorSetLayout(device, setLayout, null);
vk.DestroyShaderModule(device, module, null);
vk.UnmapMemory(device, memory);
vk.FreeMemory(device, memory, null);
vk.DestroyBuffer(device, buffer, null);
vk.DestroyDevice(device, null);
vk.DestroyInstance(instance, null);
Environment.ExitCode = failures == 0 ? 0 : 1;
static void Check(Result result, string what)
{
if (result != Result.Success)
{
throw new InvalidOperationException($"{what} failed: {result}");
}
}
}
@@ -0,0 +1,20 @@
<!--
Copyright (C) 2026 SharpEmu Emulator Project
SPDX-License-Identifier: GPL-2.0-or-later
-->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<!-- Standalone dev tool: opt out of the repo-wide lock-file requirement
so no packages.lock.json is generated or committed for it. -->
<RestorePackagesWithLockFile>false</RestorePackagesWithLockFile>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Silk.NET.Vulkan" />
</ItemGroup>
</Project>
+35 -4
View File
@@ -201,8 +201,8 @@ foreach (var (name, expectTranslate, words) in testPrograms)
null,
null)!;
object?[] compileArgs = [state, evaluation, null, null, 0, -1, 0];
if ((bool)tryCompile.Invoke(null, compileArgs)!)
var compileArgs = PadWithDefaults(tryCompile, [state, evaluation, null, null]);
if ((bool)tryCompile.Invoke(null, BindingFlags.OptionalParamBinding, null, compileArgs, null)!)
{
var shader = compileArgs[2]!;
var spirv = (byte[])shader.GetType().GetProperty("Spirv")!.GetValue(shader)!;
@@ -216,8 +216,8 @@ foreach (var (name, expectTranslate, words) in testPrograms)
Console.WriteLine($"[{name}] emit: FAILED ({compileArgs[3]})");
}
object?[] computeArgs = [state, evaluation, 1u, 1u, 1u, null, null];
if ((bool)tryCompileCompute.Invoke(null, computeArgs)!)
var computeArgs = PadWithDefaults(tryCompileCompute, [state, evaluation, 1u, 1u, 1u, null, null]);
if ((bool)tryCompileCompute.Invoke(null, BindingFlags.OptionalParamBinding, null, computeArgs, null)!)
{
var shader = computeArgs[5]!;
var spirv = (byte[])shader.GetType().GetProperty("Spirv")!.GetValue(shader)!;
@@ -237,6 +237,37 @@ Console.WriteLine(failures == 0
: $"RESULT: {failures} unexpected outcome(s)");
Environment.ExitCode = failures == 0 ? 0 : 1;
// Reflection Invoke does not apply C# default parameter values, so a newly
// added optional parameter on a translator entry point would otherwise throw
// TargetParameterCountException. Type.Missing + OptionalParamBinding lets the
// runtime substitute the declared defaults; only a new *required* parameter
// should force a tool update.
static object?[] PadWithDefaults(MethodInfo method, object?[] arguments)
{
var parameters = method.GetParameters();
if (arguments.Length > parameters.Length)
{
throw new InvalidOperationException(
$"{method.DeclaringType?.Name}.{method.Name} takes fewer parameters than the tool supplies");
}
var padded = new object?[parameters.Length];
arguments.CopyTo(padded, 0);
for (var i = arguments.Length; i < padded.Length; i++)
{
if (!parameters[i].IsOptional)
{
throw new InvalidOperationException(
$"{method.DeclaringType?.Name}.{method.Name} gained a required parameter " +
$"'{parameters[i].Name}' — the tool needs updating");
}
padded[i] = Type.Missing;
}
return padded;
}
internal sealed class FakeMemory : ICpuMemory
{
private readonly List<(ulong Base, byte[] Data)> _regions = [];