Fix ~3500 analyser issues

See merge request ryubing/ryujinx!44
This commit is contained in:
MrKev 2025-05-30 17:08:34 -05:00 committed by LotP
parent 417df486b1
commit 361d0c5632
622 changed files with 3080 additions and 2652 deletions

View file

@ -111,10 +111,12 @@ namespace Ryujinx.HLE.FileSystem
{
continue;
}
if (!ContentPath.TryGetRealPath(contentPathString, out string contentDirectory))
{
continue;
}
string registeredDirectory = Path.Combine(contentDirectory, "registered");
Directory.CreateDirectory(registeredDirectory);
@ -464,6 +466,7 @@ namespace Ryujinx.HLE.FileSystem
{
InstallFromZip(archive, temporaryDirectory);
}
break;
case ".xci":
Xci xci = new(_virtualFileSystem.KeySet, file.AsStorage());
@ -476,7 +479,7 @@ namespace Ryujinx.HLE.FileSystem
FinishInstallation(temporaryDirectory, registeredDirectory);
}
public void InstallKeys(string keysSource, string installDirectory)
public static void InstallKeys(string keysSource, string installDirectory)
{
if (Directory.Exists(keysSource))
{
@ -505,6 +508,7 @@ namespace Ryujinx.HLE.FileSystem
{
InstallKeysFromZip(archive, installDirectory);
}
break;
case ".keys":
VerifyKeysFile(keysSource);
@ -515,13 +519,14 @@ namespace Ryujinx.HLE.FileSystem
}
}
private void InstallKeysFromZip(ZipArchive archive, string installDirectory)
private static void InstallKeysFromZip(ZipArchive archive, string installDirectory)
{
string temporaryDirectory = Path.Combine(installDirectory, "temp");
if (Directory.Exists(temporaryDirectory))
{
Directory.Delete(temporaryDirectory, true);
}
Directory.CreateDirectory(temporaryDirectory);
foreach (ZipArchiveEntry entry in archive.Entries)
{
@ -541,6 +546,7 @@ namespace Ryujinx.HLE.FileSystem
}
}
}
Directory.Delete(temporaryDirectory, true);
}
@ -567,7 +573,7 @@ namespace Ryujinx.HLE.FileSystem
{
Nca nca = new(_virtualFileSystem.KeySet, OpenPossibleFragmentedFile(filesystem, entry.FullPath, OpenMode.Read).AsStorage());
SaveNca(nca, entry.Name.Remove(entry.Name.IndexOf('.')), temporaryDirectory);
SaveNca(nca, entry.Name[..entry.Name.IndexOf('.')], temporaryDirectory);
}
}
@ -641,7 +647,7 @@ namespace Ryujinx.HLE.FileSystem
return file.Release();
}
private static Stream GetZipStream(ZipArchiveEntry entry)
private static MemoryStream GetZipStream(ZipArchiveEntry entry)
{
MemoryStream dest = MemoryStreamManager.Shared.GetStream();
@ -1016,7 +1022,7 @@ namespace Ryujinx.HLE.FileSystem
return null;
}
public void VerifyKeysFile(string filePath)
public static void VerifyKeysFile(string filePath)
{
// Verify the keys file format refers to https://github.com/Thealexbarney/LibHac/blob/master/KEYS.md
string genericPattern = @"^[a-z0-9_]+ = [a-z0-9]+$";
@ -1028,7 +1034,7 @@ namespace Ryujinx.HLE.FileSystem
string fileName = Path.GetFileName(filePath);
string[] lines = File.ReadAllLines(filePath);
bool verified = false;
bool verified;
switch (fileName)
{
case "prod.keys":
@ -1046,18 +1052,20 @@ namespace Ryujinx.HLE.FileSystem
default:
throw new FormatException($"Keys file name \"{fileName}\" not supported. Only \"prod.keys\", \"title.keys\", \"console.keys\", \"dev.keys\" are supported.");
}
if (!verified)
{
throw new FormatException($"Invalid \"{filePath}\" file format.");
}
} else
}
else
{
throw new FileNotFoundException($"Keys file not found at \"{filePath}\".");
}
return;
bool VerifyKeys(string[] lines, string regex)
static bool VerifyKeys(string[] lines, string regex)
{
foreach (string line in lines)
{
@ -1066,11 +1074,12 @@ namespace Ryujinx.HLE.FileSystem
return false;
}
}
return true;
}
}
public bool AreKeysAlredyPresent(string pathToCheck)
public static bool AreKeysAlredyPresent(string pathToCheck)
{
string[] fileNames = ["prod.keys", "title.keys", "console.keys", "dev.keys"];
foreach (string file in fileNames)
@ -1080,6 +1089,7 @@ namespace Ryujinx.HLE.FileSystem
return true;
}
}
return false;
}
}

View file

@ -12,7 +12,7 @@ namespace Ryujinx.HLE.FileSystem
ref readonly SharedRef<IFileSystem> baseFileSystem, IEncryptedFileSystemCreator.KeyId idIndex,
in EncryptionSeed encryptionSeed)
{
if (idIndex < IEncryptedFileSystemCreator.KeyId.Save || idIndex > IEncryptedFileSystemCreator.KeyId.CustomStorage)
if (idIndex is < IEncryptedFileSystemCreator.KeyId.Save or > IEncryptedFileSystemCreator.KeyId.CustomStorage)
{
return ResultFs.InvalidArgument.Log();
}

View file

@ -392,7 +392,7 @@ namespace Ryujinx.HLE.FileSystem
private static Result CreateSaveDataDirectory(HorizonClient hos, in SaveDataInfo info)
{
if (info.SpaceId != SaveDataSpaceId.User && info.SpaceId != SaveDataSpaceId.System)
if (info.SpaceId is not SaveDataSpaceId.User and not SaveDataSpaceId.System)
{
return Result.Success;
}

View file

@ -1,3 +1,4 @@
using Microsoft.IO;
using Ryujinx.Common;
using Ryujinx.Common.Logging;
using Ryujinx.Common.Memory;
@ -63,7 +64,7 @@ namespace Ryujinx.HLE.HOS.Applets.Browser
private static byte[] BuildResponseOld(WebCommonReturnValue result)
{
using MemoryStream stream = MemoryStreamManager.Shared.GetStream();
using RecyclableMemoryStream stream = MemoryStreamManager.Shared.GetStream();
using BinaryWriter writer = new(stream);
writer.WriteStruct(result);
@ -71,7 +72,7 @@ namespace Ryujinx.HLE.HOS.Applets.Browser
}
private byte[] BuildResponseNew(List<BrowserOutput> outputArguments)
{
using MemoryStream stream = MemoryStreamManager.Shared.GetStream();
using RecyclableMemoryStream stream = MemoryStreamManager.Shared.GetStream();
using BinaryWriter writer = new(stream);
writer.WriteStruct(new WebArgHeader
{

View file

@ -1,8 +1,8 @@
using Ryujinx.Common.Logging;
using Ryujinx.Common.Memory;
using Ryujinx.HLE.HOS.Services.Am.AppletAE;
using Ryujinx.HLE.HOS.Services.Hid.HidServer;
using Ryujinx.HLE.HOS.Services.Hid;
using Ryujinx.HLE.HOS.Services.Hid.HidServer;
using Ryujinx.HLE.HOS.Services.Nfc.Nfp;
using Ryujinx.HLE.HOS.Services.Nfc.Nfp.NfpManager;
using System;
@ -75,7 +75,7 @@ namespace Ryujinx.HLE.HOS.Applets.Cabinet
return ResultCode.Success;
}
private void StartFormatter(ref StartParamForAmiiboSettings startParam)
private static void StartFormatter(ref StartParamForAmiiboSettings startParam)
{
// Initialize RegisterInfo
startParam.RegisterInfo = new RegisterInfo();
@ -109,6 +109,7 @@ namespace Ryujinx.HLE.HOS.Applets.Cabinet
}
}
}
VirtualAmiibo.UpdateNickName(amiiboId, newName);
}
@ -154,9 +155,9 @@ namespace Ryujinx.HLE.HOS.Applets.Cabinet
public unsafe struct ReturnValueForAmiiboSettings
{
public byte AmiiboSettingsReturnFlag;
private byte Padding1;
private byte Padding2;
private byte Padding3;
private readonly byte Padding1;
private readonly byte Padding2;
private readonly byte Padding3;
public DeviceHandle DeviceHandle;
public TagInfo TagInfo;
public RegisterInfo RegisterInfo;

View file

@ -1,3 +1,4 @@
using Microsoft.IO;
using Ryujinx.Common.Logging;
using Ryujinx.Common.Memory;
using Ryujinx.HLE.HOS.Services.Am.AppletAE;
@ -119,7 +120,7 @@ namespace Ryujinx.HLE.HOS.Applets
private static byte[] BuildResponse(ControllerSupportResultInfo result)
{
using MemoryStream stream = MemoryStreamManager.Shared.GetStream();
using RecyclableMemoryStream stream = MemoryStreamManager.Shared.GetStream();
using BinaryWriter writer = new(stream);
writer.Write(MemoryMarshal.AsBytes(MemoryMarshal.CreateReadOnlySpan(ref result, Unsafe.SizeOf<ControllerSupportResultInfo>())));
@ -129,7 +130,7 @@ namespace Ryujinx.HLE.HOS.Applets
private static byte[] BuildResponse()
{
using MemoryStream stream = MemoryStreamManager.Shared.GetStream();
using RecyclableMemoryStream stream = MemoryStreamManager.Shared.GetStream();
using BinaryWriter writer = new(stream);
writer.Write((ulong)ResultCode.Success);

View file

@ -1,3 +1,4 @@
using Microsoft.IO;
using Ryujinx.Common.Memory;
using Ryujinx.HLE.HOS.Services.Am.AppletAE;
using System;
@ -9,14 +10,14 @@ namespace Ryujinx.HLE.HOS.Applets.Dummy
{
private readonly Horizon _system;
private AppletSession _normalSession;
public event EventHandler AppletStateChanged;
public DummyApplet(Horizon system)
{
_system = system;
}
public ResultCode Start(AppletSession normalSession, AppletSession interactiveSession)
{
_normalSession = normalSession;
@ -25,10 +26,10 @@ namespace Ryujinx.HLE.HOS.Applets.Dummy
_system.ReturnFocus();
return ResultCode.Success;
}
private static byte[] BuildResponse()
{
using MemoryStream stream = MemoryStreamManager.Shared.GetStream();
using RecyclableMemoryStream stream = MemoryStreamManager.Shared.GetStream();
using BinaryWriter writer = new(stream);
writer.Write((ulong)ResultCode.Success);
return stream.ToArray();

View file

@ -159,7 +159,7 @@ namespace Ryujinx.HLE.HOS.Applets.Error
string[] buttons = GetButtonsText(module, description, "DlgBtn");
(uint Module, uint Description) errorCodeTuple = (module, uint.Parse(description.ToString("0000")));
bool showDetails = _horizon.Device.UIHandler.DisplayErrorAppletDialog($"Error Code: {module}-{description:0000}", "\n" + message, buttons, errorCodeTuple);
if (showDetails)
{

View file

@ -1,3 +1,4 @@
using Microsoft.IO;
using Ryujinx.Common.Memory;
using Ryujinx.HLE.HOS.Services.Account.Acc;
using Ryujinx.HLE.HOS.Services.Am.AppletAE;
@ -26,7 +27,7 @@ namespace Ryujinx.HLE.HOS.Applets
{
_normalSession = normalSession;
_interactiveSession = interactiveSession;
UserProfile selected = _system.Device.UIHandler.ShowPlayerSelectDialog();
if (selected == null)
{
@ -40,6 +41,7 @@ namespace Ryujinx.HLE.HOS.Applets
{
_normalSession.Push(BuildResponse(selected));
}
AppletStateChanged?.Invoke(this, null);
_system.ReturnFocus();
@ -47,9 +49,9 @@ namespace Ryujinx.HLE.HOS.Applets
return ResultCode.Success;
}
private byte[] BuildResponse(UserProfile selectedUser)
private static byte[] BuildResponse(UserProfile selectedUser)
{
using MemoryStream stream = MemoryStreamManager.Shared.GetStream();
using RecyclableMemoryStream stream = MemoryStreamManager.Shared.GetStream();
using BinaryWriter writer = new(stream);
writer.Write((ulong)PlayerSelectResult.Success);
@ -58,22 +60,22 @@ namespace Ryujinx.HLE.HOS.Applets
return stream.ToArray();
}
private byte[] BuildGuestResponse()
private static byte[] BuildGuestResponse()
{
using MemoryStream stream = MemoryStreamManager.Shared.GetStream();
using RecyclableMemoryStream stream = MemoryStreamManager.Shared.GetStream();
using BinaryWriter writer = new(stream);
writer.Write(new byte());
return stream.ToArray();
}
private byte[] BuildResponse()
private static byte[] BuildResponse()
{
using MemoryStream stream = MemoryStreamManager.Shared.GetStream();
using RecyclableMemoryStream stream = MemoryStreamManager.Shared.GetStream();
using BinaryWriter writer = new(stream);
writer.Write((ulong)PlayerSelectResult.Failure);
return stream.ToArray();

View file

@ -147,19 +147,19 @@ namespace Ryujinx.HLE.HOS.Applets
private bool IsKeyboardActive()
{
return _backgroundState >= InlineKeyboardState.Appearing && _backgroundState < InlineKeyboardState.Disappearing;
return _backgroundState is >= InlineKeyboardState.Appearing and < InlineKeyboardState.Disappearing;
}
private bool InputModeControllerEnabled()
{
return _inputMode == KeyboardInputMode.ControllerAndKeyboard ||
_inputMode == KeyboardInputMode.ControllerOnly;
return _inputMode is KeyboardInputMode.ControllerAndKeyboard or
KeyboardInputMode.ControllerOnly;
}
private bool InputModeTypingEnabled()
{
return _inputMode == KeyboardInputMode.ControllerAndKeyboard ||
_inputMode == KeyboardInputMode.KeyboardOnly;
return _inputMode is KeyboardInputMode.ControllerAndKeyboard or
KeyboardInputMode.KeyboardOnly;
}
private void AdvanceInputMode()
@ -365,6 +365,7 @@ namespace Ryujinx.HLE.HOS.Applets
}
}
}
_interactiveSession.Push(InlineResponses.ReleasedUserWordInfo(_backgroundState));
break;
case InlineKeyboardRequest.SetCustomizeDic:
@ -378,6 +379,7 @@ namespace Ryujinx.HLE.HOS.Applets
{
_keyboardBackgroundDic = reader.ReadStruct<SoftwareKeyboardCustomizeDic>();
}
break;
case InlineKeyboardRequest.SetCustomizedDictionaries:
// Read the custom dictionaries data.
@ -390,6 +392,7 @@ namespace Ryujinx.HLE.HOS.Applets
{
_keyboardBackgroundDictSet = reader.ReadStruct<SoftwareKeyboardDictSet>();
}
break;
case InlineKeyboardRequest.Calc:
// The Calc request is used to communicate configuration changes and commands to the keyboard.

View file

@ -198,6 +198,7 @@ namespace Ryujinx.HLE.HOS.Applets.SoftwareKeyboard
{
return;
}
SKCanvas canvas = _surface.Canvas;
canvas.Clear(SKColors.Transparent);

View file

@ -110,6 +110,7 @@ namespace Ryujinx.HLE.HOS
MemoryManagerHostMapped memoryManagerHostMapped = new(addressSpace, mode == MemoryManagerMode.HostMappedUnsafe, invalidAccessHandler);
processContext = new ArmProcessContext<MemoryManagerHostMapped>(pid, cpuEngine, _gpu, memoryManagerHostMapped, addressSpace.AddressSpaceSize, for64Bit);
}
break;
default:

View file

@ -210,7 +210,6 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
return true;
}
// <class-enum-type> ::= <name> # non-dependent type name, dependent type name, or dependent typename-specifier
// ::= Ts <name> # dependent elaborated type specifier using 'struct' or 'class'
// ::= Tu <name> # dependent elaborated type specifier using 'union'
@ -252,7 +251,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
// <exception-spec> ::= Do # non-throwing exception-specification (e.g., noexcept, throw())
// ::= DO <expression> E # computed (instantiation-dependent) noexcept
// ::= Dw <type>+ E # dynamic exception specification with instantiation-dependent types
private BaseNode ParseFunctionType()
private FunctionType ParseFunctionType()
{
Cv cvQualifiers = ParseCvQualifiers();
@ -347,7 +346,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
// <array-type> ::= A <positive dimension number> _ <element type>
// ::= A [<dimension expression>] _ <element type>
private BaseNode ParseArrayType()
private ArrayType ParseArrayType()
{
if (!ConsumeIf("A"))
{
@ -570,6 +569,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
default:
return null;
}
break;
case 'F':
result = ParseFunctionType();
@ -582,7 +582,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
return null;
case 'T':
// might just be a class enum type
if (Peek(1) == 's' || Peek(1) == 'u' || Peek(1) == 'e')
if (Peek(1) is 's' or 'u' or 'e')
{
result = ParseClassEnumType();
break;
@ -604,6 +604,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
result = new NameTypeWithTemplateArguments(result, templateArguments);
}
break;
case 'P':
_position++;
@ -680,6 +681,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
result = new NameTypeWithTemplateArguments(substitution, templateArgument);
break;
}
return substitution;
}
else
@ -691,6 +693,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
result = ParseClassEnumType();
break;
}
if (result != null)
{
_substitutionList.Add(result);
@ -723,6 +726,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
return new SpecialName("guard variable for ", name);
}
return null;
}
@ -848,10 +852,12 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
{
qualifiers |= Cv.Restricted;
}
if (ConsumeIf("V"))
{
qualifiers |= Cv.Volatile;
}
if (ConsumeIf("K"))
{
qualifiers |= Cv.Const;
@ -860,7 +866,6 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
return qualifiers;
}
// <ref-qualifier> ::= R # & ref-qualifier
// <ref-qualifier> ::= O # && ref-qualifier
private SimpleReferenceType ParseRefQualifiers()
@ -874,6 +879,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
{
result = Reference.LValue;
}
return new SimpleReferenceType(result, null);
}
@ -945,7 +951,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
}
// <source-name> ::= <positive length number> <identifier>
private BaseNode ParseSourceName()
private NameType ParseSourceName()
{
int length = ParsePositiveNumber();
if (Count() < length || length <= 0)
@ -1131,6 +1137,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
_position += 2;
return new NameType("operator[]");
}
return null;
case 'l':
switch (Peek(1))
@ -1244,6 +1251,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
_position += 2;
return new NameType("operator?");
}
return null;
case 'r':
switch (Peek(1))
@ -1269,6 +1277,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
_position += 2;
return new NameType("operator<=>");
}
return null;
case 'v':
// TODO: ::= v <digit> <source-name> # vendor extended operator
@ -1311,6 +1320,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
// TODO: ABI Tags
// throw new Exception("ABI Tags not implemented");
}
return result;
}
@ -1320,7 +1330,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
// ::= D0 # deleting destructor
// ::= D1 # complete object destructor
// ::= D2 # base object destructor
private BaseNode ParseCtorDtorName(NameParserContext context, BaseNode prev)
private CtorDtorNameType ParseCtorDtorName(NameParserContext context, BaseNode prev)
{
if (prev.Type == NodeType.SpecialSubstitution && prev is SpecialSubstitution substitution)
{
@ -1332,7 +1342,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
bool isInherited = ConsumeIf("I");
char ctorDtorType = Peek();
if (ctorDtorType != '1' && ctorDtorType != '2' && ctorDtorType != '3')
if (ctorDtorType is not '1' and not '2' and not '3')
{
return null;
}
@ -1355,7 +1365,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
if (ConsumeIf("D"))
{
char c = Peek();
if (c != '0' && c != '1' && c != '2')
if (c is not '0' and not '1' and not '2')
{
return null;
}
@ -1377,7 +1387,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
// ::= fp <top-level CV-qualifiers> <parameter-2 non-negative number> _ # L == 0, second and later parameters
// ::= fL <L-1 non-negative number> p <top-level CV-qualifiers> _ # L > 0, first parameter
// ::= fL <L-1 non-negative number> p <top-level CV-qualifiers> <parameter-2 non-negative number> _ # L > 0, second and later parameters
private BaseNode ParseFunctionParameter()
private FunctionParameter ParseFunctionParameter()
{
if (ConsumeIf("fp"))
{
@ -1422,7 +1432,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
// ::= fR <binary-operator-name> <expression> <expression>
// ::= fl <binary-operator-name> <expression>
// ::= fr <binary-operator-name> <expression>
private BaseNode ParseFoldExpression()
private FoldExpression ParseFoldExpression()
{
if (!ConsumeIf("f"))
{
@ -1430,8 +1440,8 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
}
char foldKind = Peek();
bool hasInitializer = foldKind == 'L' || foldKind == 'R';
bool isLeftFold = foldKind == 'l' || foldKind == 'L';
bool hasInitializer = foldKind is 'L' or 'R';
bool isLeftFold = foldKind is 'l' or 'L';
if (!isLeftFold && !(foldKind == 'r' || foldKind == 'R'))
{
@ -1568,10 +1578,9 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
return new FoldExpression(isLeftFold, operatorName, new PackedTemplateParameterExpansion(expression), initializer);
}
// ::= cv <type> <expression> # type (expression), conversion with one argument
// ::= cv <type> _ <expression>* E # type (expr-list), conversion with other than one argument
private BaseNode ParseConversionExpression()
private ConversionExpression ParseConversionExpression()
{
if (!ConsumeIf("cv"))
{
@ -1616,7 +1625,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
return new ConversionExpression(type, new NodeArray(expressions));
}
private BaseNode ParseBinaryExpression(string name)
private BinaryExpression ParseBinaryExpression(string name)
{
BaseNode leftPart = ParseExpression();
if (leftPart == null)
@ -1633,7 +1642,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
return new BinaryExpression(leftPart, name, rightPart);
}
private BaseNode ParsePrefixExpression(string name)
private PrefixExpression ParsePrefixExpression(string name)
{
BaseNode expression = ParseExpression();
if (expression == null)
@ -1644,7 +1653,6 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
return new PrefixExpression(name, expression);
}
// <braced-expression> ::= <expression>
// ::= di <field source-name> <braced-expression> # .name = expr
// ::= dx <index expression> <braced-expression> # [expr] = expr
@ -1720,7 +1728,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
// ::= [gs] na <expression>* _ <type> <initializer> # new[] (expr-list) type (init)
//
// <initializer> ::= pi <expression>* E # parenthesized initialization
private BaseNode ParseNewExpression()
private NewExpression ParseNewExpression()
{
bool isGlobal = ConsumeIf("gs");
bool isArray = Peek(1) == 'a';
@ -1771,7 +1779,6 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
return new NewExpression(new NodeArray(expressions), typeNode, new NodeArray(initializers), isGlobal, isArray);
}
// <expression> ::= <unary operator-name> <expression>
// ::= <binary operator-name> <expression> <expression>
// ::= <ternary operator-name> <expression> <expression> <expression>
@ -1872,6 +1879,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
return new EnclosedExpression("alignof (", expression, ")");
}
return null;
case 'c':
switch (Peek(1))
@ -1910,6 +1918,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
names.Add(expression);
}
return new CallExpression(callee, names);
case 'm':
_position += 2;
@ -1920,6 +1929,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
case 'v':
return ParseConversionExpression();
}
return null;
case 'd':
BaseNode leftNode;
@ -2001,6 +2011,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
_position += 2;
return ParseBinaryExpression("/=");
}
return null;
case 'e':
switch (Peek(1))
@ -2015,6 +2026,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
_position += 2;
return ParseBinaryExpression("==");
}
return null;
case 'g':
switch (Peek(1))
@ -2026,6 +2038,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
_position += 2;
return ParseBinaryExpression(">");
}
return null;
case 'i':
switch (Peek(1))
@ -2059,8 +2072,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
bracedExpressions.Add(expression);
}
return new InitListExpression(null, bracedExpressions);
}
return null;
case 'l':
switch (Peek(1))
@ -2078,6 +2093,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
_position += 2;
return ParseBinaryExpression("<");
}
return null;
case 'm':
switch (Peek(1))
@ -2109,6 +2125,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
return new PostfixExpression(expression, "--");
}
return null;
case 'n':
switch (Peek(1))
@ -2136,6 +2153,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
return new EnclosedExpression("noexcept (", expression, ")");
}
return null;
case 'o':
switch (Peek(1))
@ -2152,6 +2170,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
_position += 2;
return ParseBinaryExpression("|=");
}
return null;
case 'p':
switch (Peek(1))
@ -2196,6 +2215,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
return new MemberExpression(leftNode, "->", rightNode);
}
return null;
case 'q':
if (Peek(1) == 'u')
@ -2221,6 +2241,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
return new ConditionalExpression(condition, leftNode, rightNode);
}
return null;
case 'r':
switch (Peek(1))
@ -2253,6 +2274,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
_position += 2;
return ParseBinaryExpression(">>=");
}
return null;
case 's':
switch (Peek(1))
@ -2324,6 +2346,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
return new EnclosedExpression("sizeof...(", sizeofParamNode, ")");
}
return null;
case 'P':
_position += 2;
@ -2338,8 +2361,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
arguments.Add(argument);
}
return new EnclosedExpression("sizeof...(", new NodeArray(arguments), ")");
}
return null;
case 't':
switch (Peek(1))
@ -2379,6 +2404,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
bracedExpressions.Add(expression);
}
return new InitListExpression(typeNode, bracedExpressions);
case 'r':
_position += 2;
@ -2393,6 +2419,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
return new ThrowExpression(expression);
}
return null;
}
@ -2404,7 +2431,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
return null;
}
private BaseNode ParseIntegerLiteral(string literalName)
private IntegerLiteral ParseIntegerLiteral(string literalName)
{
string number = ParseNumber(true);
if (number == null || number.Length == 0 || !ConsumeIf("E"))
@ -2499,6 +2526,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
return encoding;
}
}
return null;
case 'T':
return null;
@ -2521,7 +2549,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
// <decltype> ::= Dt <expression> E # decltype of an id-expression or class member access (C++0x)
// ::= DT <expression> E # decltype of an expression (C++0x)
private BaseNode ParseDecltype()
private EnclosedExpression ParseDecltype()
{
if (!ConsumeIf("D") || (!ConsumeIf("t") && !ConsumeIf("T")))
{
@ -2579,6 +2607,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
_forwardTemplateReferenceList.Add(forwardTemplateReference);
return forwardTemplateReference;
}
if (index >= _templateParamList.Count)
{
return null;
@ -2588,7 +2617,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
}
// <template-args> ::= I <template-arg>+ E
private BaseNode ParseTemplateArguments(bool hasContext = false)
private TemplateArguments ParseTemplateArguments(bool hasContext = false)
{
if (!ConsumeIf("I"))
{
@ -2605,7 +2634,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
{
if (hasContext)
{
List<BaseNode> templateParamListTemp = new(_templateParamList);
List<BaseNode> templateParamListTemp = [.. _templateParamList];
BaseNode templateArgument = ParseTemplateArgument();
_templateParamList = templateParamListTemp;
if (templateArgument == null)
@ -2618,6 +2647,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
{
templateArgument = new PackedTemplateParameter(((NodeArray)templateArgument).Nodes);
}
_templateParamList.Add(templateArgument);
}
else
@ -2631,10 +2661,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
args.Add(templateArgument);
}
}
return new TemplateArguments(args);
}
// <template-arg> ::= <type> # type or template
// ::= X <expression> E # expression
// ::= <expr-primary> # simple expressions
@ -2670,6 +2700,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
templateArguments.Add(templateArgument);
}
return new NodeArray(templateArguments, NodeType.PackedTemplateArgument);
// <type>
default:
@ -2685,7 +2716,6 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
public bool CtorDtorConversion;
}
// <unresolved-type> ::= <template-param> [ <template-args> ] # T:: or T<X,Y>::
// ::= <decltype> # decltype(p)::
// ::= <substitution>
@ -2713,6 +2743,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
_substitutionList.Add(declType);
return declType;
}
return ParseSubstitution();
}
@ -2735,12 +2766,13 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
return new NameTypeWithTemplateArguments(sourceName, templateArguments);
}
return sourceName;
}
// <destructor-name> ::= <unresolved-type> # e.g., ~T or ~decltype(f())
// ::= <simple-id> # e.g., ~A<2*N>
private BaseNode ParseDestructorName()
private DtorName ParseDestructorName()
{
BaseNode node;
if (char.IsDigit(Peek()))
@ -2751,6 +2783,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
{
node = ParseUnresolvedType();
}
if (node == null)
{
return null;
@ -2794,6 +2827,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
return new NameTypeWithTemplateArguments(operatorName, templateArguments);
}
return operatorName;
}
@ -2955,6 +2989,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
return new StdQualifiedName(unresolvedName);
}
return ParseUnresolvedName(context);
}
@ -2998,6 +3033,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
continue;
}
char c = Peek();
// TODO: template args
@ -3098,10 +3134,12 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
{
return null;
}
result = CreateNameNode(result, unqualifiedName, context);
_substitutionList.Add(result);
}
if (result == null || _substitutionList.Count == 0)
{
return null;
@ -3127,6 +3165,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
{
Consume();
}
ConsumeIf("_");
}
}
@ -3134,7 +3173,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
// <local-name> ::= Z <function encoding> E <entity name> [<discriminator>]
// ::= Z <function encoding> E s [<discriminator>]
// ::= Z <function encoding> Ed [ <parameter number> ] _ <entity name>
private BaseNode ParseLocalName(NameParserContext context)
private LocalName ParseLocalName(NameParserContext context)
{
if (!ConsumeIf("Z"))
{
@ -3329,6 +3368,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
{
return encoding;
}
return null;
}
else
@ -3338,6 +3378,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler
{
return type;
}
return null;
}
}

View file

@ -345,6 +345,7 @@ namespace Ryujinx.HLE.HOS
VirtualAmiibo.ApplicationBytes = [];
VirtualAmiibo.InputBin = string.Empty;
}
if (NfpDevices[nfpDeviceId].State == NfpDeviceState.SearchingForTag)
{
NfpDevices[nfpDeviceId].State = NfpDeviceState.TagFound;
@ -359,6 +360,7 @@ namespace Ryujinx.HLE.HOS
{
VirtualAmiibo.ApplicationBytes = [];
}
byte[] encryptedData = File.ReadAllBytes(path);
VirtualAmiiboFile newFile = AmiiboBinReader.ReadBinFile(encryptedData);
if (SearchingForAmiibo(out int nfpDeviceId))
@ -495,6 +497,7 @@ namespace Ryujinx.HLE.HOS
TickSource.Resume();
}
}
IsPaused = pause;
}
}

View file

@ -981,7 +981,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Ipc
{
return KernelResult.OutOfResource;
}
else if (recvListType == 1 || recvListType == 2)
else if (recvListType is 1 or 2)
{
ulong recvListBaseAddr;
ulong recvListEndAddr;

View file

@ -86,7 +86,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory
return KernelResult.InvalidState;
}
Debug.Assert(permission == KMemoryPermission.Read || permission == KMemoryPermission.ReadAndExecute);
Debug.Assert(permission is KMemoryPermission.Read or KMemoryPermission.ReadAndExecute);
Result result = Owner.MemoryManager.MapPages(address, _pageList, MemoryState.CodeReadOnly, permission);

View file

@ -253,6 +253,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Memory
AliasRegionExtraSize = addrSpaceEnd / 8;
aliasRegion.Size += AliasRegionExtraSize;
}
break;
default:

View file

@ -138,6 +138,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Process
{
sb.AppendLine($"\tX[{i:d2}]:\t{GetReg(i)}");
}
sb.AppendLine($"\tFP:\t{GetReg(29)}");
sb.AppendLine($"\tLR:\t{GetReg(30)}");
sb.AppendLine($"\tSP:\t{GetReg(31)}");
@ -235,6 +236,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Process
{
info.SubName = Demangler.Parse(info.SubName);
}
info.SubOffset = info.Offset - symbol.Value;
}
else

View file

@ -128,7 +128,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Process
Pid = KernelContext.NewKipId();
if (Pid == 0 || Pid >= KernelConstants.InitialProcessId)
if (Pid is 0 or >= KernelConstants.InitialProcessId)
{
throw new InvalidOperationException($"Invalid KIP Id {Pid}.");
}
@ -231,7 +231,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Process
Pid = KernelContext.NewProcessId();
if (Pid == ulong.MaxValue || Pid < KernelConstants.InitialProcessId)
if (Pid is ulong.MaxValue or < KernelConstants.InitialProcessId)
{
throw new InvalidOperationException($"Invalid Process Id {Pid}.");
}
@ -309,7 +309,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Process
return KernelResult.InvalidCombination;
}
if (requiredKernelVersionMajor != KernelVersionMajor && requiredKernelVersionMajor < 3)
if (requiredKernelVersionMajor is not KernelVersionMajor and < 3)
{
return KernelResult.InvalidCombination;
}
@ -461,7 +461,6 @@ namespace Ryujinx.HLE.HOS.Kernel.Process
Result result = Result.Success;
if (_fullTlsPages.TryGetValue(tlsPageAddr, out KTlsPageInfo pageInfo))
{
// TLS page was full, free slot and move to free pages tree.
@ -509,7 +508,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Process
return result;
}
private void GenerateRandomEntropy()
private static void GenerateRandomEntropy()
{
// TODO.
}
@ -882,10 +881,10 @@ namespace Ryujinx.HLE.HOS.Kernel.Process
{
if (State >= ProcessState.Started)
{
if (State == ProcessState.Started ||
State == ProcessState.Crashed ||
State == ProcessState.Attached ||
State == ProcessState.DebugSuspended)
if (State is ProcessState.Started or
ProcessState.Crashed or
ProcessState.Attached or
ProcessState.DebugSuspended)
{
SetState(ProcessState.Exiting);
@ -925,9 +924,9 @@ namespace Ryujinx.HLE.HOS.Kernel.Process
{
if (State >= ProcessState.Started)
{
if (State == ProcessState.Started ||
State == ProcessState.Attached ||
State == ProcessState.DebugSuspended)
if (State is ProcessState.Started or
ProcessState.Attached or
ProcessState.DebugSuspended)
{
SetState(ProcessState.Exiting);
@ -1090,7 +1089,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Process
{
KernelContext.CriticalSection.Enter();
if (State != ProcessState.Exiting && State != ProcessState.Exited)
if (State is not ProcessState.Exiting and not ProcessState.Exited)
{
if (pause)
{

View file

@ -4,7 +4,6 @@ using System.Diagnostics.CodeAnalysis;
namespace Ryujinx.HLE.HOS.Kernel.Process
{
[Flags]
[SuppressMessage("Design", "CA1069: Enums values should not be duplicated")]
enum ProcessCreationFlags
{
Is64Bit = 1 << 0,

View file

@ -150,7 +150,7 @@ namespace Ryujinx.HLE.HOS.Kernel.SupervisorCall
return handleTable.GenerateHandle(process, out handle);
}
public Result StartProcess(int handle, int priority, int cpuCore, ulong mainThreadStackSize)
public static Result StartProcess(int handle, int priority, int cpuCore, ulong mainThreadStackSize)
{
KProcess process = KernelStatic.GetCurrentProcess().HandleTable.GetObject<KProcess>(handle);
@ -1071,7 +1071,7 @@ namespace Ryujinx.HLE.HOS.Kernel.SupervisorCall
return result;
}
public Result QueryMemory(out MemoryInfo info, out ulong pageInfo, ulong address)
public static Result QueryMemory(out MemoryInfo info, out ulong pageInfo, ulong address)
{
KProcess process = KernelStatic.GetCurrentProcess();
@ -1199,7 +1199,7 @@ namespace Ryujinx.HLE.HOS.Kernel.SupervisorCall
return KernelResult.InvalidMemState;
}
if (permission > KMemoryPermission.ReadAndWrite || permission == KMemoryPermission.Write)
if (permission is > KMemoryPermission.ReadAndWrite or KMemoryPermission.Write)
{
return KernelResult.InvalidPermission;
}
@ -1261,7 +1261,7 @@ namespace Ryujinx.HLE.HOS.Kernel.SupervisorCall
return KernelResult.InvalidMemState;
}
if (permission > KMemoryPermission.ReadAndWrite || permission == KMemoryPermission.Write)
if (permission is > KMemoryPermission.ReadAndWrite or KMemoryPermission.Write)
{
return KernelResult.InvalidPermission;
}
@ -1485,7 +1485,7 @@ namespace Ryujinx.HLE.HOS.Kernel.SupervisorCall
return KernelResult.InvalidMemRange;
}
if (permission != KMemoryPermission.Read && permission != KMemoryPermission.ReadAndExecute)
if (permission is not KMemoryPermission.Read and not KMemoryPermission.ReadAndExecute)
{
return KernelResult.InvalidPermission;
}
@ -1540,10 +1540,10 @@ namespace Ryujinx.HLE.HOS.Kernel.SupervisorCall
return KernelResult.InvalidSize;
}
if (permission != KMemoryPermission.None &&
permission != KMemoryPermission.Read &&
permission != KMemoryPermission.ReadAndWrite &&
permission != KMemoryPermission.ReadAndExecute)
if (permission is not KMemoryPermission.None and
not KMemoryPermission.Read and
not KMemoryPermission.ReadAndWrite and
not KMemoryPermission.ReadAndExecute)
{
return KernelResult.InvalidPermission;
}
@ -2009,6 +2009,7 @@ namespace Ryujinx.HLE.HOS.Kernel.SupervisorCall
{
value = process.MemoryManager.GetMmUsedPages() * KPageTableBase.PageSize;
}
break;
case InfoType.ProgramId:
@ -2040,12 +2041,14 @@ namespace Ryujinx.HLE.HOS.Kernel.SupervisorCall
{
value = 0;
}
break;
case InfoType.AliasRegionExtraSize:
value = process.MemoryManager.AliasRegionExtraSize;
break;
}
break;
}
@ -2093,6 +2096,7 @@ namespace Ryujinx.HLE.HOS.Kernel.SupervisorCall
value = (uint)resLimHandle;
}
break;
}
@ -2134,7 +2138,7 @@ namespace Ryujinx.HLE.HOS.Kernel.SupervisorCall
case InfoType.ThreadTickCount:
{
if (subId < -1 || subId > 3)
if (subId is < (-1) or > 3)
{
return KernelResult.InvalidCombination;
}
@ -2174,6 +2178,7 @@ namespace Ryujinx.HLE.HOS.Kernel.SupervisorCall
value = (ulong)KTimeManager.ConvertHostTicksToTicks(totalTimeRunning);
}
break;
}

View file

@ -6,7 +6,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Threading
{
private readonly KernelContext _context;
private int _recursionCount;
// type is not Lock due to Monitor class usage
public object Lock { get; } = new();

View file

@ -46,10 +46,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Threading
_currentThread = null;
if (_srcCoresHighestPrioThreads == null)
{
_srcCoresHighestPrioThreads = new int[CpuCoresCount];
}
_srcCoresHighestPrioThreads ??= new int[CpuCoresCount];
}
private static int PreemptionPriorities(int index)

View file

@ -537,7 +537,7 @@ namespace Ryujinx.HLE.HOS.Kernel.Threading
ThreadSchedState lowNibble = SchedFlags & ThreadSchedState.LowMask;
if (lowNibble != ThreadSchedState.Paused && lowNibble != ThreadSchedState.Running)
if (lowNibble is not ThreadSchedState.Paused and not ThreadSchedState.Running)
{
KernelContext.CriticalSection.Leave();

View file

@ -500,6 +500,7 @@ namespace Ryujinx.HLE.HOS
{
AddFiles(fs, mod.Name, mod.Path.FullName, fileSet, builder);
}
count++;
}
@ -516,6 +517,7 @@ namespace Ryujinx.HLE.HOS
{
AddFiles(fs, mod.Name, mod.Path.FullName, fileSet, builder);
}
count++;
}
@ -547,7 +549,7 @@ namespace Ryujinx.HLE.HOS
return newStorage;
}
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, HashSet<string> fileSet, RomFsBuilder builder)
{
foreach (DirectoryEntryEx entry in fs.EnumerateEntries()
.AsParallel()
@ -644,16 +646,11 @@ namespace Ryujinx.HLE.HOS
modLoadResult.Replaces[1 << i] = true;
using (FileStream stream = nsoFile.OpenRead())
{
nsos[i] = new NsoExecutable(stream.AsStorage(), nsoName);
Logger.Info?.Print(LogClass.ModLoader, $"NSO '{nsoName}' replaced");
using (MD5 md5 = MD5.Create())
{
stream.Seek(0, SeekOrigin.Begin);
tempHash += BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", "").ToLowerInvariant();
}
}
using FileStream stream = nsoFile.OpenRead();
nsos[i] = new NsoExecutable(stream.AsStorage(), nsoName);
Logger.Info?.Print(LogClass.ModLoader, $"NSO '{nsoName}' replaced");
stream.Seek(0, SeekOrigin.Begin);
tempHash += Convert.ToHexStringLower(MD5.HashData(stream));
}
modLoadResult.Stubs[1 << i] |= File.Exists(Path.Combine(mod.Path.FullName, nsoName + StubExtension));
@ -687,10 +684,7 @@ namespace Ryujinx.HLE.HOS
if (!string.IsNullOrEmpty(tempHash))
{
using (MD5 md5 = MD5.Create())
{
modLoadResult.Hash += BitConverter.ToString(md5.ComputeHash(tempHash.ToBytes())).Replace("-", string.Empty).ToLowerInvariant();
}
modLoadResult.Hash += Convert.ToHexStringLower(MD5.HashData(tempHash.ToBytes()));
}
return modLoadResult;

View file

@ -56,6 +56,7 @@ namespace Ryujinx.HLE.HOS.Services.Account.Acc
Logger.Warning?.Print(LogClass.Application, $"The command line specified profile named '{initialProfileName}' was not found");
}
}
OpenUser(commandLineUserProfileOverride.IsNull ? _accountSaveDataManager.LastOpened : commandLineUserProfileOverride);
}
}

View file

@ -1,3 +1,4 @@
using Microsoft.IO;
using Ryujinx.Common.Memory;
using Ryujinx.HLE.HOS.Services.Account.Acc;
using System.IO;
@ -11,7 +12,7 @@ namespace Ryujinx.HLE.HOS.Services.Am.AppletAE.Storage
public static byte[] MakeLaunchParams(UserProfile userProfile)
{
// Size needs to be at least 0x88 bytes otherwise application errors.
using MemoryStream ms = MemoryStreamManager.Shared.GetStream();
using RecyclableMemoryStream ms = MemoryStreamManager.Shared.GetStream();
BinaryWriter writer = new(ms);
ms.SetLength(0x88);

View file

@ -103,7 +103,7 @@ namespace Ryujinx.HLE.HOS.Services.Caps
};
// NOTE: The hex hash is a HMAC-SHA256 (first 32 bytes) using a hardcoded secret key over the titleId, we can simulate it by hashing the titleId instead.
string hash = Convert.ToHexString(SHA256.HashData(BitConverter.GetBytes(titleId))).Remove(0x20);
string hash = Convert.ToHexString(SHA256.HashData(BitConverter.GetBytes(titleId)))[..0x20];
string folderPath = Path.Combine(_sdCardPath, "Nintendo", "Album", currentDateTime.Year.ToString("00"), currentDateTime.Month.ToString("00"), currentDateTime.Day.ToString("00"));
string filePath = GenerateFilePath(folderPath, applicationAlbumEntry, currentDateTime, hash);

View file

@ -50,7 +50,7 @@ namespace Ryujinx.HLE.HOS.Services.Caps
MemoryHelper.FillWithZeros(context.Memory, applicationAlbumFileEntryPosition, (int)applicationAlbumFileEntrySize);
if (contentType > ContentType.Unknown || contentType == ContentType.ExtraMovie)
if (contentType is > ContentType.Unknown or ContentType.ExtraMovie)
{
resultCode = ResultCode.InvalidContentType;
}

View file

@ -60,7 +60,6 @@ namespace Ryujinx.HLE.HOS.Services.Caps
ulong screenshotDataPosition = context.Request.SendBuff[1].Position;
ulong screenshotDataSize = context.Request.SendBuff[1].Size;
// TODO: Parse the application data: At 0x00 it's UserData (Size of 0x400), at 0x404 it's a uint UserDataSize (Always empty for now).
_ = context.Memory.GetSpan(applicationDataPosition, (int)applicationDataSize).ToArray();
@ -89,7 +88,6 @@ namespace Ryujinx.HLE.HOS.Services.Caps
ulong screenshotDataPosition = context.Request.SendBuff[1].Position;
ulong screenshotDataSize = context.Request.SendBuff[1].Size;
// TODO: Parse the UserIdList.
_ = context.Memory.GetSpan(userIdListPosition, (int)userIdListSize).ToArray();

View file

@ -134,7 +134,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy
ref readonly Path name = ref FileSystemProxyHelper.GetSfPath(context);
using SharedRef<LibHac.FsSrv.Sf.IDirectory> dir = new();
Result result = _fileSystem.Get.OpenDirectory(ref dir.Ref, name, mode);
Result result = _fileSystem.Get.OpenDirectory(ref dir.Ref, in name, mode);
if (result.IsSuccess())
{

View file

@ -16,7 +16,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy
{
_baseStorage = SharedRef<LibHac.FsSrv.Sf.IStorage>.CreateMove(ref baseStorage);
}
private const string Xc2JpTitleId = "0100f3400332c000";
private const string Xc2GlobalTitleId = "0100e95004038000";
private static bool IsXc2 => TitleIDs.CurrentApplication.Value.OrDefault() is Xc2GlobalTitleId or Xc2JpTitleId;
@ -41,7 +41,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy
using WritableRegion region = context.Memory.GetWritableRegion(bufferAddress, (int)bufferLen, true);
Result result = _baseStorage.Get.Read((long)offset, new OutBuffer(region.Memory.Span), (long)size);
if (context.Device.DirtyHacks.IsEnabled(DirtyHack.Xc2MenuSoftlockFix) && IsXc2)
{
// Add a load-bearing sleep to avoid XC2 softlock

View file

@ -753,7 +753,7 @@ namespace Ryujinx.HLE.HOS.Services.Fs
public ResultCode OpenCloudBackupWorkStorageFileSystem(ServiceCtx context)
{
CloudBackupWorkStorageId storageId = (CloudBackupWorkStorageId)context.RequestData.ReadInt32();
Logger.Stub?.PrintStub(LogClass.ServiceFs, new { storageId });
throw new NotImplementedException(); // reimplementing behavior from LibHac 0.19.0
}
@ -1232,9 +1232,9 @@ namespace Ryujinx.HLE.HOS.Services.Fs
{
BisPartitionId partitionId = (BisPartitionId)context.RequestData.ReadInt32();
ref readonly FspPath path = ref FileSystemProxyHelper.GetFspPath(context);
Logger.Stub?.PrintStub(LogClass.ServiceFs, new { partitionId, path });
throw new NotImplementedException(); // reimplementing behavior from LibHac 0.19.0
}

View file

@ -42,9 +42,9 @@ namespace Ryujinx.HLE.HOS.Services.Hid.HidServer
public static bool IsValidNpadIdType(NpadIdType npadIdType)
{
return (npadIdType >= NpadIdType.Player1 && npadIdType <= NpadIdType.Player8) ||
npadIdType == NpadIdType.Handheld ||
npadIdType == NpadIdType.Unknown;
return npadIdType is >= NpadIdType.Player1 and <= NpadIdType.Player8 or
NpadIdType.Handheld or
NpadIdType.Unknown;
}
}
}

View file

@ -130,7 +130,7 @@ namespace Ryujinx.HLE.HOS.Services.Hid
return ResultCode.Success;
}
[CommandCmif(26)]
// ActivateDebugMouse(nn::applet::AppletResourceUserId)
public ResultCode ActivateDebugMouse(ServiceCtx context)
@ -702,7 +702,7 @@ namespace Ryujinx.HLE.HOS.Services.Hid
return ResultCode.Success;
}
[CommandCmif(92)]
// SetGestureOutputRanges(pid, ushort Unknown0)
public ResultCode SetGestureOutputRanges(ServiceCtx context)
@ -1161,59 +1161,54 @@ namespace Ryujinx.HLE.HOS.Services.Hid
NpadStyleIndex deviceType = (NpadStyleIndex)deviceHandle.DeviceType;
NpadIdType npadIdType = (NpadIdType)deviceHandle.PlayerId;
if (deviceType < NpadStyleIndex.System || deviceType >= NpadStyleIndex.FullKey)
if (!HidUtils.IsValidNpadIdType(npadIdType))
{
if (!HidUtils.IsValidNpadIdType(npadIdType))
{
return ResultCode.InvalidNpadIdType;
}
if (deviceHandle.Position > 1)
{
return ResultCode.InvalidDeviceIndex;
}
VibrationDeviceType vibrationDeviceType = VibrationDeviceType.None;
if (Enum.IsDefined(deviceType))
{
vibrationDeviceType = VibrationDeviceType.LinearResonantActuator;
}
else if ((uint)deviceType == 8)
{
vibrationDeviceType = VibrationDeviceType.GcErm;
}
VibrationDevicePosition vibrationDevicePosition = VibrationDevicePosition.None;
if (vibrationDeviceType == VibrationDeviceType.LinearResonantActuator)
{
if (deviceHandle.Position == 0)
{
vibrationDevicePosition = VibrationDevicePosition.Left;
}
else if (deviceHandle.Position == 1)
{
vibrationDevicePosition = VibrationDevicePosition.Right;
}
else
{
throw new InvalidOperationException($"{nameof(deviceHandle.Position)} contains an invalid value: {deviceHandle.Position}");
}
}
VibrationDeviceValue deviceInfo = new()
{
DeviceType = vibrationDeviceType,
Position = vibrationDevicePosition,
};
context.ResponseData.WriteStruct(deviceInfo);
return ResultCode.Success;
return ResultCode.InvalidNpadIdType;
}
return ResultCode.InvalidNpadDeviceType;
if (deviceHandle.Position > 1)
{
return ResultCode.InvalidDeviceIndex;
}
VibrationDeviceType vibrationDeviceType = VibrationDeviceType.None;
if (Enum.IsDefined(deviceType))
{
vibrationDeviceType = VibrationDeviceType.LinearResonantActuator;
}
else if ((uint)deviceType == 8)
{
vibrationDeviceType = VibrationDeviceType.GcErm;
}
VibrationDevicePosition vibrationDevicePosition = VibrationDevicePosition.None;
if (vibrationDeviceType == VibrationDeviceType.LinearResonantActuator)
{
if (deviceHandle.Position == 0)
{
vibrationDevicePosition = VibrationDevicePosition.Left;
}
else if (deviceHandle.Position == 1)
{
vibrationDevicePosition = VibrationDevicePosition.Right;
}
else
{
throw new InvalidOperationException($"{nameof(deviceHandle.Position)} contains an invalid value: {deviceHandle.Position}");
}
}
VibrationDeviceValue deviceInfo = new()
{
DeviceType = vibrationDeviceType,
Position = vibrationDevicePosition,
};
context.ResponseData.WriteStruct(deviceInfo);
return ResultCode.Success;
}
[CommandCmif(201)]

View file

@ -10,9 +10,7 @@ namespace Ryujinx.HLE.HOS.Services.Hid
[CommandCmif(1)]
// GetBusHandle(nn::hid::NpadIdType, nn::hidbus::BusType, nn::applet::AppletResourceUserId) -> (bool HasHandle, nn::hidbus::BusHandle)
#pragma warning disable CA1822 // Mark member as static
public ResultCode GetBusHandle(ServiceCtx context)
#pragma warning restore CA1822
{
NpadIdType npadIdType = (NpadIdType)context.RequestData.ReadInt32();
context.RequestData.BaseStream.Position += 4; // Padding

View file

@ -172,9 +172,9 @@ namespace Ryujinx.HLE.HOS.Services.Hid.Irs
{
NpadIdType npadIdType = (NpadIdType)context.RequestData.ReadUInt32();
if (npadIdType > NpadIdType.Player8 &&
npadIdType != NpadIdType.Unknown &&
npadIdType != NpadIdType.Handheld)
if (npadIdType is > NpadIdType.Player8 and
not NpadIdType.Unknown and
not NpadIdType.Handheld)
{
return ResultCode.NpadIdOutOfRange;
}

View file

@ -45,7 +45,7 @@ namespace Ryujinx.HLE.HOS.Services.Hid.Types.SharedMemory
/// </summary>
[FieldOffset(0x9A00)]
public Array10<NpadState> Npads;
/// <summary>
/// Debug mouse.
/// </summary>

View file

@ -26,17 +26,17 @@ namespace Ryujinx.HLE.HOS.Services
public IpcService(ServerBase server = null, bool registerTipc = false)
{
Stopwatch sw = Stopwatch.StartNew();
CmifCommands = GetType()
.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public)
.SelectMany(methodInfo => methodInfo.GetCustomAttributes<CommandCmifAttribute>()
.Select(command => (command.Id, methodInfo)))
.ToDictionary(command => command.Id, command => command.methodInfo);
sw.Stop();
Logger.Debug?.Print(
LogClass.Emulation,
LogClass.Emulation,
$"{CmifCommands.Count} Cmif commands loaded in {sw.ElapsedTicks} ticks ({Stopwatch.Frequency} tps).",
GetType().AsPrettyString()
);
@ -50,16 +50,16 @@ namespace Ryujinx.HLE.HOS.Services
.SelectMany(methodInfo => methodInfo.GetCustomAttributes<CommandTipcAttribute>()
.Select(command => (command.Id, methodInfo)))
.ToDictionary(command => command.Id, command => command.methodInfo);
sw.Stop();
Logger.Debug?.Print(
LogClass.Emulation,
LogClass.Emulation,
$"{TipcCommands.Count} Tipc commands loaded in {sw.ElapsedTicks} ticks ({Stopwatch.Frequency} tps).",
GetType().AsPrettyString()
);
}
Server = server;
_parent = this;
@ -202,7 +202,6 @@ namespace Ryujinx.HLE.HOS.Services
{
string serviceName;
serviceName = (this is not DummyService dummyService) ? GetType().FullName : dummyService.ServiceName;
Logger.Warning?.Print(LogClass.KernelIpc, $"Missing service {serviceName}: {commandId} ignored");

View file

@ -175,7 +175,7 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator
// NOTE: Return ResultCode.InvalidArgument if ip_address and subnet_mask are null, doesn't occur in our case.
if (_state == NetworkState.AccessPointCreated || _state == NetworkState.StationConnected)
if (_state is NetworkState.AccessPointCreated or NetworkState.StationConnected)
{
ProxyConfig config = _state switch
{
@ -522,7 +522,7 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator
return _nifmResultCode;
}
if (_state == NetworkState.AccessPoint || _state == NetworkState.AccessPointCreated)
if (_state is NetworkState.AccessPoint or NetworkState.AccessPointCreated)
{
DestroyNetworkImpl(DisconnectReason.DestroyedByUser);
}
@ -698,12 +698,12 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator
return _nifmResultCode;
}
if (bufferSize == 0 || bufferSize > LdnConst.AdvertiseDataSizeMax)
if (bufferSize is 0 or > LdnConst.AdvertiseDataSizeMax)
{
return ResultCode.InvalidArgument;
}
if (_state == NetworkState.AccessPoint || _state == NetworkState.AccessPointCreated)
if (_state is NetworkState.AccessPoint or NetworkState.AccessPointCreated)
{
byte[] advertiseData = new byte[bufferSize];
@ -733,7 +733,7 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator
return ResultCode.InvalidArgument;
}
if (_state == NetworkState.AccessPoint || _state == NetworkState.AccessPointCreated)
if (_state is NetworkState.AccessPoint or NetworkState.AccessPointCreated)
{
return _accessPoint.SetStationAcceptPolicy(acceptPolicy);
}
@ -807,7 +807,7 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator
return _nifmResultCode;
}
if (_state == NetworkState.Station || _state == NetworkState.StationConnected)
if (_state is NetworkState.Station or NetworkState.StationConnected)
{
DisconnectImpl(DisconnectReason.DisconnectedByUser);
}
@ -1089,13 +1089,14 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator
case MultiplayerMode.LdnRyu:
try
{
string ldnServer = context.Device.Configuration.MultiplayerLdnServer
string ldnServer = context.Device.Configuration.MultiplayerLdnServer
?? throw new InvalidOperationException("Cannot initialize RyuLDN with a null Multiplayer server.");
if (!IPAddress.TryParse(ldnServer, out IPAddress ipAddress))
{
ipAddress = Dns.GetHostEntry(ldnServer).AddressList[0];
}
NetworkClient = new LdnMasterProxyClient(ipAddress.ToString(), SharedConstants.LanPlayPort, context.Device.Configuration);
}
catch (Exception ex)
@ -1104,6 +1105,7 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator
Logger.Error?.Print(LogClass.ServiceLdn, ex.Message);
NetworkClient = new LdnDisabledClient();
}
break;
case MultiplayerMode.LdnMitm:
NetworkClient = new LdnMitmClient(context.Device.Configuration);

View file

@ -59,6 +59,7 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnMitm
{
Scan?.Invoke(endPoint, LanPacketType.ScanResponse, SpanHelpers.AsSpan<NetworkInfo, byte>(ref _discovery.NetworkInfo).ToArray());
}
break;
case LanPacketType.ScanResponse:
// UDP

View file

@ -179,8 +179,6 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnRyu
_error.Set();
}
private void HandleInitialize(LdnHeader header, InitializeMessage initialize)
{
InitializeMemory = initialize;

View file

@ -47,6 +47,7 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnRyu.Proxy
{
Logger.Error?.PrintMsg(LogClass.ServiceLdn, "Tcp proxy networking is untested. Please report this game so that it can be tested.");
}
return domain == AddressFamily.InterNetwork && (protocol == ProtocolType.Tcp || protocol == ProtocolType.Udp);
}

View file

@ -115,7 +115,6 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnRyu.Proxy
return _receiveQueue.Count > 0;
}
}
}
}
public bool Writable => Connected || ProtocolType == ProtocolType.Udp;
@ -256,6 +255,7 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnRyu.Proxy
{
_proxy.ReturnEphemeralPort(ProtocolType, (ushort)((IPEndPoint)LocalEndPoint).Port);
}
IPEndPoint asIPEndpoint = (IPEndPoint)localEP;
if (asIPEndpoint.Port == 0)
{

View file

@ -156,7 +156,7 @@ namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.LdnRyu.Proxy
if (_publicPort != 0)
{
_ = Executor.ExecuteAfterDelayAsync(
PortLeaseRenew.Seconds(),
PortLeaseRenew.Seconds(),
_disposedCancellation.Token,
RefreshLease);
}

View file

@ -2,7 +2,6 @@ using System.Diagnostics.CodeAnalysis;
namespace Ryujinx.HLE.HOS.Services.Loader
{
[SuppressMessage("Design", "CA1069: Enums values should not be duplicated")]
enum ResultCode
{
ModuleId = 9,

View file

@ -124,7 +124,6 @@ namespace Ryujinx.HLE.HOS.Services.Mii
}
if (_isTestModeEnabled)
#pragma warning disable CS0162
{
result = _horizonClient.Fs.CreateSystemSaveData(saveDataId, 0x10000, 0x10000,
SaveDataFlags.KeepAfterResettingSystemSaveDataWithoutUserSaveData);
@ -133,7 +132,6 @@ namespace Ryujinx.HLE.HOS.Services.Mii
return result;
}
}
#pragma warning restore CS0162
else
{
result = _horizonClient.Fs.CreateSystemSaveData(saveDataId, SystemProgramId.Ns.Value, 0x10000,
@ -155,6 +153,7 @@ namespace Ryujinx.HLE.HOS.Services.Mii
{
_mountCounter++;
}
return result;
}

View file

@ -76,202 +76,252 @@ namespace Ryujinx.HLE.HOS.Services.Mii.Types
{
return 50;
}
if (!Nickname.IsValid())
{
return 51;
}
if ((byte)FontRegion > 3)
{
return 23;
}
if (FavoriteColor > 11)
{
return 22;
}
if (Gender > Gender.Max)
{
return 24;
}
if ((sbyte)Height < 0)
{
return 32;
}
if ((sbyte)Build < 0)
{
return 3;
}
if (Type > 1)
{
return 53;
}
if (RegionMove > 3)
{
return 49;
}
if (FacelineType > FacelineType.Max)
{
return 21;
}
if (FacelineColor > FacelineColor.Max)
{
return 18;
}
if (FacelineWrinkle > FacelineWrinkle.Max)
{
return 20;
}
if (FacelineMake > FacelineMake.Max)
{
return 19;
}
if (HairType > HairType.Max)
{
return 31;
}
if (HairColor > CommonColor.Max)
{
return 29;
}
if (HairFlip > HairFlip.Max)
{
return 30;
}
if (EyeType > EyeType.Max)
{
return 8;
}
if (EyeColor > CommonColor.Max)
{
return 5;
}
if (EyeScale > 7)
{
return 7;
}
if (EyeAspect > 6)
{
return 4;
}
if (EyeRotate > 7)
{
return 6;
}
if (EyeX > 12)
{
return 9;
}
if (EyeY > 18)
{
return 10;
}
if (EyebrowType > EyebrowType.Max)
{
return 15;
}
if (EyebrowColor > CommonColor.Max)
{
return 12;
}
if (EyebrowScale > 8)
{
return 14;
}
if (EyebrowAspect > 6)
{
return 11;
}
if (EyebrowRotate > 11)
{
return 13;
}
if (EyebrowX > 12)
{
return 16;
}
if (EyebrowY - 3 > 15)
{
return 17;
}
if (NoseType > NoseType.Max)
{
return 47;
}
if (NoseScale > 8)
{
return 46;
}
if (NoseY > 18)
{
return 48;
}
if (MouthType > MouthType.Max)
{
return 40;
}
if (MouthColor > CommonColor.Max)
{
return 38;
}
if (MouthScale > 8)
{
return 39;
}
if (MouthAspect > 6)
{
return 37;
}
if (MouthY > 18)
{
return 41;
}
if (BeardColor > CommonColor.Max)
{
return 1;
}
if (BeardType > BeardType.Max)
{
return 2;
}
if (MustacheType > MustacheType.Max)
{
return 43;
}
if (MustacheScale > 8)
{
return 42;
}
if (MustacheY > 16)
{
return 44;
}
if (GlassType > GlassType.Max)
{
return 27;
}
if (GlassColor > CommonColor.Max)
{
return 25;
}
if (GlassScale > 7)
{
return 26;
}
if (GlassY > 20)
{
return 28;
}
if (MoleType > MoleType.Max)
{
return 34;
}
if (MoleScale > 8)
{
return 33;
}
if (MoleX > 16)
{
return 35;
}
if (MoleY >= 31)
{
return 36;

View file

@ -27,14 +27,12 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption
return new VirtualAmiiboFile();
}
byte[] initialCounter = new byte[16];
const int totalPages = 135;
const int pageSize = 4;
const int totalBytes = totalPages * pageSize;
if (fileBytes.Length == 532)
{
int totalPages = 135;
int pageSize = 4;
int totalBytes = totalPages * pageSize;
// add 8 bytes to the end of the file
byte[] newFileBytes = new byte[totalBytes];
Array.Copy(fileBytes, newFileBytes, fileBytes.Length);
@ -54,7 +52,6 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption
byte[] writeCounter = new byte[2];
byte[] appId = new byte[8];
byte[] settingsBytes = new byte[2];
byte formData = 0;
byte[] applicationAreas = new byte[216];
byte[] dataFull = amiiboDump.GetData();
Logger.Debug?.Print(LogClass.ServiceNfp, $"Data Full Length: {dataFull.Length}");
@ -94,7 +91,6 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption
// Bytes 0 and 1 are amiibo ID, byte 2 is set ID, byte 3 is form data
Array.Copy(pageData, 0, amiiboID, 0, 2);
setID[0] = pageData[2];
formData = pageData[3];
break;
case 64:
case 65:
@ -145,6 +141,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption
{
VirtualAmiibo.ApplicationBytes = applicationAreas;
}
VirtualAmiibo.NickName = nickName;
return virtualAmiiboFile;
}
@ -161,6 +158,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption
Logger.Error?.Print(LogClass.ServiceNfp, $"Error reading file: {ex.Message}");
return false;
}
string keyRetailBinPath = GetKeyRetailBinPath();
if (string.IsNullOrEmpty(keyRetailBinPath))
{
@ -207,6 +205,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption
Logger.Error?.Print(LogClass.ServiceNfp, "Failed to encrypt data correctly.");
return false;
}
inputFile = inputFile.Replace("_modified", string.Empty);
// Save the encrypted data to file or return it for saving externally
string outputFilePath = Path.Combine(Path.GetDirectoryName(inputFile), Path.GetFileNameWithoutExtension(inputFile) + "_modified.bin");
@ -235,6 +234,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption
Logger.Error?.Print(LogClass.ServiceNfp, $"Error reading file: {ex.Message}");
return false;
}
string keyRetailBinPath = GetKeyRetailBinPath();
if (string.IsNullOrEmpty(keyRetailBinPath))
{
@ -259,6 +259,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption
Logger.Error?.Print(LogClass.ServiceNfp, "Invalid tag data length. Expected 540 bytes.");
return false;
}
byte[] encryptedData = amiiboDecryptor.EncryptAmiiboDump(oldData).GetData();
if (encryptedData == null || encryptedData.Length != readBytes.Length)
@ -266,6 +267,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption
Logger.Error?.Print(LogClass.ServiceNfp, "Failed to encrypt data correctly.");
return false;
}
inputFile = inputFile.Replace("_modified", string.Empty);
// Save the encrypted data to file or return it for saving externally
string outputFilePath = Path.Combine(Path.GetDirectoryName(inputFile), Path.GetFileNameWithoutExtension(inputFile) + "_modified.bin");
@ -316,6 +318,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption
else
crc >>= 1;
}
table[i] = crc;
}
@ -325,6 +328,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption
byte index = (byte)((result & 0xFF) ^ b);
result = (result >> 8) ^ table[index];
}
return ~result;
}
@ -335,17 +339,17 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption
public static bool HasAmiiboKeyFile => File.Exists(GetKeyRetailBinPath());
public static DateTime DateTimeFromTag(ushort value)
public static DateTime DateTimeFromTag(ushort dateTimeTag)
{
try
{
int day = value & 0x1F;
int month = (value >> 5) & 0x0F;
int year = (value >> 9) & 0x7F;
int day = dateTimeTag & 0x1F;
int month = (dateTimeTag >> 5) & 0x0F;
int year = (dateTimeTag >> 9) & 0x7F;
if (day == 0 || month == 0 || month > 12 || day > DateTime.DaysInMonth(2000 + year, month))
throw new ArgumentOutOfRangeException();
throw new ArgumentOutOfRangeException(nameof(dateTimeTag), "Invalid date in tag.");
return new DateTime(2000 + year, month, day);
}

View file

@ -7,11 +7,11 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption
{
public class AmiiboDump
{
private AmiiboMasterKey dataMasterKey;
private AmiiboMasterKey tagMasterKey;
private readonly AmiiboMasterKey dataMasterKey;
private readonly AmiiboMasterKey tagMasterKey;
private bool isLocked;
private byte[] data;
private readonly byte[] data;
private byte[] hmacTagKey;
private byte[] hmacDataKey;
private byte[] aesKey;
@ -49,6 +49,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption
{
extract[i] = 0x00;
}
seed.AddRange(extract.Take(append));
// Add the magic bytes
@ -70,6 +71,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption
{
paddedUser[i] = (byte)(user[i] ^ key.XorPad[i]);
}
seed.AddRange(paddedUser);
byte[] seedBytes = seed.ToArray();
@ -134,9 +136,8 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption
private void DeriveKeysAndCipher()
{
byte[] discard;
// Derive HMAC Tag Key
this.hmacTagKey = DeriveKey(this.tagMasterKey, false, out discard, out discard);
this.hmacTagKey = DeriveKey(this.tagMasterKey, false, out _, out _);
// Derive HMAC Data Key and AES Key/IV
this.hmacDataKey = DeriveKey(this.dataMasterKey, true, out aesKey, out aesIv);
@ -182,27 +183,25 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption
byte[] counter = new byte[blockSize];
Array.Copy(iv, counter, blockSize);
using (ICryptoTransform encryptor = aes.CreateEncryptor())
using ICryptoTransform encryptor = aes.CreateEncryptor();
byte[] encryptedCounter = new byte[blockSize];
for (int i = 0; i < data.Length; i += blockSize)
{
byte[] encryptedCounter = new byte[blockSize];
// Encrypt the counter
encryptor.TransformBlock(counter, 0, blockSize, encryptedCounter, 0);
for (int i = 0; i < data.Length; i += blockSize)
// Determine the number of bytes to process in this block
int blockLength = Math.Min(blockSize, data.Length - i);
// XOR the encrypted counter with the plaintext/ciphertext block
for (int j = 0; j < blockLength; j++)
{
// Encrypt the counter
encryptor.TransformBlock(counter, 0, blockSize, encryptedCounter, 0);
// Determine the number of bytes to process in this block
int blockLength = Math.Min(blockSize, data.Length - i);
// XOR the encrypted counter with the plaintext/ciphertext block
for (int j = 0; j < blockLength; j++)
{
output[i + j] = (byte)(data[i + j] ^ encryptedCounter[j]);
}
// Increment the counter
IncrementCounter(counter);
output[i + j] = (byte)(data[i + j] ^ encryptedCounter[j]);
}
// Increment the counter
IncrementCounter(counter);
}
}

View file

@ -145,6 +145,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.Nfp
break;
}
}
_cancelTokenSource = new CancellationTokenSource();
Task.Run(() =>
{
@ -196,6 +197,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.Nfp
break;
}
}
return ResultCode.Success;
}
@ -601,7 +603,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.Nfp
}
else
{
if (context.Device.System.NfpDevices[i].State == NfpDeviceState.TagMounted || context.Device.System.NfpDevices[i].State == NfpDeviceState.TagFound)
if (context.Device.System.NfpDevices[i].State is NfpDeviceState.TagMounted or NfpDeviceState.TagFound)
{
byte[] uuid = VirtualAmiibo.GenerateUuid(context.Device.System.NfpDevices[i].AmiiboId, context.Device.System.NfpDevices[i].UseRandomUuid);
@ -877,6 +879,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.Nfp
return ResultCode.Success;
}
}
return ResultCode.DeviceNotFound;
}
@ -972,7 +975,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.Nfp
{
// TODO: Find the differencies between IUser and ISystem/IDebug.
if (_permissionLevel == NfpPermissionLevel.Debug || _permissionLevel == NfpPermissionLevel.System)
if (_permissionLevel is NfpPermissionLevel.Debug or NfpPermissionLevel.System)
{
return GetRegisterInfo(context);
}

View file

@ -75,6 +75,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.Nfp
nickname = NickName;
NickName = string.Empty;
}
UtilityImpl utilityImpl = new(tickSource);
CharInfo charInfo = new();
@ -109,6 +110,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.Nfp
AmiiboBinReader.SaveBinFile(InputBin, virtualAmiiboFile.NickName);
return;
}
SaveAmiiboFile(virtualAmiiboFile);
}
@ -139,6 +141,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.Nfp
ApplicationBytes = [];
return bytes;
}
VirtualAmiiboFile virtualAmiiboFile = LoadAmiiboFile(amiiboId);
foreach (VirtualAmiiboApplicationArea applicationArea in virtualAmiiboFile.ApplicationAreas)
@ -179,6 +182,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.Nfp
AmiiboBinReader.SaveBinFile(InputBin, applicationAreaData);
return;
}
VirtualAmiiboFile virtualAmiiboFile = LoadAmiiboFile(amiiboId);
if (virtualAmiiboFile.ApplicationAreas.Any(item => item.ApplicationAreaId == OpenedApplicationAreaId))
@ -246,6 +250,7 @@ namespace Ryujinx.HLE.HOS.Services.Nfc.Nfp
return true;
}
return File.Exists(Path.Join(AppDataManager.BaseDirPath, "system", "amiibo", $"{virtualAmiiboFile.AmiiboId}.json"));
}
}

View file

@ -400,7 +400,7 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvDrvServices.NvHostChannel
private NvInternalResult SetTimeslice(ref uint timeslice)
{
if (timeslice < 1000 || timeslice > 50000)
if (timeslice is < 1000 or > 50000)
{
return NvInternalResult.InvalidInput;
}
@ -562,7 +562,7 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvDrvServices.NvHostChannel
private static Host1xContext GetHost1XContext(GpuContext gpu, ulong pid)
{
return _host1xContextRegistry.GetOrAdd(pid, (ulong key) => new Host1xContext(gpu, key));
return _host1xContextRegistry.GetOrAdd(pid, key => new Host1xContext(gpu, key));
}
public static void Destroy()

View file

@ -66,6 +66,7 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvDrvServices.NvHostCtrl
{
configArgument.CopyTo(arguments);
}
break;
case 0x1c:
result = CallIoctlMethod<uint>(EventSignal, arguments);
@ -224,7 +225,6 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvDrvServices.NvHostCtrl
return result;
}
}
private NvInternalResult EventUnregister(ref uint userEventId)
@ -243,9 +243,9 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvDrvServices.NvHostCtrl
return NvInternalResult.Success;
}
if (hostEvent.State == NvHostEventState.Available ||
hostEvent.State == NvHostEventState.Cancelled ||
hostEvent.State == NvHostEventState.Signaled)
if (hostEvent.State is NvHostEventState.Available or
NvHostEventState.Cancelled or
NvHostEventState.Signaled)
{
_events[userEventId].CloseEvent(Context);
_events[userEventId] = null;
@ -392,9 +392,9 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvDrvServices.NvHostCtrl
{
lock (hostEvent.Lock)
{
if (hostEvent.State == NvHostEventState.Available ||
hostEvent.State == NvHostEventState.Signaled ||
hostEvent.State == NvHostEventState.Cancelled)
if (hostEvent.State is NvHostEventState.Available or
NvHostEventState.Signaled or
NvHostEventState.Cancelled)
{
bool timedOut = hostEvent.Wait(_device.Gpu, fence);
@ -456,9 +456,9 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvDrvServices.NvHostCtrl
if (Event != null)
{
if (Event.State == NvHostEventState.Available ||
Event.State == NvHostEventState.Signaled ||
Event.State == NvHostEventState.Cancelled)
if (Event.State is NvHostEventState.Available or
NvHostEventState.Signaled or
NvHostEventState.Cancelled)
{
eventIndex = index;

View file

@ -124,6 +124,7 @@ namespace Ryujinx.HLE.HOS.Services.Nv
{
targetPrevAddress = InvalidAddress;
}
node = node.Previous;
_tree.Remove(prevAddress);
_list.Remove(_dictionary[prevAddress]);
@ -151,6 +152,7 @@ namespace Ryujinx.HLE.HOS.Services.Nv
{
targetNextAddress = InvalidAddress;
}
_tree.Remove(nextAddress);
_list.Remove(_dictionary[nextAddress]);
_dictionary.Remove(nextAddress);
@ -212,6 +214,7 @@ namespace Ryujinx.HLE.HOS.Services.Nv
Logger.Debug?.Print(LogClass.ServiceNv, $"Target address was invalid, set to ceiling of 0x{address:X}; resulted in 0x{targetAddress:X}");
}
}
while (address < AddressSpaceSize)
{
if (targetAddress != InvalidAddress)
@ -278,6 +281,7 @@ namespace Ryujinx.HLE.HOS.Services.Nv
}
}
}
Logger.Debug?.Print(LogClass.ServiceNv, $"No suitable address range found; returning: 0x{InvalidAddress:X}.");
freeAddressStartPosition = InvalidAddress;
}
@ -303,6 +307,7 @@ namespace Ryujinx.HLE.HOS.Services.Nv
return !(gpuVa >= floorAddress && ((gpuVa + size) <= _tree.Get(floorAddress)));
}
}
return true;
}
#endregion

View file

@ -61,7 +61,7 @@ namespace Ryujinx.HLE.HOS.Services.Pctl.ParentalControlServiceFactory
{
_ratingAge[i] = Convert.ToInt32(context.Device.Processes.ActiveApplication.ApplicationControlProperties.RatingAge[i]);
}
_parentalControlFlag = context.Device.Processes.ActiveApplication.ApplicationControlProperties.ParentalControlFlag;
}
}
@ -180,7 +180,6 @@ namespace Ryujinx.HLE.HOS.Services.Pctl.ParentalControlServiceFactory
#pragma warning disable // Remove unnecessary value assignment
bool stereoVisionRestriction = false;
#pragma warning restore IDE0059
if (_stereoVisionRestrictionConfigurable)
{

View file

@ -259,6 +259,7 @@ namespace Ryujinx.HLE.HOS.Services.Ro
return baseAddress + size + GuardPagesSize <= memInfo.Address + memInfo.Size;
}
}
return false;
}
@ -313,7 +314,7 @@ namespace Ryujinx.HLE.HOS.Services.Ro
return ResultCode.Success;
}
private Result SetNroMemoryPermissions(KProcess process, IExecutable relocatableObject, ulong baseAddress)
private Result SetNroMemoryPermissions(KProcess process, NroExecutable relocatableObject, ulong baseAddress)
{
ulong textStart = baseAddress + relocatableObject.TextOffset;
ulong roStart = baseAddress + relocatableObject.RoOffset;

View file

@ -5,6 +5,7 @@ using LibHac.FsSystem;
using LibHac.Ncm;
using LibHac.Tools.FsSystem;
using LibHac.Tools.FsSystem.NcaUtils;
using Microsoft.IO;
using Ryujinx.Common.Memory;
using Ryujinx.HLE.Exceptions;
using Ryujinx.HLE.FileSystem;
@ -161,7 +162,7 @@ namespace Ryujinx.HLE.HOS.Services.Sdb.Pl
static uint KXor(uint data) => data ^ FontKey;
using BinaryReader reader = new(bfttfStream);
using MemoryStream ttfStream = MemoryStreamManager.Shared.GetStream();
using RecyclableMemoryStream ttfStream = MemoryStreamManager.Shared.GetStream();
using BinaryWriter output = new(ttfStream);
if (KXor(reader.ReadUInt32()) != BFTTFMagic)

View file

@ -25,7 +25,7 @@ namespace Ryujinx.HLE.HOS.Services
// not large enough.
private const int PointerBufferSize = 0x8000;
private static uint[] _defaultCapabilities => [
private static uint[] DefaultCapabilities => [
(((uint)KScheduler.CpuCoresCount - 1) << 24) + (((uint)KScheduler.CpuCoresCount - 1) << 16) + 0x63F7u,
0x1FFFFFCF,
0x207FFFEF,
@ -47,10 +47,10 @@ namespace Ryujinx.HLE.HOS.Services
private readonly Dictionary<int, IpcService> _sessions = new();
private readonly Dictionary<int, Func<IpcService>> _ports = new();
private readonly MemoryStream _requestDataStream;
private readonly RecyclableMemoryStream _requestDataStream;
private readonly BinaryReader _requestDataReader;
private readonly MemoryStream _responseDataStream;
private readonly RecyclableMemoryStream _responseDataStream;
private readonly BinaryWriter _responseDataWriter;
private int _isDisposed = 0;
@ -81,7 +81,7 @@ namespace Ryujinx.HLE.HOS.Services
ProcessCreationInfo creationInfo = new("Service", 1, 0, 0x8000000, 1, Flags, 0, 0);
KernelStatic.StartInitialProcess(context, creationInfo, _defaultCapabilities, 44, Main);
KernelStatic.StartInitialProcess(context, creationInfo, DefaultCapabilities, 44, Main);
}
private void AddPort(int serverPortHandle, Func<IpcService> objectFactory)
@ -353,8 +353,8 @@ namespace Ryujinx.HLE.HOS.Services
_requestDataStream.Write(request.RawData);
_requestDataStream.Position = 0;
if (request.Type == IpcMessageType.CmifRequest ||
request.Type == IpcMessageType.CmifRequestWithContext)
if (request.Type is IpcMessageType.CmifRequest or
IpcMessageType.CmifRequestWithContext)
{
response.Type = IpcMessageType.CmifResponse;
@ -374,8 +374,8 @@ namespace Ryujinx.HLE.HOS.Services
response.RawData = _responseDataStream.ToArray();
}
else if (request.Type == IpcMessageType.CmifControl ||
request.Type == IpcMessageType.CmifControlWithContext)
else if (request.Type is IpcMessageType.CmifControl or
IpcMessageType.CmifControlWithContext)
{
#pragma warning disable IDE0059 // Remove unnecessary value assignment
uint magic = (uint)_requestDataReader.ReadUInt64();
@ -425,7 +425,7 @@ namespace Ryujinx.HLE.HOS.Services
throw new NotImplementedException(cmdId.ToString());
}
}
else if (request.Type == IpcMessageType.CmifCloseSession || request.Type == IpcMessageType.TipcCloseSession)
else if (request.Type is IpcMessageType.CmifCloseSession or IpcMessageType.TipcCloseSession)
{
DestroySession(serverSessionHandle);
shouldReply = false;

View file

@ -63,7 +63,7 @@ namespace Ryujinx.HLE.HOS.Services.Settings
RegionCode regionCode = (RegionCode)context.Device.System.State.DesiredRegionCode;
if (regionCode < RegionCode.Min || regionCode > RegionCode.Max)
if (regionCode is < RegionCode.Min or > RegionCode.Max)
{
regionCode = RegionCode.USA;
}

View file

@ -242,7 +242,7 @@ namespace Ryujinx.HLE.HOS.Services.Sm
{
byte chr = context.RequestData.ReadByte();
if (chr >= 0x20 && chr < 0x7f)
if (chr is >= 0x20 and < 0x7f)
{
nameBuilder.Append((char)chr);
}

View file

@ -38,6 +38,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd
{
Logger.Warning?.Print(LogClass.ServiceBsd, $"Operation failed with error {errorCode}.");
}
result = -1;
}
@ -102,7 +103,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd
}
LinuxError errno = LinuxError.SUCCESS;
ISocket newBsdSocket;
ManagedSocket newBsdSocket;
try
{
@ -412,7 +413,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd
{
static bool IsUnexpectedLinuxError(LinuxError error)
{
return error != LinuxError.SUCCESS && error != LinuxError.ETIMEDOUT;
return error is not LinuxError.SUCCESS and not LinuxError.ETIMEDOUT;
}
// Hybrid approach
@ -817,7 +818,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd
{
Logger.Warning?.PrintMsg(LogClass.ServiceBsd, $"Invalid socket fd '{socketFd}'.");
}
return WriteBsdResult(context, 0, errno);
}
@ -933,7 +934,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd
{
errno = LinuxError.EINVAL;
if (how >= 0 && how <= 2)
if (how is >= 0 and <= 2)
{
errno = socket.Shutdown((BsdSocketShutdownFlags)how);
}
@ -950,7 +951,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd
LinuxError errno = LinuxError.EINVAL;
if (how >= 0 && how <= 2)
if (how is >= 0 and <= 2)
{
errno = _context.ShutdownAllSockets((BsdSocketShutdownFlags)how);
}
@ -1057,7 +1058,6 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd
return WriteBsdResult(context, newSockFd, errno);
}
[CommandCmif(29)] // 7.0.0+
// RecvMMsg(u32 fd, u32 vlen, u32 flags, u32 reserved, nn::socket::TimeVal timeout) -> (i32 ret, u32 bsd_errno, buffer<bytes, 6> message);
public ResultCode RecvMMsg(ServiceCtx context)

View file

@ -45,6 +45,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl
isValidEvent = true;
}
if (evnt.Data.InputEvents.HasFlag(PollEventTypeMask.Output))
{
waiters.Add(socket.WriteEvent);
@ -91,7 +92,6 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl
outputEvents |= PollEventTypeMask.Output;
}
if (outputEvents != 0)
{
evnt.Data.OutputEvents = outputEvents;

View file

@ -109,6 +109,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl
{
Logger.Warning?.Print(LogClass.ServiceBsd, $"Socket Exception: {exception}");
}
return WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
}
}
@ -128,6 +129,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl
{
Logger.Warning?.Print(LogClass.ServiceBsd, $"Socket Exception: {exception}");
}
return WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
}
}
@ -148,6 +150,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl
{
Logger.Info?.PrintMsg(LogClass.ServiceBsd, $"Connecting to: {ProtocolType}/***:{remoteEndPoint.Port}");
}
try
{
Socket.Connect(remoteEndPoint);
@ -166,6 +169,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl
{
Logger.Warning?.Print(LogClass.ServiceBsd, $"Socket Exception: {exception}");
}
return WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
}
}
@ -200,6 +204,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl
{
Logger.Warning?.Print(LogClass.ServiceBsd, $"Socket Exception: {exception}");
}
return WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
}
}
@ -223,6 +228,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl
{
Logger.Warning?.Print(LogClass.ServiceBsd, $"Socket Exception: {exception}");
}
return WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
}
}
@ -259,6 +265,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl
{
Logger.Warning?.Print(LogClass.ServiceBsd, $"Socket Exception: {exception}");
}
receiveSize = -1;
result = WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
@ -314,6 +321,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl
{
Logger.Warning?.Print(LogClass.ServiceBsd, $"Socket Exception: {exception}");
}
receiveSize = -1;
result = WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
@ -341,6 +349,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl
{
Logger.Warning?.Print(LogClass.ServiceBsd, $"Socket Exception: {exception}");
}
sendSize = -1;
return WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
@ -361,6 +370,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl
{
Logger.Warning?.Print(LogClass.ServiceBsd, $"Socket Exception: {exception}");
}
sendSize = -1;
return WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
@ -402,6 +412,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl
{
Logger.Warning?.Print(LogClass.ServiceBsd, $"Socket Exception: {exception}");
}
return WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
}
}
@ -452,6 +463,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl
{
Logger.Warning?.Print(LogClass.ServiceBsd, $"Socket Exception: {exception}");
}
return WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
}
}
@ -480,7 +492,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl
return true;
}
private static IList<ArraySegment<byte>> ConvertMessagesToBuffer(BsdMMsgHdr message)
private static ArraySegment<byte>[] ConvertMessagesToBuffer(BsdMMsgHdr message)
{
int segmentCount = 0;
int index = 0;
@ -588,6 +600,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl
{
Logger.Warning?.Print(LogClass.ServiceBsd, $"Socket Exception: {exception}");
}
return WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
}
}
@ -630,6 +643,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl
{
Logger.Warning?.Print(LogClass.ServiceBsd, $"Socket Exception: {exception}");
}
return WinSockHelper.ConvertError((WsaError)exception.ErrorCode);
}
}

View file

@ -2,7 +2,6 @@ using System.Diagnostics.CodeAnalysis;
namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Impl
{
[SuppressMessage("ReSharper", "InconsistentNaming")]
enum WsaError
{
/*

View file

@ -36,7 +36,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Proxy
throw new NotImplementedException();
}
});
};
}
FilterSockets(readEvents, readDefault, (socket) => socket.Readable);
FilterSockets(writeEvents, writeDefault, (socket) => socket.Writable);
@ -77,6 +77,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Proxy
{
Logger.Info?.PrintMsg(LogClass.ServiceBsd, $"Opening socket using host networking stack");
}
return new DefaultSocket(domain, type, protocol, lanInterfaceId);
}
}

View file

@ -2,7 +2,6 @@ using System.Diagnostics.CodeAnalysis;
namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types
{
[SuppressMessage("Design", "CA1069: Enums values should not be duplicated")]
enum BsdSocketOption
{
SoDebug = 0x1,

View file

@ -2,7 +2,6 @@ using System.Diagnostics.CodeAnalysis;
namespace Ryujinx.HLE.HOS.Services.Sockets.Bsd.Types
{
[SuppressMessage("ReSharper", "InconsistentNaming")]
enum LinuxError
{
SUCCESS = 0,

View file

@ -14,10 +14,7 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Nsd
class IManager : IpcService
{
public static readonly NsdSettings NsdSettings;
#pragma warning disable IDE0052 // Remove unread private member
private readonly FqdnResolver _fqdnResolver;
#pragma warning restore IDE0052
private readonly bool _isInitialized = false;
public IManager(ServiceCtx context)

View file

@ -24,10 +24,10 @@ namespace Ryujinx.HLE.HOS.Services.Sockets.Nsd.Manager
public static ResultCode Resolve(string address, out string resolvedAddress)
{
if (address == "api.sect.srv.nintendo.net" ||
address == "ctest.cdn.nintendo.net" ||
address == "ctest.cdn.n.nintendoswitch.cn" ||
address == "unknown.dummy.nintendo.net")
if (address is "api.sect.srv.nintendo.net" or
"ctest.cdn.nintendo.net" or
"ctest.cdn.n.nintendoswitch.cn" or
"unknown.dummy.nintendo.net")
{
resolvedAddress = address;
}

View file

@ -84,6 +84,7 @@ namespace Ryujinx.HLE.HOS.Services.Spl
{
configValue = (ulong)DramId.IcosaSamsung4GiB;
}
break;
case ConfigItem.SecurityEngineInterruptNumber:
return SmcResult.NotImplemented;

View file

@ -124,7 +124,7 @@ namespace Ryujinx.HLE.HOS.Services.Ssl
return ResultCode.Success;
}
[CommandCmif(100)]
// CreateContextForSystem(u64 pid, nn::ssl::sf::SslVersion, u64)
public ResultCode CreateContextForSystem(ServiceCtx context)
@ -132,23 +132,23 @@ namespace Ryujinx.HLE.HOS.Services.Ssl
ulong pid = context.RequestData.ReadUInt64();
SslVersion sslVersion = (SslVersion)context.RequestData.ReadUInt32();
ulong pidPlaceholder = context.RequestData.ReadUInt64();
Logger.Stub?.PrintStub(LogClass.ServiceSsl, new { pid, sslVersion, pidPlaceholder });
return ResultCode.Success;
}
[CommandCmif(101)]
// SetThreadCoreMask(u64 mask)
public ResultCode SetThreadCoreMask(ServiceCtx context)
{
ulong mask = context.RequestData.ReadUInt64();
Logger.Stub?.PrintStub(LogClass.ServiceSsl, new { mask });
return ResultCode.Success;
}
[CommandCmif(102)]
// GetThreadCoreMask() -> u64
public ResultCode GetThreadCoreMask(ServiceCtx context)
@ -157,7 +157,7 @@ namespace Ryujinx.HLE.HOS.Services.Ssl
return ResultCode.Success;
}
[CommandCmif(103)]
// VerifySignature(buffer<0x5> unknownInput1, buffer<0x5> unknownInput2, buffer<0x5> unknownInput3, buffer<bytes, 4> unknown1)
public ResultCode VerifySignature(ServiceCtx context)

View file

@ -21,7 +21,7 @@ namespace Ryujinx.HLE.HOS.Services.Ssl.SslService
private SessionCacheMode _sessionCacheMode;
private string _hostName;
private ISslConnectionBase _connection;
private SslManagedSocketConnection _connection;
private BsdContext _bsdContext;
private readonly ulong _processId;
@ -296,7 +296,6 @@ namespace Ryujinx.HLE.HOS.Services.Ssl.SslService
using WritableRegion region = context.Memory.GetWritableRegion(context.Request.ReceiveBuff[0].Position, (int)context.Request.ReceiveBuff[0].Size);
// TODO: Better error management.
result = _connection.Peek(out int peekCount, region.Memory);

View file

@ -336,7 +336,7 @@ namespace Ryujinx.HLE.HOS.Services.SurfaceFlinger
public Status SetMaxAcquiredBufferCount(int maxAcquiredBufferCount)
{
if (maxAcquiredBufferCount < 0 || maxAcquiredBufferCount > BufferSlotArray.MaxAcquiredBuffers)
if (maxAcquiredBufferCount is < 0 or > BufferSlotArray.MaxAcquiredBuffers)
{
return Status.BadValue;
}

View file

@ -126,7 +126,7 @@ namespace Ryujinx.HLE.HOS.Services.SurfaceFlinger
{
BufferState state = Slots[slot].BufferState;
if (state == BufferState.Queued || state == BufferState.Dequeued)
if (state is BufferState.Queued or BufferState.Dequeued)
{
maxBufferCount = slot + 1;
}

View file

@ -636,6 +636,7 @@ namespace Ryujinx.HLE.HOS.Services.SurfaceFlinger
status = Status.Success;
}
break;
}
}
@ -758,7 +759,6 @@ namespace Ryujinx.HLE.HOS.Services.SurfaceFlinger
return Status.BadValue;
}
if (maxBufferCount < Core.MaxBufferCountCached)
{
for (int slot = maxBufferCount; slot < Core.MaxBufferCountCached; slot++)
@ -791,6 +791,7 @@ namespace Ryujinx.HLE.HOS.Services.SurfaceFlinger
{
freeSlot = slot;
}
break;
default:
break;

View file

@ -2,7 +2,6 @@ using System.Diagnostics.CodeAnalysis;
namespace Ryujinx.HLE.HOS.Services.SurfaceFlinger
{
[SuppressMessage("Design", "CA1069: Enums values should not be duplicated")]
enum Status
{
Success = 0,

View file

@ -189,7 +189,7 @@ namespace Ryujinx.HLE.HOS.Services.SurfaceFlinger
return Vi.ResultCode.InvalidValue;
}
if (layer.State != LayerState.ManagedClosed && layer.State != LayerState.ManagedOpened)
if (layer.State is not LayerState.ManagedClosed and not LayerState.ManagedOpened)
{
Logger.Error?.Print(LogClass.SurfaceFlinger, $"Failed to destroy managed layer {layerId} (permission denied)");
@ -393,7 +393,7 @@ namespace Ryujinx.HLE.HOS.Services.SurfaceFlinger
PostFrameBuffer(layer, item);
}
else if (acquireStatus != Status.NoBufferAvailaible && acquireStatus != Status.InvalidOperation)
else if (acquireStatus is not Status.NoBufferAvailaible and not Status.InvalidOperation)
{
throw new InvalidOperationException();
}
@ -421,8 +421,8 @@ namespace Ryujinx.HLE.HOS.Services.SurfaceFlinger
Format format = ConvertColorFormat(item.GraphicBuffer.Object.Buffer.Surfaces[0].ColorFormat);
byte bytesPerPixel =
format == Format.B5G6R5Unorm ||
format == Format.R4G4B4A4Unorm ? (byte)2 : (byte)4;
format is Format.B5G6R5Unorm or
Format.R4G4B4A4Unorm ? (byte)2 : (byte)4;
int gobBlocksInY = 1 << item.GraphicBuffer.Object.Buffer.Surfaces[0].BlockHeightLog2;

View file

@ -49,7 +49,6 @@ namespace Ryujinx.HLE.HOS.Services.SurfaceFlinger
Logger.Error?.Print(LogClass.SurfaceFlinger, "Android fence didn't signal in 3000 ms");
Wait(gpuContext, Timeout.InfiniteTimeSpan);
}
}
public bool Wait(GpuContext gpuContext, TimeSpan timeout)

View file

@ -2,7 +2,6 @@ using System.Diagnostics.CodeAnalysis;
namespace Ryujinx.HLE.HOS.Services.SurfaceFlinger
{
[SuppressMessage("Design", "CA1069: Enums values should not be duplicated")]
enum ColorFormat : ulong
{
#pragma warning disable IDE0055 // Disable formatting

View file

@ -26,7 +26,6 @@ namespace Ryujinx.HLE.HOS.Services.Time.Clock
public byte Type;
public ushort Unknown;
[StructLayout(LayoutKind.Sequential, Pack = 1, Size = Size)]
private struct LocationNameStorageHolder
{

View file

@ -2,7 +2,6 @@ using System.Diagnostics.CodeAnalysis;
namespace Ryujinx.HLE.HOS.Services.Time
{
[SuppressMessage("Design", "CA1069: Enums values should not be duplicated")]
public enum ResultCode
{
ModuleId = 116,

View file

@ -222,7 +222,6 @@ namespace Ryujinx.HLE.HOS.Services.Time.TimeZone
{
seconds = 0;
bool isValid = GetNum(name, ref namePosition, out int num, 0, HoursPerDays * DaysPerWeek - 1);
if (!isValid)
{
@ -264,6 +263,7 @@ namespace Ryujinx.HLE.HOS.Services.Time.TimeZone
seconds += num;
}
}
return true;
}
@ -486,7 +486,7 @@ namespace Ryujinx.HLE.HOS.Services.Time.TimeZone
return false;
}
if (name[namePosition] != '\0' && name[namePosition] != ',' && name[namePosition] != ';')
if (name[namePosition] is not (byte)'\0' and not (byte)',' and not (byte)';')
{
bool isValid = GetOffset(name.ToArray(), ref namePosition, ref dstOffset);
@ -506,7 +506,7 @@ namespace Ryujinx.HLE.HOS.Services.Time.TimeZone
namePosition = 0;
}
if (name[namePosition] == ',' || name[namePosition] == ';')
if (name[namePosition] is (byte)',' or (byte)';')
{
namePosition++;
@ -744,6 +744,7 @@ namespace Ryujinx.HLE.HOS.Services.Time.TimeZone
{
outRules.Chars[charsPosition + i] = destName[i];
}
outRules.Chars[charsPosition + destLen] = 0;
}
@ -763,6 +764,7 @@ namespace Ryujinx.HLE.HOS.Services.Time.TimeZone
{
value += SecondsPerDay;
}
break;
case RuleType.DayOfYear:
@ -923,7 +925,6 @@ namespace Ryujinx.HLE.HOS.Services.Time.TimeZone
return false;
}
if (streamLength < (timeCount * TimeTypeSize
+ timeCount
+ typeCount * 6
@ -1051,7 +1052,6 @@ namespace Ryujinx.HLE.HOS.Services.Time.TimeZone
outRules.Ttis[i].IsGMT = p[0] != 0;
p = p[1..];
}
}
long position = (workBuffer.Length - p.Length);
@ -1554,7 +1554,7 @@ namespace Ryujinx.HLE.HOS.Services.Time.TimeZone
int savedSeconds;
if (calendarTime.Second >= 0 && calendarTime.Second < SecondsPerMinute)
if (calendarTime.Second is >= 0 and < SecondsPerMinute)
{
savedSeconds = 0;
}

View file

@ -152,7 +152,6 @@ namespace Ryujinx.HLE.HOS.Services.Time.TimeZone
TimeZone.ParseTimeZoneBinary(ref tzRule, tzif.Get.AsStream());
TimeTypeInfo ttInfo;
if (tzRule.TimeCount > 0) // Find the current transition period
{
@ -164,6 +163,7 @@ namespace Ryujinx.HLE.HOS.Services.Time.TimeZone
fin = i;
}
}
ttInfo = tzRule.Ttis[tzRule.Types[fin]];
}
else if (tzRule.TypeCount >= 1) // Otherwise, use the first offset in TTInfo

View file

@ -4,9 +4,7 @@ namespace Ryujinx.HLE.HOS.Services.Vi.RootService.ApplicationDisplayService
{
class IManagerDisplayService : IpcService
{
#pragma warning disable IDE0052 // Remove unread private member
private readonly IApplicationDisplayService _applicationDisplayService;
#pragma warning restore IDE0052
public IManagerDisplayService(IApplicationDisplayService applicationDisplayService)
{

View file

@ -4,9 +4,7 @@ namespace Ryujinx.HLE.HOS.Services.Vi.RootService.ApplicationDisplayService
{
class ISystemDisplayService : IpcService
{
#pragma warning disable IDE0052 // Remove unread private member
private readonly IApplicationDisplayService _applicationDisplayService;
#pragma warning restore IDE0052
public ISystemDisplayService(IApplicationDisplayService applicationDisplayService)
{

View file

@ -148,7 +148,7 @@ namespace Ryujinx.HLE.HOS.Services.Vi.RootService
{
byte chr = context.RequestData.ReadByte();
if (chr >= 0x20 && chr < 0x7f)
if (chr is >= 0x20 and < 0x7f)
{
nameBuilder.Append((char)chr);
}
@ -346,7 +346,7 @@ namespace Ryujinx.HLE.HOS.Services.Vi.RootService
return ResultCode.InvalidArguments;
}
if (scalingMode != SourceScalingMode.ScaleToWindow && scalingMode != SourceScalingMode.PreserveAspectRatio)
if (scalingMode is not SourceScalingMode.ScaleToWindow and not SourceScalingMode.PreserveAspectRatio)
{
// Invalid scaling mode specified.
return ResultCode.InvalidScalingMode;

View file

@ -55,7 +55,7 @@ namespace Ryujinx.HLE.HOS.Tamper
return null;
}
private ITamperProgram CompileImpl(string name, IEnumerable<string> rawInstructions)
private AtmosphereProgram CompileImpl(string name, IEnumerable<string> rawInstructions)
{
CompilationContext context = new(_exeAddress, _heapAddress, _aliasAddress, _aslrAddress, _process);
context.BlockStack.Push(new OperationBlock(null));

View file

@ -86,7 +86,7 @@ namespace Ryujinx.HLE.HOS
private static bool IsProcessValid(ITamperedProcess process)
{
return process.State != ProcessState.Crashed && process.State != ProcessState.Exiting && process.State != ProcessState.Exited;
return process.State is not ProcessState.Crashed and not ProcessState.Exiting and not ProcessState.Exited;
}
private void TamperRunner()
@ -173,7 +173,7 @@ namespace Ryujinx.HLE.HOS
// Look for the input of the player one or the handheld.
foreach (GamepadInput input in gamepadInputs)
{
if (input.PlayerId == PlayerIndex.Player1 || input.PlayerId == PlayerIndex.Handheld)
if (input.PlayerId is PlayerIndex.Player1 or PlayerIndex.Handheld)
{
Volatile.Write(ref _pressedKeys, (long)input.Buttons);

View file

@ -102,7 +102,7 @@ namespace Ryujinx.HLE
/// Control if the Profiled Translation Cache (PTC) should be used.
/// </summary>
internal readonly bool EnablePtc;
/// <summary>
/// Control the arbitrary scalar applied to emulated CPU tick timing.
/// </summary>
@ -193,7 +193,7 @@ namespace Ryujinx.HLE
/// An action called when HLE force a refresh of output after docked mode changed.
/// </summary>
public Action RefreshInputConfig { internal get; set; }
/// <summary>
/// The desired hacky workarounds.
/// </summary>

View file

@ -2,8 +2,6 @@ using System.Diagnostics.CodeAnalysis;
namespace Ryujinx.HLE.Loaders.Elf
{
[SuppressMessage("ReSharper", "InconsistentNaming")]
[SuppressMessage("Design", "CA1069: Enums values should not be duplicated")]
enum ElfDynamicTag
{
DT_NULL = 0,

View file

@ -8,8 +8,8 @@ namespace Ryujinx.HLE.Loaders.Elf
public ElfSymbolBinding Binding { get; private set; }
public ElfSymbolVisibility Visibility { get; private set; }
public readonly bool IsFuncOrObject => Type == ElfSymbolType.SttFunc || Type == ElfSymbolType.SttObject;
public readonly bool IsGlobalOrWeak => Binding == ElfSymbolBinding.StbGlobal || Binding == ElfSymbolBinding.StbWeak;
public readonly bool IsFuncOrObject => Type is ElfSymbolType.SttFunc or ElfSymbolType.SttObject;
public readonly bool IsGlobalOrWeak => Binding is ElfSymbolBinding.StbGlobal or ElfSymbolBinding.StbWeak;
public int ShIdx { get; private set; }
public ulong Value { get; private set; }

View file

@ -94,15 +94,15 @@ namespace Ryujinx.HLE.Loaders.Mods
static int ParseHexByte(byte c)
{
if (c >= '0' && c <= '9')
if (c is >= (byte)'0' and <= (byte)'9')
{
return c - '0';
}
else if (c >= 'A' && c <= 'F')
else if (c is >= (byte)'A' and <= (byte)'F')
{
return c - 'A' + 10;
}
else if (c >= 'a' && c <= 'f')
else if (c is >= (byte)'a' and <= (byte)'f')
{
return c - 'a' + 10;
}

View file

@ -76,7 +76,7 @@ namespace Ryujinx.HLE.Loaders.Mods
Logger.Warning?.Print(LogClass.ModLoader, $"Attempted to patch protected memory ({patchOffset:x} is within protected boundary of {protectedOffset:x}).");
continue;
}
if (patchOffset > memory.Length)
{
Logger.Warning?.Print(LogClass.ModLoader, $"Attempted to patch out of bounds memory (offset {patchOffset} ({patchOffset:x}) exceeds memory buffer length {memory.Length}).");

View file

@ -34,7 +34,7 @@ namespace Ryujinx.HLE.Loaders.Processes
if (!_processesByPid.TryGetValue(_latestPid, out ProcessResult value))
throw new RyujinxException(
$"The HLE Process map did not have a process with ID {_latestPid}. Are you missing firmware?");
return value;
}
}
@ -159,7 +159,7 @@ namespace Ryujinx.HLE.Loaders.Processes
return false;
}
public bool LoadNxo(string path)
{
BlitStruct<ApplicationControlProperty> nacpData = new(1);
@ -172,7 +172,7 @@ namespace Ryujinx.HLE.Loaders.Processes
// Load executable.
IExecutable executable;
if (Path.GetExtension(path).ToLower() == ".nro")
if (Path.GetExtension(path).Equals(".nro", StringComparison.OrdinalIgnoreCase))
{
FileStream input = new(path, FileMode.Open);
NroExecutable nro = new(input.AsStorage());

View file

@ -7,7 +7,7 @@ namespace Ryujinx.HLE
public class PerformanceStatistics
{
private readonly Switch _device;
private const int FrameTypeGame = 0;
private const int PercentTypeFifo = 0;
@ -33,7 +33,7 @@ namespace Ryujinx.HLE
public PerformanceStatistics(Switch device)
{
_device = device;
_frameRate = new double[1];
_accumulatedFrameTime = new double[1];
_previousFrameTime = new double[1];
@ -165,7 +165,7 @@ namespace Ryujinx.HLE
{
return 1000 / _frameRate[FrameTypeGame];
}
public string FormatFifoPercent()
{
double fifoPercent = GetFifoPercent();

View file

@ -1,4 +1,4 @@
using LibHac.Common;
using LibHac.Common;
using LibHac.Ns;
using System;
using System.Text;
@ -11,13 +11,13 @@ namespace Ryujinx.HLE
{
// https://switchbrew.org/wiki/NACP
const int OffsetOfDisplayVersion = 0x3060;
// https://switchbrew.org/wiki/NACP#ApplicationTitle
const int TotalApplicationTitles = 0x10;
const int SizeOfApplicationTitle = 0x300;
const int OffsetOfApplicationPublisherStrings = 0x200;
BlitStruct<ApplicationControlProperty> nacpData = new(1);
// name and publisher buffer
@ -27,7 +27,7 @@ namespace Ryujinx.HLE
Encoding.ASCII.GetBytes(name).AsSpan().CopyTo(nacpData.ByteSpan[(i * SizeOfApplicationTitle)..]);
"Ryujinx"u8.CopyTo(nacpData.ByteSpan[(i * SizeOfApplicationTitle + OffsetOfApplicationPublisherStrings)..]);
}
// version buffer
Encoding.ASCII.GetBytes(version).AsSpan().CopyTo(nacpData.ByteSpan[OffsetOfDisplayVersion..]);

View file

@ -20,7 +20,7 @@ namespace Ryujinx.HLE
public class Switch : IDisposable
{
public static Switch Shared { get; private set; }
public HleConfiguration Configuration { get; }
public IHardwareDeviceDriver AudioDeviceDriver { get; }
public MemoryBlock Memory { get; }
@ -35,7 +35,7 @@ namespace Ryujinx.HLE
get => System?.TickSource?.TickScalar ?? ITickSource.RealityTickScalar;
set => System.TickSource.TickScalar = value;
}
public ProcessLoader Processes { get; }
public PerformanceStatistics Statistics { get; }
public Hid Hid { get; }

View file

@ -62,8 +62,8 @@ namespace Ryujinx.HLE.UI
/// Gets fonts and colors used by the host.
/// </summary>
IHostUITheme HostUITheme { get; }
/// <summary>
/// Displays the player select dialog and returns the selected profile.
/// </summary>

View file

@ -16,7 +16,7 @@ namespace Ryujinx.HLE.Utilities
IFileSystem partitionFileSystem;
if (Path.GetExtension(path).ToLower() == ".xci")
if (Path.GetExtension(path).Equals(".xci", System.StringComparison.OrdinalIgnoreCase))
{
partitionFileSystem = new Xci(fileSystem.KeySet, file.AsStorage()).OpenPartition(XciPartitionType.Secure);
}