mirror of
https://github.com/par274/sharpemu.git
synced 2026-07-25 20:28:48 +08:00
Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d1efc3061a | |||
| 53da00fa89 | |||
| b4b95014f1 | |||
| 7b91c964fc | |||
| 9bacb883f1 |
@@ -63,6 +63,11 @@ internal static partial class Program
|
||||
|
||||
private static int Run(string[] args)
|
||||
{
|
||||
if (Updater.TryApply(args, out var updateExitCode))
|
||||
{
|
||||
return updateExitCode;
|
||||
}
|
||||
|
||||
args = NormalizeInternalArguments(args, out var isMitigatedChild);
|
||||
if (args.Length == 0 && !isMitigatedChild)
|
||||
{
|
||||
|
||||
@@ -349,10 +349,8 @@ public sealed unsafe class PhysicalVirtualMemory : IVirtualMemory, IGuestMemoryA
|
||||
var requestedCursor = AlignUp(desiredAddress, effectiveAlignment);
|
||||
var cursor = GetAllocationSearchCursor(desiredAddress, requestedCursor, effectiveAlignment, executable);
|
||||
|
||||
// POSIX treats the requested address as a hint, and Rosetta may
|
||||
// relocate whole guest windows. Over-allocate once so the returned
|
||||
// host range always contains an aligned guest-visible start.
|
||||
if (!OperatingSystem.IsWindows())
|
||||
// macOS needs alignment over-allocation; Linux uses exact-address search.
|
||||
if (OperatingSystem.IsMacOS())
|
||||
{
|
||||
var reserveSize = effectiveAlignment > PageSize
|
||||
? alignedSize + effectiveAlignment
|
||||
|
||||
@@ -12,6 +12,7 @@ using SharpEmu.Libs.Kernel;
|
||||
using SharpEmu.Libs.AppContent;
|
||||
using SharpEmu.Libs.SaveData;
|
||||
using SharpEmu.Libs.Fiber;
|
||||
using SharpEmu.Libs.SystemService;
|
||||
using System.Buffers.Binary;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@@ -141,6 +142,7 @@ public sealed class SharpEmuRuntime : ISharpEmuRuntime
|
||||
var image = LoadImage(normalizedEbootPath);
|
||||
VideoOutExports.ConfigureApplicationInfo(image.Title, image.TitleId, image.Version);
|
||||
SaveDataExports.ConfigureApplicationInfo(image.TitleId);
|
||||
SystemServiceExports.ConfigureApplicationInfo(image.TitleId);
|
||||
_ = RegisterLoadedModule(normalizedEbootPath, image, isMain: true, isSystemModule: false);
|
||||
KernelRuntimeCompatExports.ConfigureProcessProcParamAddress(image.ProcParamAddress);
|
||||
Console.Error.WriteLine($"[RUNTIME] Entry: 0x{image.EntryPoint:X16}");
|
||||
|
||||
@@ -48,6 +48,8 @@ public sealed class GuiSettings
|
||||
/// <summary>Publish launcher/game status to Discord Rich Presence.</summary>
|
||||
public bool DiscordRichPresence { get; set; } = true;
|
||||
|
||||
public bool CheckForUpdatesOnStartup { get; set; } = true;
|
||||
|
||||
/// <summary>Names of SHARPEMU_* switches set to "1" in the emulator's environment at launch.</summary>
|
||||
public List<string> EnvironmentToggles { get; set; } = new();
|
||||
|
||||
|
||||
@@ -31,9 +31,11 @@
|
||||
"Options.Env.Desc": "Switches passed to the emulator as environment variables at launch.",
|
||||
"Options.Env.Bthid.Desc": "Report Bluetooth HID as unavailable for titles whose wheel/FFB middleware polls forever.\nLeave off normally. Some titles freeze when init fails.",
|
||||
"Options.Env.LoopGuard.Desc": "Do not force quit titles that repeat the same call for too long.\nTry this when a game exits on its own while loading.",
|
||||
"Options.Env.WritableApp0.Desc": "Allow titles to create and write files inside their install folder.\nNeeded by unpackaged dumps that write their save or config data under /app0.",
|
||||
"Options.Env.VkValidation.Desc": "Enable Vulkan validation layers for GPU debugging.\nSlow. Requires the Vulkan SDK to be installed.",
|
||||
"Options.Env.DumpSpirv.Desc": "Dump AGC shaders and their SPIR-V translations to the shader-dumps folder.\nUse when reporting shader or rendering bugs.",
|
||||
"Options.Env.LogDirectMemory.Desc": "Log direct memory allocations and failures to the console.\nUse when a game aborts or exits during boot.",
|
||||
"Options.Env.LogIo.Desc": "Log file open, read, and path-resolve activity to the console.\nUse when a game cannot find its data files during boot.",
|
||||
"Options.Env.LogNp.Desc": "Log NP (PlayStation Network) library calls to the console.",
|
||||
"Options.Section.Emulation": "EMULATION",
|
||||
"Options.Section.Logging": "LOGGING",
|
||||
@@ -142,5 +144,20 @@
|
||||
"About.Discord.Label": "Discord",
|
||||
"About.Discord.Desc": "Join the community, get support and follow development.",
|
||||
"About.GithubButton": "Contribute in GitHub!",
|
||||
"About.DiscordButton": "Join our Discord!"
|
||||
"About.DiscordButton": "Join our Discord!",
|
||||
|
||||
"Updater.Auto.Label": "Check for updates on startup",
|
||||
"Updater.Auto.Desc": "Checks GitHub without delaying startup.",
|
||||
"Updater.Label": "Updates",
|
||||
"Updater.Check": "Check for updates",
|
||||
"Updater.DownloadRestart": "Download and restart",
|
||||
"Updater.Status.Ready": "Current build: {0}",
|
||||
"Updater.Status.Checking": "Checking for updates…",
|
||||
"Updater.Status.Current": "You are up to date ({0}).",
|
||||
"Updater.Status.Available": "A new build is available: {0}",
|
||||
"Updater.Status.Downloading": "Downloading update… {0}%",
|
||||
"Updater.Status.Installing": "Installing update…",
|
||||
"Updater.Status.Timeout": "Update check timed out after 10 seconds.",
|
||||
"Updater.Status.Failed": "Could not check for updates.",
|
||||
"Updater.Status.Unsupported": "Automatic updating requires a Windows, Linux or macOS x64 build."
|
||||
}
|
||||
|
||||
@@ -125,5 +125,20 @@
|
||||
"Dialog.PsExecutables": "PS çalıştırılabilirleri",
|
||||
"Dialog.SaveLogFile": "Günlük dosyasının kaydedileceği yeri seçin",
|
||||
"Dialog.PlainTextFiles": "Düz Metin Dosyaları",
|
||||
"Dialog.LogFiles": "Günlük Dosyaları"
|
||||
"Dialog.LogFiles": "Günlük Dosyaları",
|
||||
|
||||
"Updater.Auto.Label": "Açılışta güncellemeleri denetle",
|
||||
"Updater.Auto.Desc": "Açılışı geciktirmeden GitHub'ı denetler.",
|
||||
"Updater.Label": "Güncellemeler",
|
||||
"Updater.Check": "Güncellemeleri denetle",
|
||||
"Updater.DownloadRestart": "İndir ve yeniden başlat",
|
||||
"Updater.Status.Ready": "Mevcut build: {0}",
|
||||
"Updater.Status.Checking": "Güncellemeler denetleniyor…",
|
||||
"Updater.Status.Current": "Güncelsiniz ({0}).",
|
||||
"Updater.Status.Available": "Yeni build mevcut: {0}",
|
||||
"Updater.Status.Downloading": "Güncelleme indiriliyor… %{0}",
|
||||
"Updater.Status.Installing": "Güncelleme kuruluyor…",
|
||||
"Updater.Status.Timeout": "Güncelleme denetimi 10 saniye sonra zaman aşımına uğradı.",
|
||||
"Updater.Status.Failed": "Güncellemeler denetlenemedi.",
|
||||
"Updater.Status.Unsupported": "Otomatik güncelleme Windows, Linux veya macOS x64 build'i gerektirir."
|
||||
}
|
||||
|
||||
@@ -315,6 +315,16 @@ SPDX-License-Identifier: GPL-2.0-or-later
|
||||
<ToggleSwitch Grid.Column="1" x:Name="DiscordToggle" OnContent="On" OffContent="Off"
|
||||
VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<StackPanel VerticalAlignment="Center" Spacing="2" Margin="0,0,16,0">
|
||||
<TextBlock x:Name="AutoUpdateLabel" Text="Check for updates on startup" FontSize="13" />
|
||||
<TextBlock x:Name="AutoUpdateDesc" Text="Checks GitHub without delaying startup."
|
||||
FontSize="11" Foreground="{StaticResource MutedBrush}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<ToggleSwitch Grid.Column="1" x:Name="AutoUpdateToggle" OnContent="On" OffContent="Off"
|
||||
IsChecked="True" VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
<Border Classes="card">
|
||||
@@ -322,6 +332,16 @@ SPDX-License-Identifier: GPL-2.0-or-later
|
||||
<TextBlock x:Name="AboutSectionTitle"
|
||||
Classes="sectionTitle"
|
||||
Text="ABOUT" />
|
||||
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<StackPanel Grid.Column="0" Spacing="2" VerticalAlignment="Center">
|
||||
<TextBlock x:Name="UpdateLabel" Text="Updates" FontSize="13" />
|
||||
<TextBlock x:Name="UpdateStatusText" Text="Current build: dev" FontSize="11"
|
||||
Foreground="{StaticResource MutedBrush}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<Button Grid.Column="1" x:Name="UpdateButton" Classes="ghost"
|
||||
Content="Check for updates" VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
|
||||
<!--Github-->
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
@@ -420,6 +440,17 @@ SPDX-License-Identifier: GPL-2.0-or-later
|
||||
VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<StackPanel VerticalAlignment="Center" Spacing="2" Margin="0,0,16,0">
|
||||
<TextBlock Text="SHARPEMU_WRITABLE_APP0" FontSize="13" FontFamily="Consolas,monospace" />
|
||||
<TextBlock x:Name="EnvWritableApp0Desc"
|
||||
Text="Allow titles to create and write files inside their install folder. Needed by unpackaged dumps that write their save or config data under /app0."
|
||||
FontSize="11" Foreground="{StaticResource MutedBrush}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<ToggleSwitch Grid.Column="1" x:Name="EnvWritableApp0Toggle" OnContent="On" OffContent="Off"
|
||||
VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<StackPanel VerticalAlignment="Center" Spacing="2" Margin="0,0,16,0">
|
||||
<TextBlock Text="SHARPEMU_VK_VALIDATION" FontSize="13" FontFamily="Consolas,monospace" />
|
||||
@@ -453,6 +484,17 @@ SPDX-License-Identifier: GPL-2.0-or-later
|
||||
VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<StackPanel VerticalAlignment="Center" Spacing="2" Margin="0,0,16,0">
|
||||
<TextBlock Text="SHARPEMU_LOG_IO" FontSize="13" FontFamily="Consolas,monospace" />
|
||||
<TextBlock x:Name="EnvLogIoDesc"
|
||||
Text="Log file open, read, and path-resolve activity to the console. Use when a game cannot find its data files during boot."
|
||||
FontSize="11" Foreground="{StaticResource MutedBrush}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<ToggleSwitch Grid.Column="1" x:Name="EnvLogIoToggle" OnContent="On" OffContent="Off"
|
||||
VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<StackPanel VerticalAlignment="Center" Spacing="2" Margin="0,0,16,0">
|
||||
<TextBlock Text="SHARPEMU_LOG_NP" FontSize="13" FontFamily="Consolas,monospace" />
|
||||
|
||||
@@ -57,6 +57,9 @@ public partial class MainWindow : Window
|
||||
private bool _isRunning;
|
||||
private int _autoScrollTicks;
|
||||
private int _activePageIndex;
|
||||
private Updater.UpdateInfo? _availableUpdate;
|
||||
private string _updateStatusKey = "Updater.Status.Ready";
|
||||
private object?[] _updateStatusArgs = [BuildInfo.CommitSha ?? "dev"];
|
||||
|
||||
// Discord Rich Presence state.
|
||||
private readonly long _launcherStartUnixSeconds = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
||||
@@ -131,17 +134,24 @@ public partial class MainWindow : Window
|
||||
_settings.DiscordRichPresence = DiscordToggle.IsChecked == true;
|
||||
UpdateDiscordPresence();
|
||||
};
|
||||
AutoUpdateToggle.IsCheckedChanged += (_, _) =>
|
||||
_settings.CheckForUpdatesOnStartup = AutoUpdateToggle.IsChecked == true;
|
||||
UpdateButton.Click += async (_, _) => await OnUpdateButtonAsync();
|
||||
SelectLogFilePathButton.Click += async (_, _) => await SelectLogFilePathAsync();
|
||||
EnvBthidToggle.IsCheckedChanged += (_, _) =>
|
||||
SetEnvironmentToggle("SHARPEMU_BTHID_UNAVAILABLE", EnvBthidToggle.IsChecked == true);
|
||||
EnvLoopGuardToggle.IsCheckedChanged += (_, _) =>
|
||||
SetEnvironmentToggle("SHARPEMU_DISABLE_IMPORT_LOOP_GUARD", EnvLoopGuardToggle.IsChecked == true);
|
||||
EnvWritableApp0Toggle.IsCheckedChanged += (_, _) =>
|
||||
SetEnvironmentToggle("SHARPEMU_WRITABLE_APP0", EnvWritableApp0Toggle.IsChecked == true);
|
||||
EnvVkValidationToggle.IsCheckedChanged += (_, _) =>
|
||||
SetEnvironmentToggle("SHARPEMU_VK_VALIDATION", EnvVkValidationToggle.IsChecked == true);
|
||||
EnvDumpSpirvToggle.IsCheckedChanged += (_, _) =>
|
||||
SetEnvironmentToggle("SHARPEMU_DUMP_SPIRV", EnvDumpSpirvToggle.IsChecked == true);
|
||||
EnvLogDirectMemoryToggle.IsCheckedChanged += (_, _) =>
|
||||
SetEnvironmentToggle("SHARPEMU_LOG_DIRECT_MEMORY", EnvLogDirectMemoryToggle.IsChecked == true);
|
||||
EnvLogIoToggle.IsCheckedChanged += (_, _) =>
|
||||
SetEnvironmentToggle("SHARPEMU_LOG_IO", EnvLogIoToggle.IsChecked == true);
|
||||
EnvLogNpToggle.IsCheckedChanged += (_, _) =>
|
||||
SetEnvironmentToggle("SHARPEMU_LOG_NP", EnvLogNpToggle.IsChecked == true);
|
||||
LanguageBox.SelectionChanged += (_, _) => OnLanguageChanged();
|
||||
@@ -371,6 +381,10 @@ public partial class MainWindow : Window
|
||||
ApplySettingsToControls();
|
||||
LocateEmulator();
|
||||
UpdateDiscordPresence();
|
||||
if (_settings.CheckForUpdatesOnStartup)
|
||||
{
|
||||
_ = CheckForUpdatesAsync();
|
||||
}
|
||||
await RescanLibraryAsync();
|
||||
}
|
||||
|
||||
@@ -427,9 +441,11 @@ public partial class MainWindow : Window
|
||||
EnvDesc.Text = loc.Get("Options.Env.Desc");
|
||||
EnvBthidDesc.Text = loc.Get("Options.Env.Bthid.Desc");
|
||||
EnvLoopGuardDesc.Text = loc.Get("Options.Env.LoopGuard.Desc");
|
||||
EnvWritableApp0Desc.Text = loc.Get("Options.Env.WritableApp0.Desc");
|
||||
EnvVkValidationDesc.Text = loc.Get("Options.Env.VkValidation.Desc");
|
||||
EnvDumpSpirvDesc.Text = loc.Get("Options.Env.DumpSpirv.Desc");
|
||||
EnvLogDirectMemoryDesc.Text = loc.Get("Options.Env.LogDirectMemory.Desc");
|
||||
EnvLogIoDesc.Text = loc.Get("Options.Env.LogIo.Desc");
|
||||
EnvLogNpDesc.Text = loc.Get("Options.Env.LogNp.Desc");
|
||||
EmulationSectionTitle.Text = loc.Get("Options.Section.Emulation");
|
||||
LoggingSectionTitle.Text = loc.Get("Options.Section.Logging");
|
||||
@@ -472,8 +488,10 @@ public partial class MainWindow : Window
|
||||
|
||||
DiscordLabel.Text = loc.Get("Options.Discord.Label");
|
||||
DiscordDesc.Text = loc.Get("Options.Discord.Desc");
|
||||
AutoUpdateLabel.Text = loc.Get("Updater.Auto.Label");
|
||||
AutoUpdateDesc.Text = loc.Get("Updater.Auto.Desc");
|
||||
|
||||
foreach (var toggle in new[] { StrictToggle, LogToFileToggle, OverrideLogFileToggle, TitleMusicToggle, DiscordToggle })
|
||||
foreach (var toggle in new[] { StrictToggle, LogToFileToggle, OverrideLogFileToggle, TitleMusicToggle, DiscordToggle, AutoUpdateToggle })
|
||||
{
|
||||
toggle.OnContent = loc.Get("Common.On");
|
||||
toggle.OffContent = loc.Get("Common.Off");
|
||||
@@ -497,6 +515,8 @@ public partial class MainWindow : Window
|
||||
DiscordServerDesc.Text = loc.Get("About.Discord.Desc");
|
||||
GithubButton.Content = loc.Get("About.GithubButton");
|
||||
DiscordButton.Content = loc.Get("About.DiscordButton");
|
||||
UpdateLabel.Text = loc.Get("Updater.Label");
|
||||
RefreshUpdateText();
|
||||
|
||||
UpdateEmptyStateTexts();
|
||||
UpdateSelectedGameTexts();
|
||||
@@ -612,15 +632,87 @@ public partial class MainWindow : Window
|
||||
OverrideLogFileToggle.IsChecked = _settings.OverrideLogFile;
|
||||
TitleMusicToggle.IsChecked = _settings.PlayTitleMusic;
|
||||
DiscordToggle.IsChecked = _settings.DiscordRichPresence;
|
||||
AutoUpdateToggle.IsChecked = _settings.CheckForUpdatesOnStartup;
|
||||
EnvBthidToggle.IsChecked = _settings.EnvironmentToggles.Contains("SHARPEMU_BTHID_UNAVAILABLE");
|
||||
EnvLoopGuardToggle.IsChecked = _settings.EnvironmentToggles.Contains("SHARPEMU_DISABLE_IMPORT_LOOP_GUARD");
|
||||
EnvWritableApp0Toggle.IsChecked = _settings.EnvironmentToggles.Contains("SHARPEMU_WRITABLE_APP0");
|
||||
EnvVkValidationToggle.IsChecked = _settings.EnvironmentToggles.Contains("SHARPEMU_VK_VALIDATION");
|
||||
EnvDumpSpirvToggle.IsChecked = _settings.EnvironmentToggles.Contains("SHARPEMU_DUMP_SPIRV");
|
||||
EnvLogDirectMemoryToggle.IsChecked = _settings.EnvironmentToggles.Contains("SHARPEMU_LOG_DIRECT_MEMORY");
|
||||
EnvLogIoToggle.IsChecked = _settings.EnvironmentToggles.Contains("SHARPEMU_LOG_IO");
|
||||
EnvLogNpToggle.IsChecked = _settings.EnvironmentToggles.Contains("SHARPEMU_LOG_NP");
|
||||
UpdateLogFilePathText();
|
||||
}
|
||||
|
||||
private async Task OnUpdateButtonAsync()
|
||||
{
|
||||
if (_availableUpdate is null)
|
||||
{
|
||||
await CheckForUpdatesAsync();
|
||||
return;
|
||||
}
|
||||
|
||||
UpdateButton.IsEnabled = false;
|
||||
try
|
||||
{
|
||||
var progress = new Progress<int>(value =>
|
||||
SetUpdateStatus("Updater.Status.Downloading", value));
|
||||
await Updater.DownloadAndRestartAsync(_availableUpdate, progress);
|
||||
SetUpdateStatus("Updater.Status.Installing");
|
||||
Close();
|
||||
}
|
||||
catch
|
||||
{
|
||||
SetUpdateStatus("Updater.Status.Failed");
|
||||
UpdateButton.IsEnabled = true;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CheckForUpdatesAsync()
|
||||
{
|
||||
_availableUpdate = null;
|
||||
UpdateButton.IsEnabled = false;
|
||||
SetUpdateStatus("Updater.Status.Checking");
|
||||
try
|
||||
{
|
||||
_availableUpdate = await Updater.CheckAsync(BuildInfo.CommitSha);
|
||||
SetUpdateStatus(
|
||||
_availableUpdate is null ? "Updater.Status.Current" : "Updater.Status.Available",
|
||||
_availableUpdate?.Sha ?? BuildInfo.CommitSha ?? "dev");
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
SetUpdateStatus("Updater.Status.Timeout");
|
||||
}
|
||||
catch (PlatformNotSupportedException)
|
||||
{
|
||||
SetUpdateStatus("Updater.Status.Unsupported");
|
||||
}
|
||||
catch
|
||||
{
|
||||
SetUpdateStatus("Updater.Status.Failed");
|
||||
}
|
||||
finally
|
||||
{
|
||||
UpdateButton.IsEnabled = true;
|
||||
RefreshUpdateText();
|
||||
}
|
||||
}
|
||||
|
||||
private void SetUpdateStatus(string key, params object?[] args)
|
||||
{
|
||||
_updateStatusKey = key;
|
||||
_updateStatusArgs = args;
|
||||
RefreshUpdateText();
|
||||
}
|
||||
|
||||
private void RefreshUpdateText()
|
||||
{
|
||||
UpdateStatusText.Text = Localization.Instance.Format(_updateStatusKey, _updateStatusArgs);
|
||||
UpdateButton.Content = Localization.Instance.Get(
|
||||
_availableUpdate is null ? "Updater.Check" : "Updater.DownloadRestart");
|
||||
}
|
||||
|
||||
// Environment variables set on this process at the previous launch; children
|
||||
// inherit the process environment, so stale names must be cleared explicitly.
|
||||
private readonly HashSet<string> _appliedEnvironmentVariables = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using System.Diagnostics;
|
||||
using System.Formats.Tar;
|
||||
using System.IO.Compression;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace SharpEmu.GUI;
|
||||
|
||||
/// <summary>Self-contained Windows updater; the emulator layers do not depend on it.</summary>
|
||||
public static class Updater
|
||||
{
|
||||
private const string ApplyArgument = "--sharpemu-apply-update";
|
||||
private const string LatestReleaseUrl = "https://api.github.com/repos/sharpemu/sharpemu/releases/latest";
|
||||
private static readonly TimeSpan CheckTimeout = TimeSpan.FromSeconds(10);
|
||||
private static readonly HttpClient Http = CreateHttpClient();
|
||||
|
||||
public sealed record UpdateInfo(string Sha, string Name, string DownloadUrl, long Size);
|
||||
|
||||
public static async Task<UpdateInfo?> CheckAsync(string? currentSha, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var platform = CurrentPlatform();
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
timeout.CancelAfter(CheckTimeout);
|
||||
|
||||
using var response = await Http.GetAsync(LatestReleaseUrl, timeout.Token);
|
||||
response.EnsureSuccessStatusCode();
|
||||
return ParseRelease(
|
||||
await response.Content.ReadAsStringAsync(timeout.Token),
|
||||
currentSha,
|
||||
platform.Rid,
|
||||
platform.Extension);
|
||||
}
|
||||
|
||||
public static async Task DownloadAndRestartAsync(
|
||||
UpdateInfo update,
|
||||
IProgress<int>? progress = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var root = Path.Combine(Path.GetTempPath(), "SharpEmu.Update");
|
||||
var payload = Path.Combine(root, "payload");
|
||||
if (Directory.Exists(root))
|
||||
{
|
||||
Directory.Delete(root, recursive: true);
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(root);
|
||||
var archive = Path.Combine(root, update.Name);
|
||||
using (var response = await Http.GetAsync(update.DownloadUrl, HttpCompletionOption.ResponseHeadersRead, cancellationToken))
|
||||
{
|
||||
response.EnsureSuccessStatusCode();
|
||||
await using var input = await response.Content.ReadAsStreamAsync(cancellationToken);
|
||||
await using var output = File.Create(archive);
|
||||
var buffer = new byte[81920];
|
||||
long written = 0;
|
||||
int read;
|
||||
while ((read = await input.ReadAsync(buffer, cancellationToken)) > 0)
|
||||
{
|
||||
await output.WriteAsync(buffer.AsMemory(0, read), cancellationToken);
|
||||
written += read;
|
||||
progress?.Report(update.Size == 0 ? 0 : (int)(written * 100 / update.Size));
|
||||
}
|
||||
|
||||
if (written != update.Size)
|
||||
{
|
||||
throw new InvalidDataException($"Downloaded {written} bytes; expected {update.Size}.");
|
||||
}
|
||||
}
|
||||
|
||||
var platform = CurrentPlatform();
|
||||
var stagedExe = ExtractArchive(archive, payload, platform.Extension, platform.ExecutableName);
|
||||
|
||||
var start = new ProcessStartInfo(stagedExe)
|
||||
{
|
||||
UseShellExecute = false,
|
||||
WorkingDirectory = payload,
|
||||
};
|
||||
start.ArgumentList.Add(ApplyArgument);
|
||||
start.ArgumentList.Add(Environment.ProcessId.ToString());
|
||||
start.ArgumentList.Add(AppContext.BaseDirectory);
|
||||
using var helper = Process.Start(start)
|
||||
?? throw new InvalidOperationException("The update installer could not be started.");
|
||||
}
|
||||
|
||||
/// <summary>Runs from the downloaded executable after the old GUI exits.</summary>
|
||||
public static bool TryApply(string[] args, out int exitCode)
|
||||
{
|
||||
exitCode = 0;
|
||||
if (args.Length != 3 || args[0] != ApplyArgument)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (int.TryParse(args[1], out var oldPid))
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Process.GetProcessById(oldPid).WaitForExit(30_000))
|
||||
{
|
||||
throw new TimeoutException("SharpEmu did not close within 30 seconds.");
|
||||
}
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
// The old process has already exited.
|
||||
}
|
||||
}
|
||||
|
||||
var source = AppContext.BaseDirectory;
|
||||
var target = Path.GetFullPath(args[2]);
|
||||
foreach (var file in Directory.EnumerateFiles(source, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
var relative = Path.GetRelativePath(source, file);
|
||||
if (relative.Equals("gui-settings.json", StringComparison.OrdinalIgnoreCase) ||
|
||||
relative.StartsWith("user" + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) ||
|
||||
relative.StartsWith("logs" + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) ||
|
||||
relative.StartsWith("Languages" + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var destination = Path.Combine(target, relative);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(destination)!);
|
||||
File.Copy(file, destination, overwrite: true);
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
File.SetUnixFileMode(destination, File.GetUnixFileMode(file));
|
||||
}
|
||||
}
|
||||
|
||||
using var restarted = Process.Start(new ProcessStartInfo(
|
||||
Path.Combine(target, CurrentPlatform().ExecutableName))
|
||||
{
|
||||
UseShellExecute = false,
|
||||
WorkingDirectory = target,
|
||||
}) ?? throw new InvalidOperationException("The updated SharpEmu could not be started.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
exitCode = 1;
|
||||
try
|
||||
{
|
||||
File.WriteAllText(Path.Combine(args[2], "update-error.log"), ex.ToString());
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Best-effort diagnostics only.
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static UpdateInfo? ParseRelease(
|
||||
string json,
|
||||
string? currentSha,
|
||||
string rid,
|
||||
string extension)
|
||||
{
|
||||
using var document = JsonDocument.Parse(json);
|
||||
var candidates = new List<(DateTimeOffset Created, UpdateInfo Update)>();
|
||||
foreach (var asset in document.RootElement.GetProperty("assets").EnumerateArray())
|
||||
{
|
||||
var name = asset.GetProperty("name").GetString() ?? "";
|
||||
var marker = $"-{rid}-";
|
||||
var markerIndex = name.LastIndexOf(marker, StringComparison.OrdinalIgnoreCase);
|
||||
if (!name.EndsWith(extension, StringComparison.OrdinalIgnoreCase) ||
|
||||
markerIndex < 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var sha = name[(markerIndex + marker.Length)..^extension.Length];
|
||||
if (sha.Length < 7 || !sha.All(Uri.IsHexDigit))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
candidates.Add((
|
||||
asset.GetProperty("created_at").GetDateTimeOffset(),
|
||||
new UpdateInfo(
|
||||
sha,
|
||||
name,
|
||||
asset.GetProperty("browser_download_url").GetString()!,
|
||||
asset.GetProperty("size").GetInt64())));
|
||||
}
|
||||
|
||||
var latest = candidates.OrderByDescending(candidate => candidate.Created).FirstOrDefault().Update;
|
||||
return latest is null || string.Equals(latest.Sha, currentSha, StringComparison.OrdinalIgnoreCase)
|
||||
? null
|
||||
: latest;
|
||||
}
|
||||
|
||||
private static string ExtractArchive(
|
||||
string archive,
|
||||
string payload,
|
||||
string extension,
|
||||
string executableName)
|
||||
{
|
||||
if (extension == ".zip")
|
||||
{
|
||||
ZipFile.ExtractToDirectory(archive, payload);
|
||||
}
|
||||
else
|
||||
{
|
||||
Directory.CreateDirectory(payload);
|
||||
using var compressed = File.OpenRead(archive);
|
||||
using var gzip = new GZipStream(compressed, CompressionMode.Decompress);
|
||||
TarFile.ExtractToDirectory(gzip, payload, overwriteFiles: false);
|
||||
}
|
||||
|
||||
var executable = Path.Combine(payload, executableName);
|
||||
if (!File.Exists(executable))
|
||||
{
|
||||
throw new InvalidDataException($"The update archive does not contain {executableName}.");
|
||||
}
|
||||
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
File.SetUnixFileMode(executable, File.GetUnixFileMode(executable) | UnixFileMode.UserExecute);
|
||||
}
|
||||
|
||||
return executable;
|
||||
}
|
||||
|
||||
private static HttpClient CreateHttpClient()
|
||||
{
|
||||
var client = new HttpClient { Timeout = Timeout.InfiniteTimeSpan };
|
||||
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("SharpEmu", "0.0.1"));
|
||||
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github+json"));
|
||||
return client;
|
||||
}
|
||||
|
||||
private static PlatformInfo CurrentPlatform()
|
||||
{
|
||||
if (RuntimeInformation.ProcessArchitecture != Architecture.X64)
|
||||
{
|
||||
throw new PlatformNotSupportedException("SharpEmu releases require an x64 process.");
|
||||
}
|
||||
|
||||
if (OperatingSystem.IsWindows()) return new("win-x64", ".zip", "SharpEmu.exe");
|
||||
if (OperatingSystem.IsLinux()) return new("linux-x64", ".tar.gz", "SharpEmu");
|
||||
if (OperatingSystem.IsMacOS()) return new("osx-x64", ".tar.gz", "SharpEmu");
|
||||
throw new PlatformNotSupportedException();
|
||||
}
|
||||
|
||||
private sealed record PlatformInfo(string Rid, string Extension, string ExecutableName);
|
||||
}
|
||||
@@ -1574,7 +1574,27 @@ public static partial class KernelMemoryCompatExports
|
||||
ExportName = "stat",
|
||||
Target = Generation.Gen4 | Generation.Gen5,
|
||||
LibraryName = "libc")]
|
||||
public static int PosixStat(CpuContext ctx) => KernelStat(ctx);
|
||||
public static int PosixStat(CpuContext ctx)
|
||||
{
|
||||
var result = KernelStat(ctx);
|
||||
if (result == (int)OrbisGen2Result.ORBIS_GEN2_OK)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
// stat(2) follows the libc/POSIX ABI: failures return -1 and expose
|
||||
// the reason through errno. Returning the raw Orbis kernel code here
|
||||
// makes callers treat a missing file as a non-negative success value.
|
||||
var errno = result switch
|
||||
{
|
||||
(int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT => Einval,
|
||||
(int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT => Efault,
|
||||
_ => 2, // ENOENT
|
||||
};
|
||||
KernelRuntimeCompatExports.TrySetErrno(ctx, errno);
|
||||
ctx[CpuRegister.Rax] = ulong.MaxValue;
|
||||
return -1;
|
||||
}
|
||||
|
||||
[SysAbiExport(
|
||||
Nid = "gEpBkcwxUjw",
|
||||
@@ -4013,7 +4033,7 @@ public static partial class KernelMemoryCompatExports
|
||||
_ => unchecked((int)argumentSource.NextGpArg())
|
||||
};
|
||||
|
||||
var formatted = value.ToString();
|
||||
var formatted = value.ToString(CultureInfo.InvariantCulture);
|
||||
if (showSign && value >= 0)
|
||||
formatted = "+" + formatted;
|
||||
else if (spaceForSign && value >= 0)
|
||||
@@ -4033,7 +4053,7 @@ public static partial class KernelMemoryCompatExports
|
||||
_ => (uint)argumentSource.NextGpArg()
|
||||
};
|
||||
|
||||
var formatted = value.ToString();
|
||||
var formatted = value.ToString(CultureInfo.InvariantCulture);
|
||||
sb.Append(PadString(formatted, width, leftAlign, padWithZero && !leftAlign));
|
||||
}
|
||||
break;
|
||||
@@ -4050,8 +4070,8 @@ public static partial class KernelMemoryCompatExports
|
||||
};
|
||||
|
||||
var formatted = specifier == 'x'
|
||||
? value.ToString("x")
|
||||
: value.ToString("X");
|
||||
? value.ToString("x", CultureInfo.InvariantCulture)
|
||||
: value.ToString("X", CultureInfo.InvariantCulture);
|
||||
|
||||
if (alternateForm && value != 0)
|
||||
formatted = specifier == 'x' ? "0x" + formatted : "0X" + formatted;
|
||||
@@ -4155,7 +4175,10 @@ public static partial class KernelMemoryCompatExports
|
||||
var formatStr = precision >= 0
|
||||
? $"{{0:{specifier}{precision}}}"
|
||||
: $"{{0:{specifier}}}";
|
||||
var formatted = string.Format(formatStr, value);
|
||||
var formatted = string.Format(
|
||||
CultureInfo.InvariantCulture,
|
||||
formatStr,
|
||||
value);
|
||||
|
||||
if (showSign && value >= 0)
|
||||
formatted = "+" + formatted;
|
||||
@@ -4219,31 +4242,50 @@ public static partial class KernelMemoryCompatExports
|
||||
{
|
||||
private readonly CpuContext _ctx;
|
||||
private int _gpIndex;
|
||||
private int _fpIndex;
|
||||
private int _stackIndex;
|
||||
|
||||
public RegisterPrintfArgumentSource(CpuContext ctx, int gpIndex)
|
||||
{
|
||||
_ctx = ctx;
|
||||
_gpIndex = gpIndex;
|
||||
_fpIndex = 0;
|
||||
_stackIndex = 0;
|
||||
}
|
||||
|
||||
public ulong NextGpArg()
|
||||
{
|
||||
var index = _gpIndex++;
|
||||
return index switch
|
||||
var index = _gpIndex;
|
||||
if (index < 6)
|
||||
{
|
||||
0 => _ctx[CpuRegister.Rdi],
|
||||
1 => _ctx[CpuRegister.Rsi],
|
||||
2 => _ctx[CpuRegister.Rdx],
|
||||
3 => _ctx[CpuRegister.Rcx],
|
||||
4 => _ctx[CpuRegister.R8],
|
||||
5 => _ctx[CpuRegister.R9],
|
||||
_ => ReadStackArg(_ctx, (ulong)(index - 6) * 8)
|
||||
};
|
||||
_gpIndex++;
|
||||
return index switch
|
||||
{
|
||||
0 => _ctx[CpuRegister.Rdi],
|
||||
1 => _ctx[CpuRegister.Rsi],
|
||||
2 => _ctx[CpuRegister.Rdx],
|
||||
3 => _ctx[CpuRegister.Rcx],
|
||||
4 => _ctx[CpuRegister.R8],
|
||||
_ => _ctx[CpuRegister.R9],
|
||||
};
|
||||
}
|
||||
|
||||
return ReadStackArg(_ctx, (ulong)(_stackIndex++) * 8);
|
||||
}
|
||||
|
||||
public double NextFloatArg()
|
||||
{
|
||||
return BitConverter.Int64BitsToDouble(unchecked((long)NextGpArg()));
|
||||
ulong bits;
|
||||
if (_fpIndex < 8)
|
||||
{
|
||||
_ctx.GetXmmRegister(_fpIndex++, out bits, out _);
|
||||
}
|
||||
else
|
||||
{
|
||||
bits = ReadStackArg(_ctx, (ulong)(_stackIndex++) * 8);
|
||||
}
|
||||
|
||||
return BitConverter.Int64BitsToDouble(unchecked((long)bits));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4806,8 +4848,19 @@ public static partial class KernelMemoryCompatExports
|
||||
private static bool IsMutatingOpen(int flags) =>
|
||||
(flags & (O_WRONLY | O_RDWR | O_CREAT | O_TRUNC | O_APPEND)) != 0;
|
||||
|
||||
// Dev-build dumps (unpackaged UE titles, etc.) may write their Saved/ tree under
|
||||
// /app0, which is read-only on retail hardware. Opt in via SHARPEMU_WRITABLE_APP0=1
|
||||
// to allow those writes so such dumps can boot; defaults off to keep retail semantics.
|
||||
private static readonly bool _writableApp0 =
|
||||
string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_WRITABLE_APP0"), "1", StringComparison.Ordinal);
|
||||
|
||||
public static bool IsReadOnlyGuestMutationPath(string guestPath)
|
||||
{
|
||||
if (_writableApp0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var normalized = NormalizeGuestStatCachePath(guestPath);
|
||||
return normalized is not null &&
|
||||
(string.Equals(normalized, "/app0", StringComparison.OrdinalIgnoreCase) ||
|
||||
|
||||
@@ -43,6 +43,19 @@ public static class NpWebApi2Exports
|
||||
return ctx.SetReturn(0);
|
||||
}
|
||||
|
||||
[SysAbiExport(
|
||||
Nid = "sk54bi6FtYM",
|
||||
ExportName = "sceNpWebApi2CreateUserContext",
|
||||
Target = Generation.Gen4 | Generation.Gen5,
|
||||
LibraryName = "libSceNpWebApi2")]
|
||||
public static int NpWebApi2CreateUserContext(CpuContext ctx)
|
||||
{
|
||||
// No PSN backend: refuse user-context creation so the title's online
|
||||
// layer backs off instead of driving a half-created context handle.
|
||||
TraceNpWebApi2("create-user-context", unchecked((int)ctx[CpuRegister.Rdi]), ctx[CpuRegister.Rsi]);
|
||||
return ctx.SetReturn(NpWebApi2ErrorInvalidArgument);
|
||||
}
|
||||
|
||||
[SysAbiExport(
|
||||
Nid = "bEvXpcEk200",
|
||||
ExportName = "sceNpWebApi2Terminate",
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using SharpEmu.HLE;
|
||||
|
||||
namespace SharpEmu.Libs.Pad;
|
||||
@@ -16,6 +18,19 @@ public static class BluetoothHidExports
|
||||
"1",
|
||||
StringComparison.Ordinal);
|
||||
|
||||
// EXPERIMENT: fire the registered callback once with a zeroed event struct.
|
||||
// Direct execution shares the host address space with the guest, so an
|
||||
// AllocHGlobal buffer is directly readable by guest code.
|
||||
// SHARPEMU_BTHID_FIRE_CALLBACK=1 enables; SHARPEMU_BTHID_EVENT_CODE and
|
||||
// SHARPEMU_BTHID_EVENT_SIZE (default 0 / 256) shape the synthetic event.
|
||||
private static readonly bool _fireCallback = string.Equals(
|
||||
Environment.GetEnvironmentVariable("SHARPEMU_BTHID_FIRE_CALLBACK"),
|
||||
"1",
|
||||
StringComparison.Ordinal);
|
||||
|
||||
private static ulong _callbackFunction;
|
||||
private static int _fired;
|
||||
|
||||
private static int Result(CpuContext ctx) =>
|
||||
ctx.SetReturn(_reportUnavailable ? BluetoothHidUnavailable : 0);
|
||||
|
||||
@@ -31,12 +46,101 @@ public static class BluetoothHidExports
|
||||
ExportName = "sceBluetoothHidRegisterDevice",
|
||||
Target = Generation.Gen4 | Generation.Gen5,
|
||||
LibraryName = "libSceBluetoothHid")]
|
||||
public static int BluetoothHidRegisterDevice(CpuContext ctx) => Result(ctx);
|
||||
public static int BluetoothHidRegisterDevice(CpuContext ctx)
|
||||
{
|
||||
var result = Result(ctx);
|
||||
if (_fireCallback && _callbackFunction >= 0x10000 &&
|
||||
Interlocked.Exchange(ref _fired, 1) == 0)
|
||||
{
|
||||
FireEnumerationComplete(ctx);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
[SysAbiExport(
|
||||
Nid = "4Ypfo9RIwfM",
|
||||
ExportName = "sceBluetoothHidRegisterCallback",
|
||||
Target = Generation.Gen4 | Generation.Gen5,
|
||||
LibraryName = "libSceBluetoothHid")]
|
||||
public static int BluetoothHidRegisterCallback(CpuContext ctx) => Result(ctx);
|
||||
public static int BluetoothHidRegisterCallback(CpuContext ctx)
|
||||
{
|
||||
_callbackFunction = ctx[CpuRegister.Rdi];
|
||||
|
||||
// EXPERIMENT: failing ONLY the callback registration (with a generic kernel
|
||||
// error, unlike the BT-specific unavailable code) may make wheel/FFB
|
||||
// middleware disable its Bluetooth search loop instead of polling forever.
|
||||
// SHARPEMU_BTHID_CB_FAIL=nf -> NOT_FOUND, =ni -> NOT_IMPLEMENTED.
|
||||
var mode = Environment.GetEnvironmentVariable("SHARPEMU_BTHID_CB_FAIL");
|
||||
if (string.Equals(mode, "nf", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ctx.SetReturn((int)OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND);
|
||||
}
|
||||
|
||||
if (string.Equals(mode, "ni", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ctx.SetReturn((int)OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_IMPLEMENTED);
|
||||
}
|
||||
|
||||
return Result(ctx);
|
||||
}
|
||||
|
||||
private static void FireEnumerationComplete(CpuContext ctx)
|
||||
{
|
||||
var scheduler = GuestThreadExecution.Scheduler;
|
||||
if (scheduler is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var eventCode = ParseEnvUInt64("SHARPEMU_BTHID_EVENT_CODE", 0);
|
||||
var eventSize = (int)ParseEnvUInt64("SHARPEMU_BTHID_EVENT_SIZE", 256);
|
||||
if (eventSize < 1)
|
||||
{
|
||||
eventSize = 256;
|
||||
}
|
||||
|
||||
// Leaked by design: the guest may retain the pointer past the callback.
|
||||
var eventStruct = Marshal.AllocHGlobal(eventSize);
|
||||
for (var offset = 0; offset < eventSize; offset++)
|
||||
{
|
||||
Marshal.WriteByte(eventStruct, offset, 0);
|
||||
}
|
||||
|
||||
Console.Error.WriteLine(
|
||||
$"[BTHID][EXPERIMENT] firing callback=0x{_callbackFunction:X} code={eventCode} size={eventSize} struct=0x{eventStruct.ToInt64():X}");
|
||||
if (!scheduler.TryCallGuestFunction(
|
||||
ctx,
|
||||
_callbackFunction,
|
||||
unchecked((ulong)eventStruct.ToInt64()),
|
||||
eventCode,
|
||||
0,
|
||||
0,
|
||||
"sceBluetoothHid synthetic enumeration event",
|
||||
out var error))
|
||||
{
|
||||
Console.Error.WriteLine($"[BTHID][EXPERIMENT] callback failed: {error}");
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.Error.WriteLine("[BTHID][EXPERIMENT] callback returned OK");
|
||||
}
|
||||
}
|
||||
|
||||
private static ulong ParseEnvUInt64(string name, ulong fallback)
|
||||
{
|
||||
var value = Environment.GetEnvironmentVariable(name);
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
{
|
||||
return fallback;
|
||||
}
|
||||
|
||||
value = value.Trim();
|
||||
var hex = value.StartsWith("0x", StringComparison.OrdinalIgnoreCase);
|
||||
return ulong.TryParse(
|
||||
hex ? value[2..] : value,
|
||||
hex ? System.Globalization.NumberStyles.HexNumber : System.Globalization.NumberStyles.Integer,
|
||||
null,
|
||||
out var parsed) ? parsed : fallback;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,6 +23,11 @@ public static class PadExports
|
||||
private const int PrimaryPadHandle = 1;
|
||||
private const int ControllerInformationSize = 0x1C;
|
||||
private const int PadDataSize = 0x78;
|
||||
|
||||
// Real firmware hands out small non-negative handles; 0 is valid. Some titles
|
||||
// (Monster Truck Championship) read pad state with handle 0, and rejecting it
|
||||
// leaves their controller/FFB init path polling a never-valid state forever.
|
||||
private static bool IsPrimaryPadHandle(int handle) => handle is 0 or PrimaryPadHandle;
|
||||
private static readonly long InputSampleIntervalTicks = Math.Max(1, Stopwatch.Frequency / 1000);
|
||||
|
||||
[ThreadStatic]
|
||||
@@ -104,7 +109,7 @@ public static class PadExports
|
||||
public static int PadClose(CpuContext ctx)
|
||||
{
|
||||
var handle = unchecked((int)ctx[CpuRegister.Rdi]);
|
||||
return handle == PrimaryPadHandle
|
||||
return IsPrimaryPadHandle(handle)
|
||||
? ctx.SetReturn(0)
|
||||
: ctx.SetReturn(OrbisPadErrorInvalidHandle);
|
||||
}
|
||||
@@ -117,7 +122,7 @@ public static class PadExports
|
||||
public static int PadSetMotionSensorState(CpuContext ctx)
|
||||
{
|
||||
var handle = unchecked((int)ctx[CpuRegister.Rdi]);
|
||||
return handle == PrimaryPadHandle
|
||||
return IsPrimaryPadHandle(handle)
|
||||
? ctx.SetReturn(0)
|
||||
: ctx.SetReturn(OrbisPadErrorInvalidHandle);
|
||||
}
|
||||
@@ -131,7 +136,7 @@ public static class PadExports
|
||||
{
|
||||
var handle = unchecked((int)ctx[CpuRegister.Rdi]);
|
||||
var informationAddress = ctx[CpuRegister.Rsi];
|
||||
if (handle != PrimaryPadHandle)
|
||||
if (!IsPrimaryPadHandle(handle))
|
||||
{
|
||||
return ctx.SetReturn(OrbisPadErrorInvalidHandle);
|
||||
}
|
||||
@@ -166,7 +171,7 @@ public static class PadExports
|
||||
{
|
||||
var handle = unchecked((int)ctx[CpuRegister.Rdi]);
|
||||
var informationAddress = ctx[CpuRegister.Rsi];
|
||||
if (handle != PrimaryPadHandle)
|
||||
if (!IsPrimaryPadHandle(handle))
|
||||
{
|
||||
return ctx.SetReturn(OrbisPadErrorInvalidHandle);
|
||||
}
|
||||
@@ -207,7 +212,7 @@ public static class PadExports
|
||||
{
|
||||
var handle = unchecked((int)ctx[CpuRegister.Rdi]);
|
||||
var dataAddress = ctx[CpuRegister.Rsi];
|
||||
if (handle != PrimaryPadHandle)
|
||||
if (!IsPrimaryPadHandle(handle))
|
||||
{
|
||||
return ctx.SetReturn(OrbisPadErrorInvalidHandle);
|
||||
}
|
||||
@@ -232,7 +237,7 @@ public static class PadExports
|
||||
var handle = unchecked((int)ctx[CpuRegister.Rdi]);
|
||||
var dataAddress = ctx[CpuRegister.Rsi];
|
||||
var count = unchecked((int)ctx[CpuRegister.Rdx]);
|
||||
if (handle != PrimaryPadHandle)
|
||||
if (!IsPrimaryPadHandle(handle))
|
||||
{
|
||||
return ctx.SetReturn(OrbisPadErrorInvalidHandle);
|
||||
}
|
||||
@@ -266,7 +271,7 @@ public static class PadExports
|
||||
{
|
||||
var handle = unchecked((int)ctx[CpuRegister.Rdi]);
|
||||
var parameterAddress = ctx[CpuRegister.Rsi];
|
||||
if (handle != PrimaryPadHandle)
|
||||
if (!IsPrimaryPadHandle(handle))
|
||||
{
|
||||
return ctx.SetReturn(OrbisPadErrorInvalidHandle);
|
||||
}
|
||||
@@ -310,7 +315,7 @@ public static class PadExports
|
||||
{
|
||||
var handle = unchecked((int)ctx[CpuRegister.Rdi]);
|
||||
var parameterAddress = ctx[CpuRegister.Rsi];
|
||||
if (handle != PrimaryPadHandle)
|
||||
if (!IsPrimaryPadHandle(handle))
|
||||
{
|
||||
return ctx.SetReturn(OrbisPadErrorInvalidHandle);
|
||||
}
|
||||
@@ -340,7 +345,7 @@ public static class PadExports
|
||||
{
|
||||
var handle = unchecked((int)ctx[CpuRegister.Rdi]);
|
||||
var parameterAddress = ctx[CpuRegister.Rsi];
|
||||
if (handle != PrimaryPadHandle)
|
||||
if (!IsPrimaryPadHandle(handle))
|
||||
{
|
||||
return ctx.SetReturn(OrbisPadErrorInvalidHandle);
|
||||
}
|
||||
@@ -369,7 +374,7 @@ public static class PadExports
|
||||
public static int PadResetLightBar(CpuContext ctx)
|
||||
{
|
||||
var handle = unchecked((int)ctx[CpuRegister.Rdi]);
|
||||
if (handle != PrimaryPadHandle)
|
||||
if (!IsPrimaryPadHandle(handle))
|
||||
{
|
||||
return ctx.SetReturn(OrbisPadErrorInvalidHandle);
|
||||
}
|
||||
|
||||
@@ -418,12 +418,18 @@ public static class PlayGoExports
|
||||
$"[LOADER][TRACE] playgo.unknown_chunk_id id={chunkId} entries={numberOfEntries} " +
|
||||
$"known=[{string.Join(',', knownChunkIds)}]");
|
||||
}
|
||||
|
||||
// Real firmware rejects chunk ids outside the package's chunk set.
|
||||
// Titles rely on this as an enumeration terminator: Monster Truck
|
||||
// scans ids 0,1,2,... until BAD_CHUNK_ID, and answering OK for every
|
||||
// id makes that scan wrap the ushort range and spin forever.
|
||||
return OrbisPlayGoErrorBadChunkId;
|
||||
}
|
||||
|
||||
loci[i] = PlayGoLocusLocalFast;
|
||||
}
|
||||
|
||||
TracePlayGoLocus(numberOfEntries, chunkIds, outLoci);
|
||||
TracePlayGoLocus(ctx, numberOfEntries, chunkIds, outLoci);
|
||||
return ctx.Memory.TryWrite(outLoci, loci)
|
||||
? (int)OrbisGen2Result.ORBIS_GEN2_OK
|
||||
: (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT;
|
||||
@@ -663,7 +669,7 @@ public static class PlayGoExports
|
||||
{
|
||||
lock (_stateGate)
|
||||
{
|
||||
return _metadata.ChunkIds.Length == 0 || Array.BinarySearch(_metadata.ChunkIds, chunkId) >= 0;
|
||||
return Array.BinarySearch(_metadata.ChunkIds, chunkId) >= 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -672,7 +678,9 @@ public static class PlayGoExports
|
||||
var app0Root = Environment.GetEnvironmentVariable("SHARPEMU_APP0_DIR");
|
||||
if (string.IsNullOrWhiteSpace(app0Root))
|
||||
{
|
||||
return PlayGoMetadata.Empty;
|
||||
// No app0 override to probe for sidecar files: same fully-installed
|
||||
// single-chunk fallback as below, or scePlayGoOpen fails fatally.
|
||||
return new PlayGoMetadata(true, [(ushort)0]);
|
||||
}
|
||||
|
||||
var playGoDat = Path.Combine(app0Root, "sce_sys", "playgo-chunk.dat");
|
||||
@@ -682,12 +690,23 @@ public static class PlayGoExports
|
||||
var hasMetadata = File.Exists(playGoDat) || File.Exists(scenarioJson) || File.Exists(chunkDefsXml);
|
||||
if (!hasMetadata)
|
||||
{
|
||||
// Full installs may omit PlayGo sidecar metadata.
|
||||
TracePlayGo("metadata_missing; using fully-installed default chunk");
|
||||
// No PlayGo sidecar: report a fully-installed single chunk. Available must
|
||||
// stay true or scePlayGoOpen fails with NotSupportPlayGo (fatal PS5-component
|
||||
// init failure for UE titles); chunk 0 reports LocalFast and every other id
|
||||
// returns BAD_CHUNK_ID, terminating title-side chunk enumeration.
|
||||
TracePlayGo("metadata_missing; fully-installed single chunk");
|
||||
return new PlayGoMetadata(true, [(ushort)0]);
|
||||
}
|
||||
|
||||
var chunkIds = LoadChunkIds(chunkDefsXml);
|
||||
if (chunkIds.Length == 0)
|
||||
{
|
||||
// Unreadable/empty sidecar: fall back to chunk 0, not an empty set
|
||||
// (which IsKnownChunkId would treat as "every id valid").
|
||||
TracePlayGo("metadata_unreadable; fully-installed single chunk");
|
||||
return new PlayGoMetadata(true, [(ushort)0]);
|
||||
}
|
||||
|
||||
return new PlayGoMetadata(true, chunkIds);
|
||||
}
|
||||
|
||||
@@ -738,7 +757,7 @@ public static class PlayGoExports
|
||||
}
|
||||
}
|
||||
|
||||
private static void TracePlayGoLocus(uint entries, ulong chunkIds, ulong outLoci)
|
||||
private static void TracePlayGoLocus(CpuContext ctx, uint entries, ulong chunkIds, ulong outLoci)
|
||||
{
|
||||
if (!string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_LOG_PLAYGO"), "1", StringComparison.Ordinal))
|
||||
{
|
||||
@@ -748,8 +767,10 @@ public static class PlayGoExports
|
||||
var count = Interlocked.Increment(ref _locusTraceDiagnostics);
|
||||
if (entries != 1 || count <= 32 || count % 1000 == 0)
|
||||
{
|
||||
_ = ctx.TryReadUInt16(chunkIds, out var firstChunkId);
|
||||
Console.Error.WriteLine(
|
||||
$"[LOADER][TRACE] playgo.get_locus entries={entries} chunk_ids=0x{chunkIds:X16} out=0x{outLoci:X16}");
|
||||
$"[LOADER][TRACE] playgo.get_locus entries={entries} first_chunk={firstChunkId} " +
|
||||
$"chunk_ids=0x{chunkIds:X16} out=0x{outLoci:X16}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -241,6 +241,64 @@ public static class RtcExports
|
||||
LibraryName = "libSceRtc")]
|
||||
public static int RtcGetCurrentRawNetworkTick(CpuContext ctx) => RtcGetCurrentTick(ctx);
|
||||
|
||||
// Diagnostic: middleware busy-wait loops typically poll sceRtcGetCurrentTick, so the
|
||||
// caller's return address pinpoints the loop. SHARPEMU_RTC_PROBE_RANGE=<start>-<end>
|
||||
// (hex guest addresses) dumps 0x100 bytes of code around the first matching caller,
|
||||
// once, for offline disassembly. Costs nothing when the variable is unset.
|
||||
private static readonly ulong[]? _rtcProbeRange = ParseRtcProbeRange();
|
||||
private static int _rtcProbeDone;
|
||||
|
||||
private static ulong[]? ParseRtcProbeRange()
|
||||
{
|
||||
var value = Environment.GetEnvironmentVariable("SHARPEMU_RTC_PROBE_RANGE");
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var parts = value.Split('-', 2, StringSplitOptions.TrimEntries);
|
||||
return parts.Length == 2 &&
|
||||
TryParseHexAddress(parts[0], out var start) &&
|
||||
TryParseHexAddress(parts[1], out var end) &&
|
||||
start < end
|
||||
? [start, end]
|
||||
: null;
|
||||
}
|
||||
|
||||
private static bool TryParseHexAddress(string value, out ulong address)
|
||||
{
|
||||
if (value.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
value = value[2..];
|
||||
}
|
||||
|
||||
return ulong.TryParse(
|
||||
value,
|
||||
System.Globalization.NumberStyles.HexNumber,
|
||||
null,
|
||||
out address);
|
||||
}
|
||||
|
||||
private static void ProbeRtcCaller(CpuContext ctx)
|
||||
{
|
||||
if (Volatile.Read(ref _rtcProbeDone) != 0 ||
|
||||
!ctx.TryReadUInt64(ctx[CpuRegister.Rsp], out var ret) ||
|
||||
ret < _rtcProbeRange![0] ||
|
||||
ret >= _rtcProbeRange[1] ||
|
||||
Interlocked.CompareExchange(ref _rtcProbeDone, 1, 0) != 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var start = ret - 0x60;
|
||||
Span<byte> code = stackalloc byte[0x100];
|
||||
if (ctx.Memory.TryRead(start, code))
|
||||
{
|
||||
Console.Error.WriteLine(
|
||||
$"[LOADER][DIAG] rtc.caller_code ret=0x{ret:X} @0x{start:X}: {System.Convert.ToHexString(code)}");
|
||||
}
|
||||
}
|
||||
|
||||
[SysAbiExport(
|
||||
Nid = "18B2NS1y9UU",
|
||||
ExportName = "sceRtcGetCurrentTick",
|
||||
@@ -254,6 +312,11 @@ public static class RtcExports
|
||||
return unchecked((int)0x80B50002);
|
||||
}
|
||||
|
||||
if (_rtcProbeRange is not null)
|
||||
{
|
||||
ProbeRtcCaller(ctx);
|
||||
}
|
||||
|
||||
var tickValue = unchecked((ulong)(DateTime.UtcNow.Ticks / DateTimeTicksPerMicrosecond));
|
||||
if (!ctx.TryWriteUInt64(tickAddress, tickValue))
|
||||
{
|
||||
|
||||
@@ -15,6 +15,62 @@ public static class SystemServiceExports
|
||||
private const int DisplaySafeAreaInfoSize = sizeof(float) + 128;
|
||||
private const int HdrToneMapLuminanceSize = sizeof(float) * 3;
|
||||
|
||||
private const int TitleIdFieldSize = 0x10;
|
||||
|
||||
private static string? _mainAppTitleId;
|
||||
|
||||
public static void ConfigureApplicationInfo(string? titleId)
|
||||
{
|
||||
_mainAppTitleId = string.IsNullOrWhiteSpace(titleId) ? null : titleId.Trim();
|
||||
}
|
||||
|
||||
[SysAbiExport(
|
||||
Nid = "3RQ5aQfnstU",
|
||||
ExportName = "sceSystemServiceGetNoticeScreenSkipFlag",
|
||||
Target = Generation.Gen5,
|
||||
LibraryName = "libSceSystemService")]
|
||||
public static int SystemServiceGetNoticeScreenSkipFlag(CpuContext ctx)
|
||||
{
|
||||
var flagAddress = ctx[CpuRegister.Rdi];
|
||||
if (flagAddress == 0)
|
||||
{
|
||||
return ctx.SetReturn(OrbisSystemServiceErrorParameter);
|
||||
}
|
||||
|
||||
// No system notice screen to skip in the emulator; report "do not skip".
|
||||
Span<byte> flagBytes = stackalloc byte[sizeof(int)];
|
||||
BinaryPrimitives.WriteInt32LittleEndian(flagBytes, 0);
|
||||
return ctx.Memory.TryWrite(flagAddress, flagBytes)
|
||||
? ctx.SetReturn(0)
|
||||
: ctx.SetReturn((int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT);
|
||||
}
|
||||
|
||||
[SysAbiExport(
|
||||
Nid = "4veE0XiIugA",
|
||||
ExportName = "sceSystemServiceGetMainAppTitleId",
|
||||
Target = Generation.Gen5,
|
||||
LibraryName = "libSceSystemService")]
|
||||
public static int SystemServiceGetMainAppTitleId(CpuContext ctx)
|
||||
{
|
||||
var titleIdAddress = ctx[CpuRegister.Rdi];
|
||||
if (titleIdAddress == 0)
|
||||
{
|
||||
return ctx.SetReturn(OrbisSystemServiceErrorParameter);
|
||||
}
|
||||
|
||||
// Title IDs are a fixed 9-char format written into a 0x10-byte field;
|
||||
// bound the length so a malformed param.json cannot drive an unbounded
|
||||
// stack allocation or overrun the guest buffer.
|
||||
var titleId = _mainAppTitleId ?? "PPSA00000";
|
||||
var length = Math.Min(titleId.Length, TitleIdFieldSize - 1);
|
||||
Span<byte> titleIdBytes = stackalloc byte[TitleIdFieldSize];
|
||||
titleIdBytes.Clear();
|
||||
System.Text.Encoding.ASCII.GetBytes(titleId.AsSpan(0, length), titleIdBytes);
|
||||
return ctx.Memory.TryWrite(titleIdAddress, titleIdBytes[..(length + 1)])
|
||||
? ctx.SetReturn(0)
|
||||
: ctx.SetReturn((int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT);
|
||||
}
|
||||
|
||||
[SysAbiExport(
|
||||
Nid = "fZo48un7LK4",
|
||||
ExportName = "sceSystemServiceParamGetInt",
|
||||
|
||||
@@ -2646,6 +2646,12 @@ internal static unsafe class VulkanVideoPresenter
|
||||
}
|
||||
}
|
||||
|
||||
if (PngSplashLoader.TryLoadIcon(out var iconPixels, out var iconWidth, out var iconHeight))
|
||||
{
|
||||
var icon = new RawImage((int)iconWidth, (int)iconHeight, iconPixels);
|
||||
_window.SetWindowIcon(ref icon);
|
||||
}
|
||||
|
||||
WaitForRenderDocAttachIfRequested();
|
||||
_vk = Vk.GetApi();
|
||||
CreateInstance();
|
||||
@@ -4154,6 +4160,48 @@ internal static unsafe class VulkanVideoPresenter
|
||||
_submitTimeline;
|
||||
}
|
||||
|
||||
private void TransitionNewGuestImageToSampled(Image image, uint mipLevels)
|
||||
{
|
||||
var commandBuffer = AllocateGuestCommandBuffer();
|
||||
var beginInfo = new CommandBufferBeginInfo
|
||||
{
|
||||
SType = StructureType.CommandBufferBeginInfo,
|
||||
Flags = CommandBufferUsageFlags.OneTimeSubmitBit,
|
||||
};
|
||||
Check(
|
||||
_vk.BeginCommandBuffer(commandBuffer, &beginInfo),
|
||||
"vkBeginCommandBuffer(guest image init)");
|
||||
var barrier = new ImageMemoryBarrier
|
||||
{
|
||||
SType = StructureType.ImageMemoryBarrier,
|
||||
SrcAccessMask = 0,
|
||||
DstAccessMask = AccessFlags.ShaderReadBit,
|
||||
OldLayout = ImageLayout.Undefined,
|
||||
NewLayout = ImageLayout.ShaderReadOnlyOptimal,
|
||||
SrcQueueFamilyIndex = Vk.QueueFamilyIgnored,
|
||||
DstQueueFamilyIndex = Vk.QueueFamilyIgnored,
|
||||
Image = image,
|
||||
SubresourceRange = ColorSubresourceRange(0, mipLevels),
|
||||
};
|
||||
_vk.CmdPipelineBarrier(
|
||||
commandBuffer,
|
||||
PipelineStageFlags.TopOfPipeBit,
|
||||
PipelineStageFlags.AllCommandsBit,
|
||||
0,
|
||||
0,
|
||||
null,
|
||||
0,
|
||||
null,
|
||||
1,
|
||||
&barrier);
|
||||
Check(
|
||||
_vk.EndCommandBuffer(commandBuffer),
|
||||
"vkEndCommandBuffer(guest image init)");
|
||||
// Same-queue submission order makes the transition visible to any
|
||||
// later use of the image; no CPU-side wait is needed.
|
||||
SubmitGuestCommandBuffer(commandBuffer, [], []);
|
||||
}
|
||||
|
||||
private void EnsureGuestSubmissionCapacity()
|
||||
{
|
||||
CollectCompletedGuestSubmissions(waitForOldest: false);
|
||||
@@ -4214,23 +4262,43 @@ internal static unsafe class VulkanVideoPresenter
|
||||
return;
|
||||
}
|
||||
|
||||
Check(result, $"vkWaitForFences(guest: {oldest.DebugName})");
|
||||
if (result == Result.ErrorDeviceLost)
|
||||
{
|
||||
_deviceLost = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
Check(result, $"vkWaitForFences(guest: {oldest.DebugName})");
|
||||
}
|
||||
}
|
||||
|
||||
while (_pendingGuestSubmissions.TryPeek(out var submission))
|
||||
{
|
||||
var status = _vk.GetFenceStatus(_device, submission.Fence);
|
||||
if (status == Result.NotReady)
|
||||
if (status == Result.NotReady && !_deviceLost)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
Check(status, $"vkGetFenceStatus(guest: {submission.DebugName})");
|
||||
if (status == Result.ErrorDeviceLost)
|
||||
{
|
||||
// Pending fences never signal on a lost device; retire the
|
||||
// submission anyway so teardown and back-pressure survive.
|
||||
_deviceLost = true;
|
||||
}
|
||||
else if (status != Result.NotReady)
|
||||
{
|
||||
Check(status, $"vkGetFenceStatus(guest: {submission.DebugName})");
|
||||
}
|
||||
|
||||
_pendingGuestSubmissions.Dequeue();
|
||||
|
||||
foreach (var image in submission.TraceImages)
|
||||
if (!_deviceLost)
|
||||
{
|
||||
TraceGuestImageContents(image);
|
||||
foreach (var image in submission.TraceImages)
|
||||
{
|
||||
TraceGuestImageContents(image);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var resources in submission.Resources)
|
||||
@@ -4508,13 +4576,20 @@ internal static unsafe class VulkanVideoPresenter
|
||||
$"queue={_activeGuestQueue.Name} submission={_activeGuestQueue.SubmissionId} " +
|
||||
$"handle={work.VideoOutHandle} index={work.DisplayBufferIndex} " +
|
||||
$"capture_complete={(captured ? 1 : 0)}");
|
||||
#if DEBUG
|
||||
System.Diagnostics.Debug.Assert(
|
||||
work.Version == 0 || captured,
|
||||
"An ordered wait-safe marker must execute after its flip capture.");
|
||||
#endif
|
||||
// Demon's Souls executes wait-safe markers before their flip capture;
|
||||
// an assert here would fail-fast the process, so warn once instead.
|
||||
// Dedup on a flag, not the (per-frame-unique) version, to bound growth.
|
||||
if (work.Version != 0 && !captured && !_loggedFlipWaitOrderViolation)
|
||||
{
|
||||
_loggedFlipWaitOrderViolation = true;
|
||||
Console.Error.WriteLine(
|
||||
$"[LOADER][WARN] vk.flip_wait_order version={work.Version} " +
|
||||
"executed before its flip capture; continuing.");
|
||||
}
|
||||
}
|
||||
|
||||
private bool _loggedFlipWaitOrderViolation;
|
||||
|
||||
private GuestImageResource CreateGuestFlipSnapshot(
|
||||
GuestImageResource source,
|
||||
long version)
|
||||
@@ -8294,7 +8369,7 @@ internal static unsafe class VulkanVideoPresenter
|
||||
return (properties.OptimalTilingFeatures & FormatFeatureFlags.ColorAttachmentBit) != 0;
|
||||
}
|
||||
|
||||
private static Format GetTextureFormat(uint format, uint numberType) =>
|
||||
internal static Format GetTextureFormat(uint format, uint numberType) =>
|
||||
(format, numberType) switch
|
||||
{
|
||||
(9, _) => Format.A2B10G10R10UnormPack32,
|
||||
@@ -10164,6 +10239,9 @@ internal static unsafe class VulkanVideoPresenter
|
||||
_vk.AllocateMemory(_device, &allocationInfo, null, out var memory),
|
||||
"vkAllocateMemory(offscreen)");
|
||||
Check(_vk.BindImageMemory(_device, image, memory, 0), "vkBindImageMemory(offscreen)");
|
||||
// Rendering and uploads only define the mips they touch; define the whole
|
||||
// chain once so full-chain sampled binds never read Undefined layout.
|
||||
TransitionNewGuestImageToSampled(image, mipLevels);
|
||||
|
||||
var viewInfo = new ImageViewCreateInfo
|
||||
{
|
||||
@@ -10931,7 +11009,7 @@ internal static unsafe class VulkanVideoPresenter
|
||||
return view;
|
||||
}
|
||||
|
||||
private static bool IsCompatibleViewFormat(Format imageFormat, Format viewFormat)
|
||||
internal static bool IsCompatibleViewFormat(Format imageFormat, Format viewFormat)
|
||||
{
|
||||
if (imageFormat == viewFormat)
|
||||
{
|
||||
@@ -10997,6 +11075,23 @@ internal static unsafe class VulkanVideoPresenter
|
||||
}
|
||||
|
||||
private void Render(double _)
|
||||
{
|
||||
try
|
||||
{
|
||||
RenderCore();
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
// Device loss can strike between any two Vulkan calls in the frame;
|
||||
// keep the window loop pumping instead of tearing the presenter down.
|
||||
if (!TryMarkDeviceLost(exception))
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void RenderCore()
|
||||
{
|
||||
if (Volatile.Read(ref _presenterCloseRequested))
|
||||
{
|
||||
@@ -11010,6 +11105,18 @@ internal static unsafe class VulkanVideoPresenter
|
||||
return;
|
||||
}
|
||||
|
||||
if (_deviceLost)
|
||||
{
|
||||
// Drain queued work so producers aren't back-pressured, then
|
||||
// return without any Vulkan call (fences never signal post-loss).
|
||||
while (TryTakeGuestWork(out var lostWork))
|
||||
{
|
||||
CompleteGuestWork(lostWork);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Reuse of a frame slot waits only on that slot's fence, keeping
|
||||
// up to MaxFramesInFlight frames pipelined between CPU and GPU.
|
||||
var frameSlot = _currentFrameSlot;
|
||||
@@ -13830,20 +13937,38 @@ internal static unsafe class VulkanVideoPresenter
|
||||
return;
|
||||
}
|
||||
|
||||
if (result == Result.ErrorDeviceLost)
|
||||
{
|
||||
throw new VulkanDeviceLostException(operation);
|
||||
}
|
||||
|
||||
throw new InvalidOperationException($"{operation} failed with {result}.");
|
||||
}
|
||||
|
||||
private static void Check(Result result, string operation)
|
||||
{
|
||||
if (result == Result.ErrorDeviceLost)
|
||||
{
|
||||
throw new VulkanDeviceLostException(operation);
|
||||
}
|
||||
|
||||
if (result != Result.Success)
|
||||
{
|
||||
throw new InvalidOperationException($"{operation} failed with {result}.");
|
||||
}
|
||||
}
|
||||
|
||||
// Typed so the frame-boundary catch can recognize device loss without
|
||||
// depending on the exact wording of the exception message.
|
||||
private sealed class VulkanDeviceLostException(string operation)
|
||||
: InvalidOperationException($"{operation} failed with {Result.ErrorDeviceLost}.");
|
||||
|
||||
private bool TryMarkDeviceLost(Exception exception)
|
||||
{
|
||||
if (!exception.Message.Contains(nameof(Result.ErrorDeviceLost), StringComparison.Ordinal))
|
||||
// Prefer the typed signal; fall back to the message for losses that
|
||||
// surface through other layers (e.g. Silk.NET bindings).
|
||||
if (exception is not VulkanDeviceLostException &&
|
||||
!exception.Message.Contains(nameof(Result.ErrorDeviceLost), StringComparison.Ordinal))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -1767,9 +1767,9 @@ public static class Gen5ShaderTranslator
|
||||
destinations = [Gen5Operand.Vector(word & 0xFF)];
|
||||
if (opcode == "VReadlaneB32")
|
||||
{
|
||||
// VReadlaneB32 writes to scalar destination (bits 8-14), not vector.
|
||||
// Bits 0-7 are unused for this opcode.
|
||||
destinations = [Gen5Operand.Scalar((word >> 8) & 0x7F)];
|
||||
// The scalar destination lives in the low vdst byte (bits 0-7);
|
||||
// bits 8-14 are the VOP3B carry-out sdst, which readlane lacks.
|
||||
destinations = [Gen5Operand.Scalar(word & 0xFF)];
|
||||
}
|
||||
var isVop3B = IsVop3BOpcode((word >> 16) & 0x3FF);
|
||||
control = new Gen5Vop3Control(
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
// Copyright (C) 2026 SharpEmu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
using SharpEmu.HLE;
|
||||
using SharpEmu.Libs.Kernel;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Xunit;
|
||||
|
||||
namespace SharpEmu.Libs.Tests.Kernel;
|
||||
|
||||
public sealed class KernelMemoryCompatExportsTests
|
||||
{
|
||||
[Fact]
|
||||
public void PosixStat_MissingFileReturnsMinusOne()
|
||||
{
|
||||
const ulong memoryBase = 0x1_0000_0000;
|
||||
const ulong pathAddress = memoryBase + 0x100;
|
||||
const ulong statAddress = memoryBase + 0x400;
|
||||
var memory = new FakeCpuMemory(memoryBase, 0x1000);
|
||||
var context = new CpuContext(memory, Generation.Gen5);
|
||||
memory.WriteCString(pathAddress, "/__sharpemu_test_missing__/shader.cache");
|
||||
context[CpuRegister.Rdi] = pathAddress;
|
||||
context[CpuRegister.Rsi] = statAddress;
|
||||
|
||||
var result = KernelMemoryCompatExports.PosixStat(context);
|
||||
|
||||
Assert.Equal(-1, result);
|
||||
Assert.Equal(ulong.MaxValue, context[CpuRegister.Rax]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sprintf_ReadsVariadicDoubleFromXmmRegister()
|
||||
{
|
||||
const ulong memoryBase = 0x1_0000_0000;
|
||||
const ulong destinationAddress = memoryBase + 0x100;
|
||||
const ulong formatAddress = memoryBase + 0x200;
|
||||
var memory = new FakeCpuMemory(memoryBase, 0x1000);
|
||||
var context = new CpuContext(memory, Generation.Gen5);
|
||||
memory.WriteCString(formatAddress, "%.4f");
|
||||
context[CpuRegister.Rdi] = destinationAddress;
|
||||
context[CpuRegister.Rsi] = formatAddress;
|
||||
context.SetXmmRegister(
|
||||
0,
|
||||
unchecked((ulong)BitConverter.DoubleToInt64Bits(0.5576)),
|
||||
0);
|
||||
|
||||
var result = KernelMemoryCompatExports.Sprintf(context);
|
||||
|
||||
Assert.Equal(0, result);
|
||||
Assert.Equal(6UL, context[CpuRegister.Rax]);
|
||||
Span<byte> output = stackalloc byte[7];
|
||||
Assert.True(memory.TryRead(destinationAddress, output));
|
||||
Assert.Equal("0.5576\0", Encoding.UTF8.GetString(output));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sprintf_UsesCLocaleForFloatingPoint()
|
||||
{
|
||||
var previousCulture = CultureInfo.CurrentCulture;
|
||||
try
|
||||
{
|
||||
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("tr-TR");
|
||||
|
||||
const ulong memoryBase = 0x1_0000_0000;
|
||||
const ulong destinationAddress = memoryBase + 0x100;
|
||||
const ulong formatAddress = memoryBase + 0x200;
|
||||
var memory = new FakeCpuMemory(memoryBase, 0x1000);
|
||||
var context = new CpuContext(memory, Generation.Gen5);
|
||||
memory.WriteCString(formatAddress, "%.4f");
|
||||
context[CpuRegister.Rdi] = destinationAddress;
|
||||
context[CpuRegister.Rsi] = formatAddress;
|
||||
context.SetXmmRegister(
|
||||
0,
|
||||
unchecked((ulong)BitConverter.DoubleToInt64Bits(0.5576)),
|
||||
0);
|
||||
|
||||
var result = KernelMemoryCompatExports.Sprintf(context);
|
||||
|
||||
Assert.Equal(0, result);
|
||||
Span<byte> output = stackalloc byte[7];
|
||||
Assert.True(memory.TryRead(destinationAddress, output));
|
||||
Assert.Equal("0.5576\0", Encoding.UTF8.GetString(output));
|
||||
}
|
||||
finally
|
||||
{
|
||||
CultureInfo.CurrentCulture = previousCulture;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -95,6 +95,32 @@ public sealed class GuestMemoryAllocatorTests
|
||||
Assert.Equal(0UL, (ulong)memory.GetPointer(address));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AlignedAllocationDoesNotRetainOverallocatedMappingsOutsideMacOS()
|
||||
{
|
||||
if (OperatingSystem.IsMacOS())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
const ulong desiredAddress = 0x00005000_0000_0123;
|
||||
const ulong alignment = 0x10000;
|
||||
const ulong alignedAddress = 0x00005000_0001_0000;
|
||||
const ulong allocationSize = 0x2000;
|
||||
using var host = new RelocatingHostMemory(alignedAddress);
|
||||
using var memory = new PhysicalVirtualMemory(host);
|
||||
|
||||
Assert.True(memory.TryAllocateAtOrAbove(desiredAddress, 0x1234, false, alignment, out var actualAddress));
|
||||
Assert.Equal(alignedAddress + alignment, actualAddress);
|
||||
Assert.Equal(
|
||||
[
|
||||
(alignedAddress, allocationSize),
|
||||
(alignedAddress + alignment, allocationSize),
|
||||
],
|
||||
host.AllocationCalls);
|
||||
Assert.Equal([alignedAddress + 0x1000], host.FreedAddresses);
|
||||
}
|
||||
|
||||
private sealed class FakeHostMemory : IHostMemory
|
||||
{
|
||||
public ulong Allocate(ulong desiredAddress, ulong size, HostPageProtection protection) =>
|
||||
@@ -197,6 +223,63 @@ public sealed class GuestMemoryAllocatorTests
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class RelocatingHostMemory(ulong firstAddress) : IHostMemory, IDisposable
|
||||
{
|
||||
private bool _relocatedFirstAllocation;
|
||||
|
||||
public List<(ulong Address, ulong Size)> AllocationCalls { get; } = [];
|
||||
|
||||
public List<ulong> FreedAddresses { get; } = [];
|
||||
|
||||
public ulong Allocate(ulong desiredAddress, ulong size, HostPageProtection protection)
|
||||
{
|
||||
AllocationCalls.Add((desiredAddress, size));
|
||||
if (!_relocatedFirstAllocation)
|
||||
{
|
||||
_relocatedFirstAllocation = true;
|
||||
return firstAddress + 0x1000;
|
||||
}
|
||||
|
||||
return desiredAddress;
|
||||
}
|
||||
|
||||
public ulong Reserve(ulong desiredAddress, ulong size, HostPageProtection protection) => 0;
|
||||
|
||||
public bool Commit(ulong address, ulong size, HostPageProtection protection) => true;
|
||||
|
||||
public bool Free(ulong address)
|
||||
{
|
||||
FreedAddresses.Add(address);
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool Protect(ulong address, ulong size, HostPageProtection protection, out uint rawOldProtection)
|
||||
{
|
||||
rawOldProtection = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool ProtectRaw(ulong address, ulong size, uint rawProtection, out uint rawOldProtection)
|
||||
{
|
||||
rawOldProtection = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool Query(ulong address, out HostRegionInfo info)
|
||||
{
|
||||
info = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
public void FlushInstructionCache(ulong address, ulong size)
|
||||
{
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class LazyHostMemory(ulong address) : IHostMemory, IDisposable
|
||||
{
|
||||
public bool CommitSucceeds { get; set; } = true;
|
||||
|
||||
Reference in New Issue
Block a user