misc: chore: Use explicit types in HLE project

This commit is contained in:
Evan Husted 2025-01-25 14:13:18 -06:00
parent 58c1ab7989
commit 5eba42fa06
80 changed files with 410 additions and 397 deletions

View File

@ -3,6 +3,7 @@ using Ryujinx.HLE.HOS;
using Ryujinx.HLE.HOS.Ipc; using Ryujinx.HLE.HOS.Ipc;
using Ryujinx.HLE.HOS.Services; using Ryujinx.HLE.HOS.Services;
using System; using System;
using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
@ -53,12 +54,12 @@ namespace Ryujinx.HLE.Exceptions
if (callingType != null && callingMethod != null) if (callingType != null && callingMethod != null)
{ {
// If the type is past 0xF, we are using TIPC // If the type is past 0xF, we are using TIPC
var ipcCommands = Request.Type > IpcMessageType.TipcCloseSession ? Service.TipcCommands : Service.CmifCommands; IReadOnlyDictionary<int, MethodInfo> ipcCommands = Request.Type > IpcMessageType.TipcCloseSession ? Service.TipcCommands : Service.CmifCommands;
// Find the handler for the method called // Find the handler for the method called
var ipcHandler = ipcCommands.FirstOrDefault(x => x.Value == callingMethod); KeyValuePair<int, MethodInfo> ipcHandler = ipcCommands.FirstOrDefault(x => x.Value == callingMethod);
var ipcCommandId = ipcHandler.Key; int ipcCommandId = ipcHandler.Key;
var ipcMethod = ipcHandler.Value; MethodInfo ipcMethod = ipcHandler.Value;
if (ipcMethod != null) if (ipcMethod != null)
{ {
@ -83,7 +84,7 @@ namespace Ryujinx.HLE.Exceptions
{ {
sb.AppendLine("\tPtrBuff:"); sb.AppendLine("\tPtrBuff:");
foreach (var buff in Request.PtrBuff) foreach (IpcPtrBuffDesc buff in Request.PtrBuff)
{ {
sb.AppendLine($"\t[{buff.Index}] Position: 0x{buff.Position:x16} Size: 0x{buff.Size:x16}"); sb.AppendLine($"\t[{buff.Index}] Position: 0x{buff.Position:x16} Size: 0x{buff.Size:x16}");
} }
@ -93,7 +94,7 @@ namespace Ryujinx.HLE.Exceptions
{ {
sb.AppendLine("\tSendBuff:"); sb.AppendLine("\tSendBuff:");
foreach (var buff in Request.SendBuff) foreach (IpcBuffDesc buff in Request.SendBuff)
{ {
sb.AppendLine($"\tPosition: 0x{buff.Position:x16} Size: 0x{buff.Size:x16} Flags: {buff.Flags}"); sb.AppendLine($"\tPosition: 0x{buff.Position:x16} Size: 0x{buff.Size:x16} Flags: {buff.Flags}");
} }
@ -103,7 +104,7 @@ namespace Ryujinx.HLE.Exceptions
{ {
sb.AppendLine("\tReceiveBuff:"); sb.AppendLine("\tReceiveBuff:");
foreach (var buff in Request.ReceiveBuff) foreach (IpcBuffDesc buff in Request.ReceiveBuff)
{ {
sb.AppendLine($"\tPosition: 0x{buff.Position:x16} Size: 0x{buff.Size:x16} Flags: {buff.Flags}"); sb.AppendLine($"\tPosition: 0x{buff.Position:x16} Size: 0x{buff.Size:x16} Flags: {buff.Flags}");
} }
@ -113,7 +114,7 @@ namespace Ryujinx.HLE.Exceptions
{ {
sb.AppendLine("\tExchangeBuff:"); sb.AppendLine("\tExchangeBuff:");
foreach (var buff in Request.ExchangeBuff) foreach (IpcBuffDesc buff in Request.ExchangeBuff)
{ {
sb.AppendLine($"\tPosition: 0x{buff.Position:x16} Size: 0x{buff.Size:x16} Flags: {buff.Flags}"); sb.AppendLine($"\tPosition: 0x{buff.Position:x16} Size: 0x{buff.Size:x16} Flags: {buff.Flags}");
} }
@ -123,7 +124,7 @@ namespace Ryujinx.HLE.Exceptions
{ {
sb.AppendLine("\tRecvListBuff:"); sb.AppendLine("\tRecvListBuff:");
foreach (var buff in Request.RecvListBuff) foreach (IpcRecvListBuffDesc buff in Request.RecvListBuff)
{ {
sb.AppendLine($"\tPosition: 0x{buff.Position:x16} Size: 0x{buff.Size:x16}"); sb.AppendLine($"\tPosition: 0x{buff.Position:x16} Size: 0x{buff.Size:x16}");
} }
@ -147,8 +148,8 @@ namespace Ryujinx.HLE.Exceptions
// Find the IIpcService method that threw this exception // Find the IIpcService method that threw this exception
while ((frame = trace.GetFrame(i++)) != null) while ((frame = trace.GetFrame(i++)) != null)
{ {
var method = frame.GetMethod(); MethodBase method = frame.GetMethod();
var declType = method.DeclaringType; Type declType = method.DeclaringType;
if (typeof(IpcService).IsAssignableFrom(declType)) if (typeof(IpcService).IsAssignableFrom(declType))
{ {

View File

@ -107,15 +107,15 @@ namespace Ryujinx.HLE.FileSystem
foreach (StorageId storageId in Enum.GetValues<StorageId>()) foreach (StorageId storageId in Enum.GetValues<StorageId>())
{ {
if (!ContentPath.TryGetContentPath(storageId, out var contentPathString)) if (!ContentPath.TryGetContentPath(storageId, out string contentPathString))
{ {
continue; continue;
} }
if (!ContentPath.TryGetRealPath(contentPathString, out var contentDirectory)) if (!ContentPath.TryGetRealPath(contentPathString, out string contentDirectory))
{ {
continue; continue;
} }
var registeredDirectory = Path.Combine(contentDirectory, "registered"); string registeredDirectory = Path.Combine(contentDirectory, "registered");
Directory.CreateDirectory(registeredDirectory); Directory.CreateDirectory(registeredDirectory);
@ -170,7 +170,7 @@ namespace Ryujinx.HLE.FileSystem
} }
} }
if (_locationEntries.TryGetValue(storageId, out var locationEntriesItem) && locationEntriesItem?.Count == 0) if (_locationEntries.TryGetValue(storageId, out LinkedList<LocationEntry> locationEntriesItem) && locationEntriesItem?.Count == 0)
{ {
_locationEntries.Remove(storageId); _locationEntries.Remove(storageId);
} }
@ -200,7 +200,7 @@ namespace Ryujinx.HLE.FileSystem
if (!mergedToContainer) if (!mergedToContainer)
{ {
using var pfs = PartitionFileSystemUtils.OpenApplicationFileSystem(containerPath, _virtualFileSystem); using IFileSystem pfs = PartitionFileSystemUtils.OpenApplicationFileSystem(containerPath, _virtualFileSystem);
} }
} }
} }
@ -217,17 +217,17 @@ namespace Ryujinx.HLE.FileSystem
if (AocData.TryGetValue(aocTitleId, out AocItem aoc)) if (AocData.TryGetValue(aocTitleId, out AocItem aoc))
{ {
var file = new FileStream(aoc.ContainerPath, FileMode.Open, FileAccess.Read); FileStream file = new FileStream(aoc.ContainerPath, FileMode.Open, FileAccess.Read);
using var ncaFile = new UniqueRef<IFile>(); using UniqueRef<IFile> ncaFile = new UniqueRef<IFile>();
switch (Path.GetExtension(aoc.ContainerPath)) switch (Path.GetExtension(aoc.ContainerPath))
{ {
case ".xci": case ".xci":
var xci = new Xci(_virtualFileSystem.KeySet, file.AsStorage()).OpenPartition(XciPartitionType.Secure); XciPartition xci = new Xci(_virtualFileSystem.KeySet, file.AsStorage()).OpenPartition(XciPartitionType.Secure);
xci.OpenFile(ref ncaFile.Ref, aoc.NcaPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); xci.OpenFile(ref ncaFile.Ref, aoc.NcaPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
break; break;
case ".nsp": case ".nsp":
var pfs = new PartitionFileSystem(); PartitionFileSystem pfs = new PartitionFileSystem();
pfs.Initialize(file.AsStorage()); pfs.Initialize(file.AsStorage());
pfs.OpenFile(ref ncaFile.Ref, aoc.NcaPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); pfs.OpenFile(ref ncaFile.Ref, aoc.NcaPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
break; break;
@ -278,7 +278,7 @@ namespace Ryujinx.HLE.FileSystem
{ {
if (_contentDictionary.ContainsValue(ncaId)) if (_contentDictionary.ContainsValue(ncaId))
{ {
var content = _contentDictionary.FirstOrDefault(x => x.Value == ncaId); KeyValuePair<(ulong titleId, NcaContentType type), string> content = _contentDictionary.FirstOrDefault(x => x.Value == ncaId);
ulong titleId = content.Key.titleId; ulong titleId = content.Key.titleId;
NcaContentType contentType = content.Key.type; NcaContentType contentType = content.Key.type;
@ -295,7 +295,7 @@ namespace Ryujinx.HLE.FileSystem
{ {
lock (_lock) lock (_lock)
{ {
if (_contentDictionary.TryGetValue((titleId, contentType), out var contentDictionaryItem)) if (_contentDictionary.TryGetValue((titleId, contentType), out string contentDictionaryItem))
{ {
return UInt128Utils.FromHex(contentDictionaryItem); return UInt128Utils.FromHex(contentDictionaryItem);
} }
@ -430,8 +430,8 @@ namespace Ryujinx.HLE.FileSystem
public void InstallFirmware(string firmwareSource) public void InstallFirmware(string firmwareSource)
{ {
ContentPath.TryGetContentPath(StorageId.BuiltInSystem, out var contentPathString); ContentPath.TryGetContentPath(StorageId.BuiltInSystem, out string contentPathString);
ContentPath.TryGetRealPath(contentPathString, out var contentDirectory); ContentPath.TryGetRealPath(contentPathString, out string contentDirectory);
string registeredDirectory = Path.Combine(contentDirectory, "registered"); string registeredDirectory = Path.Combine(contentDirectory, "registered");
string temporaryDirectory = Path.Combine(contentDirectory, "temp"); string temporaryDirectory = Path.Combine(contentDirectory, "temp");
@ -480,7 +480,7 @@ namespace Ryujinx.HLE.FileSystem
{ {
if (Directory.Exists(keysSource)) if (Directory.Exists(keysSource))
{ {
foreach (var filePath in Directory.EnumerateFiles(keysSource, "*.keys")) foreach (string filePath in Directory.EnumerateFiles(keysSource, "*.keys"))
{ {
VerifyKeysFile(filePath); VerifyKeysFile(filePath);
File.Copy(filePath, Path.Combine(installDirectory, Path.GetFileName(filePath)), true); File.Copy(filePath, Path.Combine(installDirectory, Path.GetFileName(filePath)), true);
@ -523,7 +523,7 @@ namespace Ryujinx.HLE.FileSystem
Directory.Delete(temporaryDirectory, true); Directory.Delete(temporaryDirectory, true);
} }
Directory.CreateDirectory(temporaryDirectory); Directory.CreateDirectory(temporaryDirectory);
foreach (var entry in archive.Entries) foreach (ZipArchiveEntry entry in archive.Entries)
{ {
if (Path.GetExtension(entry.FullName).Equals(".keys", StringComparison.OrdinalIgnoreCase)) if (Path.GetExtension(entry.FullName).Equals(".keys", StringComparison.OrdinalIgnoreCase))
{ {
@ -563,7 +563,7 @@ namespace Ryujinx.HLE.FileSystem
private void InstallFromPartition(IFileSystem filesystem, string temporaryDirectory) private void InstallFromPartition(IFileSystem filesystem, string temporaryDirectory)
{ {
foreach (var entry in filesystem.EnumerateEntries("/", "*.nca")) foreach (DirectoryEntryEx entry in filesystem.EnumerateEntries("/", "*.nca"))
{ {
Nca nca = new(_virtualFileSystem.KeySet, OpenPossibleFragmentedFile(filesystem, entry.FullPath, OpenMode.Read).AsStorage()); Nca nca = new(_virtualFileSystem.KeySet, OpenPossibleFragmentedFile(filesystem, entry.FullPath, OpenMode.Read).AsStorage());
@ -587,7 +587,7 @@ namespace Ryujinx.HLE.FileSystem
private static void InstallFromZip(ZipArchive archive, string temporaryDirectory) private static void InstallFromZip(ZipArchive archive, string temporaryDirectory)
{ {
foreach (var entry in archive.Entries) foreach (ZipArchiveEntry entry in archive.Entries)
{ {
if (entry.FullName.EndsWith(".nca") || entry.FullName.EndsWith(".nca/00")) if (entry.FullName.EndsWith(".nca") || entry.FullName.EndsWith(".nca/00"))
{ {
@ -627,7 +627,7 @@ namespace Ryujinx.HLE.FileSystem
private static IFile OpenPossibleFragmentedFile(IFileSystem filesystem, string path, OpenMode mode) private static IFile OpenPossibleFragmentedFile(IFileSystem filesystem, string path, OpenMode mode)
{ {
using var file = new UniqueRef<IFile>(); using UniqueRef<IFile> file = new UniqueRef<IFile>();
if (filesystem.FileExists($"{path}/00")) if (filesystem.FileExists($"{path}/00"))
{ {
@ -697,7 +697,7 @@ namespace Ryujinx.HLE.FileSystem
{ {
SystemVersion systemVersion = null; SystemVersion systemVersion = null;
foreach (var entry in archive.Entries) foreach (ZipArchiveEntry entry in archive.Entries)
{ {
if (entry.FullName.EndsWith(".nca") || entry.FullName.EndsWith(".nca/00")) if (entry.FullName.EndsWith(".nca") || entry.FullName.EndsWith(".nca/00"))
{ {
@ -706,7 +706,7 @@ namespace Ryujinx.HLE.FileSystem
Nca nca = new(_virtualFileSystem.KeySet, storage); Nca nca = new(_virtualFileSystem.KeySet, storage);
if (updateNcas.TryGetValue(nca.Header.TitleId, out var updateNcasItem)) if (updateNcas.TryGetValue(nca.Header.TitleId, out List<(NcaContentType type, string path)> updateNcasItem))
{ {
updateNcasItem.Add((nca.Header.ContentType, entry.FullName)); updateNcasItem.Add((nca.Header.ContentType, entry.FullName));
} }
@ -717,13 +717,13 @@ namespace Ryujinx.HLE.FileSystem
} }
} }
if (updateNcas.TryGetValue(SystemUpdateTitleId, out var ncaEntry)) if (updateNcas.TryGetValue(SystemUpdateTitleId, out List<(NcaContentType type, string path)> ncaEntry))
{ {
string metaPath = ncaEntry.FirstOrDefault(x => x.type == NcaContentType.Meta).path; string metaPath = ncaEntry.FirstOrDefault(x => x.type == NcaContentType.Meta).path;
CnmtContentMetaEntry[] metaEntries = null; CnmtContentMetaEntry[] metaEntries = null;
var fileEntry = archive.GetEntry(metaPath); ZipArchiveEntry fileEntry = archive.GetEntry(metaPath);
using (Stream ncaStream = GetZipStream(fileEntry)) using (Stream ncaStream = GetZipStream(fileEntry))
{ {
@ -733,11 +733,11 @@ namespace Ryujinx.HLE.FileSystem
string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath; string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath;
using var metaFile = new UniqueRef<IFile>(); using UniqueRef<IFile> metaFile = new UniqueRef<IFile>();
if (fs.OpenFile(ref metaFile.Ref, cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess()) if (fs.OpenFile(ref metaFile.Ref, cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess())
{ {
var meta = new Cnmt(metaFile.Get.AsStream()); Cnmt meta = new Cnmt(metaFile.Get.AsStream());
if (meta.Type == ContentMetaType.SystemUpdate) if (meta.Type == ContentMetaType.SystemUpdate)
{ {
@ -753,16 +753,16 @@ namespace Ryujinx.HLE.FileSystem
throw new FileNotFoundException("System update title was not found in the firmware package."); throw new FileNotFoundException("System update title was not found in the firmware package.");
} }
if (updateNcas.TryGetValue(SystemVersionTitleId, out var updateNcasItem)) if (updateNcas.TryGetValue(SystemVersionTitleId, out List<(NcaContentType type, string path)> updateNcasItem))
{ {
string versionEntry = updateNcasItem.FirstOrDefault(x => x.type != NcaContentType.Meta).path; string versionEntry = updateNcasItem.FirstOrDefault(x => x.type != NcaContentType.Meta).path;
using Stream ncaStream = GetZipStream(archive.GetEntry(versionEntry)); using Stream ncaStream = GetZipStream(archive.GetEntry(versionEntry));
Nca nca = new(_virtualFileSystem.KeySet, ncaStream.AsStorage()); Nca nca = new(_virtualFileSystem.KeySet, ncaStream.AsStorage());
var romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid); IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid);
using var systemVersionFile = new UniqueRef<IFile>(); using UniqueRef<IFile> systemVersionFile = new UniqueRef<IFile>();
if (romfs.OpenFile(ref systemVersionFile.Ref, "/file".ToU8Span(), OpenMode.Read).IsSuccess()) if (romfs.OpenFile(ref systemVersionFile.Ref, "/file".ToU8Span(), OpenMode.Read).IsSuccess())
{ {
@ -798,11 +798,11 @@ namespace Ryujinx.HLE.FileSystem
string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath; string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath;
using var metaFile = new UniqueRef<IFile>(); using UniqueRef<IFile> metaFile = new UniqueRef<IFile>();
if (fs.OpenFile(ref metaFile.Ref, cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess()) if (fs.OpenFile(ref metaFile.Ref, cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess())
{ {
var meta = new Cnmt(metaFile.Get.AsStream()); Cnmt meta = new Cnmt(metaFile.Get.AsStream());
IStorage contentStorage = contentNcaStream.AsStorage(); IStorage contentStorage = contentNcaStream.AsStorage();
if (contentStorage.GetSize(out long size).IsSuccess()) if (contentStorage.GetSize(out long size).IsSuccess())
@ -830,9 +830,9 @@ namespace Ryujinx.HLE.FileSystem
{ {
StringBuilder extraNcas = new(); StringBuilder extraNcas = new();
foreach (var entry in updateNcas) foreach (KeyValuePair<ulong, List<(NcaContentType type, string path)>> entry in updateNcas)
{ {
foreach (var (type, path) in entry.Value) foreach ((NcaContentType type, string path) in entry.Value)
{ {
extraNcas.AppendLine(path); extraNcas.AppendLine(path);
} }
@ -855,7 +855,7 @@ namespace Ryujinx.HLE.FileSystem
CnmtContentMetaEntry[] metaEntries = null; CnmtContentMetaEntry[] metaEntries = null;
foreach (var entry in filesystem.EnumerateEntries("/", "*.nca")) foreach (DirectoryEntryEx entry in filesystem.EnumerateEntries("/", "*.nca"))
{ {
IStorage ncaStorage = OpenPossibleFragmentedFile(filesystem, entry.FullPath, OpenMode.Read).AsStorage(); IStorage ncaStorage = OpenPossibleFragmentedFile(filesystem, entry.FullPath, OpenMode.Read).AsStorage();
@ -867,11 +867,11 @@ namespace Ryujinx.HLE.FileSystem
string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath; string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath;
using var metaFile = new UniqueRef<IFile>(); using UniqueRef<IFile> metaFile = new UniqueRef<IFile>();
if (fs.OpenFile(ref metaFile.Ref, cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess()) if (fs.OpenFile(ref metaFile.Ref, cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess())
{ {
var meta = new Cnmt(metaFile.Get.AsStream()); Cnmt meta = new Cnmt(metaFile.Get.AsStream());
if (meta.Type == ContentMetaType.SystemUpdate) if (meta.Type == ContentMetaType.SystemUpdate)
{ {
@ -883,9 +883,9 @@ namespace Ryujinx.HLE.FileSystem
} }
else if (nca.Header.TitleId == SystemVersionTitleId && nca.Header.ContentType == NcaContentType.Data) else if (nca.Header.TitleId == SystemVersionTitleId && nca.Header.ContentType == NcaContentType.Data)
{ {
var romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid); IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid);
using var systemVersionFile = new UniqueRef<IFile>(); using UniqueRef<IFile> systemVersionFile = new UniqueRef<IFile>();
if (romfs.OpenFile(ref systemVersionFile.Ref, "/file".ToU8Span(), OpenMode.Read).IsSuccess()) if (romfs.OpenFile(ref systemVersionFile.Ref, "/file".ToU8Span(), OpenMode.Read).IsSuccess())
{ {
@ -893,7 +893,7 @@ namespace Ryujinx.HLE.FileSystem
} }
} }
if (updateNcas.TryGetValue(nca.Header.TitleId, out var updateNcasItem)) if (updateNcas.TryGetValue(nca.Header.TitleId, out List<(NcaContentType type, string path)> updateNcasItem))
{ {
updateNcasItem.Add((nca.Header.ContentType, entry.FullPath)); updateNcasItem.Add((nca.Header.ContentType, entry.FullPath));
} }
@ -912,7 +912,7 @@ namespace Ryujinx.HLE.FileSystem
foreach (CnmtContentMetaEntry metaEntry in metaEntries) foreach (CnmtContentMetaEntry metaEntry in metaEntries)
{ {
if (updateNcas.TryGetValue(metaEntry.TitleId, out var ncaEntry)) if (updateNcas.TryGetValue(metaEntry.TitleId, out List<(NcaContentType type, string path)> ncaEntry))
{ {
string metaNcaPath = ncaEntry.FirstOrDefault(x => x.type == NcaContentType.Meta).path; string metaNcaPath = ncaEntry.FirstOrDefault(x => x.type == NcaContentType.Meta).path;
string contentPath = ncaEntry.FirstOrDefault(x => x.type != NcaContentType.Meta).path; string contentPath = ncaEntry.FirstOrDefault(x => x.type != NcaContentType.Meta).path;
@ -935,11 +935,11 @@ namespace Ryujinx.HLE.FileSystem
string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath; string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath;
using var metaFile = new UniqueRef<IFile>(); using UniqueRef<IFile> metaFile = new UniqueRef<IFile>();
if (fs.OpenFile(ref metaFile.Ref, cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess()) if (fs.OpenFile(ref metaFile.Ref, cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess())
{ {
var meta = new Cnmt(metaFile.Get.AsStream()); Cnmt meta = new Cnmt(metaFile.Get.AsStream());
if (contentStorage.GetSize(out long size).IsSuccess()) if (contentStorage.GetSize(out long size).IsSuccess())
{ {
@ -966,9 +966,9 @@ namespace Ryujinx.HLE.FileSystem
{ {
StringBuilder extraNcas = new(); StringBuilder extraNcas = new();
foreach (var entry in updateNcas) foreach (KeyValuePair<ulong, List<(NcaContentType type, string path)>> entry in updateNcas)
{ {
foreach (var (type, path) in entry.Value) foreach ((NcaContentType type, string path) in entry.Value)
{ {
extraNcas.AppendLine(path); extraNcas.AppendLine(path);
} }
@ -987,22 +987,22 @@ namespace Ryujinx.HLE.FileSystem
lock (_lock) lock (_lock)
{ {
var locationEnties = _locationEntries[StorageId.BuiltInSystem]; LinkedList<LocationEntry> locationEnties = _locationEntries[StorageId.BuiltInSystem];
foreach (var entry in locationEnties) foreach (LocationEntry entry in locationEnties)
{ {
if (entry.ContentType == NcaContentType.Data) if (entry.ContentType == NcaContentType.Data)
{ {
var path = VirtualFileSystem.SwitchPathToSystemPath(entry.ContentPath); string path = VirtualFileSystem.SwitchPathToSystemPath(entry.ContentPath);
using FileStream fileStream = File.OpenRead(path); using FileStream fileStream = File.OpenRead(path);
Nca nca = new(_virtualFileSystem.KeySet, fileStream.AsStorage()); Nca nca = new(_virtualFileSystem.KeySet, fileStream.AsStorage());
if (nca.Header.TitleId == SystemVersionTitleId && nca.Header.ContentType == NcaContentType.Data) if (nca.Header.TitleId == SystemVersionTitleId && nca.Header.ContentType == NcaContentType.Data)
{ {
var romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid); IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid);
using var systemVersionFile = new UniqueRef<IFile>(); using UniqueRef<IFile> systemVersionFile = new UniqueRef<IFile>();
if (romfs.OpenFile(ref systemVersionFile.Ref, "/file".ToU8Span(), OpenMode.Read).IsSuccess()) if (romfs.OpenFile(ref systemVersionFile.Ref, "/file".ToU8Span(), OpenMode.Read).IsSuccess())
{ {
@ -1073,7 +1073,7 @@ namespace Ryujinx.HLE.FileSystem
public bool AreKeysAlredyPresent(string pathToCheck) public bool AreKeysAlredyPresent(string pathToCheck)
{ {
string[] fileNames = { "prod.keys", "title.keys", "console.keys", "dev.keys" }; string[] fileNames = { "prod.keys", "title.keys", "console.keys", "dev.keys" };
foreach (var file in fileNames) foreach (string file in fileNames)
{ {
if (File.Exists(Path.Combine(pathToCheck, file))) if (File.Exists(Path.Combine(pathToCheck, file)))
{ {

View File

@ -39,7 +39,7 @@ namespace Ryujinx.HLE.FileSystem
// TODO: Replace this with a check for IdOffset as soon as LibHac supports it: // TODO: Replace this with a check for IdOffset as soon as LibHac supports it:
// && entry.IdOffset == programIndex // && entry.IdOffset == programIndex
foreach (var entry in _cnmt.ContentEntries) foreach (CnmtContentEntry entry in _cnmt.ContentEntries)
{ {
if (entry.Type != type) if (entry.Type != type)
{ {

View File

@ -61,7 +61,7 @@ namespace Ryujinx.HLE.FileSystem
public void LoadRomFs(ulong pid, string fileName) public void LoadRomFs(ulong pid, string fileName)
{ {
var romfsStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); FileStream romfsStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
_romFsByPid.AddOrUpdate(pid, romfsStream, (pid, oldStream) => _romFsByPid.AddOrUpdate(pid, romfsStream, (pid, oldStream) =>
{ {
@ -140,8 +140,8 @@ namespace Ryujinx.HLE.FileSystem
return $"{rawPath}:/"; return $"{rawPath}:/";
} }
var basePath = rawPath.AsSpan(0, firstSeparatorOffset); ReadOnlySpan<char> basePath = rawPath.AsSpan(0, firstSeparatorOffset);
var fileName = rawPath.AsSpan(firstSeparatorOffset + 1); ReadOnlySpan<char> fileName = rawPath.AsSpan(firstSeparatorOffset + 1);
return $"{basePath}:/{fileName}"; return $"{basePath}:/{fileName}";
} }
@ -194,7 +194,7 @@ namespace Ryujinx.HLE.FileSystem
} }
fsServerClient = horizon.CreatePrivilegedHorizonClient(); fsServerClient = horizon.CreatePrivilegedHorizonClient();
var fsServer = new FileSystemServer(fsServerClient); FileSystemServer fsServer = new FileSystemServer(fsServerClient);
RandomDataGenerator randomGenerator = Random.Shared.NextBytes; RandomDataGenerator randomGenerator = Random.Shared.NextBytes;
@ -208,7 +208,7 @@ namespace Ryujinx.HLE.FileSystem
SdCard.SetSdCardInserted(true); SdCard.SetSdCardInserted(true);
var fsServerConfig = new FileSystemServerConfig FileSystemServerConfig fsServerConfig = new FileSystemServerConfig
{ {
ExternalKeySet = KeySet.ExternalKeySet, ExternalKeySet = KeySet.ExternalKeySet,
FsCreators = fsServerObjects.FsCreators, FsCreators = fsServerObjects.FsCreators,
@ -270,7 +270,7 @@ namespace Ryujinx.HLE.FileSystem
{ {
foreach (DirectoryEntryEx ticketEntry in fs.EnumerateEntries("/", "*.tik")) foreach (DirectoryEntryEx ticketEntry in fs.EnumerateEntries("/", "*.tik"))
{ {
using var ticketFile = new UniqueRef<IFile>(); using UniqueRef<IFile> ticketFile = new UniqueRef<IFile>();
Result result = fs.OpenFile(ref ticketFile.Ref, ticketEntry.FullPath.ToU8Span(), OpenMode.Read); Result result = fs.OpenFile(ref ticketFile.Ref, ticketEntry.FullPath.ToU8Span(), OpenMode.Read);
@ -286,7 +286,7 @@ namespace Ryujinx.HLE.FileSystem
continue; continue;
Ticket ticket = new(new MemoryStream(ticketData)); Ticket ticket = new(new MemoryStream(ticketData));
var titleKey = ticket.GetTitleKey(KeySet); byte[] titleKey = ticket.GetTitleKey(KeySet);
if (titleKey != null) if (titleKey != null)
{ {
@ -334,7 +334,7 @@ namespace Ryujinx.HLE.FileSystem
{ {
Span<SaveDataInfo> info = stackalloc SaveDataInfo[8]; Span<SaveDataInfo> info = stackalloc SaveDataInfo[8];
using var iterator = new UniqueRef<SaveDataIterator>(); using UniqueRef<SaveDataIterator> iterator = new UniqueRef<SaveDataIterator>();
Result rc = hos.Fs.OpenSaveDataIterator(ref iterator.Ref, spaceId); Result rc = hos.Fs.OpenSaveDataIterator(ref iterator.Ref, spaceId);
if (rc.IsFailure()) if (rc.IsFailure())
@ -398,7 +398,7 @@ namespace Ryujinx.HLE.FileSystem
} }
const string MountName = "SaveDir"; const string MountName = "SaveDir";
var mountNameU8 = MountName.ToU8Span(); U8Span mountNameU8 = MountName.ToU8Span();
BisPartitionId partitionId = info.SpaceId switch BisPartitionId partitionId = info.SpaceId switch
{ {
@ -415,7 +415,7 @@ namespace Ryujinx.HLE.FileSystem
try try
{ {
var path = $"{MountName}:/save/{info.SaveDataId:x16}".ToU8Span(); U8Span path = $"{MountName}:/save/{info.SaveDataId:x16}".ToU8Span();
rc = hos.Fs.GetEntryType(out _, path); rc = hos.Fs.GetEntryType(out _, path);
@ -437,7 +437,7 @@ namespace Ryujinx.HLE.FileSystem
{ {
list = null; list = null;
var mountName = "system".ToU8Span(); U8Span mountName = "system".ToU8Span();
DirectoryHandle handle = default; DirectoryHandle handle = default;
List<ulong> localList = new(); List<ulong> localList = new();
@ -498,7 +498,7 @@ namespace Ryujinx.HLE.FileSystem
// Only save data IDs added to SystemExtraDataFixInfo will be fixed. // Only save data IDs added to SystemExtraDataFixInfo will be fixed.
private static Result FixUnindexedSystemSaves(HorizonClient hos, List<ulong> existingSaveIds) private static Result FixUnindexedSystemSaves(HorizonClient hos, List<ulong> existingSaveIds)
{ {
foreach (var fixInfo in _systemExtraDataFixInfo) foreach (ExtraDataFixInfo fixInfo in _systemExtraDataFixInfo)
{ {
if (!existingSaveIds.Contains(fixInfo.StaticSaveDataId)) if (!existingSaveIds.Contains(fixInfo.StaticSaveDataId))
{ {
@ -665,7 +665,7 @@ namespace Ryujinx.HLE.FileSystem
{ {
if (disposing) if (disposing)
{ {
foreach (var stream in _romFsByPid.Values) foreach (Stream stream in _romFsByPid.Values)
{ {
stream.Close(); stream.Close();
} }

View File

@ -122,7 +122,7 @@ namespace Ryujinx.HLE.HOS.Applets.Error
if (romfs.FileExists(filePath)) if (romfs.FileExists(filePath))
{ {
using var binaryFile = new UniqueRef<IFile>(); using UniqueRef<IFile> binaryFile = new UniqueRef<IFile>();
romfs.OpenFile(ref binaryFile.Ref, filePath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); romfs.OpenFile(ref binaryFile.Ref, filePath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
StreamReader reader = new(binaryFile.Get.AsStream(), Encoding.Unicode); StreamReader reader = new(binaryFile.Get.AsStream(), Encoding.Unicode);

View File

@ -81,8 +81,8 @@ namespace Ryujinx.HLE.HOS.Applets
_interactiveSession.DataAvailable += OnInteractiveData; _interactiveSession.DataAvailable += OnInteractiveData;
var launchParams = _normalSession.Pop(); byte[] launchParams = _normalSession.Pop();
var keyboardConfig = _normalSession.Pop(); byte[] keyboardConfig = _normalSession.Pop();
_isBackground = keyboardConfig.Length == Unsafe.SizeOf<SoftwareKeyboardInitialize>(); _isBackground = keyboardConfig.Length == Unsafe.SizeOf<SoftwareKeyboardInitialize>();
@ -205,7 +205,7 @@ namespace Ryujinx.HLE.HOS.Applets
else else
{ {
// Call the configured GUI handler to get user's input. // Call the configured GUI handler to get user's input.
var args = new SoftwareKeyboardUIArgs SoftwareKeyboardUIArgs args = new SoftwareKeyboardUIArgs
{ {
KeyboardMode = _keyboardForegroundConfig.Mode, KeyboardMode = _keyboardForegroundConfig.Mode,
HeaderText = StripUnicodeControlCodes(_keyboardForegroundConfig.HeaderText), HeaderText = StripUnicodeControlCodes(_keyboardForegroundConfig.HeaderText),
@ -265,7 +265,7 @@ namespace Ryujinx.HLE.HOS.Applets
private void OnInteractiveData(object sender, EventArgs e) private void OnInteractiveData(object sender, EventArgs e)
{ {
// Obtain the validation status response. // Obtain the validation status response.
var data = _interactiveSession.Pop(); byte[] data = _interactiveSession.Pop();
if (_isBackground) if (_isBackground)
{ {
@ -320,7 +320,7 @@ namespace Ryujinx.HLE.HOS.Applets
using MemoryStream stream = new(data); using MemoryStream stream = new(data);
using BinaryReader reader = new(stream); using BinaryReader reader = new(stream);
var request = (InlineKeyboardRequest)reader.ReadUInt32(); InlineKeyboardRequest request = (InlineKeyboardRequest)reader.ReadUInt32();
long remaining; long remaining;
@ -400,14 +400,14 @@ namespace Ryujinx.HLE.HOS.Applets
remaining = stream.Length - stream.Position; remaining = stream.Length - stream.Position;
if (remaining == Marshal.SizeOf<SoftwareKeyboardCalc>()) if (remaining == Marshal.SizeOf<SoftwareKeyboardCalc>())
{ {
var keyboardCalcData = reader.ReadBytes((int)remaining); byte[] keyboardCalcData = reader.ReadBytes((int)remaining);
var keyboardCalc = ReadStruct<SoftwareKeyboardCalc>(keyboardCalcData); SoftwareKeyboardCalc keyboardCalc = ReadStruct<SoftwareKeyboardCalc>(keyboardCalcData);
newCalc = keyboardCalc.ToExtended(); newCalc = keyboardCalc.ToExtended();
} }
else if (remaining == Marshal.SizeOf<SoftwareKeyboardCalcEx>() || remaining == SoftwareKeyboardCalcEx.AlternativeSize) else if (remaining == Marshal.SizeOf<SoftwareKeyboardCalcEx>() || remaining == SoftwareKeyboardCalcEx.AlternativeSize)
{ {
var keyboardCalcData = reader.ReadBytes((int)remaining); byte[] keyboardCalcData = reader.ReadBytes((int)remaining);
newCalc = ReadStruct<SoftwareKeyboardCalcEx>(keyboardCalcData); newCalc = ReadStruct<SoftwareKeyboardCalcEx>(keyboardCalcData);
} }

View File

@ -117,8 +117,8 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
_state.OverwriteMode = overwriteMode.GetValueOrDefault(_state.OverwriteMode); _state.OverwriteMode = overwriteMode.GetValueOrDefault(_state.OverwriteMode);
_state.TypingEnabled = typingEnabled.GetValueOrDefault(_state.TypingEnabled); _state.TypingEnabled = typingEnabled.GetValueOrDefault(_state.TypingEnabled);
var begin = _state.CursorBegin; int begin = _state.CursorBegin;
var end = _state.CursorEnd; int end = _state.CursorEnd;
_state.CursorBegin = Math.Min(begin, end); _state.CursorBegin = Math.Min(begin, end);
_state.CursorEnd = Math.Max(begin, end); _state.CursorEnd = Math.Max(begin, end);

View File

@ -75,10 +75,10 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
_padCancelIcon = LoadResource(typeof(SoftwareKeyboardRendererBase).Assembly, padCancelIconPath, 0, 0); _padCancelIcon = LoadResource(typeof(SoftwareKeyboardRendererBase).Assembly, padCancelIconPath, 0, 0);
_keyModeIcon = LoadResource(typeof(SoftwareKeyboardRendererBase).Assembly, keyModeIconPath, 0, 0); _keyModeIcon = LoadResource(typeof(SoftwareKeyboardRendererBase).Assembly, keyModeIconPath, 0, 0);
var panelColor = ToColor(uiTheme.DefaultBackgroundColor, 255); SKColor panelColor = ToColor(uiTheme.DefaultBackgroundColor, 255);
var panelTransparentColor = ToColor(uiTheme.DefaultBackgroundColor, 150); SKColor panelTransparentColor = ToColor(uiTheme.DefaultBackgroundColor, 150);
var borderColor = ToColor(uiTheme.DefaultBorderColor); SKColor borderColor = ToColor(uiTheme.DefaultBorderColor);
var selectionBackgroundColor = ToColor(uiTheme.SelectionBackgroundColor); SKColor selectionBackgroundColor = ToColor(uiTheme.SelectionBackgroundColor);
_textNormalColor = ToColor(uiTheme.DefaultForegroundColor); _textNormalColor = ToColor(uiTheme.DefaultForegroundColor);
_textSelectedColor = ToColor(uiTheme.SelectionForegroundColor); _textSelectedColor = ToColor(uiTheme.SelectionForegroundColor);
@ -134,7 +134,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
{ {
try try
{ {
using var typeface = SKTypeface.FromFamilyName(fontFamily, SKFontStyle.Normal); using SKTypeface typeface = SKTypeface.FromFamilyName(fontFamily, SKFontStyle.Normal);
_messageFont = new SKFont(typeface, 26); _messageFont = new SKFont(typeface, 26);
_inputTextFont = new SKFont(typeface, _inputTextFontSize); _inputTextFont = new SKFont(typeface, _inputTextFontSize);
_labelsTextFont = new SKFont(typeface, 24); _labelsTextFont = new SKFont(typeface, 24);
@ -151,10 +151,10 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
private static SKColor ToColor(ThemeColor color, byte? overrideAlpha = null, bool flipRgb = false) private static SKColor ToColor(ThemeColor color, byte? overrideAlpha = null, bool flipRgb = false)
{ {
var a = (byte)(color.A * 255); byte a = (byte)(color.A * 255);
var r = (byte)(color.R * 255); byte r = (byte)(color.R * 255);
var g = (byte)(color.G * 255); byte g = (byte)(color.G * 255);
var b = (byte)(color.B * 255); byte b = (byte)(color.B * 255);
if (flipRgb) if (flipRgb)
{ {
@ -177,11 +177,11 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
{ {
Debug.Assert(resourceStream != null); Debug.Assert(resourceStream != null);
var bitmap = SKBitmap.Decode(resourceStream); SKBitmap bitmap = SKBitmap.Decode(resourceStream);
if (newHeight != 0 && newWidth != 0) if (newHeight != 0 && newWidth != 0)
{ {
var resized = bitmap.Resize(new SKImageInfo(newWidth, newHeight), SKFilterQuality.High); SKBitmap resized = bitmap.Resize(new SKImageInfo(newWidth, newHeight), SKFilterQuality.High);
if (resized != null) if (resized != null)
{ {
bitmap.Dispose(); bitmap.Dispose();
@ -198,7 +198,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
{ {
return; return;
} }
var canvas = _surface.Canvas; SKCanvas canvas = _surface.Canvas;
canvas.Clear(SKColors.Transparent); canvas.Clear(SKColors.Transparent);
canvas.DrawRect(_panelRectangle, _panelBrush); canvas.DrawRect(_panelRectangle, _panelBrush);
@ -219,18 +219,18 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
return; return;
} }
using var paint = new SKPaint(_messageFont) using SKPaint paint = new SKPaint(_messageFont)
{ {
Color = _textNormalColor, Color = _textNormalColor,
IsAntialias = true IsAntialias = true
}; };
var canvas = _surface.Canvas; SKCanvas canvas = _surface.Canvas;
var messageRectangle = MeasureString(MessageText, paint); SKRect messageRectangle = MeasureString(MessageText, paint);
float messagePositionX = (_panelRectangle.Width - messageRectangle.Width) / 2 - messageRectangle.Left; float messagePositionX = (_panelRectangle.Width - messageRectangle.Width) / 2 - messageRectangle.Left;
float messagePositionY = _messagePositionY - messageRectangle.Top; float messagePositionY = _messagePositionY - messageRectangle.Top;
var messagePosition = new SKPoint(messagePositionX, messagePositionY); SKPoint messagePosition = new SKPoint(messagePositionX, messagePositionY);
var messageBoundRectangle = SKRect.Create(messagePositionX, messagePositionY, messageRectangle.Width, messageRectangle.Height); SKRect messageBoundRectangle = SKRect.Create(messagePositionX, messagePositionY, messageRectangle.Width, messageRectangle.Height);
canvas.DrawRect(messageBoundRectangle, _panelBrush); canvas.DrawRect(messageBoundRectangle, _panelBrush);
@ -336,12 +336,12 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
private void DrawTextBox(SKCanvas canvas, SoftwareKeyboardUIState state) private void DrawTextBox(SKCanvas canvas, SoftwareKeyboardUIState state)
{ {
using var textPaint = new SKPaint(_labelsTextFont) using SKPaint textPaint = new SKPaint(_labelsTextFont)
{ {
IsAntialias = true, IsAntialias = true,
Color = _textNormalColor Color = _textNormalColor
}; };
var inputTextRectangle = MeasureString(state.InputText, textPaint); SKRect inputTextRectangle = MeasureString(state.InputText, textPaint);
float boxWidth = (int)(Math.Max(300, inputTextRectangle.Width + inputTextRectangle.Left + 8)); float boxWidth = (int)(Math.Max(300, inputTextRectangle.Width + inputTextRectangle.Left + 8));
float boxHeight = 32; float boxHeight = 32;
@ -360,7 +360,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
float inputTextX = (_panelRectangle.Width - inputTextRectangle.Width) / 2 - inputTextRectangle.Left; float inputTextX = (_panelRectangle.Width - inputTextRectangle.Width) / 2 - inputTextRectangle.Left;
float inputTextY = boxY + 5; float inputTextY = boxY + 5;
var inputTextPosition = new SKPoint(inputTextX, inputTextY); SKPoint inputTextPosition = new SKPoint(inputTextX, inputTextY);
canvas.DrawText(state.InputText, inputTextPosition.X, inputTextPosition.Y + (_labelsTextFont.Metrics.XHeight + _labelsTextFont.Metrics.Descent), textPaint); canvas.DrawText(state.InputText, inputTextPosition.X, inputTextPosition.Y + (_labelsTextFont.Metrics.XHeight + _labelsTextFont.Metrics.Descent), textPaint);
// Draw the cursor on top of the text and redraw the text with a different color if necessary. // Draw the cursor on top of the text and redraw the text with a different color if necessary.
@ -387,8 +387,8 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
ReadOnlySpan<char> textUntilBegin = state.InputText.AsSpan(0, state.CursorBegin); ReadOnlySpan<char> textUntilBegin = state.InputText.AsSpan(0, state.CursorBegin);
ReadOnlySpan<char> textUntilEnd = state.InputText.AsSpan(0, state.CursorEnd); ReadOnlySpan<char> textUntilEnd = state.InputText.AsSpan(0, state.CursorEnd);
var selectionBeginRectangle = MeasureString(textUntilBegin, textPaint); SKRect selectionBeginRectangle = MeasureString(textUntilBegin, textPaint);
var selectionEndRectangle = MeasureString(textUntilEnd, textPaint); SKRect selectionEndRectangle = MeasureString(textUntilEnd, textPaint);
cursorVisible = true; cursorVisible = true;
cursorPositionXLeft = inputTextX + selectionBeginRectangle.Width + selectionBeginRectangle.Left; cursorPositionXLeft = inputTextX + selectionBeginRectangle.Width + selectionBeginRectangle.Left;
@ -406,7 +406,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
int cursorBegin = Math.Min(state.InputText.Length, state.CursorBegin); int cursorBegin = Math.Min(state.InputText.Length, state.CursorBegin);
ReadOnlySpan<char> textUntilCursor = state.InputText.AsSpan(0, cursorBegin); ReadOnlySpan<char> textUntilCursor = state.InputText.AsSpan(0, cursorBegin);
var cursorTextRectangle = MeasureString(textUntilCursor, textPaint); SKRect cursorTextRectangle = MeasureString(textUntilCursor, textPaint);
cursorVisible = true; cursorVisible = true;
cursorPositionXLeft = inputTextX + cursorTextRectangle.Width + cursorTextRectangle.Left; cursorPositionXLeft = inputTextX + cursorTextRectangle.Width + cursorTextRectangle.Left;
@ -452,16 +452,16 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
} }
else else
{ {
var cursorRectangle = SKRect.Create(cursorPositionXLeft, cursorPositionYTop, cursorWidth, cursorHeight); SKRect cursorRectangle = SKRect.Create(cursorPositionXLeft, cursorPositionYTop, cursorWidth, cursorHeight);
canvas.DrawRect(cursorRectangle, cursorPen); canvas.DrawRect(cursorRectangle, cursorPen);
canvas.DrawRect(cursorRectangle, cursorBrush); canvas.DrawRect(cursorRectangle, cursorBrush);
using var textOverCursor = SKSurface.Create(new SKImageInfo((int)cursorRectangle.Width, (int)cursorRectangle.Height, SKColorType.Rgba8888)); using SKSurface textOverCursor = SKSurface.Create(new SKImageInfo((int)cursorRectangle.Width, (int)cursorRectangle.Height, SKColorType.Rgba8888));
var textOverCanvas = textOverCursor.Canvas; SKCanvas textOverCanvas = textOverCursor.Canvas;
var textRelativePosition = new SKPoint(inputTextPosition.X - cursorRectangle.Left, inputTextPosition.Y - cursorRectangle.Top); SKPoint textRelativePosition = new SKPoint(inputTextPosition.X - cursorRectangle.Left, inputTextPosition.Y - cursorRectangle.Top);
using var cursorPaint = new SKPaint(_inputTextFont) using SKPaint cursorPaint = new SKPaint(_inputTextFont)
{ {
Color = cursorTextColor, Color = cursorTextColor,
IsAntialias = true IsAntialias = true
@ -469,7 +469,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
textOverCanvas.DrawText(state.InputText, textRelativePosition.X, textRelativePosition.Y + _inputTextFont.Metrics.XHeight + _inputTextFont.Metrics.Descent, cursorPaint); textOverCanvas.DrawText(state.InputText, textRelativePosition.X, textRelativePosition.Y + _inputTextFont.Metrics.XHeight + _inputTextFont.Metrics.Descent, cursorPaint);
var cursorPosition = new SKPoint((int)cursorRectangle.Left, (int)cursorRectangle.Top); SKPoint cursorPosition = new SKPoint((int)cursorRectangle.Left, (int)cursorRectangle.Top);
textOverCursor.Flush(); textOverCursor.Flush();
canvas.DrawSurface(textOverCursor, cursorPosition); canvas.DrawSurface(textOverCursor, cursorPosition);
} }
@ -492,13 +492,13 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
float iconWidth = icon.Width; float iconWidth = icon.Width;
float iconHeight = icon.Height; float iconHeight = icon.Height;
using var paint = new SKPaint(_labelsTextFont) using SKPaint paint = new SKPaint(_labelsTextFont)
{ {
Color = _textNormalColor, Color = _textNormalColor,
IsAntialias = true IsAntialias = true
}; };
var labelRectangle = MeasureString(label, paint); SKRect labelRectangle = MeasureString(label, paint);
float labelPositionX = iconWidth + 8 - labelRectangle.Left; float labelPositionX = iconWidth + 8 - labelRectangle.Left;
float labelPositionY = 3; float labelPositionY = 3;
@ -514,13 +514,13 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
iconX += originX; iconX += originX;
iconY += originY; iconY += originY;
var iconPosition = new SKPoint((int)iconX, (int)iconY); SKPoint iconPosition = new SKPoint((int)iconX, (int)iconY);
var labelPosition = new SKPoint(labelPositionX + originX, labelPositionY + originY); SKPoint labelPosition = new SKPoint(labelPositionX + originX, labelPositionY + originY);
var selectedRectangle = SKRect.Create(originX - 2 * _padPressedPenWidth, originY - 2 * _padPressedPenWidth, SKRect selectedRectangle = SKRect.Create(originX - 2 * _padPressedPenWidth, originY - 2 * _padPressedPenWidth,
fullWidth + 4 * _padPressedPenWidth, fullHeight + 4 * _padPressedPenWidth); fullWidth + 4 * _padPressedPenWidth, fullHeight + 4 * _padPressedPenWidth);
var boundRectangle = SKRect.Create(originX, originY, fullWidth, fullHeight); SKRect boundRectangle = SKRect.Create(originX, originY, fullWidth, fullHeight);
boundRectangle.Inflate(4 * _padPressedPenWidth, 4 * _padPressedPenWidth); boundRectangle.Inflate(4 * _padPressedPenWidth, 4 * _padPressedPenWidth);
canvas.DrawRect(boundRectangle, _panelBrush); canvas.DrawRect(boundRectangle, _panelBrush);
@ -545,12 +545,12 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
private void DrawControllerToggle(SKCanvas canvas, SKPoint point) private void DrawControllerToggle(SKCanvas canvas, SKPoint point)
{ {
using var paint = new SKPaint(_labelsTextFont) using SKPaint paint = new SKPaint(_labelsTextFont)
{ {
IsAntialias = true, IsAntialias = true,
Color = _textNormalColor Color = _textNormalColor
}; };
var labelRectangle = MeasureString(ControllerToggleText, paint); SKRect labelRectangle = MeasureString(ControllerToggleText, paint);
// Use relative positions so we can center the entire drawing later. // Use relative positions so we can center the entire drawing later.
@ -574,8 +574,8 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
keyX += originX; keyX += originX;
keyY += originY; keyY += originY;
var labelPosition = new SKPoint(labelPositionX + originX, labelPositionY + originY); SKPoint labelPosition = new SKPoint(labelPositionX + originX, labelPositionY + originY);
var overlayPosition = new SKPoint((int)keyX, (int)keyY); SKPoint overlayPosition = new SKPoint((int)keyX, (int)keyY);
canvas.DrawBitmap(_keyModeIcon, overlayPosition); canvas.DrawBitmap(_keyModeIcon, overlayPosition);
canvas.DrawText(ControllerToggleText, labelPosition.X, labelPosition.Y + _labelsTextFont.Metrics.XHeight, paint); canvas.DrawText(ControllerToggleText, labelPosition.X, labelPosition.Y + _labelsTextFont.Metrics.XHeight, paint);
@ -593,7 +593,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
// Convert the pixel format used in the image to the one used in the Switch surface. // Convert the pixel format used in the image to the one used in the Switch surface.
_surface.Flush(); _surface.Flush();
var buffer = new byte[_imageInfo.BytesSize]; byte[] buffer = new byte[_imageInfo.BytesSize];
fixed (byte* bufferPtr = buffer) fixed (byte* bufferPtr = buffer)
{ {
if (!_surface.ReadPixels(_imageInfo, (nint)bufferPtr, _imageInfo.RowBytes, 0, 0)) if (!_surface.ReadPixels(_imageInfo, (nint)bufferPtr, _imageInfo.RowBytes, 0, 0))

View File

@ -79,11 +79,11 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
public void Reset(Action<float> action, int totalMilliseconds, int sleepMilliseconds) public void Reset(Action<float> action, int totalMilliseconds, int sleepMilliseconds)
{ {
// Create a dedicated cancel token for each task. // Create a dedicated cancel token for each task.
var cancelled = new TRef<bool>(false); TRef<bool> cancelled = new TRef<bool>(false);
Reset(new Thread(() => Reset(new Thread(() =>
{ {
var substepData = new SleepSubstepData(sleepMilliseconds); SleepSubstepData substepData = new SleepSubstepData(sleepMilliseconds);
int totalCount = totalMilliseconds / sleepMilliseconds; int totalCount = totalMilliseconds / sleepMilliseconds;
int totalRemainder = totalMilliseconds - totalCount * sleepMilliseconds; int totalRemainder = totalMilliseconds - totalCount * sleepMilliseconds;
@ -126,11 +126,11 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
public void Reset(Action action, int sleepMilliseconds) public void Reset(Action action, int sleepMilliseconds)
{ {
// Create a dedicated cancel token for each task. // Create a dedicated cancel token for each task.
var cancelled = new TRef<bool>(false); TRef<bool> cancelled = new TRef<bool>(false);
Reset(new Thread(() => Reset(new Thread(() =>
{ {
var substepData = new SleepSubstepData(sleepMilliseconds); SleepSubstepData substepData = new SleepSubstepData(sleepMilliseconds);
while (!Volatile.Read(ref cancelled.Value)) while (!Volatile.Read(ref cancelled.Value))
{ {
@ -147,7 +147,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
public void Reset(Action action) public void Reset(Action action)
{ {
// Create a dedicated cancel token for each task. // Create a dedicated cancel token for each task.
var cancelled = new TRef<bool>(false); TRef<bool> cancelled = new TRef<bool>(false);
Reset(new Thread(() => Reset(new Thread(() =>
{ {

View File

@ -51,8 +51,8 @@ namespace Ryujinx.HLE.HOS
if (OperatingSystem.IsMacOS() && isArm64Host && for64Bit && context.Device.Configuration.UseHypervisor) if (OperatingSystem.IsMacOS() && isArm64Host && for64Bit && context.Device.Configuration.UseHypervisor)
{ {
var cpuEngine = new HvEngine(_tickSource); HvEngine cpuEngine = new HvEngine(_tickSource);
var memoryManager = new HvMemoryManager(context.Memory, addressSpaceSize, invalidAccessHandler); HvMemoryManager memoryManager = new HvMemoryManager(context.Memory, addressSpaceSize, invalidAccessHandler);
processContext = new ArmProcessContext<HvMemoryManager>(pid, cpuEngine, _gpu, memoryManager, addressSpaceSize, for64Bit); processContext = new ArmProcessContext<HvMemoryManager>(pid, cpuEngine, _gpu, memoryManager, addressSpaceSize, for64Bit);
} }
else else
@ -86,7 +86,7 @@ namespace Ryujinx.HLE.HOS
switch (mode) switch (mode)
{ {
case MemoryManagerMode.SoftwarePageTable: case MemoryManagerMode.SoftwarePageTable:
var memoryManager = new MemoryManager(context.Memory, addressSpaceSize, invalidAccessHandler); MemoryManager memoryManager = new MemoryManager(context.Memory, addressSpaceSize, invalidAccessHandler);
processContext = new ArmProcessContext<MemoryManager>(pid, cpuEngine, _gpu, memoryManager, addressSpaceSize, for64Bit); processContext = new ArmProcessContext<MemoryManager>(pid, cpuEngine, _gpu, memoryManager, addressSpaceSize, for64Bit);
break; break;
@ -94,7 +94,7 @@ namespace Ryujinx.HLE.HOS
case MemoryManagerMode.HostMappedUnsafe: case MemoryManagerMode.HostMappedUnsafe:
if (addressSpace == null) if (addressSpace == null)
{ {
var memoryManagerHostTracked = new MemoryManagerHostTracked(context.Memory, addressSpaceSize, mode == MemoryManagerMode.HostMappedUnsafe, invalidAccessHandler); MemoryManagerHostTracked memoryManagerHostTracked = new MemoryManagerHostTracked(context.Memory, addressSpaceSize, mode == MemoryManagerMode.HostMappedUnsafe, invalidAccessHandler);
processContext = new ArmProcessContext<MemoryManagerHostTracked>(pid, cpuEngine, _gpu, memoryManagerHostTracked, addressSpaceSize, for64Bit); processContext = new ArmProcessContext<MemoryManagerHostTracked>(pid, cpuEngine, _gpu, memoryManagerHostTracked, addressSpaceSize, for64Bit);
} }
else else
@ -104,7 +104,7 @@ namespace Ryujinx.HLE.HOS
Logger.Warning?.Print(LogClass.Emulation, $"Allocated address space (0x{addressSpace.AddressSpaceSize:X}) is smaller than guest application requirements (0x{addressSpaceSize:X})"); Logger.Warning?.Print(LogClass.Emulation, $"Allocated address space (0x{addressSpace.AddressSpaceSize:X}) is smaller than guest application requirements (0x{addressSpaceSize:X})");
} }
var memoryManagerHostMapped = new MemoryManagerHostMapped(addressSpace, mode == MemoryManagerMode.HostMappedUnsafe, invalidAccessHandler); MemoryManagerHostMapped memoryManagerHostMapped = new MemoryManagerHostMapped(addressSpace, mode == MemoryManagerMode.HostMappedUnsafe, invalidAccessHandler);
processContext = new ArmProcessContext<MemoryManagerHostMapped>(pid, cpuEngine, _gpu, memoryManagerHostMapped, addressSpace.AddressSpaceSize, for64Bit); processContext = new ArmProcessContext<MemoryManagerHostMapped>(pid, cpuEngine, _gpu, memoryManagerHostMapped, addressSpace.AddressSpaceSize, for64Bit);
} }
break; break;

View File

@ -32,7 +32,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
private bool ConsumeIf(string toConsume) private bool ConsumeIf(string toConsume)
{ {
var mangledPart = Mangled.AsSpan(_position); ReadOnlySpan<char> mangledPart = Mangled.AsSpan(_position);
if (mangledPart.StartsWith(toConsume.AsSpan())) if (mangledPart.StartsWith(toConsume.AsSpan()))
{ {

View File

@ -154,11 +154,11 @@ namespace Ryujinx.HLE.HOS
timePageList.AddRange(timePa, TimeSize / KPageTableBase.PageSize); timePageList.AddRange(timePa, TimeSize / KPageTableBase.PageSize);
appletCaptureBufferPageList.AddRange(appletCaptureBufferPa, AppletCaptureBufferSize / KPageTableBase.PageSize); appletCaptureBufferPageList.AddRange(appletCaptureBufferPa, AppletCaptureBufferSize / KPageTableBase.PageSize);
var hidStorage = new SharedMemoryStorage(KernelContext, hidPageList); SharedMemoryStorage hidStorage = new SharedMemoryStorage(KernelContext, hidPageList);
var fontStorage = new SharedMemoryStorage(KernelContext, fontPageList); SharedMemoryStorage fontStorage = new SharedMemoryStorage(KernelContext, fontPageList);
var iirsStorage = new SharedMemoryStorage(KernelContext, iirsPageList); SharedMemoryStorage iirsStorage = new SharedMemoryStorage(KernelContext, iirsPageList);
var timeStorage = new SharedMemoryStorage(KernelContext, timePageList); SharedMemoryStorage timeStorage = new SharedMemoryStorage(KernelContext, timePageList);
var appletCaptureBufferStorage = new SharedMemoryStorage(KernelContext, appletCaptureBufferPageList); SharedMemoryStorage appletCaptureBufferStorage = new SharedMemoryStorage(KernelContext, appletCaptureBufferPageList);
HidStorage = hidStorage; HidStorage = hidStorage;
@ -265,7 +265,7 @@ namespace Ryujinx.HLE.HOS
HorizonFsClient fsClient = new(this); HorizonFsClient fsClient = new(this);
ServiceTable = new ServiceTable(); ServiceTable = new ServiceTable();
var services = ServiceTable.GetServices(new HorizonOptions IEnumerable<ServiceEntry> services = ServiceTable.GetServices(new HorizonOptions
(Device.Configuration.IgnoreMissingServices, (Device.Configuration.IgnoreMissingServices,
LibHacHorizonManager.BcatClient, LibHacHorizonManager.BcatClient,
fsClient, fsClient,
@ -273,7 +273,7 @@ namespace Ryujinx.HLE.HOS
Device.AudioDeviceDriver, Device.AudioDeviceDriver,
TickSource)); TickSource));
foreach (var service in services) foreach (ServiceEntry service in services)
{ {
const ProcessCreationFlags Flags = const ProcessCreationFlags Flags =
ProcessCreationFlags.EnableAslr | ProcessCreationFlags.EnableAslr |
@ -304,7 +304,7 @@ namespace Ryujinx.HLE.HOS
public bool LoadKip(string kipPath) public bool LoadKip(string kipPath)
{ {
using var kipFile = new SharedRef<IStorage>(new LocalStorage(kipPath, FileAccess.Read)); using SharedRef<IStorage> kipFile = new SharedRef<IStorage>(new LocalStorage(kipPath, FileAccess.Read));
return ProcessLoaderHelper.LoadKip(KernelContext, new KipExecutable(in kipFile)); return ProcessLoaderHelper.LoadKip(KernelContext, new KipExecutable(in kipFile));
} }

View File

@ -55,8 +55,8 @@ namespace Ryujinx.HLE.HOS
Nca nca = new(_system.KeySet, ncaStorage); Nca nca = new(_system.KeySet, ncaStorage);
using var ncaFileSystem = nca.OpenFileSystem(NcaSectionType.Data, _system.FsIntegrityCheckLevel); using IFileSystem ncaFileSystem = nca.OpenFileSystem(NcaSectionType.Data, _system.FsIntegrityCheckLevel);
using var ncaFsRef = new UniqueRef<IFileSystem>(ncaFileSystem); using UniqueRef<IFileSystem> ncaFsRef = new UniqueRef<IFileSystem>(ncaFileSystem);
Result result = _fsClient.Register(mountName.ToU8Span(), ref ncaFsRef.Ref).ToHorizonResult(); Result result = _fsClient.Register(mountName.ToU8Span(), ref ncaFsRef.Ref).ToHorizonResult();
if (result.IsFailure) if (result.IsFailure)
@ -86,7 +86,7 @@ namespace Ryujinx.HLE.HOS
public Result OpenFile(out FileHandle handle, string path, OpenMode openMode) public Result OpenFile(out FileHandle handle, string path, OpenMode openMode)
{ {
var result = _fsClient.OpenFile(out var libhacHandle, path.ToU8Span(), (LibHac.Fs.OpenMode)openMode); LibHac.Result result = _fsClient.OpenFile(out LibHac.Fs.FileHandle libhacHandle, path.ToU8Span(), (LibHac.Fs.OpenMode)openMode);
handle = new(libhacHandle); handle = new(libhacHandle);
return result.ToHorizonResult(); return result.ToHorizonResult();

View File

@ -16,7 +16,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory
{ {
for (int i = 0; i < MemoryRegions.Length; i++) for (int i = 0; i < MemoryRegions.Length; i++)
{ {
var region = MemoryRegions[i]; KMemoryRegionManager region = MemoryRegions[i];
if (address >= region.Address && address < region.EndAddr) if (address >= region.Address && address < region.EndAddr)
{ {
@ -41,7 +41,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory
{ {
while (pagesCount != 0) while (pagesCount != 0)
{ {
var region = GetMemoryRegion(address); KMemoryRegionManager region = GetMemoryRegion(address);
ulong countToProcess = Math.Min(pagesCount, region.GetPageOffsetFromEnd(address)); ulong countToProcess = Math.Min(pagesCount, region.GetPageOffsetFromEnd(address));

View File

@ -40,7 +40,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory
if (result == Result.Success) if (result == Result.Success)
{ {
foreach (var node in pageList) foreach (KPageNode node in pageList)
{ {
IncrementPagesReferenceCount(node.Address, node.PagesCount); IncrementPagesReferenceCount(node.Address, node.PagesCount);
} }

View File

@ -162,7 +162,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory
public bool ClearRange(ulong offset, int count) public bool ClearRange(ulong offset, int count)
{ {
int depth = HighestDepthIndex; int depth = HighestDepthIndex;
var bits = _bitStorages[depth]; ArraySegment<ulong> bits = _bitStorages[depth];
int bitInd = (int)(offset / UInt64BitSize); int bitInd = (int)(offset / UInt64BitSize);

View File

@ -105,7 +105,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory
_blocksCount = blockShifts.Length; _blocksCount = blockShifts.Length;
_blocks = new Block[_memoryBlockPageShifts.Length]; _blocks = new Block[_memoryBlockPageShifts.Length];
var currBitmapStorage = new ArraySegment<ulong>(new ulong[CalculateManagementOverheadSize(size, blockShifts)]); ArraySegment<ulong> currBitmapStorage = new ArraySegment<ulong>(new ulong[CalculateManagementOverheadSize(size, blockShifts)]);
for (int i = 0; i < blockShifts.Length; i++) for (int i = 0; i < blockShifts.Length; i++)
{ {

View File

@ -70,7 +70,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory
public void IncrementPagesReferenceCount(KMemoryManager manager) public void IncrementPagesReferenceCount(KMemoryManager manager)
{ {
foreach (var node in this) foreach (KPageNode node in this)
{ {
manager.IncrementPagesReferenceCount(node.Address, node.PagesCount); manager.IncrementPagesReferenceCount(node.Address, node.PagesCount);
} }
@ -78,7 +78,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory
public void DecrementPagesReferenceCount(KMemoryManager manager) public void DecrementPagesReferenceCount(KMemoryManager manager)
{ {
foreach (var node in this) foreach (KPageNode node in this)
{ {
manager.DecrementPagesReferenceCount(node.Address, node.PagesCount); manager.DecrementPagesReferenceCount(node.Address, node.PagesCount);
} }

View File

@ -28,8 +28,8 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory
/// <inheritdoc/> /// <inheritdoc/>
protected override void GetPhysicalRegions(ulong va, ulong size, KPageList pageList) protected override void GetPhysicalRegions(ulong va, ulong size, KPageList pageList)
{ {
var ranges = _cpuMemory.GetPhysicalRegions(va, size); IEnumerable<MemoryRange> ranges = _cpuMemory.GetPhysicalRegions(va, size);
foreach (var range in ranges) foreach (MemoryRange range in ranges)
{ {
pageList.AddRange(range.Address + DramMemoryMap.DramBase, range.Size / PageSize); pageList.AddRange(range.Address + DramMemoryMap.DramBase, range.Size / PageSize);
} }
@ -143,11 +143,11 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory
bool shouldFillPages, bool shouldFillPages,
byte fillValue) byte fillValue)
{ {
using var scopedPageList = new KScopedPageList(Context.MemoryManager, pageList); using KScopedPageList scopedPageList = new KScopedPageList(Context.MemoryManager, pageList);
ulong currentVa = address; ulong currentVa = address;
foreach (var pageNode in pageList) foreach (KPageNode pageNode in pageList)
{ {
ulong addr = pageNode.Address - DramMemoryMap.DramBase; ulong addr = pageNode.Address - DramMemoryMap.DramBase;
ulong size = pageNode.PagesCount * PageSize; ulong size = pageNode.PagesCount * PageSize;
@ -188,16 +188,16 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory
} }
} }
using var scopedPageList = new KScopedPageList(Context.MemoryManager, pageList); using KScopedPageList scopedPageList = new KScopedPageList(Context.MemoryManager, pageList);
foreach (var pageNode in pageList) foreach (KPageNode pageNode in pageList)
{ {
Context.CommitMemory(pageNode.Address - DramMemoryMap.DramBase, pageNode.PagesCount * PageSize); Context.CommitMemory(pageNode.Address - DramMemoryMap.DramBase, pageNode.PagesCount * PageSize);
} }
ulong offset = 0; ulong offset = 0;
foreach (var region in regions) foreach (HostMemoryRange region in regions)
{ {
_cpuMemory.MapForeign(va + offset, region.Address, region.Size); _cpuMemory.MapForeign(va + offset, region.Address, region.Size);
@ -214,9 +214,9 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory
{ {
KPageList pagesToClose = new(); KPageList pagesToClose = new();
var regions = _cpuMemory.GetPhysicalRegions(address, pagesCount * PageSize); IEnumerable<MemoryRange> regions = _cpuMemory.GetPhysicalRegions(address, pagesCount * PageSize);
foreach (var region in regions) foreach (MemoryRange region in regions)
{ {
ulong pa = region.Address + DramMemoryMap.DramBase; ulong pa = region.Address + DramMemoryMap.DramBase;
if (DramMemoryMap.IsHeapPhysicalAddress(pa)) if (DramMemoryMap.IsHeapPhysicalAddress(pa))

View File

@ -617,7 +617,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory
return result; return result;
} }
using var _ = new OnScopeExit(() => pageList.DecrementPagesReferenceCount(Context.MemoryManager)); using OnScopeExit _ = new OnScopeExit(() => pageList.DecrementPagesReferenceCount(Context.MemoryManager));
return MapPages(address, pageList, permission, MemoryMapFlags.Private); return MapPages(address, pageList, permission, MemoryMapFlags.Private);
} }
@ -769,7 +769,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory
Result result = region.AllocatePages(out KPageList pageList, pagesCount); Result result = region.AllocatePages(out KPageList pageList, pagesCount);
using var _ = new OnScopeExit(() => pageList.DecrementPagesReferenceCount(Context.MemoryManager)); using OnScopeExit _ = new OnScopeExit(() => pageList.DecrementPagesReferenceCount(Context.MemoryManager));
void CleanUpForError() void CleanUpForError()
{ {
@ -1341,7 +1341,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory
Result result = region.AllocatePages(out KPageList pageList, remainingPages); Result result = region.AllocatePages(out KPageList pageList, remainingPages);
using var _ = new OnScopeExit(() => pageList.DecrementPagesReferenceCount(Context.MemoryManager)); using OnScopeExit _ = new OnScopeExit(() => pageList.DecrementPagesReferenceCount(Context.MemoryManager));
void CleanUpForError() void CleanUpForError()
{ {
@ -1867,7 +1867,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory
ulong dstLastPagePa = 0; ulong dstLastPagePa = 0;
ulong currentVa = va; ulong currentVa = va;
using var _ = new OnScopeExit(() => using OnScopeExit _ = new OnScopeExit(() =>
{ {
if (dstFirstPagePa != 0) if (dstFirstPagePa != 0)
{ {
@ -1928,7 +1928,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory
Context.Memory.Fill(GetDramAddressFromPa(dstFirstPagePa), unusedSizeBefore, (byte)_ipcFillValue); Context.Memory.Fill(GetDramAddressFromPa(dstFirstPagePa), unusedSizeBefore, (byte)_ipcFillValue);
ulong copySize = addressRounded <= endAddr ? addressRounded - address : size; ulong copySize = addressRounded <= endAddr ? addressRounded - address : size;
var data = srcPageTable.GetReadOnlySequence(addressTruncated + unusedSizeBefore, (int)copySize); ReadOnlySequence<byte> data = srcPageTable.GetReadOnlySequence(addressTruncated + unusedSizeBefore, (int)copySize);
((IWritableBlock)Context.Memory).Write(GetDramAddressFromPa(dstFirstPagePa + unusedSizeBefore), data); ((IWritableBlock)Context.Memory).Write(GetDramAddressFromPa(dstFirstPagePa + unusedSizeBefore), data);
@ -1994,7 +1994,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory
if (send) if (send)
{ {
ulong copySize = endAddr - endAddrTruncated; ulong copySize = endAddr - endAddrTruncated;
var data = srcPageTable.GetReadOnlySequence(endAddrTruncated, (int)copySize); ReadOnlySequence<byte> data = srcPageTable.GetReadOnlySequence(endAddrTruncated, (int)copySize);
((IWritableBlock)Context.Memory).Write(GetDramAddressFromPa(dstLastPagePa), data); ((IWritableBlock)Context.Memory).Write(GetDramAddressFromPa(dstLastPagePa), data);

View File

@ -1,3 +1,4 @@
using Ryujinx.Cpu;
using Ryujinx.HLE.HOS.Diagnostics.Demangler; using Ryujinx.HLE.HOS.Diagnostics.Demangler;
using Ryujinx.HLE.HOS.Kernel.Memory; using Ryujinx.HLE.HOS.Kernel.Memory;
using Ryujinx.HLE.HOS.Kernel.Threading; using Ryujinx.HLE.HOS.Kernel.Threading;
@ -47,7 +48,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Process
{ {
EnsureLoaded(); EnsureLoaded();
var context = thread.Context; IExecutionContext context = thread.Context;
StringBuilder trace = new(); StringBuilder trace = new();
@ -109,13 +110,13 @@ namespace Ryujinx.HLE.HOS.Kernel.Process
{ {
EnsureLoaded(); EnsureLoaded();
var context = thread.Context; IExecutionContext context = thread.Context;
StringBuilder sb = new(); StringBuilder sb = new();
string GetReg(int x) string GetReg(int x)
{ {
var v = x == 32 ? context.Pc : context.GetX(x); ulong v = x == 32 ? context.Pc : context.GetX(x);
if (!AnalyzePointer(out PointerInfo info, v, thread)) if (!AnalyzePointer(out PointerInfo info, v, thread))
{ {
return $"0x{v:x16}"; return $"0x{v:x16}";
@ -251,7 +252,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Process
info = default; info = default;
ulong sp = thread.Context.GetX(31); ulong sp = thread.Context.GetX(31);
var memoryInfo = _owner.MemoryManager.QueryMemory(address); KMemoryInfo memoryInfo = _owner.MemoryManager.QueryMemory(address);
MemoryState memoryState = memoryInfo.State; MemoryState memoryState = memoryInfo.State;
if (!memoryState.HasFlag(MemoryState.Stack)) // Is this pointer within the stack? if (!memoryState.HasFlag(MemoryState.Stack)) // Is this pointer within the stack?

View File

@ -105,7 +105,7 @@ namespace Ryujinx.HLE.HOS.Kernel.SupervisorCall
KProcess process = new(_context); KProcess process = new(_context);
using var _ = new OnScopeExit(process.DecrementReferenceCount); using OnScopeExit _ = new OnScopeExit(process.DecrementReferenceCount);
KResourceLimit resourceLimit; KResourceLimit resourceLimit;
@ -1425,7 +1425,7 @@ namespace Ryujinx.HLE.HOS.Kernel.SupervisorCall
KCodeMemory codeMemory = new(_context); KCodeMemory codeMemory = new(_context);
using var _ = new OnScopeExit(codeMemory.DecrementReferenceCount); using OnScopeExit _ = new OnScopeExit(codeMemory.DecrementReferenceCount);
KProcess currentProcess = KernelStatic.GetCurrentProcess(); KProcess currentProcess = KernelStatic.GetCurrentProcess();
@ -2854,7 +2854,7 @@ namespace Ryujinx.HLE.HOS.Kernel.SupervisorCall
KThread currentThread = KernelStatic.GetCurrentThread(); KThread currentThread = KernelStatic.GetCurrentThread();
var syncObjs = new Span<KSynchronizationObject>(currentThread.WaitSyncObjects)[..handles.Length]; Span<KSynchronizationObject> syncObjs = new Span<KSynchronizationObject>(currentThread.WaitSyncObjects)[..handles.Length];
if (handles.Length != 0) if (handles.Length != 0)
{ {

View File

@ -562,8 +562,8 @@ namespace Ryujinx.HLE.HOS.Kernel.Threading
Action<KThread> removeCallback, Action<KThread> removeCallback,
Func<KThread, bool> predicate) Func<KThread, bool> predicate)
{ {
var candidates = threads.Where(predicate).OrderBy(x => x.DynamicPriority); IOrderedEnumerable<KThread> candidates = threads.Where(predicate).OrderBy(x => x.DynamicPriority);
var toSignal = (count > 0 ? candidates.Take(count) : candidates).ToArray(); KThread[] toSignal = (count > 0 ? candidates.Take(count) : candidates).ToArray();
foreach (KThread thread in toSignal) foreach (KThread thread in toSignal)
{ {

View File

@ -127,7 +127,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Threading
public KThread ScheduledThreadsElementAtOrDefault(int core, int index) public KThread ScheduledThreadsElementAtOrDefault(int core, int index)
{ {
int currentIndex = 0; int currentIndex = 0;
foreach (var scheduledThread in ScheduledThreads(core)) foreach (KThread scheduledThread in ScheduledThreads(core))
{ {
if (currentIndex == index) if (currentIndex == index)
{ {
@ -144,7 +144,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Threading
public KThread ScheduledThreadsWithDynamicPriorityFirstOrDefault(int core, int dynamicPriority) public KThread ScheduledThreadsWithDynamicPriorityFirstOrDefault(int core, int dynamicPriority)
{ {
foreach (var scheduledThread in ScheduledThreads(core)) foreach (KThread scheduledThread in ScheduledThreads(core))
{ {
if (scheduledThread.DynamicPriority == dynamicPriority) if (scheduledThread.DynamicPriority == dynamicPriority)
{ {

View File

@ -1232,7 +1232,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Threading
{ {
if (_schedulerWaitEvent == null) if (_schedulerWaitEvent == null)
{ {
var schedulerWaitEvent = new ManualResetEvent(false); ManualResetEvent schedulerWaitEvent = new ManualResetEvent(false);
if (Interlocked.Exchange(ref _schedulerWaitEvent, schedulerWaitEvent) == null) if (Interlocked.Exchange(ref _schedulerWaitEvent, schedulerWaitEvent) == null)
{ {

View File

@ -54,7 +54,7 @@ namespace Ryujinx.HLE.HOS
public void InitializeFsServer(VirtualFileSystem virtualFileSystem) public void InitializeFsServer(VirtualFileSystem virtualFileSystem)
{ {
virtualFileSystem.InitializeFsServer(Server, out var fsClient); virtualFileSystem.InitializeFsServer(Server, out HorizonClient fsClient);
FsClient = fsClient; FsClient = fsClient;
} }

View File

@ -3,6 +3,7 @@ using LibHac.Fs;
using LibHac.Fs.Fsa; using LibHac.Fs.Fsa;
using LibHac.FsSystem; using LibHac.FsSystem;
using LibHac.Loader; using LibHac.Loader;
using LibHac.Tools.Fs;
using LibHac.Tools.FsSystem; using LibHac.Tools.FsSystem;
using LibHac.Tools.FsSystem.RomFs; using LibHac.Tools.FsSystem.RomFs;
using Ryujinx.Common.Configuration; using Ryujinx.Common.Configuration;
@ -143,7 +144,7 @@ namespace Ryujinx.HLE.HOS
private static string EnsureBaseDirStructure(string modsBasePath) private static string EnsureBaseDirStructure(string modsBasePath)
{ {
var modsDir = new DirectoryInfo(modsBasePath); DirectoryInfo modsDir = new DirectoryInfo(modsBasePath);
modsDir.CreateSubdirectory(AmsContentsDir); modsDir.CreateSubdirectory(AmsContentsDir);
modsDir.CreateSubdirectory(AmsNsoPatchDir); modsDir.CreateSubdirectory(AmsNsoPatchDir);
@ -161,23 +162,23 @@ namespace Ryujinx.HLE.HOS
{ {
System.Text.StringBuilder types = new(); System.Text.StringBuilder types = new();
foreach (var modDir in dir.EnumerateDirectories()) foreach (DirectoryInfo modDir in dir.EnumerateDirectories())
{ {
types.Clear(); types.Clear();
Mod<DirectoryInfo> mod = new(string.Empty, null, true); Mod<DirectoryInfo> mod = new(string.Empty, null, true);
if (StrEquals(RomfsDir, modDir.Name)) if (StrEquals(RomfsDir, modDir.Name))
{ {
var modData = modMetadata.Mods.FirstOrDefault(x => modDir.FullName.Contains(x.Path)); Mod modData = modMetadata.Mods.FirstOrDefault(x => modDir.FullName.Contains(x.Path));
var enabled = modData?.Enabled ?? true; bool enabled = modData?.Enabled ?? true;
mods.RomfsDirs.Add(mod = new Mod<DirectoryInfo>(dir.Name, modDir, enabled)); mods.RomfsDirs.Add(mod = new Mod<DirectoryInfo>(dir.Name, modDir, enabled));
types.Append('R'); types.Append('R');
} }
else if (StrEquals(ExefsDir, modDir.Name)) else if (StrEquals(ExefsDir, modDir.Name))
{ {
var modData = modMetadata.Mods.FirstOrDefault(x => modDir.FullName.Contains(x.Path)); Mod modData = modMetadata.Mods.FirstOrDefault(x => modDir.FullName.Contains(x.Path));
var enabled = modData?.Enabled ?? true; bool enabled = modData?.Enabled ?? true;
mods.ExefsDirs.Add(mod = new Mod<DirectoryInfo>(dir.Name, modDir, enabled)); mods.ExefsDirs.Add(mod = new Mod<DirectoryInfo>(dir.Name, modDir, enabled));
types.Append('E'); types.Append('E');
@ -200,8 +201,8 @@ namespace Ryujinx.HLE.HOS
public static string GetApplicationDir(string modsBasePath, string applicationId) public static string GetApplicationDir(string modsBasePath, string applicationId)
{ {
var contentsDir = new DirectoryInfo(Path.Combine(modsBasePath, AmsContentsDir)); DirectoryInfo contentsDir = new DirectoryInfo(Path.Combine(modsBasePath, AmsContentsDir));
var applicationModsPath = FindApplicationDir(contentsDir, applicationId); DirectoryInfo applicationModsPath = FindApplicationDir(contentsDir, applicationId);
if (applicationModsPath == null) if (applicationModsPath == null)
{ {
@ -243,7 +244,7 @@ namespace Ryujinx.HLE.HOS
return; return;
} }
foreach (var modDir in patchDir.EnumerateDirectories()) foreach (DirectoryInfo modDir in patchDir.EnumerateDirectories())
{ {
patches.Add(new Mod<DirectoryInfo>(modDir.Name, modDir, true)); patches.Add(new Mod<DirectoryInfo>(modDir.Name, modDir, true));
Logger.Info?.Print(LogClass.ModLoader, $"Found {type} patch '{modDir.Name}'"); Logger.Info?.Print(LogClass.ModLoader, $"Found {type} patch '{modDir.Name}'");
@ -272,11 +273,11 @@ namespace Ryujinx.HLE.HOS
} }
} }
var fsFile = new FileInfo(Path.Combine(applicationDir.FullName, RomfsContainer)); FileInfo fsFile = new FileInfo(Path.Combine(applicationDir.FullName, RomfsContainer));
if (fsFile.Exists) if (fsFile.Exists)
{ {
var modData = modMetadata.Mods.FirstOrDefault(x => fsFile.FullName.Contains(x.Path)); Mod modData = modMetadata.Mods.FirstOrDefault(x => fsFile.FullName.Contains(x.Path));
var enabled = modData == null || modData.Enabled; bool enabled = modData == null || modData.Enabled;
mods.RomfsContainers.Add(new Mod<FileInfo>($"<{applicationDir.Name} RomFs>", fsFile, enabled)); mods.RomfsContainers.Add(new Mod<FileInfo>($"<{applicationDir.Name} RomFs>", fsFile, enabled));
} }
@ -284,8 +285,8 @@ namespace Ryujinx.HLE.HOS
fsFile = new FileInfo(Path.Combine(applicationDir.FullName, ExefsContainer)); fsFile = new FileInfo(Path.Combine(applicationDir.FullName, ExefsContainer));
if (fsFile.Exists) if (fsFile.Exists)
{ {
var modData = modMetadata.Mods.FirstOrDefault(x => fsFile.FullName.Contains(x.Path)); Mod modData = modMetadata.Mods.FirstOrDefault(x => fsFile.FullName.Contains(x.Path));
var enabled = modData == null || modData.Enabled; bool enabled = modData == null || modData.Enabled;
mods.ExefsContainers.Add(new Mod<FileInfo>($"<{applicationDir.Name} ExeFs>", fsFile, enabled)); mods.ExefsContainers.Add(new Mod<FileInfo>($"<{applicationDir.Name} ExeFs>", fsFile, enabled));
} }
@ -302,7 +303,7 @@ namespace Ryujinx.HLE.HOS
Logger.Info?.Print(LogClass.ModLoader, $"Searching mods for {((applicationId & 0x1000) != 0 ? "DLC" : "Application")} {applicationId:X16} in \"{contentsDir.FullName}\""); Logger.Info?.Print(LogClass.ModLoader, $"Searching mods for {((applicationId & 0x1000) != 0 ? "DLC" : "Application")} {applicationId:X16} in \"{contentsDir.FullName}\"");
var applicationDir = FindApplicationDir(contentsDir, $"{applicationId:x16}"); DirectoryInfo applicationDir = FindApplicationDir(contentsDir, $"{applicationId:x16}");
if (applicationDir != null) if (applicationDir != null)
{ {
@ -429,9 +430,9 @@ namespace Ryujinx.HLE.HOS
return false; return false;
} }
foreach (var path in searchDirPaths) foreach (string path in searchDirPaths)
{ {
var searchDir = new DirectoryInfo(path); DirectoryInfo searchDir = new DirectoryInfo(path);
if (!searchDir.Exists) if (!searchDir.Exists)
{ {
Logger.Warning?.Print(LogClass.ModLoader, $"Mod Search Dir '{searchDir.FullName}' doesn't exist"); Logger.Warning?.Print(LogClass.ModLoader, $"Mod Search Dir '{searchDir.FullName}' doesn't exist");
@ -440,7 +441,7 @@ namespace Ryujinx.HLE.HOS
if (!TryQuery(searchDir, patches, modCaches)) if (!TryQuery(searchDir, patches, modCaches))
{ {
foreach (var subdir in searchDir.EnumerateDirectories()) foreach (DirectoryInfo subdir in searchDir.EnumerateDirectories())
{ {
TryQuery(subdir, patches, modCaches); TryQuery(subdir, patches, modCaches);
} }
@ -469,14 +470,14 @@ namespace Ryujinx.HLE.HOS
return baseStorage; return baseStorage;
} }
var fileSet = new HashSet<string>(); HashSet<string> fileSet = new HashSet<string>();
var builder = new RomFsBuilder(); RomFsBuilder builder = new RomFsBuilder();
int count = 0; int count = 0;
Logger.Info?.Print(LogClass.ModLoader, $"Applying RomFS mods for Application {applicationId:X16}"); Logger.Info?.Print(LogClass.ModLoader, $"Applying RomFS mods for Application {applicationId:X16}");
// Prioritize loose files first // Prioritize loose files first
foreach (var mod in mods.RomfsDirs) foreach (Mod<DirectoryInfo> mod in mods.RomfsDirs)
{ {
if (!mod.Enabled) if (!mod.Enabled)
{ {
@ -491,7 +492,7 @@ namespace Ryujinx.HLE.HOS
} }
// Then files inside images // Then files inside images
foreach (var mod in mods.RomfsContainers) foreach (Mod<FileInfo> mod in mods.RomfsContainers)
{ {
if (!mod.Enabled) if (!mod.Enabled)
{ {
@ -516,12 +517,12 @@ namespace Ryujinx.HLE.HOS
Logger.Info?.Print(LogClass.ModLoader, $"Replaced {fileSet.Count} file(s) over {count} mod(s). Processing base storage..."); Logger.Info?.Print(LogClass.ModLoader, $"Replaced {fileSet.Count} file(s) over {count} mod(s). Processing base storage...");
// And finally, the base romfs // And finally, the base romfs
var baseRom = new RomFsFileSystem(baseStorage); RomFsFileSystem baseRom = new RomFsFileSystem(baseStorage);
foreach (var entry in baseRom.EnumerateEntries() foreach (DirectoryEntryEx entry in baseRom.EnumerateEntries()
.Where(f => f.Type == DirectoryEntryType.File && !fileSet.Contains(f.FullPath)) .Where(f => f.Type == DirectoryEntryType.File && !fileSet.Contains(f.FullPath))
.OrderBy(f => f.FullPath, StringComparer.Ordinal)) .OrderBy(f => f.FullPath, StringComparer.Ordinal))
{ {
using var file = new UniqueRef<IFile>(); using UniqueRef<IFile> file = new UniqueRef<IFile>();
baseRom.OpenFile(ref file.Ref, entry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); baseRom.OpenFile(ref file.Ref, entry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
builder.AddFile(entry.FullPath, file.Release()); builder.AddFile(entry.FullPath, file.Release());
@ -536,12 +537,12 @@ namespace Ryujinx.HLE.HOS
private static void AddFiles(IFileSystem fs, string modName, string rootPath, ISet<string> fileSet, RomFsBuilder builder) private static void AddFiles(IFileSystem fs, string modName, string rootPath, ISet<string> fileSet, RomFsBuilder builder)
{ {
foreach (var entry in fs.EnumerateEntries() foreach (DirectoryEntryEx entry in fs.EnumerateEntries()
.AsParallel() .AsParallel()
.Where(f => f.Type == DirectoryEntryType.File) .Where(f => f.Type == DirectoryEntryType.File)
.OrderBy(f => f.FullPath, StringComparer.Ordinal)) .OrderBy(f => f.FullPath, StringComparer.Ordinal))
{ {
var file = new LazyFile(entry.FullPath, rootPath, fs); LazyFile file = new LazyFile(entry.FullPath, rootPath, fs);
if (fileSet.Add(entry.FullPath)) if (fileSet.Add(entry.FullPath))
{ {
@ -568,7 +569,7 @@ namespace Ryujinx.HLE.HOS
Logger.Info?.Print(LogClass.ModLoader, "Using replacement ExeFS partition"); Logger.Info?.Print(LogClass.ModLoader, "Using replacement ExeFS partition");
var pfs = new PartitionFileSystem(); PartitionFileSystem pfs = new PartitionFileSystem();
pfs.Initialize(mods.ExefsContainers[0].Path.OpenRead().AsStorage()).ThrowIfFailure(); pfs.Initialize(mods.ExefsContainers[0].Path.OpenRead().AsStorage()).ThrowIfFailure();
exefs = pfs; exefs = pfs;
@ -602,9 +603,9 @@ namespace Ryujinx.HLE.HOS
throw new ArgumentOutOfRangeException(nameof(nsos), nsos.Length, "NSO Count is incorrect"); throw new ArgumentOutOfRangeException(nameof(nsos), nsos.Length, "NSO Count is incorrect");
} }
var exeMods = mods.ExefsDirs; List<Mod<DirectoryInfo>> exeMods = mods.ExefsDirs;
foreach (var mod in exeMods) foreach (Mod<DirectoryInfo> mod in exeMods)
{ {
if (!mod.Enabled) if (!mod.Enabled)
{ {
@ -613,7 +614,7 @@ namespace Ryujinx.HLE.HOS
for (int i = 0; i < ProcessConst.ExeFsPrefixes.Length; ++i) for (int i = 0; i < ProcessConst.ExeFsPrefixes.Length; ++i)
{ {
var nsoName = ProcessConst.ExeFsPrefixes[i]; string nsoName = ProcessConst.ExeFsPrefixes[i];
FileInfo nsoFile = new(Path.Combine(mod.Path.FullName, nsoName)); FileInfo nsoFile = new(Path.Combine(mod.Path.FullName, nsoName));
if (nsoFile.Exists) if (nsoFile.Exists)
@ -665,7 +666,7 @@ namespace Ryujinx.HLE.HOS
internal void ApplyNroPatches(NroExecutable nro) internal void ApplyNroPatches(NroExecutable nro)
{ {
var nroPatches = _patches.NroPatches; List<Mod<DirectoryInfo>> nroPatches = _patches.NroPatches;
if (nroPatches.Count == 0) if (nroPatches.Count == 0)
{ {
@ -707,11 +708,11 @@ namespace Ryujinx.HLE.HOS
return; return;
} }
var cheats = mods.Cheats; List<Cheat> cheats = mods.Cheats;
var processExes = tamperInfo.BuildIds.Zip(tamperInfo.CodeAddresses, (k, v) => new { k, v }) Dictionary<string, ulong> processExes = tamperInfo.BuildIds.Zip(tamperInfo.CodeAddresses, (k, v) => new { k, v })
.ToDictionary(x => x.k[..Math.Min(Cheat.CheatIdSize, x.k.Length)], x => x.v); .ToDictionary(x => x.k[..Math.Min(Cheat.CheatIdSize, x.k.Length)], x => x.v);
foreach (var cheat in cheats) foreach (Cheat cheat in cheats)
{ {
string cheatId = Path.GetFileNameWithoutExtension(cheat.Path.Name).ToUpper(); string cheatId = Path.GetFileNameWithoutExtension(cheat.Path.Name).ToUpper();
@ -732,7 +733,7 @@ namespace Ryujinx.HLE.HOS
internal static void EnableCheats(ulong applicationId, TamperMachine tamperMachine) internal static void EnableCheats(ulong applicationId, TamperMachine tamperMachine)
{ {
var contentDirectory = FindApplicationDir(new DirectoryInfo(Path.Combine(GetModsBasePath(), AmsContentsDir)), $"{applicationId:x16}"); DirectoryInfo contentDirectory = FindApplicationDir(new DirectoryInfo(Path.Combine(GetModsBasePath(), AmsContentsDir)), $"{applicationId:x16}");
string enabledCheatsPath = Path.Combine(contentDirectory.FullName, CheatDir, "enabled.txt"); string enabledCheatsPath = Path.Combine(contentDirectory.FullName, CheatDir, "enabled.txt");
if (File.Exists(enabledCheatsPath)) if (File.Exists(enabledCheatsPath))
@ -752,11 +753,11 @@ namespace Ryujinx.HLE.HOS
patches[i] = new MemPatch(); patches[i] = new MemPatch();
} }
var buildIds = new List<string>(programs.Length); List<string> buildIds = new List<string>(programs.Length);
foreach (IExecutable p in programs) foreach (IExecutable p in programs)
{ {
var buildId = p switch string buildId = p switch
{ {
NsoExecutable nso => Convert.ToHexString(nso.BuildId.ItemsRo.ToArray()).TrimEnd('0'), NsoExecutable nso => Convert.ToHexString(nso.BuildId.ItemsRo.ToArray()).TrimEnd('0'),
NroExecutable nro => Convert.ToHexString(nro.Header.BuildId).TrimEnd('0'), NroExecutable nro => Convert.ToHexString(nro.Header.BuildId).TrimEnd('0'),
@ -768,15 +769,15 @@ namespace Ryujinx.HLE.HOS
int GetIndex(string buildId) => buildIds.FindIndex(id => id == buildId); // O(n) but list is small int GetIndex(string buildId) => buildIds.FindIndex(id => id == buildId); // O(n) but list is small
// Collect patches // Collect patches
foreach (var mod in mods) foreach (Mod<DirectoryInfo> mod in mods)
{ {
if (!mod.Enabled) if (!mod.Enabled)
{ {
continue; continue;
} }
var patchDir = mod.Path; DirectoryInfo patchDir = mod.Path;
foreach (var patchFile in patchDir.EnumerateFiles()) foreach (FileInfo patchFile in patchDir.EnumerateFiles())
{ {
if (StrEquals(".ips", patchFile.Extension)) // IPS|IPS32 if (StrEquals(".ips", patchFile.Extension)) // IPS|IPS32
{ {
@ -791,18 +792,18 @@ namespace Ryujinx.HLE.HOS
Logger.Info?.Print(LogClass.ModLoader, $"Matching IPS patch '{patchFile.Name}' in '{mod.Name}' bid={buildId}"); Logger.Info?.Print(LogClass.ModLoader, $"Matching IPS patch '{patchFile.Name}' in '{mod.Name}' bid={buildId}");
using var fs = patchFile.OpenRead(); using FileStream fs = patchFile.OpenRead();
using var reader = new BinaryReader(fs); using BinaryReader reader = new BinaryReader(fs);
var patcher = new IpsPatcher(reader); IpsPatcher patcher = new IpsPatcher(reader);
patcher.AddPatches(patches[index]); patcher.AddPatches(patches[index]);
} }
else if (StrEquals(".pchtxt", patchFile.Extension)) // IPSwitch else if (StrEquals(".pchtxt", patchFile.Extension)) // IPSwitch
{ {
using var fs = patchFile.OpenRead(); using FileStream fs = patchFile.OpenRead();
using var reader = new StreamReader(fs); using StreamReader reader = new StreamReader(fs);
var patcher = new IPSwitchPatcher(reader); IPSwitchPatcher patcher = new IPSwitchPatcher(reader);
int index = GetIndex(patcher.BuildId); int index = GetIndex(patcher.BuildId);
if (index == -1) if (index == -1)

View File

@ -191,10 +191,10 @@ namespace Ryujinx.HLE.HOS.Services.Account.Acc
private void DeleteSaveData(UserId userId) private void DeleteSaveData(UserId userId)
{ {
var saveDataFilter = SaveDataFilter.Make(programId: default, saveType: default, SaveDataFilter saveDataFilter = SaveDataFilter.Make(programId: default, saveType: default,
new LibHac.Fs.UserId((ulong)userId.High, (ulong)userId.Low), saveDataId: default, index: default); new LibHac.Fs.UserId((ulong)userId.High, (ulong)userId.Low), saveDataId: default, index: default);
using var saveDataIterator = new UniqueRef<SaveDataIterator>(); using UniqueRef<SaveDataIterator> saveDataIterator = new UniqueRef<SaveDataIterator>();
_horizonClient.Fs.OpenSaveDataIterator(ref saveDataIterator.Ref, SaveDataSpaceId.User, in saveDataFilter).ThrowIfFailure(); _horizonClient.Fs.OpenSaveDataIterator(ref saveDataIterator.Ref, SaveDataSpaceId.User, in saveDataFilter).ThrowIfFailure();

View File

@ -29,7 +29,7 @@ namespace Ryujinx.HLE.HOS.Services.Account.Acc
{ {
ProfilesJson profilesJson = JsonHelper.DeserializeFromFile(_profilesJsonPath, _serializerContext.ProfilesJson); ProfilesJson profilesJson = JsonHelper.DeserializeFromFile(_profilesJsonPath, _serializerContext.ProfilesJson);
foreach (var profile in profilesJson.Profiles) foreach (UserProfileJson profile in profilesJson.Profiles)
{ {
UserProfile addedProfile = new(new UserId(profile.UserId), profile.Name, profile.Image, profile.LastModifiedTimestamp); UserProfile addedProfile = new(new UserId(profile.UserId), profile.Name, profile.Image, profile.LastModifiedTimestamp);
@ -69,7 +69,7 @@ namespace Ryujinx.HLE.HOS.Services.Account.Acc
LastOpened = LastOpened.ToString(), LastOpened = LastOpened.ToString(),
}; };
foreach (var profile in profiles) foreach (KeyValuePair<string, UserProfile> profile in profiles)
{ {
profilesJson.Profiles.Add(new UserProfileJson() profilesJson.Profiles.Add(new UserProfileJson()
{ {

View File

@ -51,7 +51,7 @@ namespace Ryujinx.HLE.HOS.Services.Account.Acc.AccountService
byte[] deviceAccountId = new byte[0x10]; byte[] deviceAccountId = new byte[0x10];
RandomNumberGenerator.Fill(deviceId); RandomNumberGenerator.Fill(deviceId);
var descriptor = new SecurityTokenDescriptor SecurityTokenDescriptor descriptor = new SecurityTokenDescriptor
{ {
Subject = new GenericIdentity(Convert.ToHexString(rawUserId).ToLower()), Subject = new GenericIdentity(Convert.ToHexString(rawUserId).ToLower()),
SigningCredentials = credentials, SigningCredentials = credentials,

View File

@ -214,7 +214,7 @@ namespace Ryujinx.HLE.HOS.Services.Am.AppletAE.AllSystemAppletProxiesService.Sys
_vrModeEnabled = vrModeEnabled; _vrModeEnabled = vrModeEnabled;
using var lblApi = new LblApi(); using LblApi lblApi = new LblApi();
if (vrModeEnabled) if (vrModeEnabled)
{ {

View File

@ -118,10 +118,10 @@ namespace Ryujinx.HLE.HOS.Services.Caps
} }
// NOTE: The saved JPEG file doesn't have the limitation in the extra EXIF data. // NOTE: The saved JPEG file doesn't have the limitation in the extra EXIF data.
using var bitmap = new SKBitmap(new SKImageInfo(1280, 720, SKColorType.Rgba8888)); using SKBitmap bitmap = new SKBitmap(new SKImageInfo(1280, 720, SKColorType.Rgba8888));
Marshal.Copy(screenshotData, 0, bitmap.GetPixels(), screenshotData.Length); Marshal.Copy(screenshotData, 0, bitmap.GetPixels(), screenshotData.Length);
using var data = bitmap.Encode(SKEncodedImageFormat.Jpeg, 80); using SKData data = bitmap.Encode(SKEncodedImageFormat.Jpeg, 80);
using var file = File.OpenWrite(filePath); using FileStream file = File.OpenWrite(filePath);
data.SaveTo(file); data.SaveTo(file);
return ResultCode.Success; return ResultCode.Success;

View File

@ -26,7 +26,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy
try try
{ {
LocalStorage storage = new(pfsPath, FileAccess.Read, FileMode.Open); LocalStorage storage = new(pfsPath, FileAccess.Read, FileMode.Open);
var pfs = new PartitionFileSystem(); PartitionFileSystem pfs = new PartitionFileSystem();
using SharedRef<LibHac.Fs.Fsa.IFileSystem> nsp = new(pfs); using SharedRef<LibHac.Fs.Fsa.IFileSystem> nsp = new(pfs);
pfs.Initialize(storage).ThrowIfFailure(); pfs.Initialize(storage).ThrowIfFailure();
@ -58,7 +58,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy
} }
LibHac.Fs.Fsa.IFileSystem fileSystem = nca.OpenFileSystem(NcaSectionType.Data, context.Device.System.FsIntegrityCheckLevel); LibHac.Fs.Fsa.IFileSystem fileSystem = nca.OpenFileSystem(NcaSectionType.Data, context.Device.System.FsIntegrityCheckLevel);
using var sharedFs = new SharedRef<LibHac.Fs.Fsa.IFileSystem>(fileSystem); using SharedRef<LibHac.Fs.Fsa.IFileSystem> sharedFs = new SharedRef<LibHac.Fs.Fsa.IFileSystem>(fileSystem);
using SharedRef<LibHac.FsSrv.Sf.IFileSystem> adapter = FileSystemInterfaceAdapter.CreateShared(ref sharedFs.Ref, true); using SharedRef<LibHac.FsSrv.Sf.IFileSystem> adapter = FileSystemInterfaceAdapter.CreateShared(ref sharedFs.Ref, true);
@ -99,7 +99,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy
string filename = fullPath.Replace(archivePath.FullName, string.Empty).TrimStart('\\'); string filename = fullPath.Replace(archivePath.FullName, string.Empty).TrimStart('\\');
using var ncaFile = new UniqueRef<LibHac.Fs.Fsa.IFile>(); using UniqueRef<LibHac.Fs.Fsa.IFile> ncaFile = new UniqueRef<LibHac.Fs.Fsa.IFile>();
Result result = nsp.OpenFile(ref ncaFile.Ref, filename.ToU8Span(), OpenMode.Read); Result result = nsp.OpenFile(ref ncaFile.Ref, filename.ToU8Span(), OpenMode.Read);
if (result.IsFailure()) if (result.IsFailure())
@ -122,14 +122,14 @@ namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy
{ {
foreach (DirectoryEntryEx ticketEntry in nsp.EnumerateEntries("/", "*.tik")) foreach (DirectoryEntryEx ticketEntry in nsp.EnumerateEntries("/", "*.tik"))
{ {
using var ticketFile = new UniqueRef<LibHac.Fs.Fsa.IFile>(); using UniqueRef<LibHac.Fs.Fsa.IFile> ticketFile = new UniqueRef<LibHac.Fs.Fsa.IFile>();
Result result = nsp.OpenFile(ref ticketFile.Ref, ticketEntry.FullPath.ToU8Span(), OpenMode.Read); Result result = nsp.OpenFile(ref ticketFile.Ref, ticketEntry.FullPath.ToU8Span(), OpenMode.Read);
if (result.IsSuccess()) if (result.IsSuccess())
{ {
Ticket ticket = new(ticketFile.Get.AsStream()); Ticket ticket = new(ticketFile.Get.AsStream());
var titleKey = ticket.GetTitleKey(keySet); byte[] titleKey = ticket.GetTitleKey(keySet);
if (titleKey != null) if (titleKey != null)
{ {

View File

@ -1,6 +1,7 @@
using LibHac; using LibHac;
using LibHac.Common; using LibHac.Common;
using LibHac.Sf; using LibHac.Sf;
using Ryujinx.Memory;
namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy
{ {
@ -20,7 +21,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy
ulong bufferAddress = context.Request.ReceiveBuff[0].Position; ulong bufferAddress = context.Request.ReceiveBuff[0].Position;
ulong bufferLen = context.Request.ReceiveBuff[0].Size; ulong bufferLen = context.Request.ReceiveBuff[0].Size;
using var region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true); using WritableRegion region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true);
Result result = _baseDirectory.Get.Read(out long entriesRead, new OutBuffer(region.Memory.Span)); Result result = _baseDirectory.Get.Read(out long entriesRead, new OutBuffer(region.Memory.Span));
context.ResponseData.Write(entriesRead); context.ResponseData.Write(entriesRead);

View File

@ -3,6 +3,7 @@ using LibHac.Common;
using LibHac.Fs; using LibHac.Fs;
using LibHac.Sf; using LibHac.Sf;
using Ryujinx.Common; using Ryujinx.Common;
using Ryujinx.Memory;
namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy
{ {
@ -28,7 +29,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy
long offset = context.RequestData.ReadInt64(); long offset = context.RequestData.ReadInt64();
long size = context.RequestData.ReadInt64(); long size = context.RequestData.ReadInt64();
using var region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true); using WritableRegion region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true);
Result result = _baseFile.Get.Read(out long bytesRead, offset, new OutBuffer(region.Memory.Span), size, readOption); Result result = _baseFile.Get.Read(out long bytesRead, offset, new OutBuffer(region.Memory.Span), size, readOption);
context.ResponseData.Write(bytesRead); context.ResponseData.Write(bytesRead);

View File

@ -111,7 +111,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy
uint mode = context.RequestData.ReadUInt32(); uint mode = context.RequestData.ReadUInt32();
ref readonly Path name = ref FileSystemProxyHelper.GetSfPath(context); ref readonly Path name = ref FileSystemProxyHelper.GetSfPath(context);
using var file = new SharedRef<LibHac.FsSrv.Sf.IFile>(); using SharedRef<LibHac.FsSrv.Sf.IFile> file = new SharedRef<LibHac.FsSrv.Sf.IFile>();
Result result = _fileSystem.Get.OpenFile(ref file.Ref, in name, mode); Result result = _fileSystem.Get.OpenFile(ref file.Ref, in name, mode);
@ -132,7 +132,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy
uint mode = context.RequestData.ReadUInt32(); uint mode = context.RequestData.ReadUInt32();
ref readonly Path name = ref FileSystemProxyHelper.GetSfPath(context); ref readonly Path name = ref FileSystemProxyHelper.GetSfPath(context);
using var dir = new SharedRef<LibHac.FsSrv.Sf.IDirectory>(); using SharedRef<LibHac.FsSrv.Sf.IDirectory> dir = new SharedRef<LibHac.FsSrv.Sf.IDirectory>();
Result result = _fileSystem.Get.OpenDirectory(ref dir.Ref, name, mode); Result result = _fileSystem.Get.OpenDirectory(ref dir.Ref, name, mode);

View File

@ -3,6 +3,7 @@ using LibHac.Common;
using LibHac.Sf; using LibHac.Sf;
using Ryujinx.Common; using Ryujinx.Common;
using Ryujinx.Common.Configuration; using Ryujinx.Common.Configuration;
using Ryujinx.Memory;
using System.Threading; using System.Threading;
namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy
@ -38,7 +39,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy
size = bufferLen; size = bufferLen;
} }
using var region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true); using WritableRegion region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true);
Result result = _baseStorage.Get.Read((long)offset, new OutBuffer(region.Memory.Span), (long)size); Result result = _baseStorage.Get.Read((long)offset, new OutBuffer(region.Memory.Span), (long)size);
if (context.Device.DirtyHacks.IsEnabled(DirtyHack.Xc2MenuSoftlockFix) && IsXc2) if (context.Device.DirtyHacks.IsEnabled(DirtyHack.Xc2MenuSoftlockFix) && IsXc2)

View File

@ -3,6 +3,7 @@ using LibHac.Common;
using LibHac.Fs; using LibHac.Fs;
using LibHac.Fs.Shim; using LibHac.Fs.Shim;
using LibHac.FsSrv.Impl; using LibHac.FsSrv.Impl;
using LibHac.FsSrv.Sf;
using LibHac.FsSystem; using LibHac.FsSystem;
using LibHac.Ncm; using LibHac.Ncm;
using LibHac.Sf; using LibHac.Sf;
@ -12,10 +13,12 @@ using LibHac.Tools.FsSystem.NcaUtils;
using Ryujinx.Common; using Ryujinx.Common;
using Ryujinx.Common.Logging; using Ryujinx.Common.Logging;
using Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy; using Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy;
using Ryujinx.Memory;
using System; using System;
using System.IO; using System.IO;
using static Ryujinx.HLE.Utilities.StringUtils; using static Ryujinx.HLE.Utilities.StringUtils;
using GameCardHandle = System.UInt32; using GameCardHandle = System.UInt32;
using IFile = Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy.IFile;
using IFileSystem = LibHac.FsSrv.Sf.IFileSystem; using IFileSystem = LibHac.FsSrv.Sf.IFileSystem;
using IStorage = LibHac.FsSrv.Sf.IStorage; using IStorage = LibHac.FsSrv.Sf.IStorage;
@ -29,7 +32,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs
public IFileSystemProxy(ServiceCtx context) : base(context.Device.System.FsServer) public IFileSystemProxy(ServiceCtx context) : base(context.Device.System.FsServer)
{ {
var applicationClient = context.Device.System.LibHacHorizonManager.ApplicationClient; HorizonClient applicationClient = context.Device.System.LibHacHorizonManager.ApplicationClient;
_baseFileSystemProxy = applicationClient.Fs.Impl.GetFileSystemProxyServiceObject(); _baseFileSystemProxy = applicationClient.Fs.Impl.GetFileSystemProxyServiceObject();
} }
@ -106,8 +109,8 @@ namespace Ryujinx.HLE.HOS.Services.Fs
{ {
BisPartitionId bisPartitionId = (BisPartitionId)context.RequestData.ReadInt32(); BisPartitionId bisPartitionId = (BisPartitionId)context.RequestData.ReadInt32();
ref readonly var path = ref FileSystemProxyHelper.GetFspPath(context); ref readonly FspPath path = ref FileSystemProxyHelper.GetFspPath(context);
using var fileSystem = new SharedRef<IFileSystem>(); using SharedRef<IFileSystem> fileSystem = new SharedRef<IFileSystem>();
Result result = _baseFileSystemProxy.Get.OpenBisFileSystem(ref fileSystem.Ref, in path, bisPartitionId); Result result = _baseFileSystemProxy.Get.OpenBisFileSystem(ref fileSystem.Ref, in path, bisPartitionId);
if (result.IsFailure()) if (result.IsFailure())
@ -125,7 +128,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs
public ResultCode OpenBisStorage(ServiceCtx context) public ResultCode OpenBisStorage(ServiceCtx context)
{ {
BisPartitionId bisPartitionId = (BisPartitionId)context.RequestData.ReadInt32(); BisPartitionId bisPartitionId = (BisPartitionId)context.RequestData.ReadInt32();
using var storage = new SharedRef<IStorage>(); using SharedRef<IStorage> storage = new SharedRef<IStorage>();
Result result = _baseFileSystemProxy.Get.OpenBisStorage(ref storage.Ref, bisPartitionId); Result result = _baseFileSystemProxy.Get.OpenBisStorage(ref storage.Ref, bisPartitionId);
if (result.IsFailure()) if (result.IsFailure())
@ -149,7 +152,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs
// OpenSdCardFileSystem() -> object<nn::fssrv::sf::IFileSystem> // OpenSdCardFileSystem() -> object<nn::fssrv::sf::IFileSystem>
public ResultCode OpenSdCardFileSystem(ServiceCtx context) public ResultCode OpenSdCardFileSystem(ServiceCtx context)
{ {
using var fileSystem = new SharedRef<IFileSystem>(); using SharedRef<IFileSystem> fileSystem = new SharedRef<IFileSystem>();
Result result = _baseFileSystemProxy.Get.OpenSdCardFileSystem(ref fileSystem.Ref); Result result = _baseFileSystemProxy.Get.OpenSdCardFileSystem(ref fileSystem.Ref);
if (result.IsFailure()) if (result.IsFailure())
@ -257,7 +260,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs
{ {
GameCardHandle handle = context.RequestData.ReadUInt32(); GameCardHandle handle = context.RequestData.ReadUInt32();
GameCardPartitionRaw partitionId = (GameCardPartitionRaw)context.RequestData.ReadInt32(); GameCardPartitionRaw partitionId = (GameCardPartitionRaw)context.RequestData.ReadInt32();
using var storage = new SharedRef<IStorage>(); using SharedRef<IStorage> storage = new SharedRef<IStorage>();
Result result = _baseFileSystemProxy.Get.OpenGameCardStorage(ref storage.Ref, handle, partitionId); Result result = _baseFileSystemProxy.Get.OpenGameCardStorage(ref storage.Ref, handle, partitionId);
if (result.IsFailure()) if (result.IsFailure())
@ -276,7 +279,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs
{ {
GameCardHandle handle = context.RequestData.ReadUInt32(); GameCardHandle handle = context.RequestData.ReadUInt32();
GameCardPartition partitionId = (GameCardPartition)context.RequestData.ReadInt32(); GameCardPartition partitionId = (GameCardPartition)context.RequestData.ReadInt32();
using var fileSystem = new SharedRef<IFileSystem>(); using SharedRef<IFileSystem> fileSystem = new SharedRef<IFileSystem>();
Result result = _baseFileSystemProxy.Get.OpenGameCardFileSystem(ref fileSystem.Ref, handle, partitionId); Result result = _baseFileSystemProxy.Get.OpenGameCardFileSystem(ref fileSystem.Ref, handle, partitionId);
if (result.IsFailure()) if (result.IsFailure())
@ -357,7 +360,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs
{ {
SaveDataSpaceId spaceId = (SaveDataSpaceId)context.RequestData.ReadInt64(); SaveDataSpaceId spaceId = (SaveDataSpaceId)context.RequestData.ReadInt64();
SaveDataAttribute attribute = context.RequestData.ReadStruct<SaveDataAttribute>(); SaveDataAttribute attribute = context.RequestData.ReadStruct<SaveDataAttribute>();
using var fileSystem = new SharedRef<IFileSystem>(); using SharedRef<IFileSystem> fileSystem = new SharedRef<IFileSystem>();
Result result = _baseFileSystemProxy.Get.OpenSaveDataFileSystem(ref fileSystem.Ref, spaceId, in attribute); Result result = _baseFileSystemProxy.Get.OpenSaveDataFileSystem(ref fileSystem.Ref, spaceId, in attribute);
if (result.IsFailure()) if (result.IsFailure())
@ -376,7 +379,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs
{ {
SaveDataSpaceId spaceId = (SaveDataSpaceId)context.RequestData.ReadInt64(); SaveDataSpaceId spaceId = (SaveDataSpaceId)context.RequestData.ReadInt64();
SaveDataAttribute attribute = context.RequestData.ReadStruct<SaveDataAttribute>(); SaveDataAttribute attribute = context.RequestData.ReadStruct<SaveDataAttribute>();
using var fileSystem = new SharedRef<IFileSystem>(); using SharedRef<IFileSystem> fileSystem = new SharedRef<IFileSystem>();
Result result = _baseFileSystemProxy.Get.OpenSaveDataFileSystemBySystemSaveDataId(ref fileSystem.Ref, spaceId, in attribute); Result result = _baseFileSystemProxy.Get.OpenSaveDataFileSystemBySystemSaveDataId(ref fileSystem.Ref, spaceId, in attribute);
if (result.IsFailure()) if (result.IsFailure())
@ -395,7 +398,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs
{ {
SaveDataSpaceId spaceId = (SaveDataSpaceId)context.RequestData.ReadInt64(); SaveDataSpaceId spaceId = (SaveDataSpaceId)context.RequestData.ReadInt64();
SaveDataAttribute attribute = context.RequestData.ReadStruct<SaveDataAttribute>(); SaveDataAttribute attribute = context.RequestData.ReadStruct<SaveDataAttribute>();
using var fileSystem = new SharedRef<IFileSystem>(); using SharedRef<IFileSystem> fileSystem = new SharedRef<IFileSystem>();
Result result = _baseFileSystemProxy.Get.OpenReadOnlySaveDataFileSystem(ref fileSystem.Ref, spaceId, in attribute); Result result = _baseFileSystemProxy.Get.OpenReadOnlySaveDataFileSystem(ref fileSystem.Ref, spaceId, in attribute);
if (result.IsFailure()) if (result.IsFailure())
@ -466,7 +469,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs
// OpenSaveDataInfoReader() -> object<nn::fssrv::sf::ISaveDataInfoReader> // OpenSaveDataInfoReader() -> object<nn::fssrv::sf::ISaveDataInfoReader>
public ResultCode OpenSaveDataInfoReader(ServiceCtx context) public ResultCode OpenSaveDataInfoReader(ServiceCtx context)
{ {
using var infoReader = new SharedRef<LibHac.FsSrv.Sf.ISaveDataInfoReader>(); using SharedRef<LibHac.FsSrv.Sf.ISaveDataInfoReader> infoReader = new SharedRef<LibHac.FsSrv.Sf.ISaveDataInfoReader>();
Result result = _baseFileSystemProxy.Get.OpenSaveDataInfoReader(ref infoReader.Ref); Result result = _baseFileSystemProxy.Get.OpenSaveDataInfoReader(ref infoReader.Ref);
if (result.IsFailure()) if (result.IsFailure())
@ -484,7 +487,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs
public ResultCode OpenSaveDataInfoReaderBySaveDataSpaceId(ServiceCtx context) public ResultCode OpenSaveDataInfoReaderBySaveDataSpaceId(ServiceCtx context)
{ {
SaveDataSpaceId spaceId = (SaveDataSpaceId)context.RequestData.ReadByte(); SaveDataSpaceId spaceId = (SaveDataSpaceId)context.RequestData.ReadByte();
using var infoReader = new SharedRef<LibHac.FsSrv.Sf.ISaveDataInfoReader>(); using SharedRef<LibHac.FsSrv.Sf.ISaveDataInfoReader> infoReader = new SharedRef<LibHac.FsSrv.Sf.ISaveDataInfoReader>();
Result result = _baseFileSystemProxy.Get.OpenSaveDataInfoReaderBySaveDataSpaceId(ref infoReader.Ref, spaceId); Result result = _baseFileSystemProxy.Get.OpenSaveDataInfoReaderBySaveDataSpaceId(ref infoReader.Ref, spaceId);
if (result.IsFailure()) if (result.IsFailure())
@ -501,7 +504,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs
// OpenSaveDataInfoReaderOnlyCacheStorage() -> object<nn::fssrv::sf::ISaveDataInfoReader> // OpenSaveDataInfoReaderOnlyCacheStorage() -> object<nn::fssrv::sf::ISaveDataInfoReader>
public ResultCode OpenSaveDataInfoReaderOnlyCacheStorage(ServiceCtx context) public ResultCode OpenSaveDataInfoReaderOnlyCacheStorage(ServiceCtx context)
{ {
using var infoReader = new SharedRef<LibHac.FsSrv.Sf.ISaveDataInfoReader>(); using SharedRef<LibHac.FsSrv.Sf.ISaveDataInfoReader> infoReader = new SharedRef<LibHac.FsSrv.Sf.ISaveDataInfoReader>();
Result result = _baseFileSystemProxy.Get.OpenSaveDataInfoReaderOnlyCacheStorage(ref infoReader.Ref); Result result = _baseFileSystemProxy.Get.OpenSaveDataInfoReaderOnlyCacheStorage(ref infoReader.Ref);
if (result.IsFailure()) if (result.IsFailure())
@ -520,7 +523,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs
{ {
SaveDataSpaceId spaceId = (SaveDataSpaceId)context.RequestData.ReadInt64(); SaveDataSpaceId spaceId = (SaveDataSpaceId)context.RequestData.ReadInt64();
ulong saveDataId = context.RequestData.ReadUInt64(); ulong saveDataId = context.RequestData.ReadUInt64();
using var fileSystem = new SharedRef<IFileSystem>(); using SharedRef<IFileSystem> fileSystem = new SharedRef<IFileSystem>();
Result result = _baseFileSystemProxy.Get.OpenSaveDataInternalStorageFileSystem(ref fileSystem.Ref, spaceId, saveDataId); Result result = _baseFileSystemProxy.Get.OpenSaveDataInternalStorageFileSystem(ref fileSystem.Ref, spaceId, saveDataId);
if (result.IsFailure()) if (result.IsFailure())
@ -567,7 +570,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs
ulong bufferAddress = context.Request.ReceiveBuff[0].Position; ulong bufferAddress = context.Request.ReceiveBuff[0].Position;
ulong bufferLen = context.Request.ReceiveBuff[0].Size; ulong bufferLen = context.Request.ReceiveBuff[0].Size;
using var region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true); using WritableRegion region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true);
Result result = _baseFileSystemProxy.Get.FindSaveDataWithFilter(out long count, new OutBuffer(region.Memory.Span), spaceId, in filter); Result result = _baseFileSystemProxy.Get.FindSaveDataWithFilter(out long count, new OutBuffer(region.Memory.Span), spaceId, in filter);
if (result.IsFailure()) if (result.IsFailure())
{ {
@ -584,7 +587,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs
{ {
SaveDataSpaceId spaceId = (SaveDataSpaceId)context.RequestData.ReadInt64(); SaveDataSpaceId spaceId = (SaveDataSpaceId)context.RequestData.ReadInt64();
SaveDataFilter filter = context.RequestData.ReadStruct<SaveDataFilter>(); SaveDataFilter filter = context.RequestData.ReadStruct<SaveDataFilter>();
using var infoReader = new SharedRef<LibHac.FsSrv.Sf.ISaveDataInfoReader>(); using SharedRef<LibHac.FsSrv.Sf.ISaveDataInfoReader> infoReader = new SharedRef<LibHac.FsSrv.Sf.ISaveDataInfoReader>();
Result result = _baseFileSystemProxy.Get.OpenSaveDataInfoReaderWithFilter(ref infoReader.Ref, spaceId, in filter); Result result = _baseFileSystemProxy.Get.OpenSaveDataInfoReaderWithFilter(ref infoReader.Ref, spaceId, in filter);
if (result.IsFailure()) if (result.IsFailure())
@ -661,7 +664,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs
SaveDataSpaceId spaceId = (SaveDataSpaceId)context.RequestData.ReadInt32(); SaveDataSpaceId spaceId = (SaveDataSpaceId)context.RequestData.ReadInt32();
SaveDataMetaType metaType = (SaveDataMetaType)context.RequestData.ReadInt32(); SaveDataMetaType metaType = (SaveDataMetaType)context.RequestData.ReadInt32();
SaveDataAttribute attribute = context.RequestData.ReadStruct<SaveDataAttribute>(); SaveDataAttribute attribute = context.RequestData.ReadStruct<SaveDataAttribute>();
using var file = new SharedRef<LibHac.FsSrv.Sf.IFile>(); using SharedRef<LibHac.FsSrv.Sf.IFile> file = new SharedRef<LibHac.FsSrv.Sf.IFile>();
Result result = _baseFileSystemProxy.Get.OpenSaveDataMetaFile(ref file.Ref, spaceId, in attribute, metaType); Result result = _baseFileSystemProxy.Get.OpenSaveDataMetaFile(ref file.Ref, spaceId, in attribute, metaType);
if (result.IsFailure()) if (result.IsFailure())
@ -699,7 +702,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs
public ResultCode OpenImageDirectoryFileSystem(ServiceCtx context) public ResultCode OpenImageDirectoryFileSystem(ServiceCtx context)
{ {
ImageDirectoryId directoryId = (ImageDirectoryId)context.RequestData.ReadInt32(); ImageDirectoryId directoryId = (ImageDirectoryId)context.RequestData.ReadInt32();
using var fileSystem = new SharedRef<IFileSystem>(); using SharedRef<IFileSystem> fileSystem = new SharedRef<IFileSystem>();
Result result = _baseFileSystemProxy.Get.OpenImageDirectoryFileSystem(ref fileSystem.Ref, directoryId); Result result = _baseFileSystemProxy.Get.OpenImageDirectoryFileSystem(ref fileSystem.Ref, directoryId);
if (result.IsFailure()) if (result.IsFailure())
@ -716,7 +719,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs
public ResultCode OpenBaseFileSystem(ServiceCtx context) public ResultCode OpenBaseFileSystem(ServiceCtx context)
{ {
BaseFileSystemId fileSystemId = (BaseFileSystemId)context.RequestData.ReadInt32(); BaseFileSystemId fileSystemId = (BaseFileSystemId)context.RequestData.ReadInt32();
using var fileSystem = new SharedRef<IFileSystem>(); using SharedRef<IFileSystem> fileSystem = new SharedRef<IFileSystem>();
Result result = _baseFileSystemProxy.Get.OpenBaseFileSystem(ref fileSystem.Ref, fileSystemId); Result result = _baseFileSystemProxy.Get.OpenBaseFileSystem(ref fileSystem.Ref, fileSystemId);
if (result.IsFailure()) if (result.IsFailure())
@ -733,7 +736,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs
public ResultCode OpenContentStorageFileSystem(ServiceCtx context) public ResultCode OpenContentStorageFileSystem(ServiceCtx context)
{ {
ContentStorageId contentStorageId = (ContentStorageId)context.RequestData.ReadInt32(); ContentStorageId contentStorageId = (ContentStorageId)context.RequestData.ReadInt32();
using var fileSystem = new SharedRef<IFileSystem>(); using SharedRef<IFileSystem> fileSystem = new SharedRef<IFileSystem>();
Result result = _baseFileSystemProxy.Get.OpenContentStorageFileSystem(ref fileSystem.Ref, contentStorageId); Result result = _baseFileSystemProxy.Get.OpenContentStorageFileSystem(ref fileSystem.Ref, contentStorageId);
if (result.IsFailure()) if (result.IsFailure())
@ -750,7 +753,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs
public ResultCode OpenCloudBackupWorkStorageFileSystem(ServiceCtx context) public ResultCode OpenCloudBackupWorkStorageFileSystem(ServiceCtx context)
{ {
CloudBackupWorkStorageId storageId = (CloudBackupWorkStorageId)context.RequestData.ReadInt32(); CloudBackupWorkStorageId storageId = (CloudBackupWorkStorageId)context.RequestData.ReadInt32();
using var fileSystem = new SharedRef<IFileSystem>(); using SharedRef<IFileSystem> fileSystem = new SharedRef<IFileSystem>();
Result result = _baseFileSystemProxy.Get.OpenCloudBackupWorkStorageFileSystem(ref fileSystem.Ref, storageId); Result result = _baseFileSystemProxy.Get.OpenCloudBackupWorkStorageFileSystem(ref fileSystem.Ref, storageId);
if (result.IsFailure()) if (result.IsFailure())
@ -767,7 +770,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs
public ResultCode OpenCustomStorageFileSystem(ServiceCtx context) public ResultCode OpenCustomStorageFileSystem(ServiceCtx context)
{ {
CustomStorageId customStorageId = (CustomStorageId)context.RequestData.ReadInt32(); CustomStorageId customStorageId = (CustomStorageId)context.RequestData.ReadInt32();
using var fileSystem = new SharedRef<IFileSystem>(); using SharedRef<IFileSystem> fileSystem = new SharedRef<IFileSystem>();
Result result = _baseFileSystemProxy.Get.OpenCustomStorageFileSystem(ref fileSystem.Ref, customStorageId); Result result = _baseFileSystemProxy.Get.OpenCustomStorageFileSystem(ref fileSystem.Ref, customStorageId);
if (result.IsFailure()) if (result.IsFailure())
@ -784,9 +787,9 @@ namespace Ryujinx.HLE.HOS.Services.Fs
// OpenDataStorageByCurrentProcess() -> object<nn::fssrv::sf::IStorage> dataStorage // OpenDataStorageByCurrentProcess() -> object<nn::fssrv::sf::IStorage> dataStorage
public ResultCode OpenDataStorageByCurrentProcess(ServiceCtx context) public ResultCode OpenDataStorageByCurrentProcess(ServiceCtx context)
{ {
var storage = context.Device.FileSystem.GetRomFs(_pid).AsStorage(true); LibHac.Fs.IStorage storage = context.Device.FileSystem.GetRomFs(_pid).AsStorage(true);
using var sharedStorage = new SharedRef<LibHac.Fs.IStorage>(storage); using SharedRef<LibHac.Fs.IStorage> sharedStorage = new SharedRef<LibHac.Fs.IStorage>(storage);
using var sfStorage = new SharedRef<IStorage>(new StorageInterfaceAdapter(ref sharedStorage.Ref)); using SharedRef<IStorage> sfStorage = new SharedRef<IStorage>(new StorageInterfaceAdapter(ref sharedStorage.Ref));
MakeObject(context, new FileSystemProxy.IStorage(ref sfStorage.Ref)); MakeObject(context, new FileSystemProxy.IStorage(ref sfStorage.Ref));
@ -809,9 +812,9 @@ namespace Ryujinx.HLE.HOS.Services.Fs
{ {
Logger.Info?.Print(LogClass.Loader, $"Opened AddOnContent Data TitleID={titleId:X16}"); Logger.Info?.Print(LogClass.Loader, $"Opened AddOnContent Data TitleID={titleId:X16}");
var storage = context.Device.FileSystem.ModLoader.ApplyRomFsMods(titleId, aocStorage); LibHac.Fs.IStorage storage = context.Device.FileSystem.ModLoader.ApplyRomFsMods(titleId, aocStorage);
using var sharedStorage = new SharedRef<LibHac.Fs.IStorage>(storage); using SharedRef<LibHac.Fs.IStorage> sharedStorage = new SharedRef<LibHac.Fs.IStorage>(storage);
using var sfStorage = new SharedRef<IStorage>(new StorageInterfaceAdapter(ref sharedStorage.Ref)); using SharedRef<IStorage> sfStorage = new SharedRef<IStorage>(new StorageInterfaceAdapter(ref sharedStorage.Ref));
MakeObject(context, new FileSystemProxy.IStorage(ref sfStorage.Ref)); MakeObject(context, new FileSystemProxy.IStorage(ref sfStorage.Ref));
@ -845,8 +848,8 @@ namespace Ryujinx.HLE.HOS.Services.Fs
LibHac.Fs.IStorage ncaStorage = new LocalStorage(ncaPath, FileAccess.Read, FileMode.Open); LibHac.Fs.IStorage ncaStorage = new LocalStorage(ncaPath, FileAccess.Read, FileMode.Open);
Nca nca = new(context.Device.System.KeySet, ncaStorage); Nca nca = new(context.Device.System.KeySet, ncaStorage);
LibHac.Fs.IStorage romfsStorage = nca.OpenStorage(NcaSectionType.Data, context.Device.System.FsIntegrityCheckLevel); LibHac.Fs.IStorage romfsStorage = nca.OpenStorage(NcaSectionType.Data, context.Device.System.FsIntegrityCheckLevel);
using var sharedStorage = new SharedRef<LibHac.Fs.IStorage>(romfsStorage); using SharedRef<LibHac.Fs.IStorage> sharedStorage = new SharedRef<LibHac.Fs.IStorage>(romfsStorage);
using var sfStorage = new SharedRef<IStorage>(new StorageInterfaceAdapter(ref sharedStorage.Ref)); using SharedRef<IStorage> sfStorage = new SharedRef<IStorage>(new StorageInterfaceAdapter(ref sharedStorage.Ref));
MakeObject(context, new FileSystemProxy.IStorage(ref sfStorage.Ref)); MakeObject(context, new FileSystemProxy.IStorage(ref sfStorage.Ref));
} }
@ -875,9 +878,9 @@ namespace Ryujinx.HLE.HOS.Services.Fs
// OpenPatchDataStorageByCurrentProcess() -> object<nn::fssrv::sf::IStorage> // OpenPatchDataStorageByCurrentProcess() -> object<nn::fssrv::sf::IStorage>
public ResultCode OpenPatchDataStorageByCurrentProcess(ServiceCtx context) public ResultCode OpenPatchDataStorageByCurrentProcess(ServiceCtx context)
{ {
var storage = context.Device.FileSystem.GetRomFs(_pid).AsStorage(true); LibHac.Fs.IStorage storage = context.Device.FileSystem.GetRomFs(_pid).AsStorage(true);
using var sharedStorage = new SharedRef<LibHac.Fs.IStorage>(storage); using SharedRef<LibHac.Fs.IStorage> sharedStorage = new SharedRef<LibHac.Fs.IStorage>(storage);
using var sfStorage = new SharedRef<IStorage>(new StorageInterfaceAdapter(ref sharedStorage.Ref)); using SharedRef<IStorage> sfStorage = new SharedRef<IStorage>(new StorageInterfaceAdapter(ref sharedStorage.Ref));
MakeObject(context, new FileSystemProxy.IStorage(ref sfStorage.Ref)); MakeObject(context, new FileSystemProxy.IStorage(ref sfStorage.Ref));
@ -895,9 +898,9 @@ namespace Ryujinx.HLE.HOS.Services.Fs
throw new NotImplementedException($"Accessing storage from other programs is not supported (program index = {programIndex})."); throw new NotImplementedException($"Accessing storage from other programs is not supported (program index = {programIndex}).");
} }
var storage = context.Device.FileSystem.GetRomFs(_pid).AsStorage(true); LibHac.Fs.IStorage storage = context.Device.FileSystem.GetRomFs(_pid).AsStorage(true);
using var sharedStorage = new SharedRef<LibHac.Fs.IStorage>(storage); using SharedRef<LibHac.Fs.IStorage> sharedStorage = new SharedRef<LibHac.Fs.IStorage>(storage);
using var sfStorage = new SharedRef<IStorage>(new StorageInterfaceAdapter(ref sharedStorage.Ref)); using SharedRef<IStorage> sfStorage = new SharedRef<IStorage>(new StorageInterfaceAdapter(ref sharedStorage.Ref));
MakeObject(context, new FileSystemProxy.IStorage(ref sfStorage.Ref)); MakeObject(context, new FileSystemProxy.IStorage(ref sfStorage.Ref));
@ -908,7 +911,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs
// OpenDataStorageByCurrentProcess() -> object<nn::fssrv::sf::IStorage> dataStorage // OpenDataStorageByCurrentProcess() -> object<nn::fssrv::sf::IStorage> dataStorage
public ResultCode OpenDeviceOperator(ServiceCtx context) public ResultCode OpenDeviceOperator(ServiceCtx context)
{ {
using var deviceOperator = new SharedRef<LibHac.FsSrv.Sf.IDeviceOperator>(); using SharedRef<LibHac.FsSrv.Sf.IDeviceOperator> deviceOperator = new SharedRef<LibHac.FsSrv.Sf.IDeviceOperator>();
Result result = _baseFileSystemProxy.Get.OpenDeviceOperator(ref deviceOperator.Ref); Result result = _baseFileSystemProxy.Get.OpenDeviceOperator(ref deviceOperator.Ref);
if (result.IsFailure()) if (result.IsFailure())
@ -1023,7 +1026,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs
[CommandCmif(609)] [CommandCmif(609)]
public ResultCode GetRightsIdByPath(ServiceCtx context) public ResultCode GetRightsIdByPath(ServiceCtx context)
{ {
ref readonly var path = ref FileSystemProxyHelper.GetFspPath(context); ref readonly FspPath path = ref FileSystemProxyHelper.GetFspPath(context);
Result result = _baseFileSystemProxy.Get.GetRightsIdByPath(out RightsId rightsId, in path); Result result = _baseFileSystemProxy.Get.GetRightsIdByPath(out RightsId rightsId, in path);
if (result.IsFailure()) if (result.IsFailure())
@ -1039,7 +1042,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs
[CommandCmif(610)] [CommandCmif(610)]
public ResultCode GetRightsIdAndKeyGenerationByPath(ServiceCtx context) public ResultCode GetRightsIdAndKeyGenerationByPath(ServiceCtx context)
{ {
ref readonly var path = ref FileSystemProxyHelper.GetFspPath(context); ref readonly FspPath path = ref FileSystemProxyHelper.GetFspPath(context);
Result result = _baseFileSystemProxy.Get.GetRightsIdAndKeyGenerationByPath(out RightsId rightsId, out byte keyGeneration, in path); Result result = _baseFileSystemProxy.Get.GetRightsIdAndKeyGenerationByPath(out RightsId rightsId, out byte keyGeneration, in path);
if (result.IsFailure()) if (result.IsFailure())
@ -1236,7 +1239,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs
public ResultCode SetBisRootForHost(ServiceCtx context) public ResultCode SetBisRootForHost(ServiceCtx context)
{ {
BisPartitionId partitionId = (BisPartitionId)context.RequestData.ReadInt32(); BisPartitionId partitionId = (BisPartitionId)context.RequestData.ReadInt32();
ref readonly var path = ref FileSystemProxyHelper.GetFspPath(context); ref readonly FspPath path = ref FileSystemProxyHelper.GetFspPath(context);
return (ResultCode)_baseFileSystemProxy.Get.SetBisRootForHost(partitionId, in path).Value; return (ResultCode)_baseFileSystemProxy.Get.SetBisRootForHost(partitionId, in path).Value;
} }
@ -1253,7 +1256,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs
[CommandCmif(1002)] [CommandCmif(1002)]
public ResultCode SetSaveDataRootPath(ServiceCtx context) public ResultCode SetSaveDataRootPath(ServiceCtx context)
{ {
ref readonly var path = ref FileSystemProxyHelper.GetFspPath(context); ref readonly FspPath path = ref FileSystemProxyHelper.GetFspPath(context);
return (ResultCode)_baseFileSystemProxy.Get.SetSaveDataRootPath(in path).Value; return (ResultCode)_baseFileSystemProxy.Get.SetSaveDataRootPath(in path).Value;
} }
@ -1307,7 +1310,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs
[CommandCmif(1008)] [CommandCmif(1008)]
public ResultCode OpenRegisteredUpdatePartition(ServiceCtx context) public ResultCode OpenRegisteredUpdatePartition(ServiceCtx context)
{ {
using var fileSystem = new SharedRef<IFileSystem>(); using SharedRef<IFileSystem> fileSystem = new SharedRef<IFileSystem>();
Result result = _baseFileSystemProxy.Get.OpenRegisteredUpdatePartition(ref fileSystem.Ref); Result result = _baseFileSystemProxy.Get.OpenRegisteredUpdatePartition(ref fileSystem.Ref);
if (result.IsFailure()) if (result.IsFailure())
@ -1417,7 +1420,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs
// OpenMultiCommitManager() -> object<nn::fssrv::sf::IMultiCommitManager> // OpenMultiCommitManager() -> object<nn::fssrv::sf::IMultiCommitManager>
public ResultCode OpenMultiCommitManager(ServiceCtx context) public ResultCode OpenMultiCommitManager(ServiceCtx context)
{ {
using var commitManager = new SharedRef<LibHac.FsSrv.Sf.IMultiCommitManager>(); using SharedRef<LibHac.FsSrv.Sf.IMultiCommitManager> commitManager = new SharedRef<LibHac.FsSrv.Sf.IMultiCommitManager>();
Result result = _baseFileSystemProxy.Get.OpenMultiCommitManager(ref commitManager.Ref); Result result = _baseFileSystemProxy.Get.OpenMultiCommitManager(ref commitManager.Ref);
if (result.IsFailure()) if (result.IsFailure())

View File

@ -1,6 +1,7 @@
using LibHac; using LibHac;
using LibHac.Common; using LibHac.Common;
using LibHac.Sf; using LibHac.Sf;
using Ryujinx.Memory;
namespace Ryujinx.HLE.HOS.Services.Fs namespace Ryujinx.HLE.HOS.Services.Fs
{ {
@ -20,7 +21,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs
ulong bufferAddress = context.Request.ReceiveBuff[0].Position; ulong bufferAddress = context.Request.ReceiveBuff[0].Position;
ulong bufferLen = context.Request.ReceiveBuff[0].Size; ulong bufferLen = context.Request.ReceiveBuff[0].Size;
using var region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true); using WritableRegion region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true);
Result result = _baseReader.Get.Read(out long readCount, new OutBuffer(region.Memory.Span)); Result result = _baseReader.Get.Read(out long readCount, new OutBuffer(region.Memory.Span));
context.ResponseData.Write(readCount); context.ResponseData.Write(readCount);

View File

@ -81,7 +81,7 @@ namespace Ryujinx.HLE.HOS.Services.Hid.Irs
{ {
IrCameraHandle irCameraHandle = context.RequestData.ReadStruct<IrCameraHandle>(); IrCameraHandle irCameraHandle = context.RequestData.ReadStruct<IrCameraHandle>();
ulong appletResourceUserId = context.RequestData.ReadUInt64(); ulong appletResourceUserId = context.RequestData.ReadUInt64();
var packedMomentProcessorConfig = context.RequestData.ReadStruct<PackedMomentProcessorConfig>(); PackedMomentProcessorConfig packedMomentProcessorConfig = context.RequestData.ReadStruct<PackedMomentProcessorConfig>();
CheckCameraHandle(irCameraHandle); CheckCameraHandle(irCameraHandle);
@ -96,7 +96,7 @@ namespace Ryujinx.HLE.HOS.Services.Hid.Irs
{ {
IrCameraHandle irCameraHandle = context.RequestData.ReadStruct<IrCameraHandle>(); IrCameraHandle irCameraHandle = context.RequestData.ReadStruct<IrCameraHandle>();
ulong appletResourceUserId = context.RequestData.ReadUInt64(); ulong appletResourceUserId = context.RequestData.ReadUInt64();
var packedClusteringProcessorConfig = context.RequestData.ReadStruct<PackedClusteringProcessorConfig>(); PackedClusteringProcessorConfig packedClusteringProcessorConfig = context.RequestData.ReadStruct<PackedClusteringProcessorConfig>();
CheckCameraHandle(irCameraHandle); CheckCameraHandle(irCameraHandle);
@ -111,7 +111,7 @@ namespace Ryujinx.HLE.HOS.Services.Hid.Irs
{ {
IrCameraHandle irCameraHandle = context.RequestData.ReadStruct<IrCameraHandle>(); IrCameraHandle irCameraHandle = context.RequestData.ReadStruct<IrCameraHandle>();
ulong appletResourceUserId = context.RequestData.ReadUInt64(); ulong appletResourceUserId = context.RequestData.ReadUInt64();
var packedImageTransferProcessorConfig = context.RequestData.ReadStruct<PackedImageTransferProcessorConfig>(); PackedImageTransferProcessorConfig packedImageTransferProcessorConfig = context.RequestData.ReadStruct<PackedImageTransferProcessorConfig>();
CheckCameraHandle(irCameraHandle); CheckCameraHandle(irCameraHandle);
@ -157,7 +157,7 @@ namespace Ryujinx.HLE.HOS.Services.Hid.Irs
{ {
IrCameraHandle irCameraHandle = context.RequestData.ReadStruct<IrCameraHandle>(); IrCameraHandle irCameraHandle = context.RequestData.ReadStruct<IrCameraHandle>();
ulong appletResourceUserId = context.RequestData.ReadUInt64(); ulong appletResourceUserId = context.RequestData.ReadUInt64();
var packedTeraPluginProcessorConfig = context.RequestData.ReadStruct<PackedTeraPluginProcessorConfig>(); PackedTeraPluginProcessorConfig packedTeraPluginProcessorConfig = context.RequestData.ReadStruct<PackedTeraPluginProcessorConfig>();
CheckCameraHandle(irCameraHandle); CheckCameraHandle(irCameraHandle);

View File

@ -65,7 +65,7 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator
// TODO: Call nn::arp::GetApplicationControlProperty here when implemented. // TODO: Call nn::arp::GetApplicationControlProperty here when implemented.
ApplicationControlProperty controlProperty = context.Device.Processes.ActiveApplication.ApplicationControlProperties; ApplicationControlProperty controlProperty = context.Device.Processes.ActiveApplication.ApplicationControlProperties;
foreach (var localCommunicationId in controlProperty.LocalCommunicationId.ItemsRo) foreach (ulong localCommunicationId in controlProperty.LocalCommunicationId.ItemsRo)
{ {
if (localCommunicationId == localCommunicationIdChecked) if (localCommunicationId == localCommunicationIdChecked)
{ {

View File

@ -244,7 +244,7 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnMitm
byte[] ip = address.GetAddressBytes(); byte[] ip = address.GetAddressBytes();
var macAddress = new Array6<byte>(); Array6<byte> macAddress = new Array6<byte>();
new byte[] { 0x02, 0x00, ip[0], ip[1], ip[2], ip[3] }.CopyTo(macAddress.AsSpan()); new byte[] { 0x02, 0x00, ip[0], ip[1], ip[2], ip[3] }.CopyTo(macAddress.AsSpan());
return macAddress; return macAddress;

View File

@ -112,7 +112,7 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnMitm.Proxy
lock (_scanLock) lock (_scanLock)
{ {
var newResults = _scanResultsLast; Dictionary<ulong, NetworkInfo> newResults = _scanResultsLast;
newResults.Clear(); newResults.Clear();
_scanResultsLast = _scanResults; _scanResultsLast = _scanResults;
@ -138,7 +138,7 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnMitm.Proxy
lock (_scanLock) lock (_scanLock)
{ {
var results = new Dictionary<ulong, NetworkInfo>(); Dictionary<ulong, NetworkInfo> results = new Dictionary<ulong, NetworkInfo>();
foreach (KeyValuePair<ulong, NetworkInfo> last in _scanResultsLast) foreach (KeyValuePair<ulong, NetworkInfo> last in _scanResultsLast)
{ {

View File

@ -490,7 +490,7 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnRyu
SendAsync(_protocol.Encode(PacketId.CreateAccessPoint, request, advertiseData)); SendAsync(_protocol.Encode(PacketId.CreateAccessPoint, request, advertiseData));
// Send a network change event with dummy data immediately. Necessary to avoid crashes in some games // Send a network change event with dummy data immediately. Necessary to avoid crashes in some games
var networkChangeEvent = new NetworkChangeEventArgs(new NetworkInfo() NetworkChangeEventArgs networkChangeEvent = new NetworkChangeEventArgs(new NetworkInfo()
{ {
Common = new CommonNetworkInfo() Common = new CommonNetworkInfo()
{ {
@ -610,7 +610,7 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnRyu
SendAsync(_protocol.Encode(PacketId.Connect, request)); SendAsync(_protocol.Encode(PacketId.Connect, request));
var networkChangeEvent = new NetworkChangeEventArgs(new NetworkInfo() NetworkChangeEventArgs networkChangeEvent = new NetworkChangeEventArgs(new NetworkInfo()
{ {
Common = request.NetworkInfo.Common, Common = request.NetworkInfo.Common,
Ldn = request.NetworkInfo.Ldn Ldn = request.NetworkInfo.Ldn

View File

@ -256,7 +256,7 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnRyu.Proxy
{ {
_proxy.ReturnEphemeralPort(ProtocolType, (ushort)((IPEndPoint)LocalEndPoint).Port); _proxy.ReturnEphemeralPort(ProtocolType, (ushort)((IPEndPoint)LocalEndPoint).Port);
} }
var asIPEndpoint = (IPEndPoint)localEP; IPEndPoint asIPEndpoint = (IPEndPoint)localEP;
if (asIPEndpoint.Port == 0) if (asIPEndpoint.Port == 0)
{ {
asIPEndpoint.Port = (ushort)_proxy.GetEphemeralPort(ProtocolType); asIPEndpoint.Port = (ushort)_proxy.GetEphemeralPort(ProtocolType);

View File

@ -440,18 +440,18 @@ namespace Ryujinx.HLE.HOS.Services.Mii.Types
int indexFor4 = 3 * (int)age + 9 * (int)gender + (int)race; int indexFor4 = 3 * (int)age + 9 * (int)gender + (int)race;
var facelineTypeInfo = RandomMiiFacelineArray[indexFor4]; RandomMiiData4 facelineTypeInfo = RandomMiiFacelineArray[indexFor4];
var facelineColorInfo = RandomMiiFacelineColorArray[3 * (int)gender + (int)race]; RandomMiiData3 facelineColorInfo = RandomMiiFacelineColorArray[3 * (int)gender + (int)race];
var facelineWrinkleInfo = RandomMiiFacelineWrinkleArray[indexFor4]; RandomMiiData4 facelineWrinkleInfo = RandomMiiFacelineWrinkleArray[indexFor4];
var facelineMakeInfo = RandomMiiFacelineMakeArray[indexFor4]; RandomMiiData4 facelineMakeInfo = RandomMiiFacelineMakeArray[indexFor4];
var hairTypeInfo = RandomMiiHairTypeArray[indexFor4]; RandomMiiData4 hairTypeInfo = RandomMiiHairTypeArray[indexFor4];
var hairColorInfo = RandomMiiHairColorArray[3 * (int)race + (int)age]; RandomMiiData3 hairColorInfo = RandomMiiHairColorArray[3 * (int)race + (int)age];
var eyeTypeInfo = RandomMiiEyeTypeArray[indexFor4]; RandomMiiData4 eyeTypeInfo = RandomMiiEyeTypeArray[indexFor4];
var eyeColorInfo = RandomMiiEyeColorArray[(int)race]; RandomMiiData2 eyeColorInfo = RandomMiiEyeColorArray[(int)race];
var eyebrowTypeInfo = RandomMiiEyebrowTypeArray[indexFor4]; RandomMiiData4 eyebrowTypeInfo = RandomMiiEyebrowTypeArray[indexFor4];
var noseTypeInfo = RandomMiiNoseTypeArray[indexFor4]; RandomMiiData4 noseTypeInfo = RandomMiiNoseTypeArray[indexFor4];
var mouthTypeInfo = RandomMiiMouthTypeArray[indexFor4]; RandomMiiData4 mouthTypeInfo = RandomMiiMouthTypeArray[indexFor4];
var glassTypeInfo = RandomMiiGlassTypeArray[(int)age]; RandomMiiData2 glassTypeInfo = RandomMiiGlassTypeArray[(int)age];
// Faceline // Faceline
coreData.FacelineType = (FacelineType)facelineTypeInfo.Values[utilImpl.GetRandom(facelineTypeInfo.ValuesCount)]; coreData.FacelineType = (FacelineType)facelineTypeInfo.Values[utilImpl.GetRandom(facelineTypeInfo.ValuesCount)];

View File

@ -9,8 +9,8 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption
public AmiiboDecryptor(string keyRetailBinPath) public AmiiboDecryptor(string keyRetailBinPath)
{ {
var combinedKeys = File.ReadAllBytes(keyRetailBinPath); byte[] combinedKeys = File.ReadAllBytes(keyRetailBinPath);
var keys = AmiiboMasterKey.FromCombinedBin(combinedKeys); (AmiiboMasterKey DataKey, AmiiboMasterKey TagKey) keys = AmiiboMasterKey.FromCombinedBin(combinedKeys);
DataKey = keys.DataKey; DataKey = keys.DataKey;
TagKey = keys.TagKey; TagKey = keys.TagKey;
} }

View File

@ -85,13 +85,13 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption
if (deriveAes) if (deriveAes)
{ {
// Derive AES Key and IV // Derive AES Key and IV
var dataForAes = new byte[2 + seedBytes.Length]; byte[] dataForAes = new byte[2 + seedBytes.Length];
dataForAes[0] = 0x00; dataForAes[0] = 0x00;
dataForAes[1] = 0x00; // Counter (0) dataForAes[1] = 0x00; // Counter (0)
Array.Copy(seedBytes, 0, dataForAes, 2, seedBytes.Length); Array.Copy(seedBytes, 0, dataForAes, 2, seedBytes.Length);
byte[] derivedBytes; byte[] derivedBytes;
using (var hmac = new HMACSHA256(key.HmacKey)) using (HMACSHA256 hmac = new HMACSHA256(key.HmacKey))
{ {
derivedBytes = hmac.ComputeHash(dataForAes); derivedBytes = hmac.ComputeHash(dataForAes);
} }
@ -100,12 +100,12 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption
derivedAesIv = derivedBytes.Skip(16).Take(16).ToArray(); derivedAesIv = derivedBytes.Skip(16).Take(16).ToArray();
// Derive HMAC Key // Derive HMAC Key
var dataForHmacKey = new byte[2 + seedBytes.Length]; byte[] dataForHmacKey = new byte[2 + seedBytes.Length];
dataForHmacKey[0] = 0x00; dataForHmacKey[0] = 0x00;
dataForHmacKey[1] = 0x01; // Counter (1) dataForHmacKey[1] = 0x01; // Counter (1)
Array.Copy(seedBytes, 0, dataForHmacKey, 2, seedBytes.Length); Array.Copy(seedBytes, 0, dataForHmacKey, 2, seedBytes.Length);
using (var hmac = new HMACSHA256(key.HmacKey)) using (HMACSHA256 hmac = new HMACSHA256(key.HmacKey))
{ {
derivedBytes = hmac.ComputeHash(dataForHmacKey); derivedBytes = hmac.ComputeHash(dataForHmacKey);
} }
@ -115,13 +115,13 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption
else else
{ {
// Derive HMAC Key only // Derive HMAC Key only
var dataForHmacKey = new byte[2 + seedBytes.Length]; byte[] dataForHmacKey = new byte[2 + seedBytes.Length];
dataForHmacKey[0] = 0x00; dataForHmacKey[0] = 0x00;
dataForHmacKey[1] = 0x01; // Counter (1) dataForHmacKey[1] = 0x01; // Counter (1)
Array.Copy(seedBytes, 0, dataForHmacKey, 2, seedBytes.Length); Array.Copy(seedBytes, 0, dataForHmacKey, 2, seedBytes.Length);
byte[] derivedBytes; byte[] derivedBytes;
using (var hmac = new HMACSHA256(key.HmacKey)) using (HMACSHA256 hmac = new HMACSHA256(key.HmacKey))
{ {
derivedBytes = hmac.ComputeHash(dataForHmacKey); derivedBytes = hmac.ComputeHash(dataForHmacKey);
} }
@ -229,7 +229,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption
Array.Copy(data, 0x054, tagHmacData, 8, 44); Array.Copy(data, 0x054, tagHmacData, 8, 44);
byte[] tagHmac; byte[] tagHmac;
using (var hmac = new HMACSHA256(hmacTagKey)) using (HMACSHA256 hmac = new HMACSHA256(hmacTagKey))
{ {
tagHmac = hmac.ComputeHash(tagHmacData); tagHmac = hmac.ComputeHash(tagHmacData);
} }
@ -258,7 +258,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption
Array.Copy(data, 0x054, dataHmacData, offset, len5); Array.Copy(data, 0x054, dataHmacData, offset, len5);
byte[] dataHmac; byte[] dataHmac;
using (var hmac = new HMACSHA256(hmacDataKey)) using (HMACSHA256 hmac = new HMACSHA256(hmacDataKey))
{ {
dataHmac = hmac.ComputeHash(dataHmacData); dataHmac = hmac.ComputeHash(dataHmacData);
} }
@ -278,7 +278,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption
Array.Copy(data, 0x054, tagHmacData, 8, 44); Array.Copy(data, 0x054, tagHmacData, 8, 44);
byte[] calculatedTagHmac; byte[] calculatedTagHmac;
using (var hmac = new HMACSHA256(hmacTagKey)) using (HMACSHA256 hmac = new HMACSHA256(hmacTagKey))
{ {
calculatedTagHmac = hmac.ComputeHash(tagHmacData); calculatedTagHmac = hmac.ComputeHash(tagHmacData);
} }
@ -312,7 +312,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption
Array.Copy(data, 0x054, dataHmacData, offset, len5); Array.Copy(data, 0x054, dataHmacData, offset, len5);
byte[] calculatedDataHmac; byte[] calculatedDataHmac;
using (var hmac = new HMACSHA256(hmacDataKey)) using (HMACSHA256 hmac = new HMACSHA256(hmacDataKey))
{ {
calculatedDataHmac = hmac.ComputeHash(dataHmacData); calculatedDataHmac = hmac.ComputeHash(dataHmacData);
} }

View File

@ -18,8 +18,8 @@ namespace Ryujinx.HLE.HOS.Services.Nv
MemoryAllocator = new NvMemoryAllocator(); MemoryAllocator = new NvMemoryAllocator();
Host1x = new Host1xDevice(gpu.Synchronization); Host1x = new Host1xDevice(gpu.Synchronization);
Smmu = gpu.CreateDeviceMemoryManager(pid); Smmu = gpu.CreateDeviceMemoryManager(pid);
var nvdec = new NvdecDevice(Smmu); NvdecDevice nvdec = new NvdecDevice(Smmu);
var vic = new VicDevice(Smmu); VicDevice vic = new VicDevice(Smmu);
Host1x.RegisterDevice(ClassId.Nvdec, nvdec); Host1x.RegisterDevice(ClassId.Nvdec, nvdec);
Host1x.RegisterDevice(ClassId.Vic, vic); Host1x.RegisterDevice(ClassId.Vic, vic);
} }

View File

@ -104,7 +104,7 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvDrvServices.NvHostAsGpu
private NvInternalResult BindChannel(ref BindChannelArguments arguments) private NvInternalResult BindChannel(ref BindChannelArguments arguments)
{ {
var channelDeviceFile = INvDrvServices.DeviceFileIdRegistry.GetData<NvHostChannelDeviceFile>(arguments.Fd); NvHostChannelDeviceFile channelDeviceFile = INvDrvServices.DeviceFileIdRegistry.GetData<NvHostChannelDeviceFile>(arguments.Fd);
if (channelDeviceFile == null) if (channelDeviceFile == null)
{ {
// TODO: Return invalid Fd error. // TODO: Return invalid Fd error.
@ -336,9 +336,9 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvDrvServices.NvHostAsGpu
for (uint i = 0; i < writeEntries; i++) for (uint i = 0; i < writeEntries; i++)
{ {
ref var region = ref arguments.Regions[(int)i]; ref VaRegion region = ref arguments.Regions[(int)i];
var vmRegion = _vmRegions[i]; VmRegion vmRegion = _vmRegions[i];
uint pageSize = _pageSizes[i]; uint pageSize = _pageSizes[i];
region.PageSize = pageSize; region.PageSize = pageSize;

View File

@ -169,7 +169,7 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvDrvServices.NvHostChannel
{ {
NvMapHandle map = NvMapDeviceFile.GetMapFromHandle(Owner, commandBuffer.Mem); NvMapHandle map = NvMapDeviceFile.GetMapFromHandle(Owner, commandBuffer.Mem);
var data = _memory.GetSpan(map.Address + commandBuffer.Offset, commandBuffer.WordsCount * 4); ReadOnlySpan<byte> data = _memory.GetSpan(map.Address + commandBuffer.Offset, commandBuffer.WordsCount * 4);
_host1xContext.Host1x.Submit(MemoryMarshal.Cast<byte, int>(data), _contextId); _host1xContext.Host1x.Submit(MemoryMarshal.Cast<byte, int>(data), _contextId);
} }

View File

@ -55,7 +55,7 @@ namespace Ryujinx.HLE.HOS.Services.Sdb.Pdm.QueryService
MemoryHelper.FillWithZeros(context.Memory, outputPosition, (int)outputSize); MemoryHelper.FillWithZeros(context.Memory, outputPosition, (int)outputSize);
// Return ResultCode.ServiceUnavailable if data is locked by another process. // Return ResultCode.ServiceUnavailable if data is locked by another process.
var filteredApplicationPlayStatistics = _applicationPlayStatistics.AsEnumerable(); IEnumerable<KeyValuePair<UserId, ApplicationPlayStatistics>> filteredApplicationPlayStatistics = _applicationPlayStatistics.AsEnumerable();
if (queryCapability == PlayLogQueryCapability.None) if (queryCapability == PlayLogQueryCapability.None)
{ {

View File

@ -76,7 +76,7 @@ namespace Ryujinx.HLE.HOS.Services.Sdb.Pl
Nca nca = new(_device.System.KeySet, ncaFileStream); Nca nca = new(_device.System.KeySet, ncaFileStream);
IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, _device.System.FsIntegrityCheckLevel); IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, _device.System.FsIntegrityCheckLevel);
using var fontFile = new UniqueRef<IFile>(); using UniqueRef<IFile> fontFile = new UniqueRef<IFile>();
romfs.OpenFile(ref fontFile.Ref, ("/" + fontFilename).ToU8Span(), OpenMode.Read).ThrowIfFailure(); romfs.OpenFile(ref fontFile.Ref, ("/" + fontFilename).ToU8Span(), OpenMode.Read).ThrowIfFailure();

View File

@ -1,3 +1,4 @@
using Microsoft.IO;
using Ryujinx.Common; using Ryujinx.Common;
using Ryujinx.Common.Logging; using Ryujinx.Common.Logging;
using Ryujinx.Common.Memory; using Ryujinx.Common.Memory;
@ -235,7 +236,7 @@ namespace Ryujinx.HLE.HOS.Services
} }
} }
var rc = _context.Syscall.ReplyAndReceive(out int signaledIndex, handles.AsSpan(0, handleCount), replyTargetHandle, -1); Result rc = _context.Syscall.ReplyAndReceive(out int signaledIndex, handles.AsSpan(0, handleCount), replyTargetHandle, -1);
_selfThread.HandlePostSyscall(); _selfThread.HandlePostSyscall();
@ -307,7 +308,7 @@ namespace Ryujinx.HLE.HOS.Services
{ {
_context.Syscall.CloseHandle(serverSessionHandle); _context.Syscall.CloseHandle(serverSessionHandle);
if (RemoveSessionObj(serverSessionHandle, out var session)) if (RemoveSessionObj(serverSessionHandle, out IpcService session))
{ {
(session as IDisposable)?.Dispose(); (session as IDisposable)?.Dispose();
} }
@ -453,7 +454,7 @@ namespace Ryujinx.HLE.HOS.Services
response.RawData = _responseDataStream.ToArray(); response.RawData = _responseDataStream.ToArray();
using var responseStream = response.GetStreamTipc(); using RecyclableMemoryStream responseStream = response.GetStreamTipc();
_selfProcess.CpuMemory.Write(_selfThread.TlsAddress, responseStream.GetReadOnlySequence()); _selfProcess.CpuMemory.Write(_selfThread.TlsAddress, responseStream.GetReadOnlySequence());
} }
else else
@ -463,7 +464,7 @@ namespace Ryujinx.HLE.HOS.Services
if (!isTipcCommunication) if (!isTipcCommunication)
{ {
using var responseStream = response.GetStream((long)_selfThread.TlsAddress, recvListAddr | ((ulong)PointerBufferSize << 48)); using RecyclableMemoryStream responseStream = response.GetStream((long)_selfThread.TlsAddress, recvListAddr | ((ulong)PointerBufferSize << 48));
_selfProcess.CpuMemory.Write(_selfThread.TlsAddress, responseStream.GetReadOnlySequence()); _selfProcess.CpuMemory.Write(_selfThread.TlsAddress, responseStream.GetReadOnlySequence());
} }

View File

@ -326,7 +326,7 @@ namespace Ryujinx.HLE.HOS.Services.Settings
IFileSystem firmwareRomFs = firmwareContent.OpenFileSystem(NcaSectionType.Data, device.System.FsIntegrityCheckLevel); IFileSystem firmwareRomFs = firmwareContent.OpenFileSystem(NcaSectionType.Data, device.System.FsIntegrityCheckLevel);
using var firmwareFile = new UniqueRef<IFile>(); using UniqueRef<IFile> firmwareFile = new UniqueRef<IFile>();
Result result = firmwareRomFs.OpenFile(ref firmwareFile.Ref, "/file".ToU8Span(), OpenMode.Read); Result result = firmwareRomFs.OpenFile(ref firmwareFile.Ref, "/file".ToU8Span(), OpenMode.Read);
if (result.IsFailure()) if (result.IsFailure())

View File

@ -315,9 +315,9 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd
} }
} }
using var readFdsOut = context.Memory.GetWritableRegion(readFdsOutBufferPosition, (int)readFdsOutBufferSize); using WritableRegion readFdsOut = context.Memory.GetWritableRegion(readFdsOutBufferPosition, (int)readFdsOutBufferSize);
using var writeFdsOut = context.Memory.GetWritableRegion(writeFdsOutBufferPosition, (int)writeFdsOutBufferSize); using WritableRegion writeFdsOut = context.Memory.GetWritableRegion(writeFdsOutBufferPosition, (int)writeFdsOutBufferSize);
using var errorFdsOut = context.Memory.GetWritableRegion(errorFdsOutBufferPosition, (int)errorFdsOutBufferSize); using WritableRegion errorFdsOut = context.Memory.GetWritableRegion(errorFdsOutBufferPosition, (int)errorFdsOutBufferSize);
_context.BuildMask(readFds, readFdsOut.Memory.Span); _context.BuildMask(readFds, readFdsOut.Memory.Span);
_context.BuildMask(writeFds, writeFdsOut.Memory.Span); _context.BuildMask(writeFds, writeFdsOut.Memory.Span);

View File

@ -303,7 +303,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl
public static bool TryConvertSocketOption(BsdSocketOption option, SocketOptionLevel level, out SocketOptionName name) public static bool TryConvertSocketOption(BsdSocketOption option, SocketOptionLevel level, out SocketOptionName name)
{ {
var table = level switch Dictionary<BsdSocketOption, SocketOptionName> table = level switch
{ {
SocketOptionLevel.Socket => _soSocketOptionMap, SocketOptionLevel.Socket => _soSocketOptionMap,
SocketOptionLevel.IP => _ipSocketOptionMap, SocketOptionLevel.IP => _ipSocketOptionMap,
@ -322,7 +322,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl
public static LinuxError ValidateSocketOption(BsdSocketOption option, SocketOptionLevel level, bool write) public static LinuxError ValidateSocketOption(BsdSocketOption option, SocketOptionLevel level, bool write)
{ {
var table = level switch Dictionary<BsdSocketOption, OptionDir> table = level switch
{ {
SocketOptionLevel.Socket => _validSoSocketOptionMap, SocketOptionLevel.Socket => _validSoSocketOptionMap,
SocketOptionLevel.IP => _validIpSocketOptionMap, SocketOptionLevel.IP => _validIpSocketOptionMap,

View File

@ -12,9 +12,9 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Proxy
public static void Select(List<ISocketImpl> readEvents, List<ISocketImpl> writeEvents, List<ISocketImpl> errorEvents, int timeout) public static void Select(List<ISocketImpl> readEvents, List<ISocketImpl> writeEvents, List<ISocketImpl> errorEvents, int timeout)
{ {
var readDefault = readEvents.Select(x => (x as DefaultSocket)?.BaseSocket).Where(x => x != null).ToList(); List<Socket> readDefault = readEvents.Select(x => (x as DefaultSocket)?.BaseSocket).Where(x => x != null).ToList();
var writeDefault = writeEvents.Select(x => (x as DefaultSocket)?.BaseSocket).Where(x => x != null).ToList(); List<Socket> writeDefault = writeEvents.Select(x => (x as DefaultSocket)?.BaseSocket).Where(x => x != null).ToList();
var errorDefault = errorEvents.Select(x => (x as DefaultSocket)?.BaseSocket).Where(x => x != null).ToList(); List<Socket> errorDefault = errorEvents.Select(x => (x as DefaultSocket)?.BaseSocket).Where(x => x != null).ToList();
if (readDefault.Count != 0 || writeDefault.Count != 0 || errorDefault.Count != 0) if (readDefault.Count != 0 || writeDefault.Count != 0 || errorDefault.Count != 0)
{ {

View File

@ -82,7 +82,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Sfdnsres.Proxy
public IPHostEntry ResolveAddress(string host) public IPHostEntry ResolveAddress(string host)
{ {
foreach (var hostEntry in _mitmHostEntries) foreach (KeyValuePair<string, IPAddress> hostEntry in _mitmHostEntries)
{ {
// Check for AMS hosts file extension: "*" // Check for AMS hosts file extension: "*"
// NOTE: MatchesSimpleExpression also allows "?" as a wildcard // NOTE: MatchesSimpleExpression also allows "?" as a wildcard

View File

@ -129,7 +129,7 @@ namespace Ryujinx.HLE.HOS.Services.Ssl
IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, _fsIntegrityCheckLevel); IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, _fsIntegrityCheckLevel);
using var trustedCertsFileRef = new UniqueRef<IFile>(); using UniqueRef<IFile> trustedCertsFileRef = new UniqueRef<IFile>();
Result result = romfs.OpenFile(ref trustedCertsFileRef.Ref, "/ssl_TrustedCerts.bdf".ToU8Span(), OpenMode.Read); Result result = romfs.OpenFile(ref trustedCertsFileRef.Ref, "/ssl_TrustedCerts.bdf".ToU8Span(), OpenMode.Read);

View File

@ -145,7 +145,7 @@ namespace Ryujinx.HLE.HOS.Services.Ssl.SslService
ulong bufferAddress = context.Request.ReceiveBuff[0].Position; ulong bufferAddress = context.Request.ReceiveBuff[0].Position;
ulong bufferLen = context.Request.ReceiveBuff[0].Size; ulong bufferLen = context.Request.ReceiveBuff[0].Size;
using (var region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true)) using (WritableRegion region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true))
{ {
Encoding.ASCII.GetBytes(_hostName, region.Memory.Span); Encoding.ASCII.GetBytes(_hostName, region.Memory.Span);
} }

View File

@ -94,7 +94,7 @@ namespace Ryujinx.HLE.HOS.Services.Time.TimeZone
Nca nca = new(_virtualFileSystem.KeySet, ncaFileStream); Nca nca = new(_virtualFileSystem.KeySet, ncaFileStream);
IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, _fsIntegrityCheckLevel); IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, _fsIntegrityCheckLevel);
using var binaryListFile = new UniqueRef<IFile>(); using UniqueRef<IFile> binaryListFile = new UniqueRef<IFile>();
romfs.OpenFile(ref binaryListFile.Ref, "/binaryList.txt".ToU8Span(), OpenMode.Read).ThrowIfFailure(); romfs.OpenFile(ref binaryListFile.Ref, "/binaryList.txt".ToU8Span(), OpenMode.Read).ThrowIfFailure();
@ -120,7 +120,7 @@ namespace Ryujinx.HLE.HOS.Services.Time.TimeZone
public IEnumerable<(int Offset, string Location, string Abbr)> ParseTzOffsets() public IEnumerable<(int Offset, string Location, string Abbr)> ParseTzOffsets()
{ {
var tzBinaryContentPath = GetTimeZoneBinaryTitleContentPath(); string tzBinaryContentPath = GetTimeZoneBinaryTitleContentPath();
if (string.IsNullOrEmpty(tzBinaryContentPath)) if (string.IsNullOrEmpty(tzBinaryContentPath))
{ {
@ -128,7 +128,7 @@ namespace Ryujinx.HLE.HOS.Services.Time.TimeZone
} }
List<(int Offset, string Location, string Abbr)> outList = new(); List<(int Offset, string Location, string Abbr)> outList = new();
var now = DateTimeOffset.Now.ToUnixTimeSeconds(); long now = DateTimeOffset.Now.ToUnixTimeSeconds();
using (IStorage ncaStorage = new LocalStorage(VirtualFileSystem.SwitchPathToSystemPath(tzBinaryContentPath), FileAccess.Read, FileMode.Open)) using (IStorage ncaStorage = new LocalStorage(VirtualFileSystem.SwitchPathToSystemPath(tzBinaryContentPath), FileAccess.Read, FileMode.Open))
using (IFileSystem romfs = new Nca(_virtualFileSystem.KeySet, ncaStorage).OpenFileSystem(NcaSectionType.Data, _fsIntegrityCheckLevel)) using (IFileSystem romfs = new Nca(_virtualFileSystem.KeySet, ncaStorage).OpenFileSystem(NcaSectionType.Data, _fsIntegrityCheckLevel))
{ {
@ -139,7 +139,7 @@ namespace Ryujinx.HLE.HOS.Services.Time.TimeZone
continue; continue;
} }
using var tzif = new UniqueRef<IFile>(); using UniqueRef<IFile> tzif = new UniqueRef<IFile>();
if (romfs.OpenFile(ref tzif.Ref, $"/zoneinfo/{locName}".ToU8Span(), OpenMode.Read).IsFailure()) if (romfs.OpenFile(ref tzif.Ref, $"/zoneinfo/{locName}".ToU8Span(), OpenMode.Read).IsFailure())
{ {
@ -176,7 +176,7 @@ namespace Ryujinx.HLE.HOS.Services.Time.TimeZone
continue; continue;
} }
var abbrStart = tzRule.Chars[ttInfo.AbbreviationListIndex..]; Span<byte> abbrStart = tzRule.Chars[ttInfo.AbbreviationListIndex..];
int abbrEnd = abbrStart.IndexOf((byte)0); int abbrEnd = abbrStart.IndexOf((byte)0);
outList.Add((ttInfo.GmtOffset, locName, Encoding.UTF8.GetString(abbrStart[..abbrEnd]))); outList.Add((ttInfo.GmtOffset, locName, Encoding.UTF8.GetString(abbrStart[..abbrEnd])));
@ -269,7 +269,7 @@ namespace Ryujinx.HLE.HOS.Services.Time.TimeZone
Nca nca = new(_virtualFileSystem.KeySet, ncaFile); Nca nca = new(_virtualFileSystem.KeySet, ncaFile);
IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, _fsIntegrityCheckLevel); IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, _fsIntegrityCheckLevel);
using var timeZoneBinaryFile = new UniqueRef<IFile>(); using UniqueRef<IFile> timeZoneBinaryFile = new UniqueRef<IFile>();
Result result = romfs.OpenFile(ref timeZoneBinaryFile.Ref, $"/zoneinfo/{locationName}".ToU8Span(), OpenMode.Read); Result result = romfs.OpenFile(ref timeZoneBinaryFile.Ref, $"/zoneinfo/{locationName}".ToU8Span(), OpenMode.Read);

View File

@ -40,7 +40,7 @@ namespace Ryujinx.HLE.HOS.Tamper.CodeEmitters
} }
// Use the conditional begin instruction stored in the stack. // Use the conditional begin instruction stored in the stack.
var upperInstruction = context.CurrentBlock.BaseInstruction; byte[] upperInstruction = context.CurrentBlock.BaseInstruction;
CodeType codeType = InstructionHelper.GetCodeType(upperInstruction); CodeType codeType = InstructionHelper.GetCodeType(upperInstruction);
// Pop the current block of operations from the stack so control instructions // Pop the current block of operations from the stack so control instructions

View File

@ -96,7 +96,7 @@ namespace Ryujinx.HLE.HOS.Tamper
// Instructions are multi-word, with 32bit words. Split the raw instruction // Instructions are multi-word, with 32bit words. Split the raw instruction
// and parse each word into individual nybbles of bits. // and parse each word into individual nybbles of bits.
var words = rawInstruction.Split((char[])null, StringSplitOptions.RemoveEmptyEntries); string[] words = rawInstruction.Split((char[])null, StringSplitOptions.RemoveEmptyEntries);
byte[] instruction = new byte[WordSize * words.Length]; byte[] instruction = new byte[WordSize * words.Length];

View File

@ -70,14 +70,14 @@ namespace Ryujinx.HLE.HOS
public void EnableCheats(string[] enabledCheats) public void EnableCheats(string[] enabledCheats)
{ {
foreach (var program in _programDictionary.Values) foreach (ITamperProgram program in _programDictionary.Values)
{ {
program.IsEnabled = false; program.IsEnabled = false;
} }
foreach (var cheat in enabledCheats) foreach (string cheat in enabledCheats)
{ {
if (_programDictionary.TryGetValue(cheat, out var program)) if (_programDictionary.TryGetValue(cheat, out ITamperProgram program))
{ {
program.IsEnabled = true; program.IsEnabled = true;
} }

View File

@ -76,7 +76,7 @@ namespace Ryujinx.HLE.Loaders.Executables
{ {
reader.GetSegmentSize(segmentType, out int uncompressedSize).ThrowIfFailure(); reader.GetSegmentSize(segmentType, out int uncompressedSize).ThrowIfFailure();
var span = program.AsSpan((int)offset, uncompressedSize); Span<byte> span = program.AsSpan((int)offset, uncompressedSize);
reader.ReadSegment(segmentType, span).ThrowIfFailure(); reader.ReadSegment(segmentType, span).ThrowIfFailure();

View File

@ -65,7 +65,7 @@ namespace Ryujinx.HLE.Loaders.Executables
{ {
reader.GetSegmentSize(segmentType, out uint uncompressedSize).ThrowIfFailure(); reader.GetSegmentSize(segmentType, out uint uncompressedSize).ThrowIfFailure();
var span = Program.AsSpan((int)offset, (int)uncompressedSize); Span<byte> span = Program.AsSpan((int)offset, (int)uncompressedSize);
reader.ReadSegment(segmentType, span).ThrowIfFailure(); reader.ReadSegment(segmentType, span).ThrowIfFailure();

View File

@ -25,7 +25,7 @@ namespace Ryujinx.HLE.Loaders.Mods
ReadOnlySpan<byte> ips32TailMagic = "EEOF"u8; ReadOnlySpan<byte> ips32TailMagic = "EEOF"u8;
MemPatch patches = new(); MemPatch patches = new();
var header = reader.ReadBytes(ipsHeaderMagic.Length).AsSpan(); Span<byte> header = reader.ReadBytes(ipsHeaderMagic.Length).AsSpan();
if (header.Length != ipsHeaderMagic.Length) if (header.Length != ipsHeaderMagic.Length)
{ {
@ -94,7 +94,7 @@ namespace Ryujinx.HLE.Loaders.Mods
} }
else // Copy mode else // Copy mode
{ {
var patch = reader.ReadBytes(patchSize); byte[] patch = reader.ReadBytes(patchSize);
if (patch.Length != patchSize) if (patch.Length != patchSize)
{ {

View File

@ -200,7 +200,7 @@ namespace Ryujinx.HLE.Loaders.Mods
} }
else if (line.StartsWith("@flag")) else if (line.StartsWith("@flag"))
{ {
var tokens = line.Split(' ', 3, StringSplitOptions.RemoveEmptyEntries); string[] tokens = line.Split(' ', 3, StringSplitOptions.RemoveEmptyEntries);
if (tokens.Length < 2) if (tokens.Length < 2)
{ {
@ -234,7 +234,7 @@ namespace Ryujinx.HLE.Loaders.Mods
continue; continue;
} }
var tokens = line.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries); string[] tokens = line.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);
if (tokens.Length < 2) if (tokens.Length < 2)
{ {
@ -259,12 +259,12 @@ namespace Ryujinx.HLE.Loaders.Mods
if (tokens[1][0] == '"') if (tokens[1][0] == '"')
{ {
var patch = Encoding.ASCII.GetBytes(tokens[1].Trim('"') + "\0"); byte[] patch = Encoding.ASCII.GetBytes(tokens[1].Trim('"') + "\0");
patches.Add((uint)offset, patch); patches.Add((uint)offset, patch);
} }
else else
{ {
var patch = Hex2ByteArrayBE(tokens[1]); byte[] patch = Hex2ByteArrayBE(tokens[1]);
patches.Add((uint)offset, patch); patches.Add((uint)offset, patch);
} }
} }

View File

@ -46,7 +46,7 @@ namespace Ryujinx.HLE.Loaders.Mods
return; return;
} }
foreach (var (patchOffset, patch) in patches._patches) foreach ((uint patchOffset, byte[] patch) in patches._patches)
{ {
_patches[patchOffset] = patch; _patches[patchOffset] = patch;
} }
@ -66,7 +66,7 @@ namespace Ryujinx.HLE.Loaders.Mods
public int Patch(Span<byte> memory, int protectedOffset = 0) public int Patch(Span<byte> memory, int protectedOffset = 0)
{ {
int count = 0; int count = 0;
foreach (var (offset, patch) in _patches.OrderBy(item => item.Key)) foreach ((uint offset, byte[] patch) in _patches.OrderBy(item => item.Key))
{ {
int patchOffset = (int)offset; int patchOffset = (int)offset;
int patchSize = patch.Length; int patchSize = patch.Length;

View File

@ -62,7 +62,7 @@ namespace Ryujinx.HLE.Loaders.Processes.Extensions
Logger.Info?.Print(LogClass.Loader, $"Loading {name}..."); Logger.Info?.Print(LogClass.Loader, $"Loading {name}...");
using var nsoFile = new UniqueRef<IFile>(); using UniqueRef<IFile> nsoFile = new UniqueRef<IFile>();
exeFs.OpenFile(ref nsoFile.Ref, $"/{name}".ToU8Span(), OpenMode.Read).ThrowIfFailure(); exeFs.OpenFile(ref nsoFile.Ref, $"/{name}".ToU8Span(), OpenMode.Read).ThrowIfFailure();

View File

@ -12,7 +12,7 @@ namespace Ryujinx.HLE.Loaders.Processes
public static ProcessResult Load(this LocalFileSystem exeFs, Switch device, string romFsPath = "") public static ProcessResult Load(this LocalFileSystem exeFs, Switch device, string romFsPath = "")
{ {
MetaLoader metaLoader = exeFs.GetNpdm(); MetaLoader metaLoader = exeFs.GetNpdm();
var nacpData = new BlitStruct<ApplicationControlProperty>(1); BlitStruct<ApplicationControlProperty> nacpData = new BlitStruct<ApplicationControlProperty>(1);
ulong programId = metaLoader.GetProgramId(); ulong programId = metaLoader.GetProgramId();
device.Configuration.VirtualFileSystem.ModLoader.CollectMods([programId]); device.Configuration.VirtualFileSystem.ModLoader.CollectMods([programId]);

View File

@ -12,21 +12,21 @@ namespace Ryujinx.HLE.Loaders.Processes.Extensions
{ {
public static ulong GetProgramId(this MetaLoader metaLoader) public static ulong GetProgramId(this MetaLoader metaLoader)
{ {
metaLoader.GetNpdm(out var npdm).ThrowIfFailure(); metaLoader.GetNpdm(out LibHac.Loader.Npdm npdm).ThrowIfFailure();
return npdm.Aci.ProgramId.Value; return npdm.Aci.ProgramId.Value;
} }
public static string GetProgramName(this MetaLoader metaLoader) public static string GetProgramName(this MetaLoader metaLoader)
{ {
metaLoader.GetNpdm(out var npdm).ThrowIfFailure(); metaLoader.GetNpdm(out LibHac.Loader.Npdm npdm).ThrowIfFailure();
return StringUtils.Utf8ZToString(npdm.Meta.ProgramName); return StringUtils.Utf8ZToString(npdm.Meta.ProgramName);
} }
public static bool IsProgram64Bit(this MetaLoader metaLoader) public static bool IsProgram64Bit(this MetaLoader metaLoader)
{ {
metaLoader.GetNpdm(out var npdm).ThrowIfFailure(); metaLoader.GetNpdm(out LibHac.Loader.Npdm npdm).ThrowIfFailure();
return (npdm.Meta.Flags & 1) != 0; return (npdm.Meta.Flags & 1) != 0;
} }
@ -45,7 +45,7 @@ namespace Ryujinx.HLE.Loaders.Processes.Extensions
path = ProcessConst.MainNpdmPath; path = ProcessConst.MainNpdmPath;
} }
using var npdmFile = new UniqueRef<IFile>(); using UniqueRef<IFile> npdmFile = new UniqueRef<IFile>();
fileSystem.OpenFile(ref npdmFile.Ref, path.ToU8Span(), OpenMode.Read).ThrowIfFailure(); fileSystem.OpenFile(ref npdmFile.Ref, path.ToU8Span(), OpenMode.Read).ThrowIfFailure();

View File

@ -49,7 +49,7 @@ namespace Ryujinx.HLE.Loaders.Processes.Extensions
ModLoader.GetSdModsBasePath()); ModLoader.GetSdModsBasePath());
// Load Nacp file. // Load Nacp file.
var nacpData = new BlitStruct<ApplicationControlProperty>(1); BlitStruct<ApplicationControlProperty> nacpData = new BlitStruct<ApplicationControlProperty>(1);
if (controlNca != null) if (controlNca != null)
{ {
@ -214,9 +214,9 @@ namespace Ryujinx.HLE.Loaders.Processes.Extensions
public static BlitStruct<ApplicationControlProperty> GetNacp(this Nca controlNca, Switch device) public static BlitStruct<ApplicationControlProperty> GetNacp(this Nca controlNca, Switch device)
{ {
var nacpData = new BlitStruct<ApplicationControlProperty>(1); BlitStruct<ApplicationControlProperty> nacpData = new BlitStruct<ApplicationControlProperty>(1);
using var controlFile = new UniqueRef<IFile>(); using UniqueRef<IFile> controlFile = new UniqueRef<IFile>();
Result result = controlNca.OpenFileSystem(NcaSectionType.Data, device.System.FsIntegrityCheckLevel) Result result = controlNca.OpenFileSystem(NcaSectionType.Data, device.System.FsIntegrityCheckLevel)
.OpenFile(ref controlFile.Ref, "/control.nacp".ToU8Span(), OpenMode.Read); .OpenFile(ref controlFile.Ref, "/control.nacp".ToU8Span(), OpenMode.Read);
@ -236,7 +236,7 @@ namespace Ryujinx.HLE.Loaders.Processes.Extensions
public static Cnmt GetCnmt(this Nca cnmtNca, IntegrityCheckLevel checkLevel, ContentMetaType metaType) public static Cnmt GetCnmt(this Nca cnmtNca, IntegrityCheckLevel checkLevel, ContentMetaType metaType)
{ {
string path = $"/{metaType}_{cnmtNca.Header.TitleId:x16}.cnmt"; string path = $"/{metaType}_{cnmtNca.Header.TitleId:x16}.cnmt";
using var cnmtFile = new UniqueRef<IFile>(); using UniqueRef<IFile> cnmtFile = new UniqueRef<IFile>();
try try
{ {

View File

@ -28,7 +28,7 @@ namespace Ryujinx.HLE.Loaders.Processes.Extensions
{ {
fileSystem.ImportTickets(partitionFileSystem); fileSystem.ImportTickets(partitionFileSystem);
var programs = new Dictionary<ulong, ContentMetaData>(); Dictionary<ulong, ContentMetaData> programs = new Dictionary<ulong, ContentMetaData>();
foreach (DirectoryEntryEx fileEntry in partitionFileSystem.EnumerateEntries("/", "*.cnmt.nca")) foreach (DirectoryEntryEx fileEntry in partitionFileSystem.EnumerateEntries("/", "*.cnmt.nca"))
{ {
@ -152,7 +152,7 @@ namespace Ryujinx.HLE.Loaders.Processes.Extensions
public static Nca GetNca(this IFileSystem fileSystem, KeySet keySet, string path) public static Nca GetNca(this IFileSystem fileSystem, KeySet keySet, string path)
{ {
using var ncaFile = new UniqueRef<IFile>(); using UniqueRef<IFile> ncaFile = new UniqueRef<IFile>();
fileSystem.OpenFile(ref ncaFile.Ref, path.ToU8Span(), OpenMode.Read).ThrowIfFailure(); fileSystem.OpenFile(ref ncaFile.Ref, path.ToU8Span(), OpenMode.Read).ThrowIfFailure();

View File

@ -161,7 +161,7 @@ namespace Ryujinx.HLE.Loaders.Processes
public bool LoadNxo(string path) public bool LoadNxo(string path)
{ {
var nacpData = new BlitStruct<ApplicationControlProperty>(1); BlitStruct<ApplicationControlProperty> nacpData = new BlitStruct<ApplicationControlProperty>(1);
IFileSystem dummyExeFs = null; IFileSystem dummyExeFs = null;
Stream romfsStream = null; Stream romfsStream = null;

View File

@ -180,7 +180,7 @@ namespace Ryujinx.HLE.Loaders.Processes
KProcess process = new(context); KProcess process = new(context);
var processContextFactory = new ArmProcessContextFactory( ArmProcessContextFactory processContextFactory = new ArmProcessContextFactory(
context.Device.System.TickSource, context.Device.System.TickSource,
context.Device.Gpu, context.Device.Gpu,
string.Empty, string.Empty,
@ -235,7 +235,7 @@ namespace Ryujinx.HLE.Loaders.Processes
{ {
context.Device.System.ServiceTable.WaitServicesReady(); context.Device.System.ServiceTable.WaitServicesReady();
LibHac.Result resultCode = metaLoader.GetNpdm(out var npdm); LibHac.Result resultCode = metaLoader.GetNpdm(out LibHac.Loader.Npdm npdm);
if (resultCode.IsFailure()) if (resultCode.IsFailure())
{ {
@ -244,14 +244,14 @@ namespace Ryujinx.HLE.Loaders.Processes
return ProcessResult.Failed; return ProcessResult.Failed;
} }
ref readonly var meta = ref npdm.Meta; ref readonly Meta meta = ref npdm.Meta;
ulong argsStart = 0; ulong argsStart = 0;
uint argsSize = 0; uint argsSize = 0;
ulong codeStart = ((meta.Flags & 1) != 0 ? 0x8000000UL : 0x200000UL) + CodeStartOffset; ulong codeStart = ((meta.Flags & 1) != 0 ? 0x8000000UL : 0x200000UL) + CodeStartOffset;
uint codeSize = 0; uint codeSize = 0;
var buildIds = new string[executables.Length]; string[] buildIds = new string[executables.Length];
for (int i = 0; i < executables.Length; i++) for (int i = 0; i < executables.Length; i++)
{ {
@ -373,7 +373,7 @@ namespace Ryujinx.HLE.Loaders.Processes
displayVersion = device.System.ContentManager.GetCurrentFirmwareVersion()?.VersionString ?? string.Empty; displayVersion = device.System.ContentManager.GetCurrentFirmwareVersion()?.VersionString ?? string.Empty;
} }
var processContextFactory = new ArmProcessContextFactory( ArmProcessContextFactory processContextFactory = new ArmProcessContextFactory(
context.Device.System.TickSource, context.Device.System.TickSource,
context.Device.Gpu, context.Device.Gpu,
$"{programId:x16}", $"{programId:x16}",

View File

@ -18,7 +18,7 @@ namespace Ryujinx.HLE
const int OffsetOfApplicationPublisherStrings = 0x200; const int OffsetOfApplicationPublisherStrings = 0x200;
var nacpData = new BlitStruct<ApplicationControlProperty>(1); BlitStruct<ApplicationControlProperty> nacpData = new BlitStruct<ApplicationControlProperty>(1);
// name and publisher buffer // name and publisher buffer
// repeat once for each locale (the ApplicationControlProperty has 16 locales) // repeat once for each locale (the ApplicationControlProperty has 16 locales)

View File

@ -1,5 +1,7 @@
using Ryujinx.Common.Memory;
using Ryujinx.HLE.HOS.Services.Hid.Types.SharedMemory.Common; using Ryujinx.HLE.HOS.Services.Hid.Types.SharedMemory.Common;
using Ryujinx.HLE.HOS.Services.Hid.Types.SharedMemory.Npad; using Ryujinx.HLE.HOS.Services.Hid.Types.SharedMemory.Npad;
using System;
namespace Ryujinx.HLE.UI.Input namespace Ryujinx.HLE.UI.Input
{ {
@ -29,7 +31,7 @@ namespace Ryujinx.HLE.UI.Input
{ {
NpadButton buttons = 0; NpadButton buttons = 0;
foreach (var state in _lastStates) foreach (NpadCommonState state in _lastStates)
{ {
buttons |= state.Buttons; buttons |= state.Buttons;
} }
@ -60,7 +62,7 @@ namespace Ryujinx.HLE.UI.Input
public void Update(bool supressEvents = false) public void Update(bool supressEvents = false)
{ {
ref var npads = ref _device.Hid.SharedMemory.Npads; ref Array10<NpadState> npads = ref _device.Hid.SharedMemory.Npads;
// Process each input individually. // Process each input individually.
for (int npadIndex = 0; npadIndex < npads.Length; npadIndex++) for (int npadIndex = 0; npadIndex < npads.Length; npadIndex++)
@ -73,10 +75,10 @@ namespace Ryujinx.HLE.UI.Input
{ {
const int MaxEntries = 1024; const int MaxEntries = 1024;
ref var npadState = ref _device.Hid.SharedMemory.Npads[npadIndex]; ref NpadState npadState = ref _device.Hid.SharedMemory.Npads[npadIndex];
ref var lastEntry = ref _lastStates[npadIndex]; ref NpadCommonState lastEntry = ref _lastStates[npadIndex];
var fullKeyEntries = GetCommonStateLifo(ref npadState.InternalState).ReadEntries(MaxEntries); ReadOnlySpan<AtomicStorage<NpadCommonState>> fullKeyEntries = GetCommonStateLifo(ref npadState.InternalState).ReadEntries(MaxEntries);
int firstEntryNum; int firstEntryNum;
@ -94,7 +96,7 @@ namespace Ryujinx.HLE.UI.Input
for (; firstEntryNum >= 0; firstEntryNum--) for (; firstEntryNum >= 0; firstEntryNum--)
{ {
var entry = fullKeyEntries[firstEntryNum]; AtomicStorage<NpadCommonState> entry = fullKeyEntries[firstEntryNum];
// The interval of valid entries should be contiguous. // The interval of valid entries should be contiguous.
if (entry.SamplingNumber < lastEntry.SamplingNumber) if (entry.SamplingNumber < lastEntry.SamplingNumber)

View File

@ -22,7 +22,7 @@ namespace Ryujinx.HLE.Utilities
} }
else else
{ {
var pfsTemp = new PartitionFileSystem(); PartitionFileSystem pfsTemp = new PartitionFileSystem();
Result initResult = pfsTemp.Initialize(file.AsStorage()); Result initResult = pfsTemp.Initialize(file.AsStorage());
if (throwOnFailure) if (throwOnFailure)