mirror of
https://github.com/par274/sharpemu.git
synced 2026-07-26 12:48:39 +08:00
Compare commits
31 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b36ecc121c | |||
| 42f0fa0e83 | |||
| 41d61bde41 | |||
| ac96fe5292 | |||
| 9b9ca8f707 | |||
| db20387502 | |||
| 44c43c8ebd | |||
| 4b5b27e686 | |||
| 5c823d0e8b | |||
| 1679897089 | |||
| ce8f75411a | |||
| f75da92fa5 | |||
| 9eaaac7cee | |||
| d446779d34 | |||
| 585d11b93b | |||
| 17f9535f0e | |||
| 8bfbb9c7fe | |||
| 2b8fe71a82 | |||
| 29b7f086c9 | |||
| eb3d8d6eb1 | |||
| 787c75b9b3 | |||
| 2a784aa405 | |||
| 2649857cb5 | |||
| c4b4aed2c5 | |||
| 757f6ea4b5 | |||
| df3ee02f8d | |||
| dfe61ec643 | |||
| 52e17b5056 | |||
| c1f3abfd5d | |||
| b5ee2c2cb7 | |||
| 16c1b74636 |
@@ -1,4 +1,4 @@
|
|||||||
<!--
|
<!--
|
||||||
Copyright (C) 2026 SharpEmu Emulator Project
|
Copyright (C) 2026 SharpEmu Emulator Project
|
||||||
SPDX-License-Identifier: GPL-2.0-or-later
|
SPDX-License-Identifier: GPL-2.0-or-later
|
||||||
-->
|
-->
|
||||||
@@ -7,10 +7,16 @@ SPDX-License-Identifier: GPL-2.0-or-later
|
|||||||
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
<PackageVersion Include="Avalonia" Version="11.3.18" />
|
||||||
|
<PackageVersion Include="Avalonia.Desktop" Version="11.3.18" />
|
||||||
|
<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="Iced" Version="1.21.0" />
|
||||||
<PackageVersion Include="Silk.NET.Vulkan" Version="2.23.0" />
|
<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.EXT" Version="2.23.0" />
|
||||||
<PackageVersion Include="Silk.NET.Vulkan.Extensions.KHR" Version="2.23.0" />
|
<PackageVersion Include="Silk.NET.Vulkan.Extensions.KHR" Version="2.23.0" />
|
||||||
<PackageVersion Include="Silk.NET.Windowing" 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" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
</Project>
|
</Project>
|
||||||
@@ -7,6 +7,7 @@ SPDX-License-Identifier: GPL-2.0-or-later
|
|||||||
<Folder Name="/src/">
|
<Folder Name="/src/">
|
||||||
<Project Path="src/SharpEmu.CLI/SharpEmu.CLI.csproj" />
|
<Project Path="src/SharpEmu.CLI/SharpEmu.CLI.csproj" />
|
||||||
<Project Path="src/SharpEmu.Core/SharpEmu.Core.csproj" />
|
<Project Path="src/SharpEmu.Core/SharpEmu.Core.csproj" />
|
||||||
|
<Project Path="src/SharpEmu.GUI/SharpEmu.GUI.csproj" />
|
||||||
<Project Path="src/SharpEmu.HLE/SharpEmu.HLE.csproj" />
|
<Project Path="src/SharpEmu.HLE/SharpEmu.HLE.csproj" />
|
||||||
<Project Path="src/SharpEmu.Libs/SharpEmu.Libs.csproj" />
|
<Project Path="src/SharpEmu.Libs/SharpEmu.Libs.csproj" />
|
||||||
<Project Path="src/SharpEmu.Logging/SharpEmu.Logging.csproj" />
|
<Project Path="src/SharpEmu.Logging/SharpEmu.Logging.csproj" />
|
||||||
|
|||||||
+102
-1
@@ -3,6 +3,7 @@
|
|||||||
|
|
||||||
using SharpEmu.Core.Runtime;
|
using SharpEmu.Core.Runtime;
|
||||||
using SharpEmu.Core.Cpu;
|
using SharpEmu.Core.Cpu;
|
||||||
|
using SharpEmu.GUI;
|
||||||
using SharpEmu.HLE;
|
using SharpEmu.HLE;
|
||||||
using SharpEmu.Logging;
|
using SharpEmu.Logging;
|
||||||
using System.Runtime.InteropServices;
|
using System.Runtime.InteropServices;
|
||||||
@@ -24,12 +25,32 @@ internal static partial class Program
|
|||||||
private const ulong PROCESS_CREATION_MITIGATION_POLICY2_CET_USER_SHADOW_STACKS_ALWAYS_OFF = 0x00000002UL << 28;
|
private const ulong PROCESS_CREATION_MITIGATION_POLICY2_CET_USER_SHADOW_STACKS_ALWAYS_OFF = 0x00000002UL << 28;
|
||||||
private const ulong PROCESS_CREATION_MITIGATION_POLICY2_USER_CET_SET_CONTEXT_IP_VALIDATION_ALWAYS_OFF = 0x00000002UL << 32;
|
private const ulong PROCESS_CREATION_MITIGATION_POLICY2_USER_CET_SET_CONTEXT_IP_VALIDATION_ALWAYS_OFF = 0x00000002UL << 32;
|
||||||
private const ulong PROCESS_CREATION_MITIGATION_POLICY2_XTENDED_CONTROL_FLOW_GUARD_ALWAYS_OFF = 0x00000002UL << 40;
|
private const ulong PROCESS_CREATION_MITIGATION_POLICY2_XTENDED_CONTROL_FLOW_GUARD_ALWAYS_OFF = 0x00000002UL << 40;
|
||||||
|
private const int ATTACH_PARENT_PROCESS = -1;
|
||||||
|
private const int STD_OUTPUT_HANDLE = -11;
|
||||||
|
private const int STD_ERROR_HANDLE = -12;
|
||||||
|
private const uint GENERIC_READ = 0x80000000;
|
||||||
|
private const uint GENERIC_WRITE = 0x40000000;
|
||||||
|
private const uint FILE_SHARE_READ = 0x00000001;
|
||||||
|
private const uint FILE_SHARE_WRITE = 0x00000002;
|
||||||
|
private const uint OPEN_EXISTING = 3;
|
||||||
|
|
||||||
|
[STAThread]
|
||||||
private static int Main(string[] args)
|
private static int Main(string[] args)
|
||||||
{
|
{
|
||||||
|
args = NormalizeInternalArguments(args, out var isMitigatedChild);
|
||||||
|
if (args.Length == 0 && !isMitigatedChild)
|
||||||
|
{
|
||||||
|
// No arguments: open the desktop frontend. Any argument selects
|
||||||
|
// the classic CLI behavior below.
|
||||||
|
return GuiLauncher.Run();
|
||||||
|
}
|
||||||
|
|
||||||
|
// The executable uses the GUI subsystem, so CLI mode has to connect
|
||||||
|
// itself to a console before the first write.
|
||||||
|
EnsureCliConsole();
|
||||||
|
|
||||||
Console.Error.WriteLine($"[DEBUG] SharpEmu starting with {args.Length} args");
|
Console.Error.WriteLine($"[DEBUG] SharpEmu starting with {args.Length} args");
|
||||||
|
|
||||||
args = NormalizeInternalArguments(args, out var isMitigatedChild);
|
|
||||||
if (!isMitigatedChild && TryRunMitigatedChild(args, out var childExitCode))
|
if (!isMitigatedChild && TryRunMitigatedChild(args, out var childExitCode))
|
||||||
{
|
{
|
||||||
return childExitCode;
|
return childExitCode;
|
||||||
@@ -101,6 +122,58 @@ internal static partial class Program
|
|||||||
return result == OrbisGen2Result.ORBIS_GEN2_OK ? 0 : 4;
|
return result == OrbisGen2Result.ORBIS_GEN2_OK ? 0 : 4;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static void EnsureCliConsole()
|
||||||
|
{
|
||||||
|
if (!OperatingSystem.IsWindows())
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Standard handles already provided (pipes or file redirection, e.g.
|
||||||
|
// when the GUI or a script launches us): use them as-is.
|
||||||
|
if (IsHandleValid(GetStdHandle(STD_OUTPUT_HANDLE)) && IsHandleValid(GetStdHandle(STD_ERROR_HANDLE)))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prefer the console of the parent process (interactive terminal);
|
||||||
|
// create one only when started with arguments but no terminal at all
|
||||||
|
// (e.g. a shortcut), so usage and errors remain visible.
|
||||||
|
if (!AttachConsole(ATTACH_PARENT_PROCESS) && GetConsoleWindow() == 0)
|
||||||
|
{
|
||||||
|
_ = AllocConsole();
|
||||||
|
}
|
||||||
|
|
||||||
|
RebindStdHandleToConsole(STD_OUTPUT_HANDLE);
|
||||||
|
RebindStdHandleToConsole(STD_ERROR_HANDLE);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void RebindStdHandleToConsole(int stdHandle)
|
||||||
|
{
|
||||||
|
if (IsHandleValid(GetStdHandle(stdHandle)) || GetConsoleWindow() == 0)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var conOut = CreateFileW(
|
||||||
|
"CONOUT$",
|
||||||
|
GENERIC_READ | GENERIC_WRITE,
|
||||||
|
FILE_SHARE_READ | FILE_SHARE_WRITE,
|
||||||
|
0,
|
||||||
|
OPEN_EXISTING,
|
||||||
|
0,
|
||||||
|
0);
|
||||||
|
if (IsHandleValid(conOut))
|
||||||
|
{
|
||||||
|
_ = SetStdHandle(stdHandle, conOut);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsHandleValid(nint handle)
|
||||||
|
{
|
||||||
|
return handle != 0 && handle != -1;
|
||||||
|
}
|
||||||
|
|
||||||
private static string[] NormalizeInternalArguments(string[] args, out bool isMitigatedChild)
|
private static string[] NormalizeInternalArguments(string[] args, out bool isMitigatedChild)
|
||||||
{
|
{
|
||||||
isMitigatedChild = false;
|
isMitigatedChild = false;
|
||||||
@@ -670,4 +743,32 @@ internal static partial class Program
|
|||||||
[DllImport("kernel32.dll", SetLastError = true)]
|
[DllImport("kernel32.dll", SetLastError = true)]
|
||||||
[return: MarshalAs(UnmanagedType.Bool)]
|
[return: MarshalAs(UnmanagedType.Bool)]
|
||||||
private static extern bool CloseHandle(nint handle);
|
private static extern bool CloseHandle(nint handle);
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll")]
|
||||||
|
private static extern nint GetConsoleWindow();
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll", SetLastError = true)]
|
||||||
|
[return: MarshalAs(UnmanagedType.Bool)]
|
||||||
|
private static extern bool AttachConsole(int processId);
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll", SetLastError = true)]
|
||||||
|
[return: MarshalAs(UnmanagedType.Bool)]
|
||||||
|
private static extern bool AllocConsole();
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll", SetLastError = true)]
|
||||||
|
private static extern nint GetStdHandle(int stdHandle);
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll", SetLastError = true)]
|
||||||
|
[return: MarshalAs(UnmanagedType.Bool)]
|
||||||
|
private static extern bool SetStdHandle(int stdHandle, nint handle);
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll", EntryPoint = "CreateFileW", SetLastError = true, CharSet = CharSet.Unicode)]
|
||||||
|
private static extern nint CreateFileW(
|
||||||
|
string fileName,
|
||||||
|
uint desiredAccess,
|
||||||
|
uint shareMode,
|
||||||
|
nint securityAttributes,
|
||||||
|
uint creationDisposition,
|
||||||
|
uint flagsAndAttributes,
|
||||||
|
nint templateFile);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,16 +7,19 @@ SPDX-License-Identifier: GPL-2.0-or-later
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\SharpEmu.Core\SharpEmu.Core.csproj" />
|
<ProjectReference Include="..\SharpEmu.Core\SharpEmu.Core.csproj" />
|
||||||
|
<ProjectReference Include="..\SharpEmu.GUI\SharpEmu.GUI.csproj" />
|
||||||
<ProjectReference Include="..\SharpEmu.Logging\SharpEmu.Logging.csproj" />
|
<ProjectReference Include="..\SharpEmu.Logging\SharpEmu.Logging.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<OutputType>Exe</OutputType>
|
<!-- GUI subsystem so starting without arguments opens the frontend with no
|
||||||
|
console window; CLI mode re-attaches to the parent terminal's console. -->
|
||||||
|
<OutputType>WinExe</OutputType>
|
||||||
<AssemblyName>SharpEmu</AssemblyName>
|
<AssemblyName>SharpEmu</AssemblyName>
|
||||||
<RuntimeIdentifiers>win-x64;linux-x64;osx-arm64</RuntimeIdentifiers>
|
<RuntimeIdentifiers>win-x64;linux-x64;osx-arm64</RuntimeIdentifiers>
|
||||||
<SelfContained>true</SelfContained>
|
<SelfContained>true</SelfContained>
|
||||||
<PublishSingleFile>true</PublishSingleFile>
|
<PublishSingleFile>true</PublishSingleFile>
|
||||||
<!-- <IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract> -->
|
<IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>
|
||||||
<EnableCompressionInSingleFile>true</EnableCompressionInSingleFile>
|
<EnableCompressionInSingleFile>true</EnableCompressionInSingleFile>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||||
@@ -43,4 +46,17 @@ SPDX-License-Identifier: GPL-2.0-or-later
|
|||||||
</Content>
|
</Content>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
<!-- Keep glfw as a loose file next to the executable; every other native
|
||||||
|
library is embedded into the single-file bundle. -->
|
||||||
|
<Target Name="KeepGlfwOutsideSingleFile" AfterTargets="ComputeResolvedFilesToPublishList">
|
||||||
|
<ItemGroup>
|
||||||
|
<_GlfwPublishFiles Include="@(ResolvedFileToPublish)"
|
||||||
|
Condition="$([System.String]::Copy('%(ResolvedFileToPublish.Filename)').StartsWith('glfw'))" />
|
||||||
|
<ResolvedFileToPublish Remove="@(_GlfwPublishFiles)" />
|
||||||
|
<ResolvedFileToPublish Include="@(_GlfwPublishFiles)">
|
||||||
|
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
|
||||||
|
</ResolvedFileToPublish>
|
||||||
|
</ItemGroup>
|
||||||
|
</Target>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -8,6 +8,105 @@
|
|||||||
"resolved": "10.0.3",
|
"resolved": "10.0.3",
|
||||||
"contentHash": "0B6nZyCHWXnvmlB559oduOspVdNOnpNXPjhpWVMovLPAsDVG7A4jJR9rzECf67JUzxP8/ee/wA8clwIzJcWNFA=="
|
"contentHash": "0B6nZyCHWXnvmlB559oduOspVdNOnpNXPjhpWVMovLPAsDVG7A4jJR9rzECf67JUzxP8/ee/wA8clwIzJcWNFA=="
|
||||||
},
|
},
|
||||||
|
"Avalonia.Angle.Windows.Natives": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "2.1.25547.20250602",
|
||||||
|
"contentHash": "ZL0VLc4s9rvNNFt19Pxm5UNAkmKNylugAwJPX9ulXZ6JWs/l6XZihPWWTyezaoNOVyEPU8YbURtW7XMAtqXH5A=="
|
||||||
|
},
|
||||||
|
"Avalonia.BuildServices": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "11.3.2",
|
||||||
|
"contentHash": "qHDToxto1e3hci5YqbG9n0Ty8mlp3zBUN5wT66wKqaDVzXyQ0do3EnRILd4Ke9jpvsktaPpgE0YjEk7hornryQ=="
|
||||||
|
},
|
||||||
|
"Avalonia.FreeDesktop": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "11.3.18",
|
||||||
|
"contentHash": "aUwv8BNruRUOaUfMu4U3uibIUS60/rSHgGOhd8zBkLkpxY3JFJvgRbeq5ZzHIyKXCuKi18PO00YHAgCarp3wdw==",
|
||||||
|
"dependencies": {
|
||||||
|
"Avalonia": "11.3.18",
|
||||||
|
"Tmds.DBus.Protocol": "0.21.3"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"Avalonia.Native": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "11.3.18",
|
||||||
|
"contentHash": "8g53DROFW6wVJAnTsE1Iu5bdZO5r0oqxbdbMQODs1QDYCK2IU/y/x/vQVKCYOvqxl4tXkzU9tExv8XqSGPWthQ==",
|
||||||
|
"dependencies": {
|
||||||
|
"Avalonia": "11.3.18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"Avalonia.Remote.Protocol": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "11.3.18",
|
||||||
|
"contentHash": "vw+6ZfgTuu72dA9aVWn6u56t2nrBd5MoMU0wo/qI9XJAl/c0oYYphIvwLvJP1JorubQY4UE3d0ac8ULBhrGBiA=="
|
||||||
|
},
|
||||||
|
"Avalonia.Skia": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "11.3.18",
|
||||||
|
"contentHash": "/B4aXmNRNjG8I5U/a1xJI+bIi0XO6DDzS3mBrIKlVnJRY2CyZiUeESRQXLnIU77Z9TvqkUROs+D47s085YjFtA==",
|
||||||
|
"dependencies": {
|
||||||
|
"Avalonia": "11.3.18",
|
||||||
|
"HarfBuzzSharp": "8.3.1.1",
|
||||||
|
"HarfBuzzSharp.NativeAssets.Linux": "8.3.1.1",
|
||||||
|
"HarfBuzzSharp.NativeAssets.WebAssembly": "8.3.1.1",
|
||||||
|
"SkiaSharp": "2.88.9",
|
||||||
|
"SkiaSharp.NativeAssets.Linux": "2.88.9",
|
||||||
|
"SkiaSharp.NativeAssets.WebAssembly": "2.88.9"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"Avalonia.Win32": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "11.3.18",
|
||||||
|
"contentHash": "eioUHkM2PeLPETd1aEks3rvb9plbba6buIrNdrqCpwE/qgHKUjvRNBd5mUQfAbGgTLiAes524gB8uUMDhrsJVQ==",
|
||||||
|
"dependencies": {
|
||||||
|
"Avalonia": "11.3.18",
|
||||||
|
"Avalonia.Angle.Windows.Natives": "2.1.25547.20250602"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"Avalonia.X11": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "11.3.18",
|
||||||
|
"contentHash": "m4Ki/G5Dovnq+6QzfS0iGbK8V77Q6oTjToMLOB0CxPCCrl3Oxywh6kIjuGJDPaN6kopMmjxlNShyQf+vPYL+JA==",
|
||||||
|
"dependencies": {
|
||||||
|
"Avalonia": "11.3.18",
|
||||||
|
"Avalonia.FreeDesktop": "11.3.18",
|
||||||
|
"Avalonia.Skia": "11.3.18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"HarfBuzzSharp": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "8.3.1.1",
|
||||||
|
"contentHash": "tLZN66oe/uiRPTZfrCU4i8ScVGwqHNh5MHrXj0yVf4l7Mz0FhTGnQ71RGySROTmdognAs0JtluHkL41pIabWuQ==",
|
||||||
|
"dependencies": {
|
||||||
|
"HarfBuzzSharp.NativeAssets.Win32": "8.3.1.1",
|
||||||
|
"HarfBuzzSharp.NativeAssets.macOS": "8.3.1.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"HarfBuzzSharp.NativeAssets.Linux": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "8.3.1.1",
|
||||||
|
"contentHash": "3EZ1mpIiKWRLL5hUYA82ZHteeDIVaEA/Z0rA/wU6tjx6crcAkJnBPwDXZugBSfo8+J3EznvRJf49uMsqYfKrHg=="
|
||||||
|
},
|
||||||
|
"HarfBuzzSharp.NativeAssets.macOS": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "8.3.1.1",
|
||||||
|
"contentHash": "jbtCsgftcaFLCA13tVKo5iWdElJScrulLTKJre36O4YQTIlwDtPPqhRZNk+Y0vv4D1gxbscasGRucUDfS44ofQ=="
|
||||||
|
},
|
||||||
|
"HarfBuzzSharp.NativeAssets.WebAssembly": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "8.3.1.1",
|
||||||
|
"contentHash": "loJweK2u/mH/3C2zBa0ggJlITIszOkK64HLAZB7FUT670dTg965whLFYHDQo69NmC4+d9UN0icLC9VHidXaVCA=="
|
||||||
|
},
|
||||||
|
"HarfBuzzSharp.NativeAssets.Win32": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "8.3.1.1",
|
||||||
|
"contentHash": "UsJtQsfAJoFDZrXc4hCUfRPMqccfKZ0iumJ/upcUjz/cmsTgVFGNEL5yaJWmkqsuFYdMWbj/En5/kS4PFl9hBA=="
|
||||||
|
},
|
||||||
|
"MicroCom.Runtime": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "0.11.0",
|
||||||
|
"contentHash": "MEnrZ3UIiH40hjzMDsxrTyi8dtqB5ziv3iBeeU4bXsL/7NLSal9F1lZKpK+tfBRnUoDSdtcW3KufE4yhATOMCA=="
|
||||||
|
},
|
||||||
"Microsoft.DotNet.PlatformAbstractions": {
|
"Microsoft.DotNet.PlatformAbstractions": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "3.1.6",
|
"resolved": "3.1.6",
|
||||||
@@ -59,6 +158,38 @@
|
|||||||
"Silk.NET.Windowing.Common": "2.23.0"
|
"Silk.NET.Windowing.Common": "2.23.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"SkiaSharp": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "2.88.9",
|
||||||
|
"contentHash": "3MD5VHjXXieSHCleRLuaTXmL2pD0mB7CcOB1x2kA1I4bhptf4e3R27iM93264ZYuAq6mkUyX5XbcxnZvMJYc1Q==",
|
||||||
|
"dependencies": {
|
||||||
|
"SkiaSharp.NativeAssets.Win32": "2.88.9",
|
||||||
|
"SkiaSharp.NativeAssets.macOS": "2.88.9"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"SkiaSharp.NativeAssets.Linux": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "2.88.9",
|
||||||
|
"contentHash": "cWSaJKVPWAaT/WIn9c8T5uT/l4ETwHxNJTkEOtNKjphNo8AW6TF9O32aRkxqw3l8GUdUo66Bu7EiqtFh/XG0Zg==",
|
||||||
|
"dependencies": {
|
||||||
|
"SkiaSharp": "2.88.9"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"SkiaSharp.NativeAssets.macOS": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "2.88.9",
|
||||||
|
"contentHash": "Nv5spmKc4505Ep7oUoJ5vp3KweFpeNqxpyGDWyeEPTX2uR6S6syXIm3gj75dM0YJz7NPvcix48mR5laqs8dPuA=="
|
||||||
|
},
|
||||||
|
"SkiaSharp.NativeAssets.WebAssembly": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "2.88.9",
|
||||||
|
"contentHash": "kt06RccBHSnAs2wDYdBSfsjIDbY3EpsOVqnlDgKdgvyuRA8ZFDaHRdWNx1VHjGgYzmnFCGiTJBnXFl5BqGwGnA=="
|
||||||
|
},
|
||||||
|
"SkiaSharp.NativeAssets.Win32": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "2.88.9",
|
||||||
|
"contentHash": "wb2kYgU7iy84nQLYZwMeJXixvK++GoIuECjU4ECaUKNuflyRlJKyiRhN1MAHswvlvzuvkrjRWlK0Za6+kYQK7w=="
|
||||||
|
},
|
||||||
"Ultz.Native.GLFW": {
|
"Ultz.Native.GLFW": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "3.4.0",
|
"resolved": "3.4.0",
|
||||||
@@ -73,6 +204,16 @@
|
|||||||
"SharpEmu.Logging": "[1.0.0, )"
|
"SharpEmu.Logging": "[1.0.0, )"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"sharpemu.gui": {
|
||||||
|
"type": "Project",
|
||||||
|
"dependencies": {
|
||||||
|
"Avalonia": "[11.3.18, )",
|
||||||
|
"Avalonia.Desktop": "[11.3.18, )",
|
||||||
|
"Avalonia.Fonts.Inter": "[11.3.18, )",
|
||||||
|
"Avalonia.Themes.Fluent": "[11.3.18, )",
|
||||||
|
"Tmds.DBus.Protocol": "[0.21.3, )"
|
||||||
|
}
|
||||||
|
},
|
||||||
"sharpemu.hle": {
|
"sharpemu.hle": {
|
||||||
"type": "Project"
|
"type": "Project"
|
||||||
},
|
},
|
||||||
@@ -89,6 +230,48 @@
|
|||||||
"sharpemu.logging": {
|
"sharpemu.logging": {
|
||||||
"type": "Project"
|
"type": "Project"
|
||||||
},
|
},
|
||||||
|
"Avalonia": {
|
||||||
|
"type": "CentralTransitive",
|
||||||
|
"requested": "[11.3.18, )",
|
||||||
|
"resolved": "11.3.18",
|
||||||
|
"contentHash": "2C4UxhWUObWGgYKWic1x5BMMWGJP6SElb91WeOxs+X/iR26rtkqpxFFwwo50FXS9AyYnHfk8QKXDEfe7oT/kZA==",
|
||||||
|
"dependencies": {
|
||||||
|
"Avalonia.BuildServices": "11.3.2",
|
||||||
|
"Avalonia.Remote.Protocol": "11.3.18",
|
||||||
|
"MicroCom.Runtime": "0.11.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"Avalonia.Desktop": {
|
||||||
|
"type": "CentralTransitive",
|
||||||
|
"requested": "[11.3.18, )",
|
||||||
|
"resolved": "11.3.18",
|
||||||
|
"contentHash": "bilMPa5vYiis6fbNovb6esKytBnOCEGojBa1XFegLCRHCP6g6PvZwS0XF/YOAGkENRlHG8dI7lohOpQ9bIkq1g==",
|
||||||
|
"dependencies": {
|
||||||
|
"Avalonia": "11.3.18",
|
||||||
|
"Avalonia.Native": "11.3.18",
|
||||||
|
"Avalonia.Skia": "11.3.18",
|
||||||
|
"Avalonia.Win32": "11.3.18",
|
||||||
|
"Avalonia.X11": "11.3.18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"Avalonia.Fonts.Inter": {
|
||||||
|
"type": "CentralTransitive",
|
||||||
|
"requested": "[11.3.18, )",
|
||||||
|
"resolved": "11.3.18",
|
||||||
|
"contentHash": "27u6hB3Y2Ue586yjfeVakberY73VNQXtuKwe/P927XG1QPlhsfmOyifLHDDpSHG85Zl1x/Xv9IZ3+tk9FnjcZQ==",
|
||||||
|
"dependencies": {
|
||||||
|
"Avalonia": "11.3.18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"Avalonia.Themes.Fluent": {
|
||||||
|
"type": "CentralTransitive",
|
||||||
|
"requested": "[11.3.18, )",
|
||||||
|
"resolved": "11.3.18",
|
||||||
|
"contentHash": "+Q/TJoynD0zNuu5w2gD+xcTl7GNKJFxlPYAndRLs/mTDrNbbsvv/271WyIysbMPsXSjCyBDp7RCZzQkpD6x5Bg==",
|
||||||
|
"dependencies": {
|
||||||
|
"Avalonia": "11.3.18"
|
||||||
|
}
|
||||||
|
},
|
||||||
"Iced": {
|
"Iced": {
|
||||||
"type": "CentralTransitive",
|
"type": "CentralTransitive",
|
||||||
"requested": "[1.21.0, )",
|
"requested": "[1.21.0, )",
|
||||||
@@ -133,9 +316,61 @@
|
|||||||
"Silk.NET.Windowing.Common": "2.23.0",
|
"Silk.NET.Windowing.Common": "2.23.0",
|
||||||
"Silk.NET.Windowing.Glfw": "2.23.0"
|
"Silk.NET.Windowing.Glfw": "2.23.0"
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"Tmds.DBus.Protocol": {
|
||||||
|
"type": "CentralTransitive",
|
||||||
|
"requested": "[0.21.3, )",
|
||||||
|
"resolved": "0.21.3",
|
||||||
|
"contentHash": "hDwB8WsQoyALQKqIbwzS68UKdlnafDm4T/DkO/JrA/YIneP/rKv96SxYPVXeh3FP4i/SXfShrYftKLtciJAIlw=="
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"net10.0/linux-x64": {
|
"net10.0/linux-x64": {
|
||||||
|
"Avalonia.Angle.Windows.Natives": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "2.1.25547.20250602",
|
||||||
|
"contentHash": "ZL0VLc4s9rvNNFt19Pxm5UNAkmKNylugAwJPX9ulXZ6JWs/l6XZihPWWTyezaoNOVyEPU8YbURtW7XMAtqXH5A=="
|
||||||
|
},
|
||||||
|
"Avalonia.Native": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "11.3.18",
|
||||||
|
"contentHash": "8g53DROFW6wVJAnTsE1Iu5bdZO5r0oqxbdbMQODs1QDYCK2IU/y/x/vQVKCYOvqxl4tXkzU9tExv8XqSGPWthQ==",
|
||||||
|
"dependencies": {
|
||||||
|
"Avalonia": "11.3.18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"HarfBuzzSharp.NativeAssets.Linux": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "8.3.1.1",
|
||||||
|
"contentHash": "3EZ1mpIiKWRLL5hUYA82ZHteeDIVaEA/Z0rA/wU6tjx6crcAkJnBPwDXZugBSfo8+J3EznvRJf49uMsqYfKrHg=="
|
||||||
|
},
|
||||||
|
"HarfBuzzSharp.NativeAssets.macOS": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "8.3.1.1",
|
||||||
|
"contentHash": "jbtCsgftcaFLCA13tVKo5iWdElJScrulLTKJre36O4YQTIlwDtPPqhRZNk+Y0vv4D1gxbscasGRucUDfS44ofQ=="
|
||||||
|
},
|
||||||
|
"HarfBuzzSharp.NativeAssets.Win32": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "8.3.1.1",
|
||||||
|
"contentHash": "UsJtQsfAJoFDZrXc4hCUfRPMqccfKZ0iumJ/upcUjz/cmsTgVFGNEL5yaJWmkqsuFYdMWbj/En5/kS4PFl9hBA=="
|
||||||
|
},
|
||||||
|
"SkiaSharp.NativeAssets.Linux": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "2.88.9",
|
||||||
|
"contentHash": "cWSaJKVPWAaT/WIn9c8T5uT/l4ETwHxNJTkEOtNKjphNo8AW6TF9O32aRkxqw3l8GUdUo66Bu7EiqtFh/XG0Zg==",
|
||||||
|
"dependencies": {
|
||||||
|
"SkiaSharp": "2.88.9"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"SkiaSharp.NativeAssets.macOS": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "2.88.9",
|
||||||
|
"contentHash": "Nv5spmKc4505Ep7oUoJ5vp3KweFpeNqxpyGDWyeEPTX2uR6S6syXIm3gj75dM0YJz7NPvcix48mR5laqs8dPuA=="
|
||||||
|
},
|
||||||
|
"SkiaSharp.NativeAssets.Win32": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "2.88.9",
|
||||||
|
"contentHash": "wb2kYgU7iy84nQLYZwMeJXixvK++GoIuECjU4ECaUKNuflyRlJKyiRhN1MAHswvlvzuvkrjRWlK0Za6+kYQK7w=="
|
||||||
|
},
|
||||||
"Ultz.Native.GLFW": {
|
"Ultz.Native.GLFW": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "3.4.0",
|
"resolved": "3.4.0",
|
||||||
@@ -143,6 +378,52 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"net10.0/osx-arm64": {
|
"net10.0/osx-arm64": {
|
||||||
|
"Avalonia.Angle.Windows.Natives": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "2.1.25547.20250602",
|
||||||
|
"contentHash": "ZL0VLc4s9rvNNFt19Pxm5UNAkmKNylugAwJPX9ulXZ6JWs/l6XZihPWWTyezaoNOVyEPU8YbURtW7XMAtqXH5A=="
|
||||||
|
},
|
||||||
|
"Avalonia.Native": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "11.3.18",
|
||||||
|
"contentHash": "8g53DROFW6wVJAnTsE1Iu5bdZO5r0oqxbdbMQODs1QDYCK2IU/y/x/vQVKCYOvqxl4tXkzU9tExv8XqSGPWthQ==",
|
||||||
|
"dependencies": {
|
||||||
|
"Avalonia": "11.3.18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"HarfBuzzSharp.NativeAssets.Linux": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "8.3.1.1",
|
||||||
|
"contentHash": "3EZ1mpIiKWRLL5hUYA82ZHteeDIVaEA/Z0rA/wU6tjx6crcAkJnBPwDXZugBSfo8+J3EznvRJf49uMsqYfKrHg=="
|
||||||
|
},
|
||||||
|
"HarfBuzzSharp.NativeAssets.macOS": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "8.3.1.1",
|
||||||
|
"contentHash": "jbtCsgftcaFLCA13tVKo5iWdElJScrulLTKJre36O4YQTIlwDtPPqhRZNk+Y0vv4D1gxbscasGRucUDfS44ofQ=="
|
||||||
|
},
|
||||||
|
"HarfBuzzSharp.NativeAssets.Win32": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "8.3.1.1",
|
||||||
|
"contentHash": "UsJtQsfAJoFDZrXc4hCUfRPMqccfKZ0iumJ/upcUjz/cmsTgVFGNEL5yaJWmkqsuFYdMWbj/En5/kS4PFl9hBA=="
|
||||||
|
},
|
||||||
|
"SkiaSharp.NativeAssets.Linux": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "2.88.9",
|
||||||
|
"contentHash": "cWSaJKVPWAaT/WIn9c8T5uT/l4ETwHxNJTkEOtNKjphNo8AW6TF9O32aRkxqw3l8GUdUo66Bu7EiqtFh/XG0Zg==",
|
||||||
|
"dependencies": {
|
||||||
|
"SkiaSharp": "2.88.9"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"SkiaSharp.NativeAssets.macOS": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "2.88.9",
|
||||||
|
"contentHash": "Nv5spmKc4505Ep7oUoJ5vp3KweFpeNqxpyGDWyeEPTX2uR6S6syXIm3gj75dM0YJz7NPvcix48mR5laqs8dPuA=="
|
||||||
|
},
|
||||||
|
"SkiaSharp.NativeAssets.Win32": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "2.88.9",
|
||||||
|
"contentHash": "wb2kYgU7iy84nQLYZwMeJXixvK++GoIuECjU4ECaUKNuflyRlJKyiRhN1MAHswvlvzuvkrjRWlK0Za6+kYQK7w=="
|
||||||
|
},
|
||||||
"Ultz.Native.GLFW": {
|
"Ultz.Native.GLFW": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "3.4.0",
|
"resolved": "3.4.0",
|
||||||
@@ -150,6 +431,52 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"net10.0/win-x64": {
|
"net10.0/win-x64": {
|
||||||
|
"Avalonia.Angle.Windows.Natives": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "2.1.25547.20250602",
|
||||||
|
"contentHash": "ZL0VLc4s9rvNNFt19Pxm5UNAkmKNylugAwJPX9ulXZ6JWs/l6XZihPWWTyezaoNOVyEPU8YbURtW7XMAtqXH5A=="
|
||||||
|
},
|
||||||
|
"Avalonia.Native": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "11.3.18",
|
||||||
|
"contentHash": "8g53DROFW6wVJAnTsE1Iu5bdZO5r0oqxbdbMQODs1QDYCK2IU/y/x/vQVKCYOvqxl4tXkzU9tExv8XqSGPWthQ==",
|
||||||
|
"dependencies": {
|
||||||
|
"Avalonia": "11.3.18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"HarfBuzzSharp.NativeAssets.Linux": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "8.3.1.1",
|
||||||
|
"contentHash": "3EZ1mpIiKWRLL5hUYA82ZHteeDIVaEA/Z0rA/wU6tjx6crcAkJnBPwDXZugBSfo8+J3EznvRJf49uMsqYfKrHg=="
|
||||||
|
},
|
||||||
|
"HarfBuzzSharp.NativeAssets.macOS": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "8.3.1.1",
|
||||||
|
"contentHash": "jbtCsgftcaFLCA13tVKo5iWdElJScrulLTKJre36O4YQTIlwDtPPqhRZNk+Y0vv4D1gxbscasGRucUDfS44ofQ=="
|
||||||
|
},
|
||||||
|
"HarfBuzzSharp.NativeAssets.Win32": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "8.3.1.1",
|
||||||
|
"contentHash": "UsJtQsfAJoFDZrXc4hCUfRPMqccfKZ0iumJ/upcUjz/cmsTgVFGNEL5yaJWmkqsuFYdMWbj/En5/kS4PFl9hBA=="
|
||||||
|
},
|
||||||
|
"SkiaSharp.NativeAssets.Linux": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "2.88.9",
|
||||||
|
"contentHash": "cWSaJKVPWAaT/WIn9c8T5uT/l4ETwHxNJTkEOtNKjphNo8AW6TF9O32aRkxqw3l8GUdUo66Bu7EiqtFh/XG0Zg==",
|
||||||
|
"dependencies": {
|
||||||
|
"SkiaSharp": "2.88.9"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"SkiaSharp.NativeAssets.macOS": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "2.88.9",
|
||||||
|
"contentHash": "Nv5spmKc4505Ep7oUoJ5vp3KweFpeNqxpyGDWyeEPTX2uR6S6syXIm3gj75dM0YJz7NPvcix48mR5laqs8dPuA=="
|
||||||
|
},
|
||||||
|
"SkiaSharp.NativeAssets.Win32": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "2.88.9",
|
||||||
|
"contentHash": "wb2kYgU7iy84nQLYZwMeJXixvK++GoIuECjU4ECaUKNuflyRlJKyiRhN1MAHswvlvzuvkrjRWlK0Za6+kYQK7w=="
|
||||||
|
},
|
||||||
"Ultz.Native.GLFW": {
|
"Ultz.Native.GLFW": {
|
||||||
"type": "Transitive",
|
"type": "Transitive",
|
||||||
"resolved": "3.4.0",
|
"resolved": "3.4.0",
|
||||||
|
|||||||
@@ -633,25 +633,56 @@ public sealed partial class DirectExecutionBackend
|
|||||||
"ASoW5WE-UPo" or // sceKernelAprSubmitCommandBufferAndGetResult
|
"ASoW5WE-UPo" or // sceKernelAprSubmitCommandBufferAndGetResult
|
||||||
"rqwFKI4PAiM" or // sceKernelAprWaitCommandBuffer
|
"rqwFKI4PAiM" or // sceKernelAprWaitCommandBuffer
|
||||||
"eE4Szl8sil8" or // sceKernelAprSubmitCommandBuffer
|
"eE4Szl8sil8" or // sceKernelAprSubmitCommandBuffer
|
||||||
"qvMUCyyaCSI"; // sceKernelAprSubmitCommandBufferAndGetId
|
"qvMUCyyaCSI" or // sceKernelAprSubmitCommandBufferAndGetId
|
||||||
|
"Q2V+iqvjgC0" or // vsnprintf
|
||||||
|
"q1cHNfGycLI" or // scePadRead
|
||||||
|
"xk0AcarP3V4" or // scePadOpen
|
||||||
|
"yH17Q6NWtVg" or // sceUserServiceGetEvent
|
||||||
|
"D-CzAxQL0XI" or // sceUserServiceGetPlatformPrivacySetting
|
||||||
|
"K-jXhbt2gn4"; // scePthreadMutexTrylock
|
||||||
|
|
||||||
private bool ShouldLogImportResult(string nid, OrbisGen2Result result)
|
private bool ShouldLogImportResult(string nid, OrbisGen2Result result)
|
||||||
{
|
{
|
||||||
|
var resultValue = unchecked((int)result);
|
||||||
|
if (resultValue > 0)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
var expectedFileProbeMiss =
|
var expectedFileProbeMiss =
|
||||||
result == OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND &&
|
result == OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND &&
|
||||||
IsExpectedFileProbeNotFoundNid(nid);
|
IsExpectedFileProbeNotFoundNid(nid);
|
||||||
var expectedTimedWaitTimeout =
|
var expectedTimedWaitTimeout =
|
||||||
string.Equals(nid, "27bAgiJmOh0", StringComparison.Ordinal) &&
|
string.Equals(nid, "27bAgiJmOh0", StringComparison.Ordinal) &&
|
||||||
unchecked((int)result) == 60;
|
unchecked((int)result) == 60;
|
||||||
|
var expectedEqueueTimeout =
|
||||||
|
string.Equals(nid, "fzyMKs9kim0", StringComparison.Ordinal) &&
|
||||||
|
result == OrbisGen2Result.ORBIS_GEN2_ERROR_TIMED_OUT;
|
||||||
var expectedMutexTrylockBusy =
|
var expectedMutexTrylockBusy =
|
||||||
string.Equals(nid, "K-jXhbt2gn4", StringComparison.Ordinal) &&
|
string.Equals(nid, "K-jXhbt2gn4", StringComparison.Ordinal) &&
|
||||||
result == OrbisGen2Result.ORBIS_GEN2_ERROR_BUSY;
|
result == OrbisGen2Result.ORBIS_GEN2_ERROR_BUSY;
|
||||||
if (!expectedFileProbeMiss && !expectedTimedWaitTimeout && !expectedMutexTrylockBusy)
|
var expectedUserServiceNoEvent =
|
||||||
|
string.Equals(nid, "yH17Q6NWtVg", StringComparison.Ordinal) &&
|
||||||
|
resultValue == unchecked((int)0x80960007);
|
||||||
|
var expectedPrivacyInvalidParameter =
|
||||||
|
string.Equals(nid, "D-CzAxQL0XI", StringComparison.Ordinal) &&
|
||||||
|
resultValue == unchecked((int)0x80960009);
|
||||||
|
if (!expectedFileProbeMiss &&
|
||||||
|
!expectedTimedWaitTimeout &&
|
||||||
|
!expectedEqueueTimeout &&
|
||||||
|
!expectedMutexTrylockBusy &&
|
||||||
|
!expectedUserServiceNoEvent &&
|
||||||
|
!expectedPrivacyInvalidParameter)
|
||||||
{
|
{
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
var key = nid + "\0" + (int)result;
|
if (!ShouldLogExpectedImportResults())
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var key = nid + "\0" + resultValue;
|
||||||
int count;
|
int count;
|
||||||
lock (_importResultLogSampleGate)
|
lock (_importResultLogSampleGate)
|
||||||
{
|
{
|
||||||
@@ -663,6 +694,12 @@ public sealed partial class DirectExecutionBackend
|
|||||||
return count <= 8 || count % 10000 == 0;
|
return count <= 8 || count % 10000 == 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static bool ShouldLogExpectedImportResults() =>
|
||||||
|
string.Equals(
|
||||||
|
Environment.GetEnvironmentVariable("SHARPEMU_LOG_EXPECTED_IMPORT_RESULTS"),
|
||||||
|
"1",
|
||||||
|
StringComparison.Ordinal);
|
||||||
|
|
||||||
private static bool IsExpectedFileProbeNotFoundNid(string nid) =>
|
private static bool IsExpectedFileProbeNotFoundNid(string nid) =>
|
||||||
nid is
|
nid is
|
||||||
"eV9wAD2riIA" or // sceKernelStat
|
"eV9wAD2riIA" or // sceKernelStat
|
||||||
|
|||||||
@@ -11,7 +11,9 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
|||||||
{
|
{
|
||||||
private readonly ReaderWriterLockSlim _gate = new(LockRecursionPolicy.SupportsRecursion);
|
private readonly ReaderWriterLockSlim _gate = new(LockRecursionPolicy.SupportsRecursion);
|
||||||
private readonly object _guestAllocationGate = new();
|
private readonly object _guestAllocationGate = new();
|
||||||
|
private readonly object _allocationSearchHintGate = new();
|
||||||
private readonly List<MemoryRegion> _regions = new();
|
private readonly List<MemoryRegion> _regions = new();
|
||||||
|
private readonly Dictionary<(ulong DesiredAddress, ulong Alignment, bool Executable), ulong> _allocationSearchHints = new();
|
||||||
private readonly Dictionary<ulong, ProgramHeaderFlags> _pageProtections = new();
|
private readonly Dictionary<ulong, ProgramHeaderFlags> _pageProtections = new();
|
||||||
private bool _disposed;
|
private bool _disposed;
|
||||||
private const ulong PageSize = 0x1000;
|
private const ulong PageSize = 0x1000;
|
||||||
@@ -19,7 +21,8 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
|||||||
private const ulong GuestAllocationArenaSize = 0x0100_0000;
|
private const ulong GuestAllocationArenaSize = 0x0100_0000;
|
||||||
private const ulong GuestAllocationArenaStartOffset = PageSize;
|
private const ulong GuestAllocationArenaStartOffset = PageSize;
|
||||||
private const ulong LargeDataReserveThreshold = 0x4000_0000UL; // 1 GiB
|
private const ulong LargeDataReserveThreshold = 0x4000_0000UL; // 1 GiB
|
||||||
private const ulong LazyReservePrimeBytes = 0x5000_0000UL; // 1.25 GiB
|
private const ulong FullCommitRegionLimit = 4UL << 30;
|
||||||
|
private const ulong DefaultLazyReservePrimeBytes = 0x0400_0000UL; // 64 MiB
|
||||||
private const ulong LazyReservePrimeChunkBytes = 0x0200_0000UL; // 32 MiB
|
private const ulong LazyReservePrimeChunkBytes = 0x0200_0000UL; // 32 MiB
|
||||||
|
|
||||||
private const uint MEM_COMMIT = 0x1000;
|
private const uint MEM_COMMIT = 0x1000;
|
||||||
@@ -35,6 +38,7 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
|||||||
|
|
||||||
private ulong _guestAllocationArenaBase;
|
private ulong _guestAllocationArenaBase;
|
||||||
private ulong _guestAllocationOffset;
|
private ulong _guestAllocationOffset;
|
||||||
|
private static readonly ulong LazyReservePrimeBytes = ResolveLazyReservePrimeBytes();
|
||||||
|
|
||||||
[DllImport("kernel32.dll", SetLastError = true)]
|
[DllImport("kernel32.dll", SetLastError = true)]
|
||||||
private static extern void* VirtualAlloc(void* lpAddress, nuint dwSize, uint flAllocationType, uint flProtect);
|
private static extern void* VirtualAlloc(void* lpAddress, nuint dwSize, uint flAllocationType, uint flProtect);
|
||||||
@@ -96,7 +100,7 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
|||||||
}
|
}
|
||||||
|
|
||||||
var allocationKind = executable ? "executable memory" : "data memory";
|
var allocationKind = executable ? "executable memory" : "data memory";
|
||||||
Console.Error.WriteLine($"[VMEM] Allocated exact {allocationKind}: 0x{actualAddress:X16} - 0x{actualAddress + alignedSize:X16} ({alignedSize} bytes)");
|
TraceVmem($"Allocated exact {allocationKind}: 0x{actualAddress:X16} - 0x{actualAddress + alignedSize:X16} ({alignedSize} bytes)");
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -110,7 +114,9 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
|||||||
var protection = executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
|
var protection = executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
|
||||||
var allocationType = MEM_COMMIT | MEM_RESERVE;
|
var allocationType = MEM_COMMIT | MEM_RESERVE;
|
||||||
var reservedOnly = false;
|
var reservedOnly = false;
|
||||||
var preferReserveOnly = !executable && alignedSize >= LargeDataReserveThreshold;
|
var preferReserveOnly = !executable &&
|
||||||
|
alignedSize >= LargeDataReserveThreshold &&
|
||||||
|
alignedSize > FullCommitRegionLimit;
|
||||||
|
|
||||||
void* result = null;
|
void* result = null;
|
||||||
if (preferReserveOnly)
|
if (preferReserveOnly)
|
||||||
@@ -139,7 +145,7 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
|||||||
throw new InvalidOperationException($"Failed to allocate exact mapping at 0x{desiredAddress:X16} ({alignedSize} bytes)");
|
throw new InvalidOperationException($"Failed to allocate exact mapping at 0x{desiredAddress:X16} ({alignedSize} bytes)");
|
||||||
}
|
}
|
||||||
|
|
||||||
Console.Error.WriteLine($"[VMEM] Could not allocate at 0x{desiredAddress:X16}, trying any address...");
|
TraceVmem($"Could not allocate at 0x{desiredAddress:X16}, trying any address...");
|
||||||
result = VirtualAlloc(null, (nuint)alignedSize, allocationType, protection);
|
result = VirtualAlloc(null, (nuint)alignedSize, allocationType, protection);
|
||||||
|
|
||||||
if (result == null)
|
if (result == null)
|
||||||
@@ -193,12 +199,12 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
|||||||
lazyPrimeState = committedBytes == primeBytes
|
lazyPrimeState = committedBytes == primeBytes
|
||||||
? $"ok:{committedBytes:X}"
|
? $"ok:{committedBytes:X}"
|
||||||
: $"partial:{committedBytes:X}/{primeBytes:X}";
|
: $"partial:{committedBytes:X}/{primeBytes:X}";
|
||||||
Console.Error.WriteLine($"[VMEM] Primed lazy region: 0x{actualAddress:X16} - 0x{actualAddress + committedBytes:X16} ({committedBytes} bytes)");
|
TraceVmem($"Primed lazy region: 0x{actualAddress:X16} - 0x{actualAddress + committedBytes:X16} ({committedBytes} bytes)");
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
lazyPrimeState = $"fail:{primeBytes:X}";
|
lazyPrimeState = $"fail:{primeBytes:X}";
|
||||||
Console.Error.WriteLine($"[VMEM] Failed to prime lazy region at 0x{actualAddress:X16} ({primeBytes} bytes), continuing with on-demand commit");
|
TraceVmem($"Failed to prime lazy region at 0x{actualAddress:X16} ({primeBytes} bytes), continuing with on-demand commit");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
@@ -227,7 +233,7 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
|||||||
var allocationKind = reservedOnly
|
var allocationKind = reservedOnly
|
||||||
? "reserved data memory (lazy commit)"
|
? "reserved data memory (lazy commit)"
|
||||||
: (executable ? "executable memory" : "data memory");
|
: (executable ? "executable memory" : "data memory");
|
||||||
Console.Error.WriteLine($"[VMEM] Allocated {allocationKind}: 0x{actualAddress:X16} - 0x{actualAddress + alignedSize:X16} ({alignedSize} bytes) lazy_prime={lazyPrimeState}");
|
TraceVmem($"Allocated {allocationKind}: 0x{actualAddress:X16} - 0x{actualAddress + alignedSize:X16} ({alignedSize} bytes) lazy_prime={lazyPrimeState}");
|
||||||
|
|
||||||
return actualAddress;
|
return actualAddress;
|
||||||
}
|
}
|
||||||
@@ -247,7 +253,8 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
|||||||
|
|
||||||
var alignedSize = AlignUp(size, PageSize);
|
var alignedSize = AlignUp(size, PageSize);
|
||||||
var effectiveAlignment = Math.Max(PageSize, alignment == 0 ? PageSize : alignment);
|
var effectiveAlignment = Math.Max(PageSize, alignment == 0 ? PageSize : alignment);
|
||||||
var cursor = AlignUp(desiredAddress, effectiveAlignment);
|
var requestedCursor = AlignUp(desiredAddress, effectiveAlignment);
|
||||||
|
var cursor = GetAllocationSearchCursor(desiredAddress, requestedCursor, effectiveAlignment, executable);
|
||||||
|
|
||||||
for (var attempt = 0; attempt < 0x10000; attempt++)
|
for (var attempt = 0; attempt < 0x10000; attempt++)
|
||||||
{
|
{
|
||||||
@@ -267,6 +274,7 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
|||||||
actualAddress = AllocateAt(cursor, alignedSize, executable, allowAlternative: false);
|
actualAddress = AllocateAt(cursor, alignedSize, executable, allowAlternative: false);
|
||||||
if (actualAddress == cursor)
|
if (actualAddress == cursor)
|
||||||
{
|
{
|
||||||
|
UpdateAllocationSearchCursor(desiredAddress, effectiveAlignment, executable, actualAddress + alignedSize);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -334,6 +342,10 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
|||||||
}
|
}
|
||||||
_regions.Clear();
|
_regions.Clear();
|
||||||
_pageProtections.Clear();
|
_pageProtections.Clear();
|
||||||
|
lock (_allocationSearchHintGate)
|
||||||
|
{
|
||||||
|
_allocationSearchHints.Clear();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
@@ -390,7 +402,7 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
|||||||
|
|
||||||
ApplySegmentProtection(mapStart, mapEnd, protection);
|
ApplySegmentProtection(mapStart, mapEnd, protection);
|
||||||
|
|
||||||
Console.Error.WriteLine($"[VMEM] Mapped segment: 0x{virtualAddress:X16} - 0x{virtualAddress + memorySize:X16} (file: {fileData.Length} bytes, prot: {protection})");
|
TraceVmem($"Mapped segment: 0x{virtualAddress:X16} - 0x{virtualAddress + memorySize:X16} (file: {fileData.Length} bytes, prot: {protection})");
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
@@ -793,6 +805,16 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
|||||||
foreach (var region in _regions)
|
foreach (var region in _regions)
|
||||||
{
|
{
|
||||||
var regionEnd = region.VirtualAddress + region.Size;
|
var regionEnd = region.VirtualAddress + region.Size;
|
||||||
|
if (region.VirtualAddress >= end)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (regionEnd <= address)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
if (address < regionEnd && region.VirtualAddress < end)
|
if (address < regionEnd && region.VirtualAddress < end)
|
||||||
{
|
{
|
||||||
overlapEnd = Math.Max(overlapEnd, regionEnd);
|
overlapEnd = Math.Max(overlapEnd, regionEnd);
|
||||||
@@ -807,6 +829,37 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
|||||||
return overlapEnd != 0;
|
return overlapEnd != 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private ulong GetAllocationSearchCursor(
|
||||||
|
ulong desiredAddress,
|
||||||
|
ulong requestedCursor,
|
||||||
|
ulong alignment,
|
||||||
|
bool executable)
|
||||||
|
{
|
||||||
|
lock (_allocationSearchHintGate)
|
||||||
|
{
|
||||||
|
var key = (desiredAddress, alignment, executable);
|
||||||
|
if (_allocationSearchHints.TryGetValue(key, out var hintedCursor) &&
|
||||||
|
hintedCursor > requestedCursor)
|
||||||
|
{
|
||||||
|
return AlignUp(hintedCursor, alignment);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return requestedCursor;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void UpdateAllocationSearchCursor(
|
||||||
|
ulong desiredAddress,
|
||||||
|
ulong alignment,
|
||||||
|
bool executable,
|
||||||
|
ulong nextCursor)
|
||||||
|
{
|
||||||
|
lock (_allocationSearchHintGate)
|
||||||
|
{
|
||||||
|
_allocationSearchHints[(desiredAddress, alignment, executable)] = AlignUp(nextCursor, alignment);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static bool TryResolveRegionOffset(ulong address, ulong size, MemoryRegion region, out ulong offset)
|
private static bool TryResolveRegionOffset(ulong address, ulong size, MemoryRegion region, out ulong offset)
|
||||||
{
|
{
|
||||||
offset = 0;
|
offset = 0;
|
||||||
@@ -975,6 +1028,29 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
|||||||
return checked((value + mask) & ~mask);
|
return checked((value + mask) & ~mask);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static ulong ResolveLazyReservePrimeBytes()
|
||||||
|
{
|
||||||
|
var configured = Environment.GetEnvironmentVariable("SHARPEMU_LAZY_RESERVE_PRIME_MB");
|
||||||
|
if (ulong.TryParse(configured, out var megabytes))
|
||||||
|
{
|
||||||
|
return megabytes == 0
|
||||||
|
? 0
|
||||||
|
: checked(Math.Min(megabytes, 4096UL) * 1024UL * 1024UL);
|
||||||
|
}
|
||||||
|
|
||||||
|
return DefaultLazyReservePrimeBytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TraceVmem(string message)
|
||||||
|
{
|
||||||
|
if (!string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_LOG_VMEM"), "1", StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Console.Error.WriteLine($"[VMEM] {message}");
|
||||||
|
}
|
||||||
|
|
||||||
public void Dispose()
|
public void Dispose()
|
||||||
{
|
{
|
||||||
if (!_disposed)
|
if (!_disposed)
|
||||||
|
|||||||
@@ -0,0 +1,118 @@
|
|||||||
|
<!--
|
||||||
|
Copyright (C) 2026 SharpEmu Emulator Project
|
||||||
|
SPDX-License-Identifier: GPL-2.0-or-later
|
||||||
|
-->
|
||||||
|
|
||||||
|
<Application xmlns="https://github.com/avaloniaui"
|
||||||
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
|
x:Class="SharpEmu.GUI.App"
|
||||||
|
RequestedThemeVariant="Dark">
|
||||||
|
|
||||||
|
<Application.Resources>
|
||||||
|
<Color x:Key="SystemAccentColor">#7C5CFC</Color>
|
||||||
|
|
||||||
|
<SolidColorBrush x:Key="BgBrush" Color="#0D1017" />
|
||||||
|
<SolidColorBrush x:Key="ChromeBrush" Color="#090C12" />
|
||||||
|
<SolidColorBrush x:Key="CardBrush" Color="#141924" />
|
||||||
|
<SolidColorBrush x:Key="CardBorderBrush" Color="#232B3A" />
|
||||||
|
<SolidColorBrush x:Key="ElevatedBrush" Color="#1B2230" />
|
||||||
|
<SolidColorBrush x:Key="TextBrush" Color="#E8ECF4" />
|
||||||
|
<SolidColorBrush x:Key="MutedBrush" Color="#8B94A7" />
|
||||||
|
<SolidColorBrush x:Key="FaintBrush" Color="#5A6478" />
|
||||||
|
<SolidColorBrush x:Key="AccentBrush" Color="#7C5CFC" />
|
||||||
|
<SolidColorBrush x:Key="AccentHoverBrush" Color="#8F73FF" />
|
||||||
|
<SolidColorBrush x:Key="DangerBrush" Color="#E5484D" />
|
||||||
|
<SolidColorBrush x:Key="DangerHoverBrush" Color="#F2555A" />
|
||||||
|
<SolidColorBrush x:Key="SuccessBrush" Color="#46C46B" />
|
||||||
|
</Application.Resources>
|
||||||
|
|
||||||
|
<Application.Styles>
|
||||||
|
<FluentTheme />
|
||||||
|
|
||||||
|
<Style Selector="Window">
|
||||||
|
<Setter Property="FontFamily" Value="Inter, Segoe UI, sans-serif" />
|
||||||
|
<Setter Property="Foreground" Value="{StaticResource TextBrush}" />
|
||||||
|
</Style>
|
||||||
|
|
||||||
|
<Style Selector="Border.card">
|
||||||
|
<Setter Property="Background" Value="{StaticResource CardBrush}" />
|
||||||
|
<Setter Property="BorderBrush" Value="{StaticResource CardBorderBrush}" />
|
||||||
|
<Setter Property="BorderThickness" Value="1" />
|
||||||
|
<Setter Property="CornerRadius" Value="10" />
|
||||||
|
<Setter Property="Padding" Value="16" />
|
||||||
|
</Style>
|
||||||
|
|
||||||
|
<Style Selector="Border.pill">
|
||||||
|
<Setter Property="Background" Value="{StaticResource ElevatedBrush}" />
|
||||||
|
<Setter Property="CornerRadius" Value="999" />
|
||||||
|
<Setter Property="Padding" Value="10,3" />
|
||||||
|
</Style>
|
||||||
|
|
||||||
|
<Style Selector="TextBlock.sectionTitle">
|
||||||
|
<Setter Property="FontSize" Value="11" />
|
||||||
|
<Setter Property="FontWeight" Value="SemiBold" />
|
||||||
|
<Setter Property="LetterSpacing" Value="1.5" />
|
||||||
|
<Setter Property="Foreground" Value="{StaticResource MutedBrush}" />
|
||||||
|
</Style>
|
||||||
|
|
||||||
|
<Style Selector="TextBlock.fieldLabel">
|
||||||
|
<Setter Property="FontSize" Value="12" />
|
||||||
|
<Setter Property="Foreground" Value="{StaticResource MutedBrush}" />
|
||||||
|
<Setter Property="Margin" Value="0,0,0,6" />
|
||||||
|
</Style>
|
||||||
|
|
||||||
|
<Style Selector="Button.accent">
|
||||||
|
<Setter Property="Background" Value="{StaticResource AccentBrush}" />
|
||||||
|
<Setter Property="Foreground" Value="White" />
|
||||||
|
<Setter Property="FontWeight" Value="SemiBold" />
|
||||||
|
<Setter Property="Padding" Value="22,10" />
|
||||||
|
<Setter Property="CornerRadius" Value="8" />
|
||||||
|
</Style>
|
||||||
|
<Style Selector="Button.accent:pointerover /template/ ContentPresenter#PART_ContentPresenter">
|
||||||
|
<Setter Property="Background" Value="{StaticResource AccentHoverBrush}" />
|
||||||
|
<Setter Property="Foreground" Value="White" />
|
||||||
|
</Style>
|
||||||
|
|
||||||
|
<Style Selector="Button.danger">
|
||||||
|
<Setter Property="Background" Value="{StaticResource DangerBrush}" />
|
||||||
|
<Setter Property="Foreground" Value="White" />
|
||||||
|
<Setter Property="FontWeight" Value="SemiBold" />
|
||||||
|
<Setter Property="Padding" Value="22,10" />
|
||||||
|
<Setter Property="CornerRadius" Value="8" />
|
||||||
|
</Style>
|
||||||
|
<Style Selector="Button.danger:pointerover /template/ ContentPresenter#PART_ContentPresenter">
|
||||||
|
<Setter Property="Background" Value="{StaticResource DangerHoverBrush}" />
|
||||||
|
<Setter Property="Foreground" Value="White" />
|
||||||
|
</Style>
|
||||||
|
|
||||||
|
<Style Selector="Button.ghost">
|
||||||
|
<Setter Property="Background" Value="Transparent" />
|
||||||
|
<Setter Property="BorderBrush" Value="{StaticResource CardBorderBrush}" />
|
||||||
|
<Setter Property="BorderThickness" Value="1" />
|
||||||
|
<Setter Property="Foreground" Value="{StaticResource TextBrush}" />
|
||||||
|
<Setter Property="Padding" Value="12,7" />
|
||||||
|
<Setter Property="CornerRadius" Value="8" />
|
||||||
|
</Style>
|
||||||
|
<Style Selector="Button.ghost:pointerover /template/ ContentPresenter#PART_ContentPresenter">
|
||||||
|
<Setter Property="Background" Value="{StaticResource ElevatedBrush}" />
|
||||||
|
<Setter Property="Foreground" Value="{StaticResource TextBrush}" />
|
||||||
|
</Style>
|
||||||
|
|
||||||
|
<Style Selector="ListBox.console">
|
||||||
|
<Setter Property="Background" Value="#0B0E14" />
|
||||||
|
<Setter Property="FontFamily" Value="Cascadia Mono, Consolas, Courier New, monospace" />
|
||||||
|
<Setter Property="FontSize" Value="12" />
|
||||||
|
</Style>
|
||||||
|
<Style Selector="ListBox.console ListBoxItem">
|
||||||
|
<Setter Property="Padding" Value="10,1" />
|
||||||
|
<Setter Property="MinHeight" Value="0" />
|
||||||
|
</Style>
|
||||||
|
|
||||||
|
<Style Selector="ListBox.library ListBoxItem">
|
||||||
|
<Setter Property="CornerRadius" Value="8" />
|
||||||
|
<Setter Property="Margin" Value="4,2" />
|
||||||
|
<Setter Property="Padding" Value="8,4" />
|
||||||
|
</Style>
|
||||||
|
</Application.Styles>
|
||||||
|
|
||||||
|
</Application>
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||||
|
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||||
|
|
||||||
|
using Avalonia;
|
||||||
|
using Avalonia.Controls.ApplicationLifetimes;
|
||||||
|
using Avalonia.Markup.Xaml;
|
||||||
|
|
||||||
|
namespace SharpEmu.GUI;
|
||||||
|
|
||||||
|
public partial class App : Application
|
||||||
|
{
|
||||||
|
public override void Initialize()
|
||||||
|
{
|
||||||
|
AvaloniaXamlLoader.Load(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void OnFrameworkInitializationCompleted()
|
||||||
|
{
|
||||||
|
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||||||
|
{
|
||||||
|
desktop.MainWindow = new MainWindow();
|
||||||
|
}
|
||||||
|
|
||||||
|
base.OnFrameworkInitializationCompleted();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,645 @@
|
|||||||
|
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||||
|
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||||
|
|
||||||
|
using System.ComponentModel;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
using System.Text;
|
||||||
|
using Microsoft.Win32.SafeHandles;
|
||||||
|
|
||||||
|
namespace SharpEmu.GUI;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Launches the SharpEmu CLI as a child process with the same CET/CFG mitigation
|
||||||
|
/// opt-outs the CLI would apply to its own relaunched child, while capturing
|
||||||
|
/// stdout/stderr through pipes. The CLI's internal relaunch is suppressed via
|
||||||
|
/// SHARPEMU_DISABLE_MITIGATION_RELAUNCH so output is not lost to a detached
|
||||||
|
/// console. A kill-on-close job object ties the emulator's lifetime to the GUI.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class EmulatorProcess : IDisposable
|
||||||
|
{
|
||||||
|
private const uint EXTENDED_STARTUPINFO_PRESENT = 0x00080000;
|
||||||
|
private const uint CREATE_NO_WINDOW = 0x08000000;
|
||||||
|
private const int STARTF_USESTDHANDLES = 0x00000100;
|
||||||
|
private const uint HANDLE_FLAG_INHERIT = 0x00000001;
|
||||||
|
private const uint INFINITE = 0xFFFFFFFF;
|
||||||
|
private const int PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY = 0x00020007;
|
||||||
|
private const uint JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000;
|
||||||
|
private const int JobObjectExtendedLimitInformation = 9;
|
||||||
|
private const ulong PROCESS_CREATION_MITIGATION_POLICY_CONTROL_FLOW_GUARD_ALWAYS_OFF = 0x00000002UL << 40;
|
||||||
|
private const ulong PROCESS_CREATION_MITIGATION_POLICY2_CET_USER_SHADOW_STACKS_ALWAYS_OFF = 0x00000002UL << 28;
|
||||||
|
private const ulong PROCESS_CREATION_MITIGATION_POLICY2_USER_CET_SET_CONTEXT_IP_VALIDATION_ALWAYS_OFF = 0x00000002UL << 32;
|
||||||
|
private const ulong PROCESS_CREATION_MITIGATION_POLICY2_XTENDED_CONTROL_FLOW_GUARD_ALWAYS_OFF = 0x00000002UL << 40;
|
||||||
|
|
||||||
|
private readonly object _sync = new();
|
||||||
|
private nint _processHandle;
|
||||||
|
private nint _jobHandle;
|
||||||
|
private Process? _fallbackProcess;
|
||||||
|
private bool _running;
|
||||||
|
private bool _disposed;
|
||||||
|
|
||||||
|
public event Action<string, bool>? OutputReceived;
|
||||||
|
|
||||||
|
public event Action<int>? Exited;
|
||||||
|
|
||||||
|
public bool IsRunning
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
lock (_sync)
|
||||||
|
{
|
||||||
|
return _running;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Start(string exePath, IReadOnlyList<string> arguments, string? workingDirectory)
|
||||||
|
{
|
||||||
|
lock (_sync)
|
||||||
|
{
|
||||||
|
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||||
|
if (_running)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("The emulator process is already running.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (OperatingSystem.IsWindows())
|
||||||
|
{
|
||||||
|
StartWindows(exePath, arguments, workingDirectory);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
StartFallback(exePath, arguments, workingDirectory);
|
||||||
|
}
|
||||||
|
|
||||||
|
_running = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Stop()
|
||||||
|
{
|
||||||
|
lock (_sync)
|
||||||
|
{
|
||||||
|
if (!_running)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_processHandle != 0)
|
||||||
|
{
|
||||||
|
_ = TerminateProcess(_processHandle, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_fallbackProcess?.Kill(entireProcessTree: true);
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException)
|
||||||
|
{
|
||||||
|
// Already exited.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
lock (_sync)
|
||||||
|
{
|
||||||
|
if (_disposed)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_disposed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
Stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void StartWindows(string exePath, IReadOnlyList<string> arguments, string? workingDirectory)
|
||||||
|
{
|
||||||
|
// The CLI would otherwise relaunch itself into a mitigated child whose
|
||||||
|
// console output cannot flow through our pipes.
|
||||||
|
Environment.SetEnvironmentVariable("SHARPEMU_DISABLE_MITIGATION_RELAUNCH", "1");
|
||||||
|
|
||||||
|
var securityAttributes = new SECURITY_ATTRIBUTES
|
||||||
|
{
|
||||||
|
nLength = Marshal.SizeOf<SECURITY_ATTRIBUTES>(),
|
||||||
|
bInheritHandle = 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!CreatePipe(out var stdoutRead, out var stdoutWrite, ref securityAttributes, 0) ||
|
||||||
|
!CreatePipe(out var stderrRead, out var stderrWrite, ref securityAttributes, 0))
|
||||||
|
{
|
||||||
|
throw new Win32Exception(Marshal.GetLastWin32Error(), "Failed to create output pipes.");
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = SetHandleInformation(stdoutRead, HANDLE_FLAG_INHERIT, 0);
|
||||||
|
_ = SetHandleInformation(stderrRead, HANDLE_FLAG_INHERIT, 0);
|
||||||
|
|
||||||
|
var startupInfoEx = new STARTUPINFOEX();
|
||||||
|
startupInfoEx.StartupInfo.cb = Marshal.SizeOf<STARTUPINFOEX>();
|
||||||
|
startupInfoEx.StartupInfo.dwFlags = STARTF_USESTDHANDLES;
|
||||||
|
startupInfoEx.StartupInfo.hStdOutput = stdoutWrite;
|
||||||
|
startupInfoEx.StartupInfo.hStdError = stderrWrite;
|
||||||
|
|
||||||
|
nint attributeList = 0;
|
||||||
|
nint mitigationPolicies = 0;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
nuint attributeListSize = 0;
|
||||||
|
_ = InitializeProcThreadAttributeList(0, 1, 0, ref attributeListSize);
|
||||||
|
attributeList = Marshal.AllocHGlobal((nint)attributeListSize);
|
||||||
|
if (!InitializeProcThreadAttributeList(attributeList, 1, 0, ref attributeListSize))
|
||||||
|
{
|
||||||
|
throw new Win32Exception(Marshal.GetLastWin32Error(), "Failed to initialize the process attribute list.");
|
||||||
|
}
|
||||||
|
|
||||||
|
startupInfoEx.lpAttributeList = attributeList;
|
||||||
|
|
||||||
|
var policy1 = PROCESS_CREATION_MITIGATION_POLICY_CONTROL_FLOW_GUARD_ALWAYS_OFF;
|
||||||
|
var policy2 =
|
||||||
|
PROCESS_CREATION_MITIGATION_POLICY2_CET_USER_SHADOW_STACKS_ALWAYS_OFF |
|
||||||
|
PROCESS_CREATION_MITIGATION_POLICY2_USER_CET_SET_CONTEXT_IP_VALIDATION_ALWAYS_OFF |
|
||||||
|
PROCESS_CREATION_MITIGATION_POLICY2_XTENDED_CONTROL_FLOW_GUARD_ALWAYS_OFF;
|
||||||
|
|
||||||
|
mitigationPolicies = Marshal.AllocHGlobal(sizeof(ulong) * 2);
|
||||||
|
Marshal.WriteInt64(mitigationPolicies, unchecked((long)policy1));
|
||||||
|
Marshal.WriteInt64(nint.Add(mitigationPolicies, sizeof(long)), unchecked((long)policy2));
|
||||||
|
|
||||||
|
if (!UpdateProcThreadAttribute(
|
||||||
|
attributeList,
|
||||||
|
0,
|
||||||
|
PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY,
|
||||||
|
mitigationPolicies,
|
||||||
|
(nuint)(sizeof(ulong) * 2),
|
||||||
|
0,
|
||||||
|
0))
|
||||||
|
{
|
||||||
|
throw new Win32Exception(Marshal.GetLastWin32Error(), "Failed to apply the mitigation policy.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var currentDirectory = workingDirectory ?? Environment.CurrentDirectory;
|
||||||
|
var created = CreateProcessW(
|
||||||
|
exePath,
|
||||||
|
new StringBuilder(BuildCommandLine(exePath, arguments)),
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
true,
|
||||||
|
EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW,
|
||||||
|
0,
|
||||||
|
currentDirectory,
|
||||||
|
ref startupInfoEx,
|
||||||
|
out var processInfo);
|
||||||
|
|
||||||
|
if (!created)
|
||||||
|
{
|
||||||
|
// Some mitigation policy bits (e.g. XFG) are not supported on
|
||||||
|
// older Windows builds. Mirror the CLI's behavior and fall back
|
||||||
|
// to launching without the mitigation attribute list.
|
||||||
|
startupInfoEx.lpAttributeList = 0;
|
||||||
|
created = CreateProcessW(
|
||||||
|
exePath,
|
||||||
|
new StringBuilder(BuildCommandLine(exePath, arguments)),
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
true,
|
||||||
|
CREATE_NO_WINDOW,
|
||||||
|
0,
|
||||||
|
currentDirectory,
|
||||||
|
ref startupInfoEx,
|
||||||
|
out processInfo);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!created)
|
||||||
|
{
|
||||||
|
var error = Marshal.GetLastWin32Error();
|
||||||
|
throw new Win32Exception(error, $"Failed to start '{exePath}' (Win32 error {error}: {new Win32Exception(error).Message}).");
|
||||||
|
}
|
||||||
|
|
||||||
|
CloseHandle(processInfo.hThread);
|
||||||
|
_processHandle = processInfo.hProcess;
|
||||||
|
|
||||||
|
_jobHandle = CreateJobObjectW(0, null);
|
||||||
|
if (_jobHandle != 0 &&
|
||||||
|
(!TryEnableKillOnJobClose(_jobHandle) || !AssignProcessToJobObject(_jobHandle, processInfo.hProcess)))
|
||||||
|
{
|
||||||
|
CloseHandle(_jobHandle);
|
||||||
|
_jobHandle = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
StartReaderThread(stdoutRead, isError: false);
|
||||||
|
StartReaderThread(stderrRead, isError: true);
|
||||||
|
StartExitWatcherThread();
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
CloseHandle(stdoutRead);
|
||||||
|
CloseHandle(stderrRead);
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
// The child owns duplicated pipe write ends; closing ours lets the
|
||||||
|
// readers observe EOF when the child exits.
|
||||||
|
CloseHandle(stdoutWrite);
|
||||||
|
CloseHandle(stderrWrite);
|
||||||
|
|
||||||
|
if (attributeList != 0)
|
||||||
|
{
|
||||||
|
DeleteProcThreadAttributeList(attributeList);
|
||||||
|
Marshal.FreeHGlobal(attributeList);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mitigationPolicies != 0)
|
||||||
|
{
|
||||||
|
Marshal.FreeHGlobal(mitigationPolicies);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void StartFallback(string exePath, IReadOnlyList<string> arguments, string? workingDirectory)
|
||||||
|
{
|
||||||
|
var startInfo = new ProcessStartInfo
|
||||||
|
{
|
||||||
|
FileName = exePath,
|
||||||
|
WorkingDirectory = workingDirectory ?? Environment.CurrentDirectory,
|
||||||
|
UseShellExecute = false,
|
||||||
|
CreateNoWindow = true,
|
||||||
|
RedirectStandardOutput = true,
|
||||||
|
RedirectStandardError = true,
|
||||||
|
};
|
||||||
|
foreach (var argument in arguments)
|
||||||
|
{
|
||||||
|
startInfo.ArgumentList.Add(argument);
|
||||||
|
}
|
||||||
|
|
||||||
|
var process = new Process { StartInfo = startInfo, EnableRaisingEvents = true };
|
||||||
|
process.OutputDataReceived += (_, e) =>
|
||||||
|
{
|
||||||
|
if (e.Data is not null)
|
||||||
|
{
|
||||||
|
OutputReceived?.Invoke(e.Data, false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
process.ErrorDataReceived += (_, e) =>
|
||||||
|
{
|
||||||
|
if (e.Data is not null)
|
||||||
|
{
|
||||||
|
OutputReceived?.Invoke(e.Data, true);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
process.Exited += (_, _) =>
|
||||||
|
{
|
||||||
|
int exitCode;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
exitCode = process.ExitCode;
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException)
|
||||||
|
{
|
||||||
|
exitCode = -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
OnExited(exitCode);
|
||||||
|
};
|
||||||
|
|
||||||
|
process.Start();
|
||||||
|
process.BeginOutputReadLine();
|
||||||
|
process.BeginErrorReadLine();
|
||||||
|
_fallbackProcess = process;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void StartReaderThread(nint readHandle, bool isError)
|
||||||
|
{
|
||||||
|
var thread = new Thread(() =>
|
||||||
|
{
|
||||||
|
using var stream = new FileStream(new SafeFileHandle(readHandle, ownsHandle: true), FileAccess.Read);
|
||||||
|
using var reader = new StreamReader(stream, Encoding.UTF8);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
while (reader.ReadLine() is { } line)
|
||||||
|
{
|
||||||
|
OutputReceived?.Invoke(line, isError);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (IOException)
|
||||||
|
{
|
||||||
|
// Pipe broken on process teardown.
|
||||||
|
}
|
||||||
|
})
|
||||||
|
{
|
||||||
|
IsBackground = true,
|
||||||
|
Name = isError ? "SharpEmu stderr reader" : "SharpEmu stdout reader",
|
||||||
|
};
|
||||||
|
thread.Start();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void StartExitWatcherThread()
|
||||||
|
{
|
||||||
|
var processHandle = _processHandle;
|
||||||
|
var thread = new Thread(() =>
|
||||||
|
{
|
||||||
|
_ = WaitForSingleObject(processHandle, INFINITE);
|
||||||
|
var exitCode = GetExitCodeProcess(processHandle, out var rawExitCode)
|
||||||
|
? unchecked((int)rawExitCode)
|
||||||
|
: -1;
|
||||||
|
OnExited(exitCode);
|
||||||
|
})
|
||||||
|
{
|
||||||
|
IsBackground = true,
|
||||||
|
Name = "SharpEmu exit watcher",
|
||||||
|
};
|
||||||
|
thread.Start();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnExited(int exitCode)
|
||||||
|
{
|
||||||
|
lock (_sync)
|
||||||
|
{
|
||||||
|
if (!_running)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_running = false;
|
||||||
|
if (_processHandle != 0)
|
||||||
|
{
|
||||||
|
CloseHandle(_processHandle);
|
||||||
|
_processHandle = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_jobHandle != 0)
|
||||||
|
{
|
||||||
|
CloseHandle(_jobHandle);
|
||||||
|
_jobHandle = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
_fallbackProcess?.Dispose();
|
||||||
|
_fallbackProcess = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
Exited?.Invoke(exitCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryEnableKillOnJobClose(nint jobHandle)
|
||||||
|
{
|
||||||
|
var extendedLimitInfo = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION
|
||||||
|
{
|
||||||
|
BasicLimitInformation = new JOBOBJECT_BASIC_LIMIT_INFORMATION
|
||||||
|
{
|
||||||
|
LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
var size = Marshal.SizeOf<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>();
|
||||||
|
var memory = Marshal.AllocHGlobal(size);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Marshal.StructureToPtr(extendedLimitInfo, memory, false);
|
||||||
|
return SetInformationJobObject(
|
||||||
|
jobHandle,
|
||||||
|
JobObjectExtendedLimitInformation,
|
||||||
|
memory,
|
||||||
|
unchecked((uint)size));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Marshal.FreeHGlobal(memory);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string BuildCommandLine(string processPath, IReadOnlyList<string> args)
|
||||||
|
{
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
builder.Append(QuoteArgument(processPath));
|
||||||
|
for (var i = 0; i < args.Count; i++)
|
||||||
|
{
|
||||||
|
builder.Append(' ');
|
||||||
|
builder.Append(QuoteArgument(args[i]));
|
||||||
|
}
|
||||||
|
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string QuoteArgument(string argument)
|
||||||
|
{
|
||||||
|
if (argument.Length == 0)
|
||||||
|
{
|
||||||
|
return "\"\"";
|
||||||
|
}
|
||||||
|
|
||||||
|
var needsQuotes = false;
|
||||||
|
foreach (var c in argument)
|
||||||
|
{
|
||||||
|
if (char.IsWhiteSpace(c) || c == '"')
|
||||||
|
{
|
||||||
|
needsQuotes = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!needsQuotes)
|
||||||
|
{
|
||||||
|
return argument;
|
||||||
|
}
|
||||||
|
|
||||||
|
var builder = new StringBuilder(argument.Length + 2);
|
||||||
|
builder.Append('"');
|
||||||
|
|
||||||
|
var backslashCount = 0;
|
||||||
|
foreach (var c in argument)
|
||||||
|
{
|
||||||
|
if (c == '\\')
|
||||||
|
{
|
||||||
|
backslashCount++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c == '"')
|
||||||
|
{
|
||||||
|
builder.Append('\\', (backslashCount * 2) + 1);
|
||||||
|
builder.Append('"');
|
||||||
|
backslashCount = 0;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (backslashCount > 0)
|
||||||
|
{
|
||||||
|
builder.Append('\\', backslashCount);
|
||||||
|
backslashCount = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
builder.Append(c);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (backslashCount > 0)
|
||||||
|
{
|
||||||
|
builder.Append('\\', backslashCount * 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
builder.Append('"');
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
[StructLayout(LayoutKind.Sequential)]
|
||||||
|
private struct SECURITY_ATTRIBUTES
|
||||||
|
{
|
||||||
|
public int nLength;
|
||||||
|
public nint lpSecurityDescriptor;
|
||||||
|
public int bInheritHandle;
|
||||||
|
}
|
||||||
|
|
||||||
|
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
||||||
|
private struct STARTUPINFO
|
||||||
|
{
|
||||||
|
public int cb;
|
||||||
|
public nint lpReserved;
|
||||||
|
public nint lpDesktop;
|
||||||
|
public nint lpTitle;
|
||||||
|
public int dwX;
|
||||||
|
public int dwY;
|
||||||
|
public int dwXSize;
|
||||||
|
public int dwYSize;
|
||||||
|
public int dwXCountChars;
|
||||||
|
public int dwYCountChars;
|
||||||
|
public int dwFillAttribute;
|
||||||
|
public int dwFlags;
|
||||||
|
public short wShowWindow;
|
||||||
|
public short cbReserved2;
|
||||||
|
public nint lpReserved2;
|
||||||
|
public nint hStdInput;
|
||||||
|
public nint hStdOutput;
|
||||||
|
public nint hStdError;
|
||||||
|
}
|
||||||
|
|
||||||
|
[StructLayout(LayoutKind.Sequential)]
|
||||||
|
private struct STARTUPINFOEX
|
||||||
|
{
|
||||||
|
public STARTUPINFO StartupInfo;
|
||||||
|
public nint lpAttributeList;
|
||||||
|
}
|
||||||
|
|
||||||
|
[StructLayout(LayoutKind.Sequential)]
|
||||||
|
private struct PROCESS_INFORMATION
|
||||||
|
{
|
||||||
|
public nint hProcess;
|
||||||
|
public nint hThread;
|
||||||
|
public int dwProcessId;
|
||||||
|
public int dwThreadId;
|
||||||
|
}
|
||||||
|
|
||||||
|
[StructLayout(LayoutKind.Sequential)]
|
||||||
|
private struct JOBOBJECT_BASIC_LIMIT_INFORMATION
|
||||||
|
{
|
||||||
|
public long PerProcessUserTimeLimit;
|
||||||
|
public long PerJobUserTimeLimit;
|
||||||
|
public uint LimitFlags;
|
||||||
|
public nuint MinimumWorkingSetSize;
|
||||||
|
public nuint MaximumWorkingSetSize;
|
||||||
|
public uint ActiveProcessLimit;
|
||||||
|
public nint Affinity;
|
||||||
|
public uint PriorityClass;
|
||||||
|
public uint SchedulingClass;
|
||||||
|
}
|
||||||
|
|
||||||
|
[StructLayout(LayoutKind.Sequential)]
|
||||||
|
private struct IO_COUNTERS
|
||||||
|
{
|
||||||
|
public ulong ReadOperationCount;
|
||||||
|
public ulong WriteOperationCount;
|
||||||
|
public ulong OtherOperationCount;
|
||||||
|
public ulong ReadTransferCount;
|
||||||
|
public ulong WriteTransferCount;
|
||||||
|
public ulong OtherTransferCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
[StructLayout(LayoutKind.Sequential)]
|
||||||
|
private struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION
|
||||||
|
{
|
||||||
|
public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation;
|
||||||
|
public IO_COUNTERS IoInfo;
|
||||||
|
public nuint ProcessMemoryLimit;
|
||||||
|
public nuint JobMemoryLimit;
|
||||||
|
public nuint PeakProcessMemoryUsed;
|
||||||
|
public nuint PeakJobMemoryUsed;
|
||||||
|
}
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll", SetLastError = true)]
|
||||||
|
[return: MarshalAs(UnmanagedType.Bool)]
|
||||||
|
private static extern bool CreatePipe(
|
||||||
|
out nint hReadPipe,
|
||||||
|
out nint hWritePipe,
|
||||||
|
ref SECURITY_ATTRIBUTES lpPipeAttributes,
|
||||||
|
uint nSize);
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll", SetLastError = true)]
|
||||||
|
[return: MarshalAs(UnmanagedType.Bool)]
|
||||||
|
private static extern bool SetHandleInformation(nint hObject, uint dwMask, uint dwFlags);
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll", SetLastError = true)]
|
||||||
|
[return: MarshalAs(UnmanagedType.Bool)]
|
||||||
|
private static extern bool InitializeProcThreadAttributeList(
|
||||||
|
nint lpAttributeList,
|
||||||
|
int dwAttributeCount,
|
||||||
|
int dwFlags,
|
||||||
|
ref nuint lpSize);
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll", SetLastError = true)]
|
||||||
|
[return: MarshalAs(UnmanagedType.Bool)]
|
||||||
|
private static extern bool UpdateProcThreadAttribute(
|
||||||
|
nint lpAttributeList,
|
||||||
|
uint dwFlags,
|
||||||
|
nint attribute,
|
||||||
|
nint lpValue,
|
||||||
|
nuint cbSize,
|
||||||
|
nint lpPreviousValue,
|
||||||
|
nint lpReturnSize);
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll")]
|
||||||
|
private static extern void DeleteProcThreadAttributeList(nint lpAttributeList);
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll", EntryPoint = "CreateJobObjectW", SetLastError = true, CharSet = CharSet.Unicode)]
|
||||||
|
private static extern nint CreateJobObjectW(nint lpJobAttributes, string? lpName);
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll", SetLastError = true)]
|
||||||
|
[return: MarshalAs(UnmanagedType.Bool)]
|
||||||
|
private static extern bool SetInformationJobObject(
|
||||||
|
nint hJob,
|
||||||
|
int jobObjectInfoClass,
|
||||||
|
nint lpJobObjectInfo,
|
||||||
|
uint cbJobObjectInfoLength);
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll", SetLastError = true)]
|
||||||
|
[return: MarshalAs(UnmanagedType.Bool)]
|
||||||
|
private static extern bool AssignProcessToJobObject(nint hJob, nint hProcess);
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll", EntryPoint = "CreateProcessW", SetLastError = true, CharSet = CharSet.Unicode)]
|
||||||
|
[return: MarshalAs(UnmanagedType.Bool)]
|
||||||
|
private static extern bool CreateProcessW(
|
||||||
|
string applicationName,
|
||||||
|
StringBuilder commandLine,
|
||||||
|
nint processAttributes,
|
||||||
|
nint threadAttributes,
|
||||||
|
[MarshalAs(UnmanagedType.Bool)] bool inheritHandles,
|
||||||
|
uint creationFlags,
|
||||||
|
nint environment,
|
||||||
|
string currentDirectory,
|
||||||
|
ref STARTUPINFOEX startupInfo,
|
||||||
|
out PROCESS_INFORMATION processInformation);
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll", SetLastError = true)]
|
||||||
|
private static extern uint WaitForSingleObject(nint handle, uint milliseconds);
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll", SetLastError = true)]
|
||||||
|
[return: MarshalAs(UnmanagedType.Bool)]
|
||||||
|
private static extern bool GetExitCodeProcess(nint process, out uint exitCode);
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll", SetLastError = true)]
|
||||||
|
[return: MarshalAs(UnmanagedType.Bool)]
|
||||||
|
private static extern bool TerminateProcess(nint process, uint exitCode);
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll", SetLastError = true)]
|
||||||
|
[return: MarshalAs(UnmanagedType.Bool)]
|
||||||
|
private static extern bool CloseHandle(nint handle);
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||||
|
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||||
|
|
||||||
|
namespace SharpEmu.GUI;
|
||||||
|
|
||||||
|
public sealed record GameEntry(string Name, string? TitleId, string Path, long SizeBytes)
|
||||||
|
{
|
||||||
|
public string Detail => TitleId is not null
|
||||||
|
? $"{TitleId} • {FormatSize(SizeBytes)}"
|
||||||
|
: $"{FormatSize(SizeBytes)} • {Path}";
|
||||||
|
|
||||||
|
private static string FormatSize(long bytes)
|
||||||
|
{
|
||||||
|
return bytes switch
|
||||||
|
{
|
||||||
|
>= 1L << 30 => $"{bytes / (double)(1L << 30):0.0} GiB",
|
||||||
|
>= 1L << 20 => $"{bytes / (double)(1L << 20):0.0} MiB",
|
||||||
|
>= 1L << 10 => $"{bytes / (double)(1L << 10):0.0} KiB",
|
||||||
|
_ => $"{bytes} B",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||||
|
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||||
|
|
||||||
|
using Avalonia;
|
||||||
|
|
||||||
|
namespace SharpEmu.GUI;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Entry point for the desktop frontend, hosted by the SharpEmu executable
|
||||||
|
/// when it is started without command-line arguments.
|
||||||
|
/// </summary>
|
||||||
|
public static class GuiLauncher
|
||||||
|
{
|
||||||
|
public static int Run()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
BuildAvaloniaApp().StartWithClassicDesktopLifetime(Array.Empty<string>());
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
WriteCrashLog(ex);
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static AppBuilder BuildAvaloniaApp()
|
||||||
|
=> AppBuilder.Configure<App>()
|
||||||
|
.UsePlatformDetect()
|
||||||
|
.WithInterFont()
|
||||||
|
.LogToTrace();
|
||||||
|
|
||||||
|
private static void WriteCrashLog(Exception ex)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.AppendAllText(
|
||||||
|
Path.Combine(AppContext.BaseDirectory, "gui-crash.log"),
|
||||||
|
$"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {ex}{Environment.NewLine}{Environment.NewLine}");
|
||||||
|
}
|
||||||
|
catch (Exception)
|
||||||
|
{
|
||||||
|
// Crash logging is best-effort.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||||
|
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||||
|
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
namespace SharpEmu.GUI;
|
||||||
|
|
||||||
|
public sealed class GuiSettings
|
||||||
|
{
|
||||||
|
private static readonly JsonSerializerOptions SerializerOptions = new()
|
||||||
|
{
|
||||||
|
WriteIndented = true,
|
||||||
|
};
|
||||||
|
|
||||||
|
public List<string> GameFolders { get; set; } = new();
|
||||||
|
|
||||||
|
public string LogLevel { get; set; } = "Info";
|
||||||
|
|
||||||
|
public int ImportTraceLimit { get; set; }
|
||||||
|
|
||||||
|
public bool StrictDynlibResolution { get; set; }
|
||||||
|
|
||||||
|
public string? EmulatorPath { get; set; }
|
||||||
|
|
||||||
|
// The emulator is portable and keeps its data next to the executable;
|
||||||
|
// the GUI follows the same convention.
|
||||||
|
public static string SettingsPath => Path.Combine(AppContext.BaseDirectory, "gui-settings.json");
|
||||||
|
|
||||||
|
public static GuiSettings Load()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (File.Exists(SettingsPath))
|
||||||
|
{
|
||||||
|
var json = File.ReadAllText(SettingsPath);
|
||||||
|
return JsonSerializer.Deserialize<GuiSettings>(json, SerializerOptions) ?? new GuiSettings();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception)
|
||||||
|
{
|
||||||
|
// Corrupt or unreadable settings fall back to defaults.
|
||||||
|
}
|
||||||
|
|
||||||
|
return new GuiSettings();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Save()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var directory = Path.GetDirectoryName(SettingsPath);
|
||||||
|
if (!string.IsNullOrEmpty(directory))
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(directory);
|
||||||
|
}
|
||||||
|
|
||||||
|
File.WriteAllText(SettingsPath, JsonSerializer.Serialize(this, SerializerOptions));
|
||||||
|
}
|
||||||
|
catch (Exception)
|
||||||
|
{
|
||||||
|
// Settings persistence is best-effort.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||||
|
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||||
|
|
||||||
|
using Avalonia.Media;
|
||||||
|
|
||||||
|
namespace SharpEmu.GUI;
|
||||||
|
|
||||||
|
public sealed record LogLine(string Text, IBrush Brush);
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
<!--
|
||||||
|
Copyright (C) 2026 SharpEmu Emulator Project
|
||||||
|
SPDX-License-Identifier: GPL-2.0-or-later
|
||||||
|
-->
|
||||||
|
|
||||||
|
<Window xmlns="https://github.com/avaloniaui"
|
||||||
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
|
x:Class="SharpEmu.GUI.MainWindow"
|
||||||
|
Title="SharpEmu"
|
||||||
|
Width="1280" Height="800"
|
||||||
|
MinWidth="980" MinHeight="620"
|
||||||
|
WindowStartupLocation="CenterScreen"
|
||||||
|
Background="{StaticResource BgBrush}"
|
||||||
|
ExtendClientAreaToDecorationsHint="True"
|
||||||
|
ExtendClientAreaChromeHints="PreferSystemChrome"
|
||||||
|
ExtendClientAreaTitleBarHeightHint="44"
|
||||||
|
Icon="avares://SharpEmu.GUI/Assets/SharpEmu.ico">
|
||||||
|
|
||||||
|
<Grid RowDefinitions="44,*,32">
|
||||||
|
|
||||||
|
<!-- Title bar -->
|
||||||
|
<Grid x:Name="TitleBar" Grid.Row="0" Background="{StaticResource ChromeBrush}">
|
||||||
|
<StackPanel Orientation="Horizontal" Spacing="10" Margin="16,0" VerticalAlignment="Center">
|
||||||
|
<Image Source="avares://SharpEmu.GUI/Assets/logo.png" Width="20" Height="20" />
|
||||||
|
<TextBlock Text="SharpEmu" FontSize="14" FontWeight="SemiBold" VerticalAlignment="Center" />
|
||||||
|
<Border Classes="pill">
|
||||||
|
<TextBlock x:Name="VersionText" Text="v0.0.1" FontSize="11" Foreground="{StaticResource MutedBrush}" />
|
||||||
|
</Border>
|
||||||
|
</StackPanel>
|
||||||
|
</Grid>
|
||||||
|
|
||||||
|
<!-- Main content -->
|
||||||
|
<Grid Grid.Row="1" Margin="14" ColumnDefinitions="360,14,*">
|
||||||
|
|
||||||
|
<!-- Game library -->
|
||||||
|
<Border Grid.Column="0" Classes="card" Padding="0">
|
||||||
|
<Grid RowDefinitions="Auto,Auto,*,Auto">
|
||||||
|
<Grid Grid.Row="0" ColumnDefinitions="*,Auto" Margin="16,16,16,10">
|
||||||
|
<TextBlock Classes="sectionTitle" Text="GAME LIBRARY" VerticalAlignment="Center" />
|
||||||
|
<Border Grid.Column="1" Classes="pill">
|
||||||
|
<TextBlock x:Name="GameCountText" Text="0" FontSize="11" Foreground="{StaticResource MutedBrush}" />
|
||||||
|
</Border>
|
||||||
|
</Grid>
|
||||||
|
|
||||||
|
<TextBox Grid.Row="1" x:Name="SearchBox" Watermark="Search games…" Margin="12,0,12,8" CornerRadius="8" />
|
||||||
|
|
||||||
|
<ListBox Grid.Row="2" x:Name="GameList" Classes="library" Background="Transparent" Margin="8,0">
|
||||||
|
<ListBox.ItemTemplate>
|
||||||
|
<DataTemplate>
|
||||||
|
<StackPanel Margin="4,4" Spacing="2">
|
||||||
|
<TextBlock Text="{Binding Name}" FontSize="14" FontWeight="SemiBold" TextTrimming="CharacterEllipsis" />
|
||||||
|
<TextBlock Text="{Binding Detail}" FontSize="11" Foreground="{StaticResource MutedBrush}" TextTrimming="CharacterEllipsis" />
|
||||||
|
</StackPanel>
|
||||||
|
</DataTemplate>
|
||||||
|
</ListBox.ItemTemplate>
|
||||||
|
</ListBox>
|
||||||
|
|
||||||
|
<StackPanel Grid.Row="3" Orientation="Horizontal" Spacing="8" Margin="16,12,16,16">
|
||||||
|
<Button x:Name="AddFolderButton" Classes="ghost" Content="+ Add folder" />
|
||||||
|
<Button x:Name="RescanButton" Classes="ghost" Content="⟳ Rescan" />
|
||||||
|
<Button x:Name="OpenFileButton" Classes="ghost" Content="Open file…" />
|
||||||
|
</StackPanel>
|
||||||
|
</Grid>
|
||||||
|
</Border>
|
||||||
|
|
||||||
|
<!-- Right column -->
|
||||||
|
<Grid Grid.Column="2" RowDefinitions="Auto,12,Auto,12,*">
|
||||||
|
|
||||||
|
<!-- Selected game / launch -->
|
||||||
|
<Border Grid.Row="0" Classes="card">
|
||||||
|
<Grid ColumnDefinitions="*,Auto">
|
||||||
|
<StackPanel Grid.Column="0" Spacing="6" VerticalAlignment="Center">
|
||||||
|
<TextBlock x:Name="SelectedGameTitle" Text="No game selected" FontSize="20" FontWeight="Bold" TextTrimming="CharacterEllipsis" />
|
||||||
|
<TextBlock x:Name="SelectedGamePath" Text="Pick a game from the library, or open an eboot.bin directly."
|
||||||
|
FontSize="12" Foreground="{StaticResource MutedBrush}" TextTrimming="CharacterEllipsis" />
|
||||||
|
<StackPanel Orientation="Horizontal" Spacing="8">
|
||||||
|
<Ellipse x:Name="StatusDot" Width="9" Height="9" Fill="{StaticResource FaintBrush}" VerticalAlignment="Center" />
|
||||||
|
<TextBlock x:Name="StatusText" Text="Idle" FontSize="12" Foreground="{StaticResource MutedBrush}" VerticalAlignment="Center" />
|
||||||
|
</StackPanel>
|
||||||
|
</StackPanel>
|
||||||
|
<StackPanel Grid.Column="1" Orientation="Horizontal" Spacing="10" VerticalAlignment="Center" Margin="16,0,0,0">
|
||||||
|
<Button x:Name="LaunchButton" Classes="accent" Content="▶ Launch" IsEnabled="False" />
|
||||||
|
<Button x:Name="StopButton" Classes="danger" Content="■ Stop" IsEnabled="False" />
|
||||||
|
</StackPanel>
|
||||||
|
</Grid>
|
||||||
|
</Border>
|
||||||
|
|
||||||
|
<!-- Launch options -->
|
||||||
|
<Border Grid.Row="2" Classes="card">
|
||||||
|
<StackPanel Spacing="12">
|
||||||
|
<TextBlock Classes="sectionTitle" Text="LAUNCH OPTIONS" />
|
||||||
|
<WrapPanel>
|
||||||
|
<StackPanel Margin="0,0,24,0">
|
||||||
|
<TextBlock Classes="fieldLabel" Text="CPU engine" />
|
||||||
|
<ComboBox x:Name="CpuEngineBox" Width="150" SelectedIndex="0" CornerRadius="8">
|
||||||
|
<ComboBoxItem Content="Native" />
|
||||||
|
</ComboBox>
|
||||||
|
</StackPanel>
|
||||||
|
<StackPanel Margin="0,0,24,0">
|
||||||
|
<TextBlock Classes="fieldLabel" Text="Log level" />
|
||||||
|
<ComboBox x:Name="LogLevelBox" Width="150" SelectedIndex="2" CornerRadius="8">
|
||||||
|
<ComboBoxItem Content="Trace" />
|
||||||
|
<ComboBoxItem Content="Debug" />
|
||||||
|
<ComboBoxItem Content="Info" />
|
||||||
|
<ComboBoxItem Content="Warning" />
|
||||||
|
<ComboBoxItem Content="Error" />
|
||||||
|
<ComboBoxItem Content="Critical" />
|
||||||
|
</ComboBox>
|
||||||
|
</StackPanel>
|
||||||
|
<StackPanel Margin="0,0,24,0">
|
||||||
|
<TextBlock Classes="fieldLabel" Text="Import trace limit (0 = off)" />
|
||||||
|
<NumericUpDown x:Name="TraceImportsBox" Width="170" Minimum="0" Maximum="4096" Increment="16"
|
||||||
|
Value="0" FormatString="0" CornerRadius="8" />
|
||||||
|
</StackPanel>
|
||||||
|
<StackPanel>
|
||||||
|
<TextBlock Classes="fieldLabel" Text="Strict dynlib resolution" />
|
||||||
|
<ToggleSwitch x:Name="StrictToggle" OnContent="On" OffContent="Off" />
|
||||||
|
</StackPanel>
|
||||||
|
</WrapPanel>
|
||||||
|
</StackPanel>
|
||||||
|
</Border>
|
||||||
|
|
||||||
|
<!-- Console -->
|
||||||
|
<Border Grid.Row="4" Classes="card" Padding="0">
|
||||||
|
<Grid RowDefinitions="Auto,*">
|
||||||
|
<Grid Grid.Row="0" ColumnDefinitions="*,Auto,Auto,Auto" Margin="16,14,16,10">
|
||||||
|
<TextBlock Classes="sectionTitle" Text="CONSOLE" VerticalAlignment="Center" />
|
||||||
|
<CheckBox Grid.Column="1" x:Name="AutoScrollCheck" Content="Auto-scroll" IsChecked="True"
|
||||||
|
FontSize="12" Margin="0,0,12,0" />
|
||||||
|
<Button Grid.Column="2" x:Name="CopyLogButton" Classes="ghost" Content="Copy" FontSize="12"
|
||||||
|
Padding="10,4" Margin="0,0,8,0" />
|
||||||
|
<Button Grid.Column="3" x:Name="ClearLogButton" Classes="ghost" Content="Clear" FontSize="12"
|
||||||
|
Padding="10,4" />
|
||||||
|
</Grid>
|
||||||
|
<ListBox Grid.Row="1" x:Name="ConsoleList" Classes="console" BorderThickness="0,1,0,0"
|
||||||
|
BorderBrush="{StaticResource CardBorderBrush}" CornerRadius="0,0,10,10">
|
||||||
|
<ListBox.ItemTemplate>
|
||||||
|
<DataTemplate>
|
||||||
|
<TextBlock Text="{Binding Text}" Foreground="{Binding Brush}" TextWrapping="NoWrap" />
|
||||||
|
</DataTemplate>
|
||||||
|
</ListBox.ItemTemplate>
|
||||||
|
</ListBox>
|
||||||
|
</Grid>
|
||||||
|
</Border>
|
||||||
|
</Grid>
|
||||||
|
</Grid>
|
||||||
|
|
||||||
|
<!-- Status bar -->
|
||||||
|
<Grid Grid.Row="2" Background="{StaticResource ChromeBrush}" ColumnDefinitions="*,Auto">
|
||||||
|
<TextBlock x:Name="EmulatorPathText" Grid.Column="0" Text="Emulator: locating…" FontSize="11"
|
||||||
|
Foreground="{StaticResource FaintBrush}" VerticalAlignment="Center" Margin="16,0"
|
||||||
|
TextTrimming="CharacterEllipsis" />
|
||||||
|
<TextBlock x:Name="StatusBarRight" Grid.Column="1" Text="" FontSize="11"
|
||||||
|
Foreground="{StaticResource FaintBrush}" VerticalAlignment="Center" Margin="16,0" />
|
||||||
|
</Grid>
|
||||||
|
</Grid>
|
||||||
|
</Window>
|
||||||
@@ -0,0 +1,609 @@
|
|||||||
|
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||||
|
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||||
|
|
||||||
|
using System.Collections.Concurrent;
|
||||||
|
using System.Collections.ObjectModel;
|
||||||
|
using System.Reflection;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Avalonia.Controls;
|
||||||
|
using Avalonia.Input;
|
||||||
|
using Avalonia.Media;
|
||||||
|
using Avalonia.Platform.Storage;
|
||||||
|
using Avalonia.Threading;
|
||||||
|
|
||||||
|
namespace SharpEmu.GUI;
|
||||||
|
|
||||||
|
public partial class MainWindow : Window
|
||||||
|
{
|
||||||
|
private const int MaxConsoleLines = 4000;
|
||||||
|
|
||||||
|
private static readonly IBrush DefaultLineBrush = new SolidColorBrush(Color.Parse("#C7CFDE"));
|
||||||
|
private static readonly IBrush DimLineBrush = new SolidColorBrush(Color.Parse("#6B7488"));
|
||||||
|
private static readonly IBrush InfoLineBrush = new SolidColorBrush(Color.Parse("#6FA8FF"));
|
||||||
|
private static readonly IBrush WarningLineBrush = new SolidColorBrush(Color.Parse("#E8B341"));
|
||||||
|
private static readonly IBrush ErrorLineBrush = new SolidColorBrush(Color.Parse("#F2777C"));
|
||||||
|
private static readonly IBrush SuccessLineBrush = new SolidColorBrush(Color.Parse("#63D489"));
|
||||||
|
|
||||||
|
private readonly List<GameEntry> _allGames = new();
|
||||||
|
private readonly ObservableCollection<GameEntry> _visibleGames = new();
|
||||||
|
private readonly ObservableCollection<LogLine> _consoleLines = new();
|
||||||
|
private readonly ConcurrentQueue<(string Line, bool IsError)> _pendingLines = new();
|
||||||
|
private readonly DispatcherTimer _consoleFlushTimer;
|
||||||
|
|
||||||
|
private GuiSettings _settings = new();
|
||||||
|
private EmulatorProcess? _emulator;
|
||||||
|
private string? _emulatorExePath;
|
||||||
|
private bool _isRunning;
|
||||||
|
private int _autoScrollTicks;
|
||||||
|
|
||||||
|
public MainWindow()
|
||||||
|
{
|
||||||
|
InitializeComponent();
|
||||||
|
|
||||||
|
GameList.ItemsSource = _visibleGames;
|
||||||
|
ConsoleList.ItemsSource = _consoleLines;
|
||||||
|
|
||||||
|
_consoleFlushTimer = new DispatcherTimer
|
||||||
|
{
|
||||||
|
Interval = TimeSpan.FromMilliseconds(80),
|
||||||
|
};
|
||||||
|
_consoleFlushTimer.Tick += (_, _) =>
|
||||||
|
{
|
||||||
|
FlushPendingConsoleLines();
|
||||||
|
MaybeAutoScroll();
|
||||||
|
};
|
||||||
|
_consoleFlushTimer.Start();
|
||||||
|
|
||||||
|
TitleBar.PointerPressed += OnTitleBarPointerPressed;
|
||||||
|
GameList.SelectionChanged += (_, _) => UpdateSelectedGame();
|
||||||
|
GameList.DoubleTapped += (_, _) => LaunchSelected();
|
||||||
|
SearchBox.TextChanged += (_, _) => RefreshVisibleGames();
|
||||||
|
AddFolderButton.Click += async (_, _) => await AddFolderAsync();
|
||||||
|
RescanButton.Click += async (_, _) => await RescanLibraryAsync();
|
||||||
|
OpenFileButton.Click += async (_, _) => await OpenFileAsync();
|
||||||
|
LaunchButton.Click += (_, _) => LaunchSelected();
|
||||||
|
StopButton.Click += (_, _) => _emulator?.Stop();
|
||||||
|
ClearLogButton.Click += (_, _) => _consoleLines.Clear();
|
||||||
|
CopyLogButton.Click += async (_, _) => await CopyConsoleAsync();
|
||||||
|
|
||||||
|
Opened += async (_, _) => await OnOpenedAsync();
|
||||||
|
Closing += (_, _) => OnWindowClosing();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task OnOpenedAsync()
|
||||||
|
{
|
||||||
|
var version = Assembly.GetExecutingAssembly().GetName().Version;
|
||||||
|
if (version is not null)
|
||||||
|
{
|
||||||
|
VersionText.Text = $"v{version.ToString(3)}";
|
||||||
|
}
|
||||||
|
|
||||||
|
_settings = GuiSettings.Load();
|
||||||
|
ApplySettingsToControls();
|
||||||
|
LocateEmulator();
|
||||||
|
await RescanLibraryAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnWindowClosing()
|
||||||
|
{
|
||||||
|
ReadControlsIntoSettings();
|
||||||
|
_settings.Save();
|
||||||
|
_consoleFlushTimer.Stop();
|
||||||
|
_emulator?.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnTitleBarPointerPressed(object? sender, PointerPressedEventArgs e)
|
||||||
|
{
|
||||||
|
if (e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
|
||||||
|
{
|
||||||
|
BeginMoveDrag(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Settings <-> controls ----
|
||||||
|
|
||||||
|
private void ApplySettingsToControls()
|
||||||
|
{
|
||||||
|
LogLevelBox.SelectedIndex = _settings.LogLevel.ToLowerInvariant() switch
|
||||||
|
{
|
||||||
|
"trace" => 0,
|
||||||
|
"debug" => 1,
|
||||||
|
"info" => 2,
|
||||||
|
"warning" or "warn" => 3,
|
||||||
|
"error" => 4,
|
||||||
|
"critical" or "fatal" => 5,
|
||||||
|
_ => 2,
|
||||||
|
};
|
||||||
|
TraceImportsBox.Value = Math.Clamp(_settings.ImportTraceLimit, 0, 4096);
|
||||||
|
StrictToggle.IsChecked = _settings.StrictDynlibResolution;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ReadControlsIntoSettings()
|
||||||
|
{
|
||||||
|
_settings.LogLevel = SelectedLogLevel();
|
||||||
|
_settings.ImportTraceLimit = (int)(TraceImportsBox.Value ?? 0);
|
||||||
|
_settings.StrictDynlibResolution = StrictToggle.IsChecked == true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private string SelectedLogLevel()
|
||||||
|
{
|
||||||
|
return LogLevelBox.SelectedIndex switch
|
||||||
|
{
|
||||||
|
0 => "Trace",
|
||||||
|
1 => "Debug",
|
||||||
|
2 => "Info",
|
||||||
|
3 => "Warning",
|
||||||
|
4 => "Error",
|
||||||
|
5 => "Critical",
|
||||||
|
_ => "Info",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Emulator discovery ----
|
||||||
|
|
||||||
|
private void LocateEmulator()
|
||||||
|
{
|
||||||
|
var exeName = OperatingSystem.IsWindows() ? "SharpEmu.exe" : "SharpEmu";
|
||||||
|
var baseDirectory = AppContext.BaseDirectory;
|
||||||
|
var candidates = new List<string>();
|
||||||
|
if (!string.IsNullOrWhiteSpace(_settings.EmulatorPath))
|
||||||
|
{
|
||||||
|
candidates.Add(_settings.EmulatorPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The GUI and the CLI are the same executable: with arguments it runs
|
||||||
|
// the emulator, so the preferred child process is this process itself.
|
||||||
|
if (Environment.ProcessPath is { } selfPath &&
|
||||||
|
Path.GetFileNameWithoutExtension(selfPath).Equals("SharpEmu", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
candidates.Add(selfPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
candidates.Add(Path.Combine(baseDirectory, exeName));
|
||||||
|
candidates.Add(Path.Combine(baseDirectory, "win-x64", exeName));
|
||||||
|
candidates.Add(Path.Combine(baseDirectory, "..", exeName));
|
||||||
|
|
||||||
|
_emulatorExePath = candidates.FirstOrDefault(File.Exists) is { } found
|
||||||
|
? Path.GetFullPath(found)
|
||||||
|
: null;
|
||||||
|
|
||||||
|
EmulatorPathText.Text = _emulatorExePath is not null
|
||||||
|
? $"Emulator: {_emulatorExePath}"
|
||||||
|
: "Emulator: SharpEmu executable not found — build SharpEmu.CLI first.";
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Game library ----
|
||||||
|
|
||||||
|
private async Task AddFolderAsync()
|
||||||
|
{
|
||||||
|
var folders = await StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions
|
||||||
|
{
|
||||||
|
Title = "Choose a folder containing games",
|
||||||
|
AllowMultiple = false,
|
||||||
|
});
|
||||||
|
|
||||||
|
var path = folders.FirstOrDefault()?.TryGetLocalPath();
|
||||||
|
if (string.IsNullOrEmpty(path))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!_settings.GameFolders.Contains(path, StringComparer.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
_settings.GameFolders.Add(path);
|
||||||
|
_settings.Save();
|
||||||
|
}
|
||||||
|
|
||||||
|
await RescanLibraryAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task RescanLibraryAsync()
|
||||||
|
{
|
||||||
|
var folders = _settings.GameFolders.ToArray();
|
||||||
|
StatusBarRight.Text = "Scanning library…";
|
||||||
|
|
||||||
|
var games = await Task.Run(() => ScanFolders(folders));
|
||||||
|
|
||||||
|
_allGames.Clear();
|
||||||
|
_allGames.AddRange(games);
|
||||||
|
RefreshVisibleGames();
|
||||||
|
StatusBarRight.Text = folders.Length == 0
|
||||||
|
? "Add a game folder to populate the library."
|
||||||
|
: $"Library scanned: {games.Count} game(s) in {folders.Length} folder(s).";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<GameEntry> ScanFolders(IReadOnlyList<string> folders)
|
||||||
|
{
|
||||||
|
var games = new List<GameEntry>();
|
||||||
|
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||||
|
var enumeration = new EnumerationOptions
|
||||||
|
{
|
||||||
|
IgnoreInaccessible = true,
|
||||||
|
RecurseSubdirectories = true,
|
||||||
|
MaxRecursionDepth = 8,
|
||||||
|
};
|
||||||
|
|
||||||
|
foreach (var folder in folders)
|
||||||
|
{
|
||||||
|
if (!Directory.Exists(folder))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
foreach (var file in Directory.EnumerateFiles(folder, "eboot.bin", enumeration))
|
||||||
|
{
|
||||||
|
var fullPath = Path.GetFullPath(file);
|
||||||
|
if (!seen.Add(fullPath))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
long size = 0;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
size = new FileInfo(fullPath).Length;
|
||||||
|
}
|
||||||
|
catch (IOException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
var (title, titleId) = TryReadParamJson(fullPath);
|
||||||
|
games.Add(new GameEntry(title ?? GameNameFor(fullPath), titleId, fullPath, size));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception)
|
||||||
|
{
|
||||||
|
// Skip folders that fail to enumerate.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
games.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase));
|
||||||
|
return games;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Reads the game title and title id from sce_sys/param.json next to the
|
||||||
|
/// executable, when present.
|
||||||
|
/// </summary>
|
||||||
|
private static (string? Title, string? TitleId) TryReadParamJson(string ebootPath)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var directory = Path.GetDirectoryName(ebootPath);
|
||||||
|
if (directory is null)
|
||||||
|
{
|
||||||
|
return (null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
var paramPath = Path.Combine(directory, "sce_sys", "param.json");
|
||||||
|
if (!File.Exists(paramPath))
|
||||||
|
{
|
||||||
|
return (null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReadAllText handles a UTF-8 BOM, which JsonDocument rejects in
|
||||||
|
// raw bytes.
|
||||||
|
using var document = JsonDocument.Parse(File.ReadAllText(paramPath));
|
||||||
|
var root = document.RootElement;
|
||||||
|
|
||||||
|
string? titleId = null;
|
||||||
|
if (root.TryGetProperty("titleId", out var idElement) && idElement.ValueKind == JsonValueKind.String)
|
||||||
|
{
|
||||||
|
titleId = idElement.GetString();
|
||||||
|
}
|
||||||
|
|
||||||
|
string? title = null;
|
||||||
|
if (root.TryGetProperty("localizedParameters", out var localized) &&
|
||||||
|
localized.ValueKind == JsonValueKind.Object)
|
||||||
|
{
|
||||||
|
if (localized.TryGetProperty("defaultLanguage", out var language) &&
|
||||||
|
language.ValueKind == JsonValueKind.String &&
|
||||||
|
localized.TryGetProperty(language.GetString()!, out var defaultBlock) &&
|
||||||
|
defaultBlock.ValueKind == JsonValueKind.Object &&
|
||||||
|
defaultBlock.TryGetProperty("titleName", out var titleName) &&
|
||||||
|
titleName.ValueKind == JsonValueKind.String)
|
||||||
|
{
|
||||||
|
title = titleName.GetString();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
foreach (var property in localized.EnumerateObject())
|
||||||
|
{
|
||||||
|
if (property.Value.ValueKind == JsonValueKind.Object &&
|
||||||
|
property.Value.TryGetProperty("titleName", out var anyTitleName) &&
|
||||||
|
anyTitleName.ValueKind == JsonValueKind.String)
|
||||||
|
{
|
||||||
|
title = anyTitleName.GetString();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
string.IsNullOrWhiteSpace(title) ? null : title,
|
||||||
|
string.IsNullOrWhiteSpace(titleId) ? null : titleId);
|
||||||
|
}
|
||||||
|
catch (Exception)
|
||||||
|
{
|
||||||
|
return (null, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string GameNameFor(string ebootPath)
|
||||||
|
{
|
||||||
|
var directory = Path.GetDirectoryName(ebootPath);
|
||||||
|
var name = directory is not null ? Path.GetFileName(directory) : null;
|
||||||
|
return string.IsNullOrEmpty(name) ? Path.GetFileName(ebootPath) : name;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void RefreshVisibleGames()
|
||||||
|
{
|
||||||
|
var query = SearchBox.Text?.Trim() ?? string.Empty;
|
||||||
|
var selected = GameList.SelectedItem as GameEntry;
|
||||||
|
|
||||||
|
_visibleGames.Clear();
|
||||||
|
foreach (var game in _allGames)
|
||||||
|
{
|
||||||
|
if (query.Length == 0 ||
|
||||||
|
game.Name.Contains(query, StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
game.Path.Contains(query, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
_visibleGames.Add(game);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
GameCountText.Text = _visibleGames.Count.ToString();
|
||||||
|
if (selected is not null && _visibleGames.Contains(selected))
|
||||||
|
{
|
||||||
|
GameList.SelectedItem = selected;
|
||||||
|
}
|
||||||
|
|
||||||
|
UpdateSelectedGame();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void UpdateSelectedGame()
|
||||||
|
{
|
||||||
|
if (GameList.SelectedItem is GameEntry game)
|
||||||
|
{
|
||||||
|
SelectedGameTitle.Text = game.Name;
|
||||||
|
SelectedGamePath.Text = game.Path;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
SelectedGameTitle.Text = "No game selected";
|
||||||
|
SelectedGamePath.Text = "Pick a game from the library, or open an eboot.bin directly.";
|
||||||
|
}
|
||||||
|
|
||||||
|
UpdateRunButtons();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Launching ----
|
||||||
|
|
||||||
|
private async Task OpenFileAsync()
|
||||||
|
{
|
||||||
|
var files = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
|
||||||
|
{
|
||||||
|
Title = "Open an executable to launch",
|
||||||
|
AllowMultiple = false,
|
||||||
|
FileTypeFilter = new[]
|
||||||
|
{
|
||||||
|
new FilePickerFileType("PS executables") { Patterns = new[] { "eboot.bin", "*.bin", "*.self", "*.elf" } },
|
||||||
|
FilePickerFileTypes.All,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
var path = files.FirstOrDefault()?.TryGetLocalPath();
|
||||||
|
if (!string.IsNullOrEmpty(path))
|
||||||
|
{
|
||||||
|
Launch(path, Path.GetFileName(path));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void LaunchSelected()
|
||||||
|
{
|
||||||
|
if (GameList.SelectedItem is GameEntry game)
|
||||||
|
{
|
||||||
|
Launch(game.Path, game.Name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Launch(string ebootPath, string displayName)
|
||||||
|
{
|
||||||
|
if (_isRunning)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_emulatorExePath is null)
|
||||||
|
{
|
||||||
|
LocateEmulator();
|
||||||
|
if (_emulatorExePath is null)
|
||||||
|
{
|
||||||
|
AppendConsoleLine("SharpEmu executable not found. Build the SharpEmu.CLI project first (dotnet build).", ErrorLineBrush);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ReadControlsIntoSettings();
|
||||||
|
_settings.Save();
|
||||||
|
|
||||||
|
var arguments = new List<string>
|
||||||
|
{
|
||||||
|
"--cpu-engine=native",
|
||||||
|
$"--log-level={_settings.LogLevel.ToLowerInvariant()}",
|
||||||
|
};
|
||||||
|
if (_settings.StrictDynlibResolution)
|
||||||
|
{
|
||||||
|
arguments.Add("--strict");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_settings.ImportTraceLimit > 0)
|
||||||
|
{
|
||||||
|
arguments.Add($"--trace-imports={_settings.ImportTraceLimit}");
|
||||||
|
}
|
||||||
|
|
||||||
|
arguments.Add(ebootPath);
|
||||||
|
|
||||||
|
_consoleLines.Clear();
|
||||||
|
AppendConsoleLine($"$ SharpEmu {string.Join(' ', arguments)}", DimLineBrush);
|
||||||
|
|
||||||
|
var emulator = new EmulatorProcess();
|
||||||
|
emulator.OutputReceived += (line, isError) => _pendingLines.Enqueue((line, isError));
|
||||||
|
emulator.Exited += code => Dispatcher.UIThread.Post(() => OnEmulatorExited(code));
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
emulator.Start(_emulatorExePath, arguments, Path.GetDirectoryName(ebootPath));
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
emulator.Dispose();
|
||||||
|
AppendConsoleLine($"Failed to start the emulator: {ex.Message}", ErrorLineBrush);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_emulator = emulator;
|
||||||
|
_isRunning = true;
|
||||||
|
StatusDot.Fill = SuccessLineBrush;
|
||||||
|
StatusText.Text = $"Running — {displayName}";
|
||||||
|
StatusBarRight.Text = $"Running {displayName}";
|
||||||
|
UpdateRunButtons();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnEmulatorExited(int exitCode)
|
||||||
|
{
|
||||||
|
FlushPendingConsoleLines();
|
||||||
|
_isRunning = false;
|
||||||
|
_emulator?.Dispose();
|
||||||
|
_emulator = null;
|
||||||
|
|
||||||
|
var meaning = exitCode switch
|
||||||
|
{
|
||||||
|
0 => "OK",
|
||||||
|
1 => "invalid arguments",
|
||||||
|
2 => "eboot not found",
|
||||||
|
3 => "runtime exception",
|
||||||
|
4 => "emulation error",
|
||||||
|
_ => "unknown",
|
||||||
|
};
|
||||||
|
var brush = exitCode == 0 ? SuccessLineBrush : ErrorLineBrush;
|
||||||
|
AppendConsoleLine($"Process exited with code {exitCode} ({meaning}).", brush);
|
||||||
|
|
||||||
|
StatusDot.Fill = exitCode == 0 ? (IBrush)SuccessLineBrush : ErrorLineBrush;
|
||||||
|
StatusText.Text = $"Exited with code {exitCode} ({meaning})";
|
||||||
|
StatusBarRight.Text = "Idle";
|
||||||
|
UpdateRunButtons();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void UpdateRunButtons()
|
||||||
|
{
|
||||||
|
LaunchButton.IsEnabled = !_isRunning && GameList.SelectedItem is GameEntry;
|
||||||
|
StopButton.IsEnabled = _isRunning;
|
||||||
|
OpenFileButton.IsEnabled = !_isRunning;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Console ----
|
||||||
|
|
||||||
|
private void FlushPendingConsoleLines()
|
||||||
|
{
|
||||||
|
if (_pendingLines.IsEmpty)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var incoming = new List<LogLine>();
|
||||||
|
while (_pendingLines.TryDequeue(out var pending))
|
||||||
|
{
|
||||||
|
incoming.Add(new LogLine(pending.Line, BrushForLine(pending.Line)));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (incoming.Count >= MaxConsoleLines)
|
||||||
|
{
|
||||||
|
// A burst larger than the cap: keep only the newest lines.
|
||||||
|
_consoleLines.Clear();
|
||||||
|
for (var i = incoming.Count - MaxConsoleLines; i < incoming.Count; i++)
|
||||||
|
{
|
||||||
|
_consoleLines.Add(incoming[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var overflow = _consoleLines.Count + incoming.Count - MaxConsoleLines;
|
||||||
|
for (var i = 0; i < overflow; i++)
|
||||||
|
{
|
||||||
|
_consoleLines.RemoveAt(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var line in incoming)
|
||||||
|
{
|
||||||
|
_consoleLines.Add(line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_autoScrollTicks = 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void AppendConsoleLine(string text, IBrush brush)
|
||||||
|
{
|
||||||
|
_consoleLines.Add(new LogLine(text, brush));
|
||||||
|
_autoScrollTicks = 3;
|
||||||
|
MaybeAutoScroll();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void MaybeAutoScroll()
|
||||||
|
{
|
||||||
|
// ScrollToEnd is applied over a few flush-timer ticks because the
|
||||||
|
// virtualizing panel re-estimates its extent after large batches, and
|
||||||
|
// a single scroll can land short of the true end. A synchronous
|
||||||
|
// ScrollIntoView during rapid adds is avoided entirely — it can crash
|
||||||
|
// the panel with "Invalid Arrange rectangle".
|
||||||
|
if (_autoScrollTicks <= 0 || AutoScrollCheck.IsChecked != true)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_autoScrollTicks--;
|
||||||
|
(ConsoleList.Scroll as ScrollViewer)?.ScrollToEnd();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IBrush BrushForLine(string line)
|
||||||
|
{
|
||||||
|
if (line.Contains("[ERROR]", StringComparison.Ordinal) ||
|
||||||
|
line.Contains("[CRITICAL]", StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
return ErrorLineBrush;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (line.Contains("[WARNING]", StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
return WarningLineBrush;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (line.Contains("[INFO]", StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
return InfoLineBrush;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (line.Contains("[DEBUG]", StringComparison.Ordinal) ||
|
||||||
|
line.Contains("[TRACE]", StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
return DimLineBrush;
|
||||||
|
}
|
||||||
|
|
||||||
|
return DefaultLineBrush;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task CopyConsoleAsync()
|
||||||
|
{
|
||||||
|
if (_consoleLines.Count == 0 || Clipboard is null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var text = string.Join(Environment.NewLine, _consoleLines.Select(line => line.Text));
|
||||||
|
await Clipboard.SetTextAsync(text);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
<!--
|
||||||
|
Copyright (C) 2026 SharpEmu Emulator Project
|
||||||
|
SPDX-License-Identifier: GPL-2.0-or-later
|
||||||
|
-->
|
||||||
|
|
||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<!-- Class library: the GUI is hosted by SharpEmu.CLI, which opens it when
|
||||||
|
the executable is started without arguments. -->
|
||||||
|
<PropertyGroup>
|
||||||
|
<GenerateDocumentationFile>false</GenerateDocumentationFile>
|
||||||
|
<Version>0.0.1</Version>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Avalonia" />
|
||||||
|
<PackageReference Include="Avalonia.Desktop" />
|
||||||
|
<PackageReference Include="Avalonia.Fonts.Inter" />
|
||||||
|
<PackageReference Include="Avalonia.Themes.Fluent" />
|
||||||
|
<PackageReference Include="Tmds.DBus.Protocol" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<AvaloniaResource Include="..\..\assets\images\logo.png" Link="Assets/logo.png" />
|
||||||
|
<AvaloniaResource Include="..\..\assets\images\SharpEmu.ico" Link="Assets/SharpEmu.ico" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
{
|
||||||
|
"version": 2,
|
||||||
|
"dependencies": {
|
||||||
|
"net10.0": {
|
||||||
|
"Avalonia": {
|
||||||
|
"type": "Direct",
|
||||||
|
"requested": "[11.3.18, )",
|
||||||
|
"resolved": "11.3.18",
|
||||||
|
"contentHash": "2C4UxhWUObWGgYKWic1x5BMMWGJP6SElb91WeOxs+X/iR26rtkqpxFFwwo50FXS9AyYnHfk8QKXDEfe7oT/kZA==",
|
||||||
|
"dependencies": {
|
||||||
|
"Avalonia.BuildServices": "11.3.2",
|
||||||
|
"Avalonia.Remote.Protocol": "11.3.18",
|
||||||
|
"MicroCom.Runtime": "0.11.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"Avalonia.Desktop": {
|
||||||
|
"type": "Direct",
|
||||||
|
"requested": "[11.3.18, )",
|
||||||
|
"resolved": "11.3.18",
|
||||||
|
"contentHash": "bilMPa5vYiis6fbNovb6esKytBnOCEGojBa1XFegLCRHCP6g6PvZwS0XF/YOAGkENRlHG8dI7lohOpQ9bIkq1g==",
|
||||||
|
"dependencies": {
|
||||||
|
"Avalonia": "11.3.18",
|
||||||
|
"Avalonia.Native": "11.3.18",
|
||||||
|
"Avalonia.Skia": "11.3.18",
|
||||||
|
"Avalonia.Win32": "11.3.18",
|
||||||
|
"Avalonia.X11": "11.3.18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"Avalonia.Fonts.Inter": {
|
||||||
|
"type": "Direct",
|
||||||
|
"requested": "[11.3.18, )",
|
||||||
|
"resolved": "11.3.18",
|
||||||
|
"contentHash": "27u6hB3Y2Ue586yjfeVakberY73VNQXtuKwe/P927XG1QPlhsfmOyifLHDDpSHG85Zl1x/Xv9IZ3+tk9FnjcZQ==",
|
||||||
|
"dependencies": {
|
||||||
|
"Avalonia": "11.3.18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"Avalonia.Themes.Fluent": {
|
||||||
|
"type": "Direct",
|
||||||
|
"requested": "[11.3.18, )",
|
||||||
|
"resolved": "11.3.18",
|
||||||
|
"contentHash": "+Q/TJoynD0zNuu5w2gD+xcTl7GNKJFxlPYAndRLs/mTDrNbbsvv/271WyIysbMPsXSjCyBDp7RCZzQkpD6x5Bg==",
|
||||||
|
"dependencies": {
|
||||||
|
"Avalonia": "11.3.18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"Tmds.DBus.Protocol": {
|
||||||
|
"type": "Direct",
|
||||||
|
"requested": "[0.21.3, )",
|
||||||
|
"resolved": "0.21.3",
|
||||||
|
"contentHash": "hDwB8WsQoyALQKqIbwzS68UKdlnafDm4T/DkO/JrA/YIneP/rKv96SxYPVXeh3FP4i/SXfShrYftKLtciJAIlw=="
|
||||||
|
},
|
||||||
|
"Avalonia.Angle.Windows.Natives": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "2.1.25547.20250602",
|
||||||
|
"contentHash": "ZL0VLc4s9rvNNFt19Pxm5UNAkmKNylugAwJPX9ulXZ6JWs/l6XZihPWWTyezaoNOVyEPU8YbURtW7XMAtqXH5A=="
|
||||||
|
},
|
||||||
|
"Avalonia.BuildServices": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "11.3.2",
|
||||||
|
"contentHash": "qHDToxto1e3hci5YqbG9n0Ty8mlp3zBUN5wT66wKqaDVzXyQ0do3EnRILd4Ke9jpvsktaPpgE0YjEk7hornryQ=="
|
||||||
|
},
|
||||||
|
"Avalonia.FreeDesktop": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "11.3.18",
|
||||||
|
"contentHash": "aUwv8BNruRUOaUfMu4U3uibIUS60/rSHgGOhd8zBkLkpxY3JFJvgRbeq5ZzHIyKXCuKi18PO00YHAgCarp3wdw==",
|
||||||
|
"dependencies": {
|
||||||
|
"Avalonia": "11.3.18",
|
||||||
|
"Tmds.DBus.Protocol": "0.21.3"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"Avalonia.Native": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "11.3.18",
|
||||||
|
"contentHash": "8g53DROFW6wVJAnTsE1Iu5bdZO5r0oqxbdbMQODs1QDYCK2IU/y/x/vQVKCYOvqxl4tXkzU9tExv8XqSGPWthQ==",
|
||||||
|
"dependencies": {
|
||||||
|
"Avalonia": "11.3.18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"Avalonia.Remote.Protocol": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "11.3.18",
|
||||||
|
"contentHash": "vw+6ZfgTuu72dA9aVWn6u56t2nrBd5MoMU0wo/qI9XJAl/c0oYYphIvwLvJP1JorubQY4UE3d0ac8ULBhrGBiA=="
|
||||||
|
},
|
||||||
|
"Avalonia.Skia": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "11.3.18",
|
||||||
|
"contentHash": "/B4aXmNRNjG8I5U/a1xJI+bIi0XO6DDzS3mBrIKlVnJRY2CyZiUeESRQXLnIU77Z9TvqkUROs+D47s085YjFtA==",
|
||||||
|
"dependencies": {
|
||||||
|
"Avalonia": "11.3.18",
|
||||||
|
"HarfBuzzSharp": "8.3.1.1",
|
||||||
|
"HarfBuzzSharp.NativeAssets.Linux": "8.3.1.1",
|
||||||
|
"HarfBuzzSharp.NativeAssets.WebAssembly": "8.3.1.1",
|
||||||
|
"SkiaSharp": "2.88.9",
|
||||||
|
"SkiaSharp.NativeAssets.Linux": "2.88.9",
|
||||||
|
"SkiaSharp.NativeAssets.WebAssembly": "2.88.9"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"Avalonia.Win32": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "11.3.18",
|
||||||
|
"contentHash": "eioUHkM2PeLPETd1aEks3rvb9plbba6buIrNdrqCpwE/qgHKUjvRNBd5mUQfAbGgTLiAes524gB8uUMDhrsJVQ==",
|
||||||
|
"dependencies": {
|
||||||
|
"Avalonia": "11.3.18",
|
||||||
|
"Avalonia.Angle.Windows.Natives": "2.1.25547.20250602"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"Avalonia.X11": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "11.3.18",
|
||||||
|
"contentHash": "m4Ki/G5Dovnq+6QzfS0iGbK8V77Q6oTjToMLOB0CxPCCrl3Oxywh6kIjuGJDPaN6kopMmjxlNShyQf+vPYL+JA==",
|
||||||
|
"dependencies": {
|
||||||
|
"Avalonia": "11.3.18",
|
||||||
|
"Avalonia.FreeDesktop": "11.3.18",
|
||||||
|
"Avalonia.Skia": "11.3.18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"HarfBuzzSharp": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "8.3.1.1",
|
||||||
|
"contentHash": "tLZN66oe/uiRPTZfrCU4i8ScVGwqHNh5MHrXj0yVf4l7Mz0FhTGnQ71RGySROTmdognAs0JtluHkL41pIabWuQ==",
|
||||||
|
"dependencies": {
|
||||||
|
"HarfBuzzSharp.NativeAssets.Win32": "8.3.1.1",
|
||||||
|
"HarfBuzzSharp.NativeAssets.macOS": "8.3.1.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"HarfBuzzSharp.NativeAssets.Linux": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "8.3.1.1",
|
||||||
|
"contentHash": "3EZ1mpIiKWRLL5hUYA82ZHteeDIVaEA/Z0rA/wU6tjx6crcAkJnBPwDXZugBSfo8+J3EznvRJf49uMsqYfKrHg=="
|
||||||
|
},
|
||||||
|
"HarfBuzzSharp.NativeAssets.macOS": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "8.3.1.1",
|
||||||
|
"contentHash": "jbtCsgftcaFLCA13tVKo5iWdElJScrulLTKJre36O4YQTIlwDtPPqhRZNk+Y0vv4D1gxbscasGRucUDfS44ofQ=="
|
||||||
|
},
|
||||||
|
"HarfBuzzSharp.NativeAssets.WebAssembly": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "8.3.1.1",
|
||||||
|
"contentHash": "loJweK2u/mH/3C2zBa0ggJlITIszOkK64HLAZB7FUT670dTg965whLFYHDQo69NmC4+d9UN0icLC9VHidXaVCA=="
|
||||||
|
},
|
||||||
|
"HarfBuzzSharp.NativeAssets.Win32": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "8.3.1.1",
|
||||||
|
"contentHash": "UsJtQsfAJoFDZrXc4hCUfRPMqccfKZ0iumJ/upcUjz/cmsTgVFGNEL5yaJWmkqsuFYdMWbj/En5/kS4PFl9hBA=="
|
||||||
|
},
|
||||||
|
"MicroCom.Runtime": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "0.11.0",
|
||||||
|
"contentHash": "MEnrZ3UIiH40hjzMDsxrTyi8dtqB5ziv3iBeeU4bXsL/7NLSal9F1lZKpK+tfBRnUoDSdtcW3KufE4yhATOMCA=="
|
||||||
|
},
|
||||||
|
"SkiaSharp": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "2.88.9",
|
||||||
|
"contentHash": "3MD5VHjXXieSHCleRLuaTXmL2pD0mB7CcOB1x2kA1I4bhptf4e3R27iM93264ZYuAq6mkUyX5XbcxnZvMJYc1Q==",
|
||||||
|
"dependencies": {
|
||||||
|
"SkiaSharp.NativeAssets.Win32": "2.88.9",
|
||||||
|
"SkiaSharp.NativeAssets.macOS": "2.88.9"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"SkiaSharp.NativeAssets.Linux": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "2.88.9",
|
||||||
|
"contentHash": "cWSaJKVPWAaT/WIn9c8T5uT/l4ETwHxNJTkEOtNKjphNo8AW6TF9O32aRkxqw3l8GUdUo66Bu7EiqtFh/XG0Zg==",
|
||||||
|
"dependencies": {
|
||||||
|
"SkiaSharp": "2.88.9"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"SkiaSharp.NativeAssets.macOS": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "2.88.9",
|
||||||
|
"contentHash": "Nv5spmKc4505Ep7oUoJ5vp3KweFpeNqxpyGDWyeEPTX2uR6S6syXIm3gj75dM0YJz7NPvcix48mR5laqs8dPuA=="
|
||||||
|
},
|
||||||
|
"SkiaSharp.NativeAssets.WebAssembly": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "2.88.9",
|
||||||
|
"contentHash": "kt06RccBHSnAs2wDYdBSfsjIDbY3EpsOVqnlDgKdgvyuRA8ZFDaHRdWNx1VHjGgYzmnFCGiTJBnXFl5BqGwGnA=="
|
||||||
|
},
|
||||||
|
"SkiaSharp.NativeAssets.Win32": {
|
||||||
|
"type": "Transitive",
|
||||||
|
"resolved": "2.88.9",
|
||||||
|
"contentHash": "wb2kYgU7iy84nQLYZwMeJXixvK++GoIuECjU4ECaUKNuflyRlJKyiRhN1MAHswvlvzuvkrjRWlK0Za6+kYQK7w=="
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -24,6 +24,7 @@ public static class AmprExports
|
|||||||
private const uint KernelEventQueueRecordType = 2;
|
private const uint KernelEventQueueRecordType = 2;
|
||||||
private const uint WriteAddressRecordType = 3;
|
private const uint WriteAddressRecordType = 3;
|
||||||
private static readonly ConcurrentDictionary<ulong, CommandBufferState> _commandBuffers = new();
|
private static readonly ConcurrentDictionary<ulong, CommandBufferState> _commandBuffers = new();
|
||||||
|
private static readonly ConcurrentDictionary<string, Lazy<CachedHostFile>> _hostFileCache = new(StringComparer.OrdinalIgnoreCase);
|
||||||
private static readonly bool _traceAmpr =
|
private static readonly bool _traceAmpr =
|
||||||
string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_LOG_AMPR"), "1", StringComparison.Ordinal);
|
string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_LOG_AMPR"), "1", StringComparison.Ordinal);
|
||||||
private static readonly bool _traceAmprReads =
|
private static readonly bool _traceAmprReads =
|
||||||
@@ -37,6 +38,23 @@ public static class AmprExports
|
|||||||
public ulong WriteOffset;
|
public ulong WriteOffset;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private sealed class CachedHostFile
|
||||||
|
{
|
||||||
|
public CachedHostFile(string path)
|
||||||
|
{
|
||||||
|
Stream = new FileStream(
|
||||||
|
path,
|
||||||
|
FileMode.Open,
|
||||||
|
FileAccess.Read,
|
||||||
|
FileShare.ReadWrite | FileShare.Delete,
|
||||||
|
bufferSize: 1024 * 1024,
|
||||||
|
FileOptions.RandomAccess);
|
||||||
|
}
|
||||||
|
|
||||||
|
public object Gate { get; } = new();
|
||||||
|
public FileStream Stream { get; }
|
||||||
|
}
|
||||||
|
|
||||||
[SysAbiExport(
|
[SysAbiExport(
|
||||||
Nid = "8aI7R7WaOlc",
|
Nid = "8aI7R7WaOlc",
|
||||||
ExportName = "sceAmprCommandBufferConstructor",
|
ExportName = "sceAmprCommandBufferConstructor",
|
||||||
@@ -249,7 +267,7 @@ public static class AmprExports
|
|||||||
return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT;
|
return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!AmprFileRegistry.TryGetHostPath(fileId, out var hostPath) || !File.Exists(hostPath))
|
if (!AmprFileRegistry.TryGetHostPath(fileId, out var hostPath))
|
||||||
{
|
{
|
||||||
TraceAmprRead(ctx, commandBuffer, fileId, destination, size, fileOffset, bytesRead: 0, hostPath, (int)OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND);
|
TraceAmprRead(ctx, commandBuffer, fileId, destination, size, fileOffset, bytesRead: 0, hostPath, (int)OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND);
|
||||||
return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND;
|
return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND;
|
||||||
@@ -634,24 +652,43 @@ public static class AmprExports
|
|||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
using var stream = new FileStream(
|
if (!TryGetCachedHostFile(hostPath, out var cachedFile, out var openResult))
|
||||||
hostPath,
|
{
|
||||||
FileMode.Open,
|
return openResult;
|
||||||
FileAccess.Read,
|
}
|
||||||
FileShare.ReadWrite | FileShare.Delete,
|
|
||||||
ChunkSize,
|
long fileLength;
|
||||||
FileOptions.SequentialScan);
|
lock (cachedFile.Gate)
|
||||||
if (fileOffset >= (ulong)stream.Length)
|
{
|
||||||
|
fileLength = cachedFile.Stream.Length;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fileOffset >= (ulong)fileLength)
|
||||||
{
|
{
|
||||||
return (int)OrbisGen2Result.ORBIS_GEN2_OK;
|
return (int)OrbisGen2Result.ORBIS_GEN2_OK;
|
||||||
}
|
}
|
||||||
|
|
||||||
stream.Position = unchecked((long)fileOffset);
|
|
||||||
|
|
||||||
while (bytesRead < size)
|
while (bytesRead < size)
|
||||||
{
|
{
|
||||||
|
if (bytesRead > ulong.MaxValue - fileOffset)
|
||||||
|
{
|
||||||
|
return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT;
|
||||||
|
}
|
||||||
|
|
||||||
|
var absoluteOffset = fileOffset + bytesRead;
|
||||||
|
if (absoluteOffset > long.MaxValue)
|
||||||
|
{
|
||||||
|
return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT;
|
||||||
|
}
|
||||||
|
|
||||||
var request = (int)Math.Min((ulong)buffer.Length, size - bytesRead);
|
var request = (int)Math.Min((ulong)buffer.Length, size - bytesRead);
|
||||||
var read = stream.Read(buffer, 0, request);
|
int read;
|
||||||
|
lock (cachedFile.Gate)
|
||||||
|
{
|
||||||
|
cachedFile.Stream.Position = unchecked((long)absoluteOffset);
|
||||||
|
read = cachedFile.Stream.Read(buffer, 0, request);
|
||||||
|
}
|
||||||
|
|
||||||
if (read <= 0)
|
if (read <= 0)
|
||||||
{
|
{
|
||||||
break;
|
break;
|
||||||
@@ -681,6 +718,44 @@ public static class AmprExports
|
|||||||
return (int)OrbisGen2Result.ORBIS_GEN2_OK;
|
return (int)OrbisGen2Result.ORBIS_GEN2_OK;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static bool TryGetCachedHostFile(string hostPath, out CachedHostFile file, out int result)
|
||||||
|
{
|
||||||
|
file = null!;
|
||||||
|
result = (int)OrbisGen2Result.ORBIS_GEN2_OK;
|
||||||
|
|
||||||
|
string cachePath;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
cachePath = Path.GetFullPath(hostPath);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
cachePath = hostPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
var lazy = _hostFileCache.GetOrAdd(
|
||||||
|
cachePath,
|
||||||
|
static path => new Lazy<CachedHostFile>(() => new CachedHostFile(path), isThreadSafe: true));
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
file = lazy.Value;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (UnauthorizedAccessException)
|
||||||
|
{
|
||||||
|
_hostFileCache.TryRemove(cachePath, out _);
|
||||||
|
result = (int)OrbisGen2Result.ORBIS_GEN2_ERROR_PERMISSION_DENIED;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
catch (IOException)
|
||||||
|
{
|
||||||
|
_hostFileCache.TryRemove(cachePath, out _);
|
||||||
|
result = (int)OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static bool AppendReadFileRecord(
|
private static bool AppendReadFileRecord(
|
||||||
CpuContext ctx,
|
CpuContext ctx,
|
||||||
ulong commandBuffer,
|
ulong commandBuffer,
|
||||||
|
|||||||
@@ -2,7 +2,9 @@
|
|||||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||||
|
|
||||||
using SharpEmu.HLE;
|
using SharpEmu.HLE;
|
||||||
|
using System.Buffers;
|
||||||
using System.Collections.Concurrent;
|
using System.Collections.Concurrent;
|
||||||
|
using System.Diagnostics;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
|
|
||||||
namespace SharpEmu.Libs.Audio;
|
namespace SharpEmu.Libs.Audio;
|
||||||
@@ -12,7 +14,70 @@ public static class AudioOutExports
|
|||||||
private static readonly ConcurrentDictionary<int, PortState> Ports = new();
|
private static readonly ConcurrentDictionary<int, PortState> Ports = new();
|
||||||
private static int _nextPortHandle;
|
private static int _nextPortHandle;
|
||||||
|
|
||||||
private sealed record PortState(int UserId, int Type, uint BufferLength, uint Frequency, int Format);
|
private sealed class PortState : IDisposable
|
||||||
|
{
|
||||||
|
private readonly object _paceGate = new();
|
||||||
|
private long _nextSilentOutput;
|
||||||
|
|
||||||
|
public PortState(
|
||||||
|
int userId,
|
||||||
|
int type,
|
||||||
|
uint bufferLength,
|
||||||
|
uint frequency,
|
||||||
|
int format,
|
||||||
|
int channels,
|
||||||
|
int bytesPerSample,
|
||||||
|
bool isFloat,
|
||||||
|
WinMmAudioPort? backend)
|
||||||
|
{
|
||||||
|
UserId = userId;
|
||||||
|
Type = type;
|
||||||
|
BufferLength = bufferLength;
|
||||||
|
Frequency = frequency;
|
||||||
|
Format = format;
|
||||||
|
Channels = channels;
|
||||||
|
BytesPerSample = bytesPerSample;
|
||||||
|
IsFloat = isFloat;
|
||||||
|
Backend = backend;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int UserId { get; }
|
||||||
|
public int Type { get; }
|
||||||
|
public uint BufferLength { get; }
|
||||||
|
public uint Frequency { get; }
|
||||||
|
public int Format { get; }
|
||||||
|
public int Channels { get; }
|
||||||
|
public int BytesPerSample { get; }
|
||||||
|
public bool IsFloat { get; }
|
||||||
|
public WinMmAudioPort? Backend { get; }
|
||||||
|
public int BufferByteLength =>
|
||||||
|
checked((int)BufferLength * Channels * BytesPerSample);
|
||||||
|
|
||||||
|
public void PaceSilence()
|
||||||
|
{
|
||||||
|
long delay;
|
||||||
|
lock (_paceGate)
|
||||||
|
{
|
||||||
|
var now = Stopwatch.GetTimestamp();
|
||||||
|
if (_nextSilentOutput < now)
|
||||||
|
{
|
||||||
|
_nextSilentOutput = now;
|
||||||
|
}
|
||||||
|
|
||||||
|
delay = _nextSilentOutput - now;
|
||||||
|
_nextSilentOutput += checked(
|
||||||
|
(long)Math.Ceiling(
|
||||||
|
Stopwatch.Frequency * (double)BufferLength / Frequency));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (delay > 0)
|
||||||
|
{
|
||||||
|
Thread.Sleep(TimeSpan.FromSeconds((double)delay / Stopwatch.Frequency));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose() => Backend?.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
[SysAbiExport(
|
[SysAbiExport(
|
||||||
Nid = "JfEPXVxhFqA",
|
Nid = "JfEPXVxhFqA",
|
||||||
@@ -33,13 +98,41 @@ public static class AudioOutExports
|
|||||||
var bufferLength = unchecked((uint)ctx[CpuRegister.Rcx]);
|
var bufferLength = unchecked((uint)ctx[CpuRegister.Rcx]);
|
||||||
var frequency = unchecked((uint)ctx[CpuRegister.R8]);
|
var frequency = unchecked((uint)ctx[CpuRegister.R8]);
|
||||||
var format = unchecked((int)ctx[CpuRegister.R9]);
|
var format = unchecked((int)ctx[CpuRegister.R9]);
|
||||||
if (bufferLength == 0 || frequency == 0)
|
if (bufferLength == 0 || frequency == 0 ||
|
||||||
|
!TryGetFormat(format, out var channels, out var bytesPerSample, out var isFloat))
|
||||||
{
|
{
|
||||||
return SetReturn(ctx, (int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT);
|
return SetReturn(ctx, (int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
WinMmAudioPort? backend = null;
|
||||||
|
string backendName;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
backend = new WinMmAudioPort(frequency);
|
||||||
|
backendName = "winmm";
|
||||||
|
}
|
||||||
|
catch (Exception exception)
|
||||||
|
{
|
||||||
|
backendName = "silent";
|
||||||
|
Console.Error.WriteLine(
|
||||||
|
$"[LOADER][WARN] AudioOut host backend unavailable: {exception.Message}");
|
||||||
|
}
|
||||||
|
|
||||||
var handle = Interlocked.Increment(ref _nextPortHandle);
|
var handle = Interlocked.Increment(ref _nextPortHandle);
|
||||||
Ports[handle] = new PortState(userId, type, bufferLength, frequency, format);
|
Ports[handle] = new PortState(
|
||||||
|
userId,
|
||||||
|
type,
|
||||||
|
bufferLength,
|
||||||
|
frequency,
|
||||||
|
format,
|
||||||
|
channels,
|
||||||
|
bytesPerSample,
|
||||||
|
isFloat,
|
||||||
|
backend);
|
||||||
|
Console.Error.WriteLine(
|
||||||
|
$"[LOADER][INFO] AudioOut port {handle}: {frequency} Hz, " +
|
||||||
|
$"{channels} ch, {(isFloat ? "float32" : "s16")}, " +
|
||||||
|
$"{bufferLength} frames, backend={backendName}");
|
||||||
return SetReturn(ctx, handle);
|
return SetReturn(ctx, handle);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -51,11 +144,13 @@ public static class AudioOutExports
|
|||||||
public static int AudioOutClose(CpuContext ctx)
|
public static int AudioOutClose(CpuContext ctx)
|
||||||
{
|
{
|
||||||
var handle = unchecked((int)ctx[CpuRegister.Rdi]);
|
var handle = unchecked((int)ctx[CpuRegister.Rdi]);
|
||||||
return SetReturn(
|
if (!Ports.TryRemove(handle, out var port))
|
||||||
ctx,
|
{
|
||||||
Ports.TryRemove(handle, out _)
|
return SetReturn(ctx, (int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT);
|
||||||
? 0
|
}
|
||||||
: (int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT);
|
|
||||||
|
port.Dispose();
|
||||||
|
return SetReturn(ctx, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
[SysAbiExport(
|
[SysAbiExport(
|
||||||
@@ -65,8 +160,44 @@ public static class AudioOutExports
|
|||||||
LibraryName = "libSceAudioOut")]
|
LibraryName = "libSceAudioOut")]
|
||||||
public static int AudioOutOutput(CpuContext ctx)
|
public static int AudioOutOutput(CpuContext ctx)
|
||||||
{
|
{
|
||||||
ctx[CpuRegister.Rax] = 0;
|
var handle = unchecked((int)ctx[CpuRegister.Rdi]);
|
||||||
return (int)OrbisGen2Result.ORBIS_GEN2_OK;
|
var sourceAddress = ctx[CpuRegister.Rsi];
|
||||||
|
if (!Ports.TryGetValue(handle, out var port))
|
||||||
|
{
|
||||||
|
return SetReturn(ctx, (int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sourceAddress == 0)
|
||||||
|
{
|
||||||
|
return SetReturn(ctx, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
var buffer = ArrayPool<byte>.Shared.Rent(port.BufferByteLength);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var source = buffer.AsSpan(0, port.BufferByteLength);
|
||||||
|
if (!ctx.Memory.TryRead(sourceAddress, source))
|
||||||
|
{
|
||||||
|
return SetReturn(ctx, (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (port.Backend is null ||
|
||||||
|
!port.Backend.Submit(
|
||||||
|
source,
|
||||||
|
port.BufferLength,
|
||||||
|
port.Channels,
|
||||||
|
port.BytesPerSample,
|
||||||
|
port.IsFloat))
|
||||||
|
{
|
||||||
|
port.PaceSilence();
|
||||||
|
}
|
||||||
|
|
||||||
|
return SetReturn(ctx, 0);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
ArrayPool<byte>.Shared.Return(buffer);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
[SysAbiExport(
|
[SysAbiExport(
|
||||||
@@ -89,4 +220,23 @@ public static class AudioOutExports
|
|||||||
ctx[CpuRegister.Rax] = unchecked((ulong)result);
|
ctx[CpuRegister.Rax] = unchecked((ulong)result);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static bool TryGetFormat(
|
||||||
|
int rawFormat,
|
||||||
|
out int channels,
|
||||||
|
out int bytesPerSample,
|
||||||
|
out bool isFloat)
|
||||||
|
{
|
||||||
|
var format = rawFormat & 0xFF;
|
||||||
|
channels = format switch
|
||||||
|
{
|
||||||
|
0 or 3 => 1,
|
||||||
|
1 or 4 => 2,
|
||||||
|
2 or 5 or 6 or 7 => 8,
|
||||||
|
_ => 0,
|
||||||
|
};
|
||||||
|
bytesPerSample = format is >= 3 and <= 5 or 7 ? 4 : 2;
|
||||||
|
isFloat = bytesPerSample == 4;
|
||||||
|
return channels != 0;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,302 @@
|
|||||||
|
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||||
|
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||||
|
|
||||||
|
using System.Buffers;
|
||||||
|
using System.Buffers.Binary;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
|
||||||
|
namespace SharpEmu.Libs.Audio;
|
||||||
|
|
||||||
|
internal sealed class WinMmAudioPort : IDisposable
|
||||||
|
{
|
||||||
|
private const uint WaveMapper = uint.MaxValue;
|
||||||
|
private const uint CallbackEvent = 0x0005_0000;
|
||||||
|
private const ushort WaveFormatPcm = 1;
|
||||||
|
private const uint WaveHeaderDone = 0x0000_0001;
|
||||||
|
private const int MaximumQueuedPcmBytes = 32 * 1024;
|
||||||
|
|
||||||
|
private readonly object _gate = new();
|
||||||
|
private readonly AutoResetEvent _completion = new(false);
|
||||||
|
private readonly Queue<NativeBuffer> _buffers = new();
|
||||||
|
private IntPtr _device;
|
||||||
|
private int _queuedPcmBytes;
|
||||||
|
private bool _disposed;
|
||||||
|
|
||||||
|
public WinMmAudioPort(uint sampleRate)
|
||||||
|
{
|
||||||
|
if (!OperatingSystem.IsWindows())
|
||||||
|
{
|
||||||
|
throw new PlatformNotSupportedException("WinMM audio is only available on Windows.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var format = new WaveFormat
|
||||||
|
{
|
||||||
|
FormatTag = WaveFormatPcm,
|
||||||
|
Channels = 2,
|
||||||
|
SamplesPerSecond = sampleRate,
|
||||||
|
AverageBytesPerSecond = checked(sampleRate * 4),
|
||||||
|
BlockAlign = 4,
|
||||||
|
BitsPerSample = 16,
|
||||||
|
ExtraSize = 0,
|
||||||
|
};
|
||||||
|
var result = WaveOutOpen(
|
||||||
|
out _device,
|
||||||
|
WaveMapper,
|
||||||
|
ref format,
|
||||||
|
_completion.SafeWaitHandle.DangerousGetHandle(),
|
||||||
|
IntPtr.Zero,
|
||||||
|
CallbackEvent);
|
||||||
|
if (result != 0)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException($"waveOutOpen failed with MMRESULT {result}.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Submit(
|
||||||
|
ReadOnlySpan<byte> source,
|
||||||
|
uint frames,
|
||||||
|
int channels,
|
||||||
|
int bytesPerSample,
|
||||||
|
bool isFloat)
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
if (_disposed)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var outputLength = checked((int)frames * 4);
|
||||||
|
ReapCompletedBuffers();
|
||||||
|
while (_queuedPcmBytes != 0 &&
|
||||||
|
_queuedPcmBytes + outputLength > MaximumQueuedPcmBytes)
|
||||||
|
{
|
||||||
|
if (!_completion.WaitOne(TimeSpan.FromSeconds(1)))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
ReapCompletedBuffers();
|
||||||
|
}
|
||||||
|
|
||||||
|
var output = ArrayPool<byte>.Shared.Rent(outputLength);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
ConvertToStereoPcm16(
|
||||||
|
source,
|
||||||
|
output.AsSpan(0, outputLength),
|
||||||
|
checked((int)frames),
|
||||||
|
channels,
|
||||||
|
bytesPerSample,
|
||||||
|
isFloat);
|
||||||
|
return QueueBuffer(output.AsSpan(0, outputLength));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
ArrayPool<byte>.Shared.Return(output);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
if (_disposed)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_disposed = true;
|
||||||
|
if (_device != IntPtr.Zero)
|
||||||
|
{
|
||||||
|
WaveOutReset(_device);
|
||||||
|
while (_buffers.TryDequeue(out var buffer))
|
||||||
|
{
|
||||||
|
ReleaseBuffer(buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
WaveOutClose(_device);
|
||||||
|
_device = IntPtr.Zero;
|
||||||
|
}
|
||||||
|
|
||||||
|
_completion.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool QueueBuffer(ReadOnlySpan<byte> data)
|
||||||
|
{
|
||||||
|
var dataAddress = Marshal.AllocHGlobal(data.Length);
|
||||||
|
var headerAddress = IntPtr.Zero;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
unsafe
|
||||||
|
{
|
||||||
|
data.CopyTo(new Span<byte>((void*)dataAddress, data.Length));
|
||||||
|
}
|
||||||
|
|
||||||
|
var header = new WaveHeader
|
||||||
|
{
|
||||||
|
Data = dataAddress,
|
||||||
|
BufferLength = checked((uint)data.Length),
|
||||||
|
};
|
||||||
|
headerAddress = Marshal.AllocHGlobal(Marshal.SizeOf<WaveHeader>());
|
||||||
|
Marshal.StructureToPtr(header, headerAddress, false);
|
||||||
|
|
||||||
|
var result = WaveOutPrepareHeader(
|
||||||
|
_device,
|
||||||
|
headerAddress,
|
||||||
|
checked((uint)Marshal.SizeOf<WaveHeader>()));
|
||||||
|
if (result != 0)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
result = WaveOutWrite(
|
||||||
|
_device,
|
||||||
|
headerAddress,
|
||||||
|
checked((uint)Marshal.SizeOf<WaveHeader>()));
|
||||||
|
if (result != 0)
|
||||||
|
{
|
||||||
|
WaveOutUnprepareHeader(
|
||||||
|
_device,
|
||||||
|
headerAddress,
|
||||||
|
checked((uint)Marshal.SizeOf<WaveHeader>()));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
_buffers.Enqueue(new NativeBuffer(dataAddress, headerAddress, data.Length));
|
||||||
|
_queuedPcmBytes += data.Length;
|
||||||
|
dataAddress = IntPtr.Zero;
|
||||||
|
headerAddress = IntPtr.Zero;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
if (headerAddress != IntPtr.Zero)
|
||||||
|
{
|
||||||
|
Marshal.FreeHGlobal(headerAddress);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dataAddress != IntPtr.Zero)
|
||||||
|
{
|
||||||
|
Marshal.FreeHGlobal(dataAddress);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ReapCompletedBuffers()
|
||||||
|
{
|
||||||
|
while (_buffers.TryPeek(out var buffer))
|
||||||
|
{
|
||||||
|
var header = Marshal.PtrToStructure<WaveHeader>(buffer.Header);
|
||||||
|
if ((header.Flags & WaveHeaderDone) == 0)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_buffers.Dequeue();
|
||||||
|
ReleaseBuffer(buffer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ReleaseBuffer(NativeBuffer buffer)
|
||||||
|
{
|
||||||
|
WaveOutUnprepareHeader(
|
||||||
|
_device,
|
||||||
|
buffer.Header,
|
||||||
|
checked((uint)Marshal.SizeOf<WaveHeader>()));
|
||||||
|
_queuedPcmBytes -= buffer.Length;
|
||||||
|
Marshal.FreeHGlobal(buffer.Header);
|
||||||
|
Marshal.FreeHGlobal(buffer.Data);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ConvertToStereoPcm16(
|
||||||
|
ReadOnlySpan<byte> source,
|
||||||
|
Span<byte> destination,
|
||||||
|
int frames,
|
||||||
|
int channels,
|
||||||
|
int bytesPerSample,
|
||||||
|
bool isFloat)
|
||||||
|
{
|
||||||
|
var sourceFrameSize = checked(channels * bytesPerSample);
|
||||||
|
for (var frame = 0; frame < frames; frame++)
|
||||||
|
{
|
||||||
|
var sourceFrame = source.Slice(frame * sourceFrameSize, sourceFrameSize);
|
||||||
|
var left = ReadSample(sourceFrame, 0, bytesPerSample, isFloat);
|
||||||
|
var right = channels == 1
|
||||||
|
? left
|
||||||
|
: ReadSample(sourceFrame, 1, bytesPerSample, isFloat);
|
||||||
|
BinaryPrimitives.WriteInt16LittleEndian(destination[(frame * 4)..], left);
|
||||||
|
BinaryPrimitives.WriteInt16LittleEndian(destination[((frame * 4) + 2)..], right);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static short ReadSample(
|
||||||
|
ReadOnlySpan<byte> frame,
|
||||||
|
int channel,
|
||||||
|
int bytesPerSample,
|
||||||
|
bool isFloat)
|
||||||
|
{
|
||||||
|
var sample = frame.Slice(channel * bytesPerSample, bytesPerSample);
|
||||||
|
if (!isFloat)
|
||||||
|
{
|
||||||
|
return BinaryPrimitives.ReadInt16LittleEndian(sample);
|
||||||
|
}
|
||||||
|
|
||||||
|
var bits = BinaryPrimitives.ReadInt32LittleEndian(sample);
|
||||||
|
var value = Math.Clamp(BitConverter.Int32BitsToSingle(bits), -1.0f, 1.0f);
|
||||||
|
return checked((short)MathF.Round(value * short.MaxValue));
|
||||||
|
}
|
||||||
|
|
||||||
|
private readonly record struct NativeBuffer(IntPtr Data, IntPtr Header, int Length);
|
||||||
|
|
||||||
|
[StructLayout(LayoutKind.Sequential, Pack = 2)]
|
||||||
|
private struct WaveFormat
|
||||||
|
{
|
||||||
|
public ushort FormatTag;
|
||||||
|
public ushort Channels;
|
||||||
|
public uint SamplesPerSecond;
|
||||||
|
public uint AverageBytesPerSecond;
|
||||||
|
public ushort BlockAlign;
|
||||||
|
public ushort BitsPerSample;
|
||||||
|
public ushort ExtraSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
[StructLayout(LayoutKind.Sequential)]
|
||||||
|
private struct WaveHeader
|
||||||
|
{
|
||||||
|
public IntPtr Data;
|
||||||
|
public uint BufferLength;
|
||||||
|
public uint BytesRecorded;
|
||||||
|
public nuint User;
|
||||||
|
public uint Flags;
|
||||||
|
public uint Loops;
|
||||||
|
public IntPtr Next;
|
||||||
|
public nuint Reserved;
|
||||||
|
}
|
||||||
|
|
||||||
|
[DllImport("winmm.dll", EntryPoint = "waveOutOpen")]
|
||||||
|
private static extern uint WaveOutOpen(
|
||||||
|
out IntPtr device,
|
||||||
|
uint deviceId,
|
||||||
|
ref WaveFormat format,
|
||||||
|
IntPtr callback,
|
||||||
|
IntPtr instance,
|
||||||
|
uint flags);
|
||||||
|
|
||||||
|
[DllImport("winmm.dll", EntryPoint = "waveOutPrepareHeader")]
|
||||||
|
private static extern uint WaveOutPrepareHeader(IntPtr device, IntPtr header, uint headerSize);
|
||||||
|
|
||||||
|
[DllImport("winmm.dll", EntryPoint = "waveOutWrite")]
|
||||||
|
private static extern uint WaveOutWrite(IntPtr device, IntPtr header, uint headerSize);
|
||||||
|
|
||||||
|
[DllImport("winmm.dll", EntryPoint = "waveOutUnprepareHeader")]
|
||||||
|
private static extern uint WaveOutUnprepareHeader(IntPtr device, IntPtr header, uint headerSize);
|
||||||
|
|
||||||
|
[DllImport("winmm.dll", EntryPoint = "waveOutReset")]
|
||||||
|
private static extern uint WaveOutReset(IntPtr device);
|
||||||
|
|
||||||
|
[DllImport("winmm.dll", EntryPoint = "waveOutClose")]
|
||||||
|
private static extern uint WaveOutClose(IntPtr device);
|
||||||
|
}
|
||||||
@@ -276,6 +276,22 @@ public static class KernelEventQueueCompatExports
|
|||||||
var outCountAddress = ctx[CpuRegister.Rcx];
|
var outCountAddress = ctx[CpuRegister.Rcx];
|
||||||
var timeoutAddress = ctx[CpuRegister.R8];
|
var timeoutAddress = ctx[CpuRegister.R8];
|
||||||
|
|
||||||
|
if (!IsValidEqueue(handle))
|
||||||
|
{
|
||||||
|
return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (eventsAddress == 0 || eventCapacity < 1)
|
||||||
|
{
|
||||||
|
return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint timeoutUsec = 0;
|
||||||
|
if (timeoutAddress != 0 && !TryReadUInt32(ctx, timeoutAddress, out timeoutUsec))
|
||||||
|
{
|
||||||
|
return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT;
|
||||||
|
}
|
||||||
|
|
||||||
var deliveredCount = DequeueEvents(ctx, handle, eventsAddress, eventCapacity);
|
var deliveredCount = DequeueEvents(ctx, handle, eventsAddress, eventCapacity);
|
||||||
if (outCountAddress != 0 && !TryWriteUInt32(ctx, outCountAddress, (uint)deliveredCount))
|
if (outCountAddress != 0 && !TryWriteUInt32(ctx, outCountAddress, (uint)deliveredCount))
|
||||||
{
|
{
|
||||||
@@ -300,6 +316,41 @@ public static class KernelEventQueueCompatExports
|
|||||||
return (int)OrbisGen2Result.ORBIS_GEN2_OK;
|
return (int)OrbisGen2Result.ORBIS_GEN2_OK;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (timeoutAddress != 0 && ctx.TryReadUInt64(timeoutAddress, out var timeoutRaw))
|
||||||
|
{
|
||||||
|
var timeoutMicros = timeoutRaw & 0xFFFF_FFFFUL;
|
||||||
|
var deadline = Environment.TickCount64 +
|
||||||
|
Math.Max(1L, (long)Math.Min(timeoutMicros / 1000, int.MaxValue));
|
||||||
|
lock (_eventQueueGate)
|
||||||
|
{
|
||||||
|
while (!HasPendingEvents(handle))
|
||||||
|
{
|
||||||
|
var remaining = deadline - Environment.TickCount64;
|
||||||
|
if (remaining <= 0)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
Monitor.Wait(_eventQueueGate, (int)Math.Min(remaining, 100));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
deliveredCount = DequeueEvents(ctx, handle, eventsAddress, eventCapacity);
|
||||||
|
if (outCountAddress != 0 && !TryWriteUInt32(ctx, outCountAddress, (uint)deliveredCount))
|
||||||
|
{
|
||||||
|
return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (deliveredCount > 0)
|
||||||
|
{
|
||||||
|
TraceEventQueue(ctx, "wait-timed-deliver", handle);
|
||||||
|
return (int)OrbisGen2Result.ORBIS_GEN2_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
TraceEventQueue(ctx, "wait-timeout", handle);
|
||||||
|
return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_TIMED_OUT;
|
||||||
|
}
|
||||||
|
|
||||||
TraceEventQueue(ctx, "wait", handle);
|
TraceEventQueue(ctx, "wait", handle);
|
||||||
return (int)OrbisGen2Result.ORBIS_GEN2_OK;
|
return (int)OrbisGen2Result.ORBIS_GEN2_OK;
|
||||||
}
|
}
|
||||||
@@ -330,6 +381,7 @@ public static class KernelEventQueueCompatExports
|
|||||||
|
|
||||||
queue.AddLast(queuedEvent);
|
queue.AddLast(queuedEvent);
|
||||||
queued = true;
|
queued = true;
|
||||||
|
Monitor.PulseAll(_eventQueueGate);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (queued)
|
if (queued)
|
||||||
@@ -494,7 +546,9 @@ public static class KernelEventQueueCompatExports
|
|||||||
return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT;
|
return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (int)OrbisGen2Result.ORBIS_GEN2_OK;
|
return deliveredCount > 0
|
||||||
|
? (int)OrbisGen2Result.ORBIS_GEN2_OK
|
||||||
|
: (int)OrbisGen2Result.ORBIS_GEN2_ERROR_TIMED_OUT;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static bool HasPendingEvents(ulong handle)
|
private static bool HasPendingEvents(ulong handle)
|
||||||
@@ -612,4 +666,17 @@ public static class KernelEventQueueCompatExports
|
|||||||
BinaryPrimitives.WriteUInt32LittleEndian(buffer, value);
|
BinaryPrimitives.WriteUInt32LittleEndian(buffer, value);
|
||||||
return ctx.Memory.TryWrite(address, buffer);
|
return ctx.Memory.TryWrite(address, buffer);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static bool TryReadUInt32(CpuContext ctx, ulong address, out uint value)
|
||||||
|
{
|
||||||
|
Span<byte> buffer = stackalloc byte[sizeof(uint)];
|
||||||
|
if (!ctx.Memory.TryRead(address, buffer))
|
||||||
|
{
|
||||||
|
value = 0;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
value = BinaryPrimitives.ReadUInt32LittleEndian(buffer);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,9 +5,9 @@ using SharpEmu.HLE;
|
|||||||
using SharpEmu.Libs.Ampr;
|
using SharpEmu.Libs.Ampr;
|
||||||
using System.Buffers;
|
using System.Buffers;
|
||||||
using System.Buffers.Binary;
|
using System.Buffers.Binary;
|
||||||
|
using System.Collections.Concurrent;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Reflection;
|
|
||||||
using System.Runtime.InteropServices;
|
using System.Runtime.InteropServices;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
@@ -108,6 +108,7 @@ public static class KernelMemoryCompatExports
|
|||||||
private static readonly Dictionary<string, string> _guestMounts = new(StringComparer.OrdinalIgnoreCase);
|
private static readonly Dictionary<string, string> _guestMounts = new(StringComparer.OrdinalIgnoreCase);
|
||||||
private static readonly HashSet<string> _tracedStatResults = new(StringComparer.Ordinal);
|
private static readonly HashSet<string> _tracedStatResults = new(StringComparer.Ordinal);
|
||||||
private static readonly HashSet<string> _negativeStatCache = new(StringComparer.OrdinalIgnoreCase);
|
private static readonly HashSet<string> _negativeStatCache = new(StringComparer.OrdinalIgnoreCase);
|
||||||
|
private static readonly ConcurrentDictionary<string, ulong> _aprFileSizeCache = new(StringComparer.OrdinalIgnoreCase);
|
||||||
private static long _nextFileDescriptor = 2;
|
private static long _nextFileDescriptor = 2;
|
||||||
private static ulong _nextPhysicalAddress;
|
private static ulong _nextPhysicalAddress;
|
||||||
private static ulong _nextVirtualAddress;
|
private static ulong _nextVirtualAddress;
|
||||||
@@ -1342,6 +1343,7 @@ public static class KernelMemoryCompatExports
|
|||||||
if (IsMutatingOpen(flags))
|
if (IsMutatingOpen(flags))
|
||||||
{
|
{
|
||||||
InvalidateNegativeStatCacheForPathAndAncestors(guestPath);
|
InvalidateNegativeStatCacheForPathAndAncestors(guestPath);
|
||||||
|
InvalidateAprFileSizeCache(hostPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
LogOpenTrace($"_open file path='{guestPath}' host='{hostPath}' flags=0x{flags:X8} fd={fd}");
|
LogOpenTrace($"_open file path='{guestPath}' host='{hostPath}' flags=0x{flags:X8} fd={fd}");
|
||||||
@@ -1550,6 +1552,7 @@ public static class KernelMemoryCompatExports
|
|||||||
|
|
||||||
File.Delete(hostPath);
|
File.Delete(hostPath);
|
||||||
InvalidateNegativeStatCacheForPathAndAncestors(guestPath);
|
InvalidateNegativeStatCacheForPathAndAncestors(guestPath);
|
||||||
|
InvalidateAprFileSizeCache(hostPath);
|
||||||
AddNegativeStatCacheForGuestPath(guestPath);
|
AddNegativeStatCacheForGuestPath(guestPath);
|
||||||
LogOpenTrace($"unlink path='{guestPath}' host='{hostPath}'");
|
LogOpenTrace($"unlink path='{guestPath}' host='{hostPath}'");
|
||||||
ctx[CpuRegister.Rax] = 0;
|
ctx[CpuRegister.Rax] = 0;
|
||||||
@@ -2528,6 +2531,17 @@ public static class KernelMemoryCompatExports
|
|||||||
if (fixedMapping && requestedAddress != 0)
|
if (fixedMapping && requestedAddress != 0)
|
||||||
{
|
{
|
||||||
mappedAddress = requestedAddress;
|
mappedAddress = requestedAddress;
|
||||||
|
reserved = IsGuestRangeBacked(ctx, requestedAddress, length);
|
||||||
|
if (!reserved)
|
||||||
|
{
|
||||||
|
TryReserveExactGuestVirtualRange(ctx, requestedAddress, length, protection);
|
||||||
|
reserved = IsGuestRangeBacked(ctx, requestedAddress, length);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!reserved)
|
||||||
|
{
|
||||||
|
mappedAddress = 0;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
@@ -2538,7 +2552,7 @@ public static class KernelMemoryCompatExports
|
|||||||
Console.Error.WriteLine(
|
Console.Error.WriteLine(
|
||||||
$"[LOADER][TRACE] map_direct reserve: requested=0x{requestedAddress:X16} desired=0x{desiredAddress:X16} reserved={reserved} mapped=0x{mappedAddress:X16}");
|
$"[LOADER][TRACE] map_direct reserve: requested=0x{requestedAddress:X16} desired=0x{desiredAddress:X16} reserved={reserved} mapped=0x{mappedAddress:X16}");
|
||||||
}
|
}
|
||||||
if (!reserved)
|
if (!reserved && !fixedMapping)
|
||||||
{
|
{
|
||||||
if (mappedAddress == 0)
|
if (mappedAddress == 0)
|
||||||
{
|
{
|
||||||
@@ -2596,8 +2610,11 @@ public static class KernelMemoryCompatExports
|
|||||||
var length = ctx[CpuRegister.Rsi];
|
var length = ctx[CpuRegister.Rsi];
|
||||||
var protection = unchecked((int)ctx[CpuRegister.Rdx]);
|
var protection = unchecked((int)ctx[CpuRegister.Rdx]);
|
||||||
var flags = ctx[CpuRegister.Rcx];
|
var flags = ctx[CpuRegister.Rcx];
|
||||||
Console.Error.WriteLine(
|
if (ShouldTraceDirectMemory())
|
||||||
$"[LOADER][TRACE] map_flexible: inout=0x{inOutAddressPointer:X16} len=0x{length:X16} prot=0x{protection:X8} flags=0x{flags:X16}");
|
{
|
||||||
|
Console.Error.WriteLine(
|
||||||
|
$"[LOADER][TRACE] map_flexible: inout=0x{inOutAddressPointer:X16} len=0x{length:X16} prot=0x{protection:X8} flags=0x{flags:X16}");
|
||||||
|
}
|
||||||
if (inOutAddressPointer == 0 || length == 0)
|
if (inOutAddressPointer == 0 || length == 0)
|
||||||
{
|
{
|
||||||
return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT;
|
return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT;
|
||||||
@@ -2619,16 +2636,25 @@ public static class KernelMemoryCompatExports
|
|||||||
if (fixedMapping && requestedAddress != 0)
|
if (fixedMapping && requestedAddress != 0)
|
||||||
{
|
{
|
||||||
mappedAddress = requestedAddress;
|
mappedAddress = requestedAddress;
|
||||||
|
if (!IsGuestRangeBacked(ctx, requestedAddress, length))
|
||||||
|
{
|
||||||
|
TryReserveExactGuestVirtualRange(ctx, requestedAddress, length, protection);
|
||||||
|
if (!IsGuestRangeBacked(ctx, requestedAddress, length))
|
||||||
|
{
|
||||||
|
mappedAddress = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
else if (!TryReserveGuestVirtualRange(ctx, desiredAddress, length, protection, OrbisPageSize, out mappedAddress))
|
else if (!TryReserveGuestVirtualRange(ctx, desiredAddress, length, protection, OrbisPageSize, out mappedAddress))
|
||||||
{
|
{
|
||||||
mappedAddress = requestedAddress != 0 && fixedMapping
|
mappedAddress = AllocateMappedGuestAddress(ctx, length, 0x1000UL);
|
||||||
? requestedAddress
|
|
||||||
: AllocateMappedGuestAddress(ctx, length, 0x1000UL);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Console.Error.WriteLine(
|
if (ShouldTraceDirectMemory())
|
||||||
$"[LOADER][TRACE] map_flexible reserve: requested=0x{requestedAddress:X16} desired=0x{desiredAddress:X16} mapped=0x{mappedAddress:X16}");
|
{
|
||||||
|
Console.Error.WriteLine(
|
||||||
|
$"[LOADER][TRACE] map_flexible reserve: requested=0x{requestedAddress:X16} desired=0x{desiredAddress:X16} mapped=0x{mappedAddress:X16}");
|
||||||
|
}
|
||||||
|
|
||||||
if (mappedAddress == 0)
|
if (mappedAddress == 0)
|
||||||
{
|
{
|
||||||
@@ -3973,118 +3999,48 @@ public static class KernelMemoryCompatExports
|
|||||||
ulong alignment,
|
ulong alignment,
|
||||||
out ulong mappedAddress)
|
out ulong mappedAddress)
|
||||||
{
|
{
|
||||||
mappedAddress = 0;
|
var executable = (protection & OrbisProtCpuExec) != 0;
|
||||||
if (length == 0)
|
return KernelVirtualRangeAllocator.TryReserve(
|
||||||
|
ctx,
|
||||||
|
desiredAddress,
|
||||||
|
length,
|
||||||
|
executable,
|
||||||
|
alignment,
|
||||||
|
allowSearch: true,
|
||||||
|
allowAllocateAtAlternative: false,
|
||||||
|
"reserve range",
|
||||||
|
out mappedAddress);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryReserveExactGuestVirtualRange(
|
||||||
|
CpuContext ctx,
|
||||||
|
ulong desiredAddress,
|
||||||
|
ulong length,
|
||||||
|
int protection)
|
||||||
|
{
|
||||||
|
var executable = (protection & OrbisProtCpuExec) != 0;
|
||||||
|
return KernelVirtualRangeAllocator.TryReserve(
|
||||||
|
ctx,
|
||||||
|
desiredAddress,
|
||||||
|
length,
|
||||||
|
executable,
|
||||||
|
alignment: 0,
|
||||||
|
allowSearch: false,
|
||||||
|
allowAllocateAtAlternative: false,
|
||||||
|
"reserve fixed range",
|
||||||
|
out _);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsGuestRangeBacked(CpuContext ctx, ulong address, ulong length)
|
||||||
|
{
|
||||||
|
if (address == 0 || length == 0 || ulong.MaxValue - address < length - 1)
|
||||||
{
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
try
|
Span<byte> probe = stackalloc byte[1];
|
||||||
{
|
return ctx.Memory.TryRead(address, probe) &&
|
||||||
object memoryObject = ctx.Memory;
|
ctx.Memory.TryRead(address + length - 1, probe);
|
||||||
MethodInfo? allocateAt = null;
|
|
||||||
MethodInfo? allocateAtOrAbove = null;
|
|
||||||
var allocateAtHasAllowAlternativeArg = false;
|
|
||||||
for (var depth = 0; depth < 4; depth++)
|
|
||||||
{
|
|
||||||
foreach (var candidate in memoryObject.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance))
|
|
||||||
{
|
|
||||||
var parameters = candidate.GetParameters();
|
|
||||||
if (string.Equals(candidate.Name, "TryAllocateAtOrAbove", StringComparison.Ordinal) &&
|
|
||||||
parameters.Length == 5 &&
|
|
||||||
parameters[0].ParameterType == typeof(ulong) &&
|
|
||||||
parameters[1].ParameterType == typeof(ulong) &&
|
|
||||||
parameters[2].ParameterType == typeof(bool) &&
|
|
||||||
parameters[3].ParameterType == typeof(ulong) &&
|
|
||||||
parameters[4].ParameterType == typeof(ulong).MakeByRefType())
|
|
||||||
{
|
|
||||||
allocateAtOrAbove = candidate;
|
|
||||||
}
|
|
||||||
else if (string.Equals(candidate.Name, "AllocateAt", StringComparison.Ordinal))
|
|
||||||
{
|
|
||||||
if (parameters.Length == 3 &&
|
|
||||||
parameters[0].ParameterType == typeof(ulong) &&
|
|
||||||
parameters[1].ParameterType == typeof(ulong) &&
|
|
||||||
parameters[2].ParameterType == typeof(bool))
|
|
||||||
{
|
|
||||||
allocateAt = candidate;
|
|
||||||
allocateAtHasAllowAlternativeArg = false;
|
|
||||||
}
|
|
||||||
else if (parameters.Length == 4 &&
|
|
||||||
parameters[0].ParameterType == typeof(ulong) &&
|
|
||||||
parameters[1].ParameterType == typeof(ulong) &&
|
|
||||||
parameters[2].ParameterType == typeof(bool) &&
|
|
||||||
parameters[3].ParameterType == typeof(bool))
|
|
||||||
{
|
|
||||||
allocateAt = candidate;
|
|
||||||
allocateAtHasAllowAlternativeArg = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (allocateAtOrAbove is not null && allocateAt is not null)
|
|
||||||
{
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (allocateAtOrAbove is not null || allocateAt is not null)
|
|
||||||
{
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
var innerProperty = memoryObject.GetType().GetProperty("Inner", BindingFlags.Public | BindingFlags.Instance);
|
|
||||||
if (innerProperty is null)
|
|
||||||
{
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
var innerValue = innerProperty.GetValue(memoryObject);
|
|
||||||
if (innerValue is null || ReferenceEquals(innerValue, memoryObject))
|
|
||||||
{
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
memoryObject = innerValue;
|
|
||||||
}
|
|
||||||
|
|
||||||
var executable = (protection & OrbisProtCpuExec) != 0;
|
|
||||||
if (allocateAtOrAbove is not null)
|
|
||||||
{
|
|
||||||
var searchArgs = new object[] { desiredAddress, length, executable, alignment, 0UL };
|
|
||||||
var searchResult = allocateAtOrAbove.Invoke(memoryObject, searchArgs);
|
|
||||||
if (searchResult is bool trueValue && trueValue &&
|
|
||||||
searchArgs[4] is ulong searchedAddress && searchedAddress != 0)
|
|
||||||
{
|
|
||||||
mappedAddress = searchedAddress;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (allocateAt is null)
|
|
||||||
{
|
|
||||||
Console.Error.WriteLine($"[LOADER][TRACE] reserve range: AllocateAt missing on {ctx.Memory.GetType().FullName}");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
var invokeArgs = allocateAtHasAllowAlternativeArg
|
|
||||||
? new object[] { desiredAddress, length, executable, false }
|
|
||||||
: new object[] { desiredAddress, length, executable };
|
|
||||||
var result = allocateAt.Invoke(memoryObject, invokeArgs);
|
|
||||||
if (result is not ulong allocated || allocated == 0)
|
|
||||||
{
|
|
||||||
var resultType = result?.GetType().FullName ?? "null";
|
|
||||||
Console.Error.WriteLine($"[LOADER][TRACE] reserve range: AllocateAt returned {resultType} value={result ?? "null"}");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
mappedAddress = allocated;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
catch
|
|
||||||
{
|
|
||||||
Console.Error.WriteLine("[LOADER][TRACE] reserve range threw while invoking AllocateAt");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static bool IsMappedGuestRangeAvailable(
|
private static bool IsMappedGuestRangeAvailable(
|
||||||
@@ -4237,6 +4193,20 @@ public static class KernelMemoryCompatExports
|
|||||||
var app0Root = ResolveApp0Root();
|
var app0Root = ResolveApp0Root();
|
||||||
if (!string.IsNullOrWhiteSpace(app0Root))
|
if (!string.IsNullOrWhiteSpace(app0Root))
|
||||||
{
|
{
|
||||||
|
if (string.Equals(guestPath, "$", StringComparison.Ordinal) ||
|
||||||
|
string.Equals(guestPath, "$/", StringComparison.Ordinal) ||
|
||||||
|
string.Equals(guestPath, "$\\", StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
return app0Root;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (guestPath.StartsWith("$/", StringComparison.Ordinal) ||
|
||||||
|
guestPath.StartsWith("$\\", StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
var relative = NormalizeMountRelativePath(guestPath[2..]);
|
||||||
|
return Path.Combine(app0Root, relative);
|
||||||
|
}
|
||||||
|
|
||||||
if (string.Equals(guestPath, "/app0", StringComparison.OrdinalIgnoreCase) ||
|
if (string.Equals(guestPath, "/app0", StringComparison.OrdinalIgnoreCase) ||
|
||||||
string.Equals(guestPath, "app0", StringComparison.OrdinalIgnoreCase))
|
string.Equals(guestPath, "app0", StringComparison.OrdinalIgnoreCase))
|
||||||
{
|
{
|
||||||
@@ -5899,22 +5869,40 @@ public static class KernelMemoryCompatExports
|
|||||||
private static bool TryGetAprFileSize(string hostPath, out ulong size)
|
private static bool TryGetAprFileSize(string hostPath, out ulong size)
|
||||||
{
|
{
|
||||||
size = 0;
|
size = 0;
|
||||||
|
|
||||||
|
string cachePath;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var fileInfo = new FileInfo(hostPath);
|
cachePath = Path.GetFullPath(hostPath);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
cachePath = hostPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_aprFileSizeCache.TryGetValue(cachePath, out size))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var fileInfo = new FileInfo(cachePath);
|
||||||
if (fileInfo.Exists)
|
if (fileInfo.Exists)
|
||||||
{
|
{
|
||||||
var length = fileInfo.Length;
|
var length = fileInfo.Length;
|
||||||
size = length < 0 ? 0UL : unchecked((ulong)length);
|
size = length < 0 ? 0UL : unchecked((ulong)length);
|
||||||
|
_aprFileSizeCache.TryAdd(cachePath, size);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!new DirectoryInfo(hostPath).Exists)
|
if (!new DirectoryInfo(cachePath).Exists)
|
||||||
{
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
size = 65536;
|
size = 65536;
|
||||||
|
_aprFileSizeCache.TryAdd(cachePath, size);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
catch
|
catch
|
||||||
@@ -6213,6 +6201,20 @@ public static class KernelMemoryCompatExports
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static void InvalidateAprFileSizeCache(string hostPath)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
hostPath = Path.GetFullPath(hostPath);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// The cache key remains the original path when normalization fails.
|
||||||
|
}
|
||||||
|
|
||||||
|
_aprFileSizeCache.TryRemove(hostPath, out _);
|
||||||
|
}
|
||||||
|
|
||||||
private static string PreviewIoBytes(byte[] buffer, int count, int maxBytes)
|
private static string PreviewIoBytes(byte[] buffer, int count, int maxBytes)
|
||||||
{
|
{
|
||||||
if (count <= 0)
|
if (count <= 0)
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ public static class KernelPthreadExtendedCompatExports
|
|||||||
private const int DefaultSchedPriority = DefaultThreadPriority;
|
private const int DefaultSchedPriority = DefaultThreadPriority;
|
||||||
private const ulong SyntheticRwlockHandleBase = 0x00006003_0000_0000;
|
private const ulong SyntheticRwlockHandleBase = 0x00006003_0000_0000;
|
||||||
private const ulong SyntheticPthreadAttrHandleBase = 0x00006004_0000_0000;
|
private const ulong SyntheticPthreadAttrHandleBase = 0x00006004_0000_0000;
|
||||||
|
private const ulong SyntheticRwlockAttrHandleBase = 0x00006005_0000_0000;
|
||||||
|
|
||||||
private static readonly object _stateGate = new();
|
private static readonly object _stateGate = new();
|
||||||
private static readonly Dictionary<ulong, ThreadState> _threadStates = new();
|
private static readonly Dictionary<ulong, ThreadState> _threadStates = new();
|
||||||
@@ -31,6 +32,7 @@ public static class KernelPthreadExtendedCompatExports
|
|||||||
private static int _nextTlsKey = 1;
|
private static int _nextTlsKey = 1;
|
||||||
private static long _nextSyntheticRwlockHandleId = 1;
|
private static long _nextSyntheticRwlockHandleId = 1;
|
||||||
private static long _nextSyntheticPthreadAttrHandleId = 1;
|
private static long _nextSyntheticPthreadAttrHandleId = 1;
|
||||||
|
private static long _nextSyntheticRwlockAttrHandleId = 1;
|
||||||
|
|
||||||
private static readonly ConcurrentDictionary<ulong, ConcurrentDictionary<int, ulong>> _threadLocalSpecific = new();
|
private static readonly ConcurrentDictionary<ulong, ConcurrentDictionary<int, ulong>> _threadLocalSpecific = new();
|
||||||
|
|
||||||
@@ -839,6 +841,37 @@ public static class KernelPthreadExtendedCompatExports
|
|||||||
return PthreadAttrSetstacksize(ctx);
|
return PthreadAttrSetstacksize(ctx);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[SysAbiExport(
|
||||||
|
Nid = "Bvn74vj6oLo",
|
||||||
|
ExportName = "scePthreadAttrSetstack",
|
||||||
|
Target = Generation.Gen4 | Generation.Gen5,
|
||||||
|
LibraryName = "libKernel")]
|
||||||
|
public static int PthreadAttrSetstack(CpuContext ctx)
|
||||||
|
{
|
||||||
|
var attrAddress = ctx[CpuRegister.Rdi];
|
||||||
|
var stackAddress = ctx[CpuRegister.Rsi];
|
||||||
|
var stackSize = ctx[CpuRegister.Rdx];
|
||||||
|
if (attrAddress == 0 || stackAddress == 0 || stackSize == 0)
|
||||||
|
{
|
||||||
|
return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT;
|
||||||
|
}
|
||||||
|
|
||||||
|
var resolvedAddress = ResolvePthreadAttrHandle(ctx, attrAddress);
|
||||||
|
lock (_stateGate)
|
||||||
|
{
|
||||||
|
var state = GetOrCreateAttrStateLocked(resolvedAddress);
|
||||||
|
var updated = state with { StackAddress = stackAddress, StackSize = stackSize };
|
||||||
|
_attrStates[resolvedAddress] = updated;
|
||||||
|
if (resolvedAddress != attrAddress)
|
||||||
|
{
|
||||||
|
_attrStates[attrAddress] = updated;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx[CpuRegister.Rax] = 0;
|
||||||
|
return (int)OrbisGen2Result.ORBIS_GEN2_OK;
|
||||||
|
}
|
||||||
|
|
||||||
[SysAbiExport(
|
[SysAbiExport(
|
||||||
Nid = "6ULAa0fq4jA",
|
Nid = "6ULAa0fq4jA",
|
||||||
ExportName = "scePthreadRwlockInit",
|
ExportName = "scePthreadRwlockInit",
|
||||||
@@ -1016,6 +1049,47 @@ public static class KernelPthreadExtendedCompatExports
|
|||||||
LibraryName = "libKernel")]
|
LibraryName = "libKernel")]
|
||||||
public static int PosixPthreadRwlockUnlock(CpuContext ctx) => PthreadRwlockUnlock(ctx);
|
public static int PosixPthreadRwlockUnlock(CpuContext ctx) => PthreadRwlockUnlock(ctx);
|
||||||
|
|
||||||
|
[SysAbiExport(
|
||||||
|
Nid = "yOfGg-I1ZII",
|
||||||
|
ExportName = "scePthreadRwlockattrInit",
|
||||||
|
Target = Generation.Gen4 | Generation.Gen5,
|
||||||
|
LibraryName = "libKernel")]
|
||||||
|
public static int PthreadRwlockattrInit(CpuContext ctx)
|
||||||
|
{
|
||||||
|
var attrAddress = ctx[CpuRegister.Rdi];
|
||||||
|
if (attrAddress == 0)
|
||||||
|
{
|
||||||
|
return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT;
|
||||||
|
}
|
||||||
|
|
||||||
|
var syntheticHandle = AllocateSyntheticHandle(SyntheticRwlockAttrHandleBase, ref _nextSyntheticRwlockAttrHandleId);
|
||||||
|
if (!KernelMemoryCompatExports.TryWriteUInt64Compat(ctx, attrAddress, syntheticHandle))
|
||||||
|
{
|
||||||
|
return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT;
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx[CpuRegister.Rax] = 0;
|
||||||
|
return (int)OrbisGen2Result.ORBIS_GEN2_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
[SysAbiExport(
|
||||||
|
Nid = "i2ifZ3fS2fo",
|
||||||
|
ExportName = "scePthreadRwlockattrDestroy",
|
||||||
|
Target = Generation.Gen4 | Generation.Gen5,
|
||||||
|
LibraryName = "libKernel")]
|
||||||
|
public static int PthreadRwlockattrDestroy(CpuContext ctx)
|
||||||
|
{
|
||||||
|
var attrAddress = ctx[CpuRegister.Rdi];
|
||||||
|
if (attrAddress == 0)
|
||||||
|
{
|
||||||
|
return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT;
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = KernelMemoryCompatExports.TryWriteUInt64Compat(ctx, attrAddress, 0);
|
||||||
|
ctx[CpuRegister.Rax] = 0;
|
||||||
|
return (int)OrbisGen2Result.ORBIS_GEN2_OK;
|
||||||
|
}
|
||||||
|
|
||||||
[SysAbiExport(
|
[SysAbiExport(
|
||||||
Nid = "mqULNdimTn0",
|
Nid = "mqULNdimTn0",
|
||||||
ExportName = "pthread_key_create",
|
ExportName = "pthread_key_create",
|
||||||
@@ -1045,7 +1119,7 @@ public static class KernelPthreadExtendedCompatExports
|
|||||||
return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT;
|
return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT;
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx[CpuRegister.Rax] = unchecked((uint)key);
|
ctx[CpuRegister.Rax] = 0;
|
||||||
return (int)OrbisGen2Result.ORBIS_GEN2_OK;
|
return (int)OrbisGen2Result.ORBIS_GEN2_OK;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ using System.Buffers.Binary;
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Reflection;
|
|
||||||
using System.Runtime.InteropServices;
|
using System.Runtime.InteropServices;
|
||||||
using System.Runtime.Intrinsics.X86;
|
using System.Runtime.Intrinsics.X86;
|
||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
@@ -87,11 +86,11 @@ public static class KernelRuntimeCompatExports
|
|||||||
|
|
||||||
if (micros < 1000)
|
if (micros < 1000)
|
||||||
{
|
{
|
||||||
// Guest worker pools use usleep(1) as a polling backoff. Periodically
|
// Guest worker pools use usleep(1) as a polling backoff. Do not turn
|
||||||
// relinquish a full host time slice so spin workers cannot starve producers.
|
// PS microsecond waits into Windows millisecond sleeps on hot paths.
|
||||||
if ((++_shortUsleepCount & 31) == 0)
|
if ((++_shortUsleepCount & 255) == 0)
|
||||||
{
|
{
|
||||||
Thread.Sleep(1);
|
Thread.Sleep(0);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
@@ -739,8 +738,11 @@ public static class KernelRuntimeCompatExports
|
|||||||
return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND;
|
return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND;
|
||||||
}
|
}
|
||||||
|
|
||||||
Console.Error.WriteLine(
|
if (ShouldTraceVirtualMemory())
|
||||||
$"[LOADER][TRACE] reserve_virtual_range: req=0x{requestedAddress:X16} desired=0x{desiredAddress:X16} mapped=0x{mappedAddress:X16} len=0x{length:X16} flags=0x{flags:X8} align=0x{effectiveAlignment:X16}");
|
{
|
||||||
|
Console.Error.WriteLine(
|
||||||
|
$"[LOADER][TRACE] reserve_virtual_range: req=0x{requestedAddress:X16} desired=0x{desiredAddress:X16} mapped=0x{mappedAddress:X16} len=0x{length:X16} flags=0x{flags:X8} align=0x{effectiveAlignment:X16}");
|
||||||
|
}
|
||||||
|
|
||||||
if (!ctx.TryWriteUInt64(inOutAddressPointer, mappedAddress))
|
if (!ctx.TryWriteUInt64(inOutAddressPointer, mappedAddress))
|
||||||
{
|
{
|
||||||
@@ -1733,117 +1735,16 @@ public static class KernelRuntimeCompatExports
|
|||||||
bool allowSearch,
|
bool allowSearch,
|
||||||
out ulong mappedAddress)
|
out ulong mappedAddress)
|
||||||
{
|
{
|
||||||
mappedAddress = 0;
|
return KernelVirtualRangeAllocator.TryReserve(
|
||||||
if (length == 0)
|
ctx,
|
||||||
{
|
desiredAddress,
|
||||||
return false;
|
length,
|
||||||
}
|
executable: false,
|
||||||
|
alignment,
|
||||||
try
|
allowSearch,
|
||||||
{
|
allowAllocateAtAlternative: allowSearch,
|
||||||
object memoryObject = ctx.Memory;
|
"reserve_virtual_range",
|
||||||
MethodInfo? allocateAt = null;
|
out mappedAddress);
|
||||||
MethodInfo? allocateAtOrAbove = null;
|
|
||||||
var allocateAtHasAllowAlternativeArg = false;
|
|
||||||
for (var depth = 0; depth < 4; depth++)
|
|
||||||
{
|
|
||||||
foreach (var candidate in memoryObject.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance))
|
|
||||||
{
|
|
||||||
var parameters = candidate.GetParameters();
|
|
||||||
if (string.Equals(candidate.Name, "TryAllocateAtOrAbove", StringComparison.Ordinal) &&
|
|
||||||
parameters.Length == 5 &&
|
|
||||||
parameters[0].ParameterType == typeof(ulong) &&
|
|
||||||
parameters[1].ParameterType == typeof(ulong) &&
|
|
||||||
parameters[2].ParameterType == typeof(bool) &&
|
|
||||||
parameters[3].ParameterType == typeof(ulong) &&
|
|
||||||
parameters[4].ParameterType == typeof(ulong).MakeByRefType())
|
|
||||||
{
|
|
||||||
allocateAtOrAbove = candidate;
|
|
||||||
}
|
|
||||||
else if (string.Equals(candidate.Name, "AllocateAt", StringComparison.Ordinal))
|
|
||||||
{
|
|
||||||
if (parameters.Length == 3 &&
|
|
||||||
parameters[0].ParameterType == typeof(ulong) &&
|
|
||||||
parameters[1].ParameterType == typeof(ulong) &&
|
|
||||||
parameters[2].ParameterType == typeof(bool))
|
|
||||||
{
|
|
||||||
allocateAt = candidate;
|
|
||||||
allocateAtHasAllowAlternativeArg = false;
|
|
||||||
}
|
|
||||||
else if (parameters.Length == 4 &&
|
|
||||||
parameters[0].ParameterType == typeof(ulong) &&
|
|
||||||
parameters[1].ParameterType == typeof(ulong) &&
|
|
||||||
parameters[2].ParameterType == typeof(bool) &&
|
|
||||||
parameters[3].ParameterType == typeof(bool))
|
|
||||||
{
|
|
||||||
allocateAt = candidate;
|
|
||||||
allocateAtHasAllowAlternativeArg = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (allocateAtOrAbove is not null && allocateAt is not null)
|
|
||||||
{
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (allocateAtOrAbove is not null || allocateAt is not null)
|
|
||||||
{
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
var innerProperty = memoryObject.GetType().GetProperty("Inner", BindingFlags.Public | BindingFlags.Instance);
|
|
||||||
if (innerProperty is null)
|
|
||||||
{
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
var innerValue = innerProperty.GetValue(memoryObject);
|
|
||||||
if (innerValue is null || ReferenceEquals(innerValue, memoryObject))
|
|
||||||
{
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
memoryObject = innerValue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (allowSearch && allocateAtOrAbove is not null)
|
|
||||||
{
|
|
||||||
var searchArgs = new object[] { desiredAddress, length, false, alignment, 0UL };
|
|
||||||
var searchResult = allocateAtOrAbove.Invoke(memoryObject, searchArgs);
|
|
||||||
if (searchResult is bool trueValue && trueValue &&
|
|
||||||
searchArgs[4] is ulong searchedAddress && searchedAddress != 0)
|
|
||||||
{
|
|
||||||
mappedAddress = searchedAddress;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (allocateAt is null)
|
|
||||||
{
|
|
||||||
Console.Error.WriteLine($"[LOADER][TRACE] reserve_virtual_range: AllocateAt missing on {ctx.Memory.GetType().FullName}");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
var invokeArgs = allocateAtHasAllowAlternativeArg
|
|
||||||
? new object[] { desiredAddress, length, false, allowSearch }
|
|
||||||
: new object[] { desiredAddress, length, false };
|
|
||||||
var result = allocateAt.Invoke(memoryObject, invokeArgs);
|
|
||||||
if (result is not ulong allocated || allocated == 0)
|
|
||||||
{
|
|
||||||
var resultType = result?.GetType().FullName ?? "null";
|
|
||||||
Console.Error.WriteLine($"[LOADER][TRACE] reserve_virtual_range: AllocateAt returned {resultType} value={result ?? "null"}");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
mappedAddress = allocated;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
catch
|
|
||||||
{
|
|
||||||
Console.Error.WriteLine("[LOADER][TRACE] reserve_virtual_range: AllocateAt invocation threw");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static ulong AlignUp(ulong value, ulong alignment)
|
private static ulong AlignUp(ulong value, ulong alignment)
|
||||||
@@ -1856,4 +1757,9 @@ public static class KernelRuntimeCompatExports
|
|||||||
var mask = alignment - 1;
|
var mask = alignment - 1;
|
||||||
return (value + mask) & ~mask;
|
return (value + mask) & ~mask;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static bool ShouldTraceVirtualMemory()
|
||||||
|
{
|
||||||
|
return string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_LOG_VIRTUAL_MEMORY"), "1", StringComparison.Ordinal);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,159 @@
|
|||||||
|
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||||
|
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||||
|
|
||||||
|
using SharpEmu.HLE;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Concurrent;
|
||||||
|
using System.Reflection;
|
||||||
|
|
||||||
|
namespace SharpEmu.Libs.Kernel;
|
||||||
|
|
||||||
|
internal static class KernelVirtualRangeAllocator
|
||||||
|
{
|
||||||
|
private static readonly ConcurrentDictionary<Type, Accessor> _accessors = new();
|
||||||
|
|
||||||
|
public static bool TryReserve(
|
||||||
|
CpuContext ctx,
|
||||||
|
ulong desiredAddress,
|
||||||
|
ulong length,
|
||||||
|
bool executable,
|
||||||
|
ulong alignment,
|
||||||
|
bool allowSearch,
|
||||||
|
bool allowAllocateAtAlternative,
|
||||||
|
string traceName,
|
||||||
|
out ulong mappedAddress)
|
||||||
|
{
|
||||||
|
mappedAddress = 0;
|
||||||
|
if (length == 0)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!TryResolveAccessor(ctx.Memory, out var target, out var accessor))
|
||||||
|
{
|
||||||
|
Console.Error.WriteLine($"[LOADER][TRACE] {traceName}: AllocateAt missing on {ctx.Memory.GetType().FullName}");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (allowSearch && accessor.AllocateAtOrAbove is not null)
|
||||||
|
{
|
||||||
|
var searchArgs = new object[] { desiredAddress, length, executable, alignment, 0UL };
|
||||||
|
var searchResult = accessor.AllocateAtOrAbove.Invoke(target, searchArgs);
|
||||||
|
if (searchResult is bool trueValue && trueValue &&
|
||||||
|
searchArgs[4] is ulong searchedAddress && searchedAddress != 0)
|
||||||
|
{
|
||||||
|
mappedAddress = searchedAddress;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (accessor.AllocateAt is null)
|
||||||
|
{
|
||||||
|
Console.Error.WriteLine($"[LOADER][TRACE] {traceName}: AllocateAt missing on {target.GetType().FullName}");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var invokeArgs = accessor.AllocateAtHasAllowAlternativeArg
|
||||||
|
? new object[] { desiredAddress, length, executable, allowAllocateAtAlternative }
|
||||||
|
: new object[] { desiredAddress, length, executable };
|
||||||
|
var result = accessor.AllocateAt.Invoke(target, invokeArgs);
|
||||||
|
if (result is not ulong allocated || allocated == 0)
|
||||||
|
{
|
||||||
|
var resultType = result?.GetType().FullName ?? "null";
|
||||||
|
Console.Error.WriteLine($"[LOADER][TRACE] {traceName}: AllocateAt returned {resultType} value={result ?? "null"}");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
mappedAddress = allocated;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
Console.Error.WriteLine($"[LOADER][TRACE] {traceName}: AllocateAt invocation threw");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryResolveAccessor(object rootMemory, out object target, out Accessor accessor)
|
||||||
|
{
|
||||||
|
target = rootMemory;
|
||||||
|
accessor = default;
|
||||||
|
|
||||||
|
for (var depth = 0; depth < 4; depth++)
|
||||||
|
{
|
||||||
|
accessor = _accessors.GetOrAdd(target.GetType(), DiscoverAccessor);
|
||||||
|
if (accessor.AllocateAt is not null || accessor.AllocateAtOrAbove is not null)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (accessor.InnerProperty is null)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
var innerValue = accessor.InnerProperty.GetValue(target);
|
||||||
|
if (innerValue is null || ReferenceEquals(innerValue, target))
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
target = innerValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Accessor DiscoverAccessor(Type type)
|
||||||
|
{
|
||||||
|
MethodInfo? allocateAt = null;
|
||||||
|
MethodInfo? allocateAtOrAbove = null;
|
||||||
|
var allocateAtHasAllowAlternativeArg = false;
|
||||||
|
|
||||||
|
foreach (var candidate in type.GetMethods(BindingFlags.Public | BindingFlags.Instance))
|
||||||
|
{
|
||||||
|
var parameters = candidate.GetParameters();
|
||||||
|
if (string.Equals(candidate.Name, "TryAllocateAtOrAbove", StringComparison.Ordinal) &&
|
||||||
|
parameters.Length == 5 &&
|
||||||
|
parameters[0].ParameterType == typeof(ulong) &&
|
||||||
|
parameters[1].ParameterType == typeof(ulong) &&
|
||||||
|
parameters[2].ParameterType == typeof(bool) &&
|
||||||
|
parameters[3].ParameterType == typeof(ulong) &&
|
||||||
|
parameters[4].ParameterType == typeof(ulong).MakeByRefType())
|
||||||
|
{
|
||||||
|
allocateAtOrAbove = candidate;
|
||||||
|
}
|
||||||
|
else if (string.Equals(candidate.Name, "AllocateAt", StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
if (parameters.Length == 3 &&
|
||||||
|
parameters[0].ParameterType == typeof(ulong) &&
|
||||||
|
parameters[1].ParameterType == typeof(ulong) &&
|
||||||
|
parameters[2].ParameterType == typeof(bool))
|
||||||
|
{
|
||||||
|
allocateAt = candidate;
|
||||||
|
allocateAtHasAllowAlternativeArg = false;
|
||||||
|
}
|
||||||
|
else if (parameters.Length == 4 &&
|
||||||
|
parameters[0].ParameterType == typeof(ulong) &&
|
||||||
|
parameters[1].ParameterType == typeof(ulong) &&
|
||||||
|
parameters[2].ParameterType == typeof(bool) &&
|
||||||
|
parameters[3].ParameterType == typeof(bool))
|
||||||
|
{
|
||||||
|
allocateAt = candidate;
|
||||||
|
allocateAtHasAllowAlternativeArg = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var innerProperty = type.GetProperty("Inner", BindingFlags.Public | BindingFlags.Instance);
|
||||||
|
return new Accessor(allocateAt, allocateAtOrAbove, allocateAtHasAllowAlternativeArg, innerProperty);
|
||||||
|
}
|
||||||
|
|
||||||
|
private readonly record struct Accessor(
|
||||||
|
MethodInfo? AllocateAt,
|
||||||
|
MethodInfo? AllocateAtOrAbove,
|
||||||
|
bool AllocateAtHasAllowAlternativeArg,
|
||||||
|
PropertyInfo? InnerProperty);
|
||||||
|
}
|
||||||
@@ -879,6 +879,8 @@ internal static unsafe class VulkanVideoPresenter
|
|||||||
private bool _swapchainRecreateDeferred;
|
private bool _swapchainRecreateDeferred;
|
||||||
private bool _tracedPresentedSwapchain;
|
private bool _tracedPresentedSwapchain;
|
||||||
private bool _swapchainReadbackPending;
|
private bool _swapchainReadbackPending;
|
||||||
|
private bool _deviceLost;
|
||||||
|
private bool _deviceLostLogged;
|
||||||
private int _directPresentationCount;
|
private int _directPresentationCount;
|
||||||
private readonly Dictionary<ulong, GuestImageResource> _guestImages = new();
|
private readonly Dictionary<ulong, GuestImageResource> _guestImages = new();
|
||||||
private readonly HashSet<(ulong Address, uint Width, uint Height, Format Format)> _tracedTextureCacheHits = new();
|
private readonly HashSet<(ulong Address, uint Width, uint Height, Format Format)> _tracedTextureCacheHits = new();
|
||||||
@@ -2816,7 +2818,8 @@ internal static unsafe class VulkanVideoPresenter
|
|||||||
dstSelect: texture.DstSelect,
|
dstSelect: texture.DstSelect,
|
||||||
out var view))
|
out var view))
|
||||||
{
|
{
|
||||||
if (_tracedTextureCacheHits.Add(
|
if (ShouldTraceVulkanResources() &&
|
||||||
|
_tracedTextureCacheHits.Add(
|
||||||
(texture.Address, texture.Width, texture.Height, vkFormat)))
|
(texture.Address, texture.Width, texture.Height, vkFormat)))
|
||||||
{
|
{
|
||||||
Console.Error.WriteLine(
|
Console.Error.WriteLine(
|
||||||
@@ -3395,7 +3398,8 @@ internal static unsafe class VulkanVideoPresenter
|
|||||||
out var memory);
|
out var memory);
|
||||||
var size = (ulong)Math.Max(guestBuffer.Data.Length, sizeof(uint));
|
var size = (ulong)Math.Max(guestBuffer.Data.Length, sizeof(uint));
|
||||||
|
|
||||||
if (_tracedGlobalBuffers.Add((guestBuffer.BaseAddress, guestBuffer.Data.Length)))
|
if (ShouldTraceVulkanResources() &&
|
||||||
|
_tracedGlobalBuffers.Add((guestBuffer.BaseAddress, guestBuffer.Data.Length)))
|
||||||
{
|
{
|
||||||
Console.Error.WriteLine(
|
Console.Error.WriteLine(
|
||||||
$"[LOADER][TRACE] vk.global_buffer base=0x{guestBuffer.BaseAddress:X16} " +
|
$"[LOADER][TRACE] vk.global_buffer base=0x{guestBuffer.BaseAddress:X16} " +
|
||||||
@@ -4030,6 +4034,11 @@ internal static unsafe class VulkanVideoPresenter
|
|||||||
|
|
||||||
private void ExecuteComputeDispatch(VulkanComputeGuestDispatch work)
|
private void ExecuteComputeDispatch(VulkanComputeGuestDispatch work)
|
||||||
{
|
{
|
||||||
|
if (_deviceLost)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (AddressListContains("SHARPEMU_SKIP_COMPUTE_CS", work.ShaderAddress))
|
if (AddressListContains("SHARPEMU_SKIP_COMPUTE_CS", work.ShaderAddress))
|
||||||
{
|
{
|
||||||
TraceVulkanShader(
|
TraceVulkanShader(
|
||||||
@@ -4132,6 +4141,11 @@ internal static unsafe class VulkanVideoPresenter
|
|||||||
}
|
}
|
||||||
catch (Exception exception)
|
catch (Exception exception)
|
||||||
{
|
{
|
||||||
|
if (TryMarkDeviceLost(exception))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
Console.Error.WriteLine(
|
Console.Error.WriteLine(
|
||||||
$"[LOADER][ERROR] Vulkan compute dispatch failed " +
|
$"[LOADER][ERROR] Vulkan compute dispatch failed " +
|
||||||
$"cs=0x{work.ShaderAddress:X16}: {exception.Message}");
|
$"cs=0x{work.ShaderAddress:X16}: {exception.Message}");
|
||||||
@@ -4197,6 +4211,11 @@ internal static unsafe class VulkanVideoPresenter
|
|||||||
|
|
||||||
private void ExecuteOffscreenDraw(VulkanOffscreenGuestDraw work)
|
private void ExecuteOffscreenDraw(VulkanOffscreenGuestDraw work)
|
||||||
{
|
{
|
||||||
|
if (_deviceLost)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
var format = GetRenderTargetFormat(work.Target.Format, work.Target.NumberType);
|
var format = GetRenderTargetFormat(work.Target.Format, work.Target.NumberType);
|
||||||
if (format == Format.Undefined)
|
if (format == Format.Undefined)
|
||||||
{
|
{
|
||||||
@@ -4354,6 +4373,11 @@ internal static unsafe class VulkanVideoPresenter
|
|||||||
}
|
}
|
||||||
catch (Exception exception)
|
catch (Exception exception)
|
||||||
{
|
{
|
||||||
|
if (TryMarkDeviceLost(exception))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (!_guestImages.TryGetValue(work.Target.Address, out var failedTarget) ||
|
if (!_guestImages.TryGetValue(work.Target.Address, out var failedTarget) ||
|
||||||
!failedTarget.Initialized)
|
!failedTarget.Initialized)
|
||||||
{
|
{
|
||||||
@@ -4809,7 +4833,10 @@ internal static unsafe class VulkanVideoPresenter
|
|||||||
}
|
}
|
||||||
|
|
||||||
_commandBuffer = _presentationCommandBuffer;
|
_commandBuffer = _presentationCommandBuffer;
|
||||||
CollectCompletedGuestSubmissions(waitForOldest: false);
|
if (!_deviceLost)
|
||||||
|
{
|
||||||
|
CollectCompletedGuestSubmissions(waitForOldest: false);
|
||||||
|
}
|
||||||
|
|
||||||
var completedWork = 0;
|
var completedWork = 0;
|
||||||
while (completedWork < MaxGuestWorkPerRender &&
|
while (completedWork < MaxGuestWorkPerRender &&
|
||||||
@@ -5667,6 +5694,12 @@ internal static unsafe class VulkanVideoPresenter
|
|||||||
string.Equals(mode, "present", StringComparison.OrdinalIgnoreCase);
|
string.Equals(mode, "present", StringComparison.OrdinalIgnoreCase);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static bool ShouldTraceVulkanResources() =>
|
||||||
|
string.Equals(
|
||||||
|
Environment.GetEnvironmentVariable("SHARPEMU_LOG_VK_RESOURCES"),
|
||||||
|
"1",
|
||||||
|
StringComparison.Ordinal);
|
||||||
|
|
||||||
private void RecordTranslatedGraphicsPass(
|
private void RecordTranslatedGraphicsPass(
|
||||||
TranslatedDrawResources resources,
|
TranslatedDrawResources resources,
|
||||||
RenderPass renderPass,
|
RenderPass renderPass,
|
||||||
@@ -6502,6 +6535,25 @@ internal static unsafe class VulkanVideoPresenter
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private bool TryMarkDeviceLost(Exception exception)
|
||||||
|
{
|
||||||
|
if (!exception.Message.Contains(nameof(Result.ErrorDeviceLost), StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
_deviceLost = true;
|
||||||
|
if (!_deviceLostLogged)
|
||||||
|
{
|
||||||
|
_deviceLostLogged = true;
|
||||||
|
Console.Error.WriteLine(
|
||||||
|
"[LOADER][ERROR] Vulkan device lost; dropping subsequent guest GPU work. " +
|
||||||
|
exception.Message);
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
private static void TraceVulkanShader(string message)
|
private static void TraceVulkanShader(string message)
|
||||||
{
|
{
|
||||||
if (!string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_LOG_AGC"), "1", StringComparison.Ordinal) &&
|
if (!string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_LOG_AGC"), "1", StringComparison.Ordinal) &&
|
||||||
|
|||||||
Reference in New Issue
Block a user