diff --git a/Ryujinx.HLE/DeviceMemory.cs b/Ryujinx.HLE/DeviceMemory.cs index edc70911..3db89c72 100644 --- a/Ryujinx.HLE/DeviceMemory.cs +++ b/Ryujinx.HLE/DeviceMemory.cs @@ -9,107 +9,107 @@ namespace Ryujinx.HLE public IntPtr RamPointer { get; private set; } - private unsafe byte* RamPtr; + private unsafe byte* _ramPtr; public unsafe DeviceMemory() { RamPointer = Marshal.AllocHGlobal(new IntPtr(RamSize)); - RamPtr = (byte*)RamPointer; + _ramPtr = (byte*)RamPointer; } - public sbyte ReadSByte(long Position) + public sbyte ReadSByte(long position) { - return (sbyte)ReadByte(Position); + return (sbyte)ReadByte(position); } - public short ReadInt16(long Position) + public short ReadInt16(long position) { - return (short)ReadUInt16(Position); + return (short)ReadUInt16(position); } - public int ReadInt32(long Position) + public int ReadInt32(long position) { - return (int)ReadUInt32(Position); + return (int)ReadUInt32(position); } - public long ReadInt64(long Position) + public long ReadInt64(long position) { - return (long)ReadUInt64(Position); + return (long)ReadUInt64(position); } - public unsafe byte ReadByte(long Position) + public unsafe byte ReadByte(long position) { - return *((byte*)(RamPtr + Position)); + return *(_ramPtr + position); } - public unsafe ushort ReadUInt16(long Position) + public unsafe ushort ReadUInt16(long position) { - return *((ushort*)(RamPtr + Position)); + return *((ushort*)(_ramPtr + position)); } - public unsafe uint ReadUInt32(long Position) + public unsafe uint ReadUInt32(long position) { - return *((uint*)(RamPtr + Position)); + return *((uint*)(_ramPtr + position)); } - public unsafe ulong ReadUInt64(long Position) + public unsafe ulong ReadUInt64(long position) { - return *((ulong*)(RamPtr + Position)); + return *((ulong*)(_ramPtr + position)); } - public void WriteSByte(long Position, sbyte Value) + public void WriteSByte(long position, sbyte value) { - WriteByte(Position, (byte)Value); + WriteByte(position, (byte)value); } - public void WriteInt16(long Position, short Value) + public void WriteInt16(long position, short value) { - WriteUInt16(Position, (ushort)Value); + WriteUInt16(position, (ushort)value); } - public void WriteInt32(long Position, int Value) + public void WriteInt32(long position, int value) { - WriteUInt32(Position, (uint)Value); + WriteUInt32(position, (uint)value); } - public void WriteInt64(long Position, long Value) + public void WriteInt64(long position, long value) { - WriteUInt64(Position, (ulong)Value); + WriteUInt64(position, (ulong)value); } - public unsafe void WriteByte(long Position, byte Value) + public unsafe void WriteByte(long position, byte value) { - *((byte*)(RamPtr + Position)) = Value; + *(_ramPtr + position) = value; } - public unsafe void WriteUInt16(long Position, ushort Value) + public unsafe void WriteUInt16(long position, ushort value) { - *((ushort*)(RamPtr + Position)) = Value; + *((ushort*)(_ramPtr + position)) = value; } - public unsafe void WriteUInt32(long Position, uint Value) + public unsafe void WriteUInt32(long position, uint value) { - *((uint*)(RamPtr + Position)) = Value; + *((uint*)(_ramPtr + position)) = value; } - public unsafe void WriteUInt64(long Position, ulong Value) + public unsafe void WriteUInt64(long position, ulong value) { - *((ulong*)(RamPtr + Position)) = Value; + *((ulong*)(_ramPtr + position)) = value; } - public void FillWithZeros(long Position, int Size) + public void FillWithZeros(long position, int size) { - int Size8 = Size & ~(8 - 1); + int size8 = size & ~(8 - 1); - for (int Offs = 0; Offs < Size8; Offs += 8) + for (int offs = 0; offs < size8; offs += 8) { - WriteInt64(Position + Offs, 0); + WriteInt64(position + offs, 0); } - for (int Offs = Size8; Offs < (Size - Size8); Offs++) + for (int offs = size8; offs < (size - size8); offs++) { - WriteByte(Position + Offs, 0); + WriteByte(position + offs, 0); } } @@ -118,7 +118,7 @@ namespace Ryujinx.HLE Dispose(true); } - protected virtual void Dispose(bool Disposing) + protected virtual void Dispose(bool disposing) { Marshal.FreeHGlobal(RamPointer); } diff --git a/Ryujinx.HLE/Exceptions/InvalidNpdmException.cs b/Ryujinx.HLE/Exceptions/InvalidNpdmException.cs index 58d04434..c4036ea0 100644 --- a/Ryujinx.HLE/Exceptions/InvalidNpdmException.cs +++ b/Ryujinx.HLE/Exceptions/InvalidNpdmException.cs @@ -4,6 +4,6 @@ namespace Ryujinx.HLE.Exceptions { public class InvalidNpdmException : Exception { - public InvalidNpdmException(string ExMsg) : base(ExMsg) { } + public InvalidNpdmException(string message) : base(message) { } } } diff --git a/Ryujinx.HLE/Exceptions/UndefinedInstructionException.cs b/Ryujinx.HLE/Exceptions/UndefinedInstructionException.cs index 24bf9efd..84bb1fc5 100644 --- a/Ryujinx.HLE/Exceptions/UndefinedInstructionException.cs +++ b/Ryujinx.HLE/Exceptions/UndefinedInstructionException.cs @@ -8,6 +8,6 @@ namespace Ryujinx.HLE.Exceptions public UndefinedInstructionException() : base() { } - public UndefinedInstructionException(long Position, int OpCode) : base(string.Format(ExMsg, Position, OpCode)) { } + public UndefinedInstructionException(long position, int opCode) : base(string.Format(ExMsg, position, opCode)) { } } } \ No newline at end of file diff --git a/Ryujinx.HLE/FileSystem/Content/ContentManager.cs b/Ryujinx.HLE/FileSystem/Content/ContentManager.cs index 3727841d..0b3bfe00 100644 --- a/Ryujinx.HLE/FileSystem/Content/ContentManager.cs +++ b/Ryujinx.HLE/FileSystem/Content/ContentManager.cs @@ -9,297 +9,297 @@ namespace Ryujinx.HLE.FileSystem.Content { internal class ContentManager { - private Dictionary> LocationEntries; + private Dictionary> _locationEntries; - private Dictionary SharedFontTitleDictionary; + private Dictionary _sharedFontTitleDictionary; - private SortedDictionary<(ulong, ContentType), string> ContentDictionary; + private SortedDictionary<(ulong, ContentType), string> _contentDictionary; - private Switch Device; + private Switch _device; - public ContentManager(Switch Device) + public ContentManager(Switch device) { - ContentDictionary = new SortedDictionary<(ulong, ContentType), string>(); - LocationEntries = new Dictionary>(); + _contentDictionary = new SortedDictionary<(ulong, ContentType), string>(); + _locationEntries = new Dictionary>(); - SharedFontTitleDictionary = new Dictionary() + _sharedFontTitleDictionary = new Dictionary { { "FontStandard", 0x0100000000000811 }, { "FontChineseSimplified", 0x0100000000000814 }, { "FontExtendedChineseSimplified", 0x0100000000000814 }, { "FontKorean", 0x0100000000000812 }, { "FontChineseTraditional", 0x0100000000000813 }, - { "FontNintendoExtended" , 0x0100000000000810 }, + { "FontNintendoExtended", 0x0100000000000810 } }; - this.Device = Device; + _device = device; } public void LoadEntries() { - ContentDictionary = new SortedDictionary<(ulong, ContentType), string>(); + _contentDictionary = new SortedDictionary<(ulong, ContentType), string>(); - foreach (StorageId StorageId in Enum.GetValues(typeof(StorageId))) + foreach (StorageId storageId in Enum.GetValues(typeof(StorageId))) { - string ContentDirectory = null; - string ContentPathString = null; - string RegisteredDirectory = null; + string contentDirectory = null; + string contentPathString = null; + string registeredDirectory = null; try { - ContentPathString = LocationHelper.GetContentRoot(StorageId); - ContentDirectory = LocationHelper.GetRealPath(Device.FileSystem, ContentPathString); - RegisteredDirectory = Path.Combine(ContentDirectory, "registered"); + contentPathString = LocationHelper.GetContentRoot(storageId); + contentDirectory = LocationHelper.GetRealPath(_device.FileSystem, contentPathString); + registeredDirectory = Path.Combine(contentDirectory, "registered"); } - catch (NotSupportedException NEx) + catch (NotSupportedException) { continue; } - Directory.CreateDirectory(RegisteredDirectory); + Directory.CreateDirectory(registeredDirectory); - LinkedList LocationList = new LinkedList(); + LinkedList locationList = new LinkedList(); - void AddEntry(LocationEntry Entry) + void AddEntry(LocationEntry entry) { - LocationList.AddLast(Entry); + locationList.AddLast(entry); } - foreach (string DirectoryPath in Directory.EnumerateDirectories(RegisteredDirectory)) + foreach (string directoryPath in Directory.EnumerateDirectories(registeredDirectory)) { - if (Directory.GetFiles(DirectoryPath).Length > 0) + if (Directory.GetFiles(directoryPath).Length > 0) { - string NcaName = new DirectoryInfo(DirectoryPath).Name.Replace(".nca", string.Empty); + string ncaName = new DirectoryInfo(directoryPath).Name.Replace(".nca", string.Empty); - using (FileStream NcaFile = new FileStream(Directory.GetFiles(DirectoryPath)[0], FileMode.Open, FileAccess.Read)) + using (FileStream ncaFile = new FileStream(Directory.GetFiles(directoryPath)[0], FileMode.Open, FileAccess.Read)) { - Nca Nca = new Nca(Device.System.KeySet, NcaFile, false); + Nca nca = new Nca(_device.System.KeySet, ncaFile, false); - string SwitchPath = Path.Combine(ContentPathString + ":", - NcaFile.Name.Replace(ContentDirectory, string.Empty).TrimStart('\\')); + string switchPath = Path.Combine(contentPathString + ":", + ncaFile.Name.Replace(contentDirectory, string.Empty).TrimStart('\\')); // Change path format to switch's - SwitchPath = SwitchPath.Replace('\\', '/'); + switchPath = switchPath.Replace('\\', '/'); - LocationEntry Entry = new LocationEntry(SwitchPath, + LocationEntry entry = new LocationEntry(switchPath, 0, - (long)Nca.Header.TitleId, - Nca.Header.ContentType); + (long)nca.Header.TitleId, + nca.Header.ContentType); - AddEntry(Entry); + AddEntry(entry); - ContentDictionary.Add((Nca.Header.TitleId, Nca.Header.ContentType), NcaName); + _contentDictionary.Add((nca.Header.TitleId, nca.Header.ContentType), ncaName); - NcaFile.Close(); - Nca.Dispose(); - NcaFile.Dispose(); + ncaFile.Close(); + nca.Dispose(); + ncaFile.Dispose(); } } } - foreach (string FilePath in Directory.EnumerateFiles(ContentDirectory)) + foreach (string filePath in Directory.EnumerateFiles(contentDirectory)) { - if (Path.GetExtension(FilePath) == ".nca") + if (Path.GetExtension(filePath) == ".nca") { - string NcaName = Path.GetFileNameWithoutExtension(FilePath); + string ncaName = Path.GetFileNameWithoutExtension(filePath); - using (FileStream NcaFile = new FileStream(FilePath, FileMode.Open, FileAccess.Read)) + using (FileStream ncaFile = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { - Nca Nca = new Nca(Device.System.KeySet, NcaFile, false); + Nca nca = new Nca(_device.System.KeySet, ncaFile, false); - string SwitchPath = Path.Combine(ContentPathString + ":", - FilePath.Replace(ContentDirectory, string.Empty).TrimStart('\\')); + string switchPath = Path.Combine(contentPathString + ":", + filePath.Replace(contentDirectory, string.Empty).TrimStart('\\')); // Change path format to switch's - SwitchPath = SwitchPath.Replace('\\', '/'); + switchPath = switchPath.Replace('\\', '/'); - LocationEntry Entry = new LocationEntry(SwitchPath, + LocationEntry entry = new LocationEntry(switchPath, 0, - (long)Nca.Header.TitleId, - Nca.Header.ContentType); + (long)nca.Header.TitleId, + nca.Header.ContentType); - AddEntry(Entry); + AddEntry(entry); - ContentDictionary.Add((Nca.Header.TitleId, Nca.Header.ContentType), NcaName); + _contentDictionary.Add((nca.Header.TitleId, nca.Header.ContentType), ncaName); - NcaFile.Close(); - Nca.Dispose(); - NcaFile.Dispose(); + ncaFile.Close(); + nca.Dispose(); + ncaFile.Dispose(); } } } - if(LocationEntries.ContainsKey(StorageId) && LocationEntries[StorageId]?.Count == 0) + if(_locationEntries.ContainsKey(storageId) && _locationEntries[storageId]?.Count == 0) { - LocationEntries.Remove(StorageId); + _locationEntries.Remove(storageId); } - if (!LocationEntries.ContainsKey(StorageId)) + if (!_locationEntries.ContainsKey(storageId)) { - LocationEntries.Add(StorageId, LocationList); + _locationEntries.Add(storageId, locationList); } } } - public void ClearEntry(long TitleId, ContentType ContentType,StorageId StorageId) + public void ClearEntry(long titleId, ContentType contentType,StorageId storageId) { - RemoveLocationEntry(TitleId, ContentType, StorageId); + RemoveLocationEntry(titleId, contentType, storageId); } - public void RefreshEntries(StorageId StorageId, int Flag) + public void RefreshEntries(StorageId storageId, int flag) { - LinkedList LocationList = LocationEntries[StorageId]; - LinkedListNode LocationEntry = LocationList.First; + LinkedList locationList = _locationEntries[storageId]; + LinkedListNode locationEntry = locationList.First; - while (LocationEntry != null) + while (locationEntry != null) { - LinkedListNode NextLocationEntry = LocationEntry.Next; + LinkedListNode nextLocationEntry = locationEntry.Next; - if (LocationEntry.Value.Flag == Flag) + if (locationEntry.Value.Flag == flag) { - LocationList.Remove(LocationEntry.Value); + locationList.Remove(locationEntry.Value); } - LocationEntry = NextLocationEntry; + locationEntry = nextLocationEntry; } } - public bool HasNca(string NcaId, StorageId StorageId) + public bool HasNca(string ncaId, StorageId storageId) { - if (ContentDictionary.ContainsValue(NcaId)) + if (_contentDictionary.ContainsValue(ncaId)) { - var Content = ContentDictionary.FirstOrDefault(x => x.Value == NcaId); - long TitleId = (long)Content.Key.Item1; - ContentType ContentType = Content.Key.Item2; - StorageId Storage = GetInstalledStorage(TitleId, ContentType, StorageId); + var content = _contentDictionary.FirstOrDefault(x => x.Value == ncaId); + long titleId = (long)content.Key.Item1; + ContentType contentType = content.Key.Item2; + StorageId storage = GetInstalledStorage(titleId, contentType, storageId); - return Storage == StorageId; + return storage == storageId; } return false; } - public UInt128 GetInstalledNcaId(long TitleId, ContentType ContentType) + public UInt128 GetInstalledNcaId(long titleId, ContentType contentType) { - if (ContentDictionary.ContainsKey(((ulong)TitleId,ContentType))) + if (_contentDictionary.ContainsKey(((ulong)titleId,contentType))) { - return new UInt128(ContentDictionary[((ulong)TitleId,ContentType)]); + return new UInt128(_contentDictionary[((ulong)titleId,contentType)]); } return new UInt128(); } - public StorageId GetInstalledStorage(long TitleId, ContentType ContentType, StorageId StorageId) + public StorageId GetInstalledStorage(long titleId, ContentType contentType, StorageId storageId) { - LocationEntry LocationEntry = GetLocation(TitleId, ContentType, StorageId); + LocationEntry locationEntry = GetLocation(titleId, contentType, storageId); - return LocationEntry.ContentPath != null ? - LocationHelper.GetStorageId(LocationEntry.ContentPath) : StorageId.None; + return locationEntry.ContentPath != null ? + LocationHelper.GetStorageId(locationEntry.ContentPath) : StorageId.None; } - public string GetInstalledContentPath(long TitleId, StorageId StorageId, ContentType ContentType) + public string GetInstalledContentPath(long titleId, StorageId storageId, ContentType contentType) { - LocationEntry LocationEntry = GetLocation(TitleId, ContentType, StorageId); + LocationEntry locationEntry = GetLocation(titleId, contentType, storageId); - if (VerifyContentType(LocationEntry, ContentType)) + if (VerifyContentType(locationEntry, contentType)) { - return LocationEntry.ContentPath; + return locationEntry.ContentPath; } return string.Empty; } - public void RedirectLocation(LocationEntry NewEntry, StorageId StorageId) + public void RedirectLocation(LocationEntry newEntry, StorageId storageId) { - LocationEntry LocationEntry = GetLocation(NewEntry.TitleId, NewEntry.ContentType, StorageId); + LocationEntry locationEntry = GetLocation(newEntry.TitleId, newEntry.ContentType, storageId); - if (LocationEntry.ContentPath != null) + if (locationEntry.ContentPath != null) { - RemoveLocationEntry(NewEntry.TitleId, NewEntry.ContentType, StorageId); + RemoveLocationEntry(newEntry.TitleId, newEntry.ContentType, storageId); } - AddLocationEntry(NewEntry, StorageId); + AddLocationEntry(newEntry, storageId); } - private bool VerifyContentType(LocationEntry LocationEntry, ContentType ContentType) + private bool VerifyContentType(LocationEntry locationEntry, ContentType contentType) { - if (LocationEntry.ContentPath == null) + if (locationEntry.ContentPath == null) { return false; } - StorageId StorageId = LocationHelper.GetStorageId(LocationEntry.ContentPath); - string InstalledPath = Device.FileSystem.SwitchPathToSystemPath(LocationEntry.ContentPath); + StorageId storageId = LocationHelper.GetStorageId(locationEntry.ContentPath); + string installedPath = _device.FileSystem.SwitchPathToSystemPath(locationEntry.ContentPath); - if (!string.IsNullOrWhiteSpace(InstalledPath)) + if (!string.IsNullOrWhiteSpace(installedPath)) { - if (File.Exists(InstalledPath)) + if (File.Exists(installedPath)) { - FileStream File = new FileStream(InstalledPath, FileMode.Open, FileAccess.Read); - Nca Nca = new Nca(Device.System.KeySet, File, false); - bool ContentCheck = Nca.Header.ContentType == ContentType; + FileStream file = new FileStream(installedPath, FileMode.Open, FileAccess.Read); + Nca nca = new Nca(_device.System.KeySet, file, false); + bool contentCheck = nca.Header.ContentType == contentType; - Nca.Dispose(); - File.Dispose(); + nca.Dispose(); + file.Dispose(); - return ContentCheck; + return contentCheck; } } return false; } - private void AddLocationEntry(LocationEntry Entry, StorageId StorageId) + private void AddLocationEntry(LocationEntry entry, StorageId storageId) { - LinkedList LocationList = null; + LinkedList locationList = null; - if (LocationEntries.ContainsKey(StorageId)) + if (_locationEntries.ContainsKey(storageId)) { - LocationList = LocationEntries[StorageId]; + locationList = _locationEntries[storageId]; } - if (LocationList != null) + if (locationList != null) { - if (LocationList.Contains(Entry)) + if (locationList.Contains(entry)) { - LocationList.Remove(Entry); + locationList.Remove(entry); } - LocationList.AddLast(Entry); + locationList.AddLast(entry); } } - private void RemoveLocationEntry(long TitleId, ContentType ContentType, StorageId StorageId) + private void RemoveLocationEntry(long titleId, ContentType contentType, StorageId storageId) { - LinkedList LocationList = null; + LinkedList locationList = null; - if (LocationEntries.ContainsKey(StorageId)) + if (_locationEntries.ContainsKey(storageId)) { - LocationList = LocationEntries[StorageId]; + locationList = _locationEntries[storageId]; } - if (LocationList != null) + if (locationList != null) { - LocationEntry Entry = - LocationList.ToList().Find(x => x.TitleId == TitleId && x.ContentType == ContentType); + LocationEntry entry = + locationList.ToList().Find(x => x.TitleId == titleId && x.ContentType == contentType); - if (Entry.ContentPath != null) + if (entry.ContentPath != null) { - LocationList.Remove(Entry); + locationList.Remove(entry); } } } - public bool TryGetFontTitle(string FontName, out long TitleId) + public bool TryGetFontTitle(string fontName, out long titleId) { - return SharedFontTitleDictionary.TryGetValue(FontName, out TitleId); + return _sharedFontTitleDictionary.TryGetValue(fontName, out titleId); } - private LocationEntry GetLocation(long TitleId, ContentType ContentType,StorageId StorageId) + private LocationEntry GetLocation(long titleId, ContentType contentType,StorageId storageId) { - LinkedList LocationList = LocationEntries[StorageId]; + LinkedList locationList = _locationEntries[storageId]; - return LocationList.ToList().Find(x => x.TitleId == TitleId && x.ContentType == ContentType); + return locationList.ToList().Find(x => x.TitleId == titleId && x.ContentType == contentType); } } } diff --git a/Ryujinx.HLE/FileSystem/Content/LocationEntry.cs b/Ryujinx.HLE/FileSystem/Content/LocationEntry.cs index c7c6133b..eabcfed8 100644 --- a/Ryujinx.HLE/FileSystem/Content/LocationEntry.cs +++ b/Ryujinx.HLE/FileSystem/Content/LocationEntry.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; -using LibHac; +using LibHac; namespace Ryujinx.HLE.FileSystem.Content { @@ -12,17 +9,17 @@ namespace Ryujinx.HLE.FileSystem.Content public long TitleId { get; private set; } public ContentType ContentType { get; private set; } - public LocationEntry(string ContentPath, int Flag, long TitleId, ContentType ContentType) + public LocationEntry(string contentPath, int flag, long titleId, ContentType contentType) { - this.ContentPath = ContentPath; - this.Flag = Flag; - this.TitleId = TitleId; - this.ContentType = ContentType; + ContentPath = contentPath; + Flag = flag; + TitleId = titleId; + ContentType = contentType; } - public void SetFlag(int Flag) + public void SetFlag(int flag) { - this.Flag = Flag; + Flag = flag; } } } diff --git a/Ryujinx.HLE/FileSystem/Content/LocationHelper.cs b/Ryujinx.HLE/FileSystem/Content/LocationHelper.cs index 75b59431..df3f5ad6 100644 --- a/Ryujinx.HLE/FileSystem/Content/LocationHelper.cs +++ b/Ryujinx.HLE/FileSystem/Content/LocationHelper.cs @@ -7,30 +7,30 @@ namespace Ryujinx.HLE.FileSystem.Content { internal static class LocationHelper { - public static string GetRealPath(VirtualFileSystem FileSystem, string SwitchContentPath) + public static string GetRealPath(VirtualFileSystem fileSystem, string switchContentPath) { - string BasePath = FileSystem.GetBasePath(); + string basePath = fileSystem.GetBasePath(); - switch (SwitchContentPath) + switch (switchContentPath) { case ContentPath.SystemContent: - return Path.Combine(FileSystem.GetBasePath(), SystemNandPath, "Contents"); + return Path.Combine(fileSystem.GetBasePath(), SystemNandPath, "Contents"); case ContentPath.UserContent: - return Path.Combine(FileSystem.GetBasePath(), UserNandPath, "Contents"); + return Path.Combine(fileSystem.GetBasePath(), UserNandPath, "Contents"); case ContentPath.SdCardContent: - return Path.Combine(FileSystem.GetSdCardPath(), "Nintendo", "Contents"); + return Path.Combine(fileSystem.GetSdCardPath(), "Nintendo", "Contents"); case ContentPath.System: - return Path.Combine(BasePath, SystemNandPath); + return Path.Combine(basePath, SystemNandPath); case ContentPath.User: - return Path.Combine(BasePath, UserNandPath); + return Path.Combine(basePath, UserNandPath); default: - throw new NotSupportedException($"Content Path `{SwitchContentPath}` is not supported."); + throw new NotSupportedException($"Content Path `{switchContentPath}` is not supported."); } } - public static string GetContentPath(ContentStorageId ContentStorageId) + public static string GetContentPath(ContentStorageId contentStorageId) { - switch (ContentStorageId) + switch (contentStorageId) { case ContentStorageId.NandSystem: return ContentPath.SystemContent; @@ -39,13 +39,13 @@ namespace Ryujinx.HLE.FileSystem.Content case ContentStorageId.SdCard: return ContentPath.SdCardContent; default: - throw new NotSupportedException($"Content Storage `{ContentStorageId}` is not supported."); + throw new NotSupportedException($"Content Storage `{contentStorageId}` is not supported."); } } - public static string GetContentRoot(StorageId StorageId) + public static string GetContentRoot(StorageId storageId) { - switch (StorageId) + switch (storageId) { case StorageId.NandSystem: return ContentPath.SystemContent; @@ -54,15 +54,15 @@ namespace Ryujinx.HLE.FileSystem.Content case StorageId.SdCard: return ContentPath.SdCardContent; default: - throw new NotSupportedException($"Storage Id `{StorageId}` is not supported."); + throw new NotSupportedException($"Storage Id `{storageId}` is not supported."); } } - public static StorageId GetStorageId(string ContentPathString) + public static StorageId GetStorageId(string contentPathString) { - string CleanedPath = ContentPathString.Split(':')[0]; + string cleanedPath = contentPathString.Split(':')[0]; - switch (CleanedPath) + switch (cleanedPath) { case ContentPath.SystemContent: case ContentPath.System: diff --git a/Ryujinx.HLE/FileSystem/FileSystemProvider.cs b/Ryujinx.HLE/FileSystem/FileSystemProvider.cs index fdaa7fd7..8461467d 100644 --- a/Ryujinx.HLE/FileSystem/FileSystemProvider.cs +++ b/Ryujinx.HLE/FileSystem/FileSystemProvider.cs @@ -10,228 +10,228 @@ namespace Ryujinx.HLE.FileSystem { class FileSystemProvider : IFileSystemProvider { - private readonly string BasePath; - private readonly string RootPath; + private readonly string _basePath; + private readonly string _rootPath; - public FileSystemProvider(string BasePath, string RootPath) + public FileSystemProvider(string basePath, string rootPath) { - this.BasePath = BasePath; - this.RootPath = RootPath; + _basePath = basePath; + _rootPath = rootPath; - CheckIfDescendentOfRootPath(BasePath); + CheckIfDescendentOfRootPath(basePath); } - public long CreateDirectory(string Name) + public long CreateDirectory(string name) { - CheckIfDescendentOfRootPath(Name); + CheckIfDescendentOfRootPath(name); - if (Directory.Exists(Name)) + if (Directory.Exists(name)) { return MakeError(ErrorModule.Fs, FsErr.PathAlreadyExists); } - Directory.CreateDirectory(Name); + Directory.CreateDirectory(name); return 0; } - public long CreateFile(string Name, long Size) + public long CreateFile(string name, long size) { - CheckIfDescendentOfRootPath(Name); + CheckIfDescendentOfRootPath(name); - if (File.Exists(Name)) + if (File.Exists(name)) { return MakeError(ErrorModule.Fs, FsErr.PathAlreadyExists); } - using (FileStream NewFile = File.Create(Name)) + using (FileStream newFile = File.Create(name)) { - NewFile.SetLength(Size); + newFile.SetLength(size); } return 0; } - public long DeleteDirectory(string Name, bool Recursive) + public long DeleteDirectory(string name, bool recursive) { - CheckIfDescendentOfRootPath(Name); + CheckIfDescendentOfRootPath(name); - string DirName = Name; + string dirName = name; - if (!Directory.Exists(DirName)) + if (!Directory.Exists(dirName)) { return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); } - Directory.Delete(DirName, Recursive); + Directory.Delete(dirName, recursive); return 0; } - public long DeleteFile(string Name) + public long DeleteFile(string name) { - CheckIfDescendentOfRootPath(Name); + CheckIfDescendentOfRootPath(name); - if (!File.Exists(Name)) + if (!File.Exists(name)) { return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); } else { - File.Delete(Name); + File.Delete(name); } return 0; } - public DirectoryEntry[] GetDirectories(string Path) + public DirectoryEntry[] GetDirectories(string path) { - CheckIfDescendentOfRootPath(Path); + CheckIfDescendentOfRootPath(path); - List Entries = new List(); + List entries = new List(); - foreach(string Directory in Directory.EnumerateDirectories(Path)) + foreach(string directory in Directory.EnumerateDirectories(path)) { - DirectoryEntry DirectoryEntry = new DirectoryEntry(Directory, DirectoryEntryType.Directory); + DirectoryEntry directoryEntry = new DirectoryEntry(directory, DirectoryEntryType.Directory); - Entries.Add(DirectoryEntry); + entries.Add(directoryEntry); } - return Entries.ToArray(); + return entries.ToArray(); } - public DirectoryEntry[] GetEntries(string Path) + public DirectoryEntry[] GetEntries(string path) { - CheckIfDescendentOfRootPath(Path); + CheckIfDescendentOfRootPath(path); - if (Directory.Exists(Path)) + if (Directory.Exists(path)) { - List Entries = new List(); + List entries = new List(); - foreach (string Directory in Directory.EnumerateDirectories(Path)) + foreach (string directory in Directory.EnumerateDirectories(path)) { - DirectoryEntry DirectoryEntry = new DirectoryEntry(Directory, DirectoryEntryType.Directory); + DirectoryEntry directoryEntry = new DirectoryEntry(directory, DirectoryEntryType.Directory); - Entries.Add(DirectoryEntry); + entries.Add(directoryEntry); } - foreach (string File in Directory.EnumerateFiles(Path)) + foreach (string file in Directory.EnumerateFiles(path)) { - FileInfo FileInfo = new FileInfo(File); - DirectoryEntry DirectoryEntry = new DirectoryEntry(File, DirectoryEntryType.File, FileInfo.Length); + FileInfo fileInfo = new FileInfo(file); + DirectoryEntry directoryEntry = new DirectoryEntry(file, DirectoryEntryType.File, fileInfo.Length); - Entries.Add(DirectoryEntry); + entries.Add(directoryEntry); } } return null; } - public DirectoryEntry[] GetFiles(string Path) + public DirectoryEntry[] GetFiles(string path) { - CheckIfDescendentOfRootPath(Path); + CheckIfDescendentOfRootPath(path); - List Entries = new List(); + List entries = new List(); - foreach (string File in Directory.EnumerateFiles(Path)) + foreach (string file in Directory.EnumerateFiles(path)) { - FileInfo FileInfo = new FileInfo(File); - DirectoryEntry DirectoryEntry = new DirectoryEntry(File, DirectoryEntryType.File, FileInfo.Length); + FileInfo fileInfo = new FileInfo(file); + DirectoryEntry directoryEntry = new DirectoryEntry(file, DirectoryEntryType.File, fileInfo.Length); - Entries.Add(DirectoryEntry); + entries.Add(directoryEntry); } - return Entries.ToArray(); + return entries.ToArray(); } - public long GetFreeSpace(ServiceCtx Context) + public long GetFreeSpace(ServiceCtx context) { - return Context.Device.FileSystem.GetDrive().AvailableFreeSpace; + return context.Device.FileSystem.GetDrive().AvailableFreeSpace; } - public string GetFullPath(string Name) + public string GetFullPath(string name) { - if (Name.StartsWith("//")) + if (name.StartsWith("//")) { - Name = Name.Substring(2); + name = name.Substring(2); } - else if (Name.StartsWith('/')) + else if (name.StartsWith('/')) { - Name = Name.Substring(1); + name = name.Substring(1); } else { return null; } - string FullPath = Path.Combine(BasePath, Name); + string fullPath = Path.Combine(_basePath, name); - CheckIfDescendentOfRootPath(FullPath); + CheckIfDescendentOfRootPath(fullPath); - return FullPath; + return fullPath; } - public long GetTotalSpace(ServiceCtx Context) + public long GetTotalSpace(ServiceCtx context) { - return Context.Device.FileSystem.GetDrive().TotalSize; + return context.Device.FileSystem.GetDrive().TotalSize; } - public bool DirectoryExists(string Name) + public bool DirectoryExists(string name) { - CheckIfDescendentOfRootPath(Name); + CheckIfDescendentOfRootPath(name); - return Directory.Exists(Name); + return Directory.Exists(name); } - public bool FileExists(string Name) + public bool FileExists(string name) { - CheckIfDescendentOfRootPath(Name); + CheckIfDescendentOfRootPath(name); - return File.Exists(Name); + return File.Exists(name); } - public long OpenDirectory(string Name, int FilterFlags, out IDirectory DirectoryInterface) + public long OpenDirectory(string name, int filterFlags, out IDirectory directoryInterface) { - CheckIfDescendentOfRootPath(Name); + CheckIfDescendentOfRootPath(name); - if (Directory.Exists(Name)) + if (Directory.Exists(name)) { - DirectoryInterface = new IDirectory(Name, FilterFlags, this); + directoryInterface = new IDirectory(name, filterFlags, this); return 0; } - DirectoryInterface = null; + directoryInterface = null; return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); } - public long OpenFile(string Name, out IFile FileInterface) + public long OpenFile(string name, out IFile fileInterface) { - CheckIfDescendentOfRootPath(Name); + CheckIfDescendentOfRootPath(name); - if (File.Exists(Name)) + if (File.Exists(name)) { - FileStream Stream = new FileStream(Name, FileMode.Open); + FileStream stream = new FileStream(name, FileMode.Open); - FileInterface = new IFile(Stream, Name); + fileInterface = new IFile(stream, name); return 0; } - FileInterface = null; + fileInterface = null; return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); } - public long RenameDirectory(string OldName, string NewName) + public long RenameDirectory(string oldName, string newName) { - CheckIfDescendentOfRootPath(OldName); - CheckIfDescendentOfRootPath(NewName); + CheckIfDescendentOfRootPath(oldName); + CheckIfDescendentOfRootPath(newName); - if (Directory.Exists(OldName)) + if (Directory.Exists(oldName)) { - Directory.Move(OldName, NewName); + Directory.Move(oldName, newName); } else { @@ -241,14 +241,14 @@ namespace Ryujinx.HLE.FileSystem return 0; } - public long RenameFile(string OldName, string NewName) + public long RenameFile(string oldName, string newName) { - CheckIfDescendentOfRootPath(OldName); - CheckIfDescendentOfRootPath(NewName); + CheckIfDescendentOfRootPath(oldName); + CheckIfDescendentOfRootPath(newName); - if (File.Exists(OldName)) + if (File.Exists(oldName)) { - File.Move(OldName, NewName); + File.Move(oldName, newName); } else { @@ -258,24 +258,24 @@ namespace Ryujinx.HLE.FileSystem return 0; } - public void CheckIfDescendentOfRootPath(string Path) + public void CheckIfDescendentOfRootPath(string path) { - DirectoryInfo PathInfo = new DirectoryInfo(Path); - DirectoryInfo RootInfo = new DirectoryInfo(RootPath); + DirectoryInfo pathInfo = new DirectoryInfo(path); + DirectoryInfo rootInfo = new DirectoryInfo(_rootPath); - while (PathInfo.Parent != null) + while (pathInfo.Parent != null) { - if (PathInfo.Parent.FullName == RootInfo.FullName) + if (pathInfo.Parent.FullName == rootInfo.FullName) { return; } else { - PathInfo = PathInfo.Parent; + pathInfo = pathInfo.Parent; } } - throw new InvalidOperationException($"Path {Path} is not a child directory of {RootPath}"); + throw new InvalidOperationException($"Path {path} is not a child directory of {_rootPath}"); } } } diff --git a/Ryujinx.HLE/FileSystem/IFileSystemProvider.cs b/Ryujinx.HLE/FileSystem/IFileSystemProvider.cs index 88a630a0..8e2cae64 100644 --- a/Ryujinx.HLE/FileSystem/IFileSystemProvider.cs +++ b/Ryujinx.HLE/FileSystem/IFileSystemProvider.cs @@ -1,41 +1,40 @@ using Ryujinx.HLE.HOS; using Ryujinx.HLE.HOS.Services.FspSrv; -using System; namespace Ryujinx.HLE.FileSystem { interface IFileSystemProvider { - long CreateFile(string Name, long Size); + long CreateFile(string name, long size); - long CreateDirectory(string Name); + long CreateDirectory(string name); - long RenameFile(string OldName, string NewName); + long RenameFile(string oldName, string newName); - long RenameDirectory(string OldName, string NewName); + long RenameDirectory(string oldName, string newName); - DirectoryEntry[] GetEntries(string Path); + DirectoryEntry[] GetEntries(string path); - DirectoryEntry[] GetDirectories(string Path); + DirectoryEntry[] GetDirectories(string path); - DirectoryEntry[] GetFiles(string Path); + DirectoryEntry[] GetFiles(string path); - long DeleteFile(string Name); + long DeleteFile(string name); - long DeleteDirectory(string Name, bool Recursive); + long DeleteDirectory(string name, bool recursive); - bool FileExists(string Name); + bool FileExists(string name); - bool DirectoryExists(string Name); + bool DirectoryExists(string name); - long OpenFile(string Name, out IFile FileInterface); + long OpenFile(string name, out IFile fileInterface); - long OpenDirectory(string Name, int FilterFlags, out IDirectory DirectoryInterface); + long OpenDirectory(string name, int filterFlags, out IDirectory directoryInterface); - string GetFullPath(string Name); + string GetFullPath(string name); - long GetFreeSpace(ServiceCtx Context); + long GetFreeSpace(ServiceCtx context); - long GetTotalSpace(ServiceCtx Context); + long GetTotalSpace(ServiceCtx context); } } diff --git a/Ryujinx.HLE/FileSystem/PFsProvider.cs b/Ryujinx.HLE/FileSystem/PFsProvider.cs index c901f073..71757669 100644 --- a/Ryujinx.HLE/FileSystem/PFsProvider.cs +++ b/Ryujinx.HLE/FileSystem/PFsProvider.cs @@ -12,98 +12,98 @@ namespace Ryujinx.HLE.FileSystem { class PFsProvider : IFileSystemProvider { - private Pfs Pfs; + private Pfs _pfs; - public PFsProvider(Pfs Pfs) + public PFsProvider(Pfs pfs) { - this.Pfs = Pfs; + _pfs = pfs; } - public long CreateDirectory(string Name) + public long CreateDirectory(string name) { throw new NotSupportedException(); } - public long CreateFile(string Name, long Size) + public long CreateFile(string name, long size) { throw new NotSupportedException(); } - public long DeleteDirectory(string Name, bool Recursive) + public long DeleteDirectory(string name, bool recursive) { throw new NotSupportedException(); } - public long DeleteFile(string Name) + public long DeleteFile(string name) { throw new NotSupportedException(); } - public DirectoryEntry[] GetDirectories(string Path) + public DirectoryEntry[] GetDirectories(string path) { return new DirectoryEntry[0]; } - public DirectoryEntry[] GetEntries(string Path) + public DirectoryEntry[] GetEntries(string path) { - List Entries = new List(); + List entries = new List(); - foreach (PfsFileEntry File in Pfs.Files) + foreach (PfsFileEntry file in _pfs.Files) { - DirectoryEntry DirectoryEntry = new DirectoryEntry(File.Name, DirectoryEntryType.File, File.Size); + DirectoryEntry directoryEntry = new DirectoryEntry(file.Name, DirectoryEntryType.File, file.Size); - Entries.Add(DirectoryEntry); + entries.Add(directoryEntry); } - return Entries.ToArray(); + return entries.ToArray(); } - public DirectoryEntry[] GetFiles(string Path) + public DirectoryEntry[] GetFiles(string path) { - List Entries = new List(); + List entries = new List(); - foreach (PfsFileEntry File in Pfs.Files) + foreach (PfsFileEntry file in _pfs.Files) { - DirectoryEntry DirectoryEntry = new DirectoryEntry(File.Name, DirectoryEntryType.File, File.Size); + DirectoryEntry directoryEntry = new DirectoryEntry(file.Name, DirectoryEntryType.File, file.Size); - Entries.Add(DirectoryEntry); + entries.Add(directoryEntry); } - return Entries.ToArray(); + return entries.ToArray(); } - public long GetFreeSpace(ServiceCtx Context) + public long GetFreeSpace(ServiceCtx context) { return 0; } - public string GetFullPath(string Name) + public string GetFullPath(string name) { - return Name; + return name; } - public long GetTotalSpace(ServiceCtx Context) + public long GetTotalSpace(ServiceCtx context) { - return Pfs.Files.Sum(x => x.Size); + return _pfs.Files.Sum(x => x.Size); } - public bool DirectoryExists(string Name) + public bool DirectoryExists(string name) { - return Name == "/" ? true : false; + return name == "/"; } - public bool FileExists(string Name) + public bool FileExists(string name) { - Name = Name.TrimStart('/'); + name = name.TrimStart('/'); - return Pfs.FileExists(Name); + return _pfs.FileExists(name); } - public long OpenDirectory(string Name, int FilterFlags, out IDirectory DirectoryInterface) + public long OpenDirectory(string name, int filterFlags, out IDirectory directoryInterface) { - if (Name == "/") + if (name == "/") { - DirectoryInterface = new IDirectory(Name, FilterFlags, this); + directoryInterface = new IDirectory(name, filterFlags, this); return 0; } @@ -111,34 +111,34 @@ namespace Ryujinx.HLE.FileSystem throw new NotSupportedException(); } - public long OpenFile(string Name, out IFile FileInterface) + public long OpenFile(string name, out IFile fileInterface) { - Name = Name.TrimStart('/'); + name = name.TrimStart('/'); - if (Pfs.FileExists(Name)) + if (_pfs.FileExists(name)) { - Stream Stream = Pfs.OpenFile(Name); - FileInterface = new IFile(Stream, Name); + Stream stream = _pfs.OpenFile(name); + fileInterface = new IFile(stream, name); return 0; } - FileInterface = null; + fileInterface = null; return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); } - public long RenameDirectory(string OldName, string NewName) + public long RenameDirectory(string oldName, string newName) { throw new NotSupportedException(); } - public long RenameFile(string OldName, string NewName) + public long RenameFile(string oldName, string newName) { throw new NotSupportedException(); } - public void CheckIfOutsideBasePath(string Path) + public void CheckIfOutsideBasePath(string path) { throw new NotSupportedException(); } diff --git a/Ryujinx.HLE/FileSystem/RomFsProvider.cs b/Ryujinx.HLE/FileSystem/RomFsProvider.cs index d966d3d7..f6a2f82f 100644 --- a/Ryujinx.HLE/FileSystem/RomFsProvider.cs +++ b/Ryujinx.HLE/FileSystem/RomFsProvider.cs @@ -12,150 +12,150 @@ namespace Ryujinx.HLE.FileSystem { class RomFsProvider : IFileSystemProvider { - private Romfs RomFs; + private Romfs _romFs; - public RomFsProvider(Stream StorageStream) + public RomFsProvider(Stream storageStream) { - RomFs = new Romfs(StorageStream); + _romFs = new Romfs(storageStream); } - public long CreateDirectory(string Name) + public long CreateDirectory(string name) { throw new NotSupportedException(); } - public long CreateFile(string Name, long Size) + public long CreateFile(string name, long size) { throw new NotSupportedException(); } - public long DeleteDirectory(string Name, bool Recursive) + public long DeleteDirectory(string name, bool recursive) { throw new NotSupportedException(); } - public long DeleteFile(string Name) + public long DeleteFile(string name) { throw new NotSupportedException(); } - public DirectoryEntry[] GetDirectories(string Path) + public DirectoryEntry[] GetDirectories(string path) { - List Directories = new List(); + List directories = new List(); - foreach(RomfsDir Directory in RomFs.Directories) + foreach(RomfsDir directory in _romFs.Directories) { - DirectoryEntry DirectoryEntry = new DirectoryEntry(Directory.Name, DirectoryEntryType.Directory); + DirectoryEntry directoryEntry = new DirectoryEntry(directory.Name, DirectoryEntryType.Directory); - Directories.Add(DirectoryEntry); + directories.Add(directoryEntry); } - return Directories.ToArray(); + return directories.ToArray(); } - public DirectoryEntry[] GetEntries(string Path) + public DirectoryEntry[] GetEntries(string path) { - List Entries = new List(); + List entries = new List(); - foreach (RomfsDir Directory in RomFs.Directories) + foreach (RomfsDir directory in _romFs.Directories) { - DirectoryEntry DirectoryEntry = new DirectoryEntry(Directory.Name, DirectoryEntryType.Directory); + DirectoryEntry directoryEntry = new DirectoryEntry(directory.Name, DirectoryEntryType.Directory); - Entries.Add(DirectoryEntry); + entries.Add(directoryEntry); } - foreach (RomfsFile File in RomFs.Files) + foreach (RomfsFile file in _romFs.Files) { - DirectoryEntry DirectoryEntry = new DirectoryEntry(File.Name, DirectoryEntryType.File, File.DataLength); + DirectoryEntry directoryEntry = new DirectoryEntry(file.Name, DirectoryEntryType.File, file.DataLength); - Entries.Add(DirectoryEntry); + entries.Add(directoryEntry); } - return Entries.ToArray(); + return entries.ToArray(); } - public DirectoryEntry[] GetFiles(string Path) + public DirectoryEntry[] GetFiles(string path) { - List Files = new List(); + List files = new List(); - foreach (RomfsFile File in RomFs.Files) + foreach (RomfsFile file in _romFs.Files) { - DirectoryEntry DirectoryEntry = new DirectoryEntry(File.Name, DirectoryEntryType.File, File.DataLength); + DirectoryEntry directoryEntry = new DirectoryEntry(file.Name, DirectoryEntryType.File, file.DataLength); - Files.Add(DirectoryEntry); + files.Add(directoryEntry); } - return Files.ToArray(); + return files.ToArray(); } - public long GetFreeSpace(ServiceCtx Context) + public long GetFreeSpace(ServiceCtx context) { return 0; } - public string GetFullPath(string Name) + public string GetFullPath(string name) { - return Name; + return name; } - public long GetTotalSpace(ServiceCtx Context) + public long GetTotalSpace(ServiceCtx context) { - return RomFs.Files.Sum(x => x.DataLength); + return _romFs.Files.Sum(x => x.DataLength); } - public bool DirectoryExists(string Name) + public bool DirectoryExists(string name) { - return RomFs.Directories.Exists(x=>x.Name == Name); + return _romFs.Directories.Exists(x=>x.Name == name); } - public bool FileExists(string Name) + public bool FileExists(string name) { - return RomFs.FileExists(Name); + return _romFs.FileExists(name); } - public long OpenDirectory(string Name, int FilterFlags, out IDirectory DirectoryInterface) + public long OpenDirectory(string name, int filterFlags, out IDirectory directoryInterface) { - RomfsDir Directory = RomFs.Directories.Find(x => x.Name == Name); + RomfsDir directory = _romFs.Directories.Find(x => x.Name == name); - if (Directory != null) + if (directory != null) { - DirectoryInterface = new IDirectory(Name, FilterFlags, this); + directoryInterface = new IDirectory(name, filterFlags, this); return 0; } - DirectoryInterface = null; + directoryInterface = null; return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); } - public long OpenFile(string Name, out IFile FileInterface) + public long OpenFile(string name, out IFile fileInterface) { - if (RomFs.FileExists(Name)) + if (_romFs.FileExists(name)) { - Stream Stream = RomFs.OpenFile(Name); + Stream stream = _romFs.OpenFile(name); - FileInterface = new IFile(Stream, Name); + fileInterface = new IFile(stream, name); return 0; } - FileInterface = null; + fileInterface = null; return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); } - public long RenameDirectory(string OldName, string NewName) + public long RenameDirectory(string oldName, string newName) { throw new NotSupportedException(); } - public long RenameFile(string OldName, string NewName) + public long RenameFile(string oldName, string newName) { throw new NotSupportedException(); } - public void CheckIfOutsideBasePath(string Path) + public void CheckIfOutsideBasePath(string path) { throw new NotSupportedException(); } diff --git a/Ryujinx.HLE/FileSystem/SaveHelper.cs b/Ryujinx.HLE/FileSystem/SaveHelper.cs index 20138c8c..0dfcfd2b 100644 --- a/Ryujinx.HLE/FileSystem/SaveHelper.cs +++ b/Ryujinx.HLE/FileSystem/SaveHelper.cs @@ -7,39 +7,39 @@ namespace Ryujinx.HLE.FileSystem { static class SaveHelper { - public static string GetSavePath(SaveInfo SaveMetaData, ServiceCtx Context) + public static string GetSavePath(SaveInfo saveMetaData, ServiceCtx context) { - string BaseSavePath = NandPath; - long CurrentTitleId = SaveMetaData.TitleId; + string baseSavePath = NandPath; + long currentTitleId = saveMetaData.TitleId; - switch (SaveMetaData.SaveSpaceId) + switch (saveMetaData.SaveSpaceId) { case SaveSpaceId.NandUser: - BaseSavePath = UserNandPath; + baseSavePath = UserNandPath; break; case SaveSpaceId.NandSystem: - BaseSavePath = SystemNandPath; + baseSavePath = SystemNandPath; break; case SaveSpaceId.SdCard: - BaseSavePath = Path.Combine(SdCardPath, "Nintendo"); + baseSavePath = Path.Combine(SdCardPath, "Nintendo"); break; } - BaseSavePath = Path.Combine(BaseSavePath, "save"); + baseSavePath = Path.Combine(baseSavePath, "save"); - if (SaveMetaData.TitleId == 0 && SaveMetaData.SaveDataType == SaveDataType.SaveData) + if (saveMetaData.TitleId == 0 && saveMetaData.SaveDataType == SaveDataType.SaveData) { - CurrentTitleId = Context.Process.TitleId; + currentTitleId = context.Process.TitleId; } - string SaveAccount = SaveMetaData.UserId.IsZero() ? "savecommon" : SaveMetaData.UserId.ToString(); + string saveAccount = saveMetaData.UserId.IsZero() ? "savecommon" : saveMetaData.UserId.ToString(); - string SavePath = Path.Combine(BaseSavePath, - SaveMetaData.SaveId.ToString("x16"), - SaveAccount, - SaveMetaData.SaveDataType == SaveDataType.SaveData ? CurrentTitleId.ToString("x16") : string.Empty); + string savePath = Path.Combine(baseSavePath, + saveMetaData.SaveId.ToString("x16"), + saveAccount, + saveMetaData.SaveDataType == SaveDataType.SaveData ? currentTitleId.ToString("x16") : string.Empty); - return SavePath; + return savePath; } } } diff --git a/Ryujinx.HLE/FileSystem/SaveInfo.cs b/Ryujinx.HLE/FileSystem/SaveInfo.cs index 3acd33fd..db7f6765 100644 --- a/Ryujinx.HLE/FileSystem/SaveInfo.cs +++ b/Ryujinx.HLE/FileSystem/SaveInfo.cs @@ -4,25 +4,25 @@ namespace Ryujinx.HLE.FileSystem { struct SaveInfo { - public long TitleId { get; private set; } - public long SaveId { get; private set; } + public long TitleId { get; private set; } + public long SaveId { get; private set; } public UInt128 UserId { get; private set; } public SaveDataType SaveDataType { get; private set; } public SaveSpaceId SaveSpaceId { get; private set; } public SaveInfo( - long TitleId, - long SaveId, - SaveDataType SaveDataType, - UInt128 UserId, - SaveSpaceId SaveSpaceId) + long titleId, + long saveId, + SaveDataType saveDataType, + UInt128 userId, + SaveSpaceId saveSpaceId) { - this.TitleId = TitleId; - this.UserId = UserId; - this.SaveId = SaveId; - this.SaveDataType = SaveDataType; - this.SaveSpaceId = SaveSpaceId; + TitleId = titleId; + UserId = userId; + SaveId = saveId; + SaveDataType = saveDataType; + SaveSpaceId = saveSpaceId; } } } diff --git a/Ryujinx.HLE/FileSystem/VirtualFileSystem.cs b/Ryujinx.HLE/FileSystem/VirtualFileSystem.cs index bde6f69f..eed5953f 100644 --- a/Ryujinx.HLE/FileSystem/VirtualFileSystem.cs +++ b/Ryujinx.HLE/FileSystem/VirtualFileSystem.cs @@ -18,40 +18,40 @@ namespace Ryujinx.HLE.FileSystem public Stream RomFs { get; private set; } - public void LoadRomFs(string FileName) + public void LoadRomFs(string fileName) { - RomFs = new FileStream(FileName, FileMode.Open, FileAccess.Read); + RomFs = new FileStream(fileName, FileMode.Open, FileAccess.Read); } - public void SetRomFs(Stream RomfsStream) + public void SetRomFs(Stream romfsStream) { RomFs?.Close(); - RomFs = RomfsStream; + RomFs = romfsStream; } - public string GetFullPath(string BasePath, string FileName) + public string GetFullPath(string basePath, string fileName) { - if (FileName.StartsWith("//")) + if (fileName.StartsWith("//")) { - FileName = FileName.Substring(2); + fileName = fileName.Substring(2); } - else if (FileName.StartsWith('/')) + else if (fileName.StartsWith('/')) { - FileName = FileName.Substring(1); + fileName = fileName.Substring(1); } else { return null; } - string FullPath = Path.GetFullPath(Path.Combine(BasePath, FileName)); + string fullPath = Path.GetFullPath(Path.Combine(basePath, fileName)); - if (!FullPath.StartsWith(GetBasePath())) + if (!fullPath.StartsWith(GetBasePath())) { return null; } - return FullPath; + return fullPath; } public string GetSdCardPath() => MakeDirAndGetFullPath(SdCardPath); @@ -60,84 +60,84 @@ namespace Ryujinx.HLE.FileSystem public string GetSystemPath() => MakeDirAndGetFullPath(SystemPath); - public string GetGameSavePath(SaveInfo Save, ServiceCtx Context) + public string GetGameSavePath(SaveInfo save, ServiceCtx context) { - return MakeDirAndGetFullPath(SaveHelper.GetSavePath(Save, Context)); + return MakeDirAndGetFullPath(SaveHelper.GetSavePath(save, context)); } - public string GetFullPartitionPath(string PartitionPath) + public string GetFullPartitionPath(string partitionPath) { - return MakeDirAndGetFullPath(PartitionPath); + return MakeDirAndGetFullPath(partitionPath); } - public string SwitchPathToSystemPath(string SwitchPath) + public string SwitchPathToSystemPath(string switchPath) { - string[] Parts = SwitchPath.Split(":"); + string[] parts = switchPath.Split(":"); - if (Parts.Length != 2) + if (parts.Length != 2) { return null; } - return GetFullPath(MakeDirAndGetFullPath(Parts[0]), Parts[1]); + return GetFullPath(MakeDirAndGetFullPath(parts[0]), parts[1]); } - public string SystemPathToSwitchPath(string SystemPath) + public string SystemPathToSwitchPath(string systemPath) { - string BaseSystemPath = GetBasePath() + Path.DirectorySeparatorChar; + string baseSystemPath = GetBasePath() + Path.DirectorySeparatorChar; - if (SystemPath.StartsWith(BaseSystemPath)) + if (systemPath.StartsWith(baseSystemPath)) { - string RawPath = SystemPath.Replace(BaseSystemPath, ""); - int FirstSeparatorOffset = RawPath.IndexOf(Path.DirectorySeparatorChar); + string rawPath = systemPath.Replace(baseSystemPath, ""); + int firstSeparatorOffset = rawPath.IndexOf(Path.DirectorySeparatorChar); - if (FirstSeparatorOffset == -1) + if (firstSeparatorOffset == -1) { - return $"{RawPath}:/"; + return $"{rawPath}:/"; } - string BasePath = RawPath.Substring(0, FirstSeparatorOffset); - string FileName = RawPath.Substring(FirstSeparatorOffset + 1); + string basePath = rawPath.Substring(0, firstSeparatorOffset); + string fileName = rawPath.Substring(firstSeparatorOffset + 1); - return $"{BasePath}:/{FileName}"; + return $"{basePath}:/{fileName}"; } return null; } - private string MakeDirAndGetFullPath(string Dir) + private string MakeDirAndGetFullPath(string dir) { // Handles Common Switch Content Paths - switch (Dir) + switch (dir) { case ContentPath.SdCard: case "@Sdcard": - Dir = SdCardPath; + dir = SdCardPath; break; case ContentPath.User: - Dir = UserNandPath; + dir = UserNandPath; break; case ContentPath.System: - Dir = SystemNandPath; + dir = SystemNandPath; break; case ContentPath.SdCardContent: - Dir = Path.Combine(SdCardPath, "Nintendo", "Contents"); + dir = Path.Combine(SdCardPath, "Nintendo", "Contents"); break; case ContentPath.UserContent: - Dir = Path.Combine(UserNandPath, "Contents"); + dir = Path.Combine(UserNandPath, "Contents"); break; case ContentPath.SystemContent: - Dir = Path.Combine(SystemNandPath, "Contents"); + dir = Path.Combine(SystemNandPath, "Contents"); break; } - string FullPath = Path.Combine(GetBasePath(), Dir); + string fullPath = Path.Combine(GetBasePath(), dir); - if (!Directory.Exists(FullPath)) + if (!Directory.Exists(fullPath)) { - Directory.CreateDirectory(FullPath); + Directory.CreateDirectory(fullPath); } - return FullPath; + return fullPath; } public DriveInfo GetDrive() @@ -147,9 +147,9 @@ namespace Ryujinx.HLE.FileSystem public string GetBasePath() { - string AppDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); + string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); - return Path.Combine(AppDataPath, BasePath); + return Path.Combine(appDataPath, BasePath); } public void Dispose() diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ArraySubscriptingExpression.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ArraySubscriptingExpression.cs index 435789e0..5145ff7b 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ArraySubscriptingExpression.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ArraySubscriptingExpression.cs @@ -4,22 +4,22 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class ArraySubscriptingExpression : BaseNode { - private BaseNode LeftNode; - private BaseNode Subscript; + private BaseNode _leftNode; + private BaseNode _subscript; - public ArraySubscriptingExpression(BaseNode LeftNode, BaseNode Subscript) : base(NodeType.ArraySubscriptingExpression) + public ArraySubscriptingExpression(BaseNode leftNode, BaseNode subscript) : base(NodeType.ArraySubscriptingExpression) { - this.LeftNode = LeftNode; - this.Subscript = Subscript; + _leftNode = leftNode; + _subscript = subscript; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Writer.Write("("); - LeftNode.Print(Writer); - Writer.Write(")["); - Subscript.Print(Writer); - Writer.Write("]"); + writer.Write("("); + _leftNode.Print(writer); + writer.Write(")["); + _subscript.Print(writer); + writer.Write("]"); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ArrayType.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ArrayType.cs index 16797360..4b1041ab 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ArrayType.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ArrayType.cs @@ -4,20 +4,20 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class ArrayType : BaseNode { - private BaseNode Base; - private BaseNode DimensionExpression; - private string DimensionString; + private BaseNode _base; + private BaseNode _dimensionExpression; + private string _dimensionString; - public ArrayType(BaseNode Base, BaseNode DimensionExpression = null) : base(NodeType.ArrayType) + public ArrayType(BaseNode Base, BaseNode dimensionExpression = null) : base(NodeType.ArrayType) { - this.Base = Base; - this.DimensionExpression = DimensionExpression; + _base = Base; + _dimensionExpression = dimensionExpression; } - public ArrayType(BaseNode Base, string DimensionString) : base(NodeType.ArrayType) + public ArrayType(BaseNode Base, string dimensionString) : base(NodeType.ArrayType) { - this.Base = Base; - this.DimensionString = DimensionString; + _base = Base; + _dimensionString = dimensionString; } public override bool HasRightPart() @@ -30,30 +30,30 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast return true; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Base.PrintLeft(Writer); + _base.PrintLeft(writer); } - public override void PrintRight(TextWriter Writer) + public override void PrintRight(TextWriter writer) { // FIXME: detect if previous char was a ]. - Writer.Write(" "); + writer.Write(" "); - Writer.Write("["); + writer.Write("["); - if (DimensionString != null) + if (_dimensionString != null) { - Writer.Write(DimensionString); + writer.Write(_dimensionString); } - else if (DimensionExpression != null) + else if (_dimensionExpression != null) { - DimensionExpression.Print(Writer); + _dimensionExpression.Print(writer); } - Writer.Write("]"); + writer.Write("]"); - Base.PrintRight(Writer); + _base.PrintRight(writer); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BaseNode.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BaseNode.cs index 87075846..ca4b98f8 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BaseNode.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BaseNode.cs @@ -4,7 +4,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public enum NodeType { - CVQualifierType, + CvQualifierType, SimpleReferenceType, NameType, EncodedFunction, @@ -62,22 +62,22 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public NodeType Type { get; protected set; } - public BaseNode(NodeType Type) + public BaseNode(NodeType type) { - this.Type = Type; + Type = type; } - public virtual void Print(TextWriter Writer) + public virtual void Print(TextWriter writer) { - PrintLeft(Writer); + PrintLeft(writer); if (HasRightPart()) { - PrintRight(Writer); + PrintRight(writer); } } - public abstract void PrintLeft(TextWriter Writer); + public abstract void PrintLeft(TextWriter writer); public virtual bool HasRightPart() { @@ -99,15 +99,15 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast return null; } - public virtual void PrintRight(TextWriter Writer) {} + public virtual void PrintRight(TextWriter writer) {} public override string ToString() { - StringWriter Writer = new StringWriter(); + StringWriter writer = new StringWriter(); - Print(Writer); + Print(writer); - return Writer.ToString(); + return writer.ToString(); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BinaryExpression.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BinaryExpression.cs index 9cd1dd77..0c492df3 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BinaryExpression.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BinaryExpression.cs @@ -4,37 +4,37 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class BinaryExpression : BaseNode { - private BaseNode LeftPart; - private string Name; - private BaseNode RightPart; + private BaseNode _leftPart; + private string _name; + private BaseNode _rightPart; - public BinaryExpression(BaseNode LeftPart, string Name, BaseNode RightPart) : base(NodeType.BinaryExpression) + public BinaryExpression(BaseNode leftPart, string name, BaseNode rightPart) : base(NodeType.BinaryExpression) { - this.LeftPart = LeftPart; - this.Name = Name; - this.RightPart = RightPart; + _leftPart = leftPart; + _name = name; + _rightPart = rightPart; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - if (Name.Equals(">")) + if (_name.Equals(">")) { - Writer.Write("("); + writer.Write("("); } - Writer.Write("("); - LeftPart.Print(Writer); - Writer.Write(") "); + writer.Write("("); + _leftPart.Print(writer); + writer.Write(") "); - Writer.Write(Name); + writer.Write(_name); - Writer.Write(" ("); - RightPart.Print(Writer); - Writer.Write(")"); + writer.Write(" ("); + _rightPart.Print(writer); + writer.Write(")"); - if (Name.Equals(">")) + if (_name.Equals(">")) { - Writer.Write(")"); + writer.Write(")"); } } } diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BracedExpression.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BracedExpression.cs index 59222ea3..6b9782f5 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BracedExpression.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BracedExpression.cs @@ -4,37 +4,37 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class BracedExpression : BaseNode { - private BaseNode Element; - private BaseNode Expression; - private bool IsArrayExpression; + private BaseNode _element; + private BaseNode _expression; + private bool _isArrayExpression; - public BracedExpression(BaseNode Element, BaseNode Expression, bool IsArrayExpression) : base(NodeType.BracedExpression) + public BracedExpression(BaseNode element, BaseNode expression, bool isArrayExpression) : base(NodeType.BracedExpression) { - this.Element = Element; - this.Expression = Expression; - this.IsArrayExpression = IsArrayExpression; + _element = element; + _expression = expression; + _isArrayExpression = isArrayExpression; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - if (IsArrayExpression) + if (_isArrayExpression) { - Writer.Write("["); - Element.Print(Writer); - Writer.Write("]"); + writer.Write("["); + _element.Print(writer); + writer.Write("]"); } else { - Writer.Write("."); - Element.Print(Writer); + writer.Write("."); + _element.Print(writer); } - if (!Expression.GetType().Equals(NodeType.BracedExpression) || !Expression.GetType().Equals(NodeType.BracedRangeExpression)) + if (!_expression.GetType().Equals(NodeType.BracedExpression) || !_expression.GetType().Equals(NodeType.BracedRangeExpression)) { - Writer.Write(" = "); + writer.Write(" = "); } - Expression.Print(Writer); + _expression.Print(writer); } } } diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BracedRangeExpression.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BracedRangeExpression.cs index e459f1a3..802422d9 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BracedRangeExpression.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BracedRangeExpression.cs @@ -4,31 +4,31 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class BracedRangeExpression : BaseNode { - private BaseNode FirstNode; - private BaseNode LastNode; - private BaseNode Expression; + private BaseNode _firstNode; + private BaseNode _lastNode; + private BaseNode _expression; - public BracedRangeExpression(BaseNode FirstNode, BaseNode LastNode, BaseNode Expression) : base(NodeType.BracedRangeExpression) + public BracedRangeExpression(BaseNode firstNode, BaseNode lastNode, BaseNode expression) : base(NodeType.BracedRangeExpression) { - this.FirstNode = FirstNode; - this.LastNode = LastNode; - this.Expression = Expression; + _firstNode = firstNode; + _lastNode = lastNode; + _expression = expression; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Writer.Write("["); - FirstNode.Print(Writer); - Writer.Write(" ... "); - LastNode.Print(Writer); - Writer.Write("]"); + writer.Write("["); + _firstNode.Print(writer); + writer.Write(" ... "); + _lastNode.Print(writer); + writer.Write("]"); - if (!Expression.GetType().Equals(NodeType.BracedExpression) || !Expression.GetType().Equals(NodeType.BracedRangeExpression)) + if (!_expression.GetType().Equals(NodeType.BracedExpression) || !_expression.GetType().Equals(NodeType.BracedRangeExpression)) { - Writer.Write(" = "); + writer.Write(" = "); } - Expression.Print(Writer); + _expression.Print(writer); } } } diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/CallExpression.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/CallExpression.cs index ae43fcdb..8e3fc3e6 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/CallExpression.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/CallExpression.cs @@ -5,20 +5,20 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class CallExpression : NodeArray { - private BaseNode Callee; + private BaseNode _callee; - public CallExpression(BaseNode Callee, List Nodes) : base(Nodes, NodeType.CallExpression) + public CallExpression(BaseNode callee, List nodes) : base(nodes, NodeType.CallExpression) { - this.Callee = Callee; + _callee = callee; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Callee.Print(Writer); + _callee.Print(writer); - Writer.Write("("); - Writer.Write(string.Join(", ", Nodes.ToArray())); - Writer.Write(")"); + writer.Write("("); + writer.Write(string.Join(", ", Nodes.ToArray())); + writer.Write(")"); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/CastExpression.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/CastExpression.cs index c02e9e65..1149a788 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/CastExpression.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/CastExpression.cs @@ -4,25 +4,25 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class CastExpression : BaseNode { - private string Kind; - private BaseNode To; - private BaseNode From; + private string _kind; + private BaseNode _to; + private BaseNode _from; - public CastExpression(string Kind, BaseNode To, BaseNode From) : base(NodeType.CastExpression) + public CastExpression(string kind, BaseNode to, BaseNode from) : base(NodeType.CastExpression) { - this.Kind = Kind; - this.To = To; - this.From = From; + _kind = kind; + _to = to; + _from = from; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Writer.Write(Kind); - Writer.Write("<"); - To.PrintLeft(Writer); - Writer.Write(">("); - From.PrintLeft(Writer); - Writer.Write(")"); + writer.Write(_kind); + writer.Write("<"); + _to.PrintLeft(writer); + writer.Write(">("); + _from.PrintLeft(writer); + writer.Write(")"); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ConditionalExpression.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ConditionalExpression.cs index 17ac7c1a..c0dd6717 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ConditionalExpression.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ConditionalExpression.cs @@ -4,26 +4,26 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class ConditionalExpression : BaseNode { - private BaseNode ThenNode; - private BaseNode ElseNode; - private BaseNode ConditionNode; + private BaseNode _thenNode; + private BaseNode _elseNode; + private BaseNode _conditionNode; - public ConditionalExpression(BaseNode ConditionNode, BaseNode ThenNode, BaseNode ElseNode) : base(NodeType.ConditionalExpression) + public ConditionalExpression(BaseNode conditionNode, BaseNode thenNode, BaseNode elseNode) : base(NodeType.ConditionalExpression) { - this.ThenNode = ThenNode; - this.ConditionNode = ConditionNode; - this.ElseNode = ElseNode; + _thenNode = thenNode; + _conditionNode = conditionNode; + _elseNode = elseNode; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Writer.Write("("); - ConditionNode.Print(Writer); - Writer.Write(") ? ("); - ThenNode.Print(Writer); - Writer.Write(") : ("); - ElseNode.Print(Writer); - Writer.Write(")"); + writer.Write("("); + _conditionNode.Print(writer); + writer.Write(") ? ("); + _thenNode.Print(writer); + writer.Write(") : ("); + _elseNode.Print(writer); + writer.Write(")"); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ConversionExpression.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ConversionExpression.cs index 7c5d35d8..dd1f7a00 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ConversionExpression.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ConversionExpression.cs @@ -4,21 +4,21 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class ConversionExpression : BaseNode { - private BaseNode TypeNode; - private BaseNode Expressions; + private BaseNode _typeNode; + private BaseNode _expressions; - public ConversionExpression(BaseNode TypeNode, BaseNode Expressions) : base(NodeType.ConversionExpression) + public ConversionExpression(BaseNode typeNode, BaseNode expressions) : base(NodeType.ConversionExpression) { - this.TypeNode = TypeNode; - this.Expressions = Expressions; + _typeNode = typeNode; + _expressions = expressions; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Writer.Write("("); - TypeNode.Print(Writer); - Writer.Write(")("); - Expressions.Print(Writer); + writer.Write("("); + _typeNode.Print(writer); + writer.Write(")("); + _expressions.Print(writer); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ConversionOperatorType.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ConversionOperatorType.cs index 55d4eeca..8a5cde86 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ConversionOperatorType.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ConversionOperatorType.cs @@ -4,12 +4,12 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class ConversionOperatorType : ParentNode { - public ConversionOperatorType(BaseNode Child) : base(NodeType.ConversionOperatorType, Child) { } + public ConversionOperatorType(BaseNode child) : base(NodeType.ConversionOperatorType, child) { } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Writer.Write("operator "); - Child.Print(Writer); + writer.Write("operator "); + Child.Print(writer); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/CtorDtorNameType.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/CtorDtorNameType.cs index 49ed386d..5f458123 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/CtorDtorNameType.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/CtorDtorNameType.cs @@ -4,21 +4,21 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class CtorDtorNameType : ParentNode { - private bool IsDestructor; + private bool _isDestructor; - public CtorDtorNameType(BaseNode Name, bool IsDestructor) : base(NodeType.CtorDtorNameType, Name) + public CtorDtorNameType(BaseNode name, bool isDestructor) : base(NodeType.CtorDtorNameType, name) { - this.IsDestructor = IsDestructor; + _isDestructor = isDestructor; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - if (IsDestructor) + if (_isDestructor) { - Writer.Write("~"); + writer.Write("~"); } - Writer.Write(Child.GetName()); + writer.Write(Child.GetName()); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/CtorVtableSpecialName.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/CtorVtableSpecialName.cs index 7630dbe5..3bb5b163 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/CtorVtableSpecialName.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/CtorVtableSpecialName.cs @@ -4,21 +4,21 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class CtorVtableSpecialName : BaseNode { - private BaseNode FirstType; - private BaseNode SecondType; + private BaseNode _firstType; + private BaseNode _secondType; - public CtorVtableSpecialName(BaseNode FirstType, BaseNode SecondType) : base(NodeType.CtorVtableSpecialName) + public CtorVtableSpecialName(BaseNode firstType, BaseNode secondType) : base(NodeType.CtorVtableSpecialName) { - this.FirstType = FirstType; - this.SecondType = SecondType; + _firstType = firstType; + _secondType = secondType; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Writer.Write("construction vtable for "); - FirstType.Print(Writer); - Writer.Write("-in-"); - SecondType.Print(Writer); + writer.Write("construction vtable for "); + _firstType.Print(writer); + writer.Write("-in-"); + _secondType.Print(writer); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/DeleteExpression.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/DeleteExpression.cs index 22c34c42..14715d25 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/DeleteExpression.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/DeleteExpression.cs @@ -4,30 +4,30 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class DeleteExpression : ParentNode { - private bool IsGlobal; - private bool IsArrayExpression; + private bool _isGlobal; + private bool _isArrayExpression; - public DeleteExpression(BaseNode Child, bool IsGlobal, bool IsArrayExpression) : base(NodeType.DeleteExpression, Child) + public DeleteExpression(BaseNode child, bool isGlobal, bool isArrayExpression) : base(NodeType.DeleteExpression, child) { - this.IsGlobal = IsGlobal; - this.IsArrayExpression = IsArrayExpression; + _isGlobal = isGlobal; + _isArrayExpression = isArrayExpression; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - if (IsGlobal) + if (_isGlobal) { - Writer.Write("::"); + writer.Write("::"); } - Writer.Write("delete"); + writer.Write("delete"); - if (IsArrayExpression) + if (_isArrayExpression) { - Writer.Write("[] "); + writer.Write("[] "); } - Child.Print(Writer); + Child.Print(writer); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/DtorName.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/DtorName.cs index c65c4cfb..5cc4e6cf 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/DtorName.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/DtorName.cs @@ -4,12 +4,12 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class DtorName : ParentNode { - public DtorName(BaseNode Name) : base(NodeType.DtOrName, Name) { } + public DtorName(BaseNode name) : base(NodeType.DtOrName, name) { } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Writer.Write("~"); - Child.PrintLeft(Writer); + writer.Write("~"); + Child.PrintLeft(writer); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/DynamicExceptionSpec.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/DynamicExceptionSpec.cs index dca5f0df..faa91443 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/DynamicExceptionSpec.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/DynamicExceptionSpec.cs @@ -4,13 +4,13 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class DynamicExceptionSpec : ParentNode { - public DynamicExceptionSpec(BaseNode Child) : base(NodeType.DynamicExceptionSpec, Child) { } + public DynamicExceptionSpec(BaseNode child) : base(NodeType.DynamicExceptionSpec, child) { } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Writer.Write("throw("); - Child.Print(Writer); - Writer.Write(")"); + writer.Write("throw("); + Child.Print(writer); + writer.Write(")"); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ElaboratedType.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ElaboratedType.cs index 11f89c8d..086cd3dc 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ElaboratedType.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ElaboratedType.cs @@ -4,18 +4,18 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class ElaboratedType : ParentNode { - private string Elaborated; + private string _elaborated; - public ElaboratedType(string Elaborated, BaseNode Type) : base(NodeType.ElaboratedType, Type) + public ElaboratedType(string elaborated, BaseNode type) : base(NodeType.ElaboratedType, type) { - this.Elaborated = Elaborated; + _elaborated = elaborated; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Writer.Write(Elaborated); - Writer.Write(" "); - Child.Print(Writer); + writer.Write(_elaborated); + writer.Write(" "); + Child.Print(writer); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/EnclosedExpression.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/EnclosedExpression.cs index dc991aa0..b45481dd 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/EnclosedExpression.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/EnclosedExpression.cs @@ -4,22 +4,22 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class EnclosedExpression : BaseNode { - private string Prefix; - private BaseNode Expression; - private string Postfix; + private string _prefix; + private BaseNode _expression; + private string _postfix; - public EnclosedExpression(string Prefix, BaseNode Expression, string Postfix) : base(NodeType.EnclosedExpression) + public EnclosedExpression(string prefix, BaseNode expression, string postfix) : base(NodeType.EnclosedExpression) { - this.Prefix = Prefix; - this.Expression = Expression; - this.Postfix = Postfix; + _prefix = prefix; + _expression = expression; + _postfix = postfix; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Writer.Write(Prefix); - Expression.Print(Writer); - Writer.Write(Postfix); + writer.Write(_prefix); + _expression.Print(writer); + writer.Write(_postfix); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/EncodedFunction.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/EncodedFunction.cs index 37a9a7af..c7b6dab1 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/EncodedFunction.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/EncodedFunction.cs @@ -4,36 +4,36 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class EncodedFunction : BaseNode { - private BaseNode Name; - private BaseNode Params; - private BaseNode CV; - private BaseNode Ref; - private BaseNode Attrs; - private BaseNode Ret; + private BaseNode _name; + private BaseNode _params; + private BaseNode _cv; + private BaseNode _ref; + private BaseNode _attrs; + private BaseNode _ret; - public EncodedFunction(BaseNode Name, BaseNode Params, BaseNode CV, BaseNode Ref, BaseNode Attrs, BaseNode Ret) : base(NodeType.NameType) + public EncodedFunction(BaseNode name, BaseNode Params, BaseNode cv, BaseNode Ref, BaseNode attrs, BaseNode ret) : base(NodeType.NameType) { - this.Name = Name; - this.Params = Params; - this.CV = CV; - this.Ref = Ref; - this.Attrs = Attrs; - this.Ret = Ret; + _name = name; + _params = Params; + _cv = cv; + _ref = Ref; + _attrs = attrs; + _ret = ret; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - if (Ret != null) + if (_ret != null) { - Ret.PrintLeft(Writer); + _ret.PrintLeft(writer); - if (!Ret.HasRightPart()) + if (!_ret.HasRightPart()) { - Writer.Write(" "); + writer.Write(" "); } } - Name.Print(Writer); + _name.Print(writer); } @@ -42,35 +42,35 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast return true; } - public override void PrintRight(TextWriter Writer) + public override void PrintRight(TextWriter writer) { - Writer.Write("("); + writer.Write("("); - if (Params != null) + if (_params != null) { - Params.Print(Writer); + _params.Print(writer); } - Writer.Write(")"); + writer.Write(")"); - if (Ret != null) + if (_ret != null) { - Ret.PrintRight(Writer); + _ret.PrintRight(writer); } - if (CV != null) + if (_cv != null) { - CV.Print(Writer); + _cv.Print(writer); } - if (Ref != null) + if (_ref != null) { - Ref.Print(Writer); + _ref.Print(writer); } - if (Attrs != null) + if (_attrs != null) { - Attrs.Print(Writer); + _attrs.Print(writer); } } } diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/FoldExpression.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/FoldExpression.cs index e0152998..04f7053e 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/FoldExpression.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/FoldExpression.cs @@ -4,45 +4,45 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class FoldExpression : BaseNode { - private bool IsLeftFold; - private string OperatorName; - private BaseNode Expression; - private BaseNode Initializer; + private bool _isLeftFold; + private string _operatorName; + private BaseNode _expression; + private BaseNode _initializer; - public FoldExpression(bool IsLeftFold, string OperatorName, BaseNode Expression, BaseNode Initializer) : base(NodeType.FunctionParameter) + public FoldExpression(bool isLeftFold, string operatorName, BaseNode expression, BaseNode initializer) : base(NodeType.FunctionParameter) { - this.IsLeftFold = IsLeftFold; - this.OperatorName = OperatorName; - this.Expression = Expression; - this.Initializer = Initializer; + _isLeftFold = isLeftFold; + _operatorName = operatorName; + _expression = expression; + _initializer = initializer; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Writer.Write("("); + writer.Write("("); - if (IsLeftFold && Initializer != null) + if (_isLeftFold && _initializer != null) { - Initializer.Print(Writer); - Writer.Write(" "); - Writer.Write(OperatorName); - Writer.Write(" "); + _initializer.Print(writer); + writer.Write(" "); + writer.Write(_operatorName); + writer.Write(" "); } - Writer.Write(IsLeftFold ? "... " : " "); - Writer.Write(OperatorName); - Writer.Write(!IsLeftFold ? " ..." : " "); - Expression.Print(Writer); + writer.Write(_isLeftFold ? "... " : " "); + writer.Write(_operatorName); + writer.Write(!_isLeftFold ? " ..." : " "); + _expression.Print(writer); - if (!IsLeftFold && Initializer != null) + if (!_isLeftFold && _initializer != null) { - Initializer.Print(Writer); - Writer.Write(" "); - Writer.Write(OperatorName); - Writer.Write(" "); + _initializer.Print(writer); + writer.Write(" "); + writer.Write(_operatorName); + writer.Write(" "); } - Writer.Write(")"); + writer.Write(")"); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ForwardTemplateReference.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ForwardTemplateReference.cs index 6456e47b..1bbf6ef9 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ForwardTemplateReference.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ForwardTemplateReference.cs @@ -6,11 +6,11 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { // TODO: Compute inside the Demangler public BaseNode Reference; - private int Index; + private int _index; - public ForwardTemplateReference(int Index) : base(NodeType.ForwardTemplateReference) + public ForwardTemplateReference(int index) : base(NodeType.ForwardTemplateReference) { - this.Index = Index; + _index = index; } public override string GetName() @@ -18,14 +18,14 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast return Reference.GetName(); } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Reference.PrintLeft(Writer); + Reference.PrintLeft(writer); } - public override void PrintRight(TextWriter Writer) + public override void PrintRight(TextWriter writer) { - Reference.PrintRight(Writer); + Reference.PrintRight(writer); } public override bool HasRightPart() diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/FunctionParameter.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/FunctionParameter.cs index 5a1ca61d..5654a048 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/FunctionParameter.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/FunctionParameter.cs @@ -4,20 +4,20 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class FunctionParameter : BaseNode { - private string Number; + private string _number; - public FunctionParameter(string Number) : base(NodeType.FunctionParameter) + public FunctionParameter(string number) : base(NodeType.FunctionParameter) { - this.Number = Number; + _number = number; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Writer.Write("fp "); + writer.Write("fp "); - if (Number != null) + if (_number != null) { - Writer.Write(Number); + writer.Write(_number); } } } diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/FunctionType.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/FunctionType.cs index c727eab9..4ad0c9f5 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/FunctionType.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/FunctionType.cs @@ -4,47 +4,47 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class FunctionType : BaseNode { - private BaseNode ReturnType; - private BaseNode Params; - private BaseNode CVQualifier; - private SimpleReferenceType ReferenceQualifier; - private BaseNode ExceptionSpec; + private BaseNode _returnType; + private BaseNode _params; + private BaseNode _cvQualifier; + private SimpleReferenceType _referenceQualifier; + private BaseNode _exceptionSpec; - public FunctionType(BaseNode ReturnType, BaseNode Params, BaseNode CVQualifier, SimpleReferenceType ReferenceQualifier, BaseNode ExceptionSpec) : base(NodeType.FunctionType) + public FunctionType(BaseNode returnType, BaseNode Params, BaseNode cvQualifier, SimpleReferenceType referenceQualifier, BaseNode exceptionSpec) : base(NodeType.FunctionType) { - this.ReturnType = ReturnType; - this.Params = Params; - this.CVQualifier = CVQualifier; - this.ReferenceQualifier = ReferenceQualifier; - this.ExceptionSpec = ExceptionSpec; + _returnType = returnType; + _params = Params; + _cvQualifier = cvQualifier; + _referenceQualifier = referenceQualifier; + _exceptionSpec = exceptionSpec; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - ReturnType.PrintLeft(Writer); - Writer.Write(" "); + _returnType.PrintLeft(writer); + writer.Write(" "); } - public override void PrintRight(TextWriter Writer) + public override void PrintRight(TextWriter writer) { - Writer.Write("("); - Params.Print(Writer); - Writer.Write(")"); + writer.Write("("); + _params.Print(writer); + writer.Write(")"); - ReturnType.PrintRight(Writer); + _returnType.PrintRight(writer); - CVQualifier.Print(Writer); + _cvQualifier.Print(writer); - if (ReferenceQualifier.Qualifier != Reference.None) + if (_referenceQualifier.Qualifier != Reference.None) { - Writer.Write(" "); - ReferenceQualifier.PrintQualifier(Writer); + writer.Write(" "); + _referenceQualifier.PrintQualifier(writer); } - if (ExceptionSpec != null) + if (_exceptionSpec != null) { - Writer.Write(" "); - ExceptionSpec.Print(Writer); + writer.Write(" "); + _exceptionSpec.Print(writer); } } diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/GlobalQualifiedName.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/GlobalQualifiedName.cs index 2346c1bf..d3b6a558 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/GlobalQualifiedName.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/GlobalQualifiedName.cs @@ -4,12 +4,12 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class GlobalQualifiedName : ParentNode { - public GlobalQualifiedName(BaseNode Child) : base(NodeType.GlobalQualifiedName, Child) { } + public GlobalQualifiedName(BaseNode child) : base(NodeType.GlobalQualifiedName, child) { } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Writer.Write("::"); - Child.Print(Writer); + writer.Write("::"); + Child.Print(writer); } } } diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/InitListExpression.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/InitListExpression.cs index 2ed4daa4..7155dd60 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/InitListExpression.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/InitListExpression.cs @@ -5,25 +5,25 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class InitListExpression : BaseNode { - private BaseNode TypeNode; - private List Nodes; + private BaseNode _typeNode; + private List _nodes; - public InitListExpression(BaseNode TypeNode, List Nodes) : base(NodeType.InitListExpression) + public InitListExpression(BaseNode typeNode, List nodes) : base(NodeType.InitListExpression) { - this.TypeNode = TypeNode; - this.Nodes = Nodes; + _typeNode = typeNode; + _nodes = nodes; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - if (TypeNode != null) + if (_typeNode != null) { - TypeNode.Print(Writer); + _typeNode.Print(writer); } - Writer.Write("{"); - Writer.Write(string.Join(", ", Nodes.ToArray())); - Writer.Write("}"); + writer.Write("{"); + writer.Write(string.Join(", ", _nodes.ToArray())); + writer.Write("}"); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/IntegerCastExpression.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/IntegerCastExpression.cs index 984c9aef..ef07414d 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/IntegerCastExpression.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/IntegerCastExpression.cs @@ -4,19 +4,19 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class IntegerCastExpression : ParentNode { - private string Number; + private string _number; - public IntegerCastExpression(BaseNode Type, string Number) : base(NodeType.IntegerCastExpression, Type) + public IntegerCastExpression(BaseNode type, string number) : base(NodeType.IntegerCastExpression, type) { - this.Number = Number; + _number = number; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Writer.Write("("); - Child.Print(Writer); - Writer.Write(")"); - Writer.Write(Number); + writer.Write("("); + Child.Print(writer); + writer.Write(")"); + writer.Write(_number); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/IntegerLiteral.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/IntegerLiteral.cs index 215cf6dc..951faa55 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/IntegerLiteral.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/IntegerLiteral.cs @@ -4,37 +4,37 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class IntegerLiteral : BaseNode { - private string LitteralName; - private string LitteralValue; + private string _literalName; + private string _literalValue; - public IntegerLiteral(string LitteralName, string LitteralValue) : base(NodeType.IntegerLiteral) + public IntegerLiteral(string literalName, string literalValue) : base(NodeType.IntegerLiteral) { - this.LitteralValue = LitteralValue; - this.LitteralName = LitteralName; + _literalValue = literalValue; + _literalName = literalName; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - if (LitteralName.Length > 3) + if (_literalName.Length > 3) { - Writer.Write("("); - Writer.Write(LitteralName); - Writer.Write(")"); + writer.Write("("); + writer.Write(_literalName); + writer.Write(")"); } - if (LitteralValue[0] == 'n') + if (_literalValue[0] == 'n') { - Writer.Write("-"); - Writer.Write(LitteralValue.Substring(1)); + writer.Write("-"); + writer.Write(_literalValue.Substring(1)); } else { - Writer.Write(LitteralValue); + writer.Write(_literalValue); } - if (LitteralName.Length <= 3) + if (_literalName.Length <= 3) { - Writer.Write(LitteralName); + writer.Write(_literalName); } } } diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/LiteralOperator.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/LiteralOperator.cs index f9bd4a6e..f7e86c9e 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/LiteralOperator.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/LiteralOperator.cs @@ -4,13 +4,13 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class LiteralOperator : ParentNode { - public LiteralOperator(BaseNode Child) : base(NodeType.LiteralOperator, Child) { } + public LiteralOperator(BaseNode child) : base(NodeType.LiteralOperator, child) { } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Writer.Write("operator \""); - Child.PrintLeft(Writer); - Writer.Write("\""); + writer.Write("operator \""); + Child.PrintLeft(writer); + writer.Write("\""); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/LocalName.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/LocalName.cs index 44c21628..15d46b38 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/LocalName.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/LocalName.cs @@ -4,20 +4,20 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class LocalName : BaseNode { - private BaseNode Encoding; - private BaseNode Entity; + private BaseNode _encoding; + private BaseNode _entity; - public LocalName(BaseNode Encoding, BaseNode Entity) : base(NodeType.LocalName) + public LocalName(BaseNode encoding, BaseNode entity) : base(NodeType.LocalName) { - this.Encoding = Encoding; - this.Entity = Entity; + _encoding = encoding; + _entity = entity; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Encoding.Print(Writer); - Writer.Write("::"); - Entity.Print(Writer); + _encoding.Print(writer); + writer.Write("::"); + _entity.Print(writer); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/MemberExpression.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/MemberExpression.cs index dd3d02db..9b91f6f5 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/MemberExpression.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/MemberExpression.cs @@ -4,22 +4,22 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class MemberExpression : BaseNode { - private BaseNode LeftNode; - private string Kind; - private BaseNode RightNode; + private BaseNode _leftNode; + private string _kind; + private BaseNode _rightNode; - public MemberExpression(BaseNode LeftNode, string Kind, BaseNode RightNode) : base(NodeType.MemberExpression) + public MemberExpression(BaseNode leftNode, string kind, BaseNode rightNode) : base(NodeType.MemberExpression) { - this.LeftNode = LeftNode; - this.Kind = Kind; - this.RightNode = RightNode; + _leftNode = leftNode; + _kind = kind; + _rightNode = rightNode; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - LeftNode.Print(Writer); - Writer.Write(Kind); - RightNode.Print(Writer); + _leftNode.Print(writer); + writer.Write(_kind); + _rightNode.Print(writer); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/NameType.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/NameType.cs index 029440cb..f9f4cb20 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/NameType.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/NameType.cs @@ -4,26 +4,26 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class NameType : BaseNode { - private string NameValue; + private string _nameValue; - public NameType(string NameValue, NodeType Type) : base(Type) + public NameType(string nameValue, NodeType type) : base(type) { - this.NameValue = NameValue; + _nameValue = nameValue; } - public NameType(string NameValue) : base(NodeType.NameType) + public NameType(string nameValue) : base(NodeType.NameType) { - this.NameValue = NameValue; + _nameValue = nameValue; } public override string GetName() { - return NameValue; + return _nameValue; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Writer.Write(NameValue); + writer.Write(_nameValue); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/NameTypeWithTemplateArguments.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/NameTypeWithTemplateArguments.cs index e16bd150..ee725f36 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/NameTypeWithTemplateArguments.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/NameTypeWithTemplateArguments.cs @@ -4,24 +4,24 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class NameTypeWithTemplateArguments : BaseNode { - private BaseNode Prev; - private BaseNode TemplateArgument; + private BaseNode _prev; + private BaseNode _templateArgument; - public NameTypeWithTemplateArguments(BaseNode Prev, BaseNode TemplateArgument) : base(NodeType.NameTypeWithTemplateArguments) + public NameTypeWithTemplateArguments(BaseNode prev, BaseNode templateArgument) : base(NodeType.NameTypeWithTemplateArguments) { - this.Prev = Prev; - this.TemplateArgument = TemplateArgument; + _prev = prev; + _templateArgument = templateArgument; } public override string GetName() { - return Prev.GetName(); + return _prev.GetName(); } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Prev.Print(Writer); - TemplateArgument.Print(Writer); + _prev.Print(writer); + _templateArgument.Print(writer); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/NestedName.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/NestedName.cs index 0ec6d982..640c200c 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/NestedName.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/NestedName.cs @@ -4,23 +4,23 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class NestedName : ParentNode { - private BaseNode Name; + private BaseNode _name; - public NestedName(BaseNode Name, BaseNode Type) : base(NodeType.NestedName, Type) + public NestedName(BaseNode name, BaseNode type) : base(NodeType.NestedName, type) { - this.Name = Name; + _name = name; } public override string GetName() { - return Name.GetName(); + return _name.GetName(); } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Child.Print(Writer); - Writer.Write("::"); - Name.Print(Writer); + Child.Print(writer); + writer.Write("::"); + _name.Print(writer); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/NewExpression.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/NewExpression.cs index 5cc14ad9..ba4690af 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/NewExpression.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/NewExpression.cs @@ -4,51 +4,51 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class NewExpression : BaseNode { - private NodeArray Expressions; - private BaseNode TypeNode; - private NodeArray Initializers; + private NodeArray _expressions; + private BaseNode _typeNode; + private NodeArray _initializers; - private bool IsGlobal; - private bool IsArrayExpression; + private bool _isGlobal; + private bool _isArrayExpression; - public NewExpression(NodeArray Expressions, BaseNode TypeNode, NodeArray Initializers, bool IsGlobal, bool IsArrayExpression) : base(NodeType.NewExpression) + public NewExpression(NodeArray expressions, BaseNode typeNode, NodeArray initializers, bool isGlobal, bool isArrayExpression) : base(NodeType.NewExpression) { - this.Expressions = Expressions; - this.TypeNode = TypeNode; - this.Initializers = Initializers; + _expressions = expressions; + _typeNode = typeNode; + _initializers = initializers; - this.IsGlobal = IsGlobal; - this.IsArrayExpression = IsArrayExpression; + _isGlobal = isGlobal; + _isArrayExpression = isArrayExpression; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - if (IsGlobal) + if (_isGlobal) { - Writer.Write("::operator "); + writer.Write("::operator "); } - Writer.Write("new "); + writer.Write("new "); - if (IsArrayExpression) + if (_isArrayExpression) { - Writer.Write("[] "); + writer.Write("[] "); } - if (Expressions.Nodes.Count != 0) + if (_expressions.Nodes.Count != 0) { - Writer.Write("("); - Expressions.Print(Writer); - Writer.Write(")"); + writer.Write("("); + _expressions.Print(writer); + writer.Write(")"); } - TypeNode.Print(Writer); + _typeNode.Print(writer); - if (Initializers.Nodes.Count != 0) + if (_initializers.Nodes.Count != 0) { - Writer.Write("("); - Initializers.Print(Writer); - Writer.Write(")"); + writer.Write("("); + _initializers.Print(writer); + writer.Write(")"); } } } diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/NodeArray.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/NodeArray.cs index f7bfa194..1482dfc3 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/NodeArray.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/NodeArray.cs @@ -7,14 +7,14 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public List Nodes { get; protected set; } - public NodeArray(List Nodes) : base(NodeType.NodeArray) + public NodeArray(List nodes) : base(NodeType.NodeArray) { - this.Nodes = Nodes; + Nodes = nodes; } - public NodeArray(List Nodes, NodeType Type) : base(Type) + public NodeArray(List nodes, NodeType type) : base(type) { - this.Nodes = Nodes; + Nodes = nodes; } public override bool IsArray() @@ -22,9 +22,9 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast return true; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Writer.Write(string.Join(", ", Nodes.ToArray())); + writer.Write(string.Join(", ", Nodes.ToArray())); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/NoexceptSpec.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/NoexceptSpec.cs index 5bee9cfa..49044493 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/NoexceptSpec.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/NoexceptSpec.cs @@ -4,13 +4,13 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class NoexceptSpec : ParentNode { - public NoexceptSpec(BaseNode Child) : base(NodeType.NoexceptSpec, Child) { } + public NoexceptSpec(BaseNode child) : base(NodeType.NoexceptSpec, child) { } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Writer.Write("noexcept("); - Child.Print(Writer); - Writer.Write(")"); + writer.Write("noexcept("); + Child.Print(writer); + writer.Write(")"); } } } diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PackedTemplateParameter.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PackedTemplateParameter.cs index 66ad1122..4c820095 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PackedTemplateParameter.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PackedTemplateParameter.cs @@ -5,29 +5,29 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class PackedTemplateParameter : NodeArray { - public PackedTemplateParameter(List Nodes) : base(Nodes, NodeType.PackedTemplateParameter) { } + public PackedTemplateParameter(List nodes) : base(nodes, NodeType.PackedTemplateParameter) { } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - foreach (BaseNode Node in Nodes) + foreach (BaseNode node in Nodes) { - Node.PrintLeft(Writer); + node.PrintLeft(writer); } } - public override void PrintRight(TextWriter Writer) + public override void PrintRight(TextWriter writer) { - foreach (BaseNode Node in Nodes) + foreach (BaseNode node in Nodes) { - Node.PrintLeft(Writer); + node.PrintLeft(writer); } } public override bool HasRightPart() { - foreach (BaseNode Node in Nodes) + foreach (BaseNode node in Nodes) { - if (Node.HasRightPart()) + if (node.HasRightPart()) { return true; } diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PackedTemplateParameterExpansion.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PackedTemplateParameterExpansion.cs index ce9fa4a3..c3645044 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PackedTemplateParameterExpansion.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PackedTemplateParameterExpansion.cs @@ -4,20 +4,20 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class PackedTemplateParameterExpansion : ParentNode { - public PackedTemplateParameterExpansion(BaseNode Child) : base(NodeType.PackedTemplateParameterExpansion, Child) {} + public PackedTemplateParameterExpansion(BaseNode child) : base(NodeType.PackedTemplateParameterExpansion, child) {} - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { if (Child is PackedTemplateParameter) { if (((PackedTemplateParameter)Child).Nodes.Count != 0) { - Child.Print(Writer); + Child.Print(writer); } } else { - Writer.Write("..."); + writer.Write("..."); } } } diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ParentNode.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ParentNode.cs index f1c28347..786abced 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ParentNode.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ParentNode.cs @@ -4,9 +4,9 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public BaseNode Child { get; private set; } - public ParentNode(NodeType Type, BaseNode Child) : base(Type) + public ParentNode(NodeType type, BaseNode child) : base(type) { - this.Child = Child; + Child = child; } public override string GetName() diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PointerType.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PointerType.cs index a60776a2..b1a3ec42 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PointerType.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PointerType.cs @@ -4,42 +4,42 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class PointerType : BaseNode { - private BaseNode Child; + private BaseNode _child; - public PointerType(BaseNode Child) : base(NodeType.PointerType) + public PointerType(BaseNode child) : base(NodeType.PointerType) { - this.Child = Child; + _child = child; } public override bool HasRightPart() { - return Child.HasRightPart(); + return _child.HasRightPart(); } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Child.PrintLeft(Writer); - if (Child.IsArray()) + _child.PrintLeft(writer); + if (_child.IsArray()) { - Writer.Write(" "); + writer.Write(" "); } - if (Child.IsArray() || Child.HasFunctions()) + if (_child.IsArray() || _child.HasFunctions()) { - Writer.Write("("); + writer.Write("("); } - Writer.Write("*"); + writer.Write("*"); } - public override void PrintRight(TextWriter Writer) + public override void PrintRight(TextWriter writer) { - if (Child.IsArray() || Child.HasFunctions()) + if (_child.IsArray() || _child.HasFunctions()) { - Writer.Write(")"); + writer.Write(")"); } - Child.PrintRight(Writer); + _child.PrintRight(writer); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PostfixExpression.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PostfixExpression.cs index 021f2de8..ccaea3ba 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PostfixExpression.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PostfixExpression.cs @@ -4,19 +4,19 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class PostfixExpression : ParentNode { - private string Operator; + private string _operator; - public PostfixExpression(BaseNode Type, string Operator) : base(NodeType.PostfixExpression, Type) + public PostfixExpression(BaseNode type, string Operator) : base(NodeType.PostfixExpression, type) { - this.Operator = Operator; + _operator = Operator; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Writer.Write("("); - Child.Print(Writer); - Writer.Write(")"); - Writer.Write(Operator); + writer.Write("("); + Child.Print(writer); + writer.Write(")"); + writer.Write(_operator); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PostfixQualifiedType.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PostfixQualifiedType.cs index 465450d3..5024a8f9 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PostfixQualifiedType.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PostfixQualifiedType.cs @@ -4,17 +4,17 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class PostfixQualifiedType : ParentNode { - private string PostfixQualifier; + private string _postfixQualifier; - public PostfixQualifiedType(string PostfixQualifier, BaseNode Type) : base(NodeType.PostfixQualifiedType, Type) + public PostfixQualifiedType(string postfixQualifier, BaseNode type) : base(NodeType.PostfixQualifiedType, type) { - this.PostfixQualifier = PostfixQualifier; + _postfixQualifier = postfixQualifier; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Child.Print(Writer); - Writer.Write(PostfixQualifier); + Child.Print(writer); + writer.Write(_postfixQualifier); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PrefixExpression.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PrefixExpression.cs index 619d0538..9c3d4552 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PrefixExpression.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PrefixExpression.cs @@ -4,19 +4,19 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class PrefixExpression : ParentNode { - private string Prefix; + private string _prefix; - public PrefixExpression(string Prefix, BaseNode Child) : base(NodeType.PrefixExpression, Child) + public PrefixExpression(string prefix, BaseNode child) : base(NodeType.PrefixExpression, child) { - this.Prefix = Prefix; + _prefix = prefix; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Writer.Write(Prefix); - Writer.Write("("); - Child.Print(Writer); - Writer.Write(")"); + writer.Write(_prefix); + writer.Write("("); + Child.Print(writer); + writer.Write(")"); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/QualifiedName.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/QualifiedName.cs index ce356e16..2e18f564 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/QualifiedName.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/QualifiedName.cs @@ -4,20 +4,20 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class QualifiedName : BaseNode { - private BaseNode Qualifier; - private BaseNode Name; + private BaseNode _qualifier; + private BaseNode _name; - public QualifiedName(BaseNode Qualifier, BaseNode Name) : base(NodeType.QualifiedName) + public QualifiedName(BaseNode qualifier, BaseNode name) : base(NodeType.QualifiedName) { - this.Qualifier = Qualifier; - this.Name = Name; + _qualifier = qualifier; + _name = name; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Qualifier.Print(Writer); - Writer.Write("::"); - Name.Print(Writer); + _qualifier.Print(writer); + writer.Write("::"); + _name.Print(writer); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/Qualifier.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/Qualifier.cs index 3721b8de..cb6dd6bf 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/Qualifier.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/Qualifier.cs @@ -2,7 +2,7 @@ using System.IO; namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { - public enum CV + public enum Cv { None, Const, @@ -17,41 +17,41 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast LValue } - public class CVType : ParentNode + public class CvType : ParentNode { - public CV Qualifier; + public Cv Qualifier; - public CVType(CV Qualifier, BaseNode Child) : base(NodeType.CVQualifierType, Child) + public CvType(Cv qualifier, BaseNode child) : base(NodeType.CvQualifierType, child) { - this.Qualifier = Qualifier; + Qualifier = qualifier; } - public void PrintQualifier(TextWriter Writer) + public void PrintQualifier(TextWriter writer) { - if ((Qualifier & CV.Const) != 0) + if ((Qualifier & Cv.Const) != 0) { - Writer.Write(" const"); + writer.Write(" const"); } - if ((Qualifier & CV.Volatile) != 0) + if ((Qualifier & Cv.Volatile) != 0) { - Writer.Write(" volatile"); + writer.Write(" volatile"); } - if ((Qualifier & CV.Restricted) != 0) + if ((Qualifier & Cv.Restricted) != 0) { - Writer.Write(" restrict"); + writer.Write(" restrict"); } } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { if (Child != null) { - Child.PrintLeft(Writer); + Child.PrintLeft(writer); } - PrintQualifier(Writer); + PrintQualifier(writer); } public override bool HasRightPart() @@ -59,11 +59,11 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast return Child != null && Child.HasRightPart(); } - public override void PrintRight(TextWriter Writer) + public override void PrintRight(TextWriter writer) { if (Child != null) { - Child.PrintRight(Writer); + Child.PrintRight(writer); } } } @@ -72,36 +72,36 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public Reference Qualifier; - public SimpleReferenceType(Reference Qualifier, BaseNode Child) : base(NodeType.SimpleReferenceType, Child) + public SimpleReferenceType(Reference qualifier, BaseNode child) : base(NodeType.SimpleReferenceType, child) { - this.Qualifier = Qualifier; + Qualifier = qualifier; } - public void PrintQualifier(TextWriter Writer) + public void PrintQualifier(TextWriter writer) { if ((Qualifier & Reference.LValue) != 0) { - Writer.Write("&"); + writer.Write("&"); } if ((Qualifier & Reference.RValue) != 0) { - Writer.Write("&&"); + writer.Write("&&"); } } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { if (Child != null) { - Child.PrintLeft(Writer); + Child.PrintLeft(writer); } else if (Qualifier != Reference.None) { - Writer.Write(" "); + writer.Write(" "); } - PrintQualifier(Writer); + PrintQualifier(writer); } public override bool HasRightPart() @@ -109,11 +109,11 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast return Child != null && Child.HasRightPart(); } - public override void PrintRight(TextWriter Writer) + public override void PrintRight(TextWriter writer) { if (Child != null) { - Child.PrintRight(Writer); + Child.PrintRight(writer); } } } diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ReferenceType.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ReferenceType.cs index 602814af..a3214171 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ReferenceType.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ReferenceType.cs @@ -4,44 +4,44 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class ReferenceType : BaseNode { - private string Reference; - private BaseNode Child; + private string _reference; + private BaseNode _child; - public ReferenceType(string Reference, BaseNode Child) : base(NodeType.ReferenceType) + public ReferenceType(string reference, BaseNode child) : base(NodeType.ReferenceType) { - this.Reference = Reference; - this.Child = Child; + _reference = reference; + _child = child; } public override bool HasRightPart() { - return Child.HasRightPart(); + return _child.HasRightPart(); } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Child.PrintLeft(Writer); + _child.PrintLeft(writer); - if (Child.IsArray()) + if (_child.IsArray()) { - Writer.Write(" "); + writer.Write(" "); } - if (Child.IsArray() || Child.HasFunctions()) + if (_child.IsArray() || _child.HasFunctions()) { - Writer.Write("("); + writer.Write("("); } - Writer.Write(Reference); + writer.Write(_reference); } - public override void PrintRight(TextWriter Writer) + public override void PrintRight(TextWriter writer) { - if (Child.IsArray() || Child.HasFunctions()) + if (_child.IsArray() || _child.HasFunctions()) { - Writer.Write(")"); + writer.Write(")"); } - Child.PrintRight(Writer); + _child.PrintRight(writer); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/SpecialName.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/SpecialName.cs index 1a299af4..1447458b 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/SpecialName.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/SpecialName.cs @@ -4,17 +4,17 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class SpecialName : ParentNode { - private string SpecialValue; + private string _specialValue; - public SpecialName(string SpecialValue, BaseNode Type) : base(NodeType.SpecialName, Type) + public SpecialName(string specialValue, BaseNode type) : base(NodeType.SpecialName, type) { - this.SpecialValue = SpecialValue; + _specialValue = specialValue; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Writer.Write(SpecialValue); - Child.Print(Writer); + writer.Write(_specialValue); + Child.Print(writer); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/SpecialSubstitution.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/SpecialSubstitution.cs index f4e9a14a..8d45e180 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/SpecialSubstitution.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/SpecialSubstitution.cs @@ -11,14 +11,14 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast String, IStream, OStream, - IOStream, + IOStream } - private SpecialType SpecialSubstitutionKey; + private SpecialType _specialSubstitutionKey; - public SpecialSubstitution(SpecialType SpecialSubstitutionKey) : base(NodeType.SpecialSubstitution) + public SpecialSubstitution(SpecialType specialSubstitutionKey) : base(NodeType.SpecialSubstitution) { - this.SpecialSubstitutionKey = SpecialSubstitutionKey; + _specialSubstitutionKey = specialSubstitutionKey; } public void SetExtended() @@ -28,7 +28,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast public override string GetName() { - switch (SpecialSubstitutionKey) + switch (_specialSubstitutionKey) { case SpecialType.Allocator: return "allocator"; @@ -54,7 +54,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast private string GetExtendedName() { - switch (SpecialSubstitutionKey) + switch (_specialSubstitutionKey) { case SpecialType.Allocator: return "std::allocator"; @@ -73,16 +73,16 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast return null; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { if (Type == NodeType.ExpandedSpecialSubstitution) { - Writer.Write(GetExtendedName()); + writer.Write(GetExtendedName()); } else { - Writer.Write("std::"); - Writer.Write(GetName()); + writer.Write("std::"); + writer.Write(GetName()); } } } diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/StdQualifiedName.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/StdQualifiedName.cs index ed1b5994..c3a97d60 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/StdQualifiedName.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/StdQualifiedName.cs @@ -4,12 +4,12 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class StdQualifiedName : ParentNode { - public StdQualifiedName(BaseNode Child) : base(NodeType.StdQualifiedName, Child) { } + public StdQualifiedName(BaseNode child) : base(NodeType.StdQualifiedName, child) { } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Writer.Write("std::"); - Child.Print(Writer); + writer.Write("std::"); + Child.Print(writer); } } } diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/TemplateArguments.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/TemplateArguments.cs index d6efbd0f..aefd668d 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/TemplateArguments.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/TemplateArguments.cs @@ -5,22 +5,22 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class TemplateArguments : NodeArray { - public TemplateArguments(List Nodes) : base(Nodes, NodeType.TemplateArguments) { } + public TemplateArguments(List nodes) : base(nodes, NodeType.TemplateArguments) { } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { string Params = string.Join(", ", Nodes.ToArray()); - Writer.Write("<"); + writer.Write("<"); - Writer.Write(Params); + writer.Write(Params); if (Params.EndsWith(">")) { - Writer.Write(" "); + writer.Write(" "); } - Writer.Write(">"); + writer.Write(">"); } } } diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ThrowExpression.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ThrowExpression.cs index bb146617..2972a31c 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ThrowExpression.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ThrowExpression.cs @@ -4,17 +4,17 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public class ThrowExpression : BaseNode { - private BaseNode Expression; + private BaseNode _expression; - public ThrowExpression(BaseNode Expression) : base(NodeType.ThrowExpression) + public ThrowExpression(BaseNode expression) : base(NodeType.ThrowExpression) { - this.Expression = Expression; + _expression = expression; } - public override void PrintLeft(TextWriter Writer) + public override void PrintLeft(TextWriter writer) { - Writer.Write("throw "); - Expression.Print(Writer); + writer.Write("throw "); + _expression.Print(writer); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Demangler.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Demangler.cs index 164d5618..b654ba79 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Demangler.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Demangler.cs @@ -8,35 +8,35 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler { class Demangler { - private static readonly string BASE_36 = "0123456789abcdefghijklmnopqrstuvwxyz"; - private List SubstitutionList = new List(); - private List TemplateParamList = new List(); + private static readonly string Base36 = "0123456789abcdefghijklmnopqrstuvwxyz"; + private List _substitutionList = new List(); + private List _templateParamList = new List(); - private List ForwardTemplateReferenceList = new List(); + private List _forwardTemplateReferenceList = new List(); public string Mangled { get; private set; } - private int Position; - private int Length; + private int _position; + private int _length; - private bool CanForwardTemplateReference; - private bool CanParseTemplateArgs; + private bool _canForwardTemplateReference; + private bool _canParseTemplateArgs; - public Demangler(string Mangled) + public Demangler(string mangled) { - this.Mangled = Mangled; - Position = 0; - Length = Mangled.Length; - CanParseTemplateArgs = true; + Mangled = mangled; + _position = 0; + _length = mangled.Length; + _canParseTemplateArgs = true; } - private bool ConsumeIf(string ToConsume) + private bool ConsumeIf(string toConsume) { - string MangledPart = Mangled.Substring(Position); + string mangledPart = Mangled.Substring(_position); - if (MangledPart.StartsWith(ToConsume)) + if (mangledPart.StartsWith(toConsume)) { - Position += ToConsume.Length; + _position += toConsume.Length; return true; } @@ -44,31 +44,31 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler return false; } - private string PeekString(int Offset = 0, int Length = 1) + private string PeekString(int offset = 0, int length = 1) { - if (Position + Offset >= Length) + if (_position + offset >= length) { return null; } - return Mangled.Substring(Position + Offset, Length); + return Mangled.Substring(_position + offset, length); } - private char Peek(int Offset = 0) + private char Peek(int offset = 0) { - if (Position + Offset >= Length) + if (_position + offset >= _length) { return '\0'; } - return Mangled[Position + Offset]; + return Mangled[_position + offset]; } private char Consume() { - if (Position < Length) + if (_position < _length) { - return Mangled[Position++]; + return Mangled[_position++]; } return '\0'; @@ -76,45 +76,45 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler private int Count() { - return Length - Position; + return _length - _position; } - private static int FromBase36(string Encoded) + private static int FromBase36(string encoded) { - char[] ReversedEncoded = Encoded.ToLower().ToCharArray().Reverse().ToArray(); + char[] reversedEncoded = encoded.ToLower().ToCharArray().Reverse().ToArray(); - int Result = 0; + int result = 0; - for (int i = 0; i < ReversedEncoded.Length; i++) + for (int i = 0; i < reversedEncoded.Length; i++) { - int Value = BASE_36.IndexOf(ReversedEncoded[i]); - if (Value == -1) + int value = Base36.IndexOf(reversedEncoded[i]); + if (value == -1) { return -1; } - Result += Value * (int)Math.Pow(36, i); + result += value * (int)Math.Pow(36, i); } - return Result; + return result; } private int ParseSeqId() { - string Part = Mangled.Substring(Position); - int SeqIdLen = 0; + string part = Mangled.Substring(_position); + int seqIdLen = 0; - for (; SeqIdLen < Part.Length; SeqIdLen++) + for (; seqIdLen < part.Length; seqIdLen++) { - if (!char.IsLetterOrDigit(Part[SeqIdLen])) + if (!char.IsLetterOrDigit(part[seqIdLen])) { break; } } - Position += SeqIdLen; + _position += seqIdLen; - return FromBase36(Part.Substring(0, SeqIdLen)); + return FromBase36(part.Substring(0, seqIdLen)); } // ::= S _ @@ -133,28 +133,28 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler return null; } - char SubstitutionSecondChar = Peek(); - if (char.IsLower(SubstitutionSecondChar)) + char substitutionSecondChar = Peek(); + if (char.IsLower(substitutionSecondChar)) { - switch (SubstitutionSecondChar) + switch (substitutionSecondChar) { case 'a': - Position++; + _position++; return new SpecialSubstitution(SpecialSubstitution.SpecialType.Allocator); case 'b': - Position++; + _position++; return new SpecialSubstitution(SpecialSubstitution.SpecialType.BasicString); case 's': - Position++; + _position++; return new SpecialSubstitution(SpecialSubstitution.SpecialType.String); case 'i': - Position++; + _position++; return new SpecialSubstitution(SpecialSubstitution.SpecialType.IStream); case 'o': - Position++; + _position++; return new SpecialSubstitution(SpecialSubstitution.SpecialType.OStream); case 'd': - Position++; + _position++; return new SpecialSubstitution(SpecialSubstitution.SpecialType.IOStream); default: return null; @@ -164,29 +164,29 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler // ::= S_ if (ConsumeIf("_")) { - if (SubstitutionList.Count != 0) + if (_substitutionList.Count != 0) { - return SubstitutionList[0]; + return _substitutionList[0]; } return null; } // ::= S _ - int SeqId = ParseSeqId(); - if (SeqId < 0) + int seqId = ParseSeqId(); + if (seqId < 0) { return null; } - SeqId++; + seqId++; - if (!ConsumeIf("_") || SeqId >= SubstitutionList.Count) + if (!ConsumeIf("_") || seqId >= _substitutionList.Count) { return null; } - return SubstitutionList[SeqId]; + return _substitutionList[seqId]; } // NOTE: thoses data aren't used in the output @@ -217,33 +217,33 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler // ::= Te # dependent elaborated type specifier using 'enum' private BaseNode ParseClassEnumType() { - string ElaboratedType = null; + string elaboratedType = null; if (ConsumeIf("Ts")) { - ElaboratedType = "struct"; + elaboratedType = "struct"; } else if (ConsumeIf("Tu")) { - ElaboratedType = "union"; + elaboratedType = "union"; } else if (ConsumeIf("Te")) { - ElaboratedType = "enum"; + elaboratedType = "enum"; } - BaseNode Name = ParseName(); - if (Name == null) + BaseNode name = ParseName(); + if (name == null) { return null; } - if (ElaboratedType == null) + if (elaboratedType == null) { - return Name; + return name; } - return new ElaboratedType(ElaboratedType, Name); + return new ElaboratedType(elaboratedType, name); } // ::= [] [] [Dx] F [Y] [] E @@ -254,40 +254,40 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler // ::= Dw + E # dynamic exception specification with instantiation-dependent types private BaseNode ParseFunctionType() { - CV CVQualifiers = ParseCVQualifiers(); + Cv cvQualifiers = ParseCvQualifiers(); - BaseNode ExceptionSpec = null; + BaseNode exceptionSpec = null; if (ConsumeIf("Do")) { - ExceptionSpec = new NameType("noexcept"); + exceptionSpec = new NameType("noexcept"); } else if (ConsumeIf("DO")) { - BaseNode Expression = ParseExpression(); - if (Expression == null || !ConsumeIf("E")) + BaseNode expression = ParseExpression(); + if (expression == null || !ConsumeIf("E")) { return null; } - ExceptionSpec = new NoexceptSpec(Expression); + exceptionSpec = new NoexceptSpec(expression); } else if (ConsumeIf("Dw")) { - List Types = new List(); + List types = new List(); while (!ConsumeIf("E")) { - BaseNode Type = ParseType(); - if (Type == null) + BaseNode type = ParseType(); + if (type == null) { return null; } - Types.Add(Type); + types.Add(type); } - ExceptionSpec = new DynamicExceptionSpec(new NodeArray(Types)); + exceptionSpec = new DynamicExceptionSpec(new NodeArray(types)); } // We don't need the transaction @@ -301,13 +301,13 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler // extern "C" ConsumeIf("Y"); - BaseNode ReturnType = ParseType(); - if (ReturnType == null) + BaseNode returnType = ParseType(); + if (returnType == null) { return null; } - Reference ReferenceQualifier = Reference.None; + Reference referenceQualifier = Reference.None; List Params = new List(); while (true) @@ -324,25 +324,25 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler if (ConsumeIf("RE")) { - ReferenceQualifier = Reference.LValue; + referenceQualifier = Reference.LValue; break; } else if (ConsumeIf("OE")) { - ReferenceQualifier = Reference.RValue; + referenceQualifier = Reference.RValue; break; } - BaseNode Type = ParseType(); - if (Type == null) + BaseNode type = ParseType(); + if (type == null) { return null; } - Params.Add(Type); + Params.Add(type); } - return new FunctionType(ReturnType, new NodeArray(Params), new CVType(CVQualifiers, null), new SimpleReferenceType(ReferenceQualifier, null), ExceptionSpec); + return new FunctionType(returnType, new NodeArray(Params), new CvType(cvQualifiers, null), new SimpleReferenceType(referenceQualifier, null), exceptionSpec); } // ::= A _ @@ -354,48 +354,48 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler return null; } - BaseNode ElementType; + BaseNode elementType; if (char.IsDigit(Peek())) { - string Dimension = ParseNumber(); - if (Dimension.Length == 0 || !ConsumeIf("_")) + string dimension = ParseNumber(); + if (dimension.Length == 0 || !ConsumeIf("_")) { return null; } - ElementType = ParseType(); - if (ElementType == null) + elementType = ParseType(); + if (elementType == null) { return null; } - return new ArrayType(ElementType, Dimension); + return new ArrayType(elementType, dimension); } if (!ConsumeIf("_")) { - BaseNode DimensionExpression = ParseExpression(); - if (DimensionExpression == null || !ConsumeIf("_")) + BaseNode dimensionExpression = ParseExpression(); + if (dimensionExpression == null || !ConsumeIf("_")) { return null; } - ElementType = ParseType(); - if (ElementType == null) + elementType = ParseType(); + if (elementType == null) { return null; } - return new ArrayType(ElementType, DimensionExpression); + return new ArrayType(elementType, dimensionExpression); } - ElementType = ParseType(); - if (ElementType == null) + elementType = ParseType(); + if (elementType == null) { return null; } - return new ArrayType(ElementType); + return new ArrayType(elementType); } // ::= @@ -413,295 +413,295 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler // ::= C # complex pair (C99) // ::= G # imaginary (C99) // ::= # See Compression below - private BaseNode ParseType(NameParserContext Context = null) + private BaseNode ParseType(NameParserContext context = null) { // Temporary context - if (Context == null) + if (context == null) { - Context = new NameParserContext(); + context = new NameParserContext(); } - BaseNode Result = null; + BaseNode result = null; switch (Peek()) { case 'r': case 'V': case 'K': - int TypePos = 0; + int typePos = 0; - if (Peek(TypePos) == 'r') + if (Peek(typePos) == 'r') { - TypePos++; + typePos++; } - if (Peek(TypePos) == 'V') + if (Peek(typePos) == 'V') { - TypePos++; + typePos++; } - if (Peek(TypePos) == 'K') + if (Peek(typePos) == 'K') { - TypePos++; + typePos++; } - if (Peek(TypePos) == 'F' || (Peek(TypePos) == 'D' && (Peek(TypePos + 1) == 'o' || Peek(TypePos + 1) == 'O' || Peek(TypePos + 1) == 'w' || Peek(TypePos + 1) == 'x'))) + if (Peek(typePos) == 'F' || (Peek(typePos) == 'D' && (Peek(typePos + 1) == 'o' || Peek(typePos + 1) == 'O' || Peek(typePos + 1) == 'w' || Peek(typePos + 1) == 'x'))) { - Result = ParseFunctionType(); + result = ParseFunctionType(); break; } - CV CV = ParseCVQualifiers(); + Cv cv = ParseCvQualifiers(); - Result = ParseType(Context); + result = ParseType(context); - if (Result == null) + if (result == null) { return null; } - Result = new CVType(CV, Result); + result = new CvType(cv, result); break; case 'U': // TODO: return null; case 'v': - Position++; + _position++; return new NameType("void"); case 'w': - Position++; + _position++; return new NameType("wchar_t"); case 'b': - Position++; + _position++; return new NameType("bool"); case 'c': - Position++; + _position++; return new NameType("char"); case 'a': - Position++; + _position++; return new NameType("signed char"); case 'h': - Position++; + _position++; return new NameType("unsigned char"); case 's': - Position++; + _position++; return new NameType("short"); case 't': - Position++; + _position++; return new NameType("unsigned short"); case 'i': - Position++; + _position++; return new NameType("int"); case 'j': - Position++; + _position++; return new NameType("unsigned int"); case 'l': - Position++; + _position++; return new NameType("long"); case 'm': - Position++; + _position++; return new NameType("unsigned long"); case 'x': - Position++; + _position++; return new NameType("long long"); case 'y': - Position++; + _position++; return new NameType("unsigned long long"); case 'n': - Position++; + _position++; return new NameType("__int128"); case 'o': - Position++; + _position++; return new NameType("unsigned __int128"); case 'f': - Position++; + _position++; return new NameType("float"); case 'd': - Position++; + _position++; return new NameType("double"); case 'e': - Position++; + _position++; return new NameType("long double"); case 'g': - Position++; + _position++; return new NameType("__float128"); case 'z': - Position++; + _position++; return new NameType("..."); case 'u': - Position++; + _position++; return ParseSourceName(); case 'D': switch (Peek(1)) { case 'd': - Position += 2; + _position += 2; return new NameType("decimal64"); case 'e': - Position += 2; + _position += 2; return new NameType("decimal128"); case 'f': - Position += 2; + _position += 2; return new NameType("decimal32"); case 'h': - Position += 2; + _position += 2; // FIXME: GNU c++flit returns this but that is not what is supposed to be returned. return new NameType("half"); //return new NameType("decimal16"); case 'i': - Position += 2; + _position += 2; return new NameType("char32_t"); case 's': - Position += 2; + _position += 2; return new NameType("char16_t"); case 'a': - Position += 2; + _position += 2; return new NameType("decltype(auto)"); case 'n': - Position += 2; + _position += 2; // FIXME: GNU c++flit returns this but that is not what is supposed to be returned. return new NameType("decltype(nullptr)"); //return new NameType("std::nullptr_t"); case 't': case 'T': - Position += 2; - Result = ParseDecltype(); + _position += 2; + result = ParseDecltype(); break; case 'o': case 'O': case 'w': case 'x': - Result = ParseFunctionType(); + result = ParseFunctionType(); break; default: return null; } break; case 'F': - Result = ParseFunctionType(); + result = ParseFunctionType(); break; case 'A': return ParseArrayType(); case 'M': // TODO: - Position++; + _position++; return null; case 'T': // might just be a class enum type if (Peek(1) == 's' || Peek(1) == 'u' || Peek(1) == 'e') { - Result = ParseClassEnumType(); + result = ParseClassEnumType(); break; } - Result = ParseTemplateParam(); - if (Result == null) + result = ParseTemplateParam(); + if (result == null) { return null; } - if (CanParseTemplateArgs && Peek() == 'I') + if (_canParseTemplateArgs && Peek() == 'I') { - BaseNode TemplateArguments = ParseTemplateArguments(); - if (TemplateArguments == null) + BaseNode templateArguments = ParseTemplateArguments(); + if (templateArguments == null) { return null; } - Result = new NameTypeWithTemplateArguments(Result, TemplateArguments); + result = new NameTypeWithTemplateArguments(result, templateArguments); } break; case 'P': - Position++; - Result = ParseType(Context); + _position++; + result = ParseType(context); - if (Result == null) + if (result == null) { return null; } - Result = new PointerType(Result); + result = new PointerType(result); break; case 'R': - Position++; - Result = ParseType(Context); + _position++; + result = ParseType(context); - if (Result == null) + if (result == null) { return null; } - Result = new ReferenceType("&", Result); + result = new ReferenceType("&", result); break; case 'O': - Position++; - Result = ParseType(Context); + _position++; + result = ParseType(context); - if (Result == null) + if (result == null) { return null; } - Result = new ReferenceType("&&", Result); + result = new ReferenceType("&&", result); break; case 'C': - Position++; - Result = ParseType(Context); + _position++; + result = ParseType(context); - if (Result == null) + if (result == null) { return null; } - Result = new PostfixQualifiedType(" complex", Result); + result = new PostfixQualifiedType(" complex", result); break; case 'G': - Position++; - Result = ParseType(Context); + _position++; + result = ParseType(context); - if (Result == null) + if (result == null) { return null; } - Result = new PostfixQualifiedType(" imaginary", Result); + result = new PostfixQualifiedType(" imaginary", result); break; case 'S': if (Peek(1) != 't') { - BaseNode Substitution = ParseSubstitution(); - if (Substitution == null) + BaseNode substitution = ParseSubstitution(); + if (substitution == null) { return null; } - if (CanParseTemplateArgs && Peek() == 'I') + if (_canParseTemplateArgs && Peek() == 'I') { - BaseNode TemplateArgument = ParseTemplateArgument(); - if (TemplateArgument == null) + BaseNode templateArgument = ParseTemplateArgument(); + if (templateArgument == null) { return null; } - Result = new NameTypeWithTemplateArguments(Substitution, TemplateArgument); + result = new NameTypeWithTemplateArguments(substitution, templateArgument); break; } - return Substitution; + return substitution; } else { - Result = ParseClassEnumType(); + result = ParseClassEnumType(); break; } default: - Result = ParseClassEnumType(); + result = ParseClassEnumType(); break; } - if (Result != null) + if (result != null) { - SubstitutionList.Add(Result); + _substitutionList.Add(result); } - return Result; + return result; } // ::= TV # virtual table @@ -714,155 +714,155 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler // ::= T // # base is the nominal target function of thunk // ::= GV # Guard variable for one-time initialization - private BaseNode ParseSpecialName(NameParserContext Context = null) + private BaseNode ParseSpecialName(NameParserContext context = null) { if (Peek() != 'T') { if (ConsumeIf("GV")) { - BaseNode Name = ParseName(); - if (Name == null) + BaseNode name = ParseName(); + if (name == null) { return null; } - return new SpecialName("guard variable for ", Name); + return new SpecialName("guard variable for ", name); } return null; } - BaseNode Node; + BaseNode node; switch (Peek(1)) { // ::= TV # virtual table case 'V': - Position += 2; - Node = ParseType(Context); - if (Node == null) + _position += 2; + node = ParseType(context); + if (node == null) { return null; } - return new SpecialName("vtable for ", Node); + return new SpecialName("vtable for ", node); // ::= TT # VTT structure (construction vtable index) case 'T': - Position += 2; - Node = ParseType(Context); - if (Node == null) + _position += 2; + node = ParseType(context); + if (node == null) { return null; } - return new SpecialName("VTT for ", Node); + return new SpecialName("VTT for ", node); // ::= TI # typeinfo structure case 'I': - Position += 2; - Node = ParseType(Context); - if (Node == null) + _position += 2; + node = ParseType(context); + if (node == null) { return null; } - return new SpecialName("typeinfo for ", Node); + return new SpecialName("typeinfo for ", node); // ::= TS # typeinfo name (null-terminated byte string) case 'S': - Position += 2; - Node = ParseType(Context); - if (Node == null) + _position += 2; + node = ParseType(context); + if (node == null) { return null; } - return new SpecialName("typeinfo name for ", Node); + return new SpecialName("typeinfo name for ", node); // ::= Tc case 'c': - Position += 2; + _position += 2; if (ParseCallOffset() || ParseCallOffset()) { return null; } - Node = ParseEncoding(); - if (Node == null) + node = ParseEncoding(); + if (node == null) { return null; } - return new SpecialName("covariant return thunk to ", Node); + return new SpecialName("covariant return thunk to ", node); // extension ::= TC _ case 'C': - Position += 2; - BaseNode FirstType = ParseType(); - if (FirstType == null || ParseNumber(true).Length == 0 || !ConsumeIf("_")) + _position += 2; + BaseNode firstType = ParseType(); + if (firstType == null || ParseNumber(true).Length == 0 || !ConsumeIf("_")) { return null; } - BaseNode SecondType = ParseType(); + BaseNode secondType = ParseType(); - return new CtorVtableSpecialName(SecondType, FirstType); + return new CtorVtableSpecialName(secondType, firstType); // ::= TH # Thread-local initialization case 'H': - Position += 2; - Node = ParseName(); - if (Node == null) + _position += 2; + node = ParseName(); + if (node == null) { return null; } - return new SpecialName("thread-local initialization routine for ", Node); + return new SpecialName("thread-local initialization routine for ", node); // ::= TW # Thread-local wrapper case 'W': - Position += 2; - Node = ParseName(); - if (Node == null) + _position += 2; + node = ParseName(); + if (node == null) { return null; } - return new SpecialName("thread-local wrapper routine for ", Node); + return new SpecialName("thread-local wrapper routine for ", node); default: - Position++; - bool IsVirtual = Peek() == 'v'; + _position++; + bool isVirtual = Peek() == 'v'; if (ParseCallOffset()) { return null; } - Node = ParseEncoding(); - if (Node == null) + node = ParseEncoding(); + if (node == null) { return null; } - if (IsVirtual) + if (isVirtual) { - return new SpecialName("virtual thunk to ", Node); + return new SpecialName("virtual thunk to ", node); } - return new SpecialName("non-virtual thunk to ", Node); + return new SpecialName("non-virtual thunk to ", node); } } // ::= [r] [V] [K] # restrict (C99), volatile, const - private CV ParseCVQualifiers() + private Cv ParseCvQualifiers() { - CV Qualifiers = CV.None; + Cv qualifiers = Cv.None; if (ConsumeIf("r")) { - Qualifiers |= CV.Restricted; + qualifiers |= Cv.Restricted; } if (ConsumeIf("V")) { - Qualifiers |= CV.Volatile; + qualifiers |= Cv.Volatile; } if (ConsumeIf("K")) { - Qualifiers |= CV.Const; + qualifiers |= Cv.Const; } - return Qualifiers; + return qualifiers; } @@ -870,102 +870,102 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler // ::= O # && ref-qualifier private SimpleReferenceType ParseRefQualifiers() { - Reference Result = Reference.None; + Reference result = Reference.None; if (ConsumeIf("O")) { - Result = Reference.RValue; + result = Reference.RValue; } else if (ConsumeIf("R")) { - Result = Reference.LValue; + result = Reference.LValue; } - return new SimpleReferenceType(Result, null); + return new SimpleReferenceType(result, null); } - private BaseNode CreateNameNode(BaseNode Prev, BaseNode Name, NameParserContext Context) + private BaseNode CreateNameNode(BaseNode prev, BaseNode name, NameParserContext context) { - BaseNode Result = Name; - if (Prev != null) + BaseNode result = name; + if (prev != null) { - Result = new NestedName(Name, Prev); + result = new NestedName(name, prev); } - if (Context != null) + if (context != null) { - Context.FinishWithTemplateArguments = false; + context.FinishWithTemplateArguments = false; } - return Result; + return result; } private int ParsePositiveNumber() { - string Part = Mangled.Substring(Position); - int NumberLength = 0; + string part = Mangled.Substring(_position); + int numberLength = 0; - for (; NumberLength < Part.Length; NumberLength++) + for (; numberLength < part.Length; numberLength++) { - if (!char.IsDigit(Part[NumberLength])) + if (!char.IsDigit(part[numberLength])) { break; } } - Position += NumberLength; + _position += numberLength; - if (NumberLength == 0) + if (numberLength == 0) { return -1; } - return int.Parse(Part.Substring(0, NumberLength)); + return int.Parse(part.Substring(0, numberLength)); } - private string ParseNumber(bool IsSigned = false) + private string ParseNumber(bool isSigned = false) { - if (IsSigned) + if (isSigned) { ConsumeIf("n"); } - if (Count() == 0 || !char.IsDigit(Mangled[Position])) + if (Count() == 0 || !char.IsDigit(Mangled[_position])) { return null; } - string Part = Mangled.Substring(Position); - int NumberLength = 0; + string part = Mangled.Substring(_position); + int numberLength = 0; - for (; NumberLength < Part.Length; NumberLength++) + for (; numberLength < part.Length; numberLength++) { - if (!char.IsDigit(Part[NumberLength])) + if (!char.IsDigit(part[numberLength])) { break; } } - Position += NumberLength; + _position += numberLength; - return Part.Substring(0, NumberLength); + return part.Substring(0, numberLength); } // ::= private BaseNode ParseSourceName() { - int Length = ParsePositiveNumber(); - if (Count() < Length || Length <= 0) + int length = ParsePositiveNumber(); + if (Count() < length || length <= 0) { return null; } - string Name = Mangled.Substring(Position, Length); - Position += Length; - if (Name.StartsWith("_GLOBAL__N")) + string name = Mangled.Substring(_position, length); + _position += length; + if (name.StartsWith("_GLOBAL__N")) { return new NameType("(anonymous namespace)"); } - return new NameType(Name); + return new NameType(name); } // ::= nw # new @@ -1019,7 +1019,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler // ::= cv # (cast) (TODO) // ::= li # operator "" // ::= v # vendor extended operator (TODO) - private BaseNode ParseOperatorName(NameParserContext Context) + private BaseNode ParseOperatorName(NameParserContext context) { switch (Peek()) { @@ -1027,17 +1027,17 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler switch (Peek(1)) { case 'a': - Position += 2; + _position += 2; return new NameType("operator&&"); case 'd': case 'n': - Position += 2; + _position += 2; return new NameType("operator&"); case 'N': - Position += 2; + _position += 2; return new NameType("operator&="); case 'S': - Position += 2; + _position += 2; return new NameType("operator="); default: return null; @@ -1046,39 +1046,39 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler switch (Peek(1)) { case 'l': - Position += 2; + _position += 2; return new NameType("operator()"); case 'm': - Position += 2; + _position += 2; return new NameType("operator,"); case 'o': - Position += 2; + _position += 2; return new NameType("operator~"); case 'v': - Position += 2; + _position += 2; - bool CanParseTemplateArgsBackup = CanParseTemplateArgs; - bool CanForwardTemplateReferenceBackup = CanForwardTemplateReference; + bool canParseTemplateArgsBackup = _canParseTemplateArgs; + bool canForwardTemplateReferenceBackup = _canForwardTemplateReference; - CanParseTemplateArgs = false; - CanForwardTemplateReference = CanForwardTemplateReferenceBackup || Context != null; + _canParseTemplateArgs = false; + _canForwardTemplateReference = canForwardTemplateReferenceBackup || context != null; - BaseNode Type = ParseType(); + BaseNode type = ParseType(); - CanParseTemplateArgs = CanParseTemplateArgsBackup; - CanForwardTemplateReference = CanForwardTemplateReferenceBackup; + _canParseTemplateArgs = canParseTemplateArgsBackup; + _canForwardTemplateReference = canForwardTemplateReferenceBackup; - if (Type == null) + if (type == null) { return null; } - if (Context != null) + if (context != null) { - Context.CtorDtorConversion = true; + context.CtorDtorConversion = true; } - return new ConversionOperatorType(Type); + return new ConversionOperatorType(type); default: return null; } @@ -1086,19 +1086,19 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler switch (Peek(1)) { case 'a': - Position += 2; + _position += 2; return new NameType("operator delete[]"); case 'e': - Position += 2; + _position += 2; return new NameType("operator*"); case 'l': - Position += 2; + _position += 2; return new NameType("operator delete"); case 'v': - Position += 2; + _position += 2; return new NameType("operator/"); case 'V': - Position += 2; + _position += 2; return new NameType("operator/="); default: return null; @@ -1107,13 +1107,13 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler switch (Peek(1)) { case 'o': - Position += 2; + _position += 2; return new NameType("operator^"); case 'O': - Position += 2; + _position += 2; return new NameType("operator^="); case 'q': - Position += 2; + _position += 2; return new NameType("operator=="); default: return null; @@ -1122,10 +1122,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler switch (Peek(1)) { case 'e': - Position += 2; + _position += 2; return new NameType("operator>="); case 't': - Position += 2; + _position += 2; return new NameType("operator>"); default: return null; @@ -1133,7 +1133,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler case 'i': if (Peek(1) == 'x') { - Position += 2; + _position += 2; return new NameType("operator[]"); } return null; @@ -1141,25 +1141,25 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler switch (Peek(1)) { case 'e': - Position += 2; + _position += 2; return new NameType("operator<="); case 'i': - Position += 2; - BaseNode SourceName = ParseSourceName(); - if (SourceName == null) + _position += 2; + BaseNode sourceName = ParseSourceName(); + if (sourceName == null) { return null; } - return new LiteralOperator(SourceName); + return new LiteralOperator(sourceName); case 's': - Position += 2; + _position += 2; return new NameType("operator<<"); case 'S': - Position += 2; + _position += 2; return new NameType("operator<<="); case 't': - Position += 2; + _position += 2; return new NameType("operator<"); default: return null; @@ -1168,19 +1168,19 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler switch (Peek(1)) { case 'i': - Position += 2; + _position += 2; return new NameType("operator-"); case 'I': - Position += 2; + _position += 2; return new NameType("operator-="); case 'l': - Position += 2; + _position += 2; return new NameType("operator*"); case 'L': - Position += 2; + _position += 2; return new NameType("operator*="); case 'm': - Position += 2; + _position += 2; return new NameType("operator--"); default: return null; @@ -1189,19 +1189,19 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler switch (Peek(1)) { case 'a': - Position += 2; + _position += 2; return new NameType("operator new[]"); case 'e': - Position += 2; + _position += 2; return new NameType("operator!="); case 'g': - Position += 2; + _position += 2; return new NameType("operator-"); case 't': - Position += 2; + _position += 2; return new NameType("operator!"); case 'w': - Position += 2; + _position += 2; return new NameType("operator new"); default: return null; @@ -1210,13 +1210,13 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler switch (Peek(1)) { case 'o': - Position += 2; + _position += 2; return new NameType("operator||"); case 'r': - Position += 2; + _position += 2; return new NameType("operator|"); case 'R': - Position += 2; + _position += 2; return new NameType("operator|="); default: return null; @@ -1225,20 +1225,20 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler switch (Peek(1)) { case 'm': - Position += 2; + _position += 2; return new NameType("operator->*"); case 's': case 'l': - Position += 2; + _position += 2; return new NameType("operator+"); case 'L': - Position += 2; + _position += 2; return new NameType("operator+="); case 'p': - Position += 2; + _position += 2; return new NameType("operator++"); case 't': - Position += 2; + _position += 2; return new NameType("operator->"); default: return null; @@ -1246,7 +1246,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler case 'q': if (Peek(1) == 'u') { - Position += 2; + _position += 2; return new NameType("operator?"); } return null; @@ -1254,16 +1254,16 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler switch (Peek(1)) { case 'm': - Position += 2; + _position += 2; return new NameType("operator%"); case 'M': - Position += 2; + _position += 2; return new NameType("operator%="); case 's': - Position += 2; + _position += 2; return new NameType("operator>>"); case 'S': - Position += 2; + _position += 2; return new NameType("operator>>="); default: return null; @@ -1271,7 +1271,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler case 's': if (Peek(1) == 's') { - Position += 2; + _position += 2; return new NameType("operator<=>"); } return null; @@ -1288,18 +1288,18 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler // ::= // ::= (TODO) // ::= DC + E # structured binding declaration (TODO) - private BaseNode ParseUnqualifiedName(NameParserContext Context) + private BaseNode ParseUnqualifiedName(NameParserContext context) { - BaseNode Result = null; - char C = Peek(); - if (C == 'U') + BaseNode result = null; + char c = Peek(); + if (c == 'U') { // TODO: Unnamed Type Name // throw new Exception("Unnamed Type Name not implemented"); } - else if (char.IsDigit(C)) + else if (char.IsDigit(c)) { - Result = ParseSourceName(); + result = ParseSourceName(); } else if (ConsumeIf("DC")) { @@ -1308,15 +1308,15 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler } else { - Result = ParseOperatorName(Context); + result = ParseOperatorName(context); } - if (Result != null) + if (result != null) { // TODO: ABI Tags //throw new Exception("ABI Tags not implemented"); } - return Result; + return result; } // ::= C1 # complete object constructor @@ -1325,54 +1325,54 @@ 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 BaseNode ParseCtorDtorName(NameParserContext context, BaseNode prev) { - if (Prev.Type == NodeType.SpecialSubstitution && Prev is SpecialSubstitution) + if (prev.Type == NodeType.SpecialSubstitution && prev is SpecialSubstitution) { - ((SpecialSubstitution)Prev).SetExtended(); + ((SpecialSubstitution)prev).SetExtended(); } if (ConsumeIf("C")) { - bool IsInherited = ConsumeIf("I"); + bool isInherited = ConsumeIf("I"); - char CtorDtorType = Peek(); - if (CtorDtorType != '1' && CtorDtorType != '2' && CtorDtorType != '3') + char ctorDtorType = Peek(); + if (ctorDtorType != '1' && ctorDtorType != '2' && ctorDtorType != '3') { return null; } - Position++; + _position++; - if (Context != null) + if (context != null) { - Context.CtorDtorConversion = true; + context.CtorDtorConversion = true; } - if (IsInherited && ParseName(Context) == null) + if (isInherited && ParseName(context) == null) { return null; } - return new CtorDtorNameType(Prev, false); + return new CtorDtorNameType(prev, false); } if (ConsumeIf("D")) { - char C = Peek(); - if (C != '0' && C != '1' && C != '2') + char c = Peek(); + if (c != '0' && c != '1' && c != '2') { return null; } - Position++; + _position++; - if (Context != null) + if (context != null) { - Context.CtorDtorConversion = true; + context.CtorDtorConversion = true; } - return new CtorDtorNameType(Prev, true); + return new CtorDtorNameType(prev, true); } return null; @@ -1387,7 +1387,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler if (ConsumeIf("fp")) { // ignored - ParseCVQualifiers(); + ParseCvQualifiers(); if (!ConsumeIf("_")) { @@ -1398,8 +1398,8 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler } else if (ConsumeIf("fL")) { - string L1Number = ParseNumber(); - if (L1Number == null || L1Number.Length == 0) + string l1Number = ParseNumber(); + if (l1Number == null || l1Number.Length == 0) { return null; } @@ -1410,7 +1410,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler } // ignored - ParseCVQualifiers(); + ParseCvQualifiers(); if (!ConsumeIf("_")) { @@ -1434,145 +1434,145 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler return null; } - char FoldKind = Peek(); - bool HasInitializer = FoldKind == 'L' || FoldKind == 'R'; - bool IsLeftFold = FoldKind == 'l' || FoldKind == 'L'; + char foldKind = Peek(); + bool hasInitializer = foldKind == 'L' || foldKind == 'R'; + bool isLeftFold = foldKind == 'l' || foldKind == 'L'; - if (!IsLeftFold && !(FoldKind == 'r' || FoldKind == 'R')) + if (!isLeftFold && !(foldKind == 'r' || foldKind == 'R')) { return null; } - Position++; + _position++; - string OperatorName = null; + string operatorName = null; switch (PeekString(0, 2)) { case "aa": - OperatorName = "&&"; + operatorName = "&&"; break; case "an": - OperatorName = "&"; + operatorName = "&"; break; case "aN": - OperatorName = "&="; + operatorName = "&="; break; case "aS": - OperatorName = "="; + operatorName = "="; break; case "cm": - OperatorName = ","; + operatorName = ","; break; case "ds": - OperatorName = ".*"; + operatorName = ".*"; break; case "dv": - OperatorName = "/"; + operatorName = "/"; break; case "dV": - OperatorName = "/="; + operatorName = "/="; break; case "eo": - OperatorName = "^"; + operatorName = "^"; break; case "eO": - OperatorName = "^="; + operatorName = "^="; break; case "eq": - OperatorName = "=="; + operatorName = "=="; break; case "ge": - OperatorName = ">="; + operatorName = ">="; break; case "gt": - OperatorName = ">"; + operatorName = ">"; break; case "le": - OperatorName = "<="; + operatorName = "<="; break; case "ls": - OperatorName = "<<"; + operatorName = "<<"; break; case "lS": - OperatorName = "<<="; + operatorName = "<<="; break; case "lt": - OperatorName = "<"; + operatorName = "<"; break; case "mi": - OperatorName = "-"; + operatorName = "-"; break; case "mI": - OperatorName = "-="; + operatorName = "-="; break; case "ml": - OperatorName = "*"; + operatorName = "*"; break; case "mL": - OperatorName = "*="; + operatorName = "*="; break; case "ne": - OperatorName = "!="; + operatorName = "!="; break; case "oo": - OperatorName = "||"; + operatorName = "||"; break; case "or": - OperatorName = "|"; + operatorName = "|"; break; case "oR": - OperatorName = "|="; + operatorName = "|="; break; case "pl": - OperatorName = "+"; + operatorName = "+"; break; case "pL": - OperatorName = "+="; + operatorName = "+="; break; case "rm": - OperatorName = "%"; + operatorName = "%"; break; case "rM": - OperatorName = "%="; + operatorName = "%="; break; case "rs": - OperatorName = ">>"; + operatorName = ">>"; break; case "rS": - OperatorName = ">>="; + operatorName = ">>="; break; default: return null; } - Position += 2; + _position += 2; - BaseNode Expression = ParseExpression(); - if (Expression == null) + BaseNode expression = ParseExpression(); + if (expression == null) { return null; } - BaseNode Initializer = null; + BaseNode initializer = null; - if (HasInitializer) + if (hasInitializer) { - Initializer = ParseExpression(); - if (Initializer == null) + initializer = ParseExpression(); + if (initializer == null) { return null; } } - if (IsLeftFold && Initializer != null) + if (isLeftFold && initializer != null) { - BaseNode Temp = Expression; - Expression = Initializer; - Initializer = Temp; + BaseNode temp = expression; + expression = initializer; + initializer = temp; } - return new FoldExpression(IsLeftFold, OperatorName, new PackedTemplateParameterExpansion(Expression), Initializer); + return new FoldExpression(isLeftFold, operatorName, new PackedTemplateParameterExpansion(expression), initializer); } @@ -1585,70 +1585,70 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler return null; } - bool CanParseTemplateArgsBackup = CanParseTemplateArgs; - CanParseTemplateArgs = false; - BaseNode Type = ParseType(); - CanParseTemplateArgs = CanParseTemplateArgsBackup; + bool canParseTemplateArgsBackup = _canParseTemplateArgs; + _canParseTemplateArgs = false; + BaseNode type = ParseType(); + _canParseTemplateArgs = canParseTemplateArgsBackup; - if (Type == null) + if (type == null) { return null; } - List Expressions = new List(); + List expressions = new List(); if (ConsumeIf("_")) { while (!ConsumeIf("E")) { - BaseNode Expression = ParseExpression(); - if (Expression == null) + BaseNode expression = ParseExpression(); + if (expression == null) { return null; } - Expressions.Add(Expression); + expressions.Add(expression); } } else { - BaseNode Expression = ParseExpression(); - if (Expression == null) + BaseNode expression = ParseExpression(); + if (expression == null) { return null; } - Expressions.Add(Expression); + expressions.Add(expression); } - return new ConversionExpression(Type, new NodeArray(Expressions)); + return new ConversionExpression(type, new NodeArray(expressions)); } - private BaseNode ParseBinaryExpression(string Name) + private BaseNode ParseBinaryExpression(string name) { - BaseNode LeftPart = ParseExpression(); - if (LeftPart == null) + BaseNode leftPart = ParseExpression(); + if (leftPart == null) { return null; } - BaseNode RightPart = ParseExpression(); - if (RightPart == null) + BaseNode rightPart = ParseExpression(); + if (rightPart == null) { return null; } - return new BinaryExpression(LeftPart, Name, RightPart); + return new BinaryExpression(leftPart, name, rightPart); } - private BaseNode ParsePrefixExpression(string Name) + private BaseNode ParsePrefixExpression(string name) { - BaseNode Expression = ParseExpression(); - if (Expression == null) + BaseNode expression = ParseExpression(); + if (expression == null) { return null; } - return new PrefixExpression(Name, Expression); + return new PrefixExpression(name, expression); } @@ -1661,60 +1661,60 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler { if (Peek() == 'd') { - BaseNode BracedExpressionNode; + BaseNode bracedExpressionNode; switch (Peek(1)) { case 'i': - Position += 2; - BaseNode Field = ParseSourceName(); - if (Field == null) + _position += 2; + BaseNode field = ParseSourceName(); + if (field == null) { return null; } - BracedExpressionNode = ParseBracedExpression(); - if (BracedExpressionNode == null) + bracedExpressionNode = ParseBracedExpression(); + if (bracedExpressionNode == null) { return null; } - return new BracedExpression(Field, BracedExpressionNode, false); + return new BracedExpression(field, bracedExpressionNode, false); case 'x': - Position += 2; - BaseNode Index = ParseExpression(); - if (Index == null) + _position += 2; + BaseNode index = ParseExpression(); + if (index == null) { return null; } - BracedExpressionNode = ParseBracedExpression(); - if (BracedExpressionNode == null) + bracedExpressionNode = ParseBracedExpression(); + if (bracedExpressionNode == null) { return null; } - return new BracedExpression(Index, BracedExpressionNode, true); + return new BracedExpression(index, bracedExpressionNode, true); case 'X': - Position += 2; - BaseNode RangeBeginExpression = ParseExpression(); - if (RangeBeginExpression == null) + _position += 2; + BaseNode rangeBeginExpression = ParseExpression(); + if (rangeBeginExpression == null) { return null; } - BaseNode RangeEndExpression = ParseExpression(); - if (RangeEndExpression == null) + BaseNode rangeEndExpression = ParseExpression(); + if (rangeEndExpression == null) { return null; } - BracedExpressionNode = ParseBracedExpression(); - if (BracedExpressionNode == null) + bracedExpressionNode = ParseBracedExpression(); + if (bracedExpressionNode == null) { return null; } - return new BracedRangeExpression(RangeBeginExpression, RangeEndExpression, BracedExpressionNode); + return new BracedRangeExpression(rangeBeginExpression, rangeEndExpression, bracedExpressionNode); } } @@ -1729,30 +1729,30 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler // ::= pi * E # parenthesized initialization private BaseNode ParseNewExpression() { - bool IsGlobal = ConsumeIf("gs"); - bool IsArray = Peek(1) == 'a'; + bool isGlobal = ConsumeIf("gs"); + bool isArray = Peek(1) == 'a'; if (!ConsumeIf("nw") || !ConsumeIf("na")) { return null; } - List Expressions = new List(); - List Initializers = new List(); + List expressions = new List(); + List initializers = new List(); while (!ConsumeIf("_")) { - BaseNode Expression = ParseExpression(); - if (Expression == null) + BaseNode expression = ParseExpression(); + if (expression == null) { return null; } - Expressions.Add(Expression); + expressions.Add(expression); } - BaseNode TypeNode = ParseType(); - if (TypeNode == null) + BaseNode typeNode = ParseType(); + if (typeNode == null) { return null; } @@ -1761,13 +1761,13 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler { while (!ConsumeIf("E")) { - BaseNode Initializer = ParseExpression(); - if (Initializer == null) + BaseNode initializer = ParseExpression(); + if (initializer == null) { return null; } - Initializers.Add(Initializer); + initializers.Add(initializer); } } else if (!ConsumeIf("E")) @@ -1775,7 +1775,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler return null; } - return new NewExpression(new NodeArray(Expressions), TypeNode, new NodeArray(Initializers), IsGlobal, IsArray); + return new NewExpression(new NodeArray(expressions), typeNode, new NodeArray(initializers), isGlobal, isArray); } @@ -1823,8 +1823,8 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler // ::= private BaseNode ParseExpression() { - bool IsGlobal = ConsumeIf("gs"); - BaseNode Expression = null; + bool isGlobal = ConsumeIf("gs"); + BaseNode expression = null; if (Count() < 2) { return null; @@ -1837,8 +1837,8 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler case 'T': return ParseTemplateParam(); case 'f': - char C = Peek(1); - if (C == 'p' || (C == 'L' && char.IsDigit(Peek(2)))) + char c = Peek(1); + if (c == 'p' || (c == 'L' && char.IsDigit(Peek(2)))) { return ParseFunctionParameter(); } @@ -1848,164 +1848,164 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler switch (Peek(1)) { case 'a': - Position += 2; + _position += 2; return ParseBinaryExpression("&&"); case 'd': case 'n': - Position += 2; + _position += 2; return ParseBinaryExpression("&"); case 'N': - Position += 2; + _position += 2; return ParseBinaryExpression("&="); case 'S': - Position += 2; + _position += 2; return ParseBinaryExpression("="); case 't': - Position += 2; - BaseNode Type = ParseType(); - if (Type == null) + _position += 2; + BaseNode type = ParseType(); + if (type == null) { return null; } - return new EnclosedExpression("alignof (", Type, ")"); + return new EnclosedExpression("alignof (", type, ")"); case 'z': - Position += 2; - Expression = ParseExpression(); - if (Expression == null) + _position += 2; + expression = ParseExpression(); + if (expression == null) { return null; } - return new EnclosedExpression("alignof (", Expression, ")"); + return new EnclosedExpression("alignof (", expression, ")"); } return null; case 'c': switch (Peek(1)) { case 'c': - Position += 2; - BaseNode To = ParseType(); - if (To == null) + _position += 2; + BaseNode to = ParseType(); + if (to == null) { return null; } - BaseNode From = ParseExpression(); - if (From == null) + BaseNode from = ParseExpression(); + if (from == null) { return null; } - return new CastExpression("const_cast", To, From); + return new CastExpression("const_cast", to, from); case 'l': - Position += 2; - BaseNode Callee = ParseExpression(); - if (Callee == null) + _position += 2; + BaseNode callee = ParseExpression(); + if (callee == null) { return null; } - List Names = new List(); + List names = new List(); while (!ConsumeIf("E")) { - Expression = ParseExpression(); - if (Expression == null) + expression = ParseExpression(); + if (expression == null) { return null; } - Names.Add(Expression); + names.Add(expression); } - return new CallExpression(Callee, Names); + return new CallExpression(callee, names); case 'm': - Position += 2; + _position += 2; return ParseBinaryExpression(","); case 'o': - Position += 2; + _position += 2; return ParsePrefixExpression("~"); case 'v': return ParseConversionExpression(); } return null; case 'd': - BaseNode LeftNode = null; - BaseNode RightNode = null; + BaseNode leftNode = null; + BaseNode rightNode = null; switch (Peek(1)) { case 'a': - Position += 2; - Expression = ParseExpression(); - if (Expression == null) + _position += 2; + expression = ParseExpression(); + if (expression == null) { - return Expression; + return expression; } - return new DeleteExpression(Expression, IsGlobal, true); + return new DeleteExpression(expression, isGlobal, true); case 'c': - Position += 2; - BaseNode Type = ParseType(); - if (Type == null) + _position += 2; + BaseNode type = ParseType(); + if (type == null) { return null; } - Expression = ParseExpression(); - if (Expression == null) + expression = ParseExpression(); + if (expression == null) { - return Expression; + return expression; } - return new CastExpression("dynamic_cast", Type, Expression); + return new CastExpression("dynamic_cast", type, expression); case 'e': - Position += 2; + _position += 2; return ParsePrefixExpression("*"); case 'l': - Position += 2; - Expression = ParseExpression(); - if (Expression == null) + _position += 2; + expression = ParseExpression(); + if (expression == null) { return null; } - return new DeleteExpression(Expression, IsGlobal, false); + return new DeleteExpression(expression, isGlobal, false); case 'n': return ParseUnresolvedName(); case 's': - Position += 2; - LeftNode = ParseExpression(); - if (LeftNode == null) + _position += 2; + leftNode = ParseExpression(); + if (leftNode == null) { return null; } - RightNode = ParseExpression(); - if (RightNode == null) + rightNode = ParseExpression(); + if (rightNode == null) { return null; } - return new MemberExpression(LeftNode, ".*", RightNode); + return new MemberExpression(leftNode, ".*", rightNode); case 't': - Position += 2; - LeftNode = ParseExpression(); - if (LeftNode == null) + _position += 2; + leftNode = ParseExpression(); + if (leftNode == null) { return null; } - RightNode = ParseExpression(); - if (RightNode == null) + rightNode = ParseExpression(); + if (rightNode == null) { return null; } - return new MemberExpression(LeftNode, ".", RightNode); + return new MemberExpression(leftNode, ".", rightNode); case 'v': - Position += 2; + _position += 2; return ParseBinaryExpression("/"); case 'V': - Position += 2; + _position += 2; return ParseBinaryExpression("/="); } return null; @@ -2013,13 +2013,13 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler switch (Peek(1)) { case 'o': - Position += 2; + _position += 2; return ParseBinaryExpression("^"); case 'O': - Position += 2; + _position += 2; return ParseBinaryExpression("^="); case 'q': - Position += 2; + _position += 2; return ParseBinaryExpression("=="); } return null; @@ -2027,10 +2027,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler switch (Peek(1)) { case 'e': - Position += 2; + _position += 2; return ParseBinaryExpression(">="); case 't': - Position += 2; + _position += 2; return ParseBinaryExpression(">"); } return null; @@ -2038,51 +2038,51 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler switch (Peek(1)) { case 'x': - Position += 2; + _position += 2; BaseNode Base = ParseExpression(); if (Base == null) { return null; } - BaseNode Subscript = ParseExpression(); + BaseNode subscript = ParseExpression(); if (Base == null) { return null; } - return new ArraySubscriptingExpression(Base, Subscript); + return new ArraySubscriptingExpression(Base, subscript); case 'l': - Position += 2; + _position += 2; - List BracedExpressions = new List(); + List bracedExpressions = new List(); while (!ConsumeIf("E")) { - Expression = ParseBracedExpression(); - if (Expression == null) + expression = ParseBracedExpression(); + if (expression == null) { return null; } - BracedExpressions.Add(Expression); + bracedExpressions.Add(expression); } - return new InitListExpression(null, BracedExpressions); + return new InitListExpression(null, bracedExpressions); } return null; case 'l': switch (Peek(1)) { case 'e': - Position += 2; + _position += 2; return ParseBinaryExpression("<="); case 's': - Position += 2; + _position += 2; return ParseBinaryExpression("<<"); case 'S': - Position += 2; + _position += 2; return ParseBinaryExpression("<<="); case 't': - Position += 2; + _position += 2; return ParseBinaryExpression("<"); } return null; @@ -2090,31 +2090,31 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler switch (Peek(1)) { case 'i': - Position += 2; + _position += 2; return ParseBinaryExpression("-"); case 'I': - Position += 2; + _position += 2; return ParseBinaryExpression("-="); case 'l': - Position += 2; + _position += 2; return ParseBinaryExpression("*"); case 'L': - Position += 2; + _position += 2; return ParseBinaryExpression("*="); case 'm': - Position += 2; + _position += 2; if (ConsumeIf("_")) { return ParsePrefixExpression("--"); } - Expression = ParseExpression(); - if (Expression == null) + expression = ParseExpression(); + if (expression == null) { return null; } - return new PostfixExpression(Expression, "--"); + return new PostfixExpression(expression, "--"); } return null; case 'n': @@ -2122,26 +2122,26 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler { case 'a': case 'w': - Position += 2; + _position += 2; return ParseNewExpression(); case 'e': - Position += 2; + _position += 2; return ParseBinaryExpression("!="); case 'g': - Position += 2; + _position += 2; return ParsePrefixExpression("-"); case 't': - Position += 2; + _position += 2; return ParsePrefixExpression("!"); case 'x': - Position += 2; - Expression = ParseExpression(); - if (Expression == null) + _position += 2; + expression = ParseExpression(); + if (expression == null) { return null; } - return new EnclosedExpression("noexcept (", Expression, ")"); + return new EnclosedExpression("noexcept (", expression, ")"); } return null; case 'o': @@ -2150,13 +2150,13 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler case 'n': return ParseUnresolvedName(); case 'o': - Position += 2; + _position += 2; return ParseBinaryExpression("||"); case 'r': - Position += 2; + _position += 2; return ParseBinaryExpression("|"); case 'R': - Position += 2; + _position += 2; return ParseBinaryExpression("|="); } return null; @@ -2164,100 +2164,100 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler switch (Peek(1)) { case 'm': - Position += 2; + _position += 2; return ParseBinaryExpression("->*"); case 'l': case 's': - Position += 2; + _position += 2; return ParseBinaryExpression("+"); case 'L': - Position += 2; + _position += 2; return ParseBinaryExpression("+="); case 'p': - Position += 2; + _position += 2; if (ConsumeIf("_")) { return ParsePrefixExpression("++"); } - Expression = ParseExpression(); - if (Expression == null) + expression = ParseExpression(); + if (expression == null) { return null; } - return new PostfixExpression(Expression, "++"); + return new PostfixExpression(expression, "++"); case 't': - Position += 2; - LeftNode = ParseExpression(); - if (LeftNode == null) + _position += 2; + leftNode = ParseExpression(); + if (leftNode == null) { return null; } - RightNode = ParseExpression(); - if (RightNode == null) + rightNode = ParseExpression(); + if (rightNode == null) { return null; } - return new MemberExpression(LeftNode, "->", RightNode); + return new MemberExpression(leftNode, "->", rightNode); } return null; case 'q': if (Peek(1) == 'u') { - Position += 2; - BaseNode Condition = ParseExpression(); - if (Condition == null) + _position += 2; + BaseNode condition = ParseExpression(); + if (condition == null) { return null; } - LeftNode = ParseExpression(); - if (LeftNode == null) + leftNode = ParseExpression(); + if (leftNode == null) { return null; } - RightNode = ParseExpression(); - if (RightNode == null) + rightNode = ParseExpression(); + if (rightNode == null) { return null; } - return new ConditionalExpression(Condition, LeftNode, RightNode); + return new ConditionalExpression(condition, leftNode, rightNode); } return null; case 'r': switch (Peek(1)) { case 'c': - Position += 2; - BaseNode To = ParseType(); - if (To == null) + _position += 2; + BaseNode to = ParseType(); + if (to == null) { return null; } - BaseNode From = ParseExpression(); - if (From == null) + BaseNode from = ParseExpression(); + if (from == null) { return null; } - return new CastExpression("reinterpret_cast", To, From); + return new CastExpression("reinterpret_cast", to, from); case 'm': - Position += 2; + _position += 2; return ParseBinaryExpression("%"); case 'M': - Position += 2; + _position += 2; return ParseBinaryExpression("%"); case 's': - Position += 2; + _position += 2; return ParseBinaryExpression(">>"); case 'S': - Position += 2; + _position += 2; return ParseBinaryExpression(">>="); } return null; @@ -2265,140 +2265,140 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler switch (Peek(1)) { case 'c': - Position += 2; - BaseNode To = ParseType(); - if (To == null) + _position += 2; + BaseNode to = ParseType(); + if (to == null) { return null; } - BaseNode From = ParseExpression(); - if (From == null) + BaseNode from = ParseExpression(); + if (from == null) { return null; } - return new CastExpression("static_cast", To, From); + return new CastExpression("static_cast", to, from); case 'p': - Position += 2; - Expression = ParseExpression(); - if (Expression == null) + _position += 2; + expression = ParseExpression(); + if (expression == null) { return null; } - return new PackedTemplateParameterExpansion(Expression); + return new PackedTemplateParameterExpansion(expression); case 'r': return ParseUnresolvedName(); case 't': - Position += 2; - BaseNode EnclosedType = ParseType(); - if (EnclosedType == null) + _position += 2; + BaseNode enclosedType = ParseType(); + if (enclosedType == null) { return null; } - return new EnclosedExpression("sizeof (", EnclosedType, ")"); + return new EnclosedExpression("sizeof (", enclosedType, ")"); case 'z': - Position += 2; - Expression = ParseExpression(); - if (Expression == null) + _position += 2; + expression = ParseExpression(); + if (expression == null) { return null; } - return new EnclosedExpression("sizeof (", Expression, ")"); + return new EnclosedExpression("sizeof (", expression, ")"); case 'Z': - Position += 2; - BaseNode SizeofParamNode = null; + _position += 2; + BaseNode sizeofParamNode = null; switch (Peek()) { case 'T': // FIXME: ??? Not entire sure if it's right - SizeofParamNode = ParseFunctionParameter(); - if (SizeofParamNode == null) + sizeofParamNode = ParseFunctionParameter(); + if (sizeofParamNode == null) { return null; } - return new EnclosedExpression("sizeof...(", new PackedTemplateParameterExpansion(SizeofParamNode), ")"); + return new EnclosedExpression("sizeof...(", new PackedTemplateParameterExpansion(sizeofParamNode), ")"); case 'f': - SizeofParamNode = ParseFunctionParameter(); - if (SizeofParamNode == null) + sizeofParamNode = ParseFunctionParameter(); + if (sizeofParamNode == null) { return null; } - return new EnclosedExpression("sizeof...(", SizeofParamNode, ")"); + return new EnclosedExpression("sizeof...(", sizeofParamNode, ")"); } return null; case 'P': - Position += 2; - List Arguments = new List(); + _position += 2; + List arguments = new List(); while (!ConsumeIf("E")) { - BaseNode Argument = ParseTemplateArgument(); - if (Argument == null) + BaseNode argument = ParseTemplateArgument(); + if (argument == null) { return null; } - Arguments.Add(Argument); + arguments.Add(argument); } - return new EnclosedExpression("sizeof...(", new NodeArray(Arguments), ")"); + return new EnclosedExpression("sizeof...(", new NodeArray(arguments), ")"); } return null; case 't': switch (Peek(1)) { case 'e': - Expression = ParseExpression(); - if (Expression == null) + expression = ParseExpression(); + if (expression == null) { return null; } - return new EnclosedExpression("typeid (", Expression, ")"); + return new EnclosedExpression("typeid (", expression, ")"); case 't': - BaseNode EnclosedType = ParseExpression(); - if (EnclosedType == null) + BaseNode enclosedType = ParseExpression(); + if (enclosedType == null) { return null; } - return new EnclosedExpression("typeid (", EnclosedType, ")"); + return new EnclosedExpression("typeid (", enclosedType, ")"); case 'l': - Position += 2; - BaseNode TypeNode = ParseType(); - if (TypeNode == null) + _position += 2; + BaseNode typeNode = ParseType(); + if (typeNode == null) { return null; } - List BracedExpressions = new List(); + List bracedExpressions = new List(); while (!ConsumeIf("E")) { - Expression = ParseBracedExpression(); - if (Expression == null) + expression = ParseBracedExpression(); + if (expression == null) { return null; } - BracedExpressions.Add(Expression); + bracedExpressions.Add(expression); } - return new InitListExpression(TypeNode, BracedExpressions); + return new InitListExpression(typeNode, bracedExpressions); case 'r': - Position += 2; + _position += 2; return new NameType("throw"); case 'w': - Position += 2; - Expression = ParseExpression(); - if (Expression == null) + _position += 2; + expression = ParseExpression(); + if (expression == null) { return null; } - return new ThrowExpression(Expression); + return new ThrowExpression(expression); } return null; } @@ -2411,15 +2411,15 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler return null; } - private BaseNode ParseIntegerLiteral(string LiteralName) + private BaseNode ParseIntegerLiteral(string literalName) { - string Number = ParseNumber(true); - if (Number == null || Number.Length == 0 || !ConsumeIf("E")) + string number = ParseNumber(true); + if (number == null || number.Length == 0 || !ConsumeIf("E")) { return null; } - return new IntegerLiteral(LiteralName, Number); + return new IntegerLiteral(literalName, number); } // ::= L E # integer literal @@ -2439,7 +2439,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler switch (Peek()) { case 'w': - Position++; + _position++; return ParseIntegerLiteral("wchar_t"); case 'b': if (ConsumeIf("b0E")) @@ -2454,43 +2454,43 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler return null; case 'c': - Position++; + _position++; return ParseIntegerLiteral("char"); case 'a': - Position++; + _position++; return ParseIntegerLiteral("signed char"); case 'h': - Position++; + _position++; return ParseIntegerLiteral("unsigned char"); case 's': - Position++; + _position++; return ParseIntegerLiteral("short"); case 't': - Position++; + _position++; return ParseIntegerLiteral("unsigned short"); case 'i': - Position++; + _position++; return ParseIntegerLiteral(""); case 'j': - Position++; + _position++; return ParseIntegerLiteral("u"); case 'l': - Position++; + _position++; return ParseIntegerLiteral("l"); case 'm': - Position++; + _position++; return ParseIntegerLiteral("ul"); case 'x': - Position++; + _position++; return ParseIntegerLiteral("ll"); case 'y': - Position++; + _position++; return ParseIntegerLiteral("ull"); case 'n': - Position++; + _position++; return ParseIntegerLiteral("__int128"); case 'o': - Position++; + _position++; return ParseIntegerLiteral("unsigned __int128"); case 'd': case 'e': @@ -2500,29 +2500,29 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler case '_': if (ConsumeIf("_Z")) { - BaseNode Encoding = ParseEncoding(); - if (Encoding != null && ConsumeIf("E")) + BaseNode encoding = ParseEncoding(); + if (encoding != null && ConsumeIf("E")) { - return Encoding; + return encoding; } } return null; case 'T': return null; default: - BaseNode Type = ParseType(); - if (Type == null) + BaseNode type = ParseType(); + if (type == null) { return null; } - string Number = ParseNumber(); - if (Number == null || Number.Length == 0 || !ConsumeIf("E")) + string number = ParseNumber(); + if (number == null || number.Length == 0 || !ConsumeIf("E")) { return null; } - return new IntegerCastExpression(Type, Number); + return new IntegerCastExpression(type, number); } } @@ -2535,8 +2535,8 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler return null; } - BaseNode Expression = ParseExpression(); - if (Expression == null) + BaseNode expression = ParseExpression(); + if (expression == null) { return null; } @@ -2546,7 +2546,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler return null; } - return new EnclosedExpression("decltype(", Expression, ")"); + return new EnclosedExpression("decltype(", expression, ")"); } // ::= T_ # first template parameter @@ -2560,16 +2560,16 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler return null; } - int Index = 0; + int index = 0; if (!ConsumeIf("_")) { - Index = ParsePositiveNumber(); - if (Index < 0) + index = ParsePositiveNumber(); + if (index < 0) { return null; } - Index++; + index++; if (!ConsumeIf("_")) { return null; @@ -2580,65 +2580,65 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler // if (IsParsingLambdaParameters) // return new NameType("auto"); - if (CanForwardTemplateReference) + if (_canForwardTemplateReference) { - ForwardTemplateReference ForwardTemplateReference = new ForwardTemplateReference(Index); - ForwardTemplateReferenceList.Add(ForwardTemplateReference); - return ForwardTemplateReference; + ForwardTemplateReference forwardTemplateReference = new ForwardTemplateReference(index); + _forwardTemplateReferenceList.Add(forwardTemplateReference); + return forwardTemplateReference; } - if (Index >= TemplateParamList.Count) + if (index >= _templateParamList.Count) { return null; } - return TemplateParamList[Index]; + return _templateParamList[index]; } // ::= I + E - private BaseNode ParseTemplateArguments(bool HasContext = false) + private BaseNode ParseTemplateArguments(bool hasContext = false) { if (!ConsumeIf("I")) { return null; } - if (HasContext) + if (hasContext) { - TemplateParamList.Clear(); + _templateParamList.Clear(); } - List Args = new List(); + List args = new List(); while (!ConsumeIf("E")) { - if (HasContext) + if (hasContext) { - List TemplateParamListTemp = new List(TemplateParamList); - BaseNode TemplateArgument = ParseTemplateArgument(); - TemplateParamList = TemplateParamListTemp; - if (TemplateArgument == null) + List templateParamListTemp = new List(_templateParamList); + BaseNode templateArgument = ParseTemplateArgument(); + _templateParamList = templateParamListTemp; + if (templateArgument == null) { return null; } - Args.Add(TemplateArgument); - if (TemplateArgument.GetType().Equals(NodeType.PackedTemplateArgument)) + args.Add(templateArgument); + if (templateArgument.GetType().Equals(NodeType.PackedTemplateArgument)) { - TemplateArgument = new PackedTemplateParameter(((NodeArray)TemplateArgument).Nodes); + templateArgument = new PackedTemplateParameter(((NodeArray)templateArgument).Nodes); } - TemplateParamList.Add(TemplateArgument); + _templateParamList.Add(templateArgument); } else { - BaseNode TemplateArgument = ParseTemplateArgument(); - if (TemplateArgument == null) + BaseNode templateArgument = ParseTemplateArgument(); + if (templateArgument == null) { return null; } - Args.Add(TemplateArgument); + args.Add(templateArgument); } } - return new TemplateArguments(Args); + return new TemplateArguments(args); } @@ -2652,32 +2652,32 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler { // X E case 'X': - Position++; - BaseNode Expression = ParseExpression(); - if (Expression == null || !ConsumeIf("E")) + _position++; + BaseNode expression = ParseExpression(); + if (expression == null || !ConsumeIf("E")) { return null; } - return Expression; + return expression; // case 'L': return ParseExpressionPrimary(); // J * E case 'J': - Position++; - List TemplateArguments = new List(); + _position++; + List templateArguments = new List(); while (!ConsumeIf("E")) { - BaseNode TemplateArgument = ParseTemplateArgument(); - if (TemplateArgument == null) + BaseNode templateArgument = ParseTemplateArgument(); + if (templateArgument == null) { return null; } - TemplateArguments.Add(TemplateArgument); + templateArguments.Add(templateArgument); } - return new NodeArray(TemplateArguments, NodeType.PackedTemplateArgument); + return new NodeArray(templateArguments, NodeType.PackedTemplateArgument); // default: return ParseType(); @@ -2686,7 +2686,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler class NameParserContext { - public CVType CV; + public CvType Cv; public SimpleReferenceType Ref; public bool FinishWithTemplateArguments; public bool CtorDtorConversion; @@ -2700,25 +2700,25 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler { if (Peek() == 'T') { - BaseNode TemplateParam = ParseTemplateParam(); - if (TemplateParam == null) + BaseNode templateParam = ParseTemplateParam(); + if (templateParam == null) { return null; } - SubstitutionList.Add(TemplateParam); - return TemplateParam; + _substitutionList.Add(templateParam); + return templateParam; } else if (Peek() == 'D') { - BaseNode DeclType = ParseDecltype(); - if (DeclType == null) + BaseNode declType = ParseDecltype(); + if (declType == null) { return null; } - SubstitutionList.Add(DeclType); - return DeclType; + _substitutionList.Add(declType); + return declType; } return ParseSubstitution(); } @@ -2726,44 +2726,44 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler // ::= [ ] private BaseNode ParseSimpleId() { - BaseNode SourceName = ParseSourceName(); - if (SourceName == null) + BaseNode sourceName = ParseSourceName(); + if (sourceName == null) { return null; } if (Peek() == 'I') { - BaseNode TemplateArguments = ParseTemplateArguments(); - if (TemplateArguments == null) + BaseNode templateArguments = ParseTemplateArguments(); + if (templateArguments == null) { return null; } - return new NameTypeWithTemplateArguments(SourceName, TemplateArguments); + return new NameTypeWithTemplateArguments(sourceName, templateArguments); } - return SourceName; + return sourceName; } // ::= # e.g., ~T or ~decltype(f()) // ::= # e.g., ~A<2*N> private BaseNode ParseDestructorName() { - BaseNode Node; + BaseNode node; if (char.IsDigit(Peek())) { - Node = ParseSimpleId(); + node = ParseSimpleId(); } else { - Node = ParseUnresolvedType(); + node = ParseUnresolvedType(); } - if (Node == null) + if (node == null) { return null; } - return new DtorName(Node); + return new DtorName(node); } // ::= # unresolved name @@ -2785,23 +2785,23 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler } ConsumeIf("on"); - BaseNode OperatorName = ParseOperatorName(null); - if (OperatorName == null) + BaseNode operatorName = ParseOperatorName(null); + if (operatorName == null) { return null; } if (Peek() == 'I') { - BaseNode TemplateArguments = ParseTemplateArguments(); - if (TemplateArguments == null) + BaseNode templateArguments = ParseTemplateArguments(); + if (templateArguments == null) { return null; } - return new NameTypeWithTemplateArguments(OperatorName, TemplateArguments); + return new NameTypeWithTemplateArguments(operatorName, templateArguments); } - return OperatorName; + return operatorName; } // ::= [gs] # x or (with "gs") ::x @@ -2810,27 +2810,27 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler // # T::N::x /decltype(p)::N::x // ::= [gs] sr + E // # A::x, N::y, A::z; "gs" means leading "::" - private BaseNode ParseUnresolvedName(NameParserContext Context = null) + private BaseNode ParseUnresolvedName(NameParserContext context = null) { - BaseNode Result = null; + BaseNode result = null; if (ConsumeIf("srN")) { - Result = ParseUnresolvedType(); - if (Result == null) + result = ParseUnresolvedType(); + if (result == null) { return null; } if (Peek() == 'I') { - BaseNode TemplateArguments = ParseTemplateArguments(); - if (TemplateArguments == null) + BaseNode templateArguments = ParseTemplateArguments(); + if (templateArguments == null) { return null; } - Result = new NameTypeWithTemplateArguments(Result, TemplateArguments); - if (Result == null) + result = new NameTypeWithTemplateArguments(result, templateArguments); + if (result == null) { return null; } @@ -2838,45 +2838,45 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler while (!ConsumeIf("E")) { - BaseNode SimpleId = ParseSimpleId(); - if (SimpleId == null) + BaseNode simpleId = ParseSimpleId(); + if (simpleId == null) { return null; } - Result = new QualifiedName(Result, SimpleId); - if (Result == null) + result = new QualifiedName(result, simpleId); + if (result == null) { return null; } } - BaseNode BaseName = ParseBaseUnresolvedName(); - if (BaseName == null) + BaseNode baseName = ParseBaseUnresolvedName(); + if (baseName == null) { return null; } - return new QualifiedName(Result, BaseName); + return new QualifiedName(result, baseName); } - bool IsGlobal = ConsumeIf("gs"); + bool isGlobal = ConsumeIf("gs"); // ::= [gs] # x or (with "gs") ::x if (!ConsumeIf("sr")) { - Result = ParseBaseUnresolvedName(); - if (Result == null) + result = ParseBaseUnresolvedName(); + if (result == null) { return null; } - if (IsGlobal) + if (isGlobal) { - Result = new GlobalQualifiedName(Result); + result = new GlobalQualifiedName(result); } - return Result; + return result; } // ::= [gs] sr + E @@ -2884,26 +2884,26 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler { do { - BaseNode Qualifier = ParseSimpleId(); - if (Qualifier == null) + BaseNode qualifier = ParseSimpleId(); + if (qualifier == null) { return null; } - if (Result != null) + if (result != null) { - Result = new QualifiedName(Result, Qualifier); + result = new QualifiedName(result, qualifier); } - else if (IsGlobal) + else if (isGlobal) { - Result = new GlobalQualifiedName(Qualifier); + result = new GlobalQualifiedName(qualifier); } else { - Result = Qualifier; + result = qualifier; } - if (Result == null) + if (result == null) { return null; } @@ -2912,62 +2912,62 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler // ::= sr [tempate-args] # T::x / decltype(p)::x else { - Result = ParseUnresolvedType(); - if (Result == null) + result = ParseUnresolvedType(); + if (result == null) { return null; } if (Peek() == 'I') { - BaseNode TemplateArguments = ParseTemplateArguments(); - if (TemplateArguments == null) + BaseNode templateArguments = ParseTemplateArguments(); + if (templateArguments == null) { return null; } - Result = new NameTypeWithTemplateArguments(Result, TemplateArguments); - if (Result == null) + result = new NameTypeWithTemplateArguments(result, templateArguments); + if (result == null) { return null; } } } - if (Result == null) + if (result == null) { return null; } - BaseNode BaseUnresolvedName = ParseBaseUnresolvedName(); - if (BaseUnresolvedName == null) + BaseNode baseUnresolvedName = ParseBaseUnresolvedName(); + if (baseUnresolvedName == null) { return null; } - return new QualifiedName(Result, BaseUnresolvedName); + return new QualifiedName(result, baseUnresolvedName); } // ::= // ::= St # ::std:: - private BaseNode ParseUnscopedName(NameParserContext Context) + private BaseNode ParseUnscopedName(NameParserContext context) { if (ConsumeIf("St")) { - BaseNode UnresolvedName = ParseUnresolvedName(Context); - if (UnresolvedName == null) + BaseNode unresolvedName = ParseUnresolvedName(context); + if (unresolvedName == null) { return null; } - return new StdQualifiedName(UnresolvedName); + return new StdQualifiedName(unresolvedName); } - return ParseUnresolvedName(Context); + return ParseUnresolvedName(context); } // ::= N [] [] E // ::= N [] [] E - private BaseNode ParseNestedName(NameParserContext Context) + private BaseNode ParseNestedName(NameParserContext context) { // Impossible in theory if (Consume() != 'N') @@ -2975,22 +2975,22 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler return null; } - BaseNode Result = null; - CVType CV = new CVType(ParseCVQualifiers(), null); - if (Context != null) + BaseNode result = null; + CvType cv = new CvType(ParseCvQualifiers(), null); + if (context != null) { - Context.CV = CV; + context.Cv = cv; } SimpleReferenceType Ref = ParseRefQualifiers(); - if (Context != null) + if (context != null) { - Context.Ref = Ref; + context.Ref = Ref; } if (ConsumeIf("St")) { - Result = new NameType("std"); + result = new NameType("std"); } while (!ConsumeIf("E")) @@ -2998,124 +2998,124 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler // end if (ConsumeIf("M")) { - if (Result == null) + if (result == null) { return null; } continue; } - char C = Peek(); + char c = Peek(); // TODO: template args - if (C == 'T') + if (c == 'T') { - BaseNode TemplateParam = ParseTemplateParam(); - if (TemplateParam == null) + BaseNode templateParam = ParseTemplateParam(); + if (templateParam == null) { return null; } - Result = CreateNameNode(Result, TemplateParam, Context); - SubstitutionList.Add(Result); + result = CreateNameNode(result, templateParam, context); + _substitutionList.Add(result); continue; } // - if (C == 'I') + if (c == 'I') { - BaseNode TemplateArgument = ParseTemplateArguments(Context != null); - if (TemplateArgument == null || Result == null) + BaseNode templateArgument = ParseTemplateArguments(context != null); + if (templateArgument == null || result == null) { return null; } - Result = new NameTypeWithTemplateArguments(Result, TemplateArgument); - if (Context != null) + result = new NameTypeWithTemplateArguments(result, templateArgument); + if (context != null) { - Context.FinishWithTemplateArguments = true; + context.FinishWithTemplateArguments = true; } - SubstitutionList.Add(Result); + _substitutionList.Add(result); continue; } // - if (C == 'D' && (Peek(1) == 't' || Peek(1) == 'T')) + if (c == 'D' && (Peek(1) == 't' || Peek(1) == 'T')) { - BaseNode Decltype = ParseDecltype(); - if (Decltype == null) + BaseNode decltype = ParseDecltype(); + if (decltype == null) { return null; } - Result = CreateNameNode(Result, Decltype, Context); - SubstitutionList.Add(Result); + result = CreateNameNode(result, decltype, context); + _substitutionList.Add(result); continue; } // - if (C == 'S' && Peek(1) != 't') + if (c == 'S' && Peek(1) != 't') { - BaseNode Substitution = ParseSubstitution(); - if (Substitution == null) + BaseNode substitution = ParseSubstitution(); + if (substitution == null) { return null; } - Result = CreateNameNode(Result, Substitution, Context); - if (Result != Substitution) + result = CreateNameNode(result, substitution, context); + if (result != substitution) { - SubstitutionList.Add(Substitution); + _substitutionList.Add(substitution); } continue; } // of ParseUnqualifiedName - if (C == 'C' || (C == 'D' && Peek(1) != 'C')) + if (c == 'C' || (c == 'D' && Peek(1) != 'C')) { // We cannot have nothing before this - if (Result == null) + if (result == null) { return null; } - BaseNode CtOrDtorName = ParseCtorDtorName(Context, Result); + BaseNode ctOrDtorName = ParseCtorDtorName(context, result); - if (CtOrDtorName == null) + if (ctOrDtorName == null) { return null; } - Result = CreateNameNode(Result, CtOrDtorName, Context); + result = CreateNameNode(result, ctOrDtorName, context); // TODO: ABI Tags (before) - if (Result == null) + if (result == null) { return null; } - SubstitutionList.Add(Result); + _substitutionList.Add(result); continue; } - BaseNode UnqualifiedName = ParseUnqualifiedName(Context); - if (UnqualifiedName == null) + BaseNode unqualifiedName = ParseUnqualifiedName(context); + if (unqualifiedName == null) { return null; } - Result = CreateNameNode(Result, UnqualifiedName, Context); + result = CreateNameNode(result, unqualifiedName, context); - SubstitutionList.Add(Result); + _substitutionList.Add(result); } - if (Result == null || SubstitutionList.Count == 0) + if (result == null || _substitutionList.Count == 0) { return null; } - SubstitutionList.RemoveAt(SubstitutionList.Count - 1); - return Result; + _substitutionList.RemoveAt(_substitutionList.Count - 1); + return result; } // ::= _ # when number < 10 @@ -3141,24 +3141,24 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler // ::= Z E [] // ::= Z E s [] // ::= Z Ed [ ] _ - private BaseNode ParseLocalName(NameParserContext Context) + private BaseNode ParseLocalName(NameParserContext context) { if (!ConsumeIf("Z")) { return null; } - BaseNode Encoding = ParseEncoding(); - if (Encoding == null || !ConsumeIf("E")) + BaseNode encoding = ParseEncoding(); + if (encoding == null || !ConsumeIf("E")) { return null; } - BaseNode EntityName; + BaseNode entityName; if (ConsumeIf("s")) { ParseDiscriminator(); - return new LocalName(Encoding, new NameType("string literal")); + return new LocalName(encoding, new NameType("string literal")); } else if (ConsumeIf("d")) { @@ -3168,47 +3168,47 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler return null; } - EntityName = ParseName(Context); - if (EntityName == null) + entityName = ParseName(context); + if (entityName == null) { return null; } - return new LocalName(Encoding, EntityName); + return new LocalName(encoding, entityName); } - EntityName = ParseName(Context); - if (EntityName == null) + entityName = ParseName(context); + if (entityName == null) { return null; } ParseDiscriminator(); - return new LocalName(Encoding, EntityName); + return new LocalName(encoding, entityName); } // ::= // ::= // ::= // ::= # See Scope Encoding below (TODO) - private BaseNode ParseName(NameParserContext Context = null) + private BaseNode ParseName(NameParserContext context = null) { ConsumeIf("L"); if (Peek() == 'N') { - return ParseNestedName(Context); + return ParseNestedName(context); } if (Peek() == 'Z') { - return ParseLocalName(Context); + return ParseLocalName(context); } if (Peek() == 'S' && Peek(1) != 't') { - BaseNode Substitution = ParseSubstitution(); - if (Substitution == null) + BaseNode substitution = ParseSubstitution(); + if (substitution == null) { return null; } @@ -3218,50 +3218,50 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler return null; } - BaseNode TemplateArguments = ParseTemplateArguments(Context != null); - if (TemplateArguments == null) + BaseNode templateArguments = ParseTemplateArguments(context != null); + if (templateArguments == null) { return null; } - if (Context != null) + if (context != null) { - Context.FinishWithTemplateArguments = true; + context.FinishWithTemplateArguments = true; } - return new NameTypeWithTemplateArguments(Substitution, TemplateArguments); + return new NameTypeWithTemplateArguments(substitution, templateArguments); } - BaseNode Result = ParseUnscopedName(Context); - if (Result == null) + BaseNode result = ParseUnscopedName(context); + if (result == null) { return null; } if (Peek() == 'I') { - SubstitutionList.Add(Result); - BaseNode TemplateArguments = ParseTemplateArguments(Context != null); - if (TemplateArguments == null) + _substitutionList.Add(result); + BaseNode templateArguments = ParseTemplateArguments(context != null); + if (templateArguments == null) { return null; } - if (Context != null) + if (context != null) { - Context.FinishWithTemplateArguments = true; + context.FinishWithTemplateArguments = true; } - return new NameTypeWithTemplateArguments(Result, TemplateArguments); + return new NameTypeWithTemplateArguments(result, templateArguments); } - return Result; + return result; } private bool IsEncodingEnd() { - char C = Peek(); - return Count() == 0 || C == 'E' || C == '.' || C == '_'; + char c = Peek(); + return Count() == 0 || c == 'E' || c == '.' || c == '_'; } // ::= @@ -3269,14 +3269,14 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler // ::= private BaseNode ParseEncoding() { - NameParserContext Context = new NameParserContext(); + NameParserContext context = new NameParserContext(); if (Peek() == 'T' || (Peek() == 'G' && Peek(1) == 'V')) { - return ParseSpecialName(Context); + return ParseSpecialName(context); } - BaseNode Name = ParseName(Context); - if (Name == null) + BaseNode name = ParseName(context); + if (name == null) { return null; } @@ -3285,16 +3285,16 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler if (IsEncodingEnd()) { - return Name; + return name; } // TODO: Ua9enable_ifI - BaseNode ReturnType = null; - if (!Context.CtorDtorConversion && Context.FinishWithTemplateArguments) + BaseNode returnType = null; + if (!context.CtorDtorConversion && context.FinishWithTemplateArguments) { - ReturnType = ParseType(); - if (ReturnType == null) + returnType = ParseType(); + if (returnType == null) { return null; } @@ -3302,27 +3302,27 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler if (ConsumeIf("v")) { - return new EncodedFunction(Name, null, Context.CV, Context.Ref, null, ReturnType); + return new EncodedFunction(name, null, context.Cv, context.Ref, null, returnType); } List Params = new List(); // backup because that can be destroyed by parseType - CVType CV = Context.CV; - SimpleReferenceType Ref = Context.Ref; + CvType cv = context.Cv; + SimpleReferenceType Ref = context.Ref; while (!IsEncodingEnd()) { - BaseNode Param = ParseType(); - if (Param == null) + BaseNode param = ParseType(); + if (param == null) { return null; } - Params.Add(Param); + Params.Add(param); } - return new EncodedFunction(Name, new NodeArray(Params), CV, Ref, null, ReturnType); + return new EncodedFunction(name, new NodeArray(Params), cv, Ref, null, returnType); } // ::= _Z @@ -3331,37 +3331,37 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler { if (ConsumeIf("_Z")) { - BaseNode Encoding = ParseEncoding(); - if (Encoding != null && Count() == 0) + BaseNode encoding = ParseEncoding(); + if (encoding != null && Count() == 0) { - return Encoding; + return encoding; } return null; } else { - BaseNode Type = ParseType(); - if (Type != null && Count() == 0) + BaseNode type = ParseType(); + if (type != null && Count() == 0) { - return Type; + return type; } return null; } } - public static string Parse(string OriginalMangled) + public static string Parse(string originalMangled) { - Demangler Instance = new Demangler(OriginalMangled); - BaseNode ResNode = Instance.Parse(); + Demangler instance = new Demangler(originalMangled); + BaseNode resNode = instance.Parse(); - if (ResNode != null) + if (resNode != null) { - StringWriter Writer = new StringWriter(); - ResNode.Print(Writer); - return Writer.ToString(); + StringWriter writer = new StringWriter(); + resNode.Print(writer); + return writer.ToString(); } - return OriginalMangled; + return originalMangled; } } } diff --git a/Ryujinx.HLE/HOS/ErrorCode.cs b/Ryujinx.HLE/HOS/ErrorCode.cs index 767664f8..564fa91d 100644 --- a/Ryujinx.HLE/HOS/ErrorCode.cs +++ b/Ryujinx.HLE/HOS/ErrorCode.cs @@ -2,9 +2,9 @@ namespace Ryujinx.HLE.HOS { static class ErrorCode { - public static uint MakeError(ErrorModule Module, int Code) + public static uint MakeError(ErrorModule module, int code) { - return (uint)Module | ((uint)Code << 9); + return (uint)module | ((uint)code << 9); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/ErrorModule.cs b/Ryujinx.HLE/HOS/ErrorModule.cs index 5c6c9b05..e13d5e84 100644 --- a/Ryujinx.HLE/HOS/ErrorModule.cs +++ b/Ryujinx.HLE/HOS/ErrorModule.cs @@ -8,18 +8,18 @@ namespace Ryujinx.HLE.HOS Htcs = 4, Ncm = 5, Dd = 6, - Debug_Monitor = 7, + DebugMonitor = 7, Lr = 8, Loader = 9, - IPC_Command_Interface = 10, - IPC = 11, + IpcCommandInterface = 10, + Ipc = 11, Pm = 15, Ns = 16, Socket = 17, Htc = 18, - Ncm_Content = 20, + NcmContent = 20, Sm = 21, - RO_Userland = 22, + RoUserland = 22, SdMmc = 24, Ovln = 25, Spl = 26, @@ -41,13 +41,13 @@ namespace Ryujinx.HLE.HOS Pcie = 120, Friends = 121, Bcat = 122, - SSL = 123, + Ssl = 123, Account = 124, News = 125, Mii = 126, Nfc = 127, Am = 128, - Play_Report = 129, + PlayReport = 129, Ahid = 130, Qlaunch = 132, Pcv = 133, @@ -64,23 +64,23 @@ namespace Ryujinx.HLE.HOS Ec = 144, ETicket = 145, Ngc = 146, - Error_Report = 147, + ErrorReport = 147, Apm = 148, Profiler = 150, - Error_Upload = 151, + ErrorUpload = 151, Audio = 153, Npns = 154, - Npns_Http_Stream = 155, + NpnsHttpStream = 155, Arp = 157, Swkbd = 158, Boot = 159, - Nfc_Mifare = 161, - Userland_Assert = 162, + NfcMifare = 161, + UserlandAssert = 162, Fatal = 163, - Nim_Shop = 164, + NimShop = 164, Spsm = 165, Bgtc = 167, - Userland_Crash = 168, + UserlandCrash = 168, SRepo = 180, Dauth = 181, Hid = 202, @@ -92,10 +92,10 @@ namespace Ryujinx.HLE.HOS Web = 210, Grc = 212, Migration = 216, - Migration_Ldc_Server = 217, - General_Web_Applet = 800, - Wifi_Web_Auth_Applet = 809, - Whitelisted_Applet = 810, + MigrationLdcServer = 217, + GeneralWebApplet = 800, + WifiWebAuthApplet = 809, + WhitelistedApplet = 810, ShopN = 811 } } diff --git a/Ryujinx.HLE/HOS/Font/SharedFontManager.cs b/Ryujinx.HLE/HOS/Font/SharedFontManager.cs index 55adf46a..31c8178a 100644 --- a/Ryujinx.HLE/HOS/Font/SharedFontManager.cs +++ b/Ryujinx.HLE/HOS/Font/SharedFontManager.cs @@ -13,116 +13,116 @@ namespace Ryujinx.HLE.HOS.Font { class SharedFontManager { - private Switch Device; + private Switch _device; - private long PhysicalAddress; + private long _physicalAddress; - private string FontsPath; + private string _fontsPath; private struct FontInfo { public int Offset; public int Size; - public FontInfo(int Offset, int Size) + public FontInfo(int offset, int size) { - this.Offset = Offset; - this.Size = Size; + Offset = offset; + Size = size; } } - private Dictionary FontData; + private Dictionary _fontData; - public SharedFontManager(Switch Device, long PhysicalAddress) + public SharedFontManager(Switch device, long physicalAddress) { - this.PhysicalAddress = PhysicalAddress; + _physicalAddress = physicalAddress; - this.Device = Device; + _device = device; - FontsPath = Path.Combine(Device.FileSystem.GetSystemPath(), "fonts"); + _fontsPath = Path.Combine(device.FileSystem.GetSystemPath(), "fonts"); } - public void EnsureInitialized(ContentManager ContentManager) + public void EnsureInitialized(ContentManager contentManager) { - if (FontData == null) + if (_fontData == null) { - Device.Memory.FillWithZeros(PhysicalAddress, Horizon.FontSize); + _device.Memory.FillWithZeros(_physicalAddress, Horizon.FontSize); - uint FontOffset = 0; + uint fontOffset = 0; - FontInfo CreateFont(string Name) + FontInfo CreateFont(string name) { - if (ContentManager.TryGetFontTitle(Name, out long FontTitle)) + if (contentManager.TryGetFontTitle(name, out long fontTitle)) { - string ContentPath = ContentManager.GetInstalledContentPath(FontTitle, StorageId.NandSystem, ContentType.Data); - string FontPath = Device.FileSystem.SwitchPathToSystemPath(ContentPath); + string contentPath = contentManager.GetInstalledContentPath(fontTitle, StorageId.NandSystem, ContentType.Data); + string fontPath = _device.FileSystem.SwitchPathToSystemPath(contentPath); - if (!string.IsNullOrWhiteSpace(FontPath)) + if (!string.IsNullOrWhiteSpace(fontPath)) { - int FileIndex = 0; + int fileIndex = 0; //Use second file in Chinese Font title for standard - if(Name == "FontChineseSimplified") + if(name == "FontChineseSimplified") { - FileIndex = 1; + fileIndex = 1; } - FileStream NcaFileStream = new FileStream(FontPath, FileMode.Open, FileAccess.Read); - Nca Nca = new Nca(Device.System.KeySet, NcaFileStream, false); - NcaSection RomfsSection = Nca.Sections.FirstOrDefault(x => x?.Type == SectionType.Romfs); - Romfs Romfs = new Romfs(Nca.OpenSection(RomfsSection.SectionNum, false, Device.System.FsIntegrityCheckLevel)); - Stream FontFile = Romfs.OpenFile(Romfs.Files[FileIndex]); + FileStream ncaFileStream = new FileStream(fontPath, FileMode.Open, FileAccess.Read); + Nca nca = new Nca(_device.System.KeySet, ncaFileStream, false); + NcaSection romfsSection = nca.Sections.FirstOrDefault(x => x?.Type == SectionType.Romfs); + Romfs romfs = new Romfs(nca.OpenSection(romfsSection.SectionNum, false, _device.System.FsIntegrityCheckLevel)); + Stream fontFile = romfs.OpenFile(romfs.Files[fileIndex]); - byte[] Data = DecryptFont(FontFile); + byte[] data = DecryptFont(fontFile); - FontInfo Info = new FontInfo((int)FontOffset, Data.Length); + FontInfo info = new FontInfo((int)fontOffset, data.Length); - WriteMagicAndSize(PhysicalAddress + FontOffset, Data.Length); + WriteMagicAndSize(_physicalAddress + fontOffset, data.Length); - FontOffset += 8; + fontOffset += 8; - uint Start = FontOffset; + uint start = fontOffset; - for (; FontOffset - Start < Data.Length; FontOffset++) + for (; fontOffset - start < data.Length; fontOffset++) { - Device.Memory.WriteByte(PhysicalAddress + FontOffset, Data[FontOffset - Start]); + _device.Memory.WriteByte(_physicalAddress + fontOffset, data[fontOffset - start]); } - NcaFileStream.Dispose(); - Nca.Dispose(); + ncaFileStream.Dispose(); + nca.Dispose(); - return Info; + return info; } } - string FontFilePath = Path.Combine(FontsPath, Name + ".ttf"); + string fontFilePath = Path.Combine(_fontsPath, name + ".ttf"); - if (File.Exists(FontFilePath)) + if (File.Exists(fontFilePath)) { - byte[] Data = File.ReadAllBytes(FontFilePath); + byte[] data = File.ReadAllBytes(fontFilePath); - FontInfo Info = new FontInfo((int)FontOffset, Data.Length); + FontInfo info = new FontInfo((int)fontOffset, data.Length); - WriteMagicAndSize(PhysicalAddress + FontOffset, Data.Length); + WriteMagicAndSize(_physicalAddress + fontOffset, data.Length); - FontOffset += 8; + fontOffset += 8; - uint Start = FontOffset; + uint start = fontOffset; - for (; FontOffset - Start < Data.Length; FontOffset++) + for (; fontOffset - start < data.Length; fontOffset++) { - Device.Memory.WriteByte(PhysicalAddress + FontOffset, Data[FontOffset - Start]); + _device.Memory.WriteByte(_physicalAddress + fontOffset, data[fontOffset - start]); } - return Info; + return info; } else { - throw new InvalidSystemResourceException($"Font \"{Name}.ttf\" not found. Please provide it in \"{FontsPath}\"."); + throw new InvalidSystemResourceException($"Font \"{name}.ttf\" not found. Please provide it in \"{_fontsPath}\"."); } } - FontData = new Dictionary() + _fontData = new Dictionary { { SharedFontType.JapanUsEurope, CreateFont("FontStandard") }, { SharedFontType.SimplifiedChinese, CreateFont("FontChineseSimplified") }, @@ -132,39 +132,39 @@ namespace Ryujinx.HLE.HOS.Font { SharedFontType.NintendoEx, CreateFont("FontNintendoExtended") } }; - if (FontOffset > Horizon.FontSize) + if (fontOffset > Horizon.FontSize) { throw new InvalidSystemResourceException( $"The sum of all fonts size exceed the shared memory size. " + $"Please make sure that the fonts don't exceed {Horizon.FontSize} bytes in total. " + - $"(actual size: {FontOffset} bytes)."); + $"(actual size: {fontOffset} bytes)."); } } } - private void WriteMagicAndSize(long Position, int Size) + private void WriteMagicAndSize(long position, int size) { - const int DecMagic = 0x18029a7f; - const int Key = 0x49621806; + const int decMagic = 0x18029a7f; + const int key = 0x49621806; - int EncryptedSize = EndianSwap.Swap32(Size ^ Key); + int encryptedSize = EndianSwap.Swap32(size ^ key); - Device.Memory.WriteInt32(Position + 0, DecMagic); - Device.Memory.WriteInt32(Position + 4, EncryptedSize); + _device.Memory.WriteInt32(position + 0, decMagic); + _device.Memory.WriteInt32(position + 4, encryptedSize); } - public int GetFontSize(SharedFontType FontType) + public int GetFontSize(SharedFontType fontType) { - EnsureInitialized(Device.System.ContentManager); + EnsureInitialized(_device.System.ContentManager); - return FontData[FontType].Size; + return _fontData[fontType].Size; } - public int GetSharedMemoryAddressOffset(SharedFontType FontType) + public int GetSharedMemoryAddressOffset(SharedFontType fontType) { - EnsureInitialized(Device.System.ContentManager); + EnsureInitialized(_device.System.ContentManager); - return FontData[FontType].Offset + 8; + return _fontData[fontType].Offset + 8; } } } diff --git a/Ryujinx.HLE/HOS/GlobalStateTable.cs b/Ryujinx.HLE/HOS/GlobalStateTable.cs index d7d83453..a350dee2 100644 --- a/Ryujinx.HLE/HOS/GlobalStateTable.cs +++ b/Ryujinx.HLE/HOS/GlobalStateTable.cs @@ -6,62 +6,62 @@ namespace Ryujinx.HLE.HOS { class GlobalStateTable { - private ConcurrentDictionary DictByProcess; + private ConcurrentDictionary _dictByProcess; public GlobalStateTable() { - DictByProcess = new ConcurrentDictionary(); + _dictByProcess = new ConcurrentDictionary(); } - public bool Add(KProcess Process, int Id, object Data) + public bool Add(KProcess process, int id, object data) { - IdDictionary Dict = DictByProcess.GetOrAdd(Process, (Key) => new IdDictionary()); + IdDictionary dict = _dictByProcess.GetOrAdd(process, (key) => new IdDictionary()); - return Dict.Add(Id, Data); + return dict.Add(id, data); } - public int Add(KProcess Process, object Data) + public int Add(KProcess process, object data) { - IdDictionary Dict = DictByProcess.GetOrAdd(Process, (Key) => new IdDictionary()); + IdDictionary dict = _dictByProcess.GetOrAdd(process, (key) => new IdDictionary()); - return Dict.Add(Data); + return dict.Add(data); } - public object GetData(KProcess Process, int Id) + public object GetData(KProcess process, int id) { - if (DictByProcess.TryGetValue(Process, out IdDictionary Dict)) + if (_dictByProcess.TryGetValue(process, out IdDictionary dict)) { - return Dict.GetData(Id); + return dict.GetData(id); } return null; } - public T GetData(KProcess Process, int Id) + public T GetData(KProcess process, int id) { - if (DictByProcess.TryGetValue(Process, out IdDictionary Dict)) + if (_dictByProcess.TryGetValue(process, out IdDictionary dict)) { - return Dict.GetData(Id); + return dict.GetData(id); } return default(T); } - public object Delete(KProcess Process, int Id) + public object Delete(KProcess process, int id) { - if (DictByProcess.TryGetValue(Process, out IdDictionary Dict)) + if (_dictByProcess.TryGetValue(process, out IdDictionary dict)) { - return Dict.Delete(Id); + return dict.Delete(id); } return null; } - public ICollection DeleteProcess(KProcess Process) + public ICollection DeleteProcess(KProcess process) { - if (DictByProcess.TryRemove(Process, out IdDictionary Dict)) + if (_dictByProcess.TryRemove(process, out IdDictionary dict)) { - return Dict.Clear(); + return dict.Clear(); } return null; diff --git a/Ryujinx.HLE/HOS/Homebrew.cs b/Ryujinx.HLE/HOS/Homebrew.cs index ffb22c7f..b0e05554 100644 --- a/Ryujinx.HLE/HOS/Homebrew.cs +++ b/Ryujinx.HLE/HOS/Homebrew.cs @@ -8,70 +8,70 @@ namespace Ryujinx.HLE.HOS public const string TemporaryNroSuffix = ".ryu_tmp.nro"; //http://switchbrew.org/index.php?title=Homebrew_ABI - public static void WriteHbAbiData(MemoryManager Memory, long Position, int MainThreadHandle, string SwitchPath) + public static void WriteHbAbiData(MemoryManager memory, long position, int mainThreadHandle, string switchPath) { //MainThreadHandle. - WriteConfigEntry(Memory, ref Position, 1, 0, MainThreadHandle); + WriteConfigEntry(memory, ref position, 1, 0, mainThreadHandle); //NextLoadPath. - WriteConfigEntry(Memory, ref Position, 2, 0, Position + 0x200, Position + 0x400); + WriteConfigEntry(memory, ref position, 2, 0, position + 0x200, position + 0x400); //Argv. - long ArgvPosition = Position + 0xC00; + long argvPosition = position + 0xC00; - Memory.WriteBytes(ArgvPosition, Encoding.ASCII.GetBytes(SwitchPath + "\0")); + memory.WriteBytes(argvPosition, Encoding.ASCII.GetBytes(switchPath + "\0")); - WriteConfigEntry(Memory, ref Position, 5, 0, 0, ArgvPosition); + WriteConfigEntry(memory, ref position, 5, 0, 0, argvPosition); //AppletType. - WriteConfigEntry(Memory, ref Position, 7); + WriteConfigEntry(memory, ref position, 7); //EndOfList. - WriteConfigEntry(Memory, ref Position, 0); + WriteConfigEntry(memory, ref position, 0); } private static void WriteConfigEntry( - MemoryManager Memory, - ref long Position, - int Key, - int Flags = 0, - long Value0 = 0, - long Value1 = 0) + MemoryManager memory, + ref long position, + int key, + int flags = 0, + long value0 = 0, + long value1 = 0) { - Memory.WriteInt32(Position + 0x00, Key); - Memory.WriteInt32(Position + 0x04, Flags); - Memory.WriteInt64(Position + 0x08, Value0); - Memory.WriteInt64(Position + 0x10, Value1); + memory.WriteInt32(position + 0x00, key); + memory.WriteInt32(position + 0x04, flags); + memory.WriteInt64(position + 0x08, value0); + memory.WriteInt64(position + 0x10, value1); - Position += 0x18; + position += 0x18; } - public static string ReadHbAbiNextLoadPath(MemoryManager Memory, long Position) + public static string ReadHbAbiNextLoadPath(MemoryManager memory, long position) { - string FileName = null; + string fileName = null; while (true) { - long Key = Memory.ReadInt64(Position); + long key = memory.ReadInt64(position); - if (Key == 2) + if (key == 2) { - long Value0 = Memory.ReadInt64(Position + 0x08); - long Value1 = Memory.ReadInt64(Position + 0x10); + long value0 = memory.ReadInt64(position + 0x08); + long value1 = memory.ReadInt64(position + 0x10); - FileName = MemoryHelper.ReadAsciiString(Memory, Value0, Value1 - Value0); + fileName = MemoryHelper.ReadAsciiString(memory, value0, value1 - value0); break; } - else if (Key == 0) + else if (key == 0) { break; } - Position += 0x18; + position += 0x18; } - return FileName; + return fileName; } } } diff --git a/Ryujinx.HLE/HOS/Horizon.cs b/Ryujinx.HLE/HOS/Horizon.cs index 46c27649..a5ea5354 100644 --- a/Ryujinx.HLE/HOS/Horizon.cs +++ b/Ryujinx.HLE/HOS/Horizon.cs @@ -60,9 +60,9 @@ namespace Ryujinx.HLE.HOS internal KContextIdManager ContextIdManager { get; private set; } - private long KipId; - private long ProcessId; - private long ThreadUid; + private long _kipId; + private long _processId; + private long _threadUid; internal CountdownEvent ThreadCounter; @@ -85,7 +85,7 @@ namespace Ryujinx.HLE.HOS internal Keyset KeySet { get; private set; } - private bool HasStarted; + private bool _hasStarted; public Nacp ControlData { get; set; } @@ -95,9 +95,9 @@ namespace Ryujinx.HLE.HOS internal long HidBaseAddress { get; private set; } - public Horizon(Switch Device) + public Horizon(Switch device) { - this.Device = Device; + Device = device; State = new SystemStateMgr(); @@ -125,8 +125,8 @@ namespace Ryujinx.HLE.HOS ContextIdManager = new KContextIdManager(); - KipId = InitialKipId; - ProcessId = InitialProcessId; + _kipId = InitialKipId; + _processId = InitialProcessId; Scheduler.StartAutoPreemptionThread(); @@ -140,90 +140,90 @@ namespace Ryujinx.HLE.HOS //Note: This is not really correct, but with HLE of services, the only memory //region used that is used is Application, so we can use the other ones for anything. - KMemoryRegionManager Region = MemoryRegions[(int)MemoryRegion.NvServices]; + KMemoryRegionManager region = MemoryRegions[(int)MemoryRegion.NvServices]; - ulong HidPa = Region.Address; - ulong FontPa = Region.Address + HidSize; + ulong hidPa = region.Address; + ulong fontPa = region.Address + HidSize; - HidBaseAddress = (long)(HidPa - DramMemoryMap.DramBase); + HidBaseAddress = (long)(hidPa - DramMemoryMap.DramBase); - KPageList HidPageList = new KPageList(); - KPageList FontPageList = new KPageList(); + KPageList hidPageList = new KPageList(); + KPageList fontPageList = new KPageList(); - HidPageList .AddRange(HidPa, HidSize / KMemoryManager.PageSize); - FontPageList.AddRange(FontPa, FontSize / KMemoryManager.PageSize); + hidPageList .AddRange(hidPa, HidSize / KMemoryManager.PageSize); + fontPageList.AddRange(fontPa, FontSize / KMemoryManager.PageSize); - HidSharedMem = new KSharedMemory(HidPageList, 0, 0, MemoryPermission.Read); - FontSharedMem = new KSharedMemory(FontPageList, 0, 0, MemoryPermission.Read); + HidSharedMem = new KSharedMemory(hidPageList, 0, 0, MemoryPermission.Read); + FontSharedMem = new KSharedMemory(fontPageList, 0, 0, MemoryPermission.Read); AppletState = new AppletStateMgr(this); AppletState.SetFocus(true); - Font = new SharedFontManager(Device, (long)(FontPa - DramMemoryMap.DramBase)); + Font = new SharedFontManager(device, (long)(fontPa - DramMemoryMap.DramBase)); VsyncEvent = new KEvent(this); LoadKeySet(); - ContentManager = new ContentManager(Device); + ContentManager = new ContentManager(device); } - public void LoadCart(string ExeFsDir, string RomFsFile = null) + public void LoadCart(string exeFsDir, string romFsFile = null) { - if (RomFsFile != null) + if (romFsFile != null) { - Device.FileSystem.LoadRomFs(RomFsFile); + Device.FileSystem.LoadRomFs(romFsFile); } - string NpdmFileName = Path.Combine(ExeFsDir, "main.npdm"); + string npdmFileName = Path.Combine(exeFsDir, "main.npdm"); - Npdm MetaData = null; + Npdm metaData = null; - if (File.Exists(NpdmFileName)) + if (File.Exists(npdmFileName)) { Logger.PrintInfo(LogClass.Loader, $"Loading main.npdm..."); - using (FileStream Input = new FileStream(NpdmFileName, FileMode.Open)) + using (FileStream input = new FileStream(npdmFileName, FileMode.Open)) { - MetaData = new Npdm(Input); + metaData = new Npdm(input); } } else { Logger.PrintWarning(LogClass.Loader, $"NPDM file not found, using default values!"); - MetaData = GetDefaultNpdm(); + metaData = GetDefaultNpdm(); } - List StaticObjects = new List(); + List staticObjects = new List(); - void LoadNso(string SearchPattern) + void LoadNso(string searchPattern) { - foreach (string File in Directory.GetFiles(ExeFsDir, SearchPattern)) + foreach (string file in Directory.GetFiles(exeFsDir, searchPattern)) { - if (Path.GetExtension(File) != string.Empty) + if (Path.GetExtension(file) != string.Empty) { continue; } - Logger.PrintInfo(LogClass.Loader, $"Loading {Path.GetFileNameWithoutExtension(File)}..."); + Logger.PrintInfo(LogClass.Loader, $"Loading {Path.GetFileNameWithoutExtension(file)}..."); - using (FileStream Input = new FileStream(File, FileMode.Open)) + using (FileStream input = new FileStream(file, FileMode.Open)) { - NxStaticObject StaticObject = new NxStaticObject(Input); + NxStaticObject staticObject = new NxStaticObject(input); - StaticObjects.Add(StaticObject); + staticObjects.Add(staticObject); } } } - if (!MetaData.Is64Bits) + if (!metaData.Is64Bits) { throw new NotImplementedException("32-bit titles are unsupported!"); } - CurrentTitle = MetaData.ACI0.TitleId.ToString("x16"); + CurrentTitle = metaData.Aci0.TitleId.ToString("x16"); LoadNso("rtld"); LoadNso("main"); @@ -232,18 +232,18 @@ namespace Ryujinx.HLE.HOS ContentManager.LoadEntries(); - ProgramLoader.LoadStaticObjects(this, MetaData, StaticObjects.ToArray()); + ProgramLoader.LoadStaticObjects(this, metaData, staticObjects.ToArray()); } - public void LoadXci(string XciFile) + public void LoadXci(string xciFile) { - FileStream File = new FileStream(XciFile, FileMode.Open, FileAccess.Read); + FileStream file = new FileStream(xciFile, FileMode.Open, FileAccess.Read); - Xci Xci = new Xci(KeySet, File); + Xci xci = new Xci(KeySet, file); - (Nca MainNca, Nca ControlNca) = GetXciGameData(Xci); + (Nca mainNca, Nca controlNca) = GetXciGameData(xci); - if (MainNca == null) + if (mainNca == null) { Logger.PrintError(LogClass.Loader, "Unable to load XCI"); @@ -252,23 +252,23 @@ namespace Ryujinx.HLE.HOS ContentManager.LoadEntries(); - LoadNca(MainNca, ControlNca); + LoadNca(mainNca, controlNca); } - private (Nca Main, Nca Control) GetXciGameData(Xci Xci) + private (Nca Main, Nca Control) GetXciGameData(Xci xci) { - if (Xci.SecurePartition == null) + if (xci.SecurePartition == null) { throw new InvalidDataException("Could not find XCI secure partition"); } - Nca MainNca = null; - Nca PatchNca = null; - Nca ControlNca = null; + Nca mainNca = null; + Nca patchNca = null; + Nca controlNca = null; - foreach (PfsFileEntry TicketEntry in Xci.SecurePartition.Files.Where(x => x.Name.EndsWith(".tik"))) + foreach (PfsFileEntry ticketEntry in xci.SecurePartition.Files.Where(x => x.Name.EndsWith(".tik"))) { - Ticket ticket = new Ticket(Xci.SecurePartition.OpenFile(TicketEntry)); + Ticket ticket = new Ticket(xci.SecurePartition.OpenFile(ticketEntry)); if (!KeySet.TitleKeys.ContainsKey(ticket.RightsId)) { @@ -276,107 +276,107 @@ namespace Ryujinx.HLE.HOS } } - foreach (PfsFileEntry FileEntry in Xci.SecurePartition.Files.Where(x => x.Name.EndsWith(".nca"))) + foreach (PfsFileEntry fileEntry in xci.SecurePartition.Files.Where(x => x.Name.EndsWith(".nca"))) { - Stream NcaStream = Xci.SecurePartition.OpenFile(FileEntry); + Stream ncaStream = xci.SecurePartition.OpenFile(fileEntry); - Nca Nca = new Nca(KeySet, NcaStream, true); + Nca nca = new Nca(KeySet, ncaStream, true); - if (Nca.Header.ContentType == ContentType.Program) + if (nca.Header.ContentType == ContentType.Program) { - if (Nca.Sections.Any(x => x?.Type == SectionType.Romfs)) + if (nca.Sections.Any(x => x?.Type == SectionType.Romfs)) { - MainNca = Nca; + mainNca = nca; } - else if (Nca.Sections.Any(x => x?.Type == SectionType.Bktr)) + else if (nca.Sections.Any(x => x?.Type == SectionType.Bktr)) { - PatchNca = Nca; + patchNca = nca; } } - else if (Nca.Header.ContentType == ContentType.Control) + else if (nca.Header.ContentType == ContentType.Control) { - ControlNca = Nca; + controlNca = nca; } } - if (MainNca == null) + if (mainNca == null) { Logger.PrintError(LogClass.Loader, "Could not find an Application NCA in the provided XCI file"); } - MainNca.SetBaseNca(PatchNca); + mainNca.SetBaseNca(patchNca); - if (ControlNca != null) + if (controlNca != null) { - ReadControlData(ControlNca); + ReadControlData(controlNca); } - if (PatchNca != null) + if (patchNca != null) { - PatchNca.SetBaseNca(MainNca); + patchNca.SetBaseNca(mainNca); - return (PatchNca, ControlNca); + return (patchNca, controlNca); } - return (MainNca, ControlNca); + return (mainNca, controlNca); } - public void ReadControlData(Nca ControlNca) + public void ReadControlData(Nca controlNca) { - Romfs ControlRomfs = new Romfs(ControlNca.OpenSection(0, false, FsIntegrityCheckLevel)); + Romfs controlRomfs = new Romfs(controlNca.OpenSection(0, false, FsIntegrityCheckLevel)); - byte[] ControlFile = ControlRomfs.GetFile("/control.nacp"); + byte[] controlFile = controlRomfs.GetFile("/control.nacp"); - BinaryReader Reader = new BinaryReader(new MemoryStream(ControlFile)); + BinaryReader reader = new BinaryReader(new MemoryStream(controlFile)); - ControlData = new Nacp(Reader); + ControlData = new Nacp(reader); } - public void LoadNca(string NcaFile) + public void LoadNca(string ncaFile) { - FileStream File = new FileStream(NcaFile, FileMode.Open, FileAccess.Read); + FileStream file = new FileStream(ncaFile, FileMode.Open, FileAccess.Read); - Nca Nca = new Nca(KeySet, File, true); + Nca nca = new Nca(KeySet, file, true); - LoadNca(Nca, null); + LoadNca(nca, null); } - public void LoadNsp(string NspFile) + public void LoadNsp(string nspFile) { - FileStream File = new FileStream(NspFile, FileMode.Open, FileAccess.Read); + FileStream file = new FileStream(nspFile, FileMode.Open, FileAccess.Read); - Pfs Nsp = new Pfs(File); + Pfs nsp = new Pfs(file); - PfsFileEntry TicketFile = Nsp.Files.FirstOrDefault(x => x.Name.EndsWith(".tik")); + PfsFileEntry ticketFile = nsp.Files.FirstOrDefault(x => x.Name.EndsWith(".tik")); // Load title key from the NSP's ticket in case the user doesn't have a title key file - if (TicketFile != null) + if (ticketFile != null) { - Ticket Ticket = new Ticket(Nsp.OpenFile(TicketFile)); + Ticket ticket = new Ticket(nsp.OpenFile(ticketFile)); - KeySet.TitleKeys[Ticket.RightsId] = Ticket.GetTitleKey(KeySet); + KeySet.TitleKeys[ticket.RightsId] = ticket.GetTitleKey(KeySet); } - Nca MainNca = null; - Nca ControlNca = null; + Nca mainNca = null; + Nca controlNca = null; - foreach (PfsFileEntry NcaFile in Nsp.Files.Where(x => x.Name.EndsWith(".nca"))) + foreach (PfsFileEntry ncaFile in nsp.Files.Where(x => x.Name.EndsWith(".nca"))) { - Nca Nca = new Nca(KeySet, Nsp.OpenFile(NcaFile), true); + Nca nca = new Nca(KeySet, nsp.OpenFile(ncaFile), true); - if (Nca.Header.ContentType == ContentType.Program) + if (nca.Header.ContentType == ContentType.Program) { - MainNca = Nca; + mainNca = nca; } - else if (Nca.Header.ContentType == ContentType.Control) + else if (nca.Header.ContentType == ContentType.Control) { - ControlNca = Nca; + controlNca = nca; } } - if (MainNca != null) + if (mainNca != null) { - LoadNca(MainNca, ControlNca); + LoadNca(mainNca, controlNca); return; } @@ -384,100 +384,100 @@ namespace Ryujinx.HLE.HOS Logger.PrintError(LogClass.Loader, "Could not find an Application NCA in the provided NSP file"); } - public void LoadNca(Nca MainNca, Nca ControlNca) + public void LoadNca(Nca mainNca, Nca controlNca) { - if (MainNca.Header.ContentType != ContentType.Program) + if (mainNca.Header.ContentType != ContentType.Program) { Logger.PrintError(LogClass.Loader, "Selected NCA is not a \"Program\" NCA"); return; } - Stream RomfsStream = MainNca.OpenSection(ProgramPartitionType.Data, false, FsIntegrityCheckLevel); - Stream ExefsStream = MainNca.OpenSection(ProgramPartitionType.Code, false, FsIntegrityCheckLevel); + Stream romfsStream = mainNca.OpenSection(ProgramPartitionType.Data, false, FsIntegrityCheckLevel); + Stream exefsStream = mainNca.OpenSection(ProgramPartitionType.Code, false, FsIntegrityCheckLevel); - if (ExefsStream == null) + if (exefsStream == null) { Logger.PrintError(LogClass.Loader, "No ExeFS found in NCA"); return; } - if (RomfsStream == null) + if (romfsStream == null) { Logger.PrintWarning(LogClass.Loader, "No RomFS found in NCA"); } else { - Device.FileSystem.SetRomFs(RomfsStream); + Device.FileSystem.SetRomFs(romfsStream); } - Pfs Exefs = new Pfs(ExefsStream); + Pfs exefs = new Pfs(exefsStream); - Npdm MetaData = null; + Npdm metaData = null; - if (Exefs.FileExists("main.npdm")) + if (exefs.FileExists("main.npdm")) { Logger.PrintInfo(LogClass.Loader, "Loading main.npdm..."); - MetaData = new Npdm(Exefs.OpenFile("main.npdm")); + metaData = new Npdm(exefs.OpenFile("main.npdm")); } else { Logger.PrintWarning(LogClass.Loader, $"NPDM file not found, using default values!"); - MetaData = GetDefaultNpdm(); + metaData = GetDefaultNpdm(); } - List StaticObjects = new List(); + List staticObjects = new List(); - void LoadNso(string Filename) + void LoadNso(string filename) { - foreach (PfsFileEntry File in Exefs.Files.Where(x => x.Name.StartsWith(Filename))) + foreach (PfsFileEntry file in exefs.Files.Where(x => x.Name.StartsWith(filename))) { - if (Path.GetExtension(File.Name) != string.Empty) + if (Path.GetExtension(file.Name) != string.Empty) { continue; } - Logger.PrintInfo(LogClass.Loader, $"Loading {Filename}..."); + Logger.PrintInfo(LogClass.Loader, $"Loading {filename}..."); - NxStaticObject StaticObject = new NxStaticObject(Exefs.OpenFile(File)); + NxStaticObject staticObject = new NxStaticObject(exefs.OpenFile(file)); - StaticObjects.Add(StaticObject); + staticObjects.Add(staticObject); } } Nacp ReadControlData() { - Romfs ControlRomfs = new Romfs(ControlNca.OpenSection(0, false, FsIntegrityCheckLevel)); + Romfs controlRomfs = new Romfs(controlNca.OpenSection(0, false, FsIntegrityCheckLevel)); - byte[] ControlFile = ControlRomfs.GetFile("/control.nacp"); + byte[] controlFile = controlRomfs.GetFile("/control.nacp"); - BinaryReader Reader = new BinaryReader(new MemoryStream(ControlFile)); + BinaryReader reader = new BinaryReader(new MemoryStream(controlFile)); - Nacp ControlData = new Nacp(Reader); + Nacp controlData = new Nacp(reader); - CurrentTitle = ControlData.Languages[(int)State.DesiredTitleLanguage].Title; + CurrentTitle = controlData.Languages[(int)State.DesiredTitleLanguage].Title; if (string.IsNullOrWhiteSpace(CurrentTitle)) { - CurrentTitle = ControlData.Languages.ToList().Find(x => !string.IsNullOrWhiteSpace(x.Title)).Title; + CurrentTitle = controlData.Languages.ToList().Find(x => !string.IsNullOrWhiteSpace(x.Title)).Title; } - return ControlData; + return controlData; } - if (ControlNca != null) + if (controlNca != null) { ReadControlData(); } else { - CurrentTitle = MetaData.ACI0.TitleId.ToString("x16"); + CurrentTitle = metaData.Aci0.TitleId.ToString("x16"); } - if (!MetaData.Is64Bits) + if (!metaData.Is64Bits) { throw new NotImplementedException("32-bit titles are not supported!"); } @@ -489,67 +489,67 @@ namespace Ryujinx.HLE.HOS ContentManager.LoadEntries(); - ProgramLoader.LoadStaticObjects(this, MetaData, StaticObjects.ToArray()); + ProgramLoader.LoadStaticObjects(this, metaData, staticObjects.ToArray()); } - public void LoadProgram(string FilePath) + public void LoadProgram(string filePath) { - Npdm MetaData = GetDefaultNpdm(); + Npdm metaData = GetDefaultNpdm(); - bool IsNro = Path.GetExtension(FilePath).ToLower() == ".nro"; + bool isNro = Path.GetExtension(filePath).ToLower() == ".nro"; - using (FileStream Input = new FileStream(FilePath, FileMode.Open)) + using (FileStream input = new FileStream(filePath, FileMode.Open)) { - IExecutable StaticObject = IsNro - ? (IExecutable)new NxRelocatableObject(Input) - : (IExecutable)new NxStaticObject(Input); + IExecutable staticObject = isNro + ? (IExecutable)new NxRelocatableObject(input) + : new NxStaticObject(input); - ProgramLoader.LoadStaticObjects(this, MetaData, new IExecutable[] { StaticObject }); + ProgramLoader.LoadStaticObjects(this, metaData, new IExecutable[] { staticObject }); } } private Npdm GetDefaultNpdm() { - Assembly Asm = Assembly.GetCallingAssembly(); + Assembly asm = Assembly.GetCallingAssembly(); - using (Stream NpdmStream = Asm.GetManifestResourceStream("Ryujinx.HLE.Homebrew.npdm")) + using (Stream npdmStream = asm.GetManifestResourceStream("Ryujinx.HLE.Homebrew.npdm")) { - return new Npdm(NpdmStream); + return new Npdm(npdmStream); } } public void LoadKeySet() { - string KeyFile = null; - string TitleKeyFile = null; - string ConsoleKeyFile = null; + string keyFile = null; + string titleKeyFile = null; + string consoleKeyFile = null; - string Home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + string home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); - LoadSetAtPath(Path.Combine(Home, ".switch")); + LoadSetAtPath(Path.Combine(home, ".switch")); LoadSetAtPath(Device.FileSystem.GetSystemPath()); - KeySet = ExternalKeys.ReadKeyFile(KeyFile, TitleKeyFile, ConsoleKeyFile); + KeySet = ExternalKeys.ReadKeyFile(keyFile, titleKeyFile, consoleKeyFile); - void LoadSetAtPath(string BasePath) + void LoadSetAtPath(string basePath) { - string LocalKeyFile = Path.Combine(BasePath, "prod.keys"); - string LocalTitleKeyFile = Path.Combine(BasePath, "title.keys"); - string LocalConsoleKeyFile = Path.Combine(BasePath, "console.keys"); + string localKeyFile = Path.Combine(basePath, "prod.keys"); + string localTitleKeyFile = Path.Combine(basePath, "title.keys"); + string localConsoleKeyFile = Path.Combine(basePath, "console.keys"); - if (File.Exists(LocalKeyFile)) + if (File.Exists(localKeyFile)) { - KeyFile = LocalKeyFile; + keyFile = localKeyFile; } - if (File.Exists(LocalTitleKeyFile)) + if (File.Exists(localTitleKeyFile)) { - TitleKeyFile = LocalTitleKeyFile; + titleKeyFile = localTitleKeyFile; } - if (File.Exists(LocalConsoleKeyFile)) + if (File.Exists(localConsoleKeyFile)) { - ConsoleKeyFile = LocalConsoleKeyFile; + consoleKeyFile = localConsoleKeyFile; } } } @@ -561,22 +561,22 @@ namespace Ryujinx.HLE.HOS internal long GetThreadUid() { - return Interlocked.Increment(ref ThreadUid) - 1; + return Interlocked.Increment(ref _threadUid) - 1; } internal long GetKipId() { - return Interlocked.Increment(ref KipId) - 1; + return Interlocked.Increment(ref _kipId) - 1; } internal long GetProcessId() { - return Interlocked.Increment(ref ProcessId) - 1; + return Interlocked.Increment(ref _processId) - 1; } public void EnableMultiCoreScheduling() { - if (!HasStarted) + if (!_hasStarted) { Scheduler.MultiCoreScheduling = true; } @@ -584,7 +584,7 @@ namespace Ryujinx.HLE.HOS public void DisableMultiCoreScheduling() { - if (!HasStarted) + if (!_hasStarted) { Scheduler.MultiCoreScheduling = false; } @@ -595,16 +595,16 @@ namespace Ryujinx.HLE.HOS Dispose(true); } - protected virtual void Dispose(bool Disposing) + protected virtual void Dispose(bool disposing) { - if (Disposing) + if (disposing) { //Force all threads to exit. lock (Processes) { - foreach (KProcess Process in Processes.Values) + foreach (KProcess process in Processes.Values) { - Process.StopAllThreads(); + process.StopAllThreads(); } } diff --git a/Ryujinx.HLE/HOS/IdDictionary.cs b/Ryujinx.HLE/HOS/IdDictionary.cs index 03d15498..c6356725 100644 --- a/Ryujinx.HLE/HOS/IdDictionary.cs +++ b/Ryujinx.HLE/HOS/IdDictionary.cs @@ -6,56 +6,56 @@ namespace Ryujinx.HLE.HOS { class IdDictionary { - private ConcurrentDictionary Objs; + private ConcurrentDictionary _objs; public IdDictionary() { - Objs = new ConcurrentDictionary(); + _objs = new ConcurrentDictionary(); } - public bool Add(int Id, object Data) + public bool Add(int id, object data) { - return Objs.TryAdd(Id, Data); + return _objs.TryAdd(id, data); } - public int Add(object Data) + public int Add(object data) { - for (int Id = 1; Id < int.MaxValue; Id++) + for (int id = 1; id < int.MaxValue; id++) { - if (Objs.TryAdd(Id, Data)) + if (_objs.TryAdd(id, data)) { - return Id; + return id; } } throw new InvalidOperationException(); } - public object GetData(int Id) + public object GetData(int id) { - if (Objs.TryGetValue(Id, out object Data)) + if (_objs.TryGetValue(id, out object data)) { - return Data; + return data; } return null; } - public T GetData(int Id) + public T GetData(int id) { - if (Objs.TryGetValue(Id, out object Data) && Data is T) + if (_objs.TryGetValue(id, out object data) && data is T) { - return (T)Data; + return (T)data; } return default(T); } - public object Delete(int Id) + public object Delete(int id) { - if (Objs.TryRemove(Id, out object Obj)) + if (_objs.TryRemove(id, out object obj)) { - return Obj; + return obj; } return null; @@ -63,11 +63,11 @@ namespace Ryujinx.HLE.HOS public ICollection Clear() { - ICollection Values = Objs.Values; + ICollection values = _objs.Values; - Objs.Clear(); + _objs.Clear(); - return Values; + return values; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Ipc/IpcBuffDesc.cs b/Ryujinx.HLE/HOS/Ipc/IpcBuffDesc.cs index 346d696e..dddd2671 100644 --- a/Ryujinx.HLE/HOS/Ipc/IpcBuffDesc.cs +++ b/Ryujinx.HLE/HOS/Ipc/IpcBuffDesc.cs @@ -8,20 +8,20 @@ namespace Ryujinx.HLE.HOS.Ipc public long Size { get; private set; } public int Flags { get; private set; } - public IpcBuffDesc(BinaryReader Reader) + public IpcBuffDesc(BinaryReader reader) { - long Word0 = Reader.ReadUInt32(); - long Word1 = Reader.ReadUInt32(); - long Word2 = Reader.ReadUInt32(); + long word0 = reader.ReadUInt32(); + long word1 = reader.ReadUInt32(); + long word2 = reader.ReadUInt32(); - Position = Word1; - Position |= (Word2 << 4) & 0x0f00000000; - Position |= (Word2 << 34) & 0x7000000000; + Position = word1; + Position |= (word2 << 4) & 0x0f00000000; + Position |= (word2 << 34) & 0x7000000000; - Size = Word0; - Size |= (Word2 << 8) & 0xf00000000; + Size = word0; + Size |= (word2 << 8) & 0xf00000000; - Flags = (int)Word2 & 3; + Flags = (int)word2 & 3; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Ipc/IpcHandleDesc.cs b/Ryujinx.HLE/HOS/Ipc/IpcHandleDesc.cs index 081b5695..5b1d5788 100644 --- a/Ryujinx.HLE/HOS/Ipc/IpcHandleDesc.cs +++ b/Ryujinx.HLE/HOS/Ipc/IpcHandleDesc.cs @@ -12,80 +12,80 @@ namespace Ryujinx.HLE.HOS.Ipc public int[] ToCopy { get; private set; } public int[] ToMove { get; private set; } - public IpcHandleDesc(BinaryReader Reader) + public IpcHandleDesc(BinaryReader reader) { - int Word = Reader.ReadInt32(); + int word = reader.ReadInt32(); - HasPId = (Word & 1) != 0; + HasPId = (word & 1) != 0; - ToCopy = new int[(Word >> 1) & 0xf]; - ToMove = new int[(Word >> 5) & 0xf]; + ToCopy = new int[(word >> 1) & 0xf]; + ToMove = new int[(word >> 5) & 0xf]; - PId = HasPId ? Reader.ReadInt64() : 0; + PId = HasPId ? reader.ReadInt64() : 0; - for (int Index = 0; Index < ToCopy.Length; Index++) + for (int index = 0; index < ToCopy.Length; index++) { - ToCopy[Index] = Reader.ReadInt32(); + ToCopy[index] = reader.ReadInt32(); } - for (int Index = 0; Index < ToMove.Length; Index++) + for (int index = 0; index < ToMove.Length; index++) { - ToMove[Index] = Reader.ReadInt32(); + ToMove[index] = reader.ReadInt32(); } } - public IpcHandleDesc(int[] Copy, int[] Move) + public IpcHandleDesc(int[] copy, int[] move) { - ToCopy = Copy ?? throw new ArgumentNullException(nameof(Copy)); - ToMove = Move ?? throw new ArgumentNullException(nameof(Move)); + ToCopy = copy ?? throw new ArgumentNullException(nameof(copy)); + ToMove = move ?? throw new ArgumentNullException(nameof(move)); } - public IpcHandleDesc(int[] Copy, int[] Move, long PId) : this(Copy, Move) + public IpcHandleDesc(int[] copy, int[] move, long pId) : this(copy, move) { - this.PId = PId; + PId = pId; HasPId = true; } - public static IpcHandleDesc MakeCopy(params int[] Handles) + public static IpcHandleDesc MakeCopy(params int[] handles) { - return new IpcHandleDesc(Handles, new int[0]); + return new IpcHandleDesc(handles, new int[0]); } - public static IpcHandleDesc MakeMove(params int[] Handles) + public static IpcHandleDesc MakeMove(params int[] handles) { - return new IpcHandleDesc(new int[0], Handles); + return new IpcHandleDesc(new int[0], handles); } public byte[] GetBytes() { - using (MemoryStream MS = new MemoryStream()) + using (MemoryStream ms = new MemoryStream()) { - BinaryWriter Writer = new BinaryWriter(MS); + BinaryWriter writer = new BinaryWriter(ms); - int Word = HasPId ? 1 : 0; + int word = HasPId ? 1 : 0; - Word |= (ToCopy.Length & 0xf) << 1; - Word |= (ToMove.Length & 0xf) << 5; + word |= (ToCopy.Length & 0xf) << 1; + word |= (ToMove.Length & 0xf) << 5; - Writer.Write(Word); + writer.Write(word); if (HasPId) { - Writer.Write((long)PId); + writer.Write(PId); } - foreach (int Handle in ToCopy) + foreach (int handle in ToCopy) { - Writer.Write(Handle); + writer.Write(handle); } - foreach (int Handle in ToMove) + foreach (int handle in ToMove) { - Writer.Write(Handle); + writer.Write(handle); } - return MS.ToArray(); + return ms.ToArray(); } } } diff --git a/Ryujinx.HLE/HOS/Ipc/IpcHandler.cs b/Ryujinx.HLE/HOS/Ipc/IpcHandler.cs index 860c8242..e5d19236 100644 --- a/Ryujinx.HLE/HOS/Ipc/IpcHandler.cs +++ b/Ryujinx.HLE/HOS/Ipc/IpcHandler.cs @@ -8,61 +8,61 @@ namespace Ryujinx.HLE.HOS.Ipc static class IpcHandler { public static long IpcCall( - Switch Device, - KProcess Process, - MemoryManager Memory, - KSession Session, - IpcMessage Request, - long CmdPtr) + Switch device, + KProcess process, + MemoryManager memory, + KSession session, + IpcMessage request, + long cmdPtr) { - IpcMessage Response = new IpcMessage(); + IpcMessage response = new IpcMessage(); - using (MemoryStream Raw = new MemoryStream(Request.RawData)) + using (MemoryStream raw = new MemoryStream(request.RawData)) { - BinaryReader ReqReader = new BinaryReader(Raw); + BinaryReader reqReader = new BinaryReader(raw); - if (Request.Type == IpcMessageType.Request || - Request.Type == IpcMessageType.RequestWithContext) + if (request.Type == IpcMessageType.Request || + request.Type == IpcMessageType.RequestWithContext) { - Response.Type = IpcMessageType.Response; + response.Type = IpcMessageType.Response; - using (MemoryStream ResMS = new MemoryStream()) + using (MemoryStream resMs = new MemoryStream()) { - BinaryWriter ResWriter = new BinaryWriter(ResMS); + BinaryWriter resWriter = new BinaryWriter(resMs); - ServiceCtx Context = new ServiceCtx( - Device, - Process, - Memory, - Session, - Request, - Response, - ReqReader, - ResWriter); + ServiceCtx context = new ServiceCtx( + device, + process, + memory, + session, + request, + response, + reqReader, + resWriter); - Session.Service.CallMethod(Context); + session.Service.CallMethod(context); - Response.RawData = ResMS.ToArray(); + response.RawData = resMs.ToArray(); } } - else if (Request.Type == IpcMessageType.Control || - Request.Type == IpcMessageType.ControlWithContext) + else if (request.Type == IpcMessageType.Control || + request.Type == IpcMessageType.ControlWithContext) { - long Magic = ReqReader.ReadInt64(); - long CmdId = ReqReader.ReadInt64(); + long magic = reqReader.ReadInt64(); + long cmdId = reqReader.ReadInt64(); - switch (CmdId) + switch (cmdId) { case 0: { - Request = FillResponse(Response, 0, Session.Service.ConvertToDomain()); + request = FillResponse(response, 0, session.Service.ConvertToDomain()); break; } case 3: { - Request = FillResponse(Response, 0, 0x500); + request = FillResponse(response, 0, 0x500); break; } @@ -71,73 +71,73 @@ namespace Ryujinx.HLE.HOS.Ipc case 2: case 4: { - int Unknown = ReqReader.ReadInt32(); + int unknown = reqReader.ReadInt32(); - if (Process.HandleTable.GenerateHandle(Session, out int Handle) != KernelResult.Success) + if (process.HandleTable.GenerateHandle(session, out int handle) != KernelResult.Success) { throw new InvalidOperationException("Out of handles!"); } - Response.HandleDesc = IpcHandleDesc.MakeMove(Handle); + response.HandleDesc = IpcHandleDesc.MakeMove(handle); - Request = FillResponse(Response, 0); + request = FillResponse(response, 0); break; } - default: throw new NotImplementedException(CmdId.ToString()); + default: throw new NotImplementedException(cmdId.ToString()); } } - else if (Request.Type == IpcMessageType.CloseSession) + else if (request.Type == IpcMessageType.CloseSession) { //TODO } else { - throw new NotImplementedException(Request.Type.ToString()); + throw new NotImplementedException(request.Type.ToString()); } - Memory.WriteBytes(CmdPtr, Response.GetBytes(CmdPtr)); + memory.WriteBytes(cmdPtr, response.GetBytes(cmdPtr)); } return 0; } - private static IpcMessage FillResponse(IpcMessage Response, long Result, params int[] Values) + private static IpcMessage FillResponse(IpcMessage response, long result, params int[] values) { - using (MemoryStream MS = new MemoryStream()) + using (MemoryStream ms = new MemoryStream()) { - BinaryWriter Writer = new BinaryWriter(MS); + BinaryWriter writer = new BinaryWriter(ms); - foreach (int Value in Values) + foreach (int value in values) { - Writer.Write(Value); + writer.Write(value); } - return FillResponse(Response, Result, MS.ToArray()); + return FillResponse(response, result, ms.ToArray()); } } - private static IpcMessage FillResponse(IpcMessage Response, long Result, byte[] Data = null) + private static IpcMessage FillResponse(IpcMessage response, long result, byte[] data = null) { - Response.Type = IpcMessageType.Response; + response.Type = IpcMessageType.Response; - using (MemoryStream MS = new MemoryStream()) + using (MemoryStream ms = new MemoryStream()) { - BinaryWriter Writer = new BinaryWriter(MS); + BinaryWriter writer = new BinaryWriter(ms); - Writer.Write(IpcMagic.Sfco); - Writer.Write(Result); + writer.Write(IpcMagic.Sfco); + writer.Write(result); - if (Data != null) + if (data != null) { - Writer.Write(Data); + writer.Write(data); } - Response.RawData = MS.ToArray(); + response.RawData = ms.ToArray(); } - return Response; + return response; } } } diff --git a/Ryujinx.HLE/HOS/Ipc/IpcMessage.cs b/Ryujinx.HLE/HOS/Ipc/IpcMessage.cs index 02900444..85b6820a 100644 --- a/Ryujinx.HLE/HOS/Ipc/IpcMessage.cs +++ b/Ryujinx.HLE/HOS/Ipc/IpcMessage.cs @@ -30,183 +30,185 @@ namespace Ryujinx.HLE.HOS.Ipc ObjectIds = new List(); } - public IpcMessage(byte[] Data, long CmdPtr) : this() + public IpcMessage(byte[] data, long cmdPtr) : this() { - using (MemoryStream MS = new MemoryStream(Data)) + using (MemoryStream ms = new MemoryStream(data)) { - BinaryReader Reader = new BinaryReader(MS); + BinaryReader reader = new BinaryReader(ms); - Initialize(Reader, CmdPtr); + Initialize(reader, cmdPtr); } } - private void Initialize(BinaryReader Reader, long CmdPtr) + private void Initialize(BinaryReader reader, long cmdPtr) { - int Word0 = Reader.ReadInt32(); - int Word1 = Reader.ReadInt32(); + int word0 = reader.ReadInt32(); + int word1 = reader.ReadInt32(); - Type = (IpcMessageType)(Word0 & 0xffff); + Type = (IpcMessageType)(word0 & 0xffff); - int PtrBuffCount = (Word0 >> 16) & 0xf; - int SendBuffCount = (Word0 >> 20) & 0xf; - int RecvBuffCount = (Word0 >> 24) & 0xf; - int XchgBuffCount = (Word0 >> 28) & 0xf; + int ptrBuffCount = (word0 >> 16) & 0xf; + int sendBuffCount = (word0 >> 20) & 0xf; + int recvBuffCount = (word0 >> 24) & 0xf; + int xchgBuffCount = (word0 >> 28) & 0xf; - int RawDataSize = (Word1 >> 0) & 0x3ff; - int RecvListFlags = (Word1 >> 10) & 0xf; - bool HndDescEnable = ((Word1 >> 31) & 0x1) != 0; + int rawDataSize = (word1 >> 0) & 0x3ff; + int recvListFlags = (word1 >> 10) & 0xf; + bool hndDescEnable = ((word1 >> 31) & 0x1) != 0; - if (HndDescEnable) + if (hndDescEnable) { - HandleDesc = new IpcHandleDesc(Reader); + HandleDesc = new IpcHandleDesc(reader); } - for (int Index = 0; Index < PtrBuffCount; Index++) + for (int index = 0; index < ptrBuffCount; index++) { - PtrBuff.Add(new IpcPtrBuffDesc(Reader)); + PtrBuff.Add(new IpcPtrBuffDesc(reader)); } - void ReadBuff(List Buff, int Count) + void ReadBuff(List buff, int count) { - for (int Index = 0; Index < Count; Index++) + for (int index = 0; index < count; index++) { - Buff.Add(new IpcBuffDesc(Reader)); + buff.Add(new IpcBuffDesc(reader)); } } - ReadBuff(SendBuff, SendBuffCount); - ReadBuff(ReceiveBuff, RecvBuffCount); - ReadBuff(ExchangeBuff, XchgBuffCount); + ReadBuff(SendBuff, sendBuffCount); + ReadBuff(ReceiveBuff, recvBuffCount); + ReadBuff(ExchangeBuff, xchgBuffCount); - RawDataSize *= 4; + rawDataSize *= 4; - long RecvListPos = Reader.BaseStream.Position + RawDataSize; + long recvListPos = reader.BaseStream.Position + rawDataSize; - long Pad0 = GetPadSize16(Reader.BaseStream.Position + CmdPtr); + long pad0 = GetPadSize16(reader.BaseStream.Position + cmdPtr); - Reader.BaseStream.Seek(Pad0, SeekOrigin.Current); + reader.BaseStream.Seek(pad0, SeekOrigin.Current); - int RecvListCount = RecvListFlags - 2; + int recvListCount = recvListFlags - 2; - if (RecvListCount == 0) + if (recvListCount == 0) { - RecvListCount = 1; + recvListCount = 1; } - else if (RecvListCount < 0) + else if (recvListCount < 0) { - RecvListCount = 0; + recvListCount = 0; } - RawData = Reader.ReadBytes(RawDataSize); + RawData = reader.ReadBytes(rawDataSize); - Reader.BaseStream.Seek(RecvListPos, SeekOrigin.Begin); + reader.BaseStream.Seek(recvListPos, SeekOrigin.Begin); - for (int Index = 0; Index < RecvListCount; Index++) + for (int index = 0; index < recvListCount; index++) { - RecvListBuff.Add(new IpcRecvListBuffDesc(Reader)); + RecvListBuff.Add(new IpcRecvListBuffDesc(reader)); } } - public byte[] GetBytes(long CmdPtr) + public byte[] GetBytes(long cmdPtr) { - using (MemoryStream MS = new MemoryStream()) + using (MemoryStream ms = new MemoryStream()) { - BinaryWriter Writer = new BinaryWriter(MS); + BinaryWriter writer = new BinaryWriter(ms); - int Word0; - int Word1; + int word0; + int word1; - Word0 = (int)Type; - Word0 |= (PtrBuff.Count & 0xf) << 16; - Word0 |= (SendBuff.Count & 0xf) << 20; - Word0 |= (ReceiveBuff.Count & 0xf) << 24; - Word0 |= (ExchangeBuff.Count & 0xf) << 28; + word0 = (int)Type; + word0 |= (PtrBuff.Count & 0xf) << 16; + word0 |= (SendBuff.Count & 0xf) << 20; + word0 |= (ReceiveBuff.Count & 0xf) << 24; + word0 |= (ExchangeBuff.Count & 0xf) << 28; - byte[] HandleData = new byte[0]; + byte[] handleData = new byte[0]; if (HandleDesc != null) { - HandleData = HandleDesc.GetBytes(); + handleData = HandleDesc.GetBytes(); } - int DataLength = RawData?.Length ?? 0; + int dataLength = RawData?.Length ?? 0; - int Pad0 = (int)GetPadSize16(CmdPtr + 8 + HandleData.Length); + int pad0 = (int)GetPadSize16(cmdPtr + 8 + handleData.Length); //Apparently, padding after Raw Data is 16 bytes, however when there is //padding before Raw Data too, we need to subtract the size of this padding. //This is the weirdest padding I've seen so far... - int Pad1 = 0x10 - Pad0; + int pad1 = 0x10 - pad0; - DataLength = (DataLength + Pad0 + Pad1) / 4; + dataLength = (dataLength + pad0 + pad1) / 4; - Word1 = DataLength & 0x3ff; + word1 = dataLength & 0x3ff; if (HandleDesc != null) { - Word1 |= 1 << 31; + word1 |= 1 << 31; } - Writer.Write(Word0); - Writer.Write(Word1); - Writer.Write(HandleData); + writer.Write(word0); + writer.Write(word1); + writer.Write(handleData); - MS.Seek(Pad0, SeekOrigin.Current); + ms.Seek(pad0, SeekOrigin.Current); if (RawData != null) { - Writer.Write(RawData); + writer.Write(RawData); } - Writer.Write(new byte[Pad1]); + writer.Write(new byte[pad1]); - return MS.ToArray(); + return ms.ToArray(); } } - private long GetPadSize16(long Position) + private long GetPadSize16(long position) { - if ((Position & 0xf) != 0) + if ((position & 0xf) != 0) { - return 0x10 - (Position & 0xf); + return 0x10 - (position & 0xf); } return 0; } - public (long Position, long Size) GetBufferType0x21(int Index = 0) + // ReSharper disable once InconsistentNaming + public (long Position, long Size) GetBufferType0x21(int index = 0) { - if (PtrBuff.Count > Index && - PtrBuff[Index].Position != 0 && - PtrBuff[Index].Size != 0) + if (PtrBuff.Count > index && + PtrBuff[index].Position != 0 && + PtrBuff[index].Size != 0) { - return (PtrBuff[Index].Position, PtrBuff[Index].Size); + return (PtrBuff[index].Position, PtrBuff[index].Size); } - if (SendBuff.Count > Index && - SendBuff[Index].Position != 0 && - SendBuff[Index].Size != 0) + if (SendBuff.Count > index && + SendBuff[index].Position != 0 && + SendBuff[index].Size != 0) { - return (SendBuff[Index].Position, SendBuff[Index].Size); + return (SendBuff[index].Position, SendBuff[index].Size); } return (0, 0); } - public (long Position, long Size) GetBufferType0x22(int Index = 0) + // ReSharper disable once InconsistentNaming + public (long Position, long Size) GetBufferType0x22(int index = 0) { - if (RecvListBuff.Count > Index && - RecvListBuff[Index].Position != 0 && - RecvListBuff[Index].Size != 0) + if (RecvListBuff.Count > index && + RecvListBuff[index].Position != 0 && + RecvListBuff[index].Size != 0) { - return (RecvListBuff[Index].Position, RecvListBuff[Index].Size); + return (RecvListBuff[index].Position, RecvListBuff[index].Size); } - if (ReceiveBuff.Count > Index && - ReceiveBuff[Index].Position != 0 && - ReceiveBuff[Index].Size != 0) + if (ReceiveBuff.Count > index && + ReceiveBuff[index].Position != 0 && + ReceiveBuff[index].Size != 0) { - return (ReceiveBuff[Index].Position, ReceiveBuff[Index].Size); + return (ReceiveBuff[index].Position, ReceiveBuff[index].Size); } return (0, 0); diff --git a/Ryujinx.HLE/HOS/Ipc/IpcPtrBuffDesc.cs b/Ryujinx.HLE/HOS/Ipc/IpcPtrBuffDesc.cs index 21f5d3bc..cdc43f17 100644 --- a/Ryujinx.HLE/HOS/Ipc/IpcPtrBuffDesc.cs +++ b/Ryujinx.HLE/HOS/Ipc/IpcPtrBuffDesc.cs @@ -8,19 +8,19 @@ namespace Ryujinx.HLE.HOS.Ipc public int Index { get; private set; } public long Size { get; private set; } - public IpcPtrBuffDesc(BinaryReader Reader) + public IpcPtrBuffDesc(BinaryReader reader) { - long Word0 = Reader.ReadUInt32(); - long Word1 = Reader.ReadUInt32(); + long word0 = reader.ReadUInt32(); + long word1 = reader.ReadUInt32(); - Position = Word1; - Position |= (Word0 << 20) & 0x0f00000000; - Position |= (Word0 << 30) & 0x7000000000; + Position = word1; + Position |= (word0 << 20) & 0x0f00000000; + Position |= (word0 << 30) & 0x7000000000; - Index = ((int)Word0 >> 0) & 0x03f; - Index |= ((int)Word0 >> 3) & 0x1c0; + Index = ((int)word0 >> 0) & 0x03f; + Index |= ((int)word0 >> 3) & 0x1c0; - Size = (ushort)(Word0 >> 16); + Size = (ushort)(word0 >> 16); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Ipc/IpcRecvListBuffDesc.cs b/Ryujinx.HLE/HOS/Ipc/IpcRecvListBuffDesc.cs index 1d0a8c80..3fd92f02 100644 --- a/Ryujinx.HLE/HOS/Ipc/IpcRecvListBuffDesc.cs +++ b/Ryujinx.HLE/HOS/Ipc/IpcRecvListBuffDesc.cs @@ -7,13 +7,13 @@ namespace Ryujinx.HLE.HOS.Ipc public long Position { get; private set; } public long Size { get; private set; } - public IpcRecvListBuffDesc(BinaryReader Reader) + public IpcRecvListBuffDesc(BinaryReader reader) { - long Value = Reader.ReadInt64(); + long value = reader.ReadInt64(); - Position = Value & 0xffffffffffff; + Position = value & 0xffffffffffff; - Size = (ushort)(Value >> 48); + Size = (ushort)(value >> 48); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Ipc/ServiceProcessRequest.cs b/Ryujinx.HLE/HOS/Ipc/ServiceProcessRequest.cs index da4a7e75..b3aaa219 100644 --- a/Ryujinx.HLE/HOS/Ipc/ServiceProcessRequest.cs +++ b/Ryujinx.HLE/HOS/Ipc/ServiceProcessRequest.cs @@ -1,4 +1,4 @@ namespace Ryujinx.HLE.HOS.Ipc { - delegate long ServiceProcessRequest(ServiceCtx Context); + delegate long ServiceProcessRequest(ServiceCtx context); } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/HleCoreManager.cs b/Ryujinx.HLE/HOS/Kernel/HleCoreManager.cs index 6a424cf2..04017d6d 100644 --- a/Ryujinx.HLE/HOS/Kernel/HleCoreManager.cs +++ b/Ryujinx.HLE/HOS/Kernel/HleCoreManager.cs @@ -17,49 +17,49 @@ namespace Ryujinx.HLE.HOS.Kernel } } - private ConcurrentDictionary Threads; + private ConcurrentDictionary _threads; public HleCoreManager() { - Threads = new ConcurrentDictionary(); + _threads = new ConcurrentDictionary(); } - public void Set(Thread Thread) + public void Set(Thread thread) { - GetThread(Thread).Event.Set(); + GetThread(thread).Event.Set(); } - public void Reset(Thread Thread) + public void Reset(Thread thread) { - GetThread(Thread).Event.Reset(); + GetThread(thread).Event.Reset(); } - public void Wait(Thread Thread) + public void Wait(Thread thread) { - PausableThread PausableThread = GetThread(Thread); + PausableThread pausableThread = GetThread(thread); - if (!PausableThread.IsExiting) + if (!pausableThread.IsExiting) { - PausableThread.Event.WaitOne(); + pausableThread.Event.WaitOne(); } } - public void Exit(Thread Thread) + public void Exit(Thread thread) { - GetThread(Thread).IsExiting = true; + GetThread(thread).IsExiting = true; } - private PausableThread GetThread(Thread Thread) + private PausableThread GetThread(Thread thread) { - return Threads.GetOrAdd(Thread, (Key) => new PausableThread()); + return _threads.GetOrAdd(thread, (key) => new PausableThread()); } - public void RemoveThread(Thread Thread) + public void RemoveThread(Thread thread) { - if (Threads.TryRemove(Thread, out PausableThread PausableThread)) + if (_threads.TryRemove(thread, out PausableThread pausableThread)) { - PausableThread.Event.Set(); - PausableThread.Event.Dispose(); + pausableThread.Event.Set(); + pausableThread.Event.Dispose(); } } } diff --git a/Ryujinx.HLE/HOS/Kernel/HleProcessDebugger.cs b/Ryujinx.HLE/HOS/Kernel/HleProcessDebugger.cs index a6053b1b..fd3ac1f5 100644 --- a/Ryujinx.HLE/HOS/Kernel/HleProcessDebugger.cs +++ b/Ryujinx.HLE/HOS/Kernel/HleProcessDebugger.cs @@ -14,7 +14,7 @@ namespace Ryujinx.HLE.HOS.Kernel { private const int Mod0 = 'M' << 0 | 'O' << 8 | 'D' << 16 | '0' << 24; - private KProcess Owner; + private KProcess _owner; private class Image { @@ -22,130 +22,130 @@ namespace Ryujinx.HLE.HOS.Kernel public ElfSymbol[] Symbols { get; private set; } - public Image(long BaseAddress, ElfSymbol[] Symbols) + public Image(long baseAddress, ElfSymbol[] symbols) { - this.BaseAddress = BaseAddress; - this.Symbols = Symbols; + BaseAddress = baseAddress; + Symbols = symbols; } } - private List Images; + private List _images; - private int Loaded; + private int _loaded; - public HleProcessDebugger(KProcess Owner) + public HleProcessDebugger(KProcess owner) { - this.Owner = Owner; + _owner = owner; - Images = new List(); + _images = new List(); } - public void PrintGuestStackTrace(CpuThreadState ThreadState) + public void PrintGuestStackTrace(CpuThreadState threadState) { EnsureLoaded(); - StringBuilder Trace = new StringBuilder(); + StringBuilder trace = new StringBuilder(); - Trace.AppendLine("Guest stack trace:"); + trace.AppendLine("Guest stack trace:"); - void AppendTrace(long Address) + void AppendTrace(long address) { - Image Image = GetImage(Address, out int ImageIndex); + Image image = GetImage(address, out int imageIndex); - if (Image == null || !TryGetSubName(Image, Address, out string SubName)) + if (image == null || !TryGetSubName(image, address, out string subName)) { - SubName = $"Sub{Address:x16}"; + subName = $"Sub{address:x16}"; } - else if (SubName.StartsWith("_Z")) + else if (subName.StartsWith("_Z")) { - SubName = Demangler.Parse(SubName); + subName = Demangler.Parse(subName); } - if (Image != null) + if (image != null) { - long Offset = Address - Image.BaseAddress; + long offset = address - image.BaseAddress; - string ImageName = GetGuessedNsoNameFromIndex(ImageIndex); + string imageName = GetGuessedNsoNameFromIndex(imageIndex); - string ImageNameAndOffset = $"[{Owner.Name}] {ImageName}:0x{Offset:x8}"; + string imageNameAndOffset = $"[{_owner.Name}] {imageName}:0x{offset:x8}"; - Trace.AppendLine($" {ImageNameAndOffset} {SubName}"); + trace.AppendLine($" {imageNameAndOffset} {subName}"); } else { - Trace.AppendLine($" [{Owner.Name}] ??? {SubName}"); + trace.AppendLine($" [{_owner.Name}] ??? {subName}"); } } - long FramePointer = (long)ThreadState.X29; + long framePointer = (long)threadState.X29; - while (FramePointer != 0) + while (framePointer != 0) { - if ((FramePointer & 7) != 0 || - !Owner.CpuMemory.IsMapped(FramePointer) || - !Owner.CpuMemory.IsMapped(FramePointer + 8)) + if ((framePointer & 7) != 0 || + !_owner.CpuMemory.IsMapped(framePointer) || + !_owner.CpuMemory.IsMapped(framePointer + 8)) { break; } //Note: This is the return address, we need to subtract one instruction //worth of bytes to get the branch instruction address. - AppendTrace(Owner.CpuMemory.ReadInt64(FramePointer + 8) - 4); + AppendTrace(_owner.CpuMemory.ReadInt64(framePointer + 8) - 4); - FramePointer = Owner.CpuMemory.ReadInt64(FramePointer); + framePointer = _owner.CpuMemory.ReadInt64(framePointer); } - Logger.PrintInfo(LogClass.Cpu, Trace.ToString()); + Logger.PrintInfo(LogClass.Cpu, trace.ToString()); } - private bool TryGetSubName(Image Image, long Address, out string Name) + private bool TryGetSubName(Image image, long address, out string name) { - Address -= Image.BaseAddress; + address -= image.BaseAddress; - int Left = 0; - int Right = Image.Symbols.Length - 1; + int left = 0; + int right = image.Symbols.Length - 1; - while (Left <= Right) + while (left <= right) { - int Size = Right - Left; + int size = right - left; - int Middle = Left + (Size >> 1); + int middle = left + (size >> 1); - ElfSymbol Symbol = Image.Symbols[Middle]; + ElfSymbol symbol = image.Symbols[middle]; - long EndAddr = Symbol.Value + Symbol.Size; + long endAddr = symbol.Value + symbol.Size; - if ((ulong)Address >= (ulong)Symbol.Value && (ulong)Address < (ulong)EndAddr) + if ((ulong)address >= (ulong)symbol.Value && (ulong)address < (ulong)endAddr) { - Name = Symbol.Name; + name = symbol.Name; return true; } - if ((ulong)Address < (ulong)Symbol.Value) + if ((ulong)address < (ulong)symbol.Value) { - Right = Middle - 1; + right = middle - 1; } else { - Left = Middle + 1; + left = middle + 1; } } - Name = null; + name = null; return false; } - private Image GetImage(long Address, out int Index) + private Image GetImage(long address, out int index) { - lock (Images) + lock (_images) { - for (Index = Images.Count - 1; Index >= 0; Index--) + for (index = _images.Count - 1; index >= 0; index--) { - if ((ulong)Address >= (ulong)Images[Index].BaseAddress) + if ((ulong)address >= (ulong)_images[index].BaseAddress) { - return Images[Index]; + return _images[index]; } } } @@ -153,42 +153,42 @@ namespace Ryujinx.HLE.HOS.Kernel return null; } - private string GetGuessedNsoNameFromIndex(int Index) + private string GetGuessedNsoNameFromIndex(int index) { - if ((uint)Index > 11) + if ((uint)index > 11) { return "???"; } - if (Index == 0) + if (index == 0) { return "rtld"; } - else if (Index == 1) + else if (index == 1) { return "main"; } - else if (Index == GetImagesCount() - 1) + else if (index == GetImagesCount() - 1) { return "sdk"; } else { - return "subsdk" + (Index - 2); + return "subsdk" + (index - 2); } } private int GetImagesCount() { - lock (Images) + lock (_images) { - return Images.Count; + return _images.Count; } } private void EnsureLoaded() { - if (Interlocked.CompareExchange(ref Loaded, 1, 0) == 0) + if (Interlocked.CompareExchange(ref _loaded, 1, 0) == 0) { ScanMemoryForTextSegments(); } @@ -196,115 +196,115 @@ namespace Ryujinx.HLE.HOS.Kernel private void ScanMemoryForTextSegments() { - ulong OldAddress = 0; - ulong Address = 0; + ulong oldAddress = 0; + ulong address = 0; - while (Address >= OldAddress) + while (address >= oldAddress) { - KMemoryInfo Info = Owner.MemoryManager.QueryMemory(Address); + KMemoryInfo info = _owner.MemoryManager.QueryMemory(address); - if (Info.State == MemoryState.Reserved) + if (info.State == MemoryState.Reserved) { break; } - if (Info.State == MemoryState.CodeStatic && Info.Permission == MemoryPermission.ReadAndExecute) + if (info.State == MemoryState.CodeStatic && info.Permission == MemoryPermission.ReadAndExecute) { - LoadMod0Symbols(Owner.CpuMemory, (long)Info.Address); + LoadMod0Symbols(_owner.CpuMemory, (long)info.Address); } - OldAddress = Address; + oldAddress = address; - Address = Info.Address + Info.Size; + address = info.Address + info.Size; } } - private void LoadMod0Symbols(MemoryManager Memory, long TextOffset) + private void LoadMod0Symbols(MemoryManager memory, long textOffset) { - long Mod0Offset = TextOffset + Memory.ReadUInt32(TextOffset + 4); + long mod0Offset = textOffset + memory.ReadUInt32(textOffset + 4); - if (Mod0Offset < TextOffset || !Memory.IsMapped(Mod0Offset) || (Mod0Offset & 3) != 0) + if (mod0Offset < textOffset || !memory.IsMapped(mod0Offset) || (mod0Offset & 3) != 0) { return; } - Dictionary Dynamic = new Dictionary(); + Dictionary dynamic = new Dictionary(); - int Mod0Magic = Memory.ReadInt32(Mod0Offset + 0x0); + int mod0Magic = memory.ReadInt32(mod0Offset + 0x0); - if (Mod0Magic != Mod0) + if (mod0Magic != Mod0) { return; } - long DynamicOffset = Memory.ReadInt32(Mod0Offset + 0x4) + Mod0Offset; - long BssStartOffset = Memory.ReadInt32(Mod0Offset + 0x8) + Mod0Offset; - long BssEndOffset = Memory.ReadInt32(Mod0Offset + 0xc) + Mod0Offset; - long EhHdrStartOffset = Memory.ReadInt32(Mod0Offset + 0x10) + Mod0Offset; - long EhHdrEndOffset = Memory.ReadInt32(Mod0Offset + 0x14) + Mod0Offset; - long ModObjOffset = Memory.ReadInt32(Mod0Offset + 0x18) + Mod0Offset; + long dynamicOffset = memory.ReadInt32(mod0Offset + 0x4) + mod0Offset; + long bssStartOffset = memory.ReadInt32(mod0Offset + 0x8) + mod0Offset; + long bssEndOffset = memory.ReadInt32(mod0Offset + 0xc) + mod0Offset; + long ehHdrStartOffset = memory.ReadInt32(mod0Offset + 0x10) + mod0Offset; + long ehHdrEndOffset = memory.ReadInt32(mod0Offset + 0x14) + mod0Offset; + long modObjOffset = memory.ReadInt32(mod0Offset + 0x18) + mod0Offset; while (true) { - long TagVal = Memory.ReadInt64(DynamicOffset + 0); - long Value = Memory.ReadInt64(DynamicOffset + 8); + long tagVal = memory.ReadInt64(dynamicOffset + 0); + long value = memory.ReadInt64(dynamicOffset + 8); - DynamicOffset += 0x10; + dynamicOffset += 0x10; - ElfDynamicTag Tag = (ElfDynamicTag)TagVal; + ElfDynamicTag tag = (ElfDynamicTag)tagVal; - if (Tag == ElfDynamicTag.DT_NULL) + if (tag == ElfDynamicTag.DT_NULL) { break; } - Dynamic[Tag] = Value; + dynamic[tag] = value; } - if (!Dynamic.TryGetValue(ElfDynamicTag.DT_STRTAB, out long StrTab) || - !Dynamic.TryGetValue(ElfDynamicTag.DT_SYMTAB, out long SymTab) || - !Dynamic.TryGetValue(ElfDynamicTag.DT_SYMENT, out long SymEntSize)) + if (!dynamic.TryGetValue(ElfDynamicTag.DT_STRTAB, out long strTab) || + !dynamic.TryGetValue(ElfDynamicTag.DT_SYMTAB, out long symTab) || + !dynamic.TryGetValue(ElfDynamicTag.DT_SYMENT, out long symEntSize)) { return; } - long StrTblAddr = TextOffset + StrTab; - long SymTblAddr = TextOffset + SymTab; + long strTblAddr = textOffset + strTab; + long symTblAddr = textOffset + symTab; - List Symbols = new List(); + List symbols = new List(); - while ((ulong)SymTblAddr < (ulong)StrTblAddr) + while ((ulong)symTblAddr < (ulong)strTblAddr) { - ElfSymbol Sym = GetSymbol(Memory, SymTblAddr, StrTblAddr); + ElfSymbol sym = GetSymbol(memory, symTblAddr, strTblAddr); - Symbols.Add(Sym); + symbols.Add(sym); - SymTblAddr += SymEntSize; + symTblAddr += symEntSize; } - lock (Images) + lock (_images) { - Images.Add(new Image(TextOffset, Symbols.OrderBy(x => x.Value).ToArray())); + _images.Add(new Image(textOffset, symbols.OrderBy(x => x.Value).ToArray())); } } - private ElfSymbol GetSymbol(MemoryManager Memory, long Address, long StrTblAddr) + private ElfSymbol GetSymbol(MemoryManager memory, long address, long strTblAddr) { - int NameIndex = Memory.ReadInt32(Address + 0); - int Info = Memory.ReadByte (Address + 4); - int Other = Memory.ReadByte (Address + 5); - int SHIdx = Memory.ReadInt16(Address + 6); - long Value = Memory.ReadInt64(Address + 8); - long Size = Memory.ReadInt64(Address + 16); + int nameIndex = memory.ReadInt32(address + 0); + int info = memory.ReadByte (address + 4); + int other = memory.ReadByte (address + 5); + int shIdx = memory.ReadInt16(address + 6); + long value = memory.ReadInt64(address + 8); + long size = memory.ReadInt64(address + 16); - string Name = string.Empty; + string name = string.Empty; - for (int Chr; (Chr = Memory.ReadByte(StrTblAddr + NameIndex++)) != 0;) + for (int chr; (chr = memory.ReadByte(strTblAddr + nameIndex++)) != 0;) { - Name += (char)Chr; + name += (char)chr; } - return new ElfSymbol(Name, Info, Other, SHIdx, Value, Size); + return new ElfSymbol(name, info, other, shIdx, value, size); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/HleScheduler.cs b/Ryujinx.HLE/HOS/Kernel/HleScheduler.cs index 87dbe553..1a4c9dfe 100644 --- a/Ryujinx.HLE/HOS/Kernel/HleScheduler.cs +++ b/Ryujinx.HLE/HOS/Kernel/HleScheduler.cs @@ -7,21 +7,21 @@ namespace Ryujinx.HLE.HOS.Kernel { private const int RoundRobinTimeQuantumMs = 10; - private int CurrentCore; + private int _currentCore; public bool MultiCoreScheduling { get; set; } public HleCoreManager CoreManager { get; private set; } - private bool KeepPreempting; + private bool _keepPreempting; public void StartAutoPreemptionThread() { - Thread PreemptionThread = new Thread(PreemptCurrentThread); + Thread preemptionThread = new Thread(PreemptCurrentThread); - KeepPreempting = true; + _keepPreempting = true; - PreemptionThread.Start(); + preemptionThread.Start(); } public void ContextSwitch() @@ -30,28 +30,28 @@ namespace Ryujinx.HLE.HOS.Kernel { if (MultiCoreScheduling) { - int SelectedCount = 0; + int selectedCount = 0; - for (int Core = 0; Core < KScheduler.CpuCoresCount; Core++) + for (int core = 0; core < CpuCoresCount; core++) { - KCoreContext CoreContext = CoreContexts[Core]; + KCoreContext coreContext = CoreContexts[core]; - if (CoreContext.ContextSwitchNeeded && (CoreContext.CurrentThread?.Context.IsCurrentThread() ?? false)) + if (coreContext.ContextSwitchNeeded && (coreContext.CurrentThread?.Context.IsCurrentThread() ?? false)) { - CoreContext.ContextSwitch(); + coreContext.ContextSwitch(); } - if (CoreContext.CurrentThread?.Context.IsCurrentThread() ?? false) + if (coreContext.CurrentThread?.Context.IsCurrentThread() ?? false) { - SelectedCount++; + selectedCount++; } } - if (SelectedCount == 0) + if (selectedCount == 0) { CoreManager.Reset(Thread.CurrentThread); } - else if (SelectedCount == 1) + else if (selectedCount == 1) { CoreManager.Set(Thread.CurrentThread); } @@ -62,41 +62,41 @@ namespace Ryujinx.HLE.HOS.Kernel } else { - KThread CurrentThread = CoreContexts[CurrentCore].CurrentThread; + KThread currentThread = CoreContexts[_currentCore].CurrentThread; - bool HasThreadExecuting = CurrentThread != null; + bool hasThreadExecuting = currentThread != null; - if (HasThreadExecuting) + if (hasThreadExecuting) { //If this is not the thread that is currently executing, we need //to request an interrupt to allow safely starting another thread. - if (!CurrentThread.Context.IsCurrentThread()) + if (!currentThread.Context.IsCurrentThread()) { - CurrentThread.Context.RequestInterrupt(); + currentThread.Context.RequestInterrupt(); return; } - CoreManager.Reset(CurrentThread.Context.Work); + CoreManager.Reset(currentThread.Context.Work); } //Advance current core and try picking a thread, //keep advancing if it is null. - for (int Core = 0; Core < 4; Core++) + for (int core = 0; core < 4; core++) { - CurrentCore = (CurrentCore + 1) % CpuCoresCount; + _currentCore = (_currentCore + 1) % CpuCoresCount; - KCoreContext CoreContext = CoreContexts[CurrentCore]; + KCoreContext coreContext = CoreContexts[_currentCore]; - CoreContext.UpdateCurrentThread(); + coreContext.UpdateCurrentThread(); - if (CoreContext.CurrentThread != null) + if (coreContext.CurrentThread != null) { - CoreContext.CurrentThread.ClearExclusive(); + coreContext.CurrentThread.ClearExclusive(); - CoreManager.Set(CoreContext.CurrentThread.Context.Work); + CoreManager.Set(coreContext.CurrentThread.Context.Work); - CoreContext.CurrentThread.Context.Execute(); + coreContext.CurrentThread.Context.Execute(); break; } @@ -104,7 +104,7 @@ namespace Ryujinx.HLE.HOS.Kernel //If nothing was running before, then we are on a "external" //HLE thread, we don't need to wait. - if (!HasThreadExecuting) + if (!hasThreadExecuting) { return; } @@ -119,13 +119,13 @@ namespace Ryujinx.HLE.HOS.Kernel //Preempts current thread every 10 milliseconds on a round-robin fashion, //when multi core scheduling is disabled, to try ensuring that all threads //gets a chance to run. - while (KeepPreempting) + while (_keepPreempting) { lock (CoreContexts) { - KThread CurrentThread = CoreContexts[CurrentCore].CurrentThread; + KThread currentThread = CoreContexts[_currentCore].CurrentThread; - CurrentThread?.Context.RequestInterrupt(); + currentThread?.Context.RequestInterrupt(); } PreemptThreads(); @@ -134,16 +134,16 @@ namespace Ryujinx.HLE.HOS.Kernel } } - public void ExitThread(KThread Thread) + public void ExitThread(KThread thread) { - Thread.Context.StopExecution(); + thread.Context.StopExecution(); - CoreManager.Exit(Thread.Context.Work); + CoreManager.Exit(thread.Context.Work); } - public void RemoveThread(KThread Thread) + public void RemoveThread(KThread thread) { - CoreManager.RemoveThread(Thread.Context.Work); + CoreManager.RemoveThread(thread.Context.Work); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/KAddressArbiter.cs b/Ryujinx.HLE/HOS/Kernel/KAddressArbiter.cs index cc637be0..b4352485 100644 --- a/Ryujinx.HLE/HOS/Kernel/KAddressArbiter.cs +++ b/Ryujinx.HLE/HOS/Kernel/KAddressArbiter.cs @@ -9,641 +9,641 @@ namespace Ryujinx.HLE.HOS.Kernel { private const int HasListenersMask = 0x40000000; - private Horizon System; + private Horizon _system; public List CondVarThreads; public List ArbiterThreads; - public KAddressArbiter(Horizon System) + public KAddressArbiter(Horizon system) { - this.System = System; + _system = system; CondVarThreads = new List(); ArbiterThreads = new List(); } - public long ArbitrateLock(int OwnerHandle, long MutexAddress, int RequesterHandle) + public long ArbitrateLock(int ownerHandle, long mutexAddress, int requesterHandle) { - KThread CurrentThread = System.Scheduler.GetCurrentThread(); + KThread currentThread = _system.Scheduler.GetCurrentThread(); - System.CriticalSection.Enter(); + _system.CriticalSection.Enter(); - CurrentThread.SignaledObj = null; - CurrentThread.ObjSyncResult = 0; + currentThread.SignaledObj = null; + currentThread.ObjSyncResult = 0; - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = _system.Scheduler.GetCurrentProcess(); - if (!KernelTransfer.UserToKernelInt32(System, MutexAddress, out int MutexValue)) + if (!KernelTransfer.UserToKernelInt32(_system, mutexAddress, out int mutexValue)) { - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); - return MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm);; + return MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); } - if (MutexValue != (OwnerHandle | HasListenersMask)) + if (mutexValue != (ownerHandle | HasListenersMask)) { - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); return 0; } - KThread MutexOwner = CurrentProcess.HandleTable.GetObject(OwnerHandle); + KThread mutexOwner = currentProcess.HandleTable.GetObject(ownerHandle); - if (MutexOwner == null) + if (mutexOwner == null) { - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); return MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle); } - CurrentThread.MutexAddress = MutexAddress; - CurrentThread.ThreadHandleForUserMutex = RequesterHandle; + currentThread.MutexAddress = mutexAddress; + currentThread.ThreadHandleForUserMutex = requesterHandle; - MutexOwner.AddMutexWaiter(CurrentThread); + mutexOwner.AddMutexWaiter(currentThread); - CurrentThread.Reschedule(ThreadSchedState.Paused); + currentThread.Reschedule(ThreadSchedState.Paused); - System.CriticalSection.Leave(); - System.CriticalSection.Enter(); + _system.CriticalSection.Leave(); + _system.CriticalSection.Enter(); - if (CurrentThread.MutexOwner != null) + if (currentThread.MutexOwner != null) { - CurrentThread.MutexOwner.RemoveMutexWaiter(CurrentThread); + currentThread.MutexOwner.RemoveMutexWaiter(currentThread); } - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); - return (uint)CurrentThread.ObjSyncResult; + return (uint)currentThread.ObjSyncResult; } - public long ArbitrateUnlock(long MutexAddress) + public long ArbitrateUnlock(long mutexAddress) { - System.CriticalSection.Enter(); + _system.CriticalSection.Enter(); - KThread CurrentThread = System.Scheduler.GetCurrentThread(); + KThread currentThread = _system.Scheduler.GetCurrentThread(); - (long Result, KThread NewOwnerThread) = MutexUnlock(CurrentThread, MutexAddress); + (long result, KThread newOwnerThread) = MutexUnlock(currentThread, mutexAddress); - if (Result != 0 && NewOwnerThread != null) + if (result != 0 && newOwnerThread != null) { - NewOwnerThread.SignaledObj = null; - NewOwnerThread.ObjSyncResult = (int)Result; + newOwnerThread.SignaledObj = null; + newOwnerThread.ObjSyncResult = (int)result; } - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); - return Result; + return result; } public long WaitProcessWideKeyAtomic( - long MutexAddress, - long CondVarAddress, - int ThreadHandle, - long Timeout) + long mutexAddress, + long condVarAddress, + int threadHandle, + long timeout) { - System.CriticalSection.Enter(); + _system.CriticalSection.Enter(); - KThread CurrentThread = System.Scheduler.GetCurrentThread(); + KThread currentThread = _system.Scheduler.GetCurrentThread(); - CurrentThread.SignaledObj = null; - CurrentThread.ObjSyncResult = (int)MakeError(ErrorModule.Kernel, KernelErr.Timeout); + currentThread.SignaledObj = null; + currentThread.ObjSyncResult = (int)MakeError(ErrorModule.Kernel, KernelErr.Timeout); - if (CurrentThread.ShallBeTerminated || - CurrentThread.SchedFlags == ThreadSchedState.TerminationPending) + if (currentThread.ShallBeTerminated || + currentThread.SchedFlags == ThreadSchedState.TerminationPending) { - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); return MakeError(ErrorModule.Kernel, KernelErr.ThreadTerminating); } - (long Result, _) = MutexUnlock(CurrentThread, MutexAddress); + (long result, _) = MutexUnlock(currentThread, mutexAddress); - if (Result != 0) + if (result != 0) { - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); - return Result; + return result; } - CurrentThread.MutexAddress = MutexAddress; - CurrentThread.ThreadHandleForUserMutex = ThreadHandle; - CurrentThread.CondVarAddress = CondVarAddress; + currentThread.MutexAddress = mutexAddress; + currentThread.ThreadHandleForUserMutex = threadHandle; + currentThread.CondVarAddress = condVarAddress; - CondVarThreads.Add(CurrentThread); + CondVarThreads.Add(currentThread); - if (Timeout != 0) + if (timeout != 0) { - CurrentThread.Reschedule(ThreadSchedState.Paused); + currentThread.Reschedule(ThreadSchedState.Paused); - if (Timeout > 0) + if (timeout > 0) { - System.TimeManager.ScheduleFutureInvocation(CurrentThread, Timeout); + _system.TimeManager.ScheduleFutureInvocation(currentThread, timeout); } } - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); - if (Timeout > 0) + if (timeout > 0) { - System.TimeManager.UnscheduleFutureInvocation(CurrentThread); + _system.TimeManager.UnscheduleFutureInvocation(currentThread); } - System.CriticalSection.Enter(); + _system.CriticalSection.Enter(); - if (CurrentThread.MutexOwner != null) + if (currentThread.MutexOwner != null) { - CurrentThread.MutexOwner.RemoveMutexWaiter(CurrentThread); + currentThread.MutexOwner.RemoveMutexWaiter(currentThread); } - CondVarThreads.Remove(CurrentThread); + CondVarThreads.Remove(currentThread); - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); - return (uint)CurrentThread.ObjSyncResult; + return (uint)currentThread.ObjSyncResult; } - private (long, KThread) MutexUnlock(KThread CurrentThread, long MutexAddress) + private (long, KThread) MutexUnlock(KThread currentThread, long mutexAddress) { - KThread NewOwnerThread = CurrentThread.RelinquishMutex(MutexAddress, out int Count); + KThread newOwnerThread = currentThread.RelinquishMutex(mutexAddress, out int count); - int MutexValue = 0; + int mutexValue = 0; - if (NewOwnerThread != null) + if (newOwnerThread != null) { - MutexValue = NewOwnerThread.ThreadHandleForUserMutex; + mutexValue = newOwnerThread.ThreadHandleForUserMutex; - if (Count >= 2) + if (count >= 2) { - MutexValue |= HasListenersMask; + mutexValue |= HasListenersMask; } - NewOwnerThread.SignaledObj = null; - NewOwnerThread.ObjSyncResult = 0; + newOwnerThread.SignaledObj = null; + newOwnerThread.ObjSyncResult = 0; - NewOwnerThread.ReleaseAndResume(); + newOwnerThread.ReleaseAndResume(); } - long Result = 0; + long result = 0; - if (!KernelTransfer.KernelToUserInt32(System, MutexAddress, MutexValue)) + if (!KernelTransfer.KernelToUserInt32(_system, mutexAddress, mutexValue)) { - Result = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); + result = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); } - return (Result, NewOwnerThread); + return (result, newOwnerThread); } - public void SignalProcessWideKey(long Address, int Count) + public void SignalProcessWideKey(long address, int count) { - Queue SignaledThreads = new Queue(); + Queue signaledThreads = new Queue(); - System.CriticalSection.Enter(); + _system.CriticalSection.Enter(); - IOrderedEnumerable SortedThreads = CondVarThreads.OrderBy(x => x.DynamicPriority); + IOrderedEnumerable sortedThreads = CondVarThreads.OrderBy(x => x.DynamicPriority); - foreach (KThread Thread in SortedThreads.Where(x => x.CondVarAddress == Address)) + foreach (KThread thread in sortedThreads.Where(x => x.CondVarAddress == address)) { - TryAcquireMutex(Thread); + TryAcquireMutex(thread); - SignaledThreads.Enqueue(Thread); + signaledThreads.Enqueue(thread); //If the count is <= 0, we should signal all threads waiting. - if (Count >= 1 && --Count == 0) + if (count >= 1 && --count == 0) { break; } } - while (SignaledThreads.TryDequeue(out KThread Thread)) + while (signaledThreads.TryDequeue(out KThread thread)) { - CondVarThreads.Remove(Thread); + CondVarThreads.Remove(thread); } - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); } - private KThread TryAcquireMutex(KThread Requester) + private KThread TryAcquireMutex(KThread requester) { - long Address = Requester.MutexAddress; + long address = requester.MutexAddress; - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = _system.Scheduler.GetCurrentProcess(); - CurrentProcess.CpuMemory.SetExclusive(0, Address); + currentProcess.CpuMemory.SetExclusive(0, address); - if (!KernelTransfer.UserToKernelInt32(System, Address, out int MutexValue)) + if (!KernelTransfer.UserToKernelInt32(_system, address, out int mutexValue)) { //Invalid address. - CurrentProcess.CpuMemory.ClearExclusive(0); + currentProcess.CpuMemory.ClearExclusive(0); - Requester.SignaledObj = null; - Requester.ObjSyncResult = (int)MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); + requester.SignaledObj = null; + requester.ObjSyncResult = (int)MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); return null; } while (true) { - if (CurrentProcess.CpuMemory.TestExclusive(0, Address)) + if (currentProcess.CpuMemory.TestExclusive(0, address)) { - if (MutexValue != 0) + if (mutexValue != 0) { //Update value to indicate there is a mutex waiter now. - CurrentProcess.CpuMemory.WriteInt32(Address, MutexValue | HasListenersMask); + currentProcess.CpuMemory.WriteInt32(address, mutexValue | HasListenersMask); } else { //No thread owning the mutex, assign to requesting thread. - CurrentProcess.CpuMemory.WriteInt32(Address, Requester.ThreadHandleForUserMutex); + currentProcess.CpuMemory.WriteInt32(address, requester.ThreadHandleForUserMutex); } - CurrentProcess.CpuMemory.ClearExclusiveForStore(0); + currentProcess.CpuMemory.ClearExclusiveForStore(0); break; } - CurrentProcess.CpuMemory.SetExclusive(0, Address); + currentProcess.CpuMemory.SetExclusive(0, address); - MutexValue = CurrentProcess.CpuMemory.ReadInt32(Address); + mutexValue = currentProcess.CpuMemory.ReadInt32(address); } - if (MutexValue == 0) + if (mutexValue == 0) { //We now own the mutex. - Requester.SignaledObj = null; - Requester.ObjSyncResult = 0; + requester.SignaledObj = null; + requester.ObjSyncResult = 0; - Requester.ReleaseAndResume(); + requester.ReleaseAndResume(); return null; } - MutexValue &= ~HasListenersMask; + mutexValue &= ~HasListenersMask; - KThread MutexOwner = CurrentProcess.HandleTable.GetObject(MutexValue); + KThread mutexOwner = currentProcess.HandleTable.GetObject(mutexValue); - if (MutexOwner != null) + if (mutexOwner != null) { //Mutex already belongs to another thread, wait for it. - MutexOwner.AddMutexWaiter(Requester); + mutexOwner.AddMutexWaiter(requester); } else { //Invalid mutex owner. - Requester.SignaledObj = null; - Requester.ObjSyncResult = (int)MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle); + requester.SignaledObj = null; + requester.ObjSyncResult = (int)MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle); - Requester.ReleaseAndResume(); + requester.ReleaseAndResume(); } - return MutexOwner; + return mutexOwner; } - public long WaitForAddressIfEqual(long Address, int Value, long Timeout) + public long WaitForAddressIfEqual(long address, int value, long timeout) { - KThread CurrentThread = System.Scheduler.GetCurrentThread(); + KThread currentThread = _system.Scheduler.GetCurrentThread(); - System.CriticalSection.Enter(); + _system.CriticalSection.Enter(); - if (CurrentThread.ShallBeTerminated || - CurrentThread.SchedFlags == ThreadSchedState.TerminationPending) + if (currentThread.ShallBeTerminated || + currentThread.SchedFlags == ThreadSchedState.TerminationPending) { - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); return MakeError(ErrorModule.Kernel, KernelErr.ThreadTerminating); } - CurrentThread.SignaledObj = null; - CurrentThread.ObjSyncResult = (int)MakeError(ErrorModule.Kernel, KernelErr.Timeout); + currentThread.SignaledObj = null; + currentThread.ObjSyncResult = (int)MakeError(ErrorModule.Kernel, KernelErr.Timeout); - if (!KernelTransfer.UserToKernelInt32(System, Address, out int CurrentValue)) + if (!KernelTransfer.UserToKernelInt32(_system, address, out int currentValue)) { - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); return MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); } - if (CurrentValue == Value) + if (currentValue == value) { - if (Timeout == 0) + if (timeout == 0) { - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); return MakeError(ErrorModule.Kernel, KernelErr.Timeout); } - CurrentThread.MutexAddress = Address; - CurrentThread.WaitingInArbitration = true; + currentThread.MutexAddress = address; + currentThread.WaitingInArbitration = true; - InsertSortedByPriority(ArbiterThreads, CurrentThread); + InsertSortedByPriority(ArbiterThreads, currentThread); - CurrentThread.Reschedule(ThreadSchedState.Paused); + currentThread.Reschedule(ThreadSchedState.Paused); - if (Timeout > 0) + if (timeout > 0) { - System.TimeManager.ScheduleFutureInvocation(CurrentThread, Timeout); + _system.TimeManager.ScheduleFutureInvocation(currentThread, timeout); } - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); - if (Timeout > 0) + if (timeout > 0) { - System.TimeManager.UnscheduleFutureInvocation(CurrentThread); + _system.TimeManager.UnscheduleFutureInvocation(currentThread); } - System.CriticalSection.Enter(); + _system.CriticalSection.Enter(); - if (CurrentThread.WaitingInArbitration) + if (currentThread.WaitingInArbitration) { - ArbiterThreads.Remove(CurrentThread); + ArbiterThreads.Remove(currentThread); - CurrentThread.WaitingInArbitration = false; + currentThread.WaitingInArbitration = false; } - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); - return CurrentThread.ObjSyncResult; + return currentThread.ObjSyncResult; } - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); return MakeError(ErrorModule.Kernel, KernelErr.InvalidState); } - public long WaitForAddressIfLessThan(long Address, int Value, bool ShouldDecrement, long Timeout) + public long WaitForAddressIfLessThan(long address, int value, bool shouldDecrement, long timeout) { - KThread CurrentThread = System.Scheduler.GetCurrentThread(); + KThread currentThread = _system.Scheduler.GetCurrentThread(); - System.CriticalSection.Enter(); + _system.CriticalSection.Enter(); - if (CurrentThread.ShallBeTerminated || - CurrentThread.SchedFlags == ThreadSchedState.TerminationPending) + if (currentThread.ShallBeTerminated || + currentThread.SchedFlags == ThreadSchedState.TerminationPending) { - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); return MakeError(ErrorModule.Kernel, KernelErr.ThreadTerminating); } - CurrentThread.SignaledObj = null; - CurrentThread.ObjSyncResult = (int)MakeError(ErrorModule.Kernel, KernelErr.Timeout); + currentThread.SignaledObj = null; + currentThread.ObjSyncResult = (int)MakeError(ErrorModule.Kernel, KernelErr.Timeout); - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = _system.Scheduler.GetCurrentProcess(); //If ShouldDecrement is true, do atomic decrement of the value at Address. - CurrentProcess.CpuMemory.SetExclusive(0, Address); + currentProcess.CpuMemory.SetExclusive(0, address); - if (!KernelTransfer.UserToKernelInt32(System, Address, out int CurrentValue)) + if (!KernelTransfer.UserToKernelInt32(_system, address, out int currentValue)) { - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); return MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); } - if (ShouldDecrement) + if (shouldDecrement) { - while (CurrentValue < Value) + while (currentValue < value) { - if (CurrentProcess.CpuMemory.TestExclusive(0, Address)) + if (currentProcess.CpuMemory.TestExclusive(0, address)) { - CurrentProcess.CpuMemory.WriteInt32(Address, CurrentValue - 1); + currentProcess.CpuMemory.WriteInt32(address, currentValue - 1); - CurrentProcess.CpuMemory.ClearExclusiveForStore(0); + currentProcess.CpuMemory.ClearExclusiveForStore(0); break; } - CurrentProcess.CpuMemory.SetExclusive(0, Address); + currentProcess.CpuMemory.SetExclusive(0, address); - CurrentValue = CurrentProcess.CpuMemory.ReadInt32(Address); + currentValue = currentProcess.CpuMemory.ReadInt32(address); } } - CurrentProcess.CpuMemory.ClearExclusive(0); + currentProcess.CpuMemory.ClearExclusive(0); - if (CurrentValue < Value) + if (currentValue < value) { - if (Timeout == 0) + if (timeout == 0) { - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); return MakeError(ErrorModule.Kernel, KernelErr.Timeout); } - CurrentThread.MutexAddress = Address; - CurrentThread.WaitingInArbitration = true; + currentThread.MutexAddress = address; + currentThread.WaitingInArbitration = true; - InsertSortedByPriority(ArbiterThreads, CurrentThread); + InsertSortedByPriority(ArbiterThreads, currentThread); - CurrentThread.Reschedule(ThreadSchedState.Paused); + currentThread.Reschedule(ThreadSchedState.Paused); - if (Timeout > 0) + if (timeout > 0) { - System.TimeManager.ScheduleFutureInvocation(CurrentThread, Timeout); + _system.TimeManager.ScheduleFutureInvocation(currentThread, timeout); } - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); - if (Timeout > 0) + if (timeout > 0) { - System.TimeManager.UnscheduleFutureInvocation(CurrentThread); + _system.TimeManager.UnscheduleFutureInvocation(currentThread); } - System.CriticalSection.Enter(); + _system.CriticalSection.Enter(); - if (CurrentThread.WaitingInArbitration) + if (currentThread.WaitingInArbitration) { - ArbiterThreads.Remove(CurrentThread); + ArbiterThreads.Remove(currentThread); - CurrentThread.WaitingInArbitration = false; + currentThread.WaitingInArbitration = false; } - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); - return CurrentThread.ObjSyncResult; + return currentThread.ObjSyncResult; } - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); return MakeError(ErrorModule.Kernel, KernelErr.InvalidState); } - private void InsertSortedByPriority(List Threads, KThread Thread) + private void InsertSortedByPriority(List threads, KThread thread) { - int NextIndex = -1; + int nextIndex = -1; - for (int Index = 0; Index < Threads.Count; Index++) + for (int index = 0; index < threads.Count; index++) { - if (Threads[Index].DynamicPriority > Thread.DynamicPriority) + if (threads[index].DynamicPriority > thread.DynamicPriority) { - NextIndex = Index; + nextIndex = index; break; } } - if (NextIndex != -1) + if (nextIndex != -1) { - Threads.Insert(NextIndex, Thread); + threads.Insert(nextIndex, thread); } else { - Threads.Add(Thread); + threads.Add(thread); } } - public long Signal(long Address, int Count) + public long Signal(long address, int count) { - System.CriticalSection.Enter(); + _system.CriticalSection.Enter(); - WakeArbiterThreads(Address, Count); + WakeArbiterThreads(address, count); - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); return 0; } - public long SignalAndIncrementIfEqual(long Address, int Value, int Count) + public long SignalAndIncrementIfEqual(long address, int value, int count) { - System.CriticalSection.Enter(); + _system.CriticalSection.Enter(); - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = _system.Scheduler.GetCurrentProcess(); - CurrentProcess.CpuMemory.SetExclusive(0, Address); + currentProcess.CpuMemory.SetExclusive(0, address); - if (!KernelTransfer.UserToKernelInt32(System, Address, out int CurrentValue)) + if (!KernelTransfer.UserToKernelInt32(_system, address, out int currentValue)) { - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); return MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); } - while (CurrentValue == Value) + while (currentValue == value) { - if (CurrentProcess.CpuMemory.TestExclusive(0, Address)) + if (currentProcess.CpuMemory.TestExclusive(0, address)) { - CurrentProcess.CpuMemory.WriteInt32(Address, CurrentValue + 1); + currentProcess.CpuMemory.WriteInt32(address, currentValue + 1); - CurrentProcess.CpuMemory.ClearExclusiveForStore(0); + currentProcess.CpuMemory.ClearExclusiveForStore(0); break; } - CurrentProcess.CpuMemory.SetExclusive(0, Address); + currentProcess.CpuMemory.SetExclusive(0, address); - CurrentValue = CurrentProcess.CpuMemory.ReadInt32(Address); + currentValue = currentProcess.CpuMemory.ReadInt32(address); } - CurrentProcess.CpuMemory.ClearExclusive(0); + currentProcess.CpuMemory.ClearExclusive(0); - if (CurrentValue != Value) + if (currentValue != value) { - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); return MakeError(ErrorModule.Kernel, KernelErr.InvalidState); } - WakeArbiterThreads(Address, Count); + WakeArbiterThreads(address, count); - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); return 0; } - public long SignalAndModifyIfEqual(long Address, int Value, int Count) + public long SignalAndModifyIfEqual(long address, int value, int count) { - System.CriticalSection.Enter(); + _system.CriticalSection.Enter(); - int Offset; + int offset; //The value is decremented if the number of threads waiting is less //or equal to the Count of threads to be signaled, or Count is zero //or negative. It is incremented if there are no threads waiting. - int WaitingCount = 0; + int waitingCount = 0; - foreach (KThread Thread in ArbiterThreads.Where(x => x.MutexAddress == Address)) + foreach (KThread thread in ArbiterThreads.Where(x => x.MutexAddress == address)) { - if (++WaitingCount > Count) + if (++waitingCount > count) { break; } } - if (WaitingCount > 0) + if (waitingCount > 0) { - Offset = WaitingCount <= Count || Count <= 0 ? -1 : 0; + offset = waitingCount <= count || count <= 0 ? -1 : 0; } else { - Offset = 1; + offset = 1; } - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = _system.Scheduler.GetCurrentProcess(); - CurrentProcess.CpuMemory.SetExclusive(0, Address); + currentProcess.CpuMemory.SetExclusive(0, address); - if (!KernelTransfer.UserToKernelInt32(System, Address, out int CurrentValue)) + if (!KernelTransfer.UserToKernelInt32(_system, address, out int currentValue)) { - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); return MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); } - while (CurrentValue == Value) + while (currentValue == value) { - if (CurrentProcess.CpuMemory.TestExclusive(0, Address)) + if (currentProcess.CpuMemory.TestExclusive(0, address)) { - CurrentProcess.CpuMemory.WriteInt32(Address, CurrentValue + Offset); + currentProcess.CpuMemory.WriteInt32(address, currentValue + offset); - CurrentProcess.CpuMemory.ClearExclusiveForStore(0); + currentProcess.CpuMemory.ClearExclusiveForStore(0); break; } - CurrentProcess.CpuMemory.SetExclusive(0, Address); + currentProcess.CpuMemory.SetExclusive(0, address); - CurrentValue = CurrentProcess.CpuMemory.ReadInt32(Address); + currentValue = currentProcess.CpuMemory.ReadInt32(address); } - CurrentProcess.CpuMemory.ClearExclusive(0); + currentProcess.CpuMemory.ClearExclusive(0); - if (CurrentValue != Value) + if (currentValue != value) { - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); return MakeError(ErrorModule.Kernel, KernelErr.InvalidState); } - WakeArbiterThreads(Address, Count); + WakeArbiterThreads(address, count); - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); return 0; } - private void WakeArbiterThreads(long Address, int Count) + private void WakeArbiterThreads(long address, int count) { - Queue SignaledThreads = new Queue(); + Queue signaledThreads = new Queue(); - foreach (KThread Thread in ArbiterThreads.Where(x => x.MutexAddress == Address)) + foreach (KThread thread in ArbiterThreads.Where(x => x.MutexAddress == address)) { - SignaledThreads.Enqueue(Thread); + signaledThreads.Enqueue(thread); //If the count is <= 0, we should signal all threads waiting. - if (Count >= 1 && --Count == 0) + if (count >= 1 && --count == 0) { break; } } - while (SignaledThreads.TryDequeue(out KThread Thread)) + while (signaledThreads.TryDequeue(out KThread thread)) { - Thread.SignaledObj = null; - Thread.ObjSyncResult = 0; + thread.SignaledObj = null; + thread.ObjSyncResult = 0; - Thread.ReleaseAndResume(); + thread.ReleaseAndResume(); - Thread.WaitingInArbitration = false; + thread.WaitingInArbitration = false; - ArbiterThreads.Remove(Thread); + ArbiterThreads.Remove(thread); } } } diff --git a/Ryujinx.HLE/HOS/Kernel/KAutoObject.cs b/Ryujinx.HLE/HOS/Kernel/KAutoObject.cs index a91bf9a8..f49beaac 100644 --- a/Ryujinx.HLE/HOS/Kernel/KAutoObject.cs +++ b/Ryujinx.HLE/HOS/Kernel/KAutoObject.cs @@ -4,14 +4,14 @@ namespace Ryujinx.HLE.HOS.Kernel { protected Horizon System; - public KAutoObject(Horizon System) + public KAutoObject(Horizon system) { - this.System = System; + System = system; } - public virtual KernelResult SetName(string Name) + public virtual KernelResult SetName(string name) { - if (!System.AutoObjectNames.TryAdd(Name, this)) + if (!System.AutoObjectNames.TryAdd(name, this)) { return KernelResult.InvalidState; } @@ -19,9 +19,9 @@ namespace Ryujinx.HLE.HOS.Kernel return KernelResult.Success; } - public static KernelResult RemoveName(Horizon System, string Name) + public static KernelResult RemoveName(Horizon system, string name) { - if (!System.AutoObjectNames.TryRemove(Name, out _)) + if (!system.AutoObjectNames.TryRemove(name, out _)) { return KernelResult.NotFound; } @@ -29,11 +29,11 @@ namespace Ryujinx.HLE.HOS.Kernel return KernelResult.Success; } - public static KAutoObject FindNamedObject(Horizon System, string Name) + public static KAutoObject FindNamedObject(Horizon system, string name) { - if (System.AutoObjectNames.TryGetValue(Name, out KAutoObject Obj)) + if (system.AutoObjectNames.TryGetValue(name, out KAutoObject obj)) { - return Obj; + return obj; } return null; diff --git a/Ryujinx.HLE/HOS/Kernel/KClientPort.cs b/Ryujinx.HLE/HOS/Kernel/KClientPort.cs index e3f8128b..57547627 100644 --- a/Ryujinx.HLE/HOS/Kernel/KClientPort.cs +++ b/Ryujinx.HLE/HOS/Kernel/KClientPort.cs @@ -2,30 +2,30 @@ namespace Ryujinx.HLE.HOS.Kernel { class KClientPort : KSynchronizationObject { - private int SessionsCount; - private int CurrentCapacity; - private int MaxSessions; + private int _sessionsCount; + private int _currentCapacity; + private int _maxSessions; - private KPort Parent; + private KPort _parent; - public KClientPort(Horizon System) : base(System) { } + public KClientPort(Horizon system) : base(system) { } - public void Initialize(KPort Parent, int MaxSessions) + public void Initialize(KPort parent, int maxSessions) { - this.MaxSessions = MaxSessions; - this.Parent = Parent; + _maxSessions = maxSessions; + _parent = parent; } - public new static KernelResult RemoveName(Horizon System, string Name) + public new static KernelResult RemoveName(Horizon system, string name) { - KAutoObject FoundObj = KAutoObject.FindNamedObject(System, Name); + KAutoObject foundObj = FindNamedObject(system, name); - if (!(FoundObj is KClientPort)) + if (!(foundObj is KClientPort)) { return KernelResult.NotFound; } - return KAutoObject.RemoveName(System, Name); + return KAutoObject.RemoveName(system, name); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/KConditionVariable.cs b/Ryujinx.HLE/HOS/Kernel/KConditionVariable.cs index 1c95f811..15c96c24 100644 --- a/Ryujinx.HLE/HOS/Kernel/KConditionVariable.cs +++ b/Ryujinx.HLE/HOS/Kernel/KConditionVariable.cs @@ -5,67 +5,67 @@ namespace Ryujinx.HLE.HOS.Kernel { static class KConditionVariable { - public static void Wait(Horizon System, LinkedList ThreadList, object Mutex, long Timeout) + public static void Wait(Horizon system, LinkedList threadList, object mutex, long timeout) { - KThread CurrentThread = System.Scheduler.GetCurrentThread(); + KThread currentThread = system.Scheduler.GetCurrentThread(); - System.CriticalSection.Enter(); + system.CriticalSection.Enter(); - Monitor.Exit(Mutex); + Monitor.Exit(mutex); - CurrentThread.Withholder = ThreadList; + currentThread.Withholder = threadList; - CurrentThread.Reschedule(ThreadSchedState.Paused); + currentThread.Reschedule(ThreadSchedState.Paused); - CurrentThread.WithholderNode = ThreadList.AddLast(CurrentThread); + currentThread.WithholderNode = threadList.AddLast(currentThread); - if (CurrentThread.ShallBeTerminated || - CurrentThread.SchedFlags == ThreadSchedState.TerminationPending) + if (currentThread.ShallBeTerminated || + currentThread.SchedFlags == ThreadSchedState.TerminationPending) { - ThreadList.Remove(CurrentThread.WithholderNode); + threadList.Remove(currentThread.WithholderNode); - CurrentThread.Reschedule(ThreadSchedState.Running); + currentThread.Reschedule(ThreadSchedState.Running); - CurrentThread.Withholder = null; + currentThread.Withholder = null; - System.CriticalSection.Leave(); + system.CriticalSection.Leave(); } else { - if (Timeout > 0) + if (timeout > 0) { - System.TimeManager.ScheduleFutureInvocation(CurrentThread, Timeout); + system.TimeManager.ScheduleFutureInvocation(currentThread, timeout); } - System.CriticalSection.Leave(); + system.CriticalSection.Leave(); - if (Timeout > 0) + if (timeout > 0) { - System.TimeManager.UnscheduleFutureInvocation(CurrentThread); + system.TimeManager.UnscheduleFutureInvocation(currentThread); } } - Monitor.Enter(Mutex); + Monitor.Enter(mutex); } - public static void NotifyAll(Horizon System, LinkedList ThreadList) + public static void NotifyAll(Horizon system, LinkedList threadList) { - System.CriticalSection.Enter(); + system.CriticalSection.Enter(); - LinkedListNode Node = ThreadList.First; + LinkedListNode node = threadList.First; - for (; Node != null; Node = ThreadList.First) + for (; node != null; node = threadList.First) { - KThread Thread = Node.Value; + KThread thread = node.Value; - ThreadList.Remove(Thread.WithholderNode); + threadList.Remove(thread.WithholderNode); - Thread.Withholder = null; + thread.Withholder = null; - Thread.Reschedule(ThreadSchedState.Running); + thread.Reschedule(ThreadSchedState.Running); } - System.CriticalSection.Leave(); + system.CriticalSection.Leave(); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/KContextIdManager.cs b/Ryujinx.HLE/HOS/Kernel/KContextIdManager.cs index 03e7dddf..80a1c1c7 100644 --- a/Ryujinx.HLE/HOS/Kernel/KContextIdManager.cs +++ b/Ryujinx.HLE/HOS/Kernel/KContextIdManager.cs @@ -7,77 +7,77 @@ namespace Ryujinx.HLE.HOS.Kernel { private const int IdMasksCount = 8; - private int[] IdMasks; + private int[] _idMasks; - private int NextFreeBitHint; + private int _nextFreeBitHint; public KContextIdManager() { - IdMasks = new int[IdMasksCount]; + _idMasks = new int[IdMasksCount]; } public int GetId() { - lock (IdMasks) + lock (_idMasks) { - int Id = 0; + int id = 0; - if (!TestBit(NextFreeBitHint)) + if (!TestBit(_nextFreeBitHint)) { - Id = NextFreeBitHint; + id = _nextFreeBitHint; } else { - for (int Index = 0; Index < IdMasksCount; Index++) + for (int index = 0; index < IdMasksCount; index++) { - int Mask = IdMasks[Index]; + int mask = _idMasks[index]; - int FirstFreeBit = BitUtils.CountLeadingZeros32((Mask + 1) & ~Mask); + int firstFreeBit = BitUtils.CountLeadingZeros32((mask + 1) & ~mask); - if (FirstFreeBit < 32) + if (firstFreeBit < 32) { - int BaseBit = Index * 32 + 31; + int baseBit = index * 32 + 31; - Id = BaseBit - FirstFreeBit; + id = baseBit - firstFreeBit; break; } - else if (Index == IdMasksCount - 1) + else if (index == IdMasksCount - 1) { throw new InvalidOperationException("Maximum number of Ids reached!"); } } } - NextFreeBitHint = Id + 1; + _nextFreeBitHint = id + 1; - SetBit(Id); + SetBit(id); - return Id; + return id; } } - public void PutId(int Id) + public void PutId(int id) { - lock (IdMasks) + lock (_idMasks) { - ClearBit(Id); + ClearBit(id); } } - private bool TestBit(int Bit) + private bool TestBit(int bit) { - return (IdMasks[NextFreeBitHint / 32] & (1 << (NextFreeBitHint & 31))) != 0; + return (_idMasks[_nextFreeBitHint / 32] & (1 << (_nextFreeBitHint & 31))) != 0; } - private void SetBit(int Bit) + private void SetBit(int bit) { - IdMasks[NextFreeBitHint / 32] |= (1 << (NextFreeBitHint & 31)); + _idMasks[_nextFreeBitHint / 32] |= (1 << (_nextFreeBitHint & 31)); } - private void ClearBit(int Bit) + private void ClearBit(int bit) { - IdMasks[NextFreeBitHint / 32] &= ~(1 << (NextFreeBitHint & 31)); + _idMasks[_nextFreeBitHint / 32] &= ~(1 << (_nextFreeBitHint & 31)); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/KCoreContext.cs b/Ryujinx.HLE/HOS/Kernel/KCoreContext.cs index 638dde9e..4ca3c25a 100644 --- a/Ryujinx.HLE/HOS/Kernel/KCoreContext.cs +++ b/Ryujinx.HLE/HOS/Kernel/KCoreContext.cs @@ -4,9 +4,9 @@ namespace Ryujinx.HLE.HOS.Kernel { class KCoreContext { - private KScheduler Scheduler; + private KScheduler _scheduler; - private HleCoreManager CoreManager; + private HleCoreManager _coreManager; public bool ContextSwitchNeeded { get; private set; } @@ -17,15 +17,15 @@ namespace Ryujinx.HLE.HOS.Kernel public KThread CurrentThread { get; private set; } public KThread SelectedThread { get; private set; } - public KCoreContext(KScheduler Scheduler, HleCoreManager CoreManager) + public KCoreContext(KScheduler scheduler, HleCoreManager coreManager) { - this.Scheduler = Scheduler; - this.CoreManager = CoreManager; + _scheduler = scheduler; + _coreManager = coreManager; } - public void SelectThread(KThread Thread) + public void SelectThread(KThread thread) { - SelectedThread = Thread; + SelectedThread = thread; if (SelectedThread != CurrentThread) { @@ -43,10 +43,10 @@ namespace Ryujinx.HLE.HOS.Kernel if (CurrentThread != null) { - long CurrentTime = PerformanceCounter.ElapsedMilliseconds; + long currentTime = PerformanceCounter.ElapsedMilliseconds; - CurrentThread.TotalTimeRunning += CurrentTime - CurrentThread.LastScheduledTime; - CurrentThread.LastScheduledTime = CurrentTime; + CurrentThread.TotalTimeRunning += currentTime - CurrentThread.LastScheduledTime; + CurrentThread.LastScheduledTime = currentTime; } } @@ -58,21 +58,21 @@ namespace Ryujinx.HLE.HOS.Kernel if (CurrentThread != null) { - CoreManager.Reset(CurrentThread.Context.Work); + _coreManager.Reset(CurrentThread.Context.Work); } CurrentThread = SelectedThread; if (CurrentThread != null) { - long CurrentTime = PerformanceCounter.ElapsedMilliseconds; + long currentTime = PerformanceCounter.ElapsedMilliseconds; - CurrentThread.TotalTimeRunning += CurrentTime - CurrentThread.LastScheduledTime; - CurrentThread.LastScheduledTime = CurrentTime; + CurrentThread.TotalTimeRunning += currentTime - CurrentThread.LastScheduledTime; + CurrentThread.LastScheduledTime = currentTime; CurrentThread.ClearExclusive(); - CoreManager.Set(CurrentThread.Context.Work); + _coreManager.Set(CurrentThread.Context.Work); CurrentThread.Context.Execute(); } diff --git a/Ryujinx.HLE/HOS/Kernel/KCriticalSection.cs b/Ryujinx.HLE/HOS/Kernel/KCriticalSection.cs index b02a1195..a54dc6cb 100644 --- a/Ryujinx.HLE/HOS/Kernel/KCriticalSection.cs +++ b/Ryujinx.HLE/HOS/Kernel/KCriticalSection.cs @@ -5,15 +5,15 @@ namespace Ryujinx.HLE.HOS.Kernel { class KCriticalSection { - private Horizon System; + private Horizon _system; public object LockObj { get; private set; } - private int RecursionCount; + private int _recursionCount; - public KCriticalSection(Horizon System) + public KCriticalSection(Horizon system) { - this.System = System; + _system = system; LockObj = new object(); } @@ -22,53 +22,53 @@ namespace Ryujinx.HLE.HOS.Kernel { Monitor.Enter(LockObj); - RecursionCount++; + _recursionCount++; } public void Leave() { - if (RecursionCount == 0) + if (_recursionCount == 0) { return; } - bool DoContextSwitch = false; + bool doContextSwitch = false; - if (--RecursionCount == 0) + if (--_recursionCount == 0) { - if (System.Scheduler.ThreadReselectionRequested) + if (_system.Scheduler.ThreadReselectionRequested) { - System.Scheduler.SelectThreads(); + _system.Scheduler.SelectThreads(); } Monitor.Exit(LockObj); - if (System.Scheduler.MultiCoreScheduling) + if (_system.Scheduler.MultiCoreScheduling) { - lock (System.Scheduler.CoreContexts) + lock (_system.Scheduler.CoreContexts) { - for (int Core = 0; Core < KScheduler.CpuCoresCount; Core++) + for (int core = 0; core < KScheduler.CpuCoresCount; core++) { - KCoreContext CoreContext = System.Scheduler.CoreContexts[Core]; + KCoreContext coreContext = _system.Scheduler.CoreContexts[core]; - if (CoreContext.ContextSwitchNeeded) + if (coreContext.ContextSwitchNeeded) { - CpuThread CurrentHleThread = CoreContext.CurrentThread?.Context; + CpuThread currentHleThread = coreContext.CurrentThread?.Context; - if (CurrentHleThread == null) + if (currentHleThread == null) { //Nothing is running, we can perform the context switch immediately. - CoreContext.ContextSwitch(); + coreContext.ContextSwitch(); } - else if (CurrentHleThread.IsCurrentThread()) + else if (currentHleThread.IsCurrentThread()) { //Thread running on the current core, context switch will block. - DoContextSwitch = true; + doContextSwitch = true; } else { //Thread running on another core, request a interrupt. - CurrentHleThread.RequestInterrupt(); + currentHleThread.RequestInterrupt(); } } } @@ -76,7 +76,7 @@ namespace Ryujinx.HLE.HOS.Kernel } else { - DoContextSwitch = true; + doContextSwitch = true; } } else @@ -84,9 +84,9 @@ namespace Ryujinx.HLE.HOS.Kernel Monitor.Exit(LockObj); } - if (DoContextSwitch) + if (doContextSwitch) { - System.Scheduler.ContextSwitch(); + _system.Scheduler.ContextSwitch(); } } } diff --git a/Ryujinx.HLE/HOS/Kernel/KEvent.cs b/Ryujinx.HLE/HOS/Kernel/KEvent.cs index 106d1b40..aa2124ec 100644 --- a/Ryujinx.HLE/HOS/Kernel/KEvent.cs +++ b/Ryujinx.HLE/HOS/Kernel/KEvent.cs @@ -5,9 +5,9 @@ namespace Ryujinx.HLE.HOS.Kernel public KReadableEvent ReadableEvent { get; private set; } public KWritableEvent WritableEvent { get; private set; } - public KEvent(Horizon System) + public KEvent(Horizon system) { - ReadableEvent = new KReadableEvent(System, this); + ReadableEvent = new KReadableEvent(system, this); WritableEvent = new KWritableEvent(this); } } diff --git a/Ryujinx.HLE/HOS/Kernel/KHandleEntry.cs b/Ryujinx.HLE/HOS/Kernel/KHandleEntry.cs index 9863a374..42e59329 100644 --- a/Ryujinx.HLE/HOS/Kernel/KHandleEntry.cs +++ b/Ryujinx.HLE/HOS/Kernel/KHandleEntry.cs @@ -9,9 +9,9 @@ namespace Ryujinx.HLE.HOS.Kernel public ushort HandleId { get; set; } public object Obj { get; set; } - public KHandleEntry(int Index) + public KHandleEntry(int index) { - this.Index = Index; + Index = index; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/KHandleTable.cs b/Ryujinx.HLE/HOS/Kernel/KHandleTable.cs index e39dfb67..88d0c513 100644 --- a/Ryujinx.HLE/HOS/Kernel/KHandleTable.cs +++ b/Ryujinx.HLE/HOS/Kernel/KHandleTable.cs @@ -7,148 +7,148 @@ namespace Ryujinx.HLE.HOS.Kernel private const int SelfThreadHandle = (0x1ffff << 15) | 0; private const int SelfProcessHandle = (0x1ffff << 15) | 1; - private Horizon System; + private Horizon _system; - private KHandleEntry[] Table; + private KHandleEntry[] _table; - private KHandleEntry TableHead; - private KHandleEntry NextFreeEntry; + private KHandleEntry _tableHead; + private KHandleEntry _nextFreeEntry; - private int ActiveSlotsCount; + private int _activeSlotsCount; - private int Size; + private int _size; - private ushort IdCounter; + private ushort _idCounter; - public KHandleTable(Horizon System) + public KHandleTable(Horizon system) { - this.System = System; + _system = system; } - public KernelResult Initialize(int Size) + public KernelResult Initialize(int size) { - if ((uint)Size > 1024) + if ((uint)size > 1024) { return KernelResult.OutOfMemory; } - if (Size < 1) + if (size < 1) { - Size = 1024; + size = 1024; } - this.Size = Size; + _size = size; - IdCounter = 1; + _idCounter = 1; - Table = new KHandleEntry[Size]; + _table = new KHandleEntry[size]; - TableHead = new KHandleEntry(0); + _tableHead = new KHandleEntry(0); - KHandleEntry Entry = TableHead; + KHandleEntry entry = _tableHead; - for (int Index = 0; Index < Size; Index++) + for (int index = 0; index < size; index++) { - Table[Index] = Entry; + _table[index] = entry; - Entry.Next = new KHandleEntry(Index + 1); + entry.Next = new KHandleEntry(index + 1); - Entry = Entry.Next; + entry = entry.Next; } - Table[Size - 1].Next = null; + _table[size - 1].Next = null; - NextFreeEntry = TableHead; + _nextFreeEntry = _tableHead; return KernelResult.Success; } - public KernelResult GenerateHandle(object Obj, out int Handle) + public KernelResult GenerateHandle(object obj, out int handle) { - Handle = 0; + handle = 0; - lock (Table) + lock (_table) { - if (ActiveSlotsCount >= Size) + if (_activeSlotsCount >= _size) { return KernelResult.HandleTableFull; } - KHandleEntry Entry = NextFreeEntry; + KHandleEntry entry = _nextFreeEntry; - NextFreeEntry = Entry.Next; + _nextFreeEntry = entry.Next; - Entry.Obj = Obj; - Entry.HandleId = IdCounter; + entry.Obj = obj; + entry.HandleId = _idCounter; - ActiveSlotsCount++; + _activeSlotsCount++; - Handle = (int)((IdCounter << 15) & (uint)0xffff8000) | Entry.Index; + handle = (int)((_idCounter << 15) & 0xffff8000) | entry.Index; - if ((short)(IdCounter + 1) >= 0) + if ((short)(_idCounter + 1) >= 0) { - IdCounter++; + _idCounter++; } else { - IdCounter = 1; + _idCounter = 1; } } return KernelResult.Success; } - public bool CloseHandle(int Handle) + public bool CloseHandle(int handle) { - if ((Handle >> 30) != 0 || - Handle == SelfThreadHandle || - Handle == SelfProcessHandle) + if ((handle >> 30) != 0 || + handle == SelfThreadHandle || + handle == SelfProcessHandle) { return false; } - int Index = (Handle >> 0) & 0x7fff; - int HandleId = (Handle >> 15); + int index = (handle >> 0) & 0x7fff; + int handleId = (handle >> 15); - bool Result = false; + bool result = false; - lock (Table) + lock (_table) { - if (HandleId != 0 && Index < Size) + if (handleId != 0 && index < _size) { - KHandleEntry Entry = Table[Index]; + KHandleEntry entry = _table[index]; - if (Entry.Obj != null && Entry.HandleId == HandleId) + if (entry.Obj != null && entry.HandleId == handleId) { - Entry.Obj = null; - Entry.Next = NextFreeEntry; + entry.Obj = null; + entry.Next = _nextFreeEntry; - NextFreeEntry = Entry; + _nextFreeEntry = entry; - ActiveSlotsCount--; + _activeSlotsCount--; - Result = true; + result = true; } } } - return Result; + return result; } - public T GetObject(int Handle) + public T GetObject(int handle) { - int Index = (Handle >> 0) & 0x7fff; - int HandleId = (Handle >> 15); + int index = (handle >> 0) & 0x7fff; + int handleId = (handle >> 15); - lock (Table) + lock (_table) { - if ((Handle >> 30) == 0 && HandleId != 0) + if ((handle >> 30) == 0 && handleId != 0) { - KHandleEntry Entry = Table[Index]; + KHandleEntry entry = _table[index]; - if (Entry.HandleId == HandleId && Entry.Obj is T Obj) + if (entry.HandleId == handleId && entry.Obj is T obj) { - return Obj; + return obj; } } } @@ -156,49 +156,49 @@ namespace Ryujinx.HLE.HOS.Kernel return default(T); } - public KThread GetKThread(int Handle) + public KThread GetKThread(int handle) { - if (Handle == SelfThreadHandle) + if (handle == SelfThreadHandle) { - return System.Scheduler.GetCurrentThread(); + return _system.Scheduler.GetCurrentThread(); } else { - return GetObject(Handle); + return GetObject(handle); } } - public KProcess GetKProcess(int Handle) + public KProcess GetKProcess(int handle) { - if (Handle == SelfProcessHandle) + if (handle == SelfProcessHandle) { - return System.Scheduler.GetCurrentProcess(); + return _system.Scheduler.GetCurrentProcess(); } else { - return GetObject(Handle); + return GetObject(handle); } } public void Destroy() { - lock (Table) + lock (_table) { - for (int Index = 0; Index < Size; Index++) + for (int index = 0; index < _size; index++) { - KHandleEntry Entry = Table[Index]; + KHandleEntry entry = _table[index]; - if (Entry.Obj != null) + if (entry.Obj != null) { - if (Entry.Obj is IDisposable DisposableObj) + if (entry.Obj is IDisposable disposableObj) { - DisposableObj.Dispose(); + disposableObj.Dispose(); } - Entry.Obj = null; - Entry.Next = NextFreeEntry; + entry.Obj = null; + entry.Next = _nextFreeEntry; - NextFreeEntry = Entry; + _nextFreeEntry = entry; } } } diff --git a/Ryujinx.HLE/HOS/Kernel/KMemoryArrange.cs b/Ryujinx.HLE/HOS/Kernel/KMemoryArrange.cs index af393b68..de8bf3b1 100644 --- a/Ryujinx.HLE/HOS/Kernel/KMemoryArrange.cs +++ b/Ryujinx.HLE/HOS/Kernel/KMemoryArrange.cs @@ -8,15 +8,15 @@ namespace Ryujinx.HLE.HOS.Kernel public KMemoryArrangeRegion Application { get; private set; } public KMemoryArrange( - KMemoryArrangeRegion Service, - KMemoryArrangeRegion NvServices, - KMemoryArrangeRegion Applet, - KMemoryArrangeRegion Application) + KMemoryArrangeRegion service, + KMemoryArrangeRegion nvServices, + KMemoryArrangeRegion applet, + KMemoryArrangeRegion application) { - this.Service = Service; - this.NvServices = NvServices; - this.Applet = Applet; - this.Application = Application; + Service = service; + NvServices = nvServices; + Applet = applet; + Application = application; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/KMemoryArrangeRegion.cs b/Ryujinx.HLE/HOS/Kernel/KMemoryArrangeRegion.cs index 7d66e291..4fe58d73 100644 --- a/Ryujinx.HLE/HOS/Kernel/KMemoryArrangeRegion.cs +++ b/Ryujinx.HLE/HOS/Kernel/KMemoryArrangeRegion.cs @@ -7,10 +7,10 @@ namespace Ryujinx.HLE.HOS.Kernel public ulong EndAddr => Address + Size; - public KMemoryArrangeRegion(ulong Address, ulong Size) + public KMemoryArrangeRegion(ulong address, ulong size) { - this.Address = Address; - this.Size = Size; + Address = address; + Size = size; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/KMemoryBlock.cs b/Ryujinx.HLE/HOS/Kernel/KMemoryBlock.cs index 08190236..44b7a683 100644 --- a/Ryujinx.HLE/HOS/Kernel/KMemoryBlock.cs +++ b/Ryujinx.HLE/HOS/Kernel/KMemoryBlock.cs @@ -13,26 +13,26 @@ namespace Ryujinx.HLE.HOS.Kernel public int DeviceRefCount { get; set; } public KMemoryBlock( - ulong BaseAddress, - ulong PagesCount, - MemoryState State, - MemoryPermission Permission, - MemoryAttribute Attribute) + ulong baseAddress, + ulong pagesCount, + MemoryState state, + MemoryPermission permission, + MemoryAttribute attribute) { - this.BaseAddress = BaseAddress; - this.PagesCount = PagesCount; - this.State = State; - this.Attribute = Attribute; - this.Permission = Permission; + BaseAddress = baseAddress; + PagesCount = pagesCount; + State = state; + Attribute = attribute; + Permission = permission; } public KMemoryInfo GetInfo() { - ulong Size = PagesCount * KMemoryManager.PageSize; + ulong size = PagesCount * KMemoryManager.PageSize; return new KMemoryInfo( BaseAddress, - Size, + size, State, Permission, Attribute, diff --git a/Ryujinx.HLE/HOS/Kernel/KMemoryBlockAllocator.cs b/Ryujinx.HLE/HOS/Kernel/KMemoryBlockAllocator.cs index 08512e12..375685e6 100644 --- a/Ryujinx.HLE/HOS/Kernel/KMemoryBlockAllocator.cs +++ b/Ryujinx.HLE/HOS/Kernel/KMemoryBlockAllocator.cs @@ -2,18 +2,18 @@ namespace Ryujinx.HLE.HOS.Kernel { class KMemoryBlockAllocator { - private ulong CapacityElements; + private ulong _capacityElements; public int Count { get; set; } - public KMemoryBlockAllocator(ulong CapacityElements) + public KMemoryBlockAllocator(ulong capacityElements) { - this.CapacityElements = CapacityElements; + _capacityElements = capacityElements; } - public bool CanAllocate(int Count) + public bool CanAllocate(int count) { - return (ulong)(this.Count + Count) <= CapacityElements; + return (ulong)(Count + count) <= _capacityElements; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/KMemoryInfo.cs b/Ryujinx.HLE/HOS/Kernel/KMemoryInfo.cs index 09ba88f2..0372e0d3 100644 --- a/Ryujinx.HLE/HOS/Kernel/KMemoryInfo.cs +++ b/Ryujinx.HLE/HOS/Kernel/KMemoryInfo.cs @@ -13,21 +13,21 @@ namespace Ryujinx.HLE.HOS.Kernel public int DeviceRefCount { get; private set; } public KMemoryInfo( - ulong Address, - ulong Size, - MemoryState State, - MemoryPermission Permission, - MemoryAttribute Attribute, - int IpcRefCount, - int DeviceRefCount) + ulong address, + ulong size, + MemoryState state, + MemoryPermission permission, + MemoryAttribute attribute, + int ipcRefCount, + int deviceRefCount) { - this.Address = Address; - this.Size = Size; - this.State = State; - this.Attribute = Attribute; - this.Permission = Permission; - this.IpcRefCount = IpcRefCount; - this.DeviceRefCount = DeviceRefCount; + Address = address; + Size = size; + State = state; + Attribute = attribute; + Permission = permission; + IpcRefCount = ipcRefCount; + DeviceRefCount = deviceRefCount; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/KMemoryManager.cs b/Ryujinx.HLE/HOS/Kernel/KMemoryManager.cs index 0aa21e3f..831844c7 100644 --- a/Ryujinx.HLE/HOS/Kernel/KMemoryManager.cs +++ b/Ryujinx.HLE/HOS/Kernel/KMemoryManager.cs @@ -15,11 +15,11 @@ namespace Ryujinx.HLE.HOS.Kernel //needs to be split in 2, plus one block that will be the new one inserted. private const int MaxBlocksNeededForInsertion = 2; - private LinkedList Blocks; + private LinkedList _blocks; - private MemoryManager CpuMemory; + private MemoryManager _cpuMemory; - private Horizon System; + private Horizon _system; public ulong AddrSpaceStart { get; private set; } public ulong AddrSpaceEnd { get; private set; } @@ -30,7 +30,7 @@ namespace Ryujinx.HLE.HOS.Kernel public ulong HeapRegionStart { get; private set; } public ulong HeapRegionEnd { get; private set; } - private ulong CurrentHeapAddr; + private ulong _currentHeapAddr; public ulong AliasRegionStart { get; private set; } public ulong AliasRegionEnd { get; private set; } @@ -41,71 +41,71 @@ namespace Ryujinx.HLE.HOS.Kernel public ulong TlsIoRegionStart { get; private set; } public ulong TlsIoRegionEnd { get; private set; } - private ulong HeapCapacity; + private ulong _heapCapacity; public ulong PhysicalMemoryUsage { get; private set; } - private MemoryRegion MemRegion; + private MemoryRegion _memRegion; - private bool AslrDisabled; + private bool _aslrDisabled; public int AddrSpaceWidth { get; private set; } - private bool IsKernel; - private bool AslrEnabled; + private bool _isKernel; + private bool _aslrEnabled; - private KMemoryBlockAllocator BlockAllocator; + private KMemoryBlockAllocator _blockAllocator; - private int ContextId; + private int _contextId; - private MersenneTwister RandomNumberGenerator; + private MersenneTwister _randomNumberGenerator; - public KMemoryManager(Horizon System, MemoryManager CpuMemory) + public KMemoryManager(Horizon system, MemoryManager cpuMemory) { - this.System = System; - this.CpuMemory = CpuMemory; + _system = system; + _cpuMemory = cpuMemory; - Blocks = new LinkedList(); + _blocks = new LinkedList(); } private static readonly int[] AddrSpaceSizes = new int[] { 32, 36, 32, 39 }; public KernelResult InitializeForProcess( - AddressSpaceType AddrSpaceType, - bool AslrEnabled, - bool AslrDisabled, - MemoryRegion MemRegion, - ulong Address, - ulong Size, - KMemoryBlockAllocator BlockAllocator) + AddressSpaceType addrSpaceType, + bool aslrEnabled, + bool aslrDisabled, + MemoryRegion memRegion, + ulong address, + ulong size, + KMemoryBlockAllocator blockAllocator) { - if ((uint)AddrSpaceType > (uint)AddressSpaceType.Addr39Bits) + if ((uint)addrSpaceType > (uint)AddressSpaceType.Addr39Bits) { - throw new ArgumentException(nameof(AddrSpaceType)); + throw new ArgumentException(nameof(addrSpaceType)); } - ContextId = System.ContextIdManager.GetId(); + _contextId = _system.ContextIdManager.GetId(); - ulong AddrSpaceBase = 0; - ulong AddrSpaceSize = 1UL << AddrSpaceSizes[(int)AddrSpaceType]; + ulong addrSpaceBase = 0; + ulong addrSpaceSize = 1UL << AddrSpaceSizes[(int)addrSpaceType]; - KernelResult Result = CreateUserAddressSpace( - AddrSpaceType, - AslrEnabled, - AslrDisabled, - AddrSpaceBase, - AddrSpaceSize, - MemRegion, - Address, - Size, - BlockAllocator); + KernelResult result = CreateUserAddressSpace( + addrSpaceType, + aslrEnabled, + aslrDisabled, + addrSpaceBase, + addrSpaceSize, + memRegion, + address, + size, + blockAllocator); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - System.ContextIdManager.PutId(ContextId); + _system.ContextIdManager.PutId(_contextId); } - return Result; + return result; } private class Region @@ -117,328 +117,328 @@ namespace Ryujinx.HLE.HOS.Kernel } private KernelResult CreateUserAddressSpace( - AddressSpaceType AddrSpaceType, - bool AslrEnabled, - bool AslrDisabled, - ulong AddrSpaceStart, - ulong AddrSpaceEnd, - MemoryRegion MemRegion, - ulong Address, - ulong Size, - KMemoryBlockAllocator BlockAllocator) + AddressSpaceType addrSpaceType, + bool aslrEnabled, + bool aslrDisabled, + ulong addrSpaceStart, + ulong addrSpaceEnd, + MemoryRegion memRegion, + ulong address, + ulong size, + KMemoryBlockAllocator blockAllocator) { - ulong EndAddr = Address + Size; + ulong endAddr = address + size; - Region AliasRegion = new Region(); - Region HeapRegion = new Region(); - Region StackRegion = new Region(); - Region TlsIoRegion = new Region(); + Region aliasRegion = new Region(); + Region heapRegion = new Region(); + Region stackRegion = new Region(); + Region tlsIoRegion = new Region(); - ulong CodeRegionSize; - ulong StackAndTlsIoStart; - ulong StackAndTlsIoEnd; - ulong BaseAddress; + ulong codeRegionSize; + ulong stackAndTlsIoStart; + ulong stackAndTlsIoEnd; + ulong baseAddress; - switch (AddrSpaceType) + switch (addrSpaceType) { case AddressSpaceType.Addr32Bits: - AliasRegion.Size = 0x40000000; - HeapRegion.Size = 0x40000000; - StackRegion.Size = 0; - TlsIoRegion.Size = 0; + aliasRegion.Size = 0x40000000; + heapRegion.Size = 0x40000000; + stackRegion.Size = 0; + tlsIoRegion.Size = 0; CodeRegionStart = 0x200000; - CodeRegionSize = 0x3fe00000; - StackAndTlsIoStart = 0x200000; - StackAndTlsIoEnd = 0x40000000; - BaseAddress = 0x200000; + codeRegionSize = 0x3fe00000; + stackAndTlsIoStart = 0x200000; + stackAndTlsIoEnd = 0x40000000; + baseAddress = 0x200000; AddrSpaceWidth = 32; break; case AddressSpaceType.Addr36Bits: - AliasRegion.Size = 0x180000000; - HeapRegion.Size = 0x180000000; - StackRegion.Size = 0; - TlsIoRegion.Size = 0; + aliasRegion.Size = 0x180000000; + heapRegion.Size = 0x180000000; + stackRegion.Size = 0; + tlsIoRegion.Size = 0; CodeRegionStart = 0x8000000; - CodeRegionSize = 0x78000000; - StackAndTlsIoStart = 0x8000000; - StackAndTlsIoEnd = 0x80000000; - BaseAddress = 0x8000000; + codeRegionSize = 0x78000000; + stackAndTlsIoStart = 0x8000000; + stackAndTlsIoEnd = 0x80000000; + baseAddress = 0x8000000; AddrSpaceWidth = 36; break; case AddressSpaceType.Addr32BitsNoMap: - AliasRegion.Size = 0; - HeapRegion.Size = 0x80000000; - StackRegion.Size = 0; - TlsIoRegion.Size = 0; + aliasRegion.Size = 0; + heapRegion.Size = 0x80000000; + stackRegion.Size = 0; + tlsIoRegion.Size = 0; CodeRegionStart = 0x200000; - CodeRegionSize = 0x3fe00000; - StackAndTlsIoStart = 0x200000; - StackAndTlsIoEnd = 0x40000000; - BaseAddress = 0x200000; + codeRegionSize = 0x3fe00000; + stackAndTlsIoStart = 0x200000; + stackAndTlsIoEnd = 0x40000000; + baseAddress = 0x200000; AddrSpaceWidth = 32; break; case AddressSpaceType.Addr39Bits: - AliasRegion.Size = 0x1000000000; - HeapRegion.Size = 0x180000000; - StackRegion.Size = 0x80000000; - TlsIoRegion.Size = 0x1000000000; - CodeRegionStart = BitUtils.AlignDown(Address, 0x200000); - CodeRegionSize = BitUtils.AlignUp (EndAddr, 0x200000) - CodeRegionStart; - StackAndTlsIoStart = 0; - StackAndTlsIoEnd = 0; - BaseAddress = 0x8000000; + aliasRegion.Size = 0x1000000000; + heapRegion.Size = 0x180000000; + stackRegion.Size = 0x80000000; + tlsIoRegion.Size = 0x1000000000; + CodeRegionStart = BitUtils.AlignDown(address, 0x200000); + codeRegionSize = BitUtils.AlignUp (endAddr, 0x200000) - CodeRegionStart; + stackAndTlsIoStart = 0; + stackAndTlsIoEnd = 0; + baseAddress = 0x8000000; AddrSpaceWidth = 39; break; - default: throw new ArgumentException(nameof(AddrSpaceType)); + default: throw new ArgumentException(nameof(addrSpaceType)); } - CodeRegionEnd = CodeRegionStart + CodeRegionSize; + CodeRegionEnd = CodeRegionStart + codeRegionSize; - ulong MapBaseAddress; - ulong MapAvailableSize; + ulong mapBaseAddress; + ulong mapAvailableSize; - if (CodeRegionStart - BaseAddress >= AddrSpaceEnd - CodeRegionEnd) + if (CodeRegionStart - baseAddress >= addrSpaceEnd - CodeRegionEnd) { //Has more space before the start of the code region. - MapBaseAddress = BaseAddress; - MapAvailableSize = CodeRegionStart - BaseAddress; + mapBaseAddress = baseAddress; + mapAvailableSize = CodeRegionStart - baseAddress; } else { //Has more space after the end of the code region. - MapBaseAddress = CodeRegionEnd; - MapAvailableSize = AddrSpaceEnd - CodeRegionEnd; + mapBaseAddress = CodeRegionEnd; + mapAvailableSize = addrSpaceEnd - CodeRegionEnd; } - ulong MapTotalSize = AliasRegion.Size + HeapRegion.Size + StackRegion.Size + TlsIoRegion.Size; + ulong mapTotalSize = aliasRegion.Size + heapRegion.Size + stackRegion.Size + tlsIoRegion.Size; - ulong AslrMaxOffset = MapAvailableSize - MapTotalSize; + ulong aslrMaxOffset = mapAvailableSize - mapTotalSize; - this.AslrEnabled = AslrEnabled; + _aslrEnabled = aslrEnabled; - this.AddrSpaceStart = AddrSpaceStart; - this.AddrSpaceEnd = AddrSpaceEnd; + AddrSpaceStart = addrSpaceStart; + AddrSpaceEnd = addrSpaceEnd; - this.BlockAllocator = BlockAllocator; + _blockAllocator = blockAllocator; - if (MapAvailableSize < MapTotalSize) + if (mapAvailableSize < mapTotalSize) { return KernelResult.OutOfMemory; } - if (AslrEnabled) + if (aslrEnabled) { - AliasRegion.AslrOffset = GetRandomValue(0, AslrMaxOffset >> 21) << 21; - HeapRegion.AslrOffset = GetRandomValue(0, AslrMaxOffset >> 21) << 21; - StackRegion.AslrOffset = GetRandomValue(0, AslrMaxOffset >> 21) << 21; - TlsIoRegion.AslrOffset = GetRandomValue(0, AslrMaxOffset >> 21) << 21; + aliasRegion.AslrOffset = GetRandomValue(0, aslrMaxOffset >> 21) << 21; + heapRegion.AslrOffset = GetRandomValue(0, aslrMaxOffset >> 21) << 21; + stackRegion.AslrOffset = GetRandomValue(0, aslrMaxOffset >> 21) << 21; + tlsIoRegion.AslrOffset = GetRandomValue(0, aslrMaxOffset >> 21) << 21; } //Regions are sorted based on ASLR offset. //When ASLR is disabled, the order is Map, Heap, NewMap and TlsIo. - AliasRegion.Start = MapBaseAddress + AliasRegion.AslrOffset; - AliasRegion.End = AliasRegion.Start + AliasRegion.Size; - HeapRegion.Start = MapBaseAddress + HeapRegion.AslrOffset; - HeapRegion.End = HeapRegion.Start + HeapRegion.Size; - StackRegion.Start = MapBaseAddress + StackRegion.AslrOffset; - StackRegion.End = StackRegion.Start + StackRegion.Size; - TlsIoRegion.Start = MapBaseAddress + TlsIoRegion.AslrOffset; - TlsIoRegion.End = TlsIoRegion.Start + TlsIoRegion.Size; + aliasRegion.Start = mapBaseAddress + aliasRegion.AslrOffset; + aliasRegion.End = aliasRegion.Start + aliasRegion.Size; + heapRegion.Start = mapBaseAddress + heapRegion.AslrOffset; + heapRegion.End = heapRegion.Start + heapRegion.Size; + stackRegion.Start = mapBaseAddress + stackRegion.AslrOffset; + stackRegion.End = stackRegion.Start + stackRegion.Size; + tlsIoRegion.Start = mapBaseAddress + tlsIoRegion.AslrOffset; + tlsIoRegion.End = tlsIoRegion.Start + tlsIoRegion.Size; - SortRegion(HeapRegion, AliasRegion); + SortRegion(heapRegion, aliasRegion); - if (StackRegion.Size != 0) + if (stackRegion.Size != 0) { - SortRegion(StackRegion, AliasRegion); - SortRegion(StackRegion, HeapRegion); + SortRegion(stackRegion, aliasRegion); + SortRegion(stackRegion, heapRegion); } else { - StackRegion.Start = StackAndTlsIoStart; - StackRegion.End = StackAndTlsIoEnd; + stackRegion.Start = stackAndTlsIoStart; + stackRegion.End = stackAndTlsIoEnd; } - if (TlsIoRegion.Size != 0) + if (tlsIoRegion.Size != 0) { - SortRegion(TlsIoRegion, AliasRegion); - SortRegion(TlsIoRegion, HeapRegion); - SortRegion(TlsIoRegion, StackRegion); + SortRegion(tlsIoRegion, aliasRegion); + SortRegion(tlsIoRegion, heapRegion); + SortRegion(tlsIoRegion, stackRegion); } else { - TlsIoRegion.Start = StackAndTlsIoStart; - TlsIoRegion.End = StackAndTlsIoEnd; + tlsIoRegion.Start = stackAndTlsIoStart; + tlsIoRegion.End = stackAndTlsIoEnd; } - AliasRegionStart = AliasRegion.Start; - AliasRegionEnd = AliasRegion.End; - HeapRegionStart = HeapRegion.Start; - HeapRegionEnd = HeapRegion.End; - StackRegionStart = StackRegion.Start; - StackRegionEnd = StackRegion.End; - TlsIoRegionStart = TlsIoRegion.Start; - TlsIoRegionEnd = TlsIoRegion.End; + AliasRegionStart = aliasRegion.Start; + AliasRegionEnd = aliasRegion.End; + HeapRegionStart = heapRegion.Start; + HeapRegionEnd = heapRegion.End; + StackRegionStart = stackRegion.Start; + StackRegionEnd = stackRegion.End; + TlsIoRegionStart = tlsIoRegion.Start; + TlsIoRegionEnd = tlsIoRegion.End; - CurrentHeapAddr = HeapRegionStart; - HeapCapacity = 0; + _currentHeapAddr = HeapRegionStart; + _heapCapacity = 0; PhysicalMemoryUsage = 0; - this.MemRegion = MemRegion; - this.AslrDisabled = AslrDisabled; + _memRegion = memRegion; + _aslrDisabled = aslrDisabled; - return InitializeBlocks(AddrSpaceStart, AddrSpaceEnd); + return InitializeBlocks(addrSpaceStart, addrSpaceEnd); } - private ulong GetRandomValue(ulong Min, ulong Max) + private ulong GetRandomValue(ulong min, ulong max) { - return (ulong)GetRandomValue((long)Min, (long)Max); + return (ulong)GetRandomValue((long)min, (long)max); } - private long GetRandomValue(long Min, long Max) + private long GetRandomValue(long min, long max) { - if (RandomNumberGenerator == null) + if (_randomNumberGenerator == null) { - RandomNumberGenerator = new MersenneTwister(0); + _randomNumberGenerator = new MersenneTwister(0); } - return RandomNumberGenerator.GenRandomNumber(Min, Max); + return _randomNumberGenerator.GenRandomNumber(min, max); } - private static void SortRegion(Region Lhs, Region Rhs) + private static void SortRegion(Region lhs, Region rhs) { - if (Lhs.AslrOffset < Rhs.AslrOffset) + if (lhs.AslrOffset < rhs.AslrOffset) { - Rhs.Start += Lhs.Size; - Rhs.End += Lhs.Size; + rhs.Start += lhs.Size; + rhs.End += lhs.Size; } else { - Lhs.Start += Rhs.Size; - Lhs.End += Rhs.Size; + lhs.Start += rhs.Size; + lhs.End += rhs.Size; } } - private KernelResult InitializeBlocks(ulong AddrSpaceStart, ulong AddrSpaceEnd) + private KernelResult InitializeBlocks(ulong addrSpaceStart, ulong addrSpaceEnd) { //First insertion will always need only a single block, //because there's nothing else to split. - if (!BlockAllocator.CanAllocate(1)) + if (!_blockAllocator.CanAllocate(1)) { return KernelResult.OutOfResource; } - ulong AddrSpacePagesCount = (AddrSpaceEnd - AddrSpaceStart) / PageSize; + ulong addrSpacePagesCount = (addrSpaceEnd - addrSpaceStart) / PageSize; - InsertBlock(AddrSpaceStart, AddrSpacePagesCount, MemoryState.Unmapped); + InsertBlock(addrSpaceStart, addrSpacePagesCount, MemoryState.Unmapped); return KernelResult.Success; } public KernelResult MapPages( - ulong Address, - KPageList PageList, - MemoryState State, - MemoryPermission Permission) + ulong address, + KPageList pageList, + MemoryState state, + MemoryPermission permission) { - ulong PagesCount = PageList.GetPagesCount(); + ulong pagesCount = pageList.GetPagesCount(); - ulong Size = PagesCount * PageSize; + ulong size = pagesCount * PageSize; - if (!ValidateRegionForState(Address, Size, State)) + if (!ValidateRegionForState(address, size, state)) { return KernelResult.InvalidMemState; } - lock (Blocks) + lock (_blocks) { - if (!IsUnmapped(Address, PagesCount * PageSize)) + if (!IsUnmapped(address, pagesCount * PageSize)) { return KernelResult.InvalidMemState; } - if (!BlockAllocator.CanAllocate(MaxBlocksNeededForInsertion)) + if (!_blockAllocator.CanAllocate(MaxBlocksNeededForInsertion)) { return KernelResult.OutOfResource; } - KernelResult Result = MapPages(Address, PageList, Permission); + KernelResult result = MapPages(address, pageList, permission); - if (Result == KernelResult.Success) + if (result == KernelResult.Success) { - InsertBlock(Address, PagesCount, State, Permission); + InsertBlock(address, pagesCount, state, permission); } - return Result; + return result; } } - public KernelResult UnmapPages(ulong Address, KPageList PageList, MemoryState StateExpected) + public KernelResult UnmapPages(ulong address, KPageList pageList, MemoryState stateExpected) { - ulong PagesCount = PageList.GetPagesCount(); + ulong pagesCount = pageList.GetPagesCount(); - ulong Size = PagesCount * PageSize; + ulong size = pagesCount * PageSize; - ulong EndAddr = Address + Size; + ulong endAddr = address + size; - ulong AddrSpacePagesCount = (AddrSpaceEnd - AddrSpaceStart) / PageSize; + ulong addrSpacePagesCount = (AddrSpaceEnd - AddrSpaceStart) / PageSize; - if (AddrSpaceStart > Address) + if (AddrSpaceStart > address) { return KernelResult.InvalidMemState; } - if (AddrSpacePagesCount < PagesCount) + if (addrSpacePagesCount < pagesCount) { return KernelResult.InvalidMemState; } - if (EndAddr - 1 > AddrSpaceEnd - 1) + if (endAddr - 1 > AddrSpaceEnd - 1) { return KernelResult.InvalidMemState; } - lock (Blocks) + lock (_blocks) { - KPageList CurrentPageList = new KPageList(); + KPageList currentPageList = new KPageList(); - AddVaRangeToPageList(CurrentPageList, Address, PagesCount); + AddVaRangeToPageList(currentPageList, address, pagesCount); - if (!CurrentPageList.IsEqual(PageList)) + if (!currentPageList.IsEqual(pageList)) { return KernelResult.InvalidMemRange; } if (CheckRange( - Address, - Size, + address, + size, MemoryState.Mask, - StateExpected, + stateExpected, MemoryPermission.None, MemoryPermission.None, MemoryAttribute.Mask, MemoryAttribute.None, MemoryAttribute.IpcAndDeviceMapped, - out MemoryState State, + out MemoryState state, out _, out _)) { - if (!BlockAllocator.CanAllocate(MaxBlocksNeededForInsertion)) + if (!_blockAllocator.CanAllocate(MaxBlocksNeededForInsertion)) { return KernelResult.OutOfResource; } - KernelResult Result = MmuUnmap(Address, PagesCount); + KernelResult result = MmuUnmap(address, pagesCount); - if (Result == KernelResult.Success) + if (result == KernelResult.Success) { - InsertBlock(Address, PagesCount, MemoryState.Unmapped); + InsertBlock(address, pagesCount, MemoryState.Unmapped); } - return Result; + return result; } else { @@ -447,191 +447,191 @@ namespace Ryujinx.HLE.HOS.Kernel } } - public KernelResult MapNormalMemory(long Address, long Size, MemoryPermission Permission) + public KernelResult MapNormalMemory(long address, long size, MemoryPermission permission) { //TODO. return KernelResult.Success; } - public KernelResult MapIoMemory(long Address, long Size, MemoryPermission Permission) + public KernelResult MapIoMemory(long address, long size, MemoryPermission permission) { //TODO. return KernelResult.Success; } public KernelResult AllocateOrMapPa( - ulong NeededPagesCount, - int Alignment, - ulong SrcPa, - bool Map, - ulong RegionStart, - ulong RegionPagesCount, - MemoryState State, - MemoryPermission Permission, - out ulong Address) + ulong neededPagesCount, + int alignment, + ulong srcPa, + bool map, + ulong regionStart, + ulong regionPagesCount, + MemoryState state, + MemoryPermission permission, + out ulong address) { - Address = 0; + address = 0; - ulong RegionSize = RegionPagesCount * PageSize; + ulong regionSize = regionPagesCount * PageSize; - ulong RegionEndAddr = RegionStart + RegionSize; + ulong regionEndAddr = regionStart + regionSize; - if (!ValidateRegionForState(RegionStart, RegionSize, State)) + if (!ValidateRegionForState(regionStart, regionSize, state)) { return KernelResult.InvalidMemState; } - if (RegionPagesCount <= NeededPagesCount) + if (regionPagesCount <= neededPagesCount) { return KernelResult.OutOfMemory; } - ulong ReservedPagesCount = IsKernel ? 1UL : 4UL; + ulong reservedPagesCount = _isKernel ? 1UL : 4UL; - lock (Blocks) + lock (_blocks) { - if (AslrEnabled) + if (_aslrEnabled) { - ulong TotalNeededSize = (ReservedPagesCount + NeededPagesCount) * PageSize; + ulong totalNeededSize = (reservedPagesCount + neededPagesCount) * PageSize; - ulong RemainingPages = RegionPagesCount - NeededPagesCount; + ulong remainingPages = regionPagesCount - neededPagesCount; - ulong AslrMaxOffset = ((RemainingPages + ReservedPagesCount) * PageSize) / (ulong)Alignment; + ulong aslrMaxOffset = ((remainingPages + reservedPagesCount) * PageSize) / (ulong)alignment; - for (int Attempt = 0; Attempt < 8; Attempt++) + for (int attempt = 0; attempt < 8; attempt++) { - Address = BitUtils.AlignDown(RegionStart + GetRandomValue(0, AslrMaxOffset) * (ulong)Alignment, Alignment); + address = BitUtils.AlignDown(regionStart + GetRandomValue(0, aslrMaxOffset) * (ulong)alignment, alignment); - ulong EndAddr = Address + TotalNeededSize; + ulong endAddr = address + totalNeededSize; - KMemoryInfo Info = FindBlock(Address).GetInfo(); + KMemoryInfo info = FindBlock(address).GetInfo(); - if (Info.State != MemoryState.Unmapped) + if (info.State != MemoryState.Unmapped) { continue; } - ulong CurrBaseAddr = Info.Address + ReservedPagesCount * PageSize; - ulong CurrEndAddr = Info.Address + Info.Size; + ulong currBaseAddr = info.Address + reservedPagesCount * PageSize; + ulong currEndAddr = info.Address + info.Size; - if (Address >= RegionStart && - Address >= CurrBaseAddr && - EndAddr - 1 <= RegionEndAddr - 1 && - EndAddr - 1 <= CurrEndAddr - 1) + if (address >= regionStart && + address >= currBaseAddr && + endAddr - 1 <= regionEndAddr - 1 && + endAddr - 1 <= currEndAddr - 1) { break; } } - if (Address == 0) + if (address == 0) { - ulong AslrPage = GetRandomValue(0, AslrMaxOffset); + ulong aslrPage = GetRandomValue(0, aslrMaxOffset); - Address = FindFirstFit( - RegionStart + AslrPage * PageSize, - RegionPagesCount - AslrPage, - NeededPagesCount, - Alignment, + address = FindFirstFit( + regionStart + aslrPage * PageSize, + regionPagesCount - aslrPage, + neededPagesCount, + alignment, 0, - ReservedPagesCount); + reservedPagesCount); } } - if (Address == 0) + if (address == 0) { - Address = FindFirstFit( - RegionStart, - RegionPagesCount, - NeededPagesCount, - Alignment, + address = FindFirstFit( + regionStart, + regionPagesCount, + neededPagesCount, + alignment, 0, - ReservedPagesCount); + reservedPagesCount); } - if (Address == 0) + if (address == 0) { return KernelResult.OutOfMemory; } - if (!BlockAllocator.CanAllocate(MaxBlocksNeededForInsertion)) + if (!_blockAllocator.CanAllocate(MaxBlocksNeededForInsertion)) { return KernelResult.OutOfResource; } - MemoryOperation Operation = Map + MemoryOperation operation = map ? MemoryOperation.MapPa : MemoryOperation.Allocate; - KernelResult Result = DoMmuOperation( - Address, - NeededPagesCount, - SrcPa, - Map, - Permission, - Operation); + KernelResult result = DoMmuOperation( + address, + neededPagesCount, + srcPa, + map, + permission, + operation); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - return Result; + return result; } - InsertBlock(Address, NeededPagesCount, State, Permission); + InsertBlock(address, neededPagesCount, state, permission); } return KernelResult.Success; } public KernelResult MapNewProcessCode( - ulong Address, - ulong PagesCount, - MemoryState State, - MemoryPermission Permission) + ulong address, + ulong pagesCount, + MemoryState state, + MemoryPermission permission) { - ulong Size = PagesCount * PageSize; + ulong size = pagesCount * PageSize; - if (!ValidateRegionForState(Address, Size, State)) + if (!ValidateRegionForState(address, size, state)) { return KernelResult.InvalidMemState; } - lock (Blocks) + lock (_blocks) { - if (!IsUnmapped(Address, Size)) + if (!IsUnmapped(address, size)) { return KernelResult.InvalidMemState; } - if (!BlockAllocator.CanAllocate(MaxBlocksNeededForInsertion)) + if (!_blockAllocator.CanAllocate(MaxBlocksNeededForInsertion)) { return KernelResult.OutOfResource; } - KernelResult Result = DoMmuOperation( - Address, - PagesCount, + KernelResult result = DoMmuOperation( + address, + pagesCount, 0, false, - Permission, + permission, MemoryOperation.Allocate); - if (Result == KernelResult.Success) + if (result == KernelResult.Success) { - InsertBlock(Address, PagesCount, State, Permission); + InsertBlock(address, pagesCount, state, permission); } - return Result; + return result; } } - public KernelResult MapProcessCodeMemory(ulong Dst, ulong Src, ulong Size) + public KernelResult MapProcessCodeMemory(ulong dst, ulong src, ulong size) { - ulong PagesCount = Size / PageSize; + ulong pagesCount = size / PageSize; - lock (Blocks) + lock (_blocks) { - bool Success = CheckRange( - Src, - Size, + bool success = CheckRange( + src, + size, MemoryState.Mask, MemoryState.Heap, MemoryPermission.Mask, @@ -639,41 +639,41 @@ namespace Ryujinx.HLE.HOS.Kernel MemoryAttribute.Mask, MemoryAttribute.None, MemoryAttribute.IpcAndDeviceMapped, - out MemoryState State, - out MemoryPermission Permission, + out MemoryState state, + out MemoryPermission permission, out _); - Success &= IsUnmapped(Dst, Size); + success &= IsUnmapped(dst, size); - if (Success) + if (success) { - if (!BlockAllocator.CanAllocate(MaxBlocksNeededForInsertion * 2)) + if (!_blockAllocator.CanAllocate(MaxBlocksNeededForInsertion * 2)) { return KernelResult.OutOfResource; } - KPageList PageList = new KPageList(); + KPageList pageList = new KPageList(); - AddVaRangeToPageList(PageList, Src, PagesCount); + AddVaRangeToPageList(pageList, src, pagesCount); - KernelResult Result = MmuChangePermission(Src, PagesCount, MemoryPermission.None); + KernelResult result = MmuChangePermission(src, pagesCount, MemoryPermission.None); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - return Result; + return result; } - Result = MapPages(Dst, PageList, MemoryPermission.None); + result = MapPages(dst, pageList, MemoryPermission.None); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - MmuChangePermission(Src, PagesCount, Permission); + MmuChangePermission(src, pagesCount, permission); - return Result; + return result; } - InsertBlock(Src, PagesCount, State, MemoryPermission.None, MemoryAttribute.Borrowed); - InsertBlock(Dst, PagesCount, MemoryState.ModCodeStatic); + InsertBlock(src, pagesCount, state, MemoryPermission.None, MemoryAttribute.Borrowed); + InsertBlock(dst, pagesCount, MemoryState.ModCodeStatic); return KernelResult.Success; } @@ -684,15 +684,15 @@ namespace Ryujinx.HLE.HOS.Kernel } } - public KernelResult UnmapProcessCodeMemory(ulong Dst, ulong Src, ulong Size) + public KernelResult UnmapProcessCodeMemory(ulong dst, ulong src, ulong size) { - ulong PagesCount = Size / PageSize; + ulong pagesCount = size / PageSize; - lock (Blocks) + lock (_blocks) { - bool Success = CheckRange( - Src, - Size, + bool success = CheckRange( + src, + size, MemoryState.Mask, MemoryState.Heap, MemoryPermission.None, @@ -704,8 +704,8 @@ namespace Ryujinx.HLE.HOS.Kernel out _, out _); - Success &= CheckRange( - Dst, + success &= CheckRange( + dst, PageSize, MemoryState.UnmapProcessCodeMemoryAllowed, MemoryState.UnmapProcessCodeMemoryAllowed, @@ -714,38 +714,38 @@ namespace Ryujinx.HLE.HOS.Kernel MemoryAttribute.Mask, MemoryAttribute.None, MemoryAttribute.IpcAndDeviceMapped, - out MemoryState State, + out MemoryState state, out _, out _); - Success &= CheckRange( - Dst, - Size, + success &= CheckRange( + dst, + size, MemoryState.Mask, - State, + state, MemoryPermission.None, MemoryPermission.None, MemoryAttribute.Mask, MemoryAttribute.None); - if (Success) + if (success) { - KernelResult Result = MmuUnmap(Dst, PagesCount); + KernelResult result = MmuUnmap(dst, pagesCount); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - return Result; + return result; } //TODO: Missing some checks here. - if (!BlockAllocator.CanAllocate(MaxBlocksNeededForInsertion * 2)) + if (!_blockAllocator.CanAllocate(MaxBlocksNeededForInsertion * 2)) { return KernelResult.OutOfResource; } - InsertBlock(Dst, PagesCount, MemoryState.Unmapped); - InsertBlock(Src, PagesCount, MemoryState.Heap, MemoryPermission.ReadAndWrite); + InsertBlock(dst, pagesCount, MemoryState.Unmapped); + InsertBlock(src, pagesCount, MemoryState.Heap, MemoryPermission.ReadAndWrite); return KernelResult.Success; } @@ -756,105 +756,105 @@ namespace Ryujinx.HLE.HOS.Kernel } } - public KernelResult SetHeapSize(ulong Size, out ulong Address) + public KernelResult SetHeapSize(ulong size, out ulong address) { - Address = 0; + address = 0; - if (Size > HeapRegionEnd - HeapRegionStart) + if (size > HeapRegionEnd - HeapRegionStart) { return KernelResult.OutOfMemory; } - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = _system.Scheduler.GetCurrentProcess(); - ulong CurrentHeapSize = GetHeapSize(); + ulong currentHeapSize = GetHeapSize(); - if (CurrentHeapSize <= Size) + if (currentHeapSize <= size) { //Expand. - ulong DiffSize = Size - CurrentHeapSize; + ulong diffSize = size - currentHeapSize; - lock (Blocks) + lock (_blocks) { - if (CurrentProcess.ResourceLimit != null && DiffSize != 0 && - !CurrentProcess.ResourceLimit.Reserve(LimitableResource.Memory, DiffSize)) + if (currentProcess.ResourceLimit != null && diffSize != 0 && + !currentProcess.ResourceLimit.Reserve(LimitableResource.Memory, diffSize)) { return KernelResult.ResLimitExceeded; } - ulong PagesCount = DiffSize / PageSize; + ulong pagesCount = diffSize / PageSize; - KMemoryRegionManager Region = GetMemoryRegionManager(); + KMemoryRegionManager region = GetMemoryRegionManager(); - KernelResult Result = Region.AllocatePages(PagesCount, AslrDisabled, out KPageList PageList); + KernelResult result = region.AllocatePages(pagesCount, _aslrDisabled, out KPageList pageList); void CleanUpForError() { - if (PageList != null) + if (pageList != null) { - Region.FreePages(PageList); + region.FreePages(pageList); } - if (CurrentProcess.ResourceLimit != null && DiffSize != 0) + if (currentProcess.ResourceLimit != null && diffSize != 0) { - CurrentProcess.ResourceLimit.Release(LimitableResource.Memory, DiffSize); + currentProcess.ResourceLimit.Release(LimitableResource.Memory, diffSize); } } - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { CleanUpForError(); - return Result; + return result; } - if (!BlockAllocator.CanAllocate(MaxBlocksNeededForInsertion)) + if (!_blockAllocator.CanAllocate(MaxBlocksNeededForInsertion)) { CleanUpForError(); return KernelResult.OutOfResource; } - if (!IsUnmapped(CurrentHeapAddr, DiffSize)) + if (!IsUnmapped(_currentHeapAddr, diffSize)) { CleanUpForError(); return KernelResult.InvalidMemState; } - Result = DoMmuOperation( - CurrentHeapAddr, - PagesCount, - PageList, + result = DoMmuOperation( + _currentHeapAddr, + pagesCount, + pageList, MemoryPermission.ReadAndWrite, MemoryOperation.MapVa); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { CleanUpForError(); - return Result; + return result; } - InsertBlock(CurrentHeapAddr, PagesCount, MemoryState.Heap, MemoryPermission.ReadAndWrite); + InsertBlock(_currentHeapAddr, pagesCount, MemoryState.Heap, MemoryPermission.ReadAndWrite); } } else { //Shrink. - ulong FreeAddr = HeapRegionStart + Size; - ulong DiffSize = CurrentHeapSize - Size; + ulong freeAddr = HeapRegionStart + size; + ulong diffSize = currentHeapSize - size; - lock (Blocks) + lock (_blocks) { - if (!BlockAllocator.CanAllocate(MaxBlocksNeededForInsertion)) + if (!_blockAllocator.CanAllocate(MaxBlocksNeededForInsertion)) { return KernelResult.OutOfResource; } if (!CheckRange( - FreeAddr, - DiffSize, + freeAddr, + diffSize, MemoryState.Mask, MemoryState.Heap, MemoryPermission.Mask, @@ -869,31 +869,31 @@ namespace Ryujinx.HLE.HOS.Kernel return KernelResult.InvalidMemState; } - ulong PagesCount = DiffSize / PageSize; + ulong pagesCount = diffSize / PageSize; - KernelResult Result = MmuUnmap(FreeAddr, PagesCount); + KernelResult result = MmuUnmap(freeAddr, pagesCount); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - return Result; + return result; } - CurrentProcess.ResourceLimit?.Release(LimitableResource.Memory, BitUtils.AlignDown(DiffSize, PageSize)); + currentProcess.ResourceLimit?.Release(LimitableResource.Memory, BitUtils.AlignDown(diffSize, PageSize)); - InsertBlock(FreeAddr, PagesCount, MemoryState.Unmapped); + InsertBlock(freeAddr, pagesCount, MemoryState.Unmapped); } } - CurrentHeapAddr = HeapRegionStart + Size; + _currentHeapAddr = HeapRegionStart + size; - Address = HeapRegionStart; + address = HeapRegionStart; return KernelResult.Success; } public ulong GetTotalHeapSize() { - lock (Blocks) + lock (_blocks) { return GetHeapSize() + PhysicalMemoryUsage; } @@ -901,30 +901,30 @@ namespace Ryujinx.HLE.HOS.Kernel private ulong GetHeapSize() { - return CurrentHeapAddr - HeapRegionStart; + return _currentHeapAddr - HeapRegionStart; } - public KernelResult SetHeapCapacity(ulong Capacity) + public KernelResult SetHeapCapacity(ulong capacity) { - lock (Blocks) + lock (_blocks) { - HeapCapacity = Capacity; + _heapCapacity = capacity; } return KernelResult.Success; } public KernelResult SetMemoryAttribute( - ulong Address, - ulong Size, - MemoryAttribute AttributeMask, - MemoryAttribute AttributeValue) + ulong address, + ulong size, + MemoryAttribute attributeMask, + MemoryAttribute attributeValue) { - lock (Blocks) + lock (_blocks) { if (CheckRange( - Address, - Size, + address, + size, MemoryState.AttributeChangeAllowed, MemoryState.AttributeChangeAllowed, MemoryPermission.None, @@ -932,21 +932,21 @@ namespace Ryujinx.HLE.HOS.Kernel MemoryAttribute.BorrowedAndIpcMapped, MemoryAttribute.None, MemoryAttribute.DeviceMappedAndUncached, - out MemoryState State, - out MemoryPermission Permission, - out MemoryAttribute Attribute)) + out MemoryState state, + out MemoryPermission permission, + out MemoryAttribute attribute)) { - if (!BlockAllocator.CanAllocate(MaxBlocksNeededForInsertion)) + if (!_blockAllocator.CanAllocate(MaxBlocksNeededForInsertion)) { return KernelResult.OutOfResource; } - ulong PagesCount = Size / PageSize; + ulong pagesCount = size / PageSize; - Attribute &= ~AttributeMask; - Attribute |= AttributeMask & AttributeValue; + attribute &= ~attributeMask; + attribute |= attributeMask & attributeValue; - InsertBlock(Address, PagesCount, State, Permission, Attribute); + InsertBlock(address, pagesCount, state, permission, attribute); return KernelResult.Success; } @@ -957,14 +957,14 @@ namespace Ryujinx.HLE.HOS.Kernel } } - public KMemoryInfo QueryMemory(ulong Address) + public KMemoryInfo QueryMemory(ulong address) { - if (Address >= AddrSpaceStart && - Address < AddrSpaceEnd) + if (address >= AddrSpaceStart && + address < AddrSpaceEnd) { - lock (Blocks) + lock (_blocks) { - return FindBlock(Address).GetInfo(); + return FindBlock(address).GetInfo(); } } else @@ -980,15 +980,15 @@ namespace Ryujinx.HLE.HOS.Kernel } } - public KernelResult Map(ulong Dst, ulong Src, ulong Size) + public KernelResult Map(ulong dst, ulong src, ulong size) { - bool Success; + bool success; - lock (Blocks) + lock (_blocks) { - Success = CheckRange( - Src, - Size, + success = CheckRange( + src, + size, MemoryState.MapAllowed, MemoryState.MapAllowed, MemoryPermission.Mask, @@ -996,46 +996,46 @@ namespace Ryujinx.HLE.HOS.Kernel MemoryAttribute.Mask, MemoryAttribute.None, MemoryAttribute.IpcAndDeviceMapped, - out MemoryState SrcState, + out MemoryState srcState, out _, out _); - Success &= IsUnmapped(Dst, Size); + success &= IsUnmapped(dst, size); - if (Success) + if (success) { - if (!BlockAllocator.CanAllocate(MaxBlocksNeededForInsertion * 2)) + if (!_blockAllocator.CanAllocate(MaxBlocksNeededForInsertion * 2)) { return KernelResult.OutOfResource; } - ulong PagesCount = Size / PageSize; + ulong pagesCount = size / PageSize; - KPageList PageList = new KPageList(); + KPageList pageList = new KPageList(); - AddVaRangeToPageList(PageList, Src, PagesCount); + AddVaRangeToPageList(pageList, src, pagesCount); - KernelResult Result = MmuChangePermission(Src, PagesCount, MemoryPermission.None); + KernelResult result = MmuChangePermission(src, pagesCount, MemoryPermission.None); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - return Result; + return result; } - Result = MapPages(Dst, PageList, MemoryPermission.ReadAndWrite); + result = MapPages(dst, pageList, MemoryPermission.ReadAndWrite); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - if (MmuChangePermission(Src, PagesCount, MemoryPermission.ReadAndWrite) != KernelResult.Success) + if (MmuChangePermission(src, pagesCount, MemoryPermission.ReadAndWrite) != KernelResult.Success) { throw new InvalidOperationException("Unexpected failure reverting memory permission."); } - return Result; + return result; } - InsertBlock(Src, PagesCount, SrcState, MemoryPermission.None, MemoryAttribute.Borrowed); - InsertBlock(Dst, PagesCount, MemoryState.Stack, MemoryPermission.ReadAndWrite); + InsertBlock(src, pagesCount, srcState, MemoryPermission.None, MemoryAttribute.Borrowed); + InsertBlock(dst, pagesCount, MemoryState.Stack, MemoryPermission.ReadAndWrite); return KernelResult.Success; } @@ -1046,17 +1046,17 @@ namespace Ryujinx.HLE.HOS.Kernel } } - public KernelResult UnmapForKernel(ulong Address, ulong PagesCount, MemoryState StateExpected) + public KernelResult UnmapForKernel(ulong address, ulong pagesCount, MemoryState stateExpected) { - ulong Size = PagesCount * PageSize; + ulong size = pagesCount * PageSize; - lock (Blocks) + lock (_blocks) { if (CheckRange( - Address, - Size, + address, + size, MemoryState.Mask, - StateExpected, + stateExpected, MemoryPermission.None, MemoryPermission.None, MemoryAttribute.Mask, @@ -1066,16 +1066,16 @@ namespace Ryujinx.HLE.HOS.Kernel out _, out _)) { - if (!BlockAllocator.CanAllocate(MaxBlocksNeededForInsertion)) + if (!_blockAllocator.CanAllocate(MaxBlocksNeededForInsertion)) { return KernelResult.OutOfResource; } - KernelResult Result = MmuUnmap(Address, PagesCount); + KernelResult result = MmuUnmap(address, pagesCount); - if (Result == KernelResult.Success) + if (result == KernelResult.Success) { - InsertBlock(Address, PagesCount, MemoryState.Unmapped); + InsertBlock(address, pagesCount, MemoryState.Unmapped); } return KernelResult.Success; @@ -1087,15 +1087,15 @@ namespace Ryujinx.HLE.HOS.Kernel } } - public KernelResult Unmap(ulong Dst, ulong Src, ulong Size) + public KernelResult Unmap(ulong dst, ulong src, ulong size) { - bool Success; + bool success; - lock (Blocks) + lock (_blocks) { - Success = CheckRange( - Src, - Size, + success = CheckRange( + src, + size, MemoryState.MapAllowed, MemoryState.MapAllowed, MemoryPermission.Mask, @@ -1103,13 +1103,13 @@ namespace Ryujinx.HLE.HOS.Kernel MemoryAttribute.Mask, MemoryAttribute.Borrowed, MemoryAttribute.IpcAndDeviceMapped, - out MemoryState SrcState, + out MemoryState srcState, out _, out _); - Success &= CheckRange( - Dst, - Size, + success &= CheckRange( + dst, + size, MemoryState.Mask, MemoryState.Stack, MemoryPermission.None, @@ -1118,47 +1118,47 @@ namespace Ryujinx.HLE.HOS.Kernel MemoryAttribute.None, MemoryAttribute.IpcAndDeviceMapped, out _, - out MemoryPermission DstPermission, + out MemoryPermission dstPermission, out _); - if (Success) + if (success) { - if (!BlockAllocator.CanAllocate(MaxBlocksNeededForInsertion * 2)) + if (!_blockAllocator.CanAllocate(MaxBlocksNeededForInsertion * 2)) { return KernelResult.OutOfResource; } - ulong PagesCount = Size / PageSize; + ulong pagesCount = size / PageSize; - KPageList SrcPageList = new KPageList(); - KPageList DstPageList = new KPageList(); + KPageList srcPageList = new KPageList(); + KPageList dstPageList = new KPageList(); - AddVaRangeToPageList(SrcPageList, Src, PagesCount); - AddVaRangeToPageList(DstPageList, Dst, PagesCount); + AddVaRangeToPageList(srcPageList, src, pagesCount); + AddVaRangeToPageList(dstPageList, dst, pagesCount); - if (!DstPageList.IsEqual(SrcPageList)) + if (!dstPageList.IsEqual(srcPageList)) { return KernelResult.InvalidMemRange; } - KernelResult Result = MmuUnmap(Dst, PagesCount); + KernelResult result = MmuUnmap(dst, pagesCount); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - return Result; + return result; } - Result = MmuChangePermission(Src, PagesCount, MemoryPermission.ReadAndWrite); + result = MmuChangePermission(src, pagesCount, MemoryPermission.ReadAndWrite); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - MapPages(Dst, DstPageList, DstPermission); + MapPages(dst, dstPageList, dstPermission); - return Result; + return result; } - InsertBlock(Src, PagesCount, SrcState, MemoryPermission.ReadAndWrite); - InsertBlock(Dst, PagesCount, MemoryState.Unmapped); + InsertBlock(src, pagesCount, srcState, MemoryPermission.ReadAndWrite); + InsertBlock(dst, pagesCount, MemoryState.Unmapped); return KernelResult.Success; } @@ -1169,13 +1169,13 @@ namespace Ryujinx.HLE.HOS.Kernel } } - public KernelResult ReserveTransferMemory(ulong Address, ulong Size, MemoryPermission Permission) + public KernelResult ReserveTransferMemory(ulong address, ulong size, MemoryPermission permission) { - lock (Blocks) + lock (_blocks) { if (CheckRange( - Address, - Size, + address, + size, MemoryState.TransferMemoryAllowed | MemoryState.IsPoolAllocated, MemoryState.TransferMemoryAllowed | MemoryState.IsPoolAllocated, MemoryPermission.Mask, @@ -1183,22 +1183,22 @@ namespace Ryujinx.HLE.HOS.Kernel MemoryAttribute.Mask, MemoryAttribute.None, MemoryAttribute.IpcAndDeviceMapped, - out MemoryState State, + out MemoryState state, out _, - out MemoryAttribute Attribute)) + out MemoryAttribute attribute)) { //TODO: Missing checks. - if (!BlockAllocator.CanAllocate(MaxBlocksNeededForInsertion)) + if (!_blockAllocator.CanAllocate(MaxBlocksNeededForInsertion)) { return KernelResult.OutOfResource; } - ulong PagesCount = Size / PageSize; + ulong pagesCount = size / PageSize; - Attribute |= MemoryAttribute.Borrowed; + attribute |= MemoryAttribute.Borrowed; - InsertBlock(Address, PagesCount, State, Permission, Attribute); + InsertBlock(address, pagesCount, state, permission, attribute); return KernelResult.Success; } @@ -1209,13 +1209,13 @@ namespace Ryujinx.HLE.HOS.Kernel } } - public KernelResult ResetTransferMemory(ulong Address, ulong Size) + public KernelResult ResetTransferMemory(ulong address, ulong size) { - lock (Blocks) + lock (_blocks) { if (CheckRange( - Address, - Size, + address, + size, MemoryState.TransferMemoryAllowed | MemoryState.IsPoolAllocated, MemoryState.TransferMemoryAllowed | MemoryState.IsPoolAllocated, MemoryPermission.None, @@ -1223,18 +1223,18 @@ namespace Ryujinx.HLE.HOS.Kernel MemoryAttribute.Mask, MemoryAttribute.Borrowed, MemoryAttribute.IpcAndDeviceMapped, - out MemoryState State, + out MemoryState state, out _, out _)) { - if (!BlockAllocator.CanAllocate(MaxBlocksNeededForInsertion)) + if (!_blockAllocator.CanAllocate(MaxBlocksNeededForInsertion)) { return KernelResult.OutOfResource; } - ulong PagesCount = Size / PageSize; + ulong pagesCount = size / PageSize; - InsertBlock(Address, PagesCount, State, MemoryPermission.ReadAndWrite); + InsertBlock(address, pagesCount, state, MemoryPermission.ReadAndWrite); return KernelResult.Success; } @@ -1245,13 +1245,13 @@ namespace Ryujinx.HLE.HOS.Kernel } } - public KernelResult SetProcessMemoryPermission(ulong Address, ulong Size, MemoryPermission Permission) + public KernelResult SetProcessMemoryPermission(ulong address, ulong size, MemoryPermission permission) { - lock (Blocks) + lock (_blocks) { if (CheckRange( - Address, - Size, + address, + size, MemoryState.ProcessPermissionChangeAllowed, MemoryState.ProcessPermissionChangeAllowed, MemoryPermission.None, @@ -1259,51 +1259,51 @@ namespace Ryujinx.HLE.HOS.Kernel MemoryAttribute.Mask, MemoryAttribute.None, MemoryAttribute.IpcAndDeviceMapped, - out MemoryState OldState, - out MemoryPermission OldPermission, + out MemoryState oldState, + out MemoryPermission oldPermission, out _)) { - MemoryState NewState = OldState; + MemoryState newState = oldState; //If writing into the code region is allowed, then we need //to change it to mutable. - if ((Permission & MemoryPermission.Write) != 0) + if ((permission & MemoryPermission.Write) != 0) { - if (OldState == MemoryState.CodeStatic) + if (oldState == MemoryState.CodeStatic) { - NewState = MemoryState.CodeMutable; + newState = MemoryState.CodeMutable; } - else if (OldState == MemoryState.ModCodeStatic) + else if (oldState == MemoryState.ModCodeStatic) { - NewState = MemoryState.ModCodeMutable; + newState = MemoryState.ModCodeMutable; } else { - throw new InvalidOperationException($"Memory state \"{OldState}\" not valid for this operation."); + throw new InvalidOperationException($"Memory state \"{oldState}\" not valid for this operation."); } } - if (NewState != OldState || Permission != OldPermission) + if (newState != oldState || permission != oldPermission) { - if (!BlockAllocator.CanAllocate(MaxBlocksNeededForInsertion)) + if (!_blockAllocator.CanAllocate(MaxBlocksNeededForInsertion)) { return KernelResult.OutOfResource; } - ulong PagesCount = Size / PageSize; + ulong pagesCount = size / PageSize; - MemoryOperation Operation = (Permission & MemoryPermission.Execute) != 0 + MemoryOperation operation = (permission & MemoryPermission.Execute) != 0 ? MemoryOperation.ChangePermsAndAttributes : MemoryOperation.ChangePermRw; - KernelResult Result = DoMmuOperation(Address, PagesCount, 0, false, Permission, Operation); + KernelResult result = DoMmuOperation(address, pagesCount, 0, false, permission, operation); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - return Result; + return result; } - InsertBlock(Address, PagesCount, NewState, Permission); + InsertBlock(address, pagesCount, newState, permission); } return KernelResult.Success; @@ -1315,85 +1315,85 @@ namespace Ryujinx.HLE.HOS.Kernel } } - public KernelResult MapPhysicalMemory(ulong Address, ulong Size) + public KernelResult MapPhysicalMemory(ulong address, ulong size) { - ulong EndAddr = Address + Size; + ulong endAddr = address + size; - lock (Blocks) + lock (_blocks) { - ulong MappedSize = 0; + ulong mappedSize = 0; - KMemoryInfo Info; + KMemoryInfo info; - LinkedListNode Node = FindBlockNode(Address); + LinkedListNode node = FindBlockNode(address); do { - Info = Node.Value.GetInfo(); + info = node.Value.GetInfo(); - if (Info.State != MemoryState.Unmapped) + if (info.State != MemoryState.Unmapped) { - MappedSize += GetSizeInRange(Info, Address, EndAddr); + mappedSize += GetSizeInRange(info, address, endAddr); } - Node = Node.Next; + node = node.Next; } - while (Info.Address + Info.Size < EndAddr && Node != null); + while (info.Address + info.Size < endAddr && node != null); - if (MappedSize == Size) + if (mappedSize == size) { return KernelResult.Success; } - ulong RemainingSize = Size - MappedSize; + ulong remainingSize = size - mappedSize; - ulong RemainingPages = RemainingSize / PageSize; + ulong remainingPages = remainingSize / PageSize; - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = _system.Scheduler.GetCurrentProcess(); - if (CurrentProcess.ResourceLimit != null && - !CurrentProcess.ResourceLimit.Reserve(LimitableResource.Memory, RemainingSize)) + if (currentProcess.ResourceLimit != null && + !currentProcess.ResourceLimit.Reserve(LimitableResource.Memory, remainingSize)) { return KernelResult.ResLimitExceeded; } - KMemoryRegionManager Region = GetMemoryRegionManager(); + KMemoryRegionManager region = GetMemoryRegionManager(); - KernelResult Result = Region.AllocatePages(RemainingPages, AslrDisabled, out KPageList PageList); + KernelResult result = region.AllocatePages(remainingPages, _aslrDisabled, out KPageList pageList); void CleanUpForError() { - if (PageList != null) + if (pageList != null) { - Region.FreePages(PageList); + region.FreePages(pageList); } - CurrentProcess.ResourceLimit?.Release(LimitableResource.Memory, RemainingSize); + currentProcess.ResourceLimit?.Release(LimitableResource.Memory, remainingSize); } - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { CleanUpForError(); - return Result; + return result; } - if (!BlockAllocator.CanAllocate(MaxBlocksNeededForInsertion)) + if (!_blockAllocator.CanAllocate(MaxBlocksNeededForInsertion)) { CleanUpForError(); return KernelResult.OutOfResource; } - MapPhysicalMemory(PageList, Address, EndAddr); + MapPhysicalMemory(pageList, address, endAddr); - PhysicalMemoryUsage += RemainingSize; + PhysicalMemoryUsage += remainingSize; - ulong PagesCount = Size / PageSize; + ulong pagesCount = size / PageSize; InsertBlock( - Address, - PagesCount, + address, + pagesCount, MemoryState.Unmapped, MemoryPermission.None, MemoryAttribute.None, @@ -1405,227 +1405,227 @@ namespace Ryujinx.HLE.HOS.Kernel return KernelResult.Success; } - public KernelResult UnmapPhysicalMemory(ulong Address, ulong Size) + public KernelResult UnmapPhysicalMemory(ulong address, ulong size) { - ulong EndAddr = Address + Size; + ulong endAddr = address + size; - lock (Blocks) + lock (_blocks) { //Scan, ensure that the region can be unmapped (all blocks are heap or //already unmapped), fill pages list for freeing memory. - ulong HeapMappedSize = 0; + ulong heapMappedSize = 0; - KPageList PageList = new KPageList(); + KPageList pageList = new KPageList(); - KMemoryInfo Info; + KMemoryInfo info; - LinkedListNode BaseNode = FindBlockNode(Address); + LinkedListNode baseNode = FindBlockNode(address); - LinkedListNode Node = BaseNode; + LinkedListNode node = baseNode; do { - Info = Node.Value.GetInfo(); + info = node.Value.GetInfo(); - if (Info.State == MemoryState.Heap) + if (info.State == MemoryState.Heap) { - if (Info.Attribute != MemoryAttribute.None) + if (info.Attribute != MemoryAttribute.None) { return KernelResult.InvalidMemState; } - ulong BlockSize = GetSizeInRange(Info, Address, EndAddr); - ulong BlockAddress = GetAddrInRange(Info, Address); + ulong blockSize = GetSizeInRange(info, address, endAddr); + ulong blockAddress = GetAddrInRange(info, address); - AddVaRangeToPageList(PageList, BlockAddress, BlockSize / PageSize); + AddVaRangeToPageList(pageList, blockAddress, blockSize / PageSize); - HeapMappedSize += BlockSize; + heapMappedSize += blockSize; } - else if (Info.State != MemoryState.Unmapped) + else if (info.State != MemoryState.Unmapped) { return KernelResult.InvalidMemState; } - Node = Node.Next; + node = node.Next; } - while (Info.Address + Info.Size < EndAddr && Node != null); + while (info.Address + info.Size < endAddr && node != null); - if (HeapMappedSize == 0) + if (heapMappedSize == 0) { return KernelResult.Success; } - if (!BlockAllocator.CanAllocate(MaxBlocksNeededForInsertion)) + if (!_blockAllocator.CanAllocate(MaxBlocksNeededForInsertion)) { return KernelResult.OutOfResource; } //Try to unmap all the heap mapped memory inside range. - KernelResult Result = KernelResult.Success; + KernelResult result = KernelResult.Success; - Node = BaseNode; + node = baseNode; do { - Info = Node.Value.GetInfo(); + info = node.Value.GetInfo(); - if (Info.State == MemoryState.Heap) + if (info.State == MemoryState.Heap) { - ulong BlockSize = GetSizeInRange(Info, Address, EndAddr); - ulong BlockAddress = GetAddrInRange(Info, Address); + ulong blockSize = GetSizeInRange(info, address, endAddr); + ulong blockAddress = GetAddrInRange(info, address); - ulong BlockPagesCount = BlockSize / PageSize; + ulong blockPagesCount = blockSize / PageSize; - Result = MmuUnmap(BlockAddress, BlockPagesCount); + result = MmuUnmap(blockAddress, blockPagesCount); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { //If we failed to unmap, we need to remap everything back again. - MapPhysicalMemory(PageList, Address, BlockAddress + BlockSize); + MapPhysicalMemory(pageList, address, blockAddress + blockSize); break; } } - Node = Node.Next; + node = node.Next; } - while (Info.Address + Info.Size < EndAddr && Node != null); + while (info.Address + info.Size < endAddr && node != null); - if (Result == KernelResult.Success) + if (result == KernelResult.Success) { - GetMemoryRegionManager().FreePages(PageList); + GetMemoryRegionManager().FreePages(pageList); - PhysicalMemoryUsage -= HeapMappedSize; + PhysicalMemoryUsage -= heapMappedSize; - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = _system.Scheduler.GetCurrentProcess(); - CurrentProcess.ResourceLimit?.Release(LimitableResource.Memory, HeapMappedSize); + currentProcess.ResourceLimit?.Release(LimitableResource.Memory, heapMappedSize); - ulong PagesCount = Size / PageSize; + ulong pagesCount = size / PageSize; - InsertBlock(Address, PagesCount, MemoryState.Unmapped); + InsertBlock(address, pagesCount, MemoryState.Unmapped); } - return Result; + return result; } } - private void MapPhysicalMemory(KPageList PageList, ulong Address, ulong EndAddr) + private void MapPhysicalMemory(KPageList pageList, ulong address, ulong endAddr) { - KMemoryInfo Info; + KMemoryInfo info; - LinkedListNode Node = FindBlockNode(Address); + LinkedListNode node = FindBlockNode(address); - LinkedListNode PageListNode = PageList.Nodes.First; + LinkedListNode pageListNode = pageList.Nodes.First; - KPageNode PageNode = PageListNode.Value; + KPageNode pageNode = pageListNode.Value; - ulong SrcPa = PageNode.Address; - ulong SrcPaPages = PageNode.PagesCount; + ulong srcPa = pageNode.Address; + ulong srcPaPages = pageNode.PagesCount; do { - Info = Node.Value.GetInfo(); + info = node.Value.GetInfo(); - if (Info.State == MemoryState.Unmapped) + if (info.State == MemoryState.Unmapped) { - ulong BlockSize = GetSizeInRange(Info, Address, EndAddr); + ulong blockSize = GetSizeInRange(info, address, endAddr); - ulong DstVaPages = BlockSize / PageSize; + ulong dstVaPages = blockSize / PageSize; - ulong DstVa = GetAddrInRange(Info, Address); + ulong dstVa = GetAddrInRange(info, address); - while (DstVaPages > 0) + while (dstVaPages > 0) { - if (SrcPaPages == 0) + if (srcPaPages == 0) { - PageListNode = PageListNode.Next; + pageListNode = pageListNode.Next; - PageNode = PageListNode.Value; + pageNode = pageListNode.Value; - SrcPa = PageNode.Address; - SrcPaPages = PageNode.PagesCount; + srcPa = pageNode.Address; + srcPaPages = pageNode.PagesCount; } - ulong PagesCount = SrcPaPages; + ulong pagesCount = srcPaPages; - if (PagesCount > DstVaPages) + if (pagesCount > dstVaPages) { - PagesCount = DstVaPages; + pagesCount = dstVaPages; } DoMmuOperation( - DstVa, - PagesCount, - SrcPa, + dstVa, + pagesCount, + srcPa, true, MemoryPermission.ReadAndWrite, MemoryOperation.MapPa); - DstVa += PagesCount * PageSize; - SrcPa += PagesCount * PageSize; - SrcPaPages -= PagesCount; - DstVaPages -= PagesCount; + dstVa += pagesCount * PageSize; + srcPa += pagesCount * PageSize; + srcPaPages -= pagesCount; + dstVaPages -= pagesCount; } } - Node = Node.Next; + node = node.Next; } - while (Info.Address + Info.Size < EndAddr && Node != null); + while (info.Address + info.Size < endAddr && node != null); } - private static ulong GetSizeInRange(KMemoryInfo Info, ulong Start, ulong End) + private static ulong GetSizeInRange(KMemoryInfo info, ulong start, ulong end) { - ulong EndAddr = Info.Size + Info.Address; - ulong Size = Info.Size; + ulong endAddr = info.Size + info.Address; + ulong size = info.Size; - if (Info.Address < Start) + if (info.Address < start) { - Size -= Start - Info.Address; + size -= start - info.Address; } - if (EndAddr > End) + if (endAddr > end) { - Size -= EndAddr - End; + size -= endAddr - end; } - return Size; + return size; } - private static ulong GetAddrInRange(KMemoryInfo Info, ulong Start) + private static ulong GetAddrInRange(KMemoryInfo info, ulong start) { - if (Info.Address < Start) + if (info.Address < start) { - return Start; + return start; } - return Info.Address; + return info.Address; } - private void AddVaRangeToPageList(KPageList PageList, ulong Start, ulong PagesCount) + private void AddVaRangeToPageList(KPageList pageList, ulong start, ulong pagesCount) { - ulong Address = Start; + ulong address = start; - while (Address < Start + PagesCount * PageSize) + while (address < start + pagesCount * PageSize) { - KernelResult Result = ConvertVaToPa(Address, out ulong Pa); + KernelResult result = ConvertVaToPa(address, out ulong pa); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { throw new InvalidOperationException("Unexpected failure translating virtual address."); } - PageList.AddRange(Pa, 1); + pageList.AddRange(pa, 1); - Address += PageSize; + address += PageSize; } } - private bool IsUnmapped(ulong Address, ulong Size) + private bool IsUnmapped(ulong address, ulong size) { return CheckRange( - Address, - Size, + address, + size, MemoryState.Mask, MemoryState.Unmapped, MemoryPermission.Mask, @@ -1639,465 +1639,465 @@ namespace Ryujinx.HLE.HOS.Kernel } private bool CheckRange( - ulong Address, - ulong Size, - MemoryState StateMask, - MemoryState StateExpected, - MemoryPermission PermissionMask, - MemoryPermission PermissionExpected, - MemoryAttribute AttributeMask, - MemoryAttribute AttributeExpected, - MemoryAttribute AttributeIgnoreMask, - out MemoryState OutState, - out MemoryPermission OutPermission, - out MemoryAttribute OutAttribute) + ulong address, + ulong size, + MemoryState stateMask, + MemoryState stateExpected, + MemoryPermission permissionMask, + MemoryPermission permissionExpected, + MemoryAttribute attributeMask, + MemoryAttribute attributeExpected, + MemoryAttribute attributeIgnoreMask, + out MemoryState outState, + out MemoryPermission outPermission, + out MemoryAttribute outAttribute) { - ulong EndAddr = Address + Size - 1; + ulong endAddr = address + size - 1; - LinkedListNode Node = FindBlockNode(Address); + LinkedListNode node = FindBlockNode(address); - KMemoryInfo Info = Node.Value.GetInfo(); + KMemoryInfo info = node.Value.GetInfo(); - MemoryState FirstState = Info.State; - MemoryPermission FirstPermission = Info.Permission; - MemoryAttribute FirstAttribute = Info.Attribute; + MemoryState firstState = info.State; + MemoryPermission firstPermission = info.Permission; + MemoryAttribute firstAttribute = info.Attribute; do { - Info = Node.Value.GetInfo(); + info = node.Value.GetInfo(); //Check if the block state matches what we expect. - if ( FirstState != Info.State || - FirstPermission != Info.Permission || - (Info.Attribute & AttributeMask) != AttributeExpected || - (FirstAttribute | AttributeIgnoreMask) != (Info.Attribute | AttributeIgnoreMask) || - (FirstState & StateMask) != StateExpected || - (FirstPermission & PermissionMask) != PermissionExpected) + if ( firstState != info.State || + firstPermission != info.Permission || + (info.Attribute & attributeMask) != attributeExpected || + (firstAttribute | attributeIgnoreMask) != (info.Attribute | attributeIgnoreMask) || + (firstState & stateMask) != stateExpected || + (firstPermission & permissionMask) != permissionExpected) { break; } //Check if this is the last block on the range, if so return success. - if (EndAddr <= Info.Address + Info.Size - 1) + if (endAddr <= info.Address + info.Size - 1) { - OutState = FirstState; - OutPermission = FirstPermission; - OutAttribute = FirstAttribute & ~AttributeIgnoreMask; + outState = firstState; + outPermission = firstPermission; + outAttribute = firstAttribute & ~attributeIgnoreMask; return true; } - Node = Node.Next; + node = node.Next; } - while (Node != null); + while (node != null); - OutState = MemoryState.Unmapped; - OutPermission = MemoryPermission.None; - OutAttribute = MemoryAttribute.None; + outState = MemoryState.Unmapped; + outPermission = MemoryPermission.None; + outAttribute = MemoryAttribute.None; return false; } private bool CheckRange( - ulong Address, - ulong Size, - MemoryState StateMask, - MemoryState StateExpected, - MemoryPermission PermissionMask, - MemoryPermission PermissionExpected, - MemoryAttribute AttributeMask, - MemoryAttribute AttributeExpected) + ulong address, + ulong size, + MemoryState stateMask, + MemoryState stateExpected, + MemoryPermission permissionMask, + MemoryPermission permissionExpected, + MemoryAttribute attributeMask, + MemoryAttribute attributeExpected) { - ulong EndAddr = Address + Size - 1; + ulong endAddr = address + size - 1; - LinkedListNode Node = FindBlockNode(Address); + LinkedListNode node = FindBlockNode(address); do { - KMemoryInfo Info = Node.Value.GetInfo(); + KMemoryInfo info = node.Value.GetInfo(); //Check if the block state matches what we expect. - if ((Info.State & StateMask) != StateExpected || - (Info.Permission & PermissionMask) != PermissionExpected || - (Info.Attribute & AttributeMask) != AttributeExpected) + if ((info.State & stateMask) != stateExpected || + (info.Permission & permissionMask) != permissionExpected || + (info.Attribute & attributeMask) != attributeExpected) { break; } //Check if this is the last block on the range, if so return success. - if (EndAddr <= Info.Address + Info.Size - 1) + if (endAddr <= info.Address + info.Size - 1) { return true; } - Node = Node.Next; + node = node.Next; } - while (Node != null); + while (node != null); return false; } private void InsertBlock( - ulong BaseAddress, - ulong PagesCount, - MemoryState OldState, - MemoryPermission OldPermission, - MemoryAttribute OldAttribute, - MemoryState NewState, - MemoryPermission NewPermission, - MemoryAttribute NewAttribute) + ulong baseAddress, + ulong pagesCount, + MemoryState oldState, + MemoryPermission oldPermission, + MemoryAttribute oldAttribute, + MemoryState newState, + MemoryPermission newPermission, + MemoryAttribute newAttribute) { //Insert new block on the list only on areas where the state //of the block matches the state specified on the Old* state //arguments, otherwise leave it as is. - int OldCount = Blocks.Count; + int oldCount = _blocks.Count; - OldAttribute |= MemoryAttribute.IpcAndDeviceMapped; + oldAttribute |= MemoryAttribute.IpcAndDeviceMapped; - ulong EndAddr = PagesCount * PageSize + BaseAddress; + ulong endAddr = pagesCount * PageSize + baseAddress; - LinkedListNode Node = Blocks.First; + LinkedListNode node = _blocks.First; - while (Node != null) + while (node != null) { - LinkedListNode NewNode = Node; - LinkedListNode NextNode = Node.Next; + LinkedListNode newNode = node; + LinkedListNode nextNode = node.Next; - KMemoryBlock CurrBlock = Node.Value; + KMemoryBlock currBlock = node.Value; - ulong CurrBaseAddr = CurrBlock.BaseAddress; - ulong CurrEndAddr = CurrBlock.PagesCount * PageSize + CurrBaseAddr; + ulong currBaseAddr = currBlock.BaseAddress; + ulong currEndAddr = currBlock.PagesCount * PageSize + currBaseAddr; - if (BaseAddress < CurrEndAddr && CurrBaseAddr < EndAddr) + if (baseAddress < currEndAddr && currBaseAddr < endAddr) { - MemoryAttribute CurrBlockAttr = CurrBlock.Attribute | MemoryAttribute.IpcAndDeviceMapped; + MemoryAttribute currBlockAttr = currBlock.Attribute | MemoryAttribute.IpcAndDeviceMapped; - if (CurrBlock.State != OldState || - CurrBlock.Permission != OldPermission || - CurrBlockAttr != OldAttribute) + if (currBlock.State != oldState || + currBlock.Permission != oldPermission || + currBlockAttr != oldAttribute) { - Node = NextNode; + node = nextNode; continue; } - if (CurrBaseAddr >= BaseAddress && CurrEndAddr <= EndAddr) + if (currBaseAddr >= baseAddress && currEndAddr <= endAddr) { - CurrBlock.State = NewState; - CurrBlock.Permission = NewPermission; - CurrBlock.Attribute &= ~MemoryAttribute.IpcAndDeviceMapped; - CurrBlock.Attribute |= NewAttribute; + currBlock.State = newState; + currBlock.Permission = newPermission; + currBlock.Attribute &= ~MemoryAttribute.IpcAndDeviceMapped; + currBlock.Attribute |= newAttribute; } - else if (CurrBaseAddr >= BaseAddress) + else if (currBaseAddr >= baseAddress) { - CurrBlock.BaseAddress = EndAddr; + currBlock.BaseAddress = endAddr; - CurrBlock.PagesCount = (CurrEndAddr - EndAddr) / PageSize; + currBlock.PagesCount = (currEndAddr - endAddr) / PageSize; - ulong NewPagesCount = (EndAddr - CurrBaseAddr) / PageSize; + ulong newPagesCount = (endAddr - currBaseAddr) / PageSize; - NewNode = Blocks.AddBefore(Node, new KMemoryBlock( - CurrBaseAddr, - NewPagesCount, - NewState, - NewPermission, - NewAttribute)); + newNode = _blocks.AddBefore(node, new KMemoryBlock( + currBaseAddr, + newPagesCount, + newState, + newPermission, + newAttribute)); } - else if (CurrEndAddr <= EndAddr) + else if (currEndAddr <= endAddr) { - CurrBlock.PagesCount = (BaseAddress - CurrBaseAddr) / PageSize; + currBlock.PagesCount = (baseAddress - currBaseAddr) / PageSize; - ulong NewPagesCount = (CurrEndAddr - BaseAddress) / PageSize; + ulong newPagesCount = (currEndAddr - baseAddress) / PageSize; - NewNode = Blocks.AddAfter(Node, new KMemoryBlock( - BaseAddress, - NewPagesCount, - NewState, - NewPermission, - NewAttribute)); + newNode = _blocks.AddAfter(node, new KMemoryBlock( + baseAddress, + newPagesCount, + newState, + newPermission, + newAttribute)); } else { - CurrBlock.PagesCount = (BaseAddress - CurrBaseAddr) / PageSize; + currBlock.PagesCount = (baseAddress - currBaseAddr) / PageSize; - ulong NextPagesCount = (CurrEndAddr - EndAddr) / PageSize; + ulong nextPagesCount = (currEndAddr - endAddr) / PageSize; - NewNode = Blocks.AddAfter(Node, new KMemoryBlock( - BaseAddress, - PagesCount, - NewState, - NewPermission, - NewAttribute)); + newNode = _blocks.AddAfter(node, new KMemoryBlock( + baseAddress, + pagesCount, + newState, + newPermission, + newAttribute)); - Blocks.AddAfter(NewNode, new KMemoryBlock( - EndAddr, - NextPagesCount, - CurrBlock.State, - CurrBlock.Permission, - CurrBlock.Attribute)); + _blocks.AddAfter(newNode, new KMemoryBlock( + endAddr, + nextPagesCount, + currBlock.State, + currBlock.Permission, + currBlock.Attribute)); - NextNode = null; + nextNode = null; } - MergeEqualStateNeighbours(NewNode); + MergeEqualStateNeighbours(newNode); } - Node = NextNode; + node = nextNode; } - BlockAllocator.Count += Blocks.Count - OldCount; + _blockAllocator.Count += _blocks.Count - oldCount; } private void InsertBlock( - ulong BaseAddress, - ulong PagesCount, - MemoryState State, - MemoryPermission Permission = MemoryPermission.None, - MemoryAttribute Attribute = MemoryAttribute.None) + ulong baseAddress, + ulong pagesCount, + MemoryState state, + MemoryPermission permission = MemoryPermission.None, + MemoryAttribute attribute = MemoryAttribute.None) { //Inserts new block at the list, replacing and spliting //existing blocks as needed. - KMemoryBlock Block = new KMemoryBlock(BaseAddress, PagesCount, State, Permission, Attribute); + KMemoryBlock block = new KMemoryBlock(baseAddress, pagesCount, state, permission, attribute); - int OldCount = Blocks.Count; + int oldCount = _blocks.Count; - ulong EndAddr = PagesCount * PageSize + BaseAddress; + ulong endAddr = pagesCount * PageSize + baseAddress; - LinkedListNode NewNode = null; + LinkedListNode newNode = null; - LinkedListNode Node = Blocks.First; + LinkedListNode node = _blocks.First; - while (Node != null) + while (node != null) { - KMemoryBlock CurrBlock = Node.Value; + KMemoryBlock currBlock = node.Value; - LinkedListNode NextNode = Node.Next; + LinkedListNode nextNode = node.Next; - ulong CurrBaseAddr = CurrBlock.BaseAddress; - ulong CurrEndAddr = CurrBlock.PagesCount * PageSize + CurrBaseAddr; + ulong currBaseAddr = currBlock.BaseAddress; + ulong currEndAddr = currBlock.PagesCount * PageSize + currBaseAddr; - if (BaseAddress < CurrEndAddr && CurrBaseAddr < EndAddr) + if (baseAddress < currEndAddr && currBaseAddr < endAddr) { - if (BaseAddress >= CurrBaseAddr && EndAddr <= CurrEndAddr) + if (baseAddress >= currBaseAddr && endAddr <= currEndAddr) { - Block.Attribute |= CurrBlock.Attribute & MemoryAttribute.IpcAndDeviceMapped; + block.Attribute |= currBlock.Attribute & MemoryAttribute.IpcAndDeviceMapped; } - if (BaseAddress > CurrBaseAddr && EndAddr < CurrEndAddr) + if (baseAddress > currBaseAddr && endAddr < currEndAddr) { - CurrBlock.PagesCount = (BaseAddress - CurrBaseAddr) / PageSize; + currBlock.PagesCount = (baseAddress - currBaseAddr) / PageSize; - ulong NextPagesCount = (CurrEndAddr - EndAddr) / PageSize; + ulong nextPagesCount = (currEndAddr - endAddr) / PageSize; - NewNode = Blocks.AddAfter(Node, Block); + newNode = _blocks.AddAfter(node, block); - Blocks.AddAfter(NewNode, new KMemoryBlock( - EndAddr, - NextPagesCount, - CurrBlock.State, - CurrBlock.Permission, - CurrBlock.Attribute)); + _blocks.AddAfter(newNode, new KMemoryBlock( + endAddr, + nextPagesCount, + currBlock.State, + currBlock.Permission, + currBlock.Attribute)); break; } - else if (BaseAddress <= CurrBaseAddr && EndAddr < CurrEndAddr) + else if (baseAddress <= currBaseAddr && endAddr < currEndAddr) { - CurrBlock.BaseAddress = EndAddr; + currBlock.BaseAddress = endAddr; - CurrBlock.PagesCount = (CurrEndAddr - EndAddr) / PageSize; + currBlock.PagesCount = (currEndAddr - endAddr) / PageSize; - if (NewNode == null) + if (newNode == null) { - NewNode = Blocks.AddBefore(Node, Block); + newNode = _blocks.AddBefore(node, block); } } - else if (BaseAddress > CurrBaseAddr && EndAddr >= CurrEndAddr) + else if (baseAddress > currBaseAddr && endAddr >= currEndAddr) { - CurrBlock.PagesCount = (BaseAddress - CurrBaseAddr) / PageSize; + currBlock.PagesCount = (baseAddress - currBaseAddr) / PageSize; - if (NewNode == null) + if (newNode == null) { - NewNode = Blocks.AddAfter(Node, Block); + newNode = _blocks.AddAfter(node, block); } } else { - if (NewNode == null) + if (newNode == null) { - NewNode = Blocks.AddBefore(Node, Block); + newNode = _blocks.AddBefore(node, block); } - Blocks.Remove(Node); + _blocks.Remove(node); } } - Node = NextNode; + node = nextNode; } - if (NewNode == null) + if (newNode == null) { - NewNode = Blocks.AddFirst(Block); + newNode = _blocks.AddFirst(block); } - MergeEqualStateNeighbours(NewNode); + MergeEqualStateNeighbours(newNode); - BlockAllocator.Count += Blocks.Count - OldCount; + _blockAllocator.Count += _blocks.Count - oldCount; } - private void MergeEqualStateNeighbours(LinkedListNode Node) + private void MergeEqualStateNeighbours(LinkedListNode node) { - KMemoryBlock Block = Node.Value; + KMemoryBlock block = node.Value; - ulong EndAddr = Block.PagesCount * PageSize + Block.BaseAddress; + ulong endAddr = block.PagesCount * PageSize + block.BaseAddress; - if (Node.Previous != null) + if (node.Previous != null) { - KMemoryBlock Previous = Node.Previous.Value; + KMemoryBlock previous = node.Previous.Value; - if (BlockStateEquals(Block, Previous)) + if (BlockStateEquals(block, previous)) { - Blocks.Remove(Node.Previous); + _blocks.Remove(node.Previous); - Block.BaseAddress = Previous.BaseAddress; + block.BaseAddress = previous.BaseAddress; } } - if (Node.Next != null) + if (node.Next != null) { - KMemoryBlock Next = Node.Next.Value; + KMemoryBlock next = node.Next.Value; - if (BlockStateEquals(Block, Next)) + if (BlockStateEquals(block, next)) { - Blocks.Remove(Node.Next); + _blocks.Remove(node.Next); - EndAddr = Next.BaseAddress + Next.PagesCount * PageSize; + endAddr = next.BaseAddress + next.PagesCount * PageSize; } } - Block.PagesCount = (EndAddr - Block.BaseAddress) / PageSize; + block.PagesCount = (endAddr - block.BaseAddress) / PageSize; } - private static bool BlockStateEquals(KMemoryBlock Lhs, KMemoryBlock Rhs) + private static bool BlockStateEquals(KMemoryBlock lhs, KMemoryBlock rhs) { - return Lhs.State == Rhs.State && - Lhs.Permission == Rhs.Permission && - Lhs.Attribute == Rhs.Attribute && - Lhs.DeviceRefCount == Rhs.DeviceRefCount && - Lhs.IpcRefCount == Rhs.IpcRefCount; + return lhs.State == rhs.State && + lhs.Permission == rhs.Permission && + lhs.Attribute == rhs.Attribute && + lhs.DeviceRefCount == rhs.DeviceRefCount && + lhs.IpcRefCount == rhs.IpcRefCount; } private ulong FindFirstFit( - ulong RegionStart, - ulong RegionPagesCount, - ulong NeededPagesCount, - int Alignment, - ulong ReservedStart, - ulong ReservedPagesCount) + ulong regionStart, + ulong regionPagesCount, + ulong neededPagesCount, + int alignment, + ulong reservedStart, + ulong reservedPagesCount) { - ulong ReservedSize = ReservedPagesCount * PageSize; + ulong reservedSize = reservedPagesCount * PageSize; - ulong TotalNeededSize = ReservedSize + NeededPagesCount * PageSize; + ulong totalNeededSize = reservedSize + neededPagesCount * PageSize; - ulong RegionEndAddr = RegionStart + RegionPagesCount * PageSize; + ulong regionEndAddr = regionStart + regionPagesCount * PageSize; - LinkedListNode Node = FindBlockNode(RegionStart); + LinkedListNode node = FindBlockNode(regionStart); - KMemoryInfo Info = Node.Value.GetInfo(); + KMemoryInfo info = node.Value.GetInfo(); - while (RegionEndAddr >= Info.Address) + while (regionEndAddr >= info.Address) { - if (Info.State == MemoryState.Unmapped) + if (info.State == MemoryState.Unmapped) { - ulong CurrBaseAddr = Info.Address + ReservedSize; - ulong CurrEndAddr = Info.Address + Info.Size - 1; + ulong currBaseAddr = info.Address + reservedSize; + ulong currEndAddr = info.Address + info.Size - 1; - ulong Address = BitUtils.AlignDown(CurrBaseAddr, Alignment) + ReservedStart; + ulong address = BitUtils.AlignDown(currBaseAddr, alignment) + reservedStart; - if (CurrBaseAddr > Address) + if (currBaseAddr > address) { - Address += (ulong)Alignment; + address += (ulong)alignment; } - ulong AllocationEndAddr = Address + TotalNeededSize - 1; + ulong allocationEndAddr = address + totalNeededSize - 1; - if (AllocationEndAddr <= RegionEndAddr && - AllocationEndAddr <= CurrEndAddr && - Address < AllocationEndAddr) + if (allocationEndAddr <= regionEndAddr && + allocationEndAddr <= currEndAddr && + address < allocationEndAddr) { - return Address; + return address; } } - Node = Node.Next; + node = node.Next; - if (Node == null) + if (node == null) { break; } - Info = Node.Value.GetInfo(); + info = node.Value.GetInfo(); } return 0; } - private KMemoryBlock FindBlock(ulong Address) + private KMemoryBlock FindBlock(ulong address) { - return FindBlockNode(Address)?.Value; + return FindBlockNode(address)?.Value; } - private LinkedListNode FindBlockNode(ulong Address) + private LinkedListNode FindBlockNode(ulong address) { - lock (Blocks) + lock (_blocks) { - LinkedListNode Node = Blocks.First; + LinkedListNode node = _blocks.First; - while (Node != null) + while (node != null) { - KMemoryBlock Block = Node.Value; + KMemoryBlock block = node.Value; - ulong CurrEndAddr = Block.PagesCount * PageSize + Block.BaseAddress; + ulong currEndAddr = block.PagesCount * PageSize + block.BaseAddress; - if (Block.BaseAddress <= Address && CurrEndAddr - 1 >= Address) + if (block.BaseAddress <= address && currEndAddr - 1 >= address) { - return Node; + return node; } - Node = Node.Next; + node = node.Next; } } return null; } - private bool ValidateRegionForState(ulong Address, ulong Size, MemoryState State) + private bool ValidateRegionForState(ulong address, ulong size, MemoryState state) { - ulong EndAddr = Address + Size; + ulong endAddr = address + size; - ulong RegionBaseAddr = GetBaseAddrForState(State); + ulong regionBaseAddr = GetBaseAddrForState(state); - ulong RegionEndAddr = RegionBaseAddr + GetSizeForState(State); + ulong regionEndAddr = regionBaseAddr + GetSizeForState(state); bool InsideRegion() { - return RegionBaseAddr <= Address && - EndAddr > Address && - EndAddr - 1 <= RegionEndAddr - 1; + return regionBaseAddr <= address && + endAddr > address && + endAddr - 1 <= regionEndAddr - 1; } bool OutsideHeapRegion() { - return EndAddr <= HeapRegionStart || - Address >= HeapRegionEnd; + return endAddr <= HeapRegionStart || + address >= HeapRegionEnd; } bool OutsideMapRegion() { - return EndAddr <= AliasRegionStart || - Address >= AliasRegionEnd; + return endAddr <= AliasRegionStart || + address >= AliasRegionEnd; } - switch (State) + switch (state) { case MemoryState.Io: case MemoryState.Normal: @@ -2127,12 +2127,12 @@ namespace Ryujinx.HLE.HOS.Kernel return InsideRegion(); } - throw new ArgumentException($"Invalid state value \"{State}\"."); + throw new ArgumentException($"Invalid state value \"{state}\"."); } - private ulong GetBaseAddrForState(MemoryState State) + private ulong GetBaseAddrForState(MemoryState state) { - switch (State) + switch (state) { case MemoryState.Io: case MemoryState.Normal: @@ -2166,12 +2166,12 @@ namespace Ryujinx.HLE.HOS.Kernel return AddrSpaceStart; } - throw new ArgumentException($"Invalid state value \"{State}\"."); + throw new ArgumentException($"Invalid state value \"{state}\"."); } - private ulong GetSizeForState(MemoryState State) + private ulong GetSizeForState(MemoryState state) { - switch (State) + switch (state) { case MemoryState.Io: case MemoryState.Normal: @@ -2205,7 +2205,7 @@ namespace Ryujinx.HLE.HOS.Kernel return AddrSpaceEnd - AddrSpaceStart; } - throw new ArgumentException($"Invalid state value \"{State}\"."); + throw new ArgumentException($"Invalid state value \"{state}\"."); } public ulong GetAddrSpaceBaseAddr() @@ -2244,98 +2244,98 @@ namespace Ryujinx.HLE.HOS.Kernel } } - private KernelResult MapPages(ulong Address, KPageList PageList, MemoryPermission Permission) + private KernelResult MapPages(ulong address, KPageList pageList, MemoryPermission permission) { - ulong CurrAddr = Address; + ulong currAddr = address; - KernelResult Result = KernelResult.Success; + KernelResult result = KernelResult.Success; - foreach (KPageNode PageNode in PageList) + foreach (KPageNode pageNode in pageList) { - Result = DoMmuOperation( - CurrAddr, - PageNode.PagesCount, - PageNode.Address, + result = DoMmuOperation( + currAddr, + pageNode.PagesCount, + pageNode.Address, true, - Permission, + permission, MemoryOperation.MapPa); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - KMemoryInfo Info = FindBlock(CurrAddr).GetInfo(); + KMemoryInfo info = FindBlock(currAddr).GetInfo(); - ulong PagesCount = (Address - CurrAddr) / PageSize; + ulong pagesCount = (address - currAddr) / PageSize; - Result = MmuUnmap(Address, PagesCount); + result = MmuUnmap(address, pagesCount); break; } - CurrAddr += PageNode.PagesCount * PageSize; + currAddr += pageNode.PagesCount * PageSize; } - return Result; + return result; } - private KernelResult MmuUnmap(ulong Address, ulong PagesCount) + private KernelResult MmuUnmap(ulong address, ulong pagesCount) { return DoMmuOperation( - Address, - PagesCount, + address, + pagesCount, 0, false, MemoryPermission.None, MemoryOperation.Unmap); } - private KernelResult MmuChangePermission(ulong Address, ulong PagesCount, MemoryPermission Permission) + private KernelResult MmuChangePermission(ulong address, ulong pagesCount, MemoryPermission permission) { return DoMmuOperation( - Address, - PagesCount, + address, + pagesCount, 0, false, - Permission, + permission, MemoryOperation.ChangePermRw); } private KernelResult DoMmuOperation( - ulong DstVa, - ulong PagesCount, - ulong SrcPa, - bool Map, - MemoryPermission Permission, - MemoryOperation Operation) + ulong dstVa, + ulong pagesCount, + ulong srcPa, + bool map, + MemoryPermission permission, + MemoryOperation operation) { - if (Map != (Operation == MemoryOperation.MapPa)) + if (map != (operation == MemoryOperation.MapPa)) { - throw new ArgumentException(nameof(Map) + " value is invalid for this operation."); + throw new ArgumentException(nameof(map) + " value is invalid for this operation."); } - KernelResult Result; + KernelResult result; - switch (Operation) + switch (operation) { case MemoryOperation.MapPa: { - ulong Size = PagesCount * PageSize; + ulong size = pagesCount * PageSize; - CpuMemory.Map((long)DstVa, (long)(SrcPa - DramMemoryMap.DramBase), (long)Size); + _cpuMemory.Map((long)dstVa, (long)(srcPa - DramMemoryMap.DramBase), (long)size); - Result = KernelResult.Success; + result = KernelResult.Success; break; } case MemoryOperation.Allocate: { - KMemoryRegionManager Region = GetMemoryRegionManager(); + KMemoryRegionManager region = GetMemoryRegionManager(); - Result = Region.AllocatePages(PagesCount, AslrDisabled, out KPageList PageList); + result = region.AllocatePages(pagesCount, _aslrDisabled, out KPageList pageList); - if (Result == KernelResult.Success) + if (result == KernelResult.Success) { - Result = MmuMapPages(DstVa, PageList); + result = MmuMapPages(dstVa, pageList); } break; @@ -2343,68 +2343,68 @@ namespace Ryujinx.HLE.HOS.Kernel case MemoryOperation.Unmap: { - ulong Size = PagesCount * PageSize; + ulong size = pagesCount * PageSize; - CpuMemory.Unmap((long)DstVa, (long)Size); + _cpuMemory.Unmap((long)dstVa, (long)size); - Result = KernelResult.Success; + result = KernelResult.Success; break; } - case MemoryOperation.ChangePermRw: Result = KernelResult.Success; break; - case MemoryOperation.ChangePermsAndAttributes: Result = KernelResult.Success; break; + case MemoryOperation.ChangePermRw: result = KernelResult.Success; break; + case MemoryOperation.ChangePermsAndAttributes: result = KernelResult.Success; break; - default: throw new ArgumentException($"Invalid operation \"{Operation}\"."); + default: throw new ArgumentException($"Invalid operation \"{operation}\"."); } - return Result; + return result; } private KernelResult DoMmuOperation( - ulong Address, - ulong PagesCount, - KPageList PageList, - MemoryPermission Permission, - MemoryOperation Operation) + ulong address, + ulong pagesCount, + KPageList pageList, + MemoryPermission permission, + MemoryOperation operation) { - if (Operation != MemoryOperation.MapVa) + if (operation != MemoryOperation.MapVa) { - throw new ArgumentException($"Invalid memory operation \"{Operation}\" specified."); + throw new ArgumentException($"Invalid memory operation \"{operation}\" specified."); } - return MmuMapPages(Address, PageList); + return MmuMapPages(address, pageList); } private KMemoryRegionManager GetMemoryRegionManager() { - return System.MemoryRegions[(int)MemRegion]; + return _system.MemoryRegions[(int)_memRegion]; } - private KernelResult MmuMapPages(ulong Address, KPageList PageList) + private KernelResult MmuMapPages(ulong address, KPageList pageList) { - foreach (KPageNode PageNode in PageList) + foreach (KPageNode pageNode in pageList) { - ulong Size = PageNode.PagesCount * PageSize; + ulong size = pageNode.PagesCount * PageSize; - CpuMemory.Map((long)Address, (long)(PageNode.Address - DramMemoryMap.DramBase), (long)Size); + _cpuMemory.Map((long)address, (long)(pageNode.Address - DramMemoryMap.DramBase), (long)size); - Address += Size; + address += size; } return KernelResult.Success; } - public KernelResult ConvertVaToPa(ulong Va, out ulong Pa) + public KernelResult ConvertVaToPa(ulong va, out ulong pa) { - Pa = DramMemoryMap.DramBase + (ulong)CpuMemory.GetPhysicalAddress((long)Va); + pa = DramMemoryMap.DramBase + (ulong)_cpuMemory.GetPhysicalAddress((long)va); return KernelResult.Success; } public long GetMmUsedPages() { - lock (Blocks) + lock (_blocks) { return BitUtils.DivRoundUp(GetMmUsedSize(), PageSize); } @@ -2412,47 +2412,47 @@ namespace Ryujinx.HLE.HOS.Kernel private long GetMmUsedSize() { - return Blocks.Count * KMemoryBlockSize; + return _blocks.Count * KMemoryBlockSize; } - public bool IsInvalidRegion(ulong Address, ulong Size) + public bool IsInvalidRegion(ulong address, ulong size) { - return Address + Size - 1 > GetAddrSpaceBaseAddr() + GetAddrSpaceSize() - 1; + return address + size - 1 > GetAddrSpaceBaseAddr() + GetAddrSpaceSize() - 1; } - public bool InsideAddrSpace(ulong Address, ulong Size) + public bool InsideAddrSpace(ulong address, ulong size) { - return AddrSpaceStart <= Address && Address + Size - 1 <= AddrSpaceEnd - 1; + return AddrSpaceStart <= address && address + size - 1 <= AddrSpaceEnd - 1; } - public bool InsideAliasRegion(ulong Address, ulong Size) + public bool InsideAliasRegion(ulong address, ulong size) { - return Address + Size > AliasRegionStart && AliasRegionEnd > Address; + return address + size > AliasRegionStart && AliasRegionEnd > address; } - public bool InsideHeapRegion(ulong Address, ulong Size) + public bool InsideHeapRegion(ulong address, ulong size) { - return Address + Size > HeapRegionStart && HeapRegionEnd > Address; + return address + size > HeapRegionStart && HeapRegionEnd > address; } - public bool InsideStackRegion(ulong Address, ulong Size) + public bool InsideStackRegion(ulong address, ulong size) { - return Address + Size > StackRegionStart && StackRegionEnd > Address; + return address + size > StackRegionStart && StackRegionEnd > address; } - public bool OutsideAliasRegion(ulong Address, ulong Size) + public bool OutsideAliasRegion(ulong address, ulong size) { - return AliasRegionStart > Address || Address + Size - 1 > AliasRegionEnd - 1; + return AliasRegionStart > address || address + size - 1 > AliasRegionEnd - 1; } - public bool OutsideAddrSpace(ulong Address, ulong Size) + public bool OutsideAddrSpace(ulong address, ulong size) { - return AddrSpaceStart > Address || Address + Size - 1 > AddrSpaceEnd - 1; + return AddrSpaceStart > address || address + size - 1 > AddrSpaceEnd - 1; } - public bool OutsideStackRegion(ulong Address, ulong Size) + public bool OutsideStackRegion(ulong address, ulong size) { - return StackRegionStart > Address || Address + Size - 1 > StackRegionEnd - 1; + return StackRegionStart > address || address + size - 1 > StackRegionEnd - 1; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/KMemoryRegionBlock.cs b/Ryujinx.HLE/HOS/Kernel/KMemoryRegionBlock.cs index 1f334e65..f7e85e9a 100644 --- a/Ryujinx.HLE/HOS/Kernel/KMemoryRegionBlock.cs +++ b/Ryujinx.HLE/HOS/Kernel/KMemoryRegionBlock.cs @@ -12,30 +12,30 @@ namespace Ryujinx.HLE.HOS.Kernel public int Order; public int NextOrder; - public bool TryCoalesce(int Index, int Size) + public bool TryCoalesce(int index, int size) { - long Mask = ((1L << Size) - 1) << (Index & 63); + long mask = ((1L << size) - 1) << (index & 63); - Index /= 64; + index /= 64; - if ((Mask & ~Masks[MaxLevel - 1][Index]) != 0) + if ((mask & ~Masks[MaxLevel - 1][index]) != 0) { return false; } - Masks[MaxLevel - 1][Index] &= ~Mask; + Masks[MaxLevel - 1][index] &= ~mask; - for (int Level = MaxLevel - 2; Level >= 0; Level--, Index /= 64) + for (int level = MaxLevel - 2; level >= 0; level--, index /= 64) { - Masks[Level][Index / 64] &= ~(1L << (Index & 63)); + Masks[level][index / 64] &= ~(1L << (index & 63)); - if (Masks[Level][Index / 64] != 0) + if (Masks[level][index / 64] != 0) { break; } } - FreeCount -= (ulong)Size; + FreeCount -= (ulong)size; return true; } diff --git a/Ryujinx.HLE/HOS/Kernel/KMemoryRegionManager.cs b/Ryujinx.HLE/HOS/Kernel/KMemoryRegionManager.cs index 10db0753..b9265b13 100644 --- a/Ryujinx.HLE/HOS/Kernel/KMemoryRegionManager.cs +++ b/Ryujinx.HLE/HOS/Kernel/KMemoryRegionManager.cs @@ -10,400 +10,400 @@ namespace Ryujinx.HLE.HOS.Kernel public ulong EndAddr { get; private set; } public ulong Size { get; private set; } - private int BlockOrdersCount; + private int _blockOrdersCount; - private KMemoryRegionBlock[] Blocks; + private KMemoryRegionBlock[] _blocks; - public KMemoryRegionManager(ulong Address, ulong Size, ulong EndAddr) + public KMemoryRegionManager(ulong address, ulong size, ulong endAddr) { - Blocks = new KMemoryRegionBlock[BlockOrders.Length]; + _blocks = new KMemoryRegionBlock[BlockOrders.Length]; - this.Address = Address; - this.Size = Size; - this.EndAddr = EndAddr; + Address = address; + Size = size; + EndAddr = endAddr; - BlockOrdersCount = BlockOrders.Length; + _blockOrdersCount = BlockOrders.Length; - for (int BlockIndex = 0; BlockIndex < BlockOrdersCount; BlockIndex++) + for (int blockIndex = 0; blockIndex < _blockOrdersCount; blockIndex++) { - Blocks[BlockIndex] = new KMemoryRegionBlock(); + _blocks[blockIndex] = new KMemoryRegionBlock(); - Blocks[BlockIndex].Order = BlockOrders[BlockIndex]; + _blocks[blockIndex].Order = BlockOrders[blockIndex]; - int NextOrder = BlockIndex == BlockOrdersCount - 1 ? 0 : BlockOrders[BlockIndex + 1]; + int nextOrder = blockIndex == _blockOrdersCount - 1 ? 0 : BlockOrders[blockIndex + 1]; - Blocks[BlockIndex].NextOrder = NextOrder; + _blocks[blockIndex].NextOrder = nextOrder; - int CurrBlockSize = 1 << BlockOrders[BlockIndex]; - int NextBlockSize = CurrBlockSize; + int currBlockSize = 1 << BlockOrders[blockIndex]; + int nextBlockSize = currBlockSize; - if (NextOrder != 0) + if (nextOrder != 0) { - NextBlockSize = 1 << NextOrder; + nextBlockSize = 1 << nextOrder; } - ulong StartAligned = BitUtils.AlignDown(Address, NextBlockSize); - ulong EndAddrAligned = BitUtils.AlignDown(EndAddr, CurrBlockSize); + ulong startAligned = BitUtils.AlignDown(address, nextBlockSize); + ulong endAddrAligned = BitUtils.AlignDown(endAddr, currBlockSize); - ulong SizeInBlocksTruncated = (EndAddrAligned - StartAligned) >> BlockOrders[BlockIndex]; + ulong sizeInBlocksTruncated = (endAddrAligned - startAligned) >> BlockOrders[blockIndex]; - ulong EndAddrRounded = BitUtils.AlignUp(Address + Size, NextBlockSize); + ulong endAddrRounded = BitUtils.AlignUp(address + size, nextBlockSize); - ulong SizeInBlocksRounded = (EndAddrRounded - StartAligned) >> BlockOrders[BlockIndex]; + ulong sizeInBlocksRounded = (endAddrRounded - startAligned) >> BlockOrders[blockIndex]; - Blocks[BlockIndex].StartAligned = StartAligned; - Blocks[BlockIndex].SizeInBlocksTruncated = SizeInBlocksTruncated; - Blocks[BlockIndex].SizeInBlocksRounded = SizeInBlocksRounded; + _blocks[blockIndex].StartAligned = startAligned; + _blocks[blockIndex].SizeInBlocksTruncated = sizeInBlocksTruncated; + _blocks[blockIndex].SizeInBlocksRounded = sizeInBlocksRounded; - ulong CurrSizeInBlocks = SizeInBlocksRounded; + ulong currSizeInBlocks = sizeInBlocksRounded; - int MaxLevel = 0; + int maxLevel = 0; do { - MaxLevel++; + maxLevel++; } - while ((CurrSizeInBlocks /= 64) != 0); + while ((currSizeInBlocks /= 64) != 0); - Blocks[BlockIndex].MaxLevel = MaxLevel; + _blocks[blockIndex].MaxLevel = maxLevel; - Blocks[BlockIndex].Masks = new long[MaxLevel][]; + _blocks[blockIndex].Masks = new long[maxLevel][]; - CurrSizeInBlocks = SizeInBlocksRounded; + currSizeInBlocks = sizeInBlocksRounded; - for (int Level = MaxLevel - 1; Level >= 0; Level--) + for (int level = maxLevel - 1; level >= 0; level--) { - CurrSizeInBlocks = (CurrSizeInBlocks + 63) / 64; + currSizeInBlocks = (currSizeInBlocks + 63) / 64; - Blocks[BlockIndex].Masks[Level] = new long[CurrSizeInBlocks]; + _blocks[blockIndex].Masks[level] = new long[currSizeInBlocks]; } } - if (Size != 0) + if (size != 0) { - FreePages(Address, Size / KMemoryManager.PageSize); + FreePages(address, size / KMemoryManager.PageSize); } } - public KernelResult AllocatePages(ulong PagesCount, bool Backwards, out KPageList PageList) + public KernelResult AllocatePages(ulong pagesCount, bool backwards, out KPageList pageList) { - lock (Blocks) + lock (_blocks) { - return AllocatePagesImpl(PagesCount, Backwards, out PageList); + return AllocatePagesImpl(pagesCount, backwards, out pageList); } } - private KernelResult AllocatePagesImpl(ulong PagesCount, bool Backwards, out KPageList PageList) + private KernelResult AllocatePagesImpl(ulong pagesCount, bool backwards, out KPageList pageList) { - PageList = new KPageList(); + pageList = new KPageList(); - if (BlockOrdersCount > 0) + if (_blockOrdersCount > 0) { - if (GetFreePagesImpl() < PagesCount) + if (GetFreePagesImpl() < pagesCount) { return KernelResult.OutOfMemory; } } - else if (PagesCount != 0) + else if (pagesCount != 0) { return KernelResult.OutOfMemory; } - for (int BlockIndex = BlockOrdersCount - 1; BlockIndex >= 0; BlockIndex--) + for (int blockIndex = _blockOrdersCount - 1; blockIndex >= 0; blockIndex--) { - KMemoryRegionBlock Block = Blocks[BlockIndex]; + KMemoryRegionBlock block = _blocks[blockIndex]; - ulong BestFitBlockSize = 1UL << Block.Order; + ulong bestFitBlockSize = 1UL << block.Order; - ulong BlockPagesCount = BestFitBlockSize / KMemoryManager.PageSize; + ulong blockPagesCount = bestFitBlockSize / KMemoryManager.PageSize; //Check if this is the best fit for this page size. //If so, try allocating as much requested pages as possible. - while (BlockPagesCount <= PagesCount) + while (blockPagesCount <= pagesCount) { - ulong Address = 0; + ulong address = 0; - for (int CurrBlockIndex = BlockIndex; - CurrBlockIndex < BlockOrdersCount && Address == 0; - CurrBlockIndex++) + for (int currBlockIndex = blockIndex; + currBlockIndex < _blockOrdersCount && address == 0; + currBlockIndex++) { - Block = Blocks[CurrBlockIndex]; + block = _blocks[currBlockIndex]; - int Index = 0; + int index = 0; - bool ZeroMask = false; + bool zeroMask = false; - for (int Level = 0; Level < Block.MaxLevel; Level++) + for (int level = 0; level < block.MaxLevel; level++) { - long Mask = Block.Masks[Level][Index]; + long mask = block.Masks[level][index]; - if (Mask == 0) + if (mask == 0) { - ZeroMask = true; + zeroMask = true; break; } - if (Backwards) + if (backwards) { - Index = (Index * 64 + 63) - BitUtils.CountLeadingZeros64(Mask); + index = (index * 64 + 63) - BitUtils.CountLeadingZeros64(mask); } else { - Index = Index * 64 + BitUtils.CountLeadingZeros64(BitUtils.ReverseBits64(Mask)); + index = index * 64 + BitUtils.CountLeadingZeros64(BitUtils.ReverseBits64(mask)); } } - if (Block.SizeInBlocksTruncated <= (ulong)Index || ZeroMask) + if (block.SizeInBlocksTruncated <= (ulong)index || zeroMask) { continue; } - Block.FreeCount--; + block.FreeCount--; - int TempIdx = Index; + int tempIdx = index; - for (int Level = Block.MaxLevel - 1; Level >= 0; Level--, TempIdx /= 64) + for (int level = block.MaxLevel - 1; level >= 0; level--, tempIdx /= 64) { - Block.Masks[Level][TempIdx / 64] &= ~(1L << (TempIdx & 63)); + block.Masks[level][tempIdx / 64] &= ~(1L << (tempIdx & 63)); - if (Block.Masks[Level][TempIdx / 64] != 0) + if (block.Masks[level][tempIdx / 64] != 0) { break; } } - Address = Block.StartAligned + ((ulong)Index << Block.Order); + address = block.StartAligned + ((ulong)index << block.Order); } - for (int CurrBlockIndex = BlockIndex; - CurrBlockIndex < BlockOrdersCount && Address == 0; - CurrBlockIndex++) + for (int currBlockIndex = blockIndex; + currBlockIndex < _blockOrdersCount && address == 0; + currBlockIndex++) { - Block = Blocks[CurrBlockIndex]; + block = _blocks[currBlockIndex]; - int Index = 0; + int index = 0; - bool ZeroMask = false; + bool zeroMask = false; - for (int Level = 0; Level < Block.MaxLevel; Level++) + for (int level = 0; level < block.MaxLevel; level++) { - long Mask = Block.Masks[Level][Index]; + long mask = block.Masks[level][index]; - if (Mask == 0) + if (mask == 0) { - ZeroMask = true; + zeroMask = true; break; } - if (Backwards) + if (backwards) { - Index = Index * 64 + BitUtils.CountLeadingZeros64(BitUtils.ReverseBits64(Mask)); + index = index * 64 + BitUtils.CountLeadingZeros64(BitUtils.ReverseBits64(mask)); } else { - Index = (Index * 64 + 63) - BitUtils.CountLeadingZeros64(Mask); + index = (index * 64 + 63) - BitUtils.CountLeadingZeros64(mask); } } - if (Block.SizeInBlocksTruncated <= (ulong)Index || ZeroMask) + if (block.SizeInBlocksTruncated <= (ulong)index || zeroMask) { continue; } - Block.FreeCount--; + block.FreeCount--; - int TempIdx = Index; + int tempIdx = index; - for (int Level = Block.MaxLevel - 1; Level >= 0; Level--, TempIdx /= 64) + for (int level = block.MaxLevel - 1; level >= 0; level--, tempIdx /= 64) { - Block.Masks[Level][TempIdx / 64] &= ~(1L << (TempIdx & 63)); + block.Masks[level][tempIdx / 64] &= ~(1L << (tempIdx & 63)); - if (Block.Masks[Level][TempIdx / 64] != 0) + if (block.Masks[level][tempIdx / 64] != 0) { break; } } - Address = Block.StartAligned + ((ulong)Index << Block.Order); + address = block.StartAligned + ((ulong)index << block.Order); } //The address being zero means that no free space was found on that order, //just give up and try with the next one. - if (Address == 0) + if (address == 0) { break; } //If we are using a larger order than best fit, then we should //split it into smaller blocks. - ulong FirstFreeBlockSize = 1UL << Block.Order; + ulong firstFreeBlockSize = 1UL << block.Order; - if (FirstFreeBlockSize > BestFitBlockSize) + if (firstFreeBlockSize > bestFitBlockSize) { - FreePages(Address + BestFitBlockSize, (FirstFreeBlockSize - BestFitBlockSize) / KMemoryManager.PageSize); + FreePages(address + bestFitBlockSize, (firstFreeBlockSize - bestFitBlockSize) / KMemoryManager.PageSize); } //Add new allocated page(s) to the pages list. //If an error occurs, then free all allocated pages and fail. - KernelResult Result = PageList.AddRange(Address, BlockPagesCount); + KernelResult result = pageList.AddRange(address, blockPagesCount); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - FreePages(Address, BlockPagesCount); + FreePages(address, blockPagesCount); - foreach (KPageNode PageNode in PageList) + foreach (KPageNode pageNode in pageList) { - FreePages(PageNode.Address, PageNode.PagesCount); + FreePages(pageNode.Address, pageNode.PagesCount); } - return Result; + return result; } - PagesCount -= BlockPagesCount; + pagesCount -= blockPagesCount; } } //Success case, all requested pages were allocated successfully. - if (PagesCount == 0) + if (pagesCount == 0) { return KernelResult.Success; } //Error case, free allocated pages and return out of memory. - foreach (KPageNode PageNode in PageList) + foreach (KPageNode pageNode in pageList) { - FreePages(PageNode.Address, PageNode.PagesCount); + FreePages(pageNode.Address, pageNode.PagesCount); } - PageList = null; + pageList = null; return KernelResult.OutOfMemory; } - public void FreePages(KPageList PageList) + public void FreePages(KPageList pageList) { - lock (Blocks) + lock (_blocks) { - foreach (KPageNode PageNode in PageList) + foreach (KPageNode pageNode in pageList) { - FreePages(PageNode.Address, PageNode.PagesCount); + FreePages(pageNode.Address, pageNode.PagesCount); } } } - private void FreePages(ulong Address, ulong PagesCount) + private void FreePages(ulong address, ulong pagesCount) { - ulong EndAddr = Address + PagesCount * KMemoryManager.PageSize; + ulong endAddr = address + pagesCount * KMemoryManager.PageSize; - int BlockIndex = BlockOrdersCount - 1; + int blockIndex = _blockOrdersCount - 1; - ulong AddressRounded = 0; - ulong EndAddrTruncated = 0; + ulong addressRounded = 0; + ulong endAddrTruncated = 0; - for (; BlockIndex >= 0; BlockIndex--) + for (; blockIndex >= 0; blockIndex--) { - KMemoryRegionBlock AllocInfo = Blocks[BlockIndex]; + KMemoryRegionBlock allocInfo = _blocks[blockIndex]; - int BlockSize = 1 << AllocInfo.Order; + int blockSize = 1 << allocInfo.Order; - AddressRounded = BitUtils.AlignUp (Address, BlockSize); - EndAddrTruncated = BitUtils.AlignDown(EndAddr, BlockSize); + addressRounded = BitUtils.AlignUp (address, blockSize); + endAddrTruncated = BitUtils.AlignDown(endAddr, blockSize); - if (AddressRounded < EndAddrTruncated) + if (addressRounded < endAddrTruncated) { break; } } - void FreeRegion(ulong CurrAddress) + void FreeRegion(ulong currAddress) { - for (int CurrBlockIndex = BlockIndex; - CurrBlockIndex < BlockOrdersCount && CurrAddress != 0; - CurrBlockIndex++) + for (int currBlockIndex = blockIndex; + currBlockIndex < _blockOrdersCount && currAddress != 0; + currBlockIndex++) { - KMemoryRegionBlock Block = Blocks[CurrBlockIndex]; + KMemoryRegionBlock block = _blocks[currBlockIndex]; - Block.FreeCount++; + block.FreeCount++; - ulong FreedBlocks = (CurrAddress - Block.StartAligned) >> Block.Order; + ulong freedBlocks = (currAddress - block.StartAligned) >> block.Order; - int Index = (int)FreedBlocks; + int index = (int)freedBlocks; - for (int Level = Block.MaxLevel - 1; Level >= 0; Level--, Index /= 64) + for (int level = block.MaxLevel - 1; level >= 0; level--, index /= 64) { - long Mask = Block.Masks[Level][Index / 64]; + long mask = block.Masks[level][index / 64]; - Block.Masks[Level][Index / 64] = Mask | (1L << (Index & 63)); + block.Masks[level][index / 64] = mask | (1L << (index & 63)); - if (Mask != 0) + if (mask != 0) { break; } } - int BlockSizeDelta = 1 << (Block.NextOrder - Block.Order); + int blockSizeDelta = 1 << (block.NextOrder - block.Order); - int FreedBlocksTruncated = BitUtils.AlignDown((int)FreedBlocks, BlockSizeDelta); + int freedBlocksTruncated = BitUtils.AlignDown((int)freedBlocks, blockSizeDelta); - if (!Block.TryCoalesce(FreedBlocksTruncated, BlockSizeDelta)) + if (!block.TryCoalesce(freedBlocksTruncated, blockSizeDelta)) { break; } - CurrAddress = Block.StartAligned + ((ulong)FreedBlocksTruncated << Block.Order); + currAddress = block.StartAligned + ((ulong)freedBlocksTruncated << block.Order); } } //Free inside aligned region. - ulong BaseAddress = AddressRounded; + ulong baseAddress = addressRounded; - while (BaseAddress < EndAddrTruncated) + while (baseAddress < endAddrTruncated) { - ulong BlockSize = 1UL << Blocks[BlockIndex].Order; + ulong blockSize = 1UL << _blocks[blockIndex].Order; - FreeRegion(BaseAddress); + FreeRegion(baseAddress); - BaseAddress += BlockSize; + baseAddress += blockSize; } - int NextBlockIndex = BlockIndex - 1; + int nextBlockIndex = blockIndex - 1; //Free region between Address and aligned region start. - BaseAddress = AddressRounded; + baseAddress = addressRounded; - for (BlockIndex = NextBlockIndex; BlockIndex >= 0; BlockIndex--) + for (blockIndex = nextBlockIndex; blockIndex >= 0; blockIndex--) { - ulong BlockSize = 1UL << Blocks[BlockIndex].Order; + ulong blockSize = 1UL << _blocks[blockIndex].Order; - while (BaseAddress - BlockSize >= Address) + while (baseAddress - blockSize >= address) { - BaseAddress -= BlockSize; + baseAddress -= blockSize; - FreeRegion(BaseAddress); + FreeRegion(baseAddress); } } //Free region between aligned region end and End Address. - BaseAddress = EndAddrTruncated; + baseAddress = endAddrTruncated; - for (BlockIndex = NextBlockIndex; BlockIndex >= 0; BlockIndex--) + for (blockIndex = nextBlockIndex; blockIndex >= 0; blockIndex--) { - ulong BlockSize = 1UL << Blocks[BlockIndex].Order; + ulong blockSize = 1UL << _blocks[blockIndex].Order; - while (BaseAddress + BlockSize <= EndAddr) + while (baseAddress + blockSize <= endAddr) { - FreeRegion(BaseAddress); + FreeRegion(baseAddress); - BaseAddress += BlockSize; + baseAddress += blockSize; } } } public ulong GetFreePages() { - lock (Blocks) + lock (_blocks) { return GetFreePagesImpl(); } @@ -411,18 +411,18 @@ namespace Ryujinx.HLE.HOS.Kernel private ulong GetFreePagesImpl() { - ulong AvailablePages = 0; + ulong availablePages = 0; - for (int BlockIndex = 0; BlockIndex < BlockOrdersCount; BlockIndex++) + for (int blockIndex = 0; blockIndex < _blockOrdersCount; blockIndex++) { - KMemoryRegionBlock Block = Blocks[BlockIndex]; + KMemoryRegionBlock block = _blocks[blockIndex]; - ulong BlockPagesCount = (1UL << Block.Order) / KMemoryManager.PageSize; + ulong blockPagesCount = (1UL << block.Order) / KMemoryManager.PageSize; - AvailablePages += BlockPagesCount * Block.FreeCount; + availablePages += blockPagesCount * block.FreeCount; } - return AvailablePages; + return availablePages; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/KPageList.cs b/Ryujinx.HLE/HOS/Kernel/KPageList.cs index 05162323..b24d126f 100644 --- a/Ryujinx.HLE/HOS/Kernel/KPageList.cs +++ b/Ryujinx.HLE/HOS/Kernel/KPageList.cs @@ -12,24 +12,24 @@ namespace Ryujinx.HLE.HOS.Kernel Nodes = new LinkedList(); } - public KernelResult AddRange(ulong Address, ulong PagesCount) + public KernelResult AddRange(ulong address, ulong pagesCount) { - if (PagesCount != 0) + if (pagesCount != 0) { if (Nodes.Last != null) { - KPageNode LastNode = Nodes.Last.Value; + KPageNode lastNode = Nodes.Last.Value; - if (LastNode.Address + LastNode.PagesCount * KMemoryManager.PageSize == Address) + if (lastNode.Address + lastNode.PagesCount * KMemoryManager.PageSize == address) { - Address = LastNode.Address; - PagesCount += LastNode.PagesCount; + address = lastNode.Address; + pagesCount += lastNode.PagesCount; Nodes.RemoveLast(); } } - Nodes.AddLast(new KPageNode(Address, PagesCount)); + Nodes.AddLast(new KPageNode(address, pagesCount)); } return KernelResult.Success; @@ -37,34 +37,34 @@ namespace Ryujinx.HLE.HOS.Kernel public ulong GetPagesCount() { - ulong Sum = 0; + ulong sum = 0; - foreach (KPageNode Node in Nodes) + foreach (KPageNode node in Nodes) { - Sum += Node.PagesCount; + sum += node.PagesCount; } - return Sum; + return sum; } - public bool IsEqual(KPageList Other) + public bool IsEqual(KPageList other) { - LinkedListNode ThisNode = Nodes.First; - LinkedListNode OtherNode = Other.Nodes.First; + LinkedListNode thisNode = Nodes.First; + LinkedListNode otherNode = other.Nodes.First; - while (ThisNode != null && OtherNode != null) + while (thisNode != null && otherNode != null) { - if (ThisNode.Value.Address != OtherNode.Value.Address || - ThisNode.Value.PagesCount != OtherNode.Value.PagesCount) + if (thisNode.Value.Address != otherNode.Value.Address || + thisNode.Value.PagesCount != otherNode.Value.PagesCount) { return false; } - ThisNode = ThisNode.Next; - OtherNode = OtherNode.Next; + thisNode = thisNode.Next; + otherNode = otherNode.Next; } - return ThisNode == null && OtherNode == null; + return thisNode == null && otherNode == null; } public IEnumerator GetEnumerator() diff --git a/Ryujinx.HLE/HOS/Kernel/KPageNode.cs b/Ryujinx.HLE/HOS/Kernel/KPageNode.cs index 6cecab2e..5cdb1c49 100644 --- a/Ryujinx.HLE/HOS/Kernel/KPageNode.cs +++ b/Ryujinx.HLE/HOS/Kernel/KPageNode.cs @@ -5,10 +5,10 @@ namespace Ryujinx.HLE.HOS.Kernel public ulong Address; public ulong PagesCount; - public KPageNode(ulong Address, ulong PagesCount) + public KPageNode(ulong address, ulong pagesCount) { - this.Address = Address; - this.PagesCount = PagesCount; + Address = address; + PagesCount = pagesCount; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/KPort.cs b/Ryujinx.HLE/HOS/Kernel/KPort.cs index 598f3a32..a6c5b375 100644 --- a/Ryujinx.HLE/HOS/Kernel/KPort.cs +++ b/Ryujinx.HLE/HOS/Kernel/KPort.cs @@ -5,22 +5,22 @@ namespace Ryujinx.HLE.HOS.Kernel public KServerPort ServerPort { get; private set; } public KClientPort ClientPort { get; private set; } - private long NameAddress; - private bool IsLight; + private long _nameAddress; + private bool _isLight; - public KPort(Horizon System) : base(System) + public KPort(Horizon system) : base(system) { - ServerPort = new KServerPort(System); - ClientPort = new KClientPort(System); + ServerPort = new KServerPort(system); + ClientPort = new KClientPort(system); } - public void Initialize(int MaxSessions, bool IsLight, long NameAddress) + public void Initialize(int maxSessions, bool isLight, long nameAddress) { ServerPort.Initialize(this); - ClientPort.Initialize(this, MaxSessions); + ClientPort.Initialize(this, maxSessions); - this.IsLight = IsLight; - this.NameAddress = NameAddress; + _isLight = isLight; + _nameAddress = nameAddress; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/KProcess.cs b/Ryujinx.HLE/HOS/Kernel/KProcess.cs index 094ef222..c5cfd964 100644 --- a/Ryujinx.HLE/HOS/Kernel/KProcess.cs +++ b/Ryujinx.HLE/HOS/Kernel/KProcess.cs @@ -23,8 +23,8 @@ namespace Ryujinx.HLE.HOS.Kernel public KMemoryManager MemoryManager { get; private set; } - private SortedDictionary FullTlsPages; - private SortedDictionary FreeTlsPages; + private SortedDictionary _fullTlsPages; + private SortedDictionary _freeTlsPages; public int DefaultCpuCore { get; private set; } @@ -34,43 +34,43 @@ namespace Ryujinx.HLE.HOS.Kernel public ulong PersonalMmHeapPagesCount { get; private set; } - private ProcessState State; + private ProcessState _state; - private object ProcessLock; - private object ThreadingLock; + private object _processLock; + private object _threadingLock; public KAddressArbiter AddressArbiter { get; private set; } public long[] RandomEntropy { get; private set; } - private bool Signaled; - private bool UseSystemMemBlocks; + private bool _signaled; + private bool _useSystemMemBlocks; public string Name { get; private set; } - private int ThreadCount; + private int _threadCount; public int MmuFlags { get; private set; } - private MemoryRegion MemRegion; + private MemoryRegion _memRegion; public KProcessCapabilities Capabilities { get; private set; } public long TitleId { get; private set; } public long Pid { get; private set; } - private long CreationTimestamp; - private ulong Entrypoint; - private ulong ImageSize; - private ulong MainThreadStackSize; - private ulong MemoryUsageCapacity; - private int Category; + private long _creationTimestamp; + private ulong _entrypoint; + private ulong _imageSize; + private ulong _mainThreadStackSize; + private ulong _memoryUsageCapacity; + private int _category; public KHandleTable HandleTable { get; private set; } public ulong UserExceptionContextAddress { get; private set; } - private LinkedList Threads; + private LinkedList _threads; public bool IsPaused { get; private set; } @@ -78,98 +78,98 @@ namespace Ryujinx.HLE.HOS.Kernel public MemoryManager CpuMemory { get; private set; } - private SvcHandler SvcHandler; + private SvcHandler _svcHandler; public HleProcessDebugger Debugger { get; private set; } - public KProcess(Horizon System) : base(System) + public KProcess(Horizon system) : base(system) { - ProcessLock = new object(); - ThreadingLock = new object(); + _processLock = new object(); + _threadingLock = new object(); - CpuMemory = new MemoryManager(System.Device.Memory.RamPointer); + CpuMemory = new MemoryManager(system.Device.Memory.RamPointer); CpuMemory.InvalidAccess += InvalidAccessHandler; - AddressArbiter = new KAddressArbiter(System); + AddressArbiter = new KAddressArbiter(system); - MemoryManager = new KMemoryManager(System, CpuMemory); + MemoryManager = new KMemoryManager(system, CpuMemory); - FullTlsPages = new SortedDictionary(); - FreeTlsPages = new SortedDictionary(); + _fullTlsPages = new SortedDictionary(); + _freeTlsPages = new SortedDictionary(); Capabilities = new KProcessCapabilities(); RandomEntropy = new long[KScheduler.CpuCoresCount]; - Threads = new LinkedList(); + _threads = new LinkedList(); Translator = new Translator(); Translator.CpuTrace += CpuTraceHandler; - SvcHandler = new SvcHandler(System.Device, this); + _svcHandler = new SvcHandler(system.Device, this); Debugger = new HleProcessDebugger(this); } public KernelResult InitializeKip( - ProcessCreationInfo CreationInfo, - int[] Caps, - KPageList PageList, - KResourceLimit ResourceLimit, - MemoryRegion MemRegion) + ProcessCreationInfo creationInfo, + int[] caps, + KPageList pageList, + KResourceLimit resourceLimit, + MemoryRegion memRegion) { - this.ResourceLimit = ResourceLimit; - this.MemRegion = MemRegion; + ResourceLimit = resourceLimit; + _memRegion = memRegion; - AddressSpaceType AddrSpaceType = (AddressSpaceType)((CreationInfo.MmuFlags >> 1) & 7); + AddressSpaceType addrSpaceType = (AddressSpaceType)((creationInfo.MmuFlags >> 1) & 7); - bool AslrEnabled = ((CreationInfo.MmuFlags >> 5) & 1) != 0; + bool aslrEnabled = ((creationInfo.MmuFlags >> 5) & 1) != 0; - ulong CodeAddress = CreationInfo.CodeAddress; + ulong codeAddress = creationInfo.CodeAddress; - ulong CodeSize = (ulong)CreationInfo.CodePagesCount * KMemoryManager.PageSize; + ulong codeSize = (ulong)creationInfo.CodePagesCount * KMemoryManager.PageSize; - KMemoryBlockAllocator MemoryBlockAllocator = (MmuFlags & 0x40) != 0 + KMemoryBlockAllocator memoryBlockAllocator = (MmuFlags & 0x40) != 0 ? System.LargeMemoryBlockAllocator : System.SmallMemoryBlockAllocator; - KernelResult Result = MemoryManager.InitializeForProcess( - AddrSpaceType, - AslrEnabled, - !AslrEnabled, - MemRegion, - CodeAddress, - CodeSize, - MemoryBlockAllocator); + KernelResult result = MemoryManager.InitializeForProcess( + addrSpaceType, + aslrEnabled, + !aslrEnabled, + memRegion, + codeAddress, + codeSize, + memoryBlockAllocator); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - return Result; + return result; } - if (!ValidateCodeAddressAndSize(CodeAddress, CodeSize)) + if (!ValidateCodeAddressAndSize(codeAddress, codeSize)) { return KernelResult.InvalidMemRange; } - Result = MemoryManager.MapPages( - CodeAddress, - PageList, + result = MemoryManager.MapPages( + codeAddress, + pageList, MemoryState.CodeStatic, MemoryPermission.None); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - return Result; + return result; } - Result = Capabilities.InitializeForKernel(Caps, MemoryManager); + result = Capabilities.InitializeForKernel(caps, MemoryManager); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - return Result; + return result; } Pid = System.GetKipId(); @@ -179,29 +179,29 @@ namespace Ryujinx.HLE.HOS.Kernel throw new InvalidOperationException($"Invalid KIP Id {Pid}."); } - Result = ParseProcessInfo(CreationInfo); + result = ParseProcessInfo(creationInfo); - return Result; + return result; } public KernelResult Initialize( - ProcessCreationInfo CreationInfo, - int[] Caps, - KResourceLimit ResourceLimit, - MemoryRegion MemRegion) + ProcessCreationInfo creationInfo, + int[] caps, + KResourceLimit resourceLimit, + MemoryRegion memRegion) { - this.ResourceLimit = ResourceLimit; - this.MemRegion = MemRegion; + ResourceLimit = resourceLimit; + _memRegion = memRegion; - ulong PersonalMmHeapSize = GetPersonalMmHeapSize((ulong)CreationInfo.PersonalMmHeapPagesCount, MemRegion); + ulong personalMmHeapSize = GetPersonalMmHeapSize((ulong)creationInfo.PersonalMmHeapPagesCount, memRegion); - ulong CodePagesCount = (ulong)CreationInfo.CodePagesCount; + ulong codePagesCount = (ulong)creationInfo.CodePagesCount; - ulong NeededSizeForProcess = PersonalMmHeapSize + CodePagesCount * KMemoryManager.PageSize; + ulong neededSizeForProcess = personalMmHeapSize + codePagesCount * KMemoryManager.PageSize; - if (NeededSizeForProcess != 0 && ResourceLimit != null) + if (neededSizeForProcess != 0 && resourceLimit != null) { - if (!ResourceLimit.Reserve(LimitableResource.Memory, NeededSizeForProcess)) + if (!resourceLimit.Reserve(LimitableResource.Memory, neededSizeForProcess)) { return KernelResult.ResLimitExceeded; } @@ -209,78 +209,78 @@ namespace Ryujinx.HLE.HOS.Kernel void CleanUpForError() { - if (NeededSizeForProcess != 0 && ResourceLimit != null) + if (neededSizeForProcess != 0 && resourceLimit != null) { - ResourceLimit.Release(LimitableResource.Memory, NeededSizeForProcess); + resourceLimit.Release(LimitableResource.Memory, neededSizeForProcess); } } - PersonalMmHeapPagesCount = (ulong)CreationInfo.PersonalMmHeapPagesCount; + PersonalMmHeapPagesCount = (ulong)creationInfo.PersonalMmHeapPagesCount; - KMemoryBlockAllocator MemoryBlockAllocator; + KMemoryBlockAllocator memoryBlockAllocator; if (PersonalMmHeapPagesCount != 0) { - MemoryBlockAllocator = new KMemoryBlockAllocator(PersonalMmHeapPagesCount * KMemoryManager.PageSize); + memoryBlockAllocator = new KMemoryBlockAllocator(PersonalMmHeapPagesCount * KMemoryManager.PageSize); } else { - MemoryBlockAllocator = (MmuFlags & 0x40) != 0 + memoryBlockAllocator = (MmuFlags & 0x40) != 0 ? System.LargeMemoryBlockAllocator : System.SmallMemoryBlockAllocator; } - AddressSpaceType AddrSpaceType = (AddressSpaceType)((CreationInfo.MmuFlags >> 1) & 7); + AddressSpaceType addrSpaceType = (AddressSpaceType)((creationInfo.MmuFlags >> 1) & 7); - bool AslrEnabled = ((CreationInfo.MmuFlags >> 5) & 1) != 0; + bool aslrEnabled = ((creationInfo.MmuFlags >> 5) & 1) != 0; - ulong CodeAddress = CreationInfo.CodeAddress; + ulong codeAddress = creationInfo.CodeAddress; - ulong CodeSize = CodePagesCount * KMemoryManager.PageSize; + ulong codeSize = codePagesCount * KMemoryManager.PageSize; - KernelResult Result = MemoryManager.InitializeForProcess( - AddrSpaceType, - AslrEnabled, - !AslrEnabled, - MemRegion, - CodeAddress, - CodeSize, - MemoryBlockAllocator); + KernelResult result = MemoryManager.InitializeForProcess( + addrSpaceType, + aslrEnabled, + !aslrEnabled, + memRegion, + codeAddress, + codeSize, + memoryBlockAllocator); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { CleanUpForError(); - return Result; + return result; } - if (!ValidateCodeAddressAndSize(CodeAddress, CodeSize)) + if (!ValidateCodeAddressAndSize(codeAddress, codeSize)) { CleanUpForError(); return KernelResult.InvalidMemRange; } - Result = MemoryManager.MapNewProcessCode( - CodeAddress, - CodePagesCount, + result = MemoryManager.MapNewProcessCode( + codeAddress, + codePagesCount, MemoryState.CodeStatic, MemoryPermission.None); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { CleanUpForError(); - return Result; + return result; } - Result = Capabilities.InitializeForUser(Caps, MemoryManager); + result = Capabilities.InitializeForUser(caps, MemoryManager); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { CleanUpForError(); - return Result; + return result; } Pid = System.GetProcessId(); @@ -290,53 +290,53 @@ namespace Ryujinx.HLE.HOS.Kernel throw new InvalidOperationException($"Invalid Process Id {Pid}."); } - Result = ParseProcessInfo(CreationInfo); + result = ParseProcessInfo(creationInfo); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { CleanUpForError(); } - return Result; + return result; } - private bool ValidateCodeAddressAndSize(ulong Address, ulong Size) + private bool ValidateCodeAddressAndSize(ulong address, ulong size) { - ulong CodeRegionStart; - ulong CodeRegionSize; + ulong codeRegionStart; + ulong codeRegionSize; switch (MemoryManager.AddrSpaceWidth) { case 32: - CodeRegionStart = 0x200000; - CodeRegionSize = 0x3fe00000; + codeRegionStart = 0x200000; + codeRegionSize = 0x3fe00000; break; case 36: - CodeRegionStart = 0x8000000; - CodeRegionSize = 0x78000000; + codeRegionStart = 0x8000000; + codeRegionSize = 0x78000000; break; case 39: - CodeRegionStart = 0x8000000; - CodeRegionSize = 0x7ff8000000; + codeRegionStart = 0x8000000; + codeRegionSize = 0x7ff8000000; break; default: throw new InvalidOperationException("Invalid address space width on memory manager."); } - ulong EndAddr = Address + Size; + ulong endAddr = address + size; - ulong CodeRegionEnd = CodeRegionStart + CodeRegionSize; + ulong codeRegionEnd = codeRegionStart + codeRegionSize; - if (EndAddr <= Address || - EndAddr - 1 > CodeRegionEnd - 1) + if (endAddr <= address || + endAddr - 1 > codeRegionEnd - 1) { return false; } - if (MemoryManager.InsideHeapRegion (Address, Size) || - MemoryManager.InsideAliasRegion(Address, Size)) + if (MemoryManager.InsideHeapRegion (address, size) || + MemoryManager.InsideAliasRegion(address, size)) { return false; } @@ -344,69 +344,69 @@ namespace Ryujinx.HLE.HOS.Kernel return true; } - private KernelResult ParseProcessInfo(ProcessCreationInfo CreationInfo) + private KernelResult ParseProcessInfo(ProcessCreationInfo creationInfo) { //Ensure that the current kernel version is equal or above to the minimum required. - uint RequiredKernelVersionMajor = (uint)Capabilities.KernelReleaseVersion >> 19; - uint RequiredKernelVersionMinor = ((uint)Capabilities.KernelReleaseVersion >> 15) & 0xf; + uint requiredKernelVersionMajor = (uint)Capabilities.KernelReleaseVersion >> 19; + uint requiredKernelVersionMinor = ((uint)Capabilities.KernelReleaseVersion >> 15) & 0xf; if (System.EnableVersionChecks) { - if (RequiredKernelVersionMajor > KernelVersionMajor) + if (requiredKernelVersionMajor > KernelVersionMajor) { return KernelResult.InvalidCombination; } - if (RequiredKernelVersionMajor != KernelVersionMajor && RequiredKernelVersionMajor < 3) + if (requiredKernelVersionMajor != KernelVersionMajor && requiredKernelVersionMajor < 3) { return KernelResult.InvalidCombination; } - if (RequiredKernelVersionMinor > KernelVersionMinor) + if (requiredKernelVersionMinor > KernelVersionMinor) { return KernelResult.InvalidCombination; } } - KernelResult Result = AllocateThreadLocalStorage(out ulong UserExceptionContextAddress); + KernelResult result = AllocateThreadLocalStorage(out ulong userExceptionContextAddress); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - return Result; + return result; } - this.UserExceptionContextAddress = UserExceptionContextAddress; + UserExceptionContextAddress = userExceptionContextAddress; - MemoryHelper.FillWithZeros(CpuMemory, (long)UserExceptionContextAddress, KTlsPageInfo.TlsEntrySize); + MemoryHelper.FillWithZeros(CpuMemory, (long)userExceptionContextAddress, KTlsPageInfo.TlsEntrySize); - Name = CreationInfo.Name; + Name = creationInfo.Name; - State = ProcessState.Created; + _state = ProcessState.Created; - CreationTimestamp = PerformanceCounter.ElapsedMilliseconds; + _creationTimestamp = PerformanceCounter.ElapsedMilliseconds; - MmuFlags = CreationInfo.MmuFlags; - Category = CreationInfo.Category; - TitleId = CreationInfo.TitleId; - Entrypoint = CreationInfo.CodeAddress; - ImageSize = (ulong)CreationInfo.CodePagesCount * KMemoryManager.PageSize; + MmuFlags = creationInfo.MmuFlags; + _category = creationInfo.Category; + TitleId = creationInfo.TitleId; + _entrypoint = creationInfo.CodeAddress; + _imageSize = (ulong)creationInfo.CodePagesCount * KMemoryManager.PageSize; - UseSystemMemBlocks = ((MmuFlags >> 6) & 1) != 0; + _useSystemMemBlocks = ((MmuFlags >> 6) & 1) != 0; switch ((AddressSpaceType)((MmuFlags >> 1) & 7)) { case AddressSpaceType.Addr32Bits: case AddressSpaceType.Addr36Bits: case AddressSpaceType.Addr39Bits: - MemoryUsageCapacity = MemoryManager.HeapRegionEnd - + _memoryUsageCapacity = MemoryManager.HeapRegionEnd - MemoryManager.HeapRegionStart; break; case AddressSpaceType.Addr32BitsNoMap: - MemoryUsageCapacity = MemoryManager.HeapRegionEnd - - MemoryManager.HeapRegionStart + - MemoryManager.AliasRegionEnd - - MemoryManager.AliasRegionStart; + _memoryUsageCapacity = MemoryManager.HeapRegionEnd - + MemoryManager.HeapRegionStart + + MemoryManager.AliasRegionEnd - + MemoryManager.AliasRegionStart; break; default: throw new InvalidOperationException($"Invalid MMU flags value 0x{MmuFlags:x2}."); @@ -417,130 +417,130 @@ namespace Ryujinx.HLE.HOS.Kernel return KernelResult.Success; } - public KernelResult AllocateThreadLocalStorage(out ulong Address) + public KernelResult AllocateThreadLocalStorage(out ulong address) { System.CriticalSection.Enter(); - KernelResult Result; + KernelResult result; - if (FreeTlsPages.Count > 0) + if (_freeTlsPages.Count > 0) { //If we have free TLS pages available, just use the first one. - KTlsPageInfo PageInfo = FreeTlsPages.Values.First(); + KTlsPageInfo pageInfo = _freeTlsPages.Values.First(); - if (!PageInfo.TryGetFreePage(out Address)) + if (!pageInfo.TryGetFreePage(out address)) { throw new InvalidOperationException("Unexpected failure getting free TLS page!"); } - if (PageInfo.IsFull()) + if (pageInfo.IsFull()) { - FreeTlsPages.Remove(PageInfo.PageAddr); + _freeTlsPages.Remove(pageInfo.PageAddr); - FullTlsPages.Add(PageInfo.PageAddr, PageInfo); + _fullTlsPages.Add(pageInfo.PageAddr, pageInfo); } - Result = KernelResult.Success; + result = KernelResult.Success; } else { //Otherwise, we need to create a new one. - Result = AllocateTlsPage(out KTlsPageInfo PageInfo); + result = AllocateTlsPage(out KTlsPageInfo pageInfo); - if (Result == KernelResult.Success) + if (result == KernelResult.Success) { - if (!PageInfo.TryGetFreePage(out Address)) + if (!pageInfo.TryGetFreePage(out address)) { throw new InvalidOperationException("Unexpected failure getting free TLS page!"); } - FreeTlsPages.Add(PageInfo.PageAddr, PageInfo); + _freeTlsPages.Add(pageInfo.PageAddr, pageInfo); } else { - Address = 0; + address = 0; } } System.CriticalSection.Leave(); - return Result; + return result; } - private KernelResult AllocateTlsPage(out KTlsPageInfo PageInfo) + private KernelResult AllocateTlsPage(out KTlsPageInfo pageInfo) { - PageInfo = default(KTlsPageInfo); + pageInfo = default(KTlsPageInfo); - if (!System.UserSlabHeapPages.TryGetItem(out ulong TlsPagePa)) + if (!System.UserSlabHeapPages.TryGetItem(out ulong tlsPagePa)) { return KernelResult.OutOfMemory; } - ulong RegionStart = MemoryManager.TlsIoRegionStart; - ulong RegionSize = MemoryManager.TlsIoRegionEnd - RegionStart; + ulong regionStart = MemoryManager.TlsIoRegionStart; + ulong regionSize = MemoryManager.TlsIoRegionEnd - regionStart; - ulong RegionPagesCount = RegionSize / KMemoryManager.PageSize; + ulong regionPagesCount = regionSize / KMemoryManager.PageSize; - KernelResult Result = MemoryManager.AllocateOrMapPa( + KernelResult result = MemoryManager.AllocateOrMapPa( 1, KMemoryManager.PageSize, - TlsPagePa, + tlsPagePa, true, - RegionStart, - RegionPagesCount, + regionStart, + regionPagesCount, MemoryState.ThreadLocal, MemoryPermission.ReadAndWrite, - out ulong TlsPageVa); + out ulong tlsPageVa); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - System.UserSlabHeapPages.Free(TlsPagePa); + System.UserSlabHeapPages.Free(tlsPagePa); } else { - PageInfo = new KTlsPageInfo(TlsPageVa); + pageInfo = new KTlsPageInfo(tlsPageVa); - MemoryHelper.FillWithZeros(CpuMemory, (long)TlsPageVa, KMemoryManager.PageSize); + MemoryHelper.FillWithZeros(CpuMemory, (long)tlsPageVa, KMemoryManager.PageSize); } - return Result; + return result; } - public KernelResult FreeThreadLocalStorage(ulong TlsSlotAddr) + public KernelResult FreeThreadLocalStorage(ulong tlsSlotAddr) { - ulong TlsPageAddr = BitUtils.AlignDown(TlsSlotAddr, KMemoryManager.PageSize); + ulong tlsPageAddr = BitUtils.AlignDown(tlsSlotAddr, KMemoryManager.PageSize); System.CriticalSection.Enter(); - KernelResult Result = KernelResult.Success; + KernelResult result = KernelResult.Success; - KTlsPageInfo PageInfo = null; + KTlsPageInfo pageInfo = null; - if (FullTlsPages.TryGetValue(TlsPageAddr, out PageInfo)) + if (_fullTlsPages.TryGetValue(tlsPageAddr, out pageInfo)) { //TLS page was full, free slot and move to free pages tree. - FullTlsPages.Remove(TlsPageAddr); + _fullTlsPages.Remove(tlsPageAddr); - FreeTlsPages.Add(TlsPageAddr, PageInfo); + _freeTlsPages.Add(tlsPageAddr, pageInfo); } - else if (!FreeTlsPages.TryGetValue(TlsPageAddr, out PageInfo)) + else if (!_freeTlsPages.TryGetValue(tlsPageAddr, out pageInfo)) { - Result = KernelResult.InvalidAddress; + result = KernelResult.InvalidAddress; } - if (PageInfo != null) + if (pageInfo != null) { - PageInfo.FreeTlsSlot(TlsSlotAddr); + pageInfo.FreeTlsSlot(tlsSlotAddr); - if (PageInfo.IsEmpty()) + if (pageInfo.IsEmpty()) { //TLS page is now empty, we should ensure it is removed //from all trees, and free the memory it was using. - FreeTlsPages.Remove(TlsPageAddr); + _freeTlsPages.Remove(tlsPageAddr); System.CriticalSection.Leave(); - FreeTlsPage(PageInfo); + FreeTlsPage(pageInfo); return KernelResult.Success; } @@ -548,26 +548,26 @@ namespace Ryujinx.HLE.HOS.Kernel System.CriticalSection.Leave(); - return Result; + return result; } - private KernelResult FreeTlsPage(KTlsPageInfo PageInfo) + private KernelResult FreeTlsPage(KTlsPageInfo pageInfo) { - KernelResult Result = MemoryManager.ConvertVaToPa(PageInfo.PageAddr, out ulong TlsPagePa); + KernelResult result = MemoryManager.ConvertVaToPa(pageInfo.PageAddr, out ulong tlsPagePa); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { throw new InvalidOperationException("Unexpected failure translating virtual address to physical."); } - Result = MemoryManager.UnmapForKernel(PageInfo.PageAddr, 1, MemoryState.ThreadLocal); + result = MemoryManager.UnmapForKernel(pageInfo.PageAddr, 1, MemoryState.ThreadLocal); - if (Result == KernelResult.Success) + if (result == KernelResult.Success) { - System.UserSlabHeapPages.Free(TlsPagePa); + System.UserSlabHeapPages.Free(tlsPagePa); } - return Result; + return result; } private void GenerateRandomEntropy() @@ -575,11 +575,11 @@ namespace Ryujinx.HLE.HOS.Kernel //TODO. } - public KernelResult Start(int MainThreadPriority, ulong StackSize) + public KernelResult Start(int mainThreadPriority, ulong stackSize) { - lock (ProcessLock) + lock (_processLock) { - if (State > ProcessState.CreatedAttached) + if (_state > ProcessState.CreatedAttached) { return KernelResult.InvalidState; } @@ -589,153 +589,153 @@ namespace Ryujinx.HLE.HOS.Kernel return KernelResult.ResLimitExceeded; } - KResourceLimit ThreadResourceLimit = ResourceLimit; - KResourceLimit MemoryResourceLimit = null; + KResourceLimit threadResourceLimit = ResourceLimit; + KResourceLimit memoryResourceLimit = null; - if (MainThreadStackSize != 0) + if (_mainThreadStackSize != 0) { throw new InvalidOperationException("Trying to start a process with a invalid state!"); } - ulong StackSizeRounded = BitUtils.AlignUp(StackSize, KMemoryManager.PageSize); + ulong stackSizeRounded = BitUtils.AlignUp(stackSize, KMemoryManager.PageSize); - ulong NeededSize = StackSizeRounded + ImageSize; + ulong neededSize = stackSizeRounded + _imageSize; //Check if the needed size for the code and the stack will fit on the //memory usage capacity of this Process. Also check for possible overflow //on the above addition. - if (NeededSize > MemoryUsageCapacity || - NeededSize < StackSizeRounded) + if (neededSize > _memoryUsageCapacity || + neededSize < stackSizeRounded) { - ThreadResourceLimit?.Release(LimitableResource.Thread, 1); + threadResourceLimit?.Release(LimitableResource.Thread, 1); return KernelResult.OutOfMemory; } - if (StackSizeRounded != 0 && ResourceLimit != null) + if (stackSizeRounded != 0 && ResourceLimit != null) { - MemoryResourceLimit = ResourceLimit; + memoryResourceLimit = ResourceLimit; - if (!MemoryResourceLimit.Reserve(LimitableResource.Memory, StackSizeRounded)) + if (!memoryResourceLimit.Reserve(LimitableResource.Memory, stackSizeRounded)) { - ThreadResourceLimit?.Release(LimitableResource.Thread, 1); + threadResourceLimit?.Release(LimitableResource.Thread, 1); return KernelResult.ResLimitExceeded; } } - KernelResult Result; + KernelResult result; - KThread MainThread = null; + KThread mainThread = null; - ulong StackTop = 0; + ulong stackTop = 0; void CleanUpForError() { - MainThread?.Terminate(); + mainThread?.Terminate(); HandleTable.Destroy(); - if (MainThreadStackSize != 0) + if (_mainThreadStackSize != 0) { - ulong StackBottom = StackTop - MainThreadStackSize; + ulong stackBottom = stackTop - _mainThreadStackSize; - ulong StackPagesCount = MainThreadStackSize / KMemoryManager.PageSize; + ulong stackPagesCount = _mainThreadStackSize / KMemoryManager.PageSize; - MemoryManager.UnmapForKernel(StackBottom, StackPagesCount, MemoryState.Stack); + MemoryManager.UnmapForKernel(stackBottom, stackPagesCount, MemoryState.Stack); } - MemoryResourceLimit?.Release(LimitableResource.Memory, StackSizeRounded); - ThreadResourceLimit?.Release(LimitableResource.Thread, 1); + memoryResourceLimit?.Release(LimitableResource.Memory, stackSizeRounded); + threadResourceLimit?.Release(LimitableResource.Thread, 1); } - if (StackSizeRounded != 0) + if (stackSizeRounded != 0) { - ulong StackPagesCount = StackSizeRounded / KMemoryManager.PageSize; + ulong stackPagesCount = stackSizeRounded / KMemoryManager.PageSize; - ulong RegionStart = MemoryManager.StackRegionStart; - ulong RegionSize = MemoryManager.StackRegionEnd - RegionStart; + ulong regionStart = MemoryManager.StackRegionStart; + ulong regionSize = MemoryManager.StackRegionEnd - regionStart; - ulong RegionPagesCount = RegionSize / KMemoryManager.PageSize; + ulong regionPagesCount = regionSize / KMemoryManager.PageSize; - Result = MemoryManager.AllocateOrMapPa( - StackPagesCount, + result = MemoryManager.AllocateOrMapPa( + stackPagesCount, KMemoryManager.PageSize, 0, false, - RegionStart, - RegionPagesCount, + regionStart, + regionPagesCount, MemoryState.Stack, MemoryPermission.ReadAndWrite, - out ulong StackBottom); + out ulong stackBottom); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { CleanUpForError(); - return Result; + return result; } - MainThreadStackSize += StackSizeRounded; + _mainThreadStackSize += stackSizeRounded; - StackTop = StackBottom + StackSizeRounded; + stackTop = stackBottom + stackSizeRounded; } - ulong HeapCapacity = MemoryUsageCapacity - MainThreadStackSize - ImageSize; + ulong heapCapacity = _memoryUsageCapacity - _mainThreadStackSize - _imageSize; - Result = MemoryManager.SetHeapCapacity(HeapCapacity); + result = MemoryManager.SetHeapCapacity(heapCapacity); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { CleanUpForError(); - return Result; + return result; } HandleTable = new KHandleTable(System); - Result = HandleTable.Initialize(Capabilities.HandleTableSize); + result = HandleTable.Initialize(Capabilities.HandleTableSize); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { CleanUpForError(); - return Result; + return result; } - MainThread = new KThread(System); + mainThread = new KThread(System); - Result = MainThread.Initialize( - Entrypoint, + result = mainThread.Initialize( + _entrypoint, 0, - StackTop, - MainThreadPriority, + stackTop, + mainThreadPriority, DefaultCpuCore, this); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { CleanUpForError(); - return Result; + return result; } - Result = HandleTable.GenerateHandle(MainThread, out int MainThreadHandle); + result = HandleTable.GenerateHandle(mainThread, out int mainThreadHandle); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { CleanUpForError(); - return Result; + return result; } - MainThread.SetEntryArguments(0, MainThreadHandle); + mainThread.SetEntryArguments(0, mainThreadHandle); - ProcessState OldState = State; - ProcessState NewState = State != ProcessState.Created + ProcessState oldState = _state; + ProcessState newState = _state != ProcessState.Created ? ProcessState.Attached : ProcessState.Started; - SetState(NewState); + SetState(newState); //TODO: We can't call KThread.Start from a non-guest thread. //We will need to make some changes to allow the creation of @@ -750,41 +750,41 @@ namespace Ryujinx.HLE.HOS.Kernel CleanUpForError(); } */ - MainThread.Reschedule(ThreadSchedState.Running); + mainThread.Reschedule(ThreadSchedState.Running); - return Result; + return result; } } - private void SetState(ProcessState NewState) + private void SetState(ProcessState newState) { - if (State != NewState) + if (_state != newState) { - State = NewState; - Signaled = true; + _state = newState; + _signaled = true; Signal(); } } public KernelResult InitializeThread( - KThread Thread, - ulong Entrypoint, - ulong ArgsPtr, - ulong StackTop, - int Priority, - int CpuCore) + KThread thread, + ulong entrypoint, + ulong argsPtr, + ulong stackTop, + int priority, + int cpuCore) { - lock (ProcessLock) + lock (_processLock) { - return Thread.Initialize(Entrypoint, ArgsPtr, StackTop, Priority, CpuCore, this); + return thread.Initialize(entrypoint, argsPtr, stackTop, priority, cpuCore, this); } } - public void SubscribeThreadEventHandlers(CpuThread Context) + public void SubscribeThreadEventHandlers(CpuThread context) { - Context.ThreadState.Interrupt += InterruptHandler; - Context.ThreadState.SvcCall += SvcHandler.SvcCall; + context.ThreadState.Interrupt += InterruptHandler; + context.ThreadState.SvcCall += _svcHandler.SvcCall; } private void InterruptHandler(object sender, EventArgs e) @@ -794,7 +794,7 @@ namespace Ryujinx.HLE.HOS.Kernel public void IncrementThreadCount() { - Interlocked.Increment(ref ThreadCount); + Interlocked.Increment(ref _threadCount); System.ThreadCounter.AddCount(); } @@ -803,7 +803,7 @@ namespace Ryujinx.HLE.HOS.Kernel { System.ThreadCounter.Signal(); - if (Interlocked.Decrement(ref ThreadCount) == 0) + if (Interlocked.Decrement(ref _threadCount) == 0) { Terminate(); } @@ -811,25 +811,25 @@ namespace Ryujinx.HLE.HOS.Kernel public ulong GetMemoryCapacity() { - ulong TotalCapacity = (ulong)ResourceLimit.GetRemainingValue(LimitableResource.Memory); + ulong totalCapacity = (ulong)ResourceLimit.GetRemainingValue(LimitableResource.Memory); - TotalCapacity += MemoryManager.GetTotalHeapSize(); + totalCapacity += MemoryManager.GetTotalHeapSize(); - TotalCapacity += GetPersonalMmHeapSize(); + totalCapacity += GetPersonalMmHeapSize(); - TotalCapacity += ImageSize + MainThreadStackSize; + totalCapacity += _imageSize + _mainThreadStackSize; - if (TotalCapacity <= MemoryUsageCapacity) + if (totalCapacity <= _memoryUsageCapacity) { - return TotalCapacity; + return totalCapacity; } - return MemoryUsageCapacity; + return _memoryUsageCapacity; } public ulong GetMemoryUsage() { - return ImageSize + MainThreadStackSize + MemoryManager.GetTotalHeapSize() + GetPersonalMmHeapSize(); + return _imageSize + _mainThreadStackSize + MemoryManager.GetTotalHeapSize() + GetPersonalMmHeapSize(); } public ulong GetMemoryCapacityWithoutPersonalMmHeap() @@ -844,83 +844,83 @@ namespace Ryujinx.HLE.HOS.Kernel private ulong GetPersonalMmHeapSize() { - return GetPersonalMmHeapSize(PersonalMmHeapPagesCount, MemRegion); + return GetPersonalMmHeapSize(PersonalMmHeapPagesCount, _memRegion); } - private static ulong GetPersonalMmHeapSize(ulong PersonalMmHeapPagesCount, MemoryRegion MemRegion) + private static ulong GetPersonalMmHeapSize(ulong personalMmHeapPagesCount, MemoryRegion memRegion) { - if (MemRegion == MemoryRegion.Applet) + if (memRegion == MemoryRegion.Applet) { return 0; } - return PersonalMmHeapPagesCount * KMemoryManager.PageSize; + return personalMmHeapPagesCount * KMemoryManager.PageSize; } - public void AddThread(KThread Thread) + public void AddThread(KThread thread) { - lock (ThreadingLock) + lock (_threadingLock) { - Thread.ProcessListNode = Threads.AddLast(Thread); + thread.ProcessListNode = _threads.AddLast(thread); } } - public void RemoveThread(KThread Thread) + public void RemoveThread(KThread thread) { - lock (ThreadingLock) + lock (_threadingLock) { - Threads.Remove(Thread.ProcessListNode); + _threads.Remove(thread.ProcessListNode); } } - public bool IsCpuCoreAllowed(int Core) + public bool IsCpuCoreAllowed(int core) { - return (Capabilities.AllowedCpuCoresMask & (1L << Core)) != 0; + return (Capabilities.AllowedCpuCoresMask & (1L << core)) != 0; } - public bool IsPriorityAllowed(int Priority) + public bool IsPriorityAllowed(int priority) { - return (Capabilities.AllowedThreadPriosMask & (1L << Priority)) != 0; + return (Capabilities.AllowedThreadPriosMask & (1L << priority)) != 0; } public override bool IsSignaled() { - return Signaled; + return _signaled; } public KernelResult Terminate() { - KernelResult Result; + KernelResult result; - bool ShallTerminate = false; + bool shallTerminate = false; System.CriticalSection.Enter(); - lock (ProcessLock) + lock (_processLock) { - if (State >= ProcessState.Started) + if (_state >= ProcessState.Started) { - if (State == ProcessState.Started || - State == ProcessState.Crashed || - State == ProcessState.Attached || - State == ProcessState.DebugSuspended) + if (_state == ProcessState.Started || + _state == ProcessState.Crashed || + _state == ProcessState.Attached || + _state == ProcessState.DebugSuspended) { SetState(ProcessState.Exiting); - ShallTerminate = true; + shallTerminate = true; } - Result = KernelResult.Success; + result = KernelResult.Success; } else { - Result = KernelResult.InvalidState; + result = KernelResult.InvalidState; } } System.CriticalSection.Leave(); - if (ShallTerminate) + if (shallTerminate) { //UnpauseAndTerminateAllThreadsExcept(System.Scheduler.GetCurrentThread()); @@ -930,10 +930,10 @@ namespace Ryujinx.HLE.HOS.Kernel SignalExit(); } - return Result; + return result; } - private void UnpauseAndTerminateAllThreadsExcept(KThread Thread) + private void UnpauseAndTerminateAllThreadsExcept(KThread thread) { //TODO. } @@ -959,38 +959,38 @@ namespace Ryujinx.HLE.HOS.Kernel public KernelResult ClearIfNotExited() { - KernelResult Result; + KernelResult result; System.CriticalSection.Enter(); - lock (ProcessLock) + lock (_processLock) { - if (State != ProcessState.Exited && Signaled) + if (_state != ProcessState.Exited && _signaled) { - Signaled = false; + _signaled = false; - Result = KernelResult.Success; + result = KernelResult.Success; } else { - Result = KernelResult.InvalidState; + result = KernelResult.InvalidState; } } System.CriticalSection.Leave(); - return Result; + return result; } public void StopAllThreads() { - lock (ThreadingLock) + lock (_threadingLock) { - foreach (KThread Thread in Threads) + foreach (KThread thread in _threads) { - Thread.Context.StopExecution(); + thread.Context.StopExecution(); - System.Scheduler.CoreManager.Set(Thread.Context.Work); + System.Scheduler.CoreManager.Set(thread.Context.Work); } } } diff --git a/Ryujinx.HLE/HOS/Kernel/KProcessCapabilities.cs b/Ryujinx.HLE/HOS/Kernel/KProcessCapabilities.cs index dfbe1f36..4dc8500c 100644 --- a/Ryujinx.HLE/HOS/Kernel/KProcessCapabilities.cs +++ b/Ryujinx.HLE/HOS/Kernel/KProcessCapabilities.cs @@ -21,91 +21,91 @@ namespace Ryujinx.HLE.HOS.Kernel IrqAccessMask = new byte[0x80]; } - public KernelResult InitializeForKernel(int[] Caps, KMemoryManager MemoryManager) + public KernelResult InitializeForKernel(int[] caps, KMemoryManager memoryManager) { AllowedCpuCoresMask = 0xf; AllowedThreadPriosMask = -1; DebuggingFlags &= ~3; KernelReleaseVersion = KProcess.KernelVersionPacked; - return Parse(Caps, MemoryManager); + return Parse(caps, memoryManager); } - public KernelResult InitializeForUser(int[] Caps, KMemoryManager MemoryManager) + public KernelResult InitializeForUser(int[] caps, KMemoryManager memoryManager) { - return Parse(Caps, MemoryManager); + return Parse(caps, memoryManager); } - private KernelResult Parse(int[] Caps, KMemoryManager MemoryManager) + private KernelResult Parse(int[] caps, KMemoryManager memoryManager) { - int Mask0 = 0; - int Mask1 = 0; + int mask0 = 0; + int mask1 = 0; - for (int Index = 0; Index < Caps.Length; Index++) + for (int index = 0; index < caps.Length; index++) { - int Cap = Caps[Index]; + int cap = caps[index]; - if (((Cap + 1) & ~Cap) != 0x40) + if (((cap + 1) & ~cap) != 0x40) { - KernelResult Result = ParseCapability(Cap, ref Mask0, ref Mask1, MemoryManager); + KernelResult result = ParseCapability(cap, ref mask0, ref mask1, memoryManager); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - return Result; + return result; } } else { - if ((uint)Index + 1 >= Caps.Length) + if ((uint)index + 1 >= caps.Length) { return KernelResult.InvalidCombination; } - int PrevCap = Cap; + int prevCap = cap; - Cap = Caps[++Index]; + cap = caps[++index]; - if (((Cap + 1) & ~Cap) != 0x40) + if (((cap + 1) & ~cap) != 0x40) { return KernelResult.InvalidCombination; } - if ((Cap & 0x78000000) != 0) + if ((cap & 0x78000000) != 0) { return KernelResult.MaximumExceeded; } - if ((Cap & 0x7ffff80) == 0) + if ((cap & 0x7ffff80) == 0) { return KernelResult.InvalidSize; } - long Address = ((long)(uint)PrevCap << 5) & 0xffffff000; - long Size = ((long)(uint)Cap << 5) & 0xfffff000; + long address = ((long)(uint)prevCap << 5) & 0xffffff000; + long size = ((long)(uint)cap << 5) & 0xfffff000; - if (((ulong)(Address + Size - 1) >> 36) != 0) + if (((ulong)(address + size - 1) >> 36) != 0) { return KernelResult.InvalidAddress; } - MemoryPermission Perm = (PrevCap >> 31) != 0 + MemoryPermission perm = (prevCap >> 31) != 0 ? MemoryPermission.Read : MemoryPermission.ReadAndWrite; - KernelResult Result; + KernelResult result; - if ((Cap >> 31) != 0) + if ((cap >> 31) != 0) { - Result = MemoryManager.MapNormalMemory(Address, Size, Perm); + result = memoryManager.MapNormalMemory(address, size, perm); } else { - Result = MemoryManager.MapIoMemory(Address, Size, Perm); + result = memoryManager.MapIoMemory(address, size, perm); } - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - return Result; + return result; } } } @@ -113,30 +113,30 @@ namespace Ryujinx.HLE.HOS.Kernel return KernelResult.Success; } - private KernelResult ParseCapability(int Cap, ref int Mask0, ref int Mask1, KMemoryManager MemoryManager) + private KernelResult ParseCapability(int cap, ref int mask0, ref int mask1, KMemoryManager memoryManager) { - int Code = (Cap + 1) & ~Cap; + int code = (cap + 1) & ~cap; - if (Code == 1) + if (code == 1) { return KernelResult.InvalidCapability; } - else if (Code == 0) + else if (code == 0) { return KernelResult.Success; } - int CodeMask = 1 << (32 - BitUtils.CountLeadingZeros32(Code + 1)); + int codeMask = 1 << (32 - BitUtils.CountLeadingZeros32(code + 1)); //Check if the property was already set. - if (((Mask0 & CodeMask) & 0x1e008) != 0) + if (((mask0 & codeMask) & 0x1e008) != 0) { return KernelResult.InvalidCombination; } - Mask0 |= CodeMask; + mask0 |= codeMask; - switch (Code) + switch (code) { case 8: { @@ -145,65 +145,65 @@ namespace Ryujinx.HLE.HOS.Kernel return KernelResult.InvalidCapability; } - int LowestCpuCore = (Cap >> 16) & 0xff; - int HighestCpuCore = (Cap >> 24) & 0xff; + int lowestCpuCore = (cap >> 16) & 0xff; + int highestCpuCore = (cap >> 24) & 0xff; - if (LowestCpuCore > HighestCpuCore) + if (lowestCpuCore > highestCpuCore) { return KernelResult.InvalidCombination; } - int HighestThreadPrio = (Cap >> 4) & 0x3f; - int LowestThreadPrio = (Cap >> 10) & 0x3f; + int highestThreadPrio = (cap >> 4) & 0x3f; + int lowestThreadPrio = (cap >> 10) & 0x3f; - if (LowestThreadPrio > HighestThreadPrio) + if (lowestThreadPrio > highestThreadPrio) { return KernelResult.InvalidCombination; } - if (HighestCpuCore >= KScheduler.CpuCoresCount) + if (highestCpuCore >= KScheduler.CpuCoresCount) { return KernelResult.InvalidCpuCore; } - AllowedCpuCoresMask = GetMaskFromMinMax(LowestCpuCore, HighestCpuCore); - AllowedThreadPriosMask = GetMaskFromMinMax(LowestThreadPrio, HighestThreadPrio); + AllowedCpuCoresMask = GetMaskFromMinMax(lowestCpuCore, highestCpuCore); + AllowedThreadPriosMask = GetMaskFromMinMax(lowestThreadPrio, highestThreadPrio); break; } case 0x10: { - int Slot = (Cap >> 29) & 7; + int slot = (cap >> 29) & 7; - int SvcSlotMask = 1 << Slot; + int svcSlotMask = 1 << slot; - if ((Mask1 & SvcSlotMask) != 0) + if ((mask1 & svcSlotMask) != 0) { return KernelResult.InvalidCombination; } - Mask1 |= SvcSlotMask; + mask1 |= svcSlotMask; - int SvcMask = (Cap >> 5) & 0xffffff; + int svcMask = (cap >> 5) & 0xffffff; - int BaseSvc = Slot * 24; + int baseSvc = slot * 24; - for (int Index = 0; Index < 24; Index++) + for (int index = 0; index < 24; index++) { - if (((SvcMask >> Index) & 1) == 0) + if (((svcMask >> index) & 1) == 0) { continue; } - int SvcId = BaseSvc + Index; + int svcId = baseSvc + index; - if (SvcId > 0x7f) + if (svcId > 0x7f) { return KernelResult.MaximumExceeded; } - SvcAccessMask[SvcId / 8] |= (byte)(1 << (SvcId & 7)); + SvcAccessMask[svcId / 8] |= (byte)(1 << (svcId & 7)); } break; @@ -211,9 +211,9 @@ namespace Ryujinx.HLE.HOS.Kernel case 0x80: { - long Address = ((long)(uint)Cap << 4) & 0xffffff000; + long address = ((long)(uint)cap << 4) & 0xffffff000; - MemoryManager.MapIoMemory(Address, KMemoryManager.PageSize, MemoryPermission.ReadAndWrite); + memoryManager.MapIoMemory(address, KMemoryManager.PageSize, MemoryPermission.ReadAndWrite); break; } @@ -221,17 +221,17 @@ namespace Ryujinx.HLE.HOS.Kernel case 0x800: { //TODO: GIC distributor check. - int Irq0 = (Cap >> 12) & 0x3ff; - int Irq1 = (Cap >> 22) & 0x3ff; + int irq0 = (cap >> 12) & 0x3ff; + int irq1 = (cap >> 22) & 0x3ff; - if (Irq0 != 0x3ff) + if (irq0 != 0x3ff) { - IrqAccessMask[Irq0 / 8] |= (byte)(1 << (Irq0 & 7)); + IrqAccessMask[irq0 / 8] |= (byte)(1 << (irq0 & 7)); } - if (Irq1 != 0x3ff) + if (irq1 != 0x3ff) { - IrqAccessMask[Irq1 / 8] |= (byte)(1 << (Irq1 & 7)); + IrqAccessMask[irq1 / 8] |= (byte)(1 << (irq1 & 7)); } break; @@ -239,14 +239,14 @@ namespace Ryujinx.HLE.HOS.Kernel case 0x2000: { - int ApplicationType = Cap >> 14; + int applicationType = cap >> 14; - if ((uint)ApplicationType > 7) + if ((uint)applicationType > 7) { return KernelResult.ReservedValue; } - this.ApplicationType = ApplicationType; + ApplicationType = applicationType; break; } @@ -254,41 +254,41 @@ namespace Ryujinx.HLE.HOS.Kernel case 0x4000: { //Note: This check is bugged on kernel too, we are just replicating the bug here. - if ((KernelReleaseVersion >> 17) != 0 || Cap < 0x80000) + if ((KernelReleaseVersion >> 17) != 0 || cap < 0x80000) { return KernelResult.ReservedValue; } - KernelReleaseVersion = Cap; + KernelReleaseVersion = cap; break; } case 0x8000: { - int HandleTableSize = Cap >> 26; + int handleTableSize = cap >> 26; - if ((uint)HandleTableSize > 0x3ff) + if ((uint)handleTableSize > 0x3ff) { return KernelResult.ReservedValue; } - this.HandleTableSize = HandleTableSize; + HandleTableSize = handleTableSize; break; } case 0x10000: { - int DebuggingFlags = Cap >> 19; + int debuggingFlags = cap >> 19; - if ((uint)DebuggingFlags > 3) + if ((uint)debuggingFlags > 3) { return KernelResult.ReservedValue; } - this.DebuggingFlags &= ~3; - this.DebuggingFlags |= DebuggingFlags; + DebuggingFlags &= ~3; + DebuggingFlags |= debuggingFlags; break; } @@ -299,13 +299,13 @@ namespace Ryujinx.HLE.HOS.Kernel return KernelResult.Success; } - private static long GetMaskFromMinMax(int Min, int Max) + private static long GetMaskFromMinMax(int min, int max) { - int Range = Max - Min + 1; + int range = max - min + 1; - long Mask = (1L << Range) - 1; + long mask = (1L << range) - 1; - return Mask << Min; + return mask << min; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/KReadableEvent.cs b/Ryujinx.HLE/HOS/Kernel/KReadableEvent.cs index bfb8e7e2..e1a3e63f 100644 --- a/Ryujinx.HLE/HOS/Kernel/KReadableEvent.cs +++ b/Ryujinx.HLE/HOS/Kernel/KReadableEvent.cs @@ -2,22 +2,22 @@ namespace Ryujinx.HLE.HOS.Kernel { class KReadableEvent : KSynchronizationObject { - private KEvent Parent; + private KEvent _parent; - private bool Signaled; + private bool _signaled; - public KReadableEvent(Horizon System, KEvent Parent) : base(System) + public KReadableEvent(Horizon system, KEvent parent) : base(system) { - this.Parent = Parent; + _parent = parent; } public override void Signal() { System.CriticalSection.Enter(); - if (!Signaled) + if (!_signaled) { - Signaled = true; + _signaled = true; base.Signal(); } @@ -27,36 +27,36 @@ namespace Ryujinx.HLE.HOS.Kernel public KernelResult Clear() { - Signaled = false; + _signaled = false; return KernelResult.Success; } public KernelResult ClearIfSignaled() { - KernelResult Result; + KernelResult result; System.CriticalSection.Enter(); - if (Signaled) + if (_signaled) { - Signaled = false; + _signaled = false; - Result = KernelResult.Success; + result = KernelResult.Success; } else { - Result = KernelResult.InvalidState; + result = KernelResult.InvalidState; } System.CriticalSection.Leave(); - return Result; + return result; } public override bool IsSignaled() { - return Signaled; + return _signaled; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/KResourceLimit.cs b/Ryujinx.HLE/HOS/Kernel/KResourceLimit.cs index 6fd70d0c..09c53e5b 100644 --- a/Ryujinx.HLE/HOS/Kernel/KResourceLimit.cs +++ b/Ryujinx.HLE/HOS/Kernel/KResourceLimit.cs @@ -7,127 +7,127 @@ namespace Ryujinx.HLE.HOS.Kernel { private const int Time10SecondsMs = 10000; - private long[] Current; - private long[] Limit; - private long[] Available; + private long[] _current; + private long[] _limit; + private long[] _available; - private object LockObj; + private object _lockObj; - private LinkedList WaitingThreads; + private LinkedList _waitingThreads; - private int WaitingThreadsCount; + private int _waitingThreadsCount; - private Horizon System; + private Horizon _system; - public KResourceLimit(Horizon System) + public KResourceLimit(Horizon system) { - Current = new long[(int)LimitableResource.Count]; - Limit = new long[(int)LimitableResource.Count]; - Available = new long[(int)LimitableResource.Count]; + _current = new long[(int)LimitableResource.Count]; + _limit = new long[(int)LimitableResource.Count]; + _available = new long[(int)LimitableResource.Count]; - LockObj = new object(); + _lockObj = new object(); - WaitingThreads = new LinkedList(); + _waitingThreads = new LinkedList(); - this.System = System; + _system = system; } - public bool Reserve(LimitableResource Resource, ulong Amount) + public bool Reserve(LimitableResource resource, ulong amount) { - return Reserve(Resource, (long)Amount); + return Reserve(resource, (long)amount); } - public bool Reserve(LimitableResource Resource, long Amount) + public bool Reserve(LimitableResource resource, long amount) { - return Reserve(Resource, Amount, KTimeManager.ConvertMillisecondsToNanoseconds(Time10SecondsMs)); + return Reserve(resource, amount, KTimeManager.ConvertMillisecondsToNanoseconds(Time10SecondsMs)); } - public bool Reserve(LimitableResource Resource, long Amount, long Timeout) + public bool Reserve(LimitableResource resource, long amount, long timeout) { - long EndTimePoint = KTimeManager.ConvertNanosecondsToMilliseconds(Timeout); + long endTimePoint = KTimeManager.ConvertNanosecondsToMilliseconds(timeout); - EndTimePoint += PerformanceCounter.ElapsedMilliseconds; + endTimePoint += PerformanceCounter.ElapsedMilliseconds; - bool Success = false; + bool success = false; - int Index = GetIndex(Resource); + int index = GetIndex(resource); - lock (LockObj) + lock (_lockObj) { - long NewCurrent = Current[Index] + Amount; + long newCurrent = _current[index] + amount; - while (NewCurrent > Limit[Index] && Available[Index] + Amount <= Limit[Index]) + while (newCurrent > _limit[index] && _available[index] + amount <= _limit[index]) { - WaitingThreadsCount++; + _waitingThreadsCount++; - KConditionVariable.Wait(System, WaitingThreads, LockObj, Timeout); + KConditionVariable.Wait(_system, _waitingThreads, _lockObj, timeout); - WaitingThreadsCount--; + _waitingThreadsCount--; - NewCurrent = Current[Index] + Amount; + newCurrent = _current[index] + amount; - if (Timeout >= 0 && PerformanceCounter.ElapsedMilliseconds > EndTimePoint) + if (timeout >= 0 && PerformanceCounter.ElapsedMilliseconds > endTimePoint) { break; } } - if (NewCurrent <= Limit[Index]) + if (newCurrent <= _limit[index]) { - Current[Index] = NewCurrent; + _current[index] = newCurrent; - Success = true; + success = true; } } - return Success; + return success; } - public void Release(LimitableResource Resource, ulong Amount) + public void Release(LimitableResource resource, ulong amount) { - Release(Resource, (long)Amount); + Release(resource, (long)amount); } - public void Release(LimitableResource Resource, long Amount) + public void Release(LimitableResource resource, long amount) { - Release(Resource, Amount, Amount); + Release(resource, amount, amount); } - private void Release(LimitableResource Resource, long UsedAmount, long AvailableAmount) + private void Release(LimitableResource resource, long usedAmount, long availableAmount) { - int Index = GetIndex(Resource); + int index = GetIndex(resource); - lock (LockObj) + lock (_lockObj) { - Current [Index] -= UsedAmount; - Available[Index] -= AvailableAmount; + _current [index] -= usedAmount; + _available[index] -= availableAmount; - if (WaitingThreadsCount > 0) + if (_waitingThreadsCount > 0) { - KConditionVariable.NotifyAll(System, WaitingThreads); + KConditionVariable.NotifyAll(_system, _waitingThreads); } } } - public long GetRemainingValue(LimitableResource Resource) + public long GetRemainingValue(LimitableResource resource) { - int Index = GetIndex(Resource); + int index = GetIndex(resource); - lock (LockObj) + lock (_lockObj) { - return Limit[Index] - Current[Index]; + return _limit[index] - _current[index]; } } - public KernelResult SetLimitValue(LimitableResource Resource, long Limit) + public KernelResult SetLimitValue(LimitableResource resource, long limit) { - int Index = GetIndex(Resource); + int index = GetIndex(resource); - lock (LockObj) + lock (_lockObj) { - if (Current[Index] <= Limit) + if (_current[index] <= limit) { - this.Limit[Index] = Limit; + _limit[index] = limit; return KernelResult.Success; } @@ -138,9 +138,9 @@ namespace Ryujinx.HLE.HOS.Kernel } } - private static int GetIndex(LimitableResource Resource) + private static int GetIndex(LimitableResource resource) { - return (int)Resource; + return (int)resource; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/KScheduler.cs b/Ryujinx.HLE/HOS/Kernel/KScheduler.cs index 3342f4a6..f85b9e8c 100644 --- a/Ryujinx.HLE/HOS/Kernel/KScheduler.cs +++ b/Ryujinx.HLE/HOS/Kernel/KScheduler.cs @@ -12,7 +12,7 @@ namespace Ryujinx.HLE.HOS.Kernel private const int PreemptionPriorityCores012 = 59; private const int PreemptionPriorityCore3 = 63; - private Horizon System; + private Horizon _system; public KSchedulingData SchedulingData { get; private set; } @@ -20,9 +20,9 @@ namespace Ryujinx.HLE.HOS.Kernel public bool ThreadReselectionRequested { get; set; } - public KScheduler(Horizon System) + public KScheduler(Horizon system) { - this.System = System; + _system = system; SchedulingData = new KSchedulingData(); @@ -30,87 +30,87 @@ namespace Ryujinx.HLE.HOS.Kernel CoreContexts = new KCoreContext[CpuCoresCount]; - for (int Core = 0; Core < CpuCoresCount; Core++) + for (int core = 0; core < CpuCoresCount; core++) { - CoreContexts[Core] = new KCoreContext(this, CoreManager); + CoreContexts[core] = new KCoreContext(this, CoreManager); } } private void PreemptThreads() { - System.CriticalSection.Enter(); + _system.CriticalSection.Enter(); PreemptThread(PreemptionPriorityCores012, 0); PreemptThread(PreemptionPriorityCores012, 1); PreemptThread(PreemptionPriorityCores012, 2); PreemptThread(PreemptionPriorityCore3, 3); - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); } - private void PreemptThread(int Prio, int Core) + private void PreemptThread(int prio, int core) { - IEnumerable ScheduledThreads = SchedulingData.ScheduledThreads(Core); + IEnumerable scheduledThreads = SchedulingData.ScheduledThreads(core); - KThread SelectedThread = ScheduledThreads.FirstOrDefault(x => x.DynamicPriority == Prio); + KThread selectedThread = scheduledThreads.FirstOrDefault(x => x.DynamicPriority == prio); //Yield priority queue. - if (SelectedThread != null) + if (selectedThread != null) { - SchedulingData.Reschedule(Prio, Core, SelectedThread); + SchedulingData.Reschedule(prio, core, selectedThread); } IEnumerable SuitableCandidates() { - foreach (KThread Thread in SchedulingData.SuggestedThreads(Core)) + foreach (KThread thread in SchedulingData.SuggestedThreads(core)) { - int SrcCore = Thread.CurrentCore; + int srcCore = thread.CurrentCore; - if (SrcCore >= 0) + if (srcCore >= 0) { - KThread HighestPrioSrcCore = SchedulingData.ScheduledThreads(SrcCore).FirstOrDefault(); + KThread highestPrioSrcCore = SchedulingData.ScheduledThreads(srcCore).FirstOrDefault(); - if (HighestPrioSrcCore != null && HighestPrioSrcCore.DynamicPriority < 2) + if (highestPrioSrcCore != null && highestPrioSrcCore.DynamicPriority < 2) { break; } - if (HighestPrioSrcCore == Thread) + if (highestPrioSrcCore == thread) { continue; } } //If the candidate was scheduled after the current thread, then it's not worth it. - if (SelectedThread == null || SelectedThread.LastScheduledTime >= Thread.LastScheduledTime) + if (selectedThread == null || selectedThread.LastScheduledTime >= thread.LastScheduledTime) { - yield return Thread; + yield return thread; } } } //Select candidate threads that could run on this core. //Only take into account threads that are not yet selected. - KThread Dst = SuitableCandidates().FirstOrDefault(x => x.DynamicPriority == Prio); + KThread dst = SuitableCandidates().FirstOrDefault(x => x.DynamicPriority == prio); - if (Dst != null) + if (dst != null) { - SchedulingData.TransferToCore(Prio, Core, Dst); + SchedulingData.TransferToCore(prio, core, dst); - SelectedThread = Dst; + selectedThread = dst; } //If the priority of the currently selected thread is lower than preemption priority, //then allow threads with lower priorities to be selected aswell. - if (SelectedThread != null && SelectedThread.DynamicPriority > Prio) + if (selectedThread != null && selectedThread.DynamicPriority > prio) { - Func Predicate = x => x.DynamicPriority >= SelectedThread.DynamicPriority; + Func predicate = x => x.DynamicPriority >= selectedThread.DynamicPriority; - Dst = SuitableCandidates().FirstOrDefault(Predicate); + dst = SuitableCandidates().FirstOrDefault(predicate); - if (Dst != null) + if (dst != null) { - SchedulingData.TransferToCore(Dst.DynamicPriority, Core, Dst); + SchedulingData.TransferToCore(dst.DynamicPriority, core, dst); } } @@ -121,52 +121,52 @@ namespace Ryujinx.HLE.HOS.Kernel { ThreadReselectionRequested = false; - for (int Core = 0; Core < CpuCoresCount; Core++) + for (int core = 0; core < CpuCoresCount; core++) { - KThread Thread = SchedulingData.ScheduledThreads(Core).FirstOrDefault(); + KThread thread = SchedulingData.ScheduledThreads(core).FirstOrDefault(); - CoreContexts[Core].SelectThread(Thread); + CoreContexts[core].SelectThread(thread); } - for (int Core = 0; Core < CpuCoresCount; Core++) + for (int core = 0; core < CpuCoresCount; core++) { //If the core is not idle (there's already a thread running on it), //then we don't need to attempt load balancing. - if (SchedulingData.ScheduledThreads(Core).Any()) + if (SchedulingData.ScheduledThreads(core).Any()) { continue; } - int[] SrcCoresHighestPrioThreads = new int[CpuCoresCount]; + int[] srcCoresHighestPrioThreads = new int[CpuCoresCount]; - int SrcCoresHighestPrioThreadsCount = 0; + int srcCoresHighestPrioThreadsCount = 0; - KThread Dst = null; + KThread dst = null; //Select candidate threads that could run on this core. //Give preference to threads that are not yet selected. - foreach (KThread Thread in SchedulingData.SuggestedThreads(Core)) + foreach (KThread thread in SchedulingData.SuggestedThreads(core)) { - if (Thread.CurrentCore < 0 || Thread != CoreContexts[Thread.CurrentCore].SelectedThread) + if (thread.CurrentCore < 0 || thread != CoreContexts[thread.CurrentCore].SelectedThread) { - Dst = Thread; + dst = thread; break; } - SrcCoresHighestPrioThreads[SrcCoresHighestPrioThreadsCount++] = Thread.CurrentCore; + srcCoresHighestPrioThreads[srcCoresHighestPrioThreadsCount++] = thread.CurrentCore; } //Not yet selected candidate found. - if (Dst != null) + if (dst != null) { //Priorities < 2 are used for the kernel message dispatching //threads, we should skip load balancing entirely. - if (Dst.DynamicPriority >= 2) + if (dst.DynamicPriority >= 2) { - SchedulingData.TransferToCore(Dst.DynamicPriority, Core, Dst); + SchedulingData.TransferToCore(dst.DynamicPriority, core, dst); - CoreContexts[Core].SelectThread(Dst); + CoreContexts[core].SelectThread(dst); } continue; @@ -174,23 +174,23 @@ namespace Ryujinx.HLE.HOS.Kernel //All candiates are already selected, choose the best one //(the first one that doesn't make the source core idle if moved). - for (int Index = 0; Index < SrcCoresHighestPrioThreadsCount; Index++) + for (int index = 0; index < srcCoresHighestPrioThreadsCount; index++) { - int SrcCore = SrcCoresHighestPrioThreads[Index]; + int srcCore = srcCoresHighestPrioThreads[index]; - KThread Src = SchedulingData.ScheduledThreads(SrcCore).ElementAtOrDefault(1); + KThread src = SchedulingData.ScheduledThreads(srcCore).ElementAtOrDefault(1); - if (Src != null) + if (src != null) { //Run the second thread on the queue on the source core, //move the first one to the current core. - KThread OrigSelectedCoreSrc = CoreContexts[SrcCore].SelectedThread; + KThread origSelectedCoreSrc = CoreContexts[srcCore].SelectedThread; - CoreContexts[SrcCore].SelectThread(Src); + CoreContexts[srcCore].SelectThread(src); - SchedulingData.TransferToCore(OrigSelectedCoreSrc.DynamicPriority, Core, OrigSelectedCoreSrc); + SchedulingData.TransferToCore(origSelectedCoreSrc.DynamicPriority, core, origSelectedCoreSrc); - CoreContexts[Core].SelectThread(OrigSelectedCoreSrc); + CoreContexts[core].SelectThread(origSelectedCoreSrc); } } } @@ -200,11 +200,11 @@ namespace Ryujinx.HLE.HOS.Kernel { lock (CoreContexts) { - for (int Core = 0; Core < CpuCoresCount; Core++) + for (int core = 0; core < CpuCoresCount; core++) { - if (CoreContexts[Core].CurrentThread?.Context.IsCurrentThread() ?? false) + if (CoreContexts[core].CurrentThread?.Context.IsCurrentThread() ?? false) { - return CoreContexts[Core].CurrentThread; + return CoreContexts[core].CurrentThread; } } } @@ -222,11 +222,11 @@ namespace Ryujinx.HLE.HOS.Kernel Dispose(true); } - protected virtual void Dispose(bool Disposing) + protected virtual void Dispose(bool disposing) { - if (Disposing) + if (disposing) { - KeepPreempting = false; + _keepPreempting = false; } } } diff --git a/Ryujinx.HLE/HOS/Kernel/KSchedulingData.cs b/Ryujinx.HLE/HOS/Kernel/KSchedulingData.cs index ba2730a2..65116036 100644 --- a/Ryujinx.HLE/HOS/Kernel/KSchedulingData.cs +++ b/Ryujinx.HLE/HOS/Kernel/KSchedulingData.cs @@ -4,204 +4,204 @@ namespace Ryujinx.HLE.HOS.Kernel { class KSchedulingData { - private LinkedList[][] ScheduledThreadsPerPrioPerCore; - private LinkedList[][] SuggestedThreadsPerPrioPerCore; + private LinkedList[][] _scheduledThreadsPerPrioPerCore; + private LinkedList[][] _suggestedThreadsPerPrioPerCore; - private long[] ScheduledPrioritiesPerCore; - private long[] SuggestedPrioritiesPerCore; + private long[] _scheduledPrioritiesPerCore; + private long[] _suggestedPrioritiesPerCore; public KSchedulingData() { - SuggestedThreadsPerPrioPerCore = new LinkedList[KScheduler.PrioritiesCount][]; - ScheduledThreadsPerPrioPerCore = new LinkedList[KScheduler.PrioritiesCount][]; + _suggestedThreadsPerPrioPerCore = new LinkedList[KScheduler.PrioritiesCount][]; + _scheduledThreadsPerPrioPerCore = new LinkedList[KScheduler.PrioritiesCount][]; - for (int Prio = 0; Prio < KScheduler.PrioritiesCount; Prio++) + for (int prio = 0; prio < KScheduler.PrioritiesCount; prio++) { - SuggestedThreadsPerPrioPerCore[Prio] = new LinkedList[KScheduler.CpuCoresCount]; - ScheduledThreadsPerPrioPerCore[Prio] = new LinkedList[KScheduler.CpuCoresCount]; + _suggestedThreadsPerPrioPerCore[prio] = new LinkedList[KScheduler.CpuCoresCount]; + _scheduledThreadsPerPrioPerCore[prio] = new LinkedList[KScheduler.CpuCoresCount]; - for (int Core = 0; Core < KScheduler.CpuCoresCount; Core++) + for (int core = 0; core < KScheduler.CpuCoresCount; core++) { - SuggestedThreadsPerPrioPerCore[Prio][Core] = new LinkedList(); - ScheduledThreadsPerPrioPerCore[Prio][Core] = new LinkedList(); + _suggestedThreadsPerPrioPerCore[prio][core] = new LinkedList(); + _scheduledThreadsPerPrioPerCore[prio][core] = new LinkedList(); } } - ScheduledPrioritiesPerCore = new long[KScheduler.CpuCoresCount]; - SuggestedPrioritiesPerCore = new long[KScheduler.CpuCoresCount]; + _scheduledPrioritiesPerCore = new long[KScheduler.CpuCoresCount]; + _suggestedPrioritiesPerCore = new long[KScheduler.CpuCoresCount]; } - public IEnumerable SuggestedThreads(int Core) + public IEnumerable SuggestedThreads(int core) { - return Iterate(SuggestedThreadsPerPrioPerCore, SuggestedPrioritiesPerCore, Core); + return Iterate(_suggestedThreadsPerPrioPerCore, _suggestedPrioritiesPerCore, core); } - public IEnumerable ScheduledThreads(int Core) + public IEnumerable ScheduledThreads(int core) { - return Iterate(ScheduledThreadsPerPrioPerCore, ScheduledPrioritiesPerCore, Core); + return Iterate(_scheduledThreadsPerPrioPerCore, _scheduledPrioritiesPerCore, core); } - private IEnumerable Iterate(LinkedList[][] ListPerPrioPerCore, long[] Prios, int Core) + private IEnumerable Iterate(LinkedList[][] listPerPrioPerCore, long[] prios, int core) { - long PrioMask = Prios[Core]; + long prioMask = prios[core]; - int Prio = CountTrailingZeros(PrioMask); + int prio = CountTrailingZeros(prioMask); - PrioMask &= ~(1L << Prio); + prioMask &= ~(1L << prio); - while (Prio < KScheduler.PrioritiesCount) + while (prio < KScheduler.PrioritiesCount) { - LinkedList List = ListPerPrioPerCore[Prio][Core]; + LinkedList list = listPerPrioPerCore[prio][core]; - LinkedListNode Node = List.First; + LinkedListNode node = list.First; - while (Node != null) + while (node != null) { - yield return Node.Value; + yield return node.Value; - Node = Node.Next; + node = node.Next; } - Prio = CountTrailingZeros(PrioMask); + prio = CountTrailingZeros(prioMask); - PrioMask &= ~(1L << Prio); + prioMask &= ~(1L << prio); } } - private int CountTrailingZeros(long Value) + private int CountTrailingZeros(long value) { - int Count = 0; + int count = 0; - while (((Value >> Count) & 0xf) == 0 && Count < 64) + while (((value >> count) & 0xf) == 0 && count < 64) { - Count += 4; + count += 4; } - while (((Value >> Count) & 1) == 0 && Count < 64) + while (((value >> count) & 1) == 0 && count < 64) { - Count++; + count++; } - return Count; + return count; } - public void TransferToCore(int Prio, int DstCore, KThread Thread) + public void TransferToCore(int prio, int dstCore, KThread thread) { - bool Schedulable = Thread.DynamicPriority < KScheduler.PrioritiesCount; + bool schedulable = thread.DynamicPriority < KScheduler.PrioritiesCount; - int SrcCore = Thread.CurrentCore; + int srcCore = thread.CurrentCore; - Thread.CurrentCore = DstCore; + thread.CurrentCore = dstCore; - if (SrcCore == DstCore || !Schedulable) + if (srcCore == dstCore || !schedulable) { return; } - if (SrcCore >= 0) + if (srcCore >= 0) { - Unschedule(Prio, SrcCore, Thread); + Unschedule(prio, srcCore, thread); } - if (DstCore >= 0) + if (dstCore >= 0) { - Unsuggest(Prio, DstCore, Thread); - Schedule(Prio, DstCore, Thread); + Unsuggest(prio, dstCore, thread); + Schedule(prio, dstCore, thread); } - if (SrcCore >= 0) + if (srcCore >= 0) { - Suggest(Prio, SrcCore, Thread); + Suggest(prio, srcCore, thread); } } - public void Suggest(int Prio, int Core, KThread Thread) + public void Suggest(int prio, int core, KThread thread) { - if (Prio >= KScheduler.PrioritiesCount) + if (prio >= KScheduler.PrioritiesCount) { return; } - Thread.SiblingsPerCore[Core] = SuggestedQueue(Prio, Core).AddFirst(Thread); + thread.SiblingsPerCore[core] = SuggestedQueue(prio, core).AddFirst(thread); - SuggestedPrioritiesPerCore[Core] |= 1L << Prio; + _suggestedPrioritiesPerCore[core] |= 1L << prio; } - public void Unsuggest(int Prio, int Core, KThread Thread) + public void Unsuggest(int prio, int core, KThread thread) { - if (Prio >= KScheduler.PrioritiesCount) + if (prio >= KScheduler.PrioritiesCount) { return; } - LinkedList Queue = SuggestedQueue(Prio, Core); + LinkedList queue = SuggestedQueue(prio, core); - Queue.Remove(Thread.SiblingsPerCore[Core]); + queue.Remove(thread.SiblingsPerCore[core]); - if (Queue.First == null) + if (queue.First == null) { - SuggestedPrioritiesPerCore[Core] &= ~(1L << Prio); + _suggestedPrioritiesPerCore[core] &= ~(1L << prio); } } - public void Schedule(int Prio, int Core, KThread Thread) + public void Schedule(int prio, int core, KThread thread) { - if (Prio >= KScheduler.PrioritiesCount) + if (prio >= KScheduler.PrioritiesCount) { return; } - Thread.SiblingsPerCore[Core] = ScheduledQueue(Prio, Core).AddLast(Thread); + thread.SiblingsPerCore[core] = ScheduledQueue(prio, core).AddLast(thread); - ScheduledPrioritiesPerCore[Core] |= 1L << Prio; + _scheduledPrioritiesPerCore[core] |= 1L << prio; } - public void SchedulePrepend(int Prio, int Core, KThread Thread) + public void SchedulePrepend(int prio, int core, KThread thread) { - if (Prio >= KScheduler.PrioritiesCount) + if (prio >= KScheduler.PrioritiesCount) { return; } - Thread.SiblingsPerCore[Core] = ScheduledQueue(Prio, Core).AddFirst(Thread); + thread.SiblingsPerCore[core] = ScheduledQueue(prio, core).AddFirst(thread); - ScheduledPrioritiesPerCore[Core] |= 1L << Prio; + _scheduledPrioritiesPerCore[core] |= 1L << prio; } - public void Reschedule(int Prio, int Core, KThread Thread) + public void Reschedule(int prio, int core, KThread thread) { - LinkedList Queue = ScheduledQueue(Prio, Core); + LinkedList queue = ScheduledQueue(prio, core); - Queue.Remove(Thread.SiblingsPerCore[Core]); + queue.Remove(thread.SiblingsPerCore[core]); - Thread.SiblingsPerCore[Core] = Queue.AddLast(Thread); + thread.SiblingsPerCore[core] = queue.AddLast(thread); } - public void Unschedule(int Prio, int Core, KThread Thread) + public void Unschedule(int prio, int core, KThread thread) { - if (Prio >= KScheduler.PrioritiesCount) + if (prio >= KScheduler.PrioritiesCount) { return; } - LinkedList Queue = ScheduledQueue(Prio, Core); + LinkedList queue = ScheduledQueue(prio, core); - Queue.Remove(Thread.SiblingsPerCore[Core]); + queue.Remove(thread.SiblingsPerCore[core]); - if (Queue.First == null) + if (queue.First == null) { - ScheduledPrioritiesPerCore[Core] &= ~(1L << Prio); + _scheduledPrioritiesPerCore[core] &= ~(1L << prio); } } - private LinkedList SuggestedQueue(int Prio, int Core) + private LinkedList SuggestedQueue(int prio, int core) { - return SuggestedThreadsPerPrioPerCore[Prio][Core]; + return _suggestedThreadsPerPrioPerCore[prio][core]; } - private LinkedList ScheduledQueue(int Prio, int Core) + private LinkedList ScheduledQueue(int prio, int core) { - return ScheduledThreadsPerPrioPerCore[Prio][Core]; + return _scheduledThreadsPerPrioPerCore[prio][core]; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/KServerPort.cs b/Ryujinx.HLE/HOS/Kernel/KServerPort.cs index 42135cd8..0aa74e48 100644 --- a/Ryujinx.HLE/HOS/Kernel/KServerPort.cs +++ b/Ryujinx.HLE/HOS/Kernel/KServerPort.cs @@ -2,13 +2,13 @@ namespace Ryujinx.HLE.HOS.Kernel { class KServerPort : KSynchronizationObject { - private KPort Parent; + private KPort _parent; - public KServerPort(Horizon System) : base(System) { } + public KServerPort(Horizon system) : base(system) { } - public void Initialize(KPort Parent) + public void Initialize(KPort parent) { - this.Parent = Parent; + _parent = parent; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/KSession.cs b/Ryujinx.HLE/HOS/Kernel/KSession.cs index 4b21d3a6..361a7479 100644 --- a/Ryujinx.HLE/HOS/Kernel/KSession.cs +++ b/Ryujinx.HLE/HOS/Kernel/KSession.cs @@ -9,10 +9,10 @@ namespace Ryujinx.HLE.HOS.Kernel public string ServiceName { get; private set; } - public KSession(IpcService Service, string ServiceName) + public KSession(IpcService service, string serviceName) { - this.Service = Service; - this.ServiceName = ServiceName; + Service = service; + ServiceName = serviceName; } public void Dispose() @@ -20,11 +20,11 @@ namespace Ryujinx.HLE.HOS.Kernel Dispose(true); } - protected virtual void Dispose(bool Disposing) + protected virtual void Dispose(bool disposing) { - if (Disposing && Service is IDisposable DisposableService) + if (disposing && Service is IDisposable disposableService) { - DisposableService.Dispose(); + disposableService.Dispose(); } } } diff --git a/Ryujinx.HLE/HOS/Kernel/KSharedMemory.cs b/Ryujinx.HLE/HOS/Kernel/KSharedMemory.cs index a440438b..0e9f8840 100644 --- a/Ryujinx.HLE/HOS/Kernel/KSharedMemory.cs +++ b/Ryujinx.HLE/HOS/Kernel/KSharedMemory.cs @@ -4,65 +4,65 @@ namespace Ryujinx.HLE.HOS.Kernel { class KSharedMemory { - private KPageList PageList; + private KPageList _pageList; - private long OwnerPid; + private long _ownerPid; - private MemoryPermission OwnerPermission; - private MemoryPermission UserPermission; + private MemoryPermission _ownerPermission; + private MemoryPermission _userPermission; public KSharedMemory( - KPageList PageList, - long OwnerPid, - MemoryPermission OwnerPermission, - MemoryPermission UserPermission) + KPageList pageList, + long ownerPid, + MemoryPermission ownerPermission, + MemoryPermission userPermission) { - this.PageList = PageList; - this.OwnerPid = OwnerPid; - this.OwnerPermission = OwnerPermission; - this.UserPermission = UserPermission; + _pageList = pageList; + _ownerPid = ownerPid; + _ownerPermission = ownerPermission; + _userPermission = userPermission; } public KernelResult MapIntoProcess( - KMemoryManager MemoryManager, - ulong Address, - ulong Size, - KProcess Process, - MemoryPermission Permission) + KMemoryManager memoryManager, + ulong address, + ulong size, + KProcess process, + MemoryPermission permission) { - ulong PagesCountRounded = BitUtils.DivRoundUp(Size, KMemoryManager.PageSize); + ulong pagesCountRounded = BitUtils.DivRoundUp(size, KMemoryManager.PageSize); - if (PageList.GetPagesCount() != PagesCountRounded) + if (_pageList.GetPagesCount() != pagesCountRounded) { return KernelResult.InvalidSize; } - MemoryPermission ExpectedPermission = Process.Pid == OwnerPid - ? OwnerPermission - : UserPermission; + MemoryPermission expectedPermission = process.Pid == _ownerPid + ? _ownerPermission + : _userPermission; - if (Permission != ExpectedPermission) + if (permission != expectedPermission) { return KernelResult.InvalidPermission; } - return MemoryManager.MapPages(Address, PageList, MemoryState.SharedMemory, Permission); + return memoryManager.MapPages(address, _pageList, MemoryState.SharedMemory, permission); } public KernelResult UnmapFromProcess( - KMemoryManager MemoryManager, - ulong Address, - ulong Size, - KProcess Process) + KMemoryManager memoryManager, + ulong address, + ulong size, + KProcess process) { - ulong PagesCountRounded = BitUtils.DivRoundUp(Size, KMemoryManager.PageSize); + ulong pagesCountRounded = BitUtils.DivRoundUp(size, KMemoryManager.PageSize); - if (PageList.GetPagesCount() != PagesCountRounded) + if (_pageList.GetPagesCount() != pagesCountRounded) { return KernelResult.InvalidSize; } - return MemoryManager.UnmapPages(Address, PageList, MemoryState.SharedMemory); + return memoryManager.UnmapPages(address, _pageList, MemoryState.SharedMemory); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/KSlabHeap.cs b/Ryujinx.HLE/HOS/Kernel/KSlabHeap.cs index 2d6b3ca0..84c4dc01 100644 --- a/Ryujinx.HLE/HOS/Kernel/KSlabHeap.cs +++ b/Ryujinx.HLE/HOS/Kernel/KSlabHeap.cs @@ -4,46 +4,46 @@ namespace Ryujinx.HLE.HOS.Kernel { class KSlabHeap { - private LinkedList Items; + private LinkedList _items; - public KSlabHeap(ulong Pa, ulong ItemSize, ulong Size) + public KSlabHeap(ulong pa, ulong itemSize, ulong size) { - Items = new LinkedList(); + _items = new LinkedList(); - int ItemsCount = (int)(Size / ItemSize); + int itemsCount = (int)(size / itemSize); - for (int Index = 0; Index < ItemsCount; Index++) + for (int index = 0; index < itemsCount; index++) { - Items.AddLast(Pa); + _items.AddLast(pa); - Pa += ItemSize; + pa += itemSize; } } - public bool TryGetItem(out ulong Pa) + public bool TryGetItem(out ulong pa) { - lock (Items) + lock (_items) { - if (Items.First != null) + if (_items.First != null) { - Pa = Items.First.Value; + pa = _items.First.Value; - Items.RemoveFirst(); + _items.RemoveFirst(); return true; } } - Pa = 0; + pa = 0; return false; } - public void Free(ulong Pa) + public void Free(ulong pa) { - lock (Items) + lock (_items) { - Items.AddFirst(Pa); + _items.AddFirst(pa); } } } diff --git a/Ryujinx.HLE/HOS/Kernel/KSynchronization.cs b/Ryujinx.HLE/HOS/Kernel/KSynchronization.cs index 19e700f4..51b74a03 100644 --- a/Ryujinx.HLE/HOS/Kernel/KSynchronization.cs +++ b/Ryujinx.HLE/HOS/Kernel/KSynchronization.cs @@ -6,130 +6,130 @@ namespace Ryujinx.HLE.HOS.Kernel { class KSynchronization { - private Horizon System; + private Horizon _system; - public KSynchronization(Horizon System) + public KSynchronization(Horizon system) { - this.System = System; + _system = system; } - public long WaitFor(KSynchronizationObject[] SyncObjs, long Timeout, ref int HndIndex) + public long WaitFor(KSynchronizationObject[] syncObjs, long timeout, ref int hndIndex) { - long Result = MakeError(ErrorModule.Kernel, KernelErr.Timeout); + long result = MakeError(ErrorModule.Kernel, KernelErr.Timeout); - System.CriticalSection.Enter(); + _system.CriticalSection.Enter(); //Check if objects are already signaled before waiting. - for (int Index = 0; Index < SyncObjs.Length; Index++) + for (int index = 0; index < syncObjs.Length; index++) { - if (!SyncObjs[Index].IsSignaled()) + if (!syncObjs[index].IsSignaled()) { continue; } - HndIndex = Index; + hndIndex = index; - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); return 0; } - if (Timeout == 0) + if (timeout == 0) { - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); - return Result; + return result; } - KThread CurrentThread = System.Scheduler.GetCurrentThread(); + KThread currentThread = _system.Scheduler.GetCurrentThread(); - if (CurrentThread.ShallBeTerminated || - CurrentThread.SchedFlags == ThreadSchedState.TerminationPending) + if (currentThread.ShallBeTerminated || + currentThread.SchedFlags == ThreadSchedState.TerminationPending) { - Result = MakeError(ErrorModule.Kernel, KernelErr.ThreadTerminating); + result = MakeError(ErrorModule.Kernel, KernelErr.ThreadTerminating); } - else if (CurrentThread.SyncCancelled) + else if (currentThread.SyncCancelled) { - CurrentThread.SyncCancelled = false; + currentThread.SyncCancelled = false; - Result = MakeError(ErrorModule.Kernel, KernelErr.Cancelled); + result = MakeError(ErrorModule.Kernel, KernelErr.Cancelled); } else { - LinkedListNode[] SyncNodes = new LinkedListNode[SyncObjs.Length]; + LinkedListNode[] syncNodes = new LinkedListNode[syncObjs.Length]; - for (int Index = 0; Index < SyncObjs.Length; Index++) + for (int index = 0; index < syncObjs.Length; index++) { - SyncNodes[Index] = SyncObjs[Index].AddWaitingThread(CurrentThread); + syncNodes[index] = syncObjs[index].AddWaitingThread(currentThread); } - CurrentThread.WaitingSync = true; - CurrentThread.SignaledObj = null; - CurrentThread.ObjSyncResult = (int)Result; + currentThread.WaitingSync = true; + currentThread.SignaledObj = null; + currentThread.ObjSyncResult = (int)result; - CurrentThread.Reschedule(ThreadSchedState.Paused); + currentThread.Reschedule(ThreadSchedState.Paused); - if (Timeout > 0) + if (timeout > 0) { - System.TimeManager.ScheduleFutureInvocation(CurrentThread, Timeout); + _system.TimeManager.ScheduleFutureInvocation(currentThread, timeout); } - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); - CurrentThread.WaitingSync = false; + currentThread.WaitingSync = false; - if (Timeout > 0) + if (timeout > 0) { - System.TimeManager.UnscheduleFutureInvocation(CurrentThread); + _system.TimeManager.UnscheduleFutureInvocation(currentThread); } - System.CriticalSection.Enter(); + _system.CriticalSection.Enter(); - Result = (uint)CurrentThread.ObjSyncResult; + result = (uint)currentThread.ObjSyncResult; - HndIndex = -1; + hndIndex = -1; - for (int Index = 0; Index < SyncObjs.Length; Index++) + for (int index = 0; index < syncObjs.Length; index++) { - SyncObjs[Index].RemoveWaitingThread(SyncNodes[Index]); + syncObjs[index].RemoveWaitingThread(syncNodes[index]); - if (SyncObjs[Index] == CurrentThread.SignaledObj) + if (syncObjs[index] == currentThread.SignaledObj) { - HndIndex = Index; + hndIndex = index; } } } - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); - return Result; + return result; } - public void SignalObject(KSynchronizationObject SyncObj) + public void SignalObject(KSynchronizationObject syncObj) { - System.CriticalSection.Enter(); + _system.CriticalSection.Enter(); - if (SyncObj.IsSignaled()) + if (syncObj.IsSignaled()) { - LinkedListNode Node = SyncObj.WaitingThreads.First; + LinkedListNode node = syncObj.WaitingThreads.First; - while (Node != null) + while (node != null) { - KThread Thread = Node.Value; + KThread thread = node.Value; - if ((Thread.SchedFlags & ThreadSchedState.LowMask) == ThreadSchedState.Paused) + if ((thread.SchedFlags & ThreadSchedState.LowMask) == ThreadSchedState.Paused) { - Thread.SignaledObj = SyncObj; - Thread.ObjSyncResult = 0; + thread.SignaledObj = syncObj; + thread.ObjSyncResult = 0; - Thread.Reschedule(ThreadSchedState.Running); + thread.Reschedule(ThreadSchedState.Running); } - Node = Node.Next; + node = node.Next; } } - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/KSynchronizationObject.cs b/Ryujinx.HLE/HOS/Kernel/KSynchronizationObject.cs index 5ba7784f..79f0673f 100644 --- a/Ryujinx.HLE/HOS/Kernel/KSynchronizationObject.cs +++ b/Ryujinx.HLE/HOS/Kernel/KSynchronizationObject.cs @@ -6,19 +6,19 @@ namespace Ryujinx.HLE.HOS.Kernel { public LinkedList WaitingThreads; - public KSynchronizationObject(Horizon System) : base(System) + public KSynchronizationObject(Horizon system) : base(system) { WaitingThreads = new LinkedList(); } - public LinkedListNode AddWaitingThread(KThread Thread) + public LinkedListNode AddWaitingThread(KThread thread) { - return WaitingThreads.AddLast(Thread); + return WaitingThreads.AddLast(thread); } - public void RemoveWaitingThread(LinkedListNode Node) + public void RemoveWaitingThread(LinkedListNode node) { - WaitingThreads.Remove(Node); + WaitingThreads.Remove(node); } public virtual void Signal() diff --git a/Ryujinx.HLE/HOS/Kernel/KThread.cs b/Ryujinx.HLE/HOS/Kernel/KThread.cs index 88f144c8..846b41aa 100644 --- a/Ryujinx.HLE/HOS/Kernel/KThread.cs +++ b/Ryujinx.HLE/HOS/Kernel/KThread.cs @@ -22,13 +22,13 @@ namespace Ryujinx.HLE.HOS.Kernel public long CondVarAddress { get; set; } - private ulong Entrypoint; + private ulong _entrypoint; public long MutexAddress { get; set; } public KProcess Owner { get; private set; } - private ulong TlsAddress; + private ulong _tlsAddress; public long LastScheduledTime { get; set; } @@ -39,14 +39,14 @@ namespace Ryujinx.HLE.HOS.Kernel public LinkedListNode ProcessListNode { get; set; } - private LinkedList MutexWaiters; - private LinkedListNode MutexWaiterNode; + private LinkedList _mutexWaiters; + private LinkedListNode _mutexWaiterNode; public KThread MutexOwner { get; private set; } public int ThreadHandleForUserMutex { get; set; } - private ThreadSchedState ForcePauseFlags; + private ThreadSchedState _forcePauseFlags; public int ObjSyncResult { get; set; } @@ -55,9 +55,9 @@ namespace Ryujinx.HLE.HOS.Kernel public int BasePriority { get; set; } public int PreferredCore { get; set; } - private long AffinityMaskOverride; - private int PreferredCoreOverride; - private int AffinityOverrideCount; + private long _affinityMaskOverride; + private int _preferredCoreOverride; + private int _affinityOverrideCount; public ThreadSchedState SchedFlags { get; private set; } @@ -66,101 +66,101 @@ namespace Ryujinx.HLE.HOS.Kernel public bool SyncCancelled { get; set; } public bool WaitingSync { get; set; } - private bool HasExited; + private bool _hasExited; public bool WaitingInArbitration { get; set; } - private KScheduler Scheduler; + private KScheduler _scheduler; - private KSchedulingData SchedulingData; + private KSchedulingData _schedulingData; public long LastPc { get; set; } - public KThread(Horizon System) : base(System) + public KThread(Horizon system) : base(system) { - Scheduler = System.Scheduler; - SchedulingData = System.Scheduler.SchedulingData; + _scheduler = system.Scheduler; + _schedulingData = system.Scheduler.SchedulingData; SiblingsPerCore = new LinkedListNode[KScheduler.CpuCoresCount]; - MutexWaiters = new LinkedList(); + _mutexWaiters = new LinkedList(); } public KernelResult Initialize( - ulong Entrypoint, - ulong ArgsPtr, - ulong StackTop, - int Priority, - int DefaultCpuCore, - KProcess Owner, - ThreadType Type = ThreadType.User) + ulong entrypoint, + ulong argsPtr, + ulong stackTop, + int priority, + int defaultCpuCore, + KProcess owner, + ThreadType type = ThreadType.User) { - if ((uint)Type > 3) + if ((uint)type > 3) { - throw new ArgumentException($"Invalid thread type \"{Type}\"."); + throw new ArgumentException($"Invalid thread type \"{type}\"."); } - PreferredCore = DefaultCpuCore; + PreferredCore = defaultCpuCore; - AffinityMask |= 1L << DefaultCpuCore; + AffinityMask |= 1L << defaultCpuCore; - SchedFlags = Type == ThreadType.Dummy + SchedFlags = type == ThreadType.Dummy ? ThreadSchedState.Running : ThreadSchedState.None; CurrentCore = PreferredCore; - DynamicPriority = Priority; - BasePriority = Priority; + DynamicPriority = priority; + BasePriority = priority; ObjSyncResult = 0x7201; - this.Entrypoint = Entrypoint; + _entrypoint = entrypoint; - if (Type == ThreadType.User) + if (type == ThreadType.User) { - if (Owner.AllocateThreadLocalStorage(out TlsAddress) != KernelResult.Success) + if (owner.AllocateThreadLocalStorage(out _tlsAddress) != KernelResult.Success) { return KernelResult.OutOfMemory; } - MemoryHelper.FillWithZeros(Owner.CpuMemory, (long)TlsAddress, KTlsPageInfo.TlsEntrySize); + MemoryHelper.FillWithZeros(owner.CpuMemory, (long)_tlsAddress, KTlsPageInfo.TlsEntrySize); } - bool Is64Bits; + bool is64Bits; - if (Owner != null) + if (owner != null) { - this.Owner = Owner; + Owner = owner; - Owner.IncrementThreadCount(); + owner.IncrementThreadCount(); - Is64Bits = (Owner.MmuFlags & 1) != 0; + is64Bits = (owner.MmuFlags & 1) != 0; } else { - Is64Bits = true; + is64Bits = true; } - Context = new CpuThread(Owner.Translator, Owner.CpuMemory, (long)Entrypoint); + Context = new CpuThread(owner.Translator, owner.CpuMemory, (long)entrypoint); - Context.ThreadState.X0 = ArgsPtr; - Context.ThreadState.X31 = StackTop; + Context.ThreadState.X0 = argsPtr; + Context.ThreadState.X31 = stackTop; Context.ThreadState.CntfrqEl0 = 19200000; - Context.ThreadState.Tpidr = (long)TlsAddress; + Context.ThreadState.Tpidr = (long)_tlsAddress; - Owner.SubscribeThreadEventHandlers(Context); + owner.SubscribeThreadEventHandlers(Context); Context.WorkFinished += ThreadFinishedHandler; ThreadUid = System.GetThreadUid(); - if (Owner != null) + if (owner != null) { - Owner.AddThread(this); + owner.AddThread(this); - if (Owner.IsPaused) + if (owner.IsPaused) { System.CriticalSection.Enter(); @@ -171,7 +171,7 @@ namespace Ryujinx.HLE.HOS.Kernel return KernelResult.Success; } - ForcePauseFlags |= ThreadSchedState.ProcessPauseFlag; + _forcePauseFlags |= ThreadSchedState.ProcessPauseFlag; CombineForcePauseFlags(); @@ -190,7 +190,7 @@ namespace Ryujinx.HLE.HOS.Kernel if (!ShallBeTerminated && SchedFlags != ThreadSchedState.TerminationPending) { - ForcePauseFlags |= ThreadSchedState.KernelInitPauseFlag; + _forcePauseFlags |= ThreadSchedState.KernelInitPauseFlag; CombineForcePauseFlags(); } @@ -198,46 +198,46 @@ namespace Ryujinx.HLE.HOS.Kernel System.CriticalSection.Leave(); } - KernelResult Result = KernelResult.ThreadTerminating; + KernelResult result = KernelResult.ThreadTerminating; System.CriticalSection.Enter(); if (!ShallBeTerminated) { - KThread CurrentThread = System.Scheduler.GetCurrentThread(); + KThread currentThread = System.Scheduler.GetCurrentThread(); while (SchedFlags != ThreadSchedState.TerminationPending && - CurrentThread.SchedFlags != ThreadSchedState.TerminationPending && - !CurrentThread.ShallBeTerminated) + currentThread.SchedFlags != ThreadSchedState.TerminationPending && + !currentThread.ShallBeTerminated) { if ((SchedFlags & ThreadSchedState.LowMask) != ThreadSchedState.None) { - Result = KernelResult.InvalidState; + result = KernelResult.InvalidState; break; } - if (CurrentThread.ForcePauseFlags == ThreadSchedState.None) + if (currentThread._forcePauseFlags == ThreadSchedState.None) { - if (Owner != null && ForcePauseFlags != ThreadSchedState.None) + if (Owner != null && _forcePauseFlags != ThreadSchedState.None) { CombineForcePauseFlags(); } SetNewSchedFlags(ThreadSchedState.Running); - Result = KernelResult.Success; + result = KernelResult.Success; break; } else { - CurrentThread.CombineForcePauseFlags(); + currentThread.CombineForcePauseFlags(); System.CriticalSection.Leave(); System.CriticalSection.Enter(); - if (CurrentThread.ShallBeTerminated) + if (currentThread.ShallBeTerminated) { break; } @@ -247,14 +247,14 @@ namespace Ryujinx.HLE.HOS.Kernel System.CriticalSection.Leave(); - return Result; + return result; } public void Exit() { System.CriticalSection.Enter(); - ForcePauseFlags &= ~ThreadSchedState.ForcePauseMask; + _forcePauseFlags &= ~ThreadSchedState.ForcePauseMask; ExitImpl(); @@ -267,14 +267,14 @@ namespace Ryujinx.HLE.HOS.Kernel SetNewSchedFlags(ThreadSchedState.TerminationPending); - HasExited = true; + _hasExited = true; Signal(); System.CriticalSection.Leave(); } - public long Sleep(long Timeout) + public long Sleep(long timeout) { System.CriticalSection.Enter(); @@ -287,14 +287,14 @@ namespace Ryujinx.HLE.HOS.Kernel SetNewSchedFlags(ThreadSchedState.Paused); - if (Timeout > 0) + if (timeout > 0) { - System.TimeManager.ScheduleFutureInvocation(this, Timeout); + System.TimeManager.ScheduleFutureInvocation(this, timeout); } System.CriticalSection.Leave(); - if (Timeout > 0) + if (timeout > 0) { System.TimeManager.UnscheduleFutureInvocation(this); } @@ -318,10 +318,10 @@ namespace Ryujinx.HLE.HOS.Kernel if (DynamicPriority < KScheduler.PrioritiesCount) { //Move current thread to the end of the queue. - SchedulingData.Reschedule(DynamicPriority, CurrentCore, this); + _schedulingData.Reschedule(DynamicPriority, CurrentCore, this); } - Scheduler.ThreadReselectionRequested = true; + _scheduler.ThreadReselectionRequested = true; System.CriticalSection.Leave(); @@ -341,32 +341,32 @@ namespace Ryujinx.HLE.HOS.Kernel return; } - int Prio = DynamicPriority; - int Core = CurrentCore; + int prio = DynamicPriority; + int core = CurrentCore; - KThread NextThreadOnCurrentQueue = null; + KThread nextThreadOnCurrentQueue = null; if (DynamicPriority < KScheduler.PrioritiesCount) { //Move current thread to the end of the queue. - SchedulingData.Reschedule(Prio, Core, this); + _schedulingData.Reschedule(prio, core, this); - Func Predicate = x => x.DynamicPriority == Prio; + Func predicate = x => x.DynamicPriority == prio; - NextThreadOnCurrentQueue = SchedulingData.ScheduledThreads(Core).FirstOrDefault(Predicate); + nextThreadOnCurrentQueue = _schedulingData.ScheduledThreads(core).FirstOrDefault(predicate); } IEnumerable SuitableCandidates() { - foreach (KThread Thread in SchedulingData.SuggestedThreads(Core)) + foreach (KThread thread in _schedulingData.SuggestedThreads(core)) { - int SrcCore = Thread.CurrentCore; + int srcCore = thread.CurrentCore; - if (SrcCore >= 0) + if (srcCore >= 0) { - KThread SelectedSrcCore = Scheduler.CoreContexts[SrcCore].SelectedThread; + KThread selectedSrcCore = _scheduler.CoreContexts[srcCore].SelectedThread; - if (SelectedSrcCore == Thread || ((SelectedSrcCore?.DynamicPriority ?? 2) < 2)) + if (selectedSrcCore == thread || ((selectedSrcCore?.DynamicPriority ?? 2) < 2)) { continue; } @@ -374,26 +374,26 @@ namespace Ryujinx.HLE.HOS.Kernel //If the candidate was scheduled after the current thread, then it's not worth it, //unless the priority is higher than the current one. - if (NextThreadOnCurrentQueue.LastScheduledTime >= Thread.LastScheduledTime || - NextThreadOnCurrentQueue.DynamicPriority < Thread.DynamicPriority) + if (nextThreadOnCurrentQueue.LastScheduledTime >= thread.LastScheduledTime || + nextThreadOnCurrentQueue.DynamicPriority < thread.DynamicPriority) { - yield return Thread; + yield return thread; } } } - KThread Dst = SuitableCandidates().FirstOrDefault(x => x.DynamicPriority <= Prio); + KThread dst = SuitableCandidates().FirstOrDefault(x => x.DynamicPriority <= prio); - if (Dst != null) + if (dst != null) { - SchedulingData.TransferToCore(Dst.DynamicPriority, Core, Dst); + _schedulingData.TransferToCore(dst.DynamicPriority, core, dst); - Scheduler.ThreadReselectionRequested = true; + _scheduler.ThreadReselectionRequested = true; } - if (this != NextThreadOnCurrentQueue) + if (this != nextThreadOnCurrentQueue) { - Scheduler.ThreadReselectionRequested = true; + _scheduler.ThreadReselectionRequested = true; } System.CriticalSection.Leave(); @@ -414,42 +414,42 @@ namespace Ryujinx.HLE.HOS.Kernel return; } - int Core = CurrentCore; + int core = CurrentCore; - SchedulingData.TransferToCore(DynamicPriority, -1, this); + _schedulingData.TransferToCore(DynamicPriority, -1, this); - KThread SelectedThread = null; + KThread selectedThread = null; - if (!SchedulingData.ScheduledThreads(Core).Any()) + if (!_schedulingData.ScheduledThreads(core).Any()) { - foreach (KThread Thread in SchedulingData.SuggestedThreads(Core)) + foreach (KThread thread in _schedulingData.SuggestedThreads(core)) { - if (Thread.CurrentCore < 0) + if (thread.CurrentCore < 0) { continue; } - KThread FirstCandidate = SchedulingData.ScheduledThreads(Thread.CurrentCore).FirstOrDefault(); + KThread firstCandidate = _schedulingData.ScheduledThreads(thread.CurrentCore).FirstOrDefault(); - if (FirstCandidate == Thread) + if (firstCandidate == thread) { continue; } - if (FirstCandidate == null || FirstCandidate.DynamicPriority >= 2) + if (firstCandidate == null || firstCandidate.DynamicPriority >= 2) { - SchedulingData.TransferToCore(Thread.DynamicPriority, Core, Thread); + _schedulingData.TransferToCore(thread.DynamicPriority, core, thread); - SelectedThread = Thread; + selectedThread = thread; } break; } } - if (SelectedThread != this) + if (selectedThread != this) { - Scheduler.ThreadReselectionRequested = true; + _scheduler.ThreadReselectionRequested = true; } System.CriticalSection.Leave(); @@ -457,26 +457,26 @@ namespace Ryujinx.HLE.HOS.Kernel System.Scheduler.ContextSwitch(); } - public void SetPriority(int Priority) + public void SetPriority(int priority) { System.CriticalSection.Enter(); - BasePriority = Priority; + BasePriority = priority; UpdatePriorityInheritance(); System.CriticalSection.Leave(); } - public long SetActivity(bool Pause) + public long SetActivity(bool pause) { - long Result = 0; + long result = 0; System.CriticalSection.Enter(); - ThreadSchedState LowNibble = SchedFlags & ThreadSchedState.LowMask; + ThreadSchedState lowNibble = SchedFlags & ThreadSchedState.LowMask; - if (LowNibble != ThreadSchedState.Paused && LowNibble != ThreadSchedState.Running) + if (lowNibble != ThreadSchedState.Paused && lowNibble != ThreadSchedState.Running) { System.CriticalSection.Leave(); @@ -487,41 +487,41 @@ namespace Ryujinx.HLE.HOS.Kernel if (!ShallBeTerminated && SchedFlags != ThreadSchedState.TerminationPending) { - if (Pause) + if (pause) { //Pause, the force pause flag should be clear (thread is NOT paused). - if ((ForcePauseFlags & ThreadSchedState.ThreadPauseFlag) == 0) + if ((_forcePauseFlags & ThreadSchedState.ThreadPauseFlag) == 0) { - ForcePauseFlags |= ThreadSchedState.ThreadPauseFlag; + _forcePauseFlags |= ThreadSchedState.ThreadPauseFlag; CombineForcePauseFlags(); } else { - Result = MakeError(ErrorModule.Kernel, KernelErr.InvalidState); + result = MakeError(ErrorModule.Kernel, KernelErr.InvalidState); } } else { //Unpause, the force pause flag should be set (thread is paused). - if ((ForcePauseFlags & ThreadSchedState.ThreadPauseFlag) != 0) + if ((_forcePauseFlags & ThreadSchedState.ThreadPauseFlag) != 0) { - ThreadSchedState OldForcePauseFlags = ForcePauseFlags; + ThreadSchedState oldForcePauseFlags = _forcePauseFlags; - ForcePauseFlags &= ~ThreadSchedState.ThreadPauseFlag; + _forcePauseFlags &= ~ThreadSchedState.ThreadPauseFlag; - if ((OldForcePauseFlags & ~ThreadSchedState.ThreadPauseFlag) == ThreadSchedState.None) + if ((oldForcePauseFlags & ~ThreadSchedState.ThreadPauseFlag) == ThreadSchedState.None) { - ThreadSchedState OldSchedFlags = SchedFlags; + ThreadSchedState oldSchedFlags = SchedFlags; SchedFlags &= ThreadSchedState.LowMask; - AdjustScheduling(OldSchedFlags); + AdjustScheduling(oldSchedFlags); } } else { - Result = MakeError(ErrorModule.Kernel, KernelErr.InvalidState); + result = MakeError(ErrorModule.Kernel, KernelErr.InvalidState); } } } @@ -529,7 +529,7 @@ namespace Ryujinx.HLE.HOS.Kernel System.CriticalSection.Leave(); System.CriticalSection.Leave(); - return Result; + return result; } public void CancelSynchronization() @@ -563,18 +563,18 @@ namespace Ryujinx.HLE.HOS.Kernel System.CriticalSection.Leave(); } - public KernelResult SetCoreAndAffinityMask(int NewCore, long NewAffinityMask) + public KernelResult SetCoreAndAffinityMask(int newCore, long newAffinityMask) { System.CriticalSection.Enter(); - bool UseOverride = AffinityOverrideCount != 0; + bool useOverride = _affinityOverrideCount != 0; //The value -3 is "do not change the preferred core". - if (NewCore == -3) + if (newCore == -3) { - NewCore = UseOverride ? PreferredCoreOverride : PreferredCore; + newCore = useOverride ? _preferredCoreOverride : PreferredCore; - if ((NewAffinityMask & (1 << NewCore)) == 0) + if ((newAffinityMask & (1 << newCore)) == 0) { System.CriticalSection.Leave(); @@ -582,21 +582,21 @@ namespace Ryujinx.HLE.HOS.Kernel } } - if (UseOverride) + if (useOverride) { - PreferredCoreOverride = NewCore; - AffinityMaskOverride = NewAffinityMask; + _preferredCoreOverride = newCore; + _affinityMaskOverride = newAffinityMask; } else { - long OldAffinityMask = AffinityMask; + long oldAffinityMask = AffinityMask; - PreferredCore = NewCore; - AffinityMask = NewAffinityMask; + PreferredCore = newCore; + AffinityMask = newAffinityMask; - if (OldAffinityMask != NewAffinityMask) + if (oldAffinityMask != newAffinityMask) { - int OldCore = CurrentCore; + int oldCore = CurrentCore; if (CurrentCore >= 0 && ((AffinityMask >> CurrentCore) & 1) == 0) { @@ -610,7 +610,7 @@ namespace Ryujinx.HLE.HOS.Kernel } } - AdjustSchedulingForNewAffinity(OldAffinityMask, OldCore); + AdjustSchedulingForNewAffinity(oldAffinityMask, oldCore); } } @@ -619,13 +619,13 @@ namespace Ryujinx.HLE.HOS.Kernel return KernelResult.Success; } - private static int HighestSetCore(long Mask) + private static int HighestSetCore(long mask) { - for (int Core = KScheduler.CpuCoresCount - 1; Core >= 0; Core--) + for (int core = KScheduler.CpuCoresCount - 1; core >= 0; core--) { - if (((Mask >> Core) & 1) != 0) + if (((mask >> core) & 1) != 0) { - return Core; + return core; } } @@ -634,25 +634,25 @@ namespace Ryujinx.HLE.HOS.Kernel private void CombineForcePauseFlags() { - ThreadSchedState OldFlags = SchedFlags; - ThreadSchedState LowNibble = SchedFlags & ThreadSchedState.LowMask; + ThreadSchedState oldFlags = SchedFlags; + ThreadSchedState lowNibble = SchedFlags & ThreadSchedState.LowMask; - SchedFlags = LowNibble | ForcePauseFlags; + SchedFlags = lowNibble | _forcePauseFlags; - AdjustScheduling(OldFlags); + AdjustScheduling(oldFlags); } - private void SetNewSchedFlags(ThreadSchedState NewFlags) + private void SetNewSchedFlags(ThreadSchedState newFlags) { System.CriticalSection.Enter(); - ThreadSchedState OldFlags = SchedFlags; + ThreadSchedState oldFlags = SchedFlags; - SchedFlags = (OldFlags & ThreadSchedState.HighMask) | NewFlags; + SchedFlags = (oldFlags & ThreadSchedState.HighMask) | newFlags; - if ((OldFlags & ThreadSchedState.LowMask) != NewFlags) + if ((oldFlags & ThreadSchedState.LowMask) != newFlags) { - AdjustScheduling(OldFlags); + AdjustScheduling(oldFlags); } System.CriticalSection.Leave(); @@ -681,98 +681,98 @@ namespace Ryujinx.HLE.HOS.Kernel System.CriticalSection.Leave(); } - public void Reschedule(ThreadSchedState NewFlags) + public void Reschedule(ThreadSchedState newFlags) { System.CriticalSection.Enter(); - ThreadSchedState OldFlags = SchedFlags; + ThreadSchedState oldFlags = SchedFlags; - SchedFlags = (OldFlags & ThreadSchedState.HighMask) | - (NewFlags & ThreadSchedState.LowMask); + SchedFlags = (oldFlags & ThreadSchedState.HighMask) | + (newFlags & ThreadSchedState.LowMask); - AdjustScheduling(OldFlags); + AdjustScheduling(oldFlags); System.CriticalSection.Leave(); } - public void AddMutexWaiter(KThread Requester) + public void AddMutexWaiter(KThread requester) { - AddToMutexWaitersList(Requester); + AddToMutexWaitersList(requester); - Requester.MutexOwner = this; + requester.MutexOwner = this; UpdatePriorityInheritance(); } - public void RemoveMutexWaiter(KThread Thread) + public void RemoveMutexWaiter(KThread thread) { - if (Thread.MutexWaiterNode?.List != null) + if (thread._mutexWaiterNode?.List != null) { - MutexWaiters.Remove(Thread.MutexWaiterNode); + _mutexWaiters.Remove(thread._mutexWaiterNode); } - Thread.MutexOwner = null; + thread.MutexOwner = null; UpdatePriorityInheritance(); } - public KThread RelinquishMutex(long MutexAddress, out int Count) + public KThread RelinquishMutex(long mutexAddress, out int count) { - Count = 0; + count = 0; - if (MutexWaiters.First == null) + if (_mutexWaiters.First == null) { return null; } - KThread NewMutexOwner = null; + KThread newMutexOwner = null; - LinkedListNode CurrentNode = MutexWaiters.First; + LinkedListNode currentNode = _mutexWaiters.First; do { //Skip all threads that are not waiting for this mutex. - while (CurrentNode != null && CurrentNode.Value.MutexAddress != MutexAddress) + while (currentNode != null && currentNode.Value.MutexAddress != mutexAddress) { - CurrentNode = CurrentNode.Next; + currentNode = currentNode.Next; } - if (CurrentNode == null) + if (currentNode == null) { break; } - LinkedListNode NextNode = CurrentNode.Next; + LinkedListNode nextNode = currentNode.Next; - MutexWaiters.Remove(CurrentNode); + _mutexWaiters.Remove(currentNode); - CurrentNode.Value.MutexOwner = NewMutexOwner; + currentNode.Value.MutexOwner = newMutexOwner; - if (NewMutexOwner != null) + if (newMutexOwner != null) { //New owner was already selected, re-insert on new owner list. - NewMutexOwner.AddToMutexWaitersList(CurrentNode.Value); + newMutexOwner.AddToMutexWaitersList(currentNode.Value); } else { //New owner not selected yet, use current thread. - NewMutexOwner = CurrentNode.Value; + newMutexOwner = currentNode.Value; } - Count++; + count++; - CurrentNode = NextNode; + currentNode = nextNode; } - while (CurrentNode != null); + while (currentNode != null); - if (NewMutexOwner != null) + if (newMutexOwner != null) { UpdatePriorityInheritance(); - NewMutexOwner.UpdatePriorityInheritance(); + newMutexOwner.UpdatePriorityInheritance(); } - return NewMutexOwner; + return newMutexOwner; } private void UpdatePriorityInheritance() @@ -780,30 +780,30 @@ namespace Ryujinx.HLE.HOS.Kernel //If any of the threads waiting for the mutex has //higher priority than the current thread, then //the current thread inherits that priority. - int HighestPriority = BasePriority; + int highestPriority = BasePriority; - if (MutexWaiters.First != null) + if (_mutexWaiters.First != null) { - int WaitingDynamicPriority = MutexWaiters.First.Value.DynamicPriority; + int waitingDynamicPriority = _mutexWaiters.First.Value.DynamicPriority; - if (WaitingDynamicPriority < HighestPriority) + if (waitingDynamicPriority < highestPriority) { - HighestPriority = WaitingDynamicPriority; + highestPriority = waitingDynamicPriority; } } - if (HighestPriority != DynamicPriority) + if (highestPriority != DynamicPriority) { - int OldPriority = DynamicPriority; + int oldPriority = DynamicPriority; - DynamicPriority = HighestPriority; + DynamicPriority = highestPriority; - AdjustSchedulingForNewPriority(OldPriority); + AdjustSchedulingForNewPriority(oldPriority); if (MutexOwner != null) { //Remove and re-insert to ensure proper sorting based on new priority. - MutexOwner.MutexWaiters.Remove(MutexWaiterNode); + MutexOwner._mutexWaiters.Remove(_mutexWaiterNode); MutexOwner.AddToMutexWaitersList(this); @@ -812,47 +812,47 @@ namespace Ryujinx.HLE.HOS.Kernel } } - private void AddToMutexWaitersList(KThread Thread) + private void AddToMutexWaitersList(KThread thread) { - LinkedListNode NextPrio = MutexWaiters.First; + LinkedListNode nextPrio = _mutexWaiters.First; - int CurrentPriority = Thread.DynamicPriority; + int currentPriority = thread.DynamicPriority; - while (NextPrio != null && NextPrio.Value.DynamicPriority <= CurrentPriority) + while (nextPrio != null && nextPrio.Value.DynamicPriority <= currentPriority) { - NextPrio = NextPrio.Next; + nextPrio = nextPrio.Next; } - if (NextPrio != null) + if (nextPrio != null) { - Thread.MutexWaiterNode = MutexWaiters.AddBefore(NextPrio, Thread); + thread._mutexWaiterNode = _mutexWaiters.AddBefore(nextPrio, thread); } else { - Thread.MutexWaiterNode = MutexWaiters.AddLast(Thread); + thread._mutexWaiterNode = _mutexWaiters.AddLast(thread); } } - private void AdjustScheduling(ThreadSchedState OldFlags) + private void AdjustScheduling(ThreadSchedState oldFlags) { - if (OldFlags == SchedFlags) + if (oldFlags == SchedFlags) { return; } - if (OldFlags == ThreadSchedState.Running) + if (oldFlags == ThreadSchedState.Running) { //Was running, now it's stopped. if (CurrentCore >= 0) { - SchedulingData.Unschedule(DynamicPriority, CurrentCore, this); + _schedulingData.Unschedule(DynamicPriority, CurrentCore, this); } - for (int Core = 0; Core < KScheduler.CpuCoresCount; Core++) + for (int core = 0; core < KScheduler.CpuCoresCount; core++) { - if (Core != CurrentCore && ((AffinityMask >> Core) & 1) != 0) + if (core != CurrentCore && ((AffinityMask >> core) & 1) != 0) { - SchedulingData.Unsuggest(DynamicPriority, Core, this); + _schedulingData.Unsuggest(DynamicPriority, core, this); } } } @@ -861,22 +861,22 @@ namespace Ryujinx.HLE.HOS.Kernel //Was stopped, now it's running. if (CurrentCore >= 0) { - SchedulingData.Schedule(DynamicPriority, CurrentCore, this); + _schedulingData.Schedule(DynamicPriority, CurrentCore, this); } - for (int Core = 0; Core < KScheduler.CpuCoresCount; Core++) + for (int core = 0; core < KScheduler.CpuCoresCount; core++) { - if (Core != CurrentCore && ((AffinityMask >> Core) & 1) != 0) + if (core != CurrentCore && ((AffinityMask >> core) & 1) != 0) { - SchedulingData.Suggest(DynamicPriority, Core, this); + _schedulingData.Suggest(DynamicPriority, core, this); } } } - Scheduler.ThreadReselectionRequested = true; + _scheduler.ThreadReselectionRequested = true; } - private void AdjustSchedulingForNewPriority(int OldPriority) + private void AdjustSchedulingForNewPriority(int oldPriority) { if (SchedFlags != ThreadSchedState.Running) { @@ -886,44 +886,44 @@ namespace Ryujinx.HLE.HOS.Kernel //Remove thread from the old priority queues. if (CurrentCore >= 0) { - SchedulingData.Unschedule(OldPriority, CurrentCore, this); + _schedulingData.Unschedule(oldPriority, CurrentCore, this); } - for (int Core = 0; Core < KScheduler.CpuCoresCount; Core++) + for (int core = 0; core < KScheduler.CpuCoresCount; core++) { - if (Core != CurrentCore && ((AffinityMask >> Core) & 1) != 0) + if (core != CurrentCore && ((AffinityMask >> core) & 1) != 0) { - SchedulingData.Unsuggest(OldPriority, Core, this); + _schedulingData.Unsuggest(oldPriority, core, this); } } //Add thread to the new priority queues. - KThread CurrentThread = Scheduler.GetCurrentThread(); + KThread currentThread = _scheduler.GetCurrentThread(); if (CurrentCore >= 0) { - if (CurrentThread == this) + if (currentThread == this) { - SchedulingData.SchedulePrepend(DynamicPriority, CurrentCore, this); + _schedulingData.SchedulePrepend(DynamicPriority, CurrentCore, this); } else { - SchedulingData.Schedule(DynamicPriority, CurrentCore, this); + _schedulingData.Schedule(DynamicPriority, CurrentCore, this); } } - for (int Core = 0; Core < KScheduler.CpuCoresCount; Core++) + for (int core = 0; core < KScheduler.CpuCoresCount; core++) { - if (Core != CurrentCore && ((AffinityMask >> Core) & 1) != 0) + if (core != CurrentCore && ((AffinityMask >> core) & 1) != 0) { - SchedulingData.Suggest(DynamicPriority, Core, this); + _schedulingData.Suggest(DynamicPriority, core, this); } } - Scheduler.ThreadReselectionRequested = true; + _scheduler.ThreadReselectionRequested = true; } - private void AdjustSchedulingForNewAffinity(long OldAffinityMask, int OldCore) + private void AdjustSchedulingForNewAffinity(long oldAffinityMask, int oldCore) { if (SchedFlags != ThreadSchedState.Running || DynamicPriority >= KScheduler.PrioritiesCount) { @@ -931,49 +931,49 @@ namespace Ryujinx.HLE.HOS.Kernel } //Remove from old queues. - for (int Core = 0; Core < KScheduler.CpuCoresCount; Core++) + for (int core = 0; core < KScheduler.CpuCoresCount; core++) { - if (((OldAffinityMask >> Core) & 1) != 0) + if (((oldAffinityMask >> core) & 1) != 0) { - if (Core == OldCore) + if (core == oldCore) { - SchedulingData.Unschedule(DynamicPriority, Core, this); + _schedulingData.Unschedule(DynamicPriority, core, this); } else { - SchedulingData.Unsuggest(DynamicPriority, Core, this); + _schedulingData.Unsuggest(DynamicPriority, core, this); } } } //Insert on new queues. - for (int Core = 0; Core < KScheduler.CpuCoresCount; Core++) + for (int core = 0; core < KScheduler.CpuCoresCount; core++) { - if (((AffinityMask >> Core) & 1) != 0) + if (((AffinityMask >> core) & 1) != 0) { - if (Core == CurrentCore) + if (core == CurrentCore) { - SchedulingData.Schedule(DynamicPriority, Core, this); + _schedulingData.Schedule(DynamicPriority, core, this); } else { - SchedulingData.Suggest(DynamicPriority, Core, this); + _schedulingData.Suggest(DynamicPriority, core, this); } } } - Scheduler.ThreadReselectionRequested = true; + _scheduler.ThreadReselectionRequested = true; } public override bool IsSignaled() { - return HasExited; + return _hasExited; } - public void SetEntryArguments(long ArgsPtr, int ThreadHandle) + public void SetEntryArguments(long argsPtr, int threadHandle) { - Context.ThreadState.X0 = (ulong)ArgsPtr; - Context.ThreadState.X1 = (ulong)ThreadHandle; + Context.ThreadState.X0 = (ulong)argsPtr; + Context.ThreadState.X1 = (ulong)threadHandle; } public void ClearExclusive() @@ -1004,7 +1004,7 @@ namespace Ryujinx.HLE.HOS.Kernel { Owner?.RemoveThread(this); - if (TlsAddress != 0 && Owner.FreeThreadLocalStorage(TlsAddress) != KernelResult.Success) + if (_tlsAddress != 0 && Owner.FreeThreadLocalStorage(_tlsAddress) != KernelResult.Success) { throw new InvalidOperationException("Unexpected failure freeing thread local storage."); } @@ -1013,13 +1013,13 @@ namespace Ryujinx.HLE.HOS.Kernel //Wake up all threads that may be waiting for a mutex being held //by this thread. - foreach (KThread Thread in MutexWaiters) + foreach (KThread thread in _mutexWaiters) { - Thread.MutexOwner = null; - Thread.PreferredCoreOverride = 0; - Thread.ObjSyncResult = 0xfa01; + thread.MutexOwner = null; + thread._preferredCoreOverride = 0; + thread.ObjSyncResult = 0xfa01; - Thread.ReleaseAndResume(); + thread.ReleaseAndResume(); } System.CriticalSection.Leave(); diff --git a/Ryujinx.HLE/HOS/Kernel/KTimeManager.cs b/Ryujinx.HLE/HOS/Kernel/KTimeManager.cs index 375789f0..0c2551a3 100644 --- a/Ryujinx.HLE/HOS/Kernel/KTimeManager.cs +++ b/Ryujinx.HLE/HOS/Kernel/KTimeManager.cs @@ -14,112 +14,112 @@ namespace Ryujinx.HLE.HOS.Kernel public long TimePoint { get; private set; } - public WaitingObject(IKFutureSchedulerObject Object, long TimePoint) + public WaitingObject(IKFutureSchedulerObject schedulerObj, long timePoint) { - this.Object = Object; - this.TimePoint = TimePoint; + Object = schedulerObj; + TimePoint = timePoint; } } - private List WaitingObjects; + private List _waitingObjects; - private AutoResetEvent WaitEvent; + private AutoResetEvent _waitEvent; - private bool KeepRunning; + private bool _keepRunning; public KTimeManager() { - WaitingObjects = new List(); + _waitingObjects = new List(); - KeepRunning = true; + _keepRunning = true; - Thread Work = new Thread(WaitAndCheckScheduledObjects); + Thread work = new Thread(WaitAndCheckScheduledObjects); - Work.Start(); + work.Start(); } - public void ScheduleFutureInvocation(IKFutureSchedulerObject Object, long Timeout) + public void ScheduleFutureInvocation(IKFutureSchedulerObject schedulerObj, long timeout) { - long TimePoint = PerformanceCounter.ElapsedMilliseconds + ConvertNanosecondsToMilliseconds(Timeout); + long timePoint = PerformanceCounter.ElapsedMilliseconds + ConvertNanosecondsToMilliseconds(timeout); - lock (WaitingObjects) + lock (_waitingObjects) { - WaitingObjects.Add(new WaitingObject(Object, TimePoint)); + _waitingObjects.Add(new WaitingObject(schedulerObj, timePoint)); } - WaitEvent.Set(); + _waitEvent.Set(); } - public static long ConvertNanosecondsToMilliseconds(long Time) + public static long ConvertNanosecondsToMilliseconds(long time) { - Time /= 1000000; + time /= 1000000; - if ((ulong)Time > int.MaxValue) + if ((ulong)time > int.MaxValue) { return int.MaxValue; } - return Time; + return time; } - public static long ConvertMillisecondsToNanoseconds(long Time) + public static long ConvertMillisecondsToNanoseconds(long time) { - return Time * 1000000; + return time * 1000000; } - public static long ConvertMillisecondsToTicks(long Time) + public static long ConvertMillisecondsToTicks(long time) { - return Time * 19200; + return time * 19200; } public void UnscheduleFutureInvocation(IKFutureSchedulerObject Object) { - lock (WaitingObjects) + lock (_waitingObjects) { - WaitingObjects.RemoveAll(x => x.Object == Object); + _waitingObjects.RemoveAll(x => x.Object == Object); } } private void WaitAndCheckScheduledObjects() { - using (WaitEvent = new AutoResetEvent(false)) + using (_waitEvent = new AutoResetEvent(false)) { - while (KeepRunning) + while (_keepRunning) { - WaitingObject Next; + WaitingObject next; - lock (WaitingObjects) + lock (_waitingObjects) { - Next = WaitingObjects.OrderBy(x => x.TimePoint).FirstOrDefault(); + next = _waitingObjects.OrderBy(x => x.TimePoint).FirstOrDefault(); } - if (Next != null) + if (next != null) { - long TimePoint = PerformanceCounter.ElapsedMilliseconds; + long timePoint = PerformanceCounter.ElapsedMilliseconds; - if (Next.TimePoint > TimePoint) + if (next.TimePoint > timePoint) { - WaitEvent.WaitOne((int)(Next.TimePoint - TimePoint)); + _waitEvent.WaitOne((int)(next.TimePoint - timePoint)); } - bool TimeUp = PerformanceCounter.ElapsedMilliseconds >= Next.TimePoint; + bool timeUp = PerformanceCounter.ElapsedMilliseconds >= next.TimePoint; - if (TimeUp) + if (timeUp) { - lock (WaitingObjects) + lock (_waitingObjects) { - TimeUp = WaitingObjects.Remove(Next); + timeUp = _waitingObjects.Remove(next); } } - if (TimeUp) + if (timeUp) { - Next.Object.TimeUp(); + next.Object.TimeUp(); } } else { - WaitEvent.WaitOne(); + _waitEvent.WaitOne(); } } } @@ -130,13 +130,13 @@ namespace Ryujinx.HLE.HOS.Kernel Dispose(true); } - protected virtual void Dispose(bool Disposing) + protected virtual void Dispose(bool disposing) { - if (Disposing) + if (disposing) { - KeepRunning = false; + _keepRunning = false; - WaitEvent?.Set(); + _waitEvent?.Set(); } } } diff --git a/Ryujinx.HLE/HOS/Kernel/KTlsPageInfo.cs b/Ryujinx.HLE/HOS/Kernel/KTlsPageInfo.cs index 18dc2dec..ff5ecf13 100644 --- a/Ryujinx.HLE/HOS/Kernel/KTlsPageInfo.cs +++ b/Ryujinx.HLE/HOS/Kernel/KTlsPageInfo.cs @@ -6,68 +6,68 @@ namespace Ryujinx.HLE.HOS.Kernel public ulong PageAddr { get; private set; } - private bool[] IsSlotFree; + private bool[] _isSlotFree; - public KTlsPageInfo(ulong PageAddress) + public KTlsPageInfo(ulong pageAddress) { - this.PageAddr = PageAddress; + PageAddr = pageAddress; - IsSlotFree = new bool[KMemoryManager.PageSize / TlsEntrySize]; + _isSlotFree = new bool[KMemoryManager.PageSize / TlsEntrySize]; - for (int Index = 0; Index < IsSlotFree.Length; Index++) + for (int index = 0; index < _isSlotFree.Length; index++) { - IsSlotFree[Index] = true; + _isSlotFree[index] = true; } } - public bool TryGetFreePage(out ulong Address) + public bool TryGetFreePage(out ulong address) { - Address = PageAddr; + address = PageAddr; - for (int Index = 0; Index < IsSlotFree.Length; Index++) + for (int index = 0; index < _isSlotFree.Length; index++) { - if (IsSlotFree[Index]) + if (_isSlotFree[index]) { - IsSlotFree[Index] = false; + _isSlotFree[index] = false; return true; } - Address += TlsEntrySize; + address += TlsEntrySize; } - Address = 0; + address = 0; return false; } public bool IsFull() { - bool HasFree = false; + bool hasFree = false; - for (int Index = 0; Index < IsSlotFree.Length; Index++) + for (int index = 0; index < _isSlotFree.Length; index++) { - HasFree |= IsSlotFree[Index]; + hasFree |= _isSlotFree[index]; } - return !HasFree; + return !hasFree; } public bool IsEmpty() { - bool AllFree = true; + bool allFree = true; - for (int Index = 0; Index < IsSlotFree.Length; Index++) + for (int index = 0; index < _isSlotFree.Length; index++) { - AllFree &= IsSlotFree[Index]; + allFree &= _isSlotFree[index]; } - return AllFree; + return allFree; } - public void FreeTlsSlot(ulong Address) + public void FreeTlsSlot(ulong address) { - IsSlotFree[(Address - PageAddr) / TlsEntrySize] = true; + _isSlotFree[(address - PageAddr) / TlsEntrySize] = true; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/KTlsPageManager.cs b/Ryujinx.HLE/HOS/Kernel/KTlsPageManager.cs index 1fb2ce6a..75f595eb 100644 --- a/Ryujinx.HLE/HOS/Kernel/KTlsPageManager.cs +++ b/Ryujinx.HLE/HOS/Kernel/KTlsPageManager.cs @@ -6,55 +6,55 @@ namespace Ryujinx.HLE.HOS.Kernel { private const int TlsEntrySize = 0x200; - private long PagePosition; + private long _pagePosition; - private int UsedSlots; + private int _usedSlots; - private bool[] Slots; + private bool[] _slots; - public bool IsEmpty => UsedSlots == 0; - public bool IsFull => UsedSlots == Slots.Length; + public bool IsEmpty => _usedSlots == 0; + public bool IsFull => _usedSlots == _slots.Length; - public KTlsPageManager(long PagePosition) + public KTlsPageManager(long pagePosition) { - this.PagePosition = PagePosition; + _pagePosition = pagePosition; - Slots = new bool[KMemoryManager.PageSize / TlsEntrySize]; + _slots = new bool[KMemoryManager.PageSize / TlsEntrySize]; } - public bool TryGetFreeTlsAddr(out long Position) + public bool TryGetFreeTlsAddr(out long position) { - Position = PagePosition; + position = _pagePosition; - for (int Index = 0; Index < Slots.Length; Index++) + for (int index = 0; index < _slots.Length; index++) { - if (!Slots[Index]) + if (!_slots[index]) { - Slots[Index] = true; + _slots[index] = true; - UsedSlots++; + _usedSlots++; return true; } - Position += TlsEntrySize; + position += TlsEntrySize; } - Position = 0; + position = 0; return false; } - public void FreeTlsSlot(int Slot) + public void FreeTlsSlot(int slot) { - if ((uint)Slot > Slots.Length) + if ((uint)slot > _slots.Length) { - throw new ArgumentOutOfRangeException(nameof(Slot)); + throw new ArgumentOutOfRangeException(nameof(slot)); } - Slots[Slot] = false; + _slots[slot] = false; - UsedSlots--; + _usedSlots--; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/KTransferMemory.cs b/Ryujinx.HLE/HOS/Kernel/KTransferMemory.cs index 5598f78d..d8837851 100644 --- a/Ryujinx.HLE/HOS/Kernel/KTransferMemory.cs +++ b/Ryujinx.HLE/HOS/Kernel/KTransferMemory.cs @@ -3,12 +3,12 @@ namespace Ryujinx.HLE.HOS.Kernel class KTransferMemory { public ulong Address { get; private set; } - public ulong Size { get; private set; } + public ulong Size { get; private set; } - public KTransferMemory(ulong Address, ulong Size) + public KTransferMemory(ulong address, ulong size) { - this.Address = Address; - this.Size = Size; + Address = address; + Size = size; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/KWritableEvent.cs b/Ryujinx.HLE/HOS/Kernel/KWritableEvent.cs index 1721ed00..4d56a92d 100644 --- a/Ryujinx.HLE/HOS/Kernel/KWritableEvent.cs +++ b/Ryujinx.HLE/HOS/Kernel/KWritableEvent.cs @@ -2,21 +2,21 @@ namespace Ryujinx.HLE.HOS.Kernel { class KWritableEvent { - private KEvent Parent; + private KEvent _parent; - public KWritableEvent(KEvent Parent) + public KWritableEvent(KEvent parent) { - this.Parent = Parent; + _parent = parent; } public void Signal() { - Parent.ReadableEvent.Signal(); + _parent.ReadableEvent.Signal(); } public KernelResult Clear() { - return Parent.ReadableEvent.Clear(); + return _parent.ReadableEvent.Clear(); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/KernelInit.cs b/Ryujinx.HLE/HOS/Kernel/KernelInit.cs index efb514c1..a797951b 100644 --- a/Ryujinx.HLE/HOS/Kernel/KernelInit.cs +++ b/Ryujinx.HLE/HOS/Kernel/KernelInit.cs @@ -4,28 +4,28 @@ namespace Ryujinx.HLE.HOS.Kernel { static class KernelInit { - public static void InitializeResourceLimit(KResourceLimit ResourceLimit) + public static void InitializeResourceLimit(KResourceLimit resourceLimit) { - void EnsureSuccess(KernelResult Result) + void EnsureSuccess(KernelResult result) { - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - throw new InvalidOperationException($"Unexpected result \"{Result}\"."); + throw new InvalidOperationException($"Unexpected result \"{result}\"."); } } - int KernelMemoryCfg = 0; + int kernelMemoryCfg = 0; - long RamSize = GetRamSize(KernelMemoryCfg); + long ramSize = GetRamSize(kernelMemoryCfg); - EnsureSuccess(ResourceLimit.SetLimitValue(LimitableResource.Memory, RamSize)); - EnsureSuccess(ResourceLimit.SetLimitValue(LimitableResource.Thread, 800)); - EnsureSuccess(ResourceLimit.SetLimitValue(LimitableResource.Event, 700)); - EnsureSuccess(ResourceLimit.SetLimitValue(LimitableResource.TransferMemory, 200)); - EnsureSuccess(ResourceLimit.SetLimitValue(LimitableResource.Session, 900)); + EnsureSuccess(resourceLimit.SetLimitValue(LimitableResource.Memory, ramSize)); + EnsureSuccess(resourceLimit.SetLimitValue(LimitableResource.Thread, 800)); + EnsureSuccess(resourceLimit.SetLimitValue(LimitableResource.Event, 700)); + EnsureSuccess(resourceLimit.SetLimitValue(LimitableResource.TransferMemory, 200)); + EnsureSuccess(resourceLimit.SetLimitValue(LimitableResource.Session, 900)); - if (!ResourceLimit.Reserve(LimitableResource.Memory, 0) || - !ResourceLimit.Reserve(LimitableResource.Memory, 0x60000)) + if (!resourceLimit.Reserve(LimitableResource.Memory, 0) || + !resourceLimit.Reserve(LimitableResource.Memory, 0x60000)) { throw new InvalidOperationException("Unexpected failure reserving memory on resource limit."); } @@ -33,99 +33,99 @@ namespace Ryujinx.HLE.HOS.Kernel public static KMemoryRegionManager[] GetMemoryRegions() { - KMemoryArrange Arrange = GetMemoryArrange(); + KMemoryArrange arrange = GetMemoryArrange(); return new KMemoryRegionManager[] { - GetMemoryRegion(Arrange.Application), - GetMemoryRegion(Arrange.Applet), - GetMemoryRegion(Arrange.Service), - GetMemoryRegion(Arrange.NvServices) + GetMemoryRegion(arrange.Application), + GetMemoryRegion(arrange.Applet), + GetMemoryRegion(arrange.Service), + GetMemoryRegion(arrange.NvServices) }; } - private static KMemoryRegionManager GetMemoryRegion(KMemoryArrangeRegion Region) + private static KMemoryRegionManager GetMemoryRegion(KMemoryArrangeRegion region) { - return new KMemoryRegionManager(Region.Address, Region.Size, Region.EndAddr); + return new KMemoryRegionManager(region.Address, region.Size, region.EndAddr); } private static KMemoryArrange GetMemoryArrange() { - int McEmemCfg = 0x1000; + int mcEmemCfg = 0x1000; - ulong EmemApertureSize = (ulong)(McEmemCfg & 0x3fff) << 20; + ulong ememApertureSize = (ulong)(mcEmemCfg & 0x3fff) << 20; - int KernelMemoryCfg = 0; + int kernelMemoryCfg = 0; - ulong RamSize = (ulong)GetRamSize(KernelMemoryCfg); + ulong ramSize = (ulong)GetRamSize(kernelMemoryCfg); - ulong RamPart0; - ulong RamPart1; + ulong ramPart0; + ulong ramPart1; - if (RamSize * 2 > EmemApertureSize) + if (ramSize * 2 > ememApertureSize) { - RamPart0 = EmemApertureSize / 2; - RamPart1 = EmemApertureSize / 2; + ramPart0 = ememApertureSize / 2; + ramPart1 = ememApertureSize / 2; } else { - RamPart0 = EmemApertureSize; - RamPart1 = 0; + ramPart0 = ememApertureSize; + ramPart1 = 0; } - int MemoryArrange = 1; + int memoryArrange = 1; - ulong ApplicationRgSize; + ulong applicationRgSize; - switch (MemoryArrange) + switch (memoryArrange) { - case 2: ApplicationRgSize = 0x80000000; break; + case 2: applicationRgSize = 0x80000000; break; case 0x11: - case 0x21: ApplicationRgSize = 0x133400000; break; - default: ApplicationRgSize = 0xcd500000; break; + case 0x21: applicationRgSize = 0x133400000; break; + default: applicationRgSize = 0xcd500000; break; } - ulong AppletRgSize; + ulong appletRgSize; - switch (MemoryArrange) + switch (memoryArrange) { - case 2: AppletRgSize = 0x61200000; break; - case 3: AppletRgSize = 0x1c000000; break; - case 0x11: AppletRgSize = 0x23200000; break; + case 2: appletRgSize = 0x61200000; break; + case 3: appletRgSize = 0x1c000000; break; + case 0x11: appletRgSize = 0x23200000; break; case 0x12: - case 0x21: AppletRgSize = 0x89100000; break; - default: AppletRgSize = 0x1fb00000; break; + case 0x21: appletRgSize = 0x89100000; break; + default: appletRgSize = 0x1fb00000; break; } - KMemoryArrangeRegion ServiceRg; - KMemoryArrangeRegion NvServicesRg; - KMemoryArrangeRegion AppletRg; - KMemoryArrangeRegion ApplicationRg; + KMemoryArrangeRegion serviceRg; + KMemoryArrangeRegion nvServicesRg; + KMemoryArrangeRegion appletRg; + KMemoryArrangeRegion applicationRg; - const ulong NvServicesRgSize = 0x29ba000; + const ulong nvServicesRgSize = 0x29ba000; - ulong ApplicationRgEnd = DramMemoryMap.DramEnd; //- RamPart0; + ulong applicationRgEnd = DramMemoryMap.DramEnd; //- RamPart0; - ApplicationRg = new KMemoryArrangeRegion(ApplicationRgEnd - ApplicationRgSize, ApplicationRgSize); + applicationRg = new KMemoryArrangeRegion(applicationRgEnd - applicationRgSize, applicationRgSize); - ulong NvServicesRgEnd = ApplicationRg.Address - AppletRgSize; + ulong nvServicesRgEnd = applicationRg.Address - appletRgSize; - NvServicesRg = new KMemoryArrangeRegion(NvServicesRgEnd - NvServicesRgSize, NvServicesRgSize); - AppletRg = new KMemoryArrangeRegion(NvServicesRgEnd, AppletRgSize); + nvServicesRg = new KMemoryArrangeRegion(nvServicesRgEnd - nvServicesRgSize, nvServicesRgSize); + appletRg = new KMemoryArrangeRegion(nvServicesRgEnd, appletRgSize); //Note: There is an extra region used by the kernel, however //since we are doing HLE we are not going to use that memory, so give all //the remaining memory space to services. - ulong ServiceRgSize = NvServicesRg.Address - DramMemoryMap.SlabHeapEnd; + ulong serviceRgSize = nvServicesRg.Address - DramMemoryMap.SlabHeapEnd; - ServiceRg = new KMemoryArrangeRegion(DramMemoryMap.SlabHeapEnd, ServiceRgSize); + serviceRg = new KMemoryArrangeRegion(DramMemoryMap.SlabHeapEnd, serviceRgSize); - return new KMemoryArrange(ServiceRg, NvServicesRg, AppletRg, ApplicationRg); + return new KMemoryArrange(serviceRg, nvServicesRg, appletRg, applicationRg); } - private static long GetRamSize(int KernelMemoryCfg) + private static long GetRamSize(int kernelMemoryCfg) { - switch ((KernelMemoryCfg >> 16) & 3) + switch ((kernelMemoryCfg >> 16) & 3) { case 1: return 0x180000000; case 2: return 0x200000000; diff --git a/Ryujinx.HLE/HOS/Kernel/KernelTransfer.cs b/Ryujinx.HLE/HOS/Kernel/KernelTransfer.cs index a3fabeae..c0ce72c0 100644 --- a/Ryujinx.HLE/HOS/Kernel/KernelTransfer.cs +++ b/Ryujinx.HLE/HOS/Kernel/KernelTransfer.cs @@ -4,48 +4,48 @@ namespace Ryujinx.HLE.HOS.Kernel { static class KernelTransfer { - public static bool UserToKernelInt32(Horizon System, long Address, out int Value) + public static bool UserToKernelInt32(Horizon system, long address, out int value) { - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = system.Scheduler.GetCurrentProcess(); - if (CurrentProcess.CpuMemory.IsMapped(Address) && - CurrentProcess.CpuMemory.IsMapped(Address + 3)) + if (currentProcess.CpuMemory.IsMapped(address) && + currentProcess.CpuMemory.IsMapped(address + 3)) { - Value = CurrentProcess.CpuMemory.ReadInt32(Address); + value = currentProcess.CpuMemory.ReadInt32(address); return true; } - Value = 0; + value = 0; return false; } - public static bool UserToKernelString(Horizon System, long Address, int Size, out string Value) + public static bool UserToKernelString(Horizon system, long address, int size, out string value) { - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = system.Scheduler.GetCurrentProcess(); - if (CurrentProcess.CpuMemory.IsMapped(Address) && - CurrentProcess.CpuMemory.IsMapped(Address + Size - 1)) + if (currentProcess.CpuMemory.IsMapped(address) && + currentProcess.CpuMemory.IsMapped(address + size - 1)) { - Value = MemoryHelper.ReadAsciiString(CurrentProcess.CpuMemory, Address, Size); + value = MemoryHelper.ReadAsciiString(currentProcess.CpuMemory, address, size); return true; } - Value = null; + value = null; return false; } - public static bool KernelToUserInt32(Horizon System, long Address, int Value) + public static bool KernelToUserInt32(Horizon system, long address, int value) { - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = system.Scheduler.GetCurrentProcess(); - if (CurrentProcess.CpuMemory.IsMapped(Address) && - CurrentProcess.CpuMemory.IsMapped(Address + 3)) + if (currentProcess.CpuMemory.IsMapped(address) && + currentProcess.CpuMemory.IsMapped(address + 3)) { - CurrentProcess.CpuMemory.WriteInt32ToSharedAddr(Address, Value); + currentProcess.CpuMemory.WriteInt32ToSharedAddr(address, value); return true; } @@ -53,14 +53,14 @@ namespace Ryujinx.HLE.HOS.Kernel return false; } - public static bool KernelToUserInt64(Horizon System, long Address, long Value) + public static bool KernelToUserInt64(Horizon system, long address, long value) { - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = system.Scheduler.GetCurrentProcess(); - if (CurrentProcess.CpuMemory.IsMapped(Address) && - CurrentProcess.CpuMemory.IsMapped(Address + 7)) + if (currentProcess.CpuMemory.IsMapped(address) && + currentProcess.CpuMemory.IsMapped(address + 7)) { - CurrentProcess.CpuMemory.WriteInt64(Address, Value); + currentProcess.CpuMemory.WriteInt64(address, value); return true; } diff --git a/Ryujinx.HLE/HOS/Kernel/MersenneTwister.cs b/Ryujinx.HLE/HOS/Kernel/MersenneTwister.cs index b90d54d2..5307bdc9 100644 --- a/Ryujinx.HLE/HOS/Kernel/MersenneTwister.cs +++ b/Ryujinx.HLE/HOS/Kernel/MersenneTwister.cs @@ -4,125 +4,125 @@ namespace Ryujinx.HLE.HOS.Kernel { class MersenneTwister { - private int Index; - private uint[] Mt; + private int _index; + private uint[] _mt; - public MersenneTwister(uint Seed) + public MersenneTwister(uint seed) { - Mt = new uint[624]; + _mt = new uint[624]; - Mt[0] = Seed; + _mt[0] = seed; - for (int MtIdx = 1; MtIdx < Mt.Length; MtIdx++) + for (int mtIdx = 1; mtIdx < _mt.Length; mtIdx++) { - uint Prev = Mt[MtIdx - 1]; + uint prev = _mt[mtIdx - 1]; - Mt[MtIdx] = (uint)(0x6c078965 * (Prev ^ (Prev >> 30)) + MtIdx); + _mt[mtIdx] = (uint)(0x6c078965 * (prev ^ (prev >> 30)) + mtIdx); } - Index = Mt.Length; + _index = _mt.Length; } - public long GenRandomNumber(long Min, long Max) + public long GenRandomNumber(long min, long max) { - long Range = Max - Min; + long range = max - min; - if (Min == Max) + if (min == max) { - return Min; + return min; } - if (Range == -1) + if (range == -1) { //Increment would cause a overflow, special case. return GenRandomNumber(2, 2, 32, 0xffffffffu, 0xffffffffu); } - Range++; + range++; //This is log2(Range) plus one. - int NextRangeLog2 = 64 - BitUtils.CountLeadingZeros64(Range); + int nextRangeLog2 = 64 - BitUtils.CountLeadingZeros64(range); //If Range is already power of 2, subtract one to use log2(Range) directly. - int RangeLog2 = NextRangeLog2 - (BitUtils.IsPowerOfTwo64(Range) ? 1 : 0); + int rangeLog2 = nextRangeLog2 - (BitUtils.IsPowerOfTwo64(range) ? 1 : 0); - int Parts = RangeLog2 > 32 ? 2 : 1; - int BitsPerPart = RangeLog2 / Parts; + int parts = rangeLog2 > 32 ? 2 : 1; + int bitsPerPart = rangeLog2 / parts; - int FullParts = Parts - (RangeLog2 - Parts * BitsPerPart); + int fullParts = parts - (rangeLog2 - parts * bitsPerPart); - uint Mask = 0xffffffffu >> (32 - BitsPerPart); - uint MaskPlus1 = 0xffffffffu >> (31 - BitsPerPart); + uint mask = 0xffffffffu >> (32 - bitsPerPart); + uint maskPlus1 = 0xffffffffu >> (31 - bitsPerPart); - long RandomNumber; + long randomNumber; do { - RandomNumber = GenRandomNumber(Parts, FullParts, BitsPerPart, Mask, MaskPlus1); + randomNumber = GenRandomNumber(parts, fullParts, bitsPerPart, mask, maskPlus1); } - while ((ulong)RandomNumber >= (ulong)Range); + while ((ulong)randomNumber >= (ulong)range); - return Min + RandomNumber; + return min + randomNumber; } private long GenRandomNumber( - int Parts, - int FullParts, - int BitsPerPart, - uint Mask, - uint MaskPlus1) + int parts, + int fullParts, + int bitsPerPart, + uint mask, + uint maskPlus1) { - long RandomNumber = 0; + long randomNumber = 0; - int Part = 0; + int part = 0; - for (; Part < FullParts; Part++) + for (; part < fullParts; part++) { - RandomNumber <<= BitsPerPart; - RandomNumber |= GenRandomNumber() & Mask; + randomNumber <<= bitsPerPart; + randomNumber |= GenRandomNumber() & mask; } - for (; Part < Parts; Part++) + for (; part < parts; part++) { - RandomNumber <<= BitsPerPart + 1; - RandomNumber |= GenRandomNumber() & MaskPlus1; + randomNumber <<= bitsPerPart + 1; + randomNumber |= GenRandomNumber() & maskPlus1; } - return RandomNumber; + return randomNumber; } private uint GenRandomNumber() { - if (Index >= Mt.Length) + if (_index >= _mt.Length) { Twist(); } - uint Value = Mt[Index++]; + uint value = _mt[_index++]; - Value ^= Value >> 11; - Value ^= (Value << 7) & 0x9d2c5680; - Value ^= (Value << 15) & 0xefc60000; - Value ^= Value >> 18; + value ^= value >> 11; + value ^= (value << 7) & 0x9d2c5680; + value ^= (value << 15) & 0xefc60000; + value ^= value >> 18; - return Value; + return value; } private void Twist() { - for (int MtIdx = 0; MtIdx < Mt.Length; MtIdx++) + for (int mtIdx = 0; mtIdx < _mt.Length; mtIdx++) { - uint Value = (Mt[MtIdx] & 0x80000000) + (Mt[(MtIdx + 1) % Mt.Length] & 0x7fffffff); + uint value = (_mt[mtIdx] & 0x80000000) + (_mt[(mtIdx + 1) % _mt.Length] & 0x7fffffff); - Mt[MtIdx] = Mt[(MtIdx + 397) % Mt.Length] ^ (Value >> 1); + _mt[mtIdx] = _mt[(mtIdx + 397) % _mt.Length] ^ (value >> 1); - if ((Value & 1) != 0) + if ((value & 1) != 0) { - Mt[MtIdx] ^= 0x9908b0df; + _mt[mtIdx] ^= 0x9908b0df; } } - Index = 0; + _index = 0; } } } diff --git a/Ryujinx.HLE/HOS/Kernel/ProcessCreationInfo.cs b/Ryujinx.HLE/HOS/Kernel/ProcessCreationInfo.cs index dae1345a..7b2e8b72 100644 --- a/Ryujinx.HLE/HOS/Kernel/ProcessCreationInfo.cs +++ b/Ryujinx.HLE/HOS/Kernel/ProcessCreationInfo.cs @@ -15,23 +15,23 @@ namespace Ryujinx.HLE.HOS.Kernel public int PersonalMmHeapPagesCount { get; private set; } public ProcessCreationInfo( - string Name, - int Category, - long TitleId, - ulong CodeAddress, - int CodePagesCount, - int MmuFlags, - int ResourceLimitHandle, - int PersonalMmHeapPagesCount) + string name, + int category, + long titleId, + ulong codeAddress, + int codePagesCount, + int mmuFlags, + int resourceLimitHandle, + int personalMmHeapPagesCount) { - this.Name = Name; - this.Category = Category; - this.TitleId = TitleId; - this.CodeAddress = CodeAddress; - this.CodePagesCount = CodePagesCount; - this.MmuFlags = MmuFlags; - this.ResourceLimitHandle = ResourceLimitHandle; - this.PersonalMmHeapPagesCount = PersonalMmHeapPagesCount; + Name = name; + Category = category; + TitleId = titleId; + CodeAddress = codeAddress; + CodePagesCount = codePagesCount; + MmuFlags = mmuFlags; + ResourceLimitHandle = resourceLimitHandle; + PersonalMmHeapPagesCount = personalMmHeapPagesCount; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/SvcHandler.cs b/Ryujinx.HLE/HOS/Kernel/SvcHandler.cs index cbc5e31c..78a0cc85 100644 --- a/Ryujinx.HLE/HOS/Kernel/SvcHandler.cs +++ b/Ryujinx.HLE/HOS/Kernel/SvcHandler.cs @@ -10,14 +10,14 @@ namespace Ryujinx.HLE.HOS.Kernel { partial class SvcHandler { - private delegate void SvcFunc(CpuThreadState ThreadState); + private delegate void SvcFunc(CpuThreadState threadState); - private Dictionary SvcFuncs; + private Dictionary _svcFuncs; - private Switch Device; - private KProcess Process; - private Horizon System; - private MemoryManager Memory; + private Switch _device; + private KProcess _process; + private Horizon _system; + private MemoryManager _memory; private struct HleIpcMessage { @@ -27,21 +27,21 @@ namespace Ryujinx.HLE.HOS.Kernel public long MessagePtr { get; private set; } public HleIpcMessage( - KThread Thread, - KSession Session, - IpcMessage Message, - long MessagePtr) + KThread thread, + KSession session, + IpcMessage message, + long messagePtr) { - this.Thread = Thread; - this.Session = Session; - this.Message = Message; - this.MessagePtr = MessagePtr; + Thread = thread; + Session = session; + Message = message; + MessagePtr = messagePtr; } } - public SvcHandler(Switch Device, KProcess Process) + public SvcHandler(Switch device, KProcess process) { - SvcFuncs = new Dictionary() + _svcFuncs = new Dictionary { { 0x01, SvcSetHeapSize }, { 0x03, SvcSetMemoryAttribute }, @@ -93,23 +93,23 @@ namespace Ryujinx.HLE.HOS.Kernel { 0x71, ManageNamedPort64 } }; - this.Device = Device; - this.Process = Process; - this.System = Device.System; - this.Memory = Process.CpuMemory; + _device = device; + _process = process; + _system = device.System; + _memory = process.CpuMemory; } public void SvcCall(object sender, InstExceptionEventArgs e) { - CpuThreadState ThreadState = (CpuThreadState)sender; + CpuThreadState threadState = (CpuThreadState)sender; - if (SvcFuncs.TryGetValue(e.Id, out SvcFunc Func)) + if (_svcFuncs.TryGetValue(e.Id, out SvcFunc func)) { - Logger.PrintDebug(LogClass.KernelSvc, $"{Func.Method.Name} called."); + Logger.PrintDebug(LogClass.KernelSvc, $"{func.Method.Name} called."); - Func(ThreadState); + func(threadState); - Logger.PrintDebug(LogClass.KernelSvc, $"{Func.Method.Name} ended."); + Logger.PrintDebug(LogClass.KernelSvc, $"{func.Method.Name} ended."); } else { diff --git a/Ryujinx.HLE/HOS/Kernel/SvcMemory.cs b/Ryujinx.HLE/HOS/Kernel/SvcMemory.cs index b5845f0b..c99c1e98 100644 --- a/Ryujinx.HLE/HOS/Kernel/SvcMemory.cs +++ b/Ryujinx.HLE/HOS/Kernel/SvcMemory.cs @@ -7,575 +7,575 @@ namespace Ryujinx.HLE.HOS.Kernel { partial class SvcHandler { - private void SvcSetHeapSize(CpuThreadState ThreadState) + private void SvcSetHeapSize(CpuThreadState threadState) { - ulong Size = ThreadState.X1; + ulong size = threadState.X1; - if ((Size & 0xfffffffe001fffff) != 0) + if ((size & 0xfffffffe001fffff) != 0) { - Logger.PrintWarning(LogClass.KernelSvc, $"Heap size 0x{Size:x16} is not aligned!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Heap size 0x{size:x16} is not aligned!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidSize); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidSize); return; } - KernelResult Result = Process.MemoryManager.SetHeapSize(Size, out ulong Position); + KernelResult result = _process.MemoryManager.SetHeapSize(size, out ulong position); - ThreadState.X0 = (ulong)Result; + threadState.X0 = (ulong)result; - if (Result == KernelResult.Success) + if (result == KernelResult.Success) { - ThreadState.X1 = Position; + threadState.X1 = position; } else { - Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error \"{Result}\"."); + Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error \"{result}\"."); } } - private void SvcSetMemoryAttribute(CpuThreadState ThreadState) + private void SvcSetMemoryAttribute(CpuThreadState threadState) { - ulong Position = ThreadState.X0; - ulong Size = ThreadState.X1; + ulong position = threadState.X0; + ulong size = threadState.X1; - if (!PageAligned(Position)) + if (!PageAligned(position)) { - Logger.PrintWarning(LogClass.KernelSvc, $"Address 0x{Position:x16} is not page aligned!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Address 0x{position:x16} is not page aligned!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidAddress); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidAddress); return; } - if (!PageAligned(Size) || Size == 0) + if (!PageAligned(size) || size == 0) { - Logger.PrintWarning(LogClass.KernelSvc, $"Size 0x{Size:x16} is not page aligned or is zero!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Size 0x{size:x16} is not page aligned or is zero!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidSize); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidSize); return; } - MemoryAttribute AttributeMask = (MemoryAttribute)ThreadState.X2; - MemoryAttribute AttributeValue = (MemoryAttribute)ThreadState.X3; + MemoryAttribute attributeMask = (MemoryAttribute)threadState.X2; + MemoryAttribute attributeValue = (MemoryAttribute)threadState.X3; - MemoryAttribute Attributes = AttributeMask | AttributeValue; + MemoryAttribute attributes = attributeMask | attributeValue; - if (Attributes != AttributeMask || - (Attributes | MemoryAttribute.Uncached) != MemoryAttribute.Uncached) + if (attributes != attributeMask || + (attributes | MemoryAttribute.Uncached) != MemoryAttribute.Uncached) { Logger.PrintWarning(LogClass.KernelSvc, "Invalid memory attributes!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidMaskValue); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidMaskValue); return; } - KernelResult Result = Process.MemoryManager.SetMemoryAttribute( - Position, - Size, - AttributeMask, - AttributeValue); + KernelResult result = _process.MemoryManager.SetMemoryAttribute( + position, + size, + attributeMask, + attributeValue); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error \"{Result}\"."); + Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error \"{result}\"."); } else { - Memory.StopObservingRegion((long)Position, (long)Size); + _memory.StopObservingRegion((long)position, (long)size); } - ThreadState.X0 = (ulong)Result; + threadState.X0 = (ulong)result; } - private void SvcMapMemory(CpuThreadState ThreadState) + private void SvcMapMemory(CpuThreadState threadState) { - ulong Dst = ThreadState.X0; - ulong Src = ThreadState.X1; - ulong Size = ThreadState.X2; + ulong dst = threadState.X0; + ulong src = threadState.X1; + ulong size = threadState.X2; - if (!PageAligned(Src | Dst)) + if (!PageAligned(src | dst)) { Logger.PrintWarning(LogClass.KernelSvc, "Addresses are not page aligned!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidAddress); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidAddress); return; } - if (!PageAligned(Size) || Size == 0) + if (!PageAligned(size) || size == 0) { - Logger.PrintWarning(LogClass.KernelSvc, $"Size 0x{Size:x16} is not page aligned or is zero!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Size 0x{size:x16} is not page aligned or is zero!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidSize); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidSize); return; } - if (Src + Size <= Src || Dst + Size <= Dst) + if (src + size <= src || dst + size <= dst) { Logger.PrintWarning(LogClass.KernelSvc, "Addresses outside of range!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); return; } - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = _system.Scheduler.GetCurrentProcess(); - if (!CurrentProcess.MemoryManager.InsideAddrSpace(Src, Size)) + if (!currentProcess.MemoryManager.InsideAddrSpace(src, size)) { - Logger.PrintWarning(LogClass.KernelSvc, $"Src address 0x{Src:x16} out of range!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Src address 0x{src:x16} out of range!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); return; } - if (CurrentProcess.MemoryManager.OutsideStackRegion(Dst, Size) || - CurrentProcess.MemoryManager.InsideHeapRegion (Dst, Size) || - CurrentProcess.MemoryManager.InsideAliasRegion (Dst, Size)) + if (currentProcess.MemoryManager.OutsideStackRegion(dst, size) || + currentProcess.MemoryManager.InsideHeapRegion (dst, size) || + currentProcess.MemoryManager.InsideAliasRegion (dst, size)) { - Logger.PrintWarning(LogClass.KernelSvc, $"Dst address 0x{Dst:x16} out of range!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Dst address 0x{dst:x16} out of range!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidMemRange); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidMemRange); return; } - KernelResult Result = Process.MemoryManager.Map(Dst, Src, Size); + KernelResult result = _process.MemoryManager.Map(dst, src, size); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{Result:x}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); } - ThreadState.X0 = (ulong)Result; + threadState.X0 = (ulong)result; } - private void SvcUnmapMemory(CpuThreadState ThreadState) + private void SvcUnmapMemory(CpuThreadState threadState) { - ulong Dst = ThreadState.X0; - ulong Src = ThreadState.X1; - ulong Size = ThreadState.X2; + ulong dst = threadState.X0; + ulong src = threadState.X1; + ulong size = threadState.X2; - if (!PageAligned(Src | Dst)) + if (!PageAligned(src | dst)) { Logger.PrintWarning(LogClass.KernelSvc, "Addresses are not page aligned!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidAddress); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidAddress); return; } - if (!PageAligned(Size) || Size == 0) + if (!PageAligned(size) || size == 0) { - Logger.PrintWarning(LogClass.KernelSvc, $"Size 0x{Size:x16} is not page aligned or is zero!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Size 0x{size:x16} is not page aligned or is zero!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidSize); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidSize); return; } - if (Src + Size <= Src || Dst + Size <= Dst) + if (src + size <= src || dst + size <= dst) { Logger.PrintWarning(LogClass.KernelSvc, "Addresses outside of range!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); return; } - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = _system.Scheduler.GetCurrentProcess(); - if (!CurrentProcess.MemoryManager.InsideAddrSpace(Src, Size)) + if (!currentProcess.MemoryManager.InsideAddrSpace(src, size)) { - Logger.PrintWarning(LogClass.KernelSvc, $"Src address 0x{Src:x16} out of range!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Src address 0x{src:x16} out of range!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); return; } - if (CurrentProcess.MemoryManager.OutsideStackRegion(Dst, Size) || - CurrentProcess.MemoryManager.InsideHeapRegion (Dst, Size) || - CurrentProcess.MemoryManager.InsideAliasRegion (Dst, Size)) + if (currentProcess.MemoryManager.OutsideStackRegion(dst, size) || + currentProcess.MemoryManager.InsideHeapRegion (dst, size) || + currentProcess.MemoryManager.InsideAliasRegion (dst, size)) { - Logger.PrintWarning(LogClass.KernelSvc, $"Dst address 0x{Dst:x16} out of range!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Dst address 0x{dst:x16} out of range!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidMemRange); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidMemRange); return; } - KernelResult Result = Process.MemoryManager.Unmap(Dst, Src, Size); + KernelResult result = _process.MemoryManager.Unmap(dst, src, size); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{Result:x}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); } - ThreadState.X0 = (ulong)Result; + threadState.X0 = (ulong)result; } - private void SvcQueryMemory(CpuThreadState ThreadState) + private void SvcQueryMemory(CpuThreadState threadState) { - long InfoPtr = (long)ThreadState.X0; - ulong Position = ThreadState.X2; + long infoPtr = (long)threadState.X0; + ulong position = threadState.X2; - KMemoryInfo BlkInfo = Process.MemoryManager.QueryMemory(Position); + KMemoryInfo blkInfo = _process.MemoryManager.QueryMemory(position); - Memory.WriteUInt64(InfoPtr + 0x00, BlkInfo.Address); - Memory.WriteUInt64(InfoPtr + 0x08, BlkInfo.Size); - Memory.WriteInt32 (InfoPtr + 0x10, (int)BlkInfo.State & 0xff); - Memory.WriteInt32 (InfoPtr + 0x14, (int)BlkInfo.Attribute); - Memory.WriteInt32 (InfoPtr + 0x18, (int)BlkInfo.Permission); - Memory.WriteInt32 (InfoPtr + 0x1c, BlkInfo.IpcRefCount); - Memory.WriteInt32 (InfoPtr + 0x20, BlkInfo.DeviceRefCount); - Memory.WriteInt32 (InfoPtr + 0x24, 0); + _memory.WriteUInt64(infoPtr + 0x00, blkInfo.Address); + _memory.WriteUInt64(infoPtr + 0x08, blkInfo.Size); + _memory.WriteInt32 (infoPtr + 0x10, (int)blkInfo.State & 0xff); + _memory.WriteInt32 (infoPtr + 0x14, (int)blkInfo.Attribute); + _memory.WriteInt32 (infoPtr + 0x18, (int)blkInfo.Permission); + _memory.WriteInt32 (infoPtr + 0x1c, blkInfo.IpcRefCount); + _memory.WriteInt32 (infoPtr + 0x20, blkInfo.DeviceRefCount); + _memory.WriteInt32 (infoPtr + 0x24, 0); - ThreadState.X0 = 0; - ThreadState.X1 = 0; + threadState.X0 = 0; + threadState.X1 = 0; } - private void SvcMapSharedMemory(CpuThreadState ThreadState) + private void SvcMapSharedMemory(CpuThreadState threadState) { - int Handle = (int)ThreadState.X0; - ulong Address = ThreadState.X1; - ulong Size = ThreadState.X2; + int handle = (int)threadState.X0; + ulong address = threadState.X1; + ulong size = threadState.X2; - if (!PageAligned(Address)) + if (!PageAligned(address)) { - Logger.PrintWarning(LogClass.KernelSvc, $"Address 0x{Address:x16} is not page aligned!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Address 0x{address:x16} is not page aligned!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidAddress); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidAddress); return; } - if (!PageAligned(Size) || Size == 0) + if (!PageAligned(size) || size == 0) { - Logger.PrintWarning(LogClass.KernelSvc, $"Size 0x{Size:x16} is not page aligned or is zero!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Size 0x{size:x16} is not page aligned or is zero!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidSize); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidSize); return; } - if (Address + Size <= Address) + if (address + size <= address) { - Logger.PrintWarning(LogClass.KernelSvc, $"Invalid region address 0x{Address:x16} / size 0x{Size:x16}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Invalid region address 0x{address:x16} / size 0x{size:x16}!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); return; } - MemoryPermission Permission = (MemoryPermission)ThreadState.X3; + MemoryPermission permission = (MemoryPermission)threadState.X3; - if ((Permission | MemoryPermission.Write) != MemoryPermission.ReadAndWrite) + if ((permission | MemoryPermission.Write) != MemoryPermission.ReadAndWrite) { - Logger.PrintWarning(LogClass.KernelSvc, $"Invalid permission {Permission}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Invalid permission {permission}!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidPermission); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidPermission); return; } - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = _system.Scheduler.GetCurrentProcess(); - KSharedMemory SharedMemory = CurrentProcess.HandleTable.GetObject(Handle); + KSharedMemory sharedMemory = currentProcess.HandleTable.GetObject(handle); - if (SharedMemory == null) + if (sharedMemory == null) { - Logger.PrintWarning(LogClass.KernelSvc, $"Invalid shared memory handle 0x{Handle:x8}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Invalid shared memory handle 0x{handle:x8}!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle); return; } - if (CurrentProcess.MemoryManager.IsInvalidRegion (Address, Size) || - CurrentProcess.MemoryManager.InsideHeapRegion (Address, Size) || - CurrentProcess.MemoryManager.InsideAliasRegion(Address, Size)) + if (currentProcess.MemoryManager.IsInvalidRegion (address, size) || + currentProcess.MemoryManager.InsideHeapRegion (address, size) || + currentProcess.MemoryManager.InsideAliasRegion(address, size)) { - Logger.PrintWarning(LogClass.KernelSvc, $"Address 0x{Address:x16} out of range!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Address 0x{address:x16} out of range!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); return; } - KernelResult Result = SharedMemory.MapIntoProcess( - CurrentProcess.MemoryManager, - Address, - Size, - CurrentProcess, - Permission); + KernelResult result = sharedMemory.MapIntoProcess( + currentProcess.MemoryManager, + address, + size, + currentProcess, + permission); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error \"{Result}\"."); + Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error \"{result}\"."); } - ThreadState.X0 = (ulong)Result; + threadState.X0 = (ulong)result; } - private void SvcUnmapSharedMemory(CpuThreadState ThreadState) + private void SvcUnmapSharedMemory(CpuThreadState threadState) { - int Handle = (int)ThreadState.X0; - ulong Address = ThreadState.X1; - ulong Size = ThreadState.X2; + int handle = (int)threadState.X0; + ulong address = threadState.X1; + ulong size = threadState.X2; - if (!PageAligned(Address)) + if (!PageAligned(address)) { - Logger.PrintWarning(LogClass.KernelSvc, $"Address 0x{Address:x16} is not page aligned!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Address 0x{address:x16} is not page aligned!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidAddress); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidAddress); return; } - if (!PageAligned(Size) || Size == 0) + if (!PageAligned(size) || size == 0) { - Logger.PrintWarning(LogClass.KernelSvc, $"Size 0x{Size:x16} is not page aligned or is zero!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Size 0x{size:x16} is not page aligned or is zero!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidSize); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidSize); return; } - if (Address + Size <= Address) + if (address + size <= address) { - Logger.PrintWarning(LogClass.KernelSvc, $"Invalid region address 0x{Address:x16} / size 0x{Size:x16}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Invalid region address 0x{address:x16} / size 0x{size:x16}!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); return; } - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = _system.Scheduler.GetCurrentProcess(); - KSharedMemory SharedMemory = CurrentProcess.HandleTable.GetObject(Handle); + KSharedMemory sharedMemory = currentProcess.HandleTable.GetObject(handle); - if (SharedMemory == null) + if (sharedMemory == null) { - Logger.PrintWarning(LogClass.KernelSvc, $"Invalid shared memory handle 0x{Handle:x8}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Invalid shared memory handle 0x{handle:x8}!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle); return; } - if (CurrentProcess.MemoryManager.IsInvalidRegion (Address, Size) || - CurrentProcess.MemoryManager.InsideHeapRegion (Address, Size) || - CurrentProcess.MemoryManager.InsideAliasRegion(Address, Size)) + if (currentProcess.MemoryManager.IsInvalidRegion (address, size) || + currentProcess.MemoryManager.InsideHeapRegion (address, size) || + currentProcess.MemoryManager.InsideAliasRegion(address, size)) { - Logger.PrintWarning(LogClass.KernelSvc, $"Address 0x{Address:x16} out of range!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Address 0x{address:x16} out of range!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); return; } - KernelResult Result = SharedMemory.UnmapFromProcess( - CurrentProcess.MemoryManager, - Address, - Size, - CurrentProcess); + KernelResult result = sharedMemory.UnmapFromProcess( + currentProcess.MemoryManager, + address, + size, + currentProcess); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error \"{Result}\"."); + Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error \"{result}\"."); } - ThreadState.X0 = (ulong)Result; + threadState.X0 = (ulong)result; } - private void SvcCreateTransferMemory(CpuThreadState ThreadState) + private void SvcCreateTransferMemory(CpuThreadState threadState) { - ulong Address = ThreadState.X1; - ulong Size = ThreadState.X2; + ulong address = threadState.X1; + ulong size = threadState.X2; - if (!PageAligned(Address)) + if (!PageAligned(address)) { - Logger.PrintWarning(LogClass.KernelSvc, $"Address 0x{Address:x16} is not page aligned!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Address 0x{address:x16} is not page aligned!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidAddress); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidAddress); return; } - if (!PageAligned(Size) || Size == 0) + if (!PageAligned(size) || size == 0) { - Logger.PrintWarning(LogClass.KernelSvc, $"Size 0x{Size:x16} is not page aligned or is zero!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Size 0x{size:x16} is not page aligned or is zero!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidAddress); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidAddress); return; } - if (Address + Size <= Address) + if (address + size <= address) { - Logger.PrintWarning(LogClass.KernelSvc, $"Invalid region address 0x{Address:x16} / size 0x{Size:x16}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Invalid region address 0x{address:x16} / size 0x{size:x16}!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); return; } - MemoryPermission Permission = (MemoryPermission)ThreadState.X3; + MemoryPermission permission = (MemoryPermission)threadState.X3; - if (Permission > MemoryPermission.ReadAndWrite || Permission == MemoryPermission.Write) + if (permission > MemoryPermission.ReadAndWrite || permission == MemoryPermission.Write) { - Logger.PrintWarning(LogClass.KernelSvc, $"Invalid permission {Permission}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Invalid permission {permission}!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidPermission); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidPermission); return; } - Process.MemoryManager.ReserveTransferMemory(Address, Size, Permission); + _process.MemoryManager.ReserveTransferMemory(address, size, permission); - KTransferMemory TransferMemory = new KTransferMemory(Address, Size); + KTransferMemory transferMemory = new KTransferMemory(address, size); - KernelResult Result = Process.HandleTable.GenerateHandle(TransferMemory, out int Handle); + KernelResult result = _process.HandleTable.GenerateHandle(transferMemory, out int handle); - ThreadState.X0 = (uint)Result; - ThreadState.X1 = (ulong)Handle; + threadState.X0 = (uint)result; + threadState.X1 = (ulong)handle; } - private void SvcMapPhysicalMemory(CpuThreadState ThreadState) + private void SvcMapPhysicalMemory(CpuThreadState threadState) { - ulong Address = ThreadState.X0; - ulong Size = ThreadState.X1; + ulong address = threadState.X0; + ulong size = threadState.X1; - if (!PageAligned(Address)) + if (!PageAligned(address)) { - Logger.PrintWarning(LogClass.KernelSvc, $"Address 0x{Address:x16} is not page aligned!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Address 0x{address:x16} is not page aligned!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidAddress); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidAddress); return; } - if (!PageAligned(Size) || Size == 0) + if (!PageAligned(size) || size == 0) { - Logger.PrintWarning(LogClass.KernelSvc, $"Size 0x{Size:x16} is not page aligned or is zero!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Size 0x{size:x16} is not page aligned or is zero!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidSize); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidSize); return; } - if (Address + Size <= Address) + if (address + size <= address) { - Logger.PrintWarning(LogClass.KernelSvc, $"Invalid region address 0x{Address:x16} / size 0x{Size:x16}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Invalid region address 0x{address:x16} / size 0x{size:x16}!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); return; } - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = _system.Scheduler.GetCurrentProcess(); - if ((CurrentProcess.PersonalMmHeapPagesCount & 0xfffffffffffff) == 0) + if ((currentProcess.PersonalMmHeapPagesCount & 0xfffffffffffff) == 0) { Logger.PrintWarning(LogClass.KernelSvc, $"System resource size is zero."); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidState); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidState); return; } - if (!CurrentProcess.MemoryManager.InsideAddrSpace (Address, Size) || - CurrentProcess.MemoryManager.OutsideAliasRegion(Address, Size)) + if (!currentProcess.MemoryManager.InsideAddrSpace (address, size) || + currentProcess.MemoryManager.OutsideAliasRegion(address, size)) { - Logger.PrintWarning(LogClass.KernelSvc, $"Invalid address {Address:x16}."); + Logger.PrintWarning(LogClass.KernelSvc, $"Invalid address {address:x16}."); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); return; } - KernelResult Result = Process.MemoryManager.MapPhysicalMemory(Address, Size); + KernelResult result = _process.MemoryManager.MapPhysicalMemory(address, size); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{Result:x}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); } - ThreadState.X0 = (ulong)Result; + threadState.X0 = (ulong)result; } - private void SvcUnmapPhysicalMemory(CpuThreadState ThreadState) + private void SvcUnmapPhysicalMemory(CpuThreadState threadState) { - ulong Address = ThreadState.X0; - ulong Size = ThreadState.X1; + ulong address = threadState.X0; + ulong size = threadState.X1; - if (!PageAligned(Address)) + if (!PageAligned(address)) { - Logger.PrintWarning(LogClass.KernelSvc, $"Address 0x{Address:x16} is not page aligned!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Address 0x{address:x16} is not page aligned!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidAddress); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidAddress); return; } - if (!PageAligned(Size) || Size == 0) + if (!PageAligned(size) || size == 0) { - Logger.PrintWarning(LogClass.KernelSvc, $"Size 0x{Size:x16} is not page aligned or is zero!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Size 0x{size:x16} is not page aligned or is zero!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidSize); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidSize); return; } - if (Address + Size <= Address) + if (address + size <= address) { - Logger.PrintWarning(LogClass.KernelSvc, $"Invalid region address 0x{Address:x16} / size 0x{Size:x16}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Invalid region address 0x{address:x16} / size 0x{size:x16}!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); return; } - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = _system.Scheduler.GetCurrentProcess(); - if ((CurrentProcess.PersonalMmHeapPagesCount & 0xfffffffffffff) == 0) + if ((currentProcess.PersonalMmHeapPagesCount & 0xfffffffffffff) == 0) { Logger.PrintWarning(LogClass.KernelSvc, $"System resource size is zero."); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidState); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidState); return; } - if (!CurrentProcess.MemoryManager.InsideAddrSpace (Address, Size) || - CurrentProcess.MemoryManager.OutsideAliasRegion(Address, Size)) + if (!currentProcess.MemoryManager.InsideAddrSpace (address, size) || + currentProcess.MemoryManager.OutsideAliasRegion(address, size)) { - Logger.PrintWarning(LogClass.KernelSvc, $"Invalid address {Address:x16}."); + Logger.PrintWarning(LogClass.KernelSvc, $"Invalid address {address:x16}."); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); return; } - KernelResult Result = Process.MemoryManager.UnmapPhysicalMemory(Address, Size); + KernelResult result = _process.MemoryManager.UnmapPhysicalMemory(address, size); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{Result:x}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); } - ThreadState.X0 = (ulong)Result; + threadState.X0 = (ulong)result; } - private static bool PageAligned(ulong Position) + private static bool PageAligned(ulong position) { - return (Position & (KMemoryManager.PageSize - 1)) == 0; + return (position & (KMemoryManager.PageSize - 1)) == 0; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/SvcSystem.cs b/Ryujinx.HLE/HOS/Kernel/SvcSystem.cs index 1c1d76f1..e42c2b4e 100644 --- a/Ryujinx.HLE/HOS/Kernel/SvcSystem.cs +++ b/Ryujinx.HLE/HOS/Kernel/SvcSystem.cs @@ -14,286 +14,286 @@ namespace Ryujinx.HLE.HOS.Kernel { partial class SvcHandler { - private void SvcExitProcess(CpuThreadState ThreadState) + private void SvcExitProcess(CpuThreadState threadState) { - System.Scheduler.GetCurrentProcess().Terminate(); + _system.Scheduler.GetCurrentProcess().Terminate(); } - private void SignalEvent64(CpuThreadState ThreadState) + private void SignalEvent64(CpuThreadState threadState) { - ThreadState.X0 = (ulong)SignalEvent((int)ThreadState.X0); + threadState.X0 = (ulong)SignalEvent((int)threadState.X0); } - private KernelResult SignalEvent(int Handle) + private KernelResult SignalEvent(int handle) { - KWritableEvent WritableEvent = Process.HandleTable.GetObject(Handle); + KWritableEvent writableEvent = _process.HandleTable.GetObject(handle); - KernelResult Result; + KernelResult result; - if (WritableEvent != null) + if (writableEvent != null) { - WritableEvent.Signal(); + writableEvent.Signal(); - Result = KernelResult.Success; + result = KernelResult.Success; } else { - Result = KernelResult.InvalidHandle; + result = KernelResult.InvalidHandle; } - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - Logger.PrintWarning(LogClass.KernelSvc, "Operation failed with error: " + Result + "!"); + Logger.PrintWarning(LogClass.KernelSvc, "Operation failed with error: " + result + "!"); } - return Result; + return result; } - private void ClearEvent64(CpuThreadState ThreadState) + private void ClearEvent64(CpuThreadState threadState) { - ThreadState.X0 = (ulong)ClearEvent((int)ThreadState.X0); + threadState.X0 = (ulong)ClearEvent((int)threadState.X0); } - private KernelResult ClearEvent(int Handle) + private KernelResult ClearEvent(int handle) { - KernelResult Result; + KernelResult result; - KWritableEvent WritableEvent = Process.HandleTable.GetObject(Handle); + KWritableEvent writableEvent = _process.HandleTable.GetObject(handle); - if (WritableEvent == null) + if (writableEvent == null) { - KReadableEvent ReadableEvent = Process.HandleTable.GetObject(Handle); + KReadableEvent readableEvent = _process.HandleTable.GetObject(handle); - Result = ReadableEvent?.Clear() ?? KernelResult.InvalidHandle; + result = readableEvent?.Clear() ?? KernelResult.InvalidHandle; } else { - Result = WritableEvent.Clear(); + result = writableEvent.Clear(); } - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - Logger.PrintWarning(LogClass.KernelSvc, "Operation failed with error: " + Result + "!"); + Logger.PrintWarning(LogClass.KernelSvc, "Operation failed with error: " + result + "!"); } - return Result; + return result; } - private void SvcCloseHandle(CpuThreadState ThreadState) + private void SvcCloseHandle(CpuThreadState threadState) { - int Handle = (int)ThreadState.X0; + int handle = (int)threadState.X0; - object Obj = Process.HandleTable.GetObject(Handle); + object obj = _process.HandleTable.GetObject(handle); - Process.HandleTable.CloseHandle(Handle); + _process.HandleTable.CloseHandle(handle); - if (Obj == null) + if (obj == null) { - Logger.PrintWarning(LogClass.KernelSvc, $"Invalid handle 0x{Handle:x8}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Invalid handle 0x{handle:x8}!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle); return; } - if (Obj is KSession Session) + if (obj is KSession session) { - Session.Dispose(); + session.Dispose(); } - else if (Obj is KTransferMemory TransferMemory) + else if (obj is KTransferMemory transferMemory) { - Process.MemoryManager.ResetTransferMemory( - TransferMemory.Address, - TransferMemory.Size); + _process.MemoryManager.ResetTransferMemory( + transferMemory.Address, + transferMemory.Size); } - ThreadState.X0 = 0; + threadState.X0 = 0; } - private void ResetSignal64(CpuThreadState ThreadState) + private void ResetSignal64(CpuThreadState threadState) { - ThreadState.X0 = (ulong)ResetSignal((int)ThreadState.X0); + threadState.X0 = (ulong)ResetSignal((int)threadState.X0); } - private KernelResult ResetSignal(int Handle) + private KernelResult ResetSignal(int handle) { - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = _system.Scheduler.GetCurrentProcess(); - KReadableEvent ReadableEvent = CurrentProcess.HandleTable.GetObject(Handle); + KReadableEvent readableEvent = currentProcess.HandleTable.GetObject(handle); - KernelResult Result; + KernelResult result; - if (ReadableEvent != null) + if (readableEvent != null) { - Result = ReadableEvent.ClearIfSignaled(); + result = readableEvent.ClearIfSignaled(); } else { - KProcess Process = CurrentProcess.HandleTable.GetKProcess(Handle); + KProcess process = currentProcess.HandleTable.GetKProcess(handle); - if (Process != null) + if (process != null) { - Result = Process.ClearIfNotExited(); + result = process.ClearIfNotExited(); } else { - Result = KernelResult.InvalidHandle; + result = KernelResult.InvalidHandle; } } - if (Result == KernelResult.InvalidState) + if (result == KernelResult.InvalidState) { - Logger.PrintDebug(LogClass.KernelSvc, "Operation failed with error: " + Result + "!"); + Logger.PrintDebug(LogClass.KernelSvc, "Operation failed with error: " + result + "!"); } - else if (Result != KernelResult.Success) + else if (result != KernelResult.Success) { - Logger.PrintWarning(LogClass.KernelSvc, "Operation failed with error: " + Result + "!"); + Logger.PrintWarning(LogClass.KernelSvc, "Operation failed with error: " + result + "!"); } - return Result; + return result; } - private void SvcGetSystemTick(CpuThreadState ThreadState) + private void SvcGetSystemTick(CpuThreadState threadState) { - ThreadState.X0 = ThreadState.CntpctEl0; + threadState.X0 = threadState.CntpctEl0; } - private void SvcConnectToNamedPort(CpuThreadState ThreadState) + private void SvcConnectToNamedPort(CpuThreadState threadState) { - long StackPtr = (long)ThreadState.X0; - long NamePtr = (long)ThreadState.X1; + long stackPtr = (long)threadState.X0; + long namePtr = (long)threadState.X1; - string Name = MemoryHelper.ReadAsciiString(Memory, NamePtr, 8); + string name = MemoryHelper.ReadAsciiString(_memory, namePtr, 8); //TODO: Validate that app has perms to access the service, and that the service //actually exists, return error codes otherwise. - KSession Session = new KSession(ServiceFactory.MakeService(System, Name), Name); + KSession session = new KSession(ServiceFactory.MakeService(_system, name), name); - if (Process.HandleTable.GenerateHandle(Session, out int Handle) != KernelResult.Success) + if (_process.HandleTable.GenerateHandle(session, out int handle) != KernelResult.Success) { throw new InvalidOperationException("Out of handles!"); } - ThreadState.X0 = 0; - ThreadState.X1 = (uint)Handle; + threadState.X0 = 0; + threadState.X1 = (uint)handle; } - private void SvcSendSyncRequest(CpuThreadState ThreadState) + private void SvcSendSyncRequest(CpuThreadState threadState) { - SendSyncRequest(ThreadState, ThreadState.Tpidr, 0x100, (int)ThreadState.X0); + SendSyncRequest(threadState, threadState.Tpidr, 0x100, (int)threadState.X0); } - private void SvcSendSyncRequestWithUserBuffer(CpuThreadState ThreadState) + private void SvcSendSyncRequestWithUserBuffer(CpuThreadState threadState) { SendSyncRequest( - ThreadState, - (long)ThreadState.X0, - (long)ThreadState.X1, - (int)ThreadState.X2); + threadState, + (long)threadState.X0, + (long)threadState.X1, + (int)threadState.X2); } - private void SendSyncRequest(CpuThreadState ThreadState, long MessagePtr, long Size, int Handle) + private void SendSyncRequest(CpuThreadState threadState, long messagePtr, long size, int handle) { - byte[] MessageData = Memory.ReadBytes(MessagePtr, Size); + byte[] messageData = _memory.ReadBytes(messagePtr, size); - KSession Session = Process.HandleTable.GetObject(Handle); + KSession session = _process.HandleTable.GetObject(handle); - if (Session != null) + if (session != null) { - System.CriticalSection.Enter(); + _system.CriticalSection.Enter(); - KThread CurrentThread = System.Scheduler.GetCurrentThread(); + KThread currentThread = _system.Scheduler.GetCurrentThread(); - CurrentThread.SignaledObj = null; - CurrentThread.ObjSyncResult = 0; + currentThread.SignaledObj = null; + currentThread.ObjSyncResult = 0; - CurrentThread.Reschedule(ThreadSchedState.Paused); + currentThread.Reschedule(ThreadSchedState.Paused); - IpcMessage Message = new IpcMessage(MessageData, MessagePtr); + IpcMessage message = new IpcMessage(messageData, messagePtr); ThreadPool.QueueUserWorkItem(ProcessIpcRequest, new HleIpcMessage( - CurrentThread, - Session, - Message, - MessagePtr)); + currentThread, + session, + message, + messagePtr)); - System.ThreadCounter.AddCount(); + _system.ThreadCounter.AddCount(); - System.CriticalSection.Leave(); + _system.CriticalSection.Leave(); - ThreadState.X0 = (ulong)CurrentThread.ObjSyncResult; + threadState.X0 = (ulong)currentThread.ObjSyncResult; } else { - Logger.PrintWarning(LogClass.KernelSvc, $"Invalid session handle 0x{Handle:x8}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Invalid session handle 0x{handle:x8}!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle); } } - private void ProcessIpcRequest(object State) + private void ProcessIpcRequest(object state) { - HleIpcMessage IpcMessage = (HleIpcMessage)State; + HleIpcMessage ipcMessage = (HleIpcMessage)state; - IpcMessage.Thread.ObjSyncResult = (int)IpcHandler.IpcCall( - Device, - Process, - Memory, - IpcMessage.Session, - IpcMessage.Message, - IpcMessage.MessagePtr); + ipcMessage.Thread.ObjSyncResult = (int)IpcHandler.IpcCall( + _device, + _process, + _memory, + ipcMessage.Session, + ipcMessage.Message, + ipcMessage.MessagePtr); - System.ThreadCounter.Signal(); + _system.ThreadCounter.Signal(); - IpcMessage.Thread.Reschedule(ThreadSchedState.Running); + ipcMessage.Thread.Reschedule(ThreadSchedState.Running); } - private void GetProcessId64(CpuThreadState ThreadState) + private void GetProcessId64(CpuThreadState threadState) { - int Handle = (int)ThreadState.X1; + int handle = (int)threadState.X1; - KernelResult Result = GetProcessId(Handle, out long Pid); + KernelResult result = GetProcessId(handle, out long pid); - ThreadState.X0 = (ulong)Result; - ThreadState.X1 = (ulong)Pid; + threadState.X0 = (ulong)result; + threadState.X1 = (ulong)pid; } - private KernelResult GetProcessId(int Handle, out long Pid) + private KernelResult GetProcessId(int handle, out long pid) { - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = _system.Scheduler.GetCurrentProcess(); - KProcess Process = CurrentProcess.HandleTable.GetKProcess(Handle); + KProcess process = currentProcess.HandleTable.GetKProcess(handle); - if (Process == null) + if (process == null) { - KThread Thread = CurrentProcess.HandleTable.GetKThread(Handle); + KThread thread = currentProcess.HandleTable.GetKThread(handle); - if (Thread != null) + if (thread != null) { - Process = Thread.Owner; + process = thread.Owner; } //TODO: KDebugEvent. } - Pid = Process?.Pid ?? 0; + pid = process?.Pid ?? 0; - return Process != null + return process != null ? KernelResult.Success : KernelResult.InvalidHandle; } - private void SvcBreak(CpuThreadState ThreadState) + private void SvcBreak(CpuThreadState threadState) { - long Reason = (long)ThreadState.X0; - long Unknown = (long)ThreadState.X1; - long Info = (long)ThreadState.X2; + long reason = (long)threadState.X0; + long unknown = (long)threadState.X1; + long info = (long)threadState.X2; - KThread CurrentThread = System.Scheduler.GetCurrentThread(); + KThread currentThread = _system.Scheduler.GetCurrentThread(); - if ((Reason & (1 << 31)) == 0) + if ((reason & (1 << 31)) == 0) { - CurrentThread.PrintGuestStackTrace(); + currentThread.PrintGuestStackTrace(); throw new GuestBrokeExecutionException(); } @@ -301,40 +301,40 @@ namespace Ryujinx.HLE.HOS.Kernel { Logger.PrintInfo(LogClass.KernelSvc, "Debugger triggered."); - CurrentThread.PrintGuestStackTrace(); + currentThread.PrintGuestStackTrace(); } } - private void SvcOutputDebugString(CpuThreadState ThreadState) + private void SvcOutputDebugString(CpuThreadState threadState) { - long Position = (long)ThreadState.X0; - long Size = (long)ThreadState.X1; + long position = (long)threadState.X0; + long size = (long)threadState.X1; - string Str = MemoryHelper.ReadAsciiString(Memory, Position, Size); + string str = MemoryHelper.ReadAsciiString(_memory, position, size); - Logger.PrintWarning(LogClass.KernelSvc, Str); + Logger.PrintWarning(LogClass.KernelSvc, str); - ThreadState.X0 = 0; + threadState.X0 = 0; } - private void GetInfo64(CpuThreadState ThreadState) + private void GetInfo64(CpuThreadState threadState) { - long StackPtr = (long)ThreadState.X0; - uint Id = (uint)ThreadState.X1; - int Handle = (int)ThreadState.X2; - long SubId = (long)ThreadState.X3; + long stackPtr = (long)threadState.X0; + uint id = (uint)threadState.X1; + int handle = (int)threadState.X2; + long subId = (long)threadState.X3; - KernelResult Result = GetInfo(Id, Handle, SubId, out long Value); + KernelResult result = GetInfo(id, handle, subId, out long value); - ThreadState.X0 = (ulong)Result; - ThreadState.X1 = (ulong)Value; + threadState.X0 = (ulong)result; + threadState.X1 = (ulong)value; } - private KernelResult GetInfo(uint Id, int Handle, long SubId, out long Value) + private KernelResult GetInfo(uint id, int handle, long subId, out long value) { - Value = 0; + value = 0; - switch (Id) + switch (id) { case 0: case 1: @@ -355,62 +355,62 @@ namespace Ryujinx.HLE.HOS.Kernel case 21: case 22: { - if (SubId != 0) + if (subId != 0) { return KernelResult.InvalidCombination; } - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = _system.Scheduler.GetCurrentProcess(); - KProcess Process = CurrentProcess.HandleTable.GetKProcess(Handle); + KProcess process = currentProcess.HandleTable.GetKProcess(handle); - if (Process == null) + if (process == null) { return KernelResult.InvalidHandle; } - switch (Id) + switch (id) { - case 0: Value = Process.Capabilities.AllowedCpuCoresMask; break; - case 1: Value = Process.Capabilities.AllowedThreadPriosMask; break; + case 0: value = process.Capabilities.AllowedCpuCoresMask; break; + case 1: value = process.Capabilities.AllowedThreadPriosMask; break; - case 2: Value = (long)Process.MemoryManager.AliasRegionStart; break; - case 3: Value = (long)(Process.MemoryManager.AliasRegionEnd - - Process.MemoryManager.AliasRegionStart); break; + case 2: value = (long)process.MemoryManager.AliasRegionStart; break; + case 3: value = (long)(process.MemoryManager.AliasRegionEnd - + process.MemoryManager.AliasRegionStart); break; - case 4: Value = (long)Process.MemoryManager.HeapRegionStart; break; - case 5: Value = (long)(Process.MemoryManager.HeapRegionEnd - - Process.MemoryManager.HeapRegionStart); break; + case 4: value = (long)process.MemoryManager.HeapRegionStart; break; + case 5: value = (long)(process.MemoryManager.HeapRegionEnd - + process.MemoryManager.HeapRegionStart); break; - case 6: Value = (long)Process.GetMemoryCapacity(); break; + case 6: value = (long)process.GetMemoryCapacity(); break; - case 7: Value = (long)Process.GetMemoryUsage(); break; + case 7: value = (long)process.GetMemoryUsage(); break; - case 12: Value = (long)Process.MemoryManager.GetAddrSpaceBaseAddr(); break; + case 12: value = (long)process.MemoryManager.GetAddrSpaceBaseAddr(); break; - case 13: Value = (long)Process.MemoryManager.GetAddrSpaceSize(); break; + case 13: value = (long)process.MemoryManager.GetAddrSpaceSize(); break; - case 14: Value = (long)Process.MemoryManager.StackRegionStart; break; - case 15: Value = (long)(Process.MemoryManager.StackRegionEnd - - Process.MemoryManager.StackRegionStart); break; + case 14: value = (long)process.MemoryManager.StackRegionStart; break; + case 15: value = (long)(process.MemoryManager.StackRegionEnd - + process.MemoryManager.StackRegionStart); break; - case 16: Value = (long)Process.PersonalMmHeapPagesCount * KMemoryManager.PageSize; break; + case 16: value = (long)process.PersonalMmHeapPagesCount * KMemoryManager.PageSize; break; case 17: - if (Process.PersonalMmHeapPagesCount != 0) + if (process.PersonalMmHeapPagesCount != 0) { - Value = Process.MemoryManager.GetMmUsedPages() * KMemoryManager.PageSize; + value = process.MemoryManager.GetMmUsedPages() * KMemoryManager.PageSize; } break; - case 18: Value = Process.TitleId; break; + case 18: value = process.TitleId; break; - case 20: Value = (long)Process.UserExceptionContextAddress; break; + case 20: value = (long)process.UserExceptionContextAddress; break; - case 21: Value = (long)Process.GetMemoryCapacityWithoutPersonalMmHeap(); break; + case 21: value = (long)process.GetMemoryCapacityWithoutPersonalMmHeap(); break; - case 22: Value = (long)Process.GetMemoryUsageWithoutPersonalMmHeap(); break; + case 22: value = (long)process.GetMemoryUsageWithoutPersonalMmHeap(); break; } break; @@ -418,48 +418,48 @@ namespace Ryujinx.HLE.HOS.Kernel case 8: { - if (Handle != 0) + if (handle != 0) { return KernelResult.InvalidHandle; } - if (SubId != 0) + if (subId != 0) { return KernelResult.InvalidCombination; } - Value = System.Scheduler.GetCurrentProcess().Debug ? 1 : 0; + value = _system.Scheduler.GetCurrentProcess().Debug ? 1 : 0; break; } case 9: { - if (Handle != 0) + if (handle != 0) { return KernelResult.InvalidHandle; } - if (SubId != 0) + if (subId != 0) { return KernelResult.InvalidCombination; } - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = _system.Scheduler.GetCurrentProcess(); - if (CurrentProcess.ResourceLimit != null) + if (currentProcess.ResourceLimit != null) { - KHandleTable HandleTable = CurrentProcess.HandleTable; - KResourceLimit ResourceLimit = CurrentProcess.ResourceLimit; + KHandleTable handleTable = currentProcess.HandleTable; + KResourceLimit resourceLimit = currentProcess.ResourceLimit; - KernelResult Result = HandleTable.GenerateHandle(ResourceLimit, out int ResLimHandle); + KernelResult result = handleTable.GenerateHandle(resourceLimit, out int resLimHandle); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - return Result; + return result; } - Value = (uint)ResLimHandle; + value = (uint)resLimHandle; } break; @@ -467,84 +467,84 @@ namespace Ryujinx.HLE.HOS.Kernel case 10: { - if (Handle != 0) + if (handle != 0) { return KernelResult.InvalidHandle; } - int CurrentCore = System.Scheduler.GetCurrentThread().CurrentCore; + int currentCore = _system.Scheduler.GetCurrentThread().CurrentCore; - if (SubId != -1 && SubId != CurrentCore) + if (subId != -1 && subId != currentCore) { return KernelResult.InvalidCombination; } - Value = System.Scheduler.CoreContexts[CurrentCore].TotalIdleTimeTicks; + value = _system.Scheduler.CoreContexts[currentCore].TotalIdleTimeTicks; break; } case 11: { - if (Handle != 0) + if (handle != 0) { return KernelResult.InvalidHandle; } - if ((ulong)SubId > 3) + if ((ulong)subId > 3) { return KernelResult.InvalidCombination; } - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = _system.Scheduler.GetCurrentProcess(); - Value = CurrentProcess.RandomEntropy[SubId]; + value = currentProcess.RandomEntropy[subId]; break; } case 0xf0000002u: { - if (SubId < -1 || SubId > 3) + if (subId < -1 || subId > 3) { return KernelResult.InvalidCombination; } - KThread Thread = System.Scheduler.GetCurrentProcess().HandleTable.GetKThread(Handle); + KThread thread = _system.Scheduler.GetCurrentProcess().HandleTable.GetKThread(handle); - if (Thread == null) + if (thread == null) { return KernelResult.InvalidHandle; } - KThread CurrentThread = System.Scheduler.GetCurrentThread(); + KThread currentThread = _system.Scheduler.GetCurrentThread(); - int CurrentCore = CurrentThread.CurrentCore; + int currentCore = currentThread.CurrentCore; - if (SubId != -1 && SubId != CurrentCore) + if (subId != -1 && subId != currentCore) { return KernelResult.Success; } - KCoreContext CoreContext = System.Scheduler.CoreContexts[CurrentCore]; + KCoreContext coreContext = _system.Scheduler.CoreContexts[currentCore]; - long TimeDelta = PerformanceCounter.ElapsedMilliseconds - CoreContext.LastContextSwitchTime; + long timeDelta = PerformanceCounter.ElapsedMilliseconds - coreContext.LastContextSwitchTime; - if (SubId != -1) + if (subId != -1) { - Value = KTimeManager.ConvertMillisecondsToTicks(TimeDelta); + value = KTimeManager.ConvertMillisecondsToTicks(timeDelta); } else { - long TotalTimeRunning = Thread.TotalTimeRunning; + long totalTimeRunning = thread.TotalTimeRunning; - if (Thread == CurrentThread) + if (thread == currentThread) { - TotalTimeRunning += TimeDelta; + totalTimeRunning += timeDelta; } - Value = KTimeManager.ConvertMillisecondsToTicks(TotalTimeRunning); + value = KTimeManager.ConvertMillisecondsToTicks(totalTimeRunning); } break; @@ -556,144 +556,144 @@ namespace Ryujinx.HLE.HOS.Kernel return KernelResult.Success; } - private void CreateEvent64(CpuThreadState State) + private void CreateEvent64(CpuThreadState state) { - KernelResult Result = CreateEvent(out int WEventHandle, out int REventHandle); + KernelResult result = CreateEvent(out int wEventHandle, out int rEventHandle); - State.X0 = (ulong)Result; - State.X1 = (ulong)WEventHandle; - State.X2 = (ulong)REventHandle; + state.X0 = (ulong)result; + state.X1 = (ulong)wEventHandle; + state.X2 = (ulong)rEventHandle; } - private KernelResult CreateEvent(out int WEventHandle, out int REventHandle) + private KernelResult CreateEvent(out int wEventHandle, out int rEventHandle) { - KEvent Event = new KEvent(System); + KEvent Event = new KEvent(_system); - KernelResult Result = Process.HandleTable.GenerateHandle(Event.WritableEvent, out WEventHandle); + KernelResult result = _process.HandleTable.GenerateHandle(Event.WritableEvent, out wEventHandle); - if (Result == KernelResult.Success) + if (result == KernelResult.Success) { - Result = Process.HandleTable.GenerateHandle(Event.ReadableEvent, out REventHandle); + result = _process.HandleTable.GenerateHandle(Event.ReadableEvent, out rEventHandle); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - Process.HandleTable.CloseHandle(WEventHandle); + _process.HandleTable.CloseHandle(wEventHandle); } } else { - REventHandle = 0; + rEventHandle = 0; } - return Result; + return result; } - private void GetProcessList64(CpuThreadState State) + private void GetProcessList64(CpuThreadState state) { - ulong Address = State.X1; - int MaxOut = (int)State.X2; + ulong address = state.X1; + int maxOut = (int)state.X2; - KernelResult Result = GetProcessList(Address, MaxOut, out int Count); + KernelResult result = GetProcessList(address, maxOut, out int count); - State.X0 = (ulong)Result; - State.X1 = (ulong)Count; + state.X0 = (ulong)result; + state.X1 = (ulong)count; } - private KernelResult GetProcessList(ulong Address, int MaxCount, out int Count) + private KernelResult GetProcessList(ulong address, int maxCount, out int count) { - Count = 0; + count = 0; - if ((MaxCount >> 28) != 0) + if ((maxCount >> 28) != 0) { return KernelResult.MaximumExceeded; } - if (MaxCount != 0) + if (maxCount != 0) { - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = _system.Scheduler.GetCurrentProcess(); - ulong CopySize = (ulong)MaxCount * 8; + ulong copySize = (ulong)maxCount * 8; - if (Address + CopySize <= Address) + if (address + copySize <= address) { return KernelResult.InvalidMemState; } - if (CurrentProcess.MemoryManager.OutsideAddrSpace(Address, CopySize)) + if (currentProcess.MemoryManager.OutsideAddrSpace(address, copySize)) { return KernelResult.InvalidMemState; } } - int CopyCount = 0; + int copyCount = 0; - lock (System.Processes) + lock (_system.Processes) { - foreach (KProcess Process in System.Processes.Values) + foreach (KProcess process in _system.Processes.Values) { - if (CopyCount < MaxCount) + if (copyCount < maxCount) { - if (!KernelTransfer.KernelToUserInt64(System, (long)Address + CopyCount * 8, Process.Pid)) + if (!KernelTransfer.KernelToUserInt64(_system, (long)address + copyCount * 8, process.Pid)) { return KernelResult.UserCopyFailed; } } - CopyCount++; + copyCount++; } } - Count = CopyCount; + count = copyCount; return KernelResult.Success; } - private void GetSystemInfo64(CpuThreadState State) + private void GetSystemInfo64(CpuThreadState state) { - uint Id = (uint)State.X1; - int Handle = (int)State.X2; - long SubId = (long)State.X3; + uint id = (uint)state.X1; + int handle = (int)state.X2; + long subId = (long)state.X3; - KernelResult Result = GetSystemInfo(Id, Handle, SubId, out long Value); + KernelResult result = GetSystemInfo(id, handle, subId, out long value); - State.X0 = (ulong)Result; - State.X1 = (ulong)Value; + state.X0 = (ulong)result; + state.X1 = (ulong)value; } - private KernelResult GetSystemInfo(uint Id, int Handle, long SubId, out long Value) + private KernelResult GetSystemInfo(uint id, int handle, long subId, out long value) { - Value = 0; + value = 0; - if (Id > 2) + if (id > 2) { return KernelResult.InvalidEnumValue; } - if (Handle != 0) + if (handle != 0) { return KernelResult.InvalidHandle; } - if (Id < 2) + if (id < 2) { - if ((ulong)SubId > 3) + if ((ulong)subId > 3) { return KernelResult.InvalidCombination; } - KMemoryRegionManager Region = System.MemoryRegions[SubId]; + KMemoryRegionManager region = _system.MemoryRegions[subId]; - switch (Id) + switch (id) { //Memory region capacity. - case 0: Value = (long)Region.Size; break; + case 0: value = (long)region.Size; break; //Memory region free space. case 1: { - ulong FreePagesCount = Region.GetFreePages(); + ulong freePagesCount = region.GetFreePages(); - Value = (long)(FreePagesCount * KMemoryManager.PageSize); + value = (long)(freePagesCount * KMemoryManager.PageSize); break; } @@ -701,127 +701,127 @@ namespace Ryujinx.HLE.HOS.Kernel } else /* if (Id == 2) */ { - if ((ulong)SubId > 1) + if ((ulong)subId > 1) { return KernelResult.InvalidCombination; } - switch (SubId) + switch (subId) { - case 0: Value = System.PrivilegedProcessLowestId; break; - case 1: Value = System.PrivilegedProcessHighestId; break; + case 0: value = _system.PrivilegedProcessLowestId; break; + case 1: value = _system.PrivilegedProcessHighestId; break; } } return KernelResult.Success; } - private void CreatePort64(CpuThreadState State) + private void CreatePort64(CpuThreadState state) { - int MaxSessions = (int)State.X2; - bool IsLight = (State.X3 & 1) != 0; - long NameAddress = (long)State.X4; + int maxSessions = (int)state.X2; + bool isLight = (state.X3 & 1) != 0; + long nameAddress = (long)state.X4; - KernelResult Result = CreatePort( - MaxSessions, - IsLight, - NameAddress, - out int ServerPortHandle, - out int ClientPortHandle); + KernelResult result = CreatePort( + maxSessions, + isLight, + nameAddress, + out int serverPortHandle, + out int clientPortHandle); - State.X0 = (ulong)Result; - State.X1 = (ulong)ServerPortHandle; - State.X2 = (ulong)ClientPortHandle; + state.X0 = (ulong)result; + state.X1 = (ulong)serverPortHandle; + state.X2 = (ulong)clientPortHandle; } private KernelResult CreatePort( - int MaxSessions, - bool IsLight, - long NameAddress, - out int ServerPortHandle, - out int ClientPortHandle) + int maxSessions, + bool isLight, + long nameAddress, + out int serverPortHandle, + out int clientPortHandle) { - ServerPortHandle = ClientPortHandle = 0; + serverPortHandle = clientPortHandle = 0; - if (MaxSessions < 1) + if (maxSessions < 1) { return KernelResult.MaximumExceeded; } - KPort Port = new KPort(System); + KPort port = new KPort(_system); - Port.Initialize(MaxSessions, IsLight, NameAddress); + port.Initialize(maxSessions, isLight, nameAddress); - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = _system.Scheduler.GetCurrentProcess(); - KernelResult Result = CurrentProcess.HandleTable.GenerateHandle(Port.ClientPort, out ClientPortHandle); + KernelResult result = currentProcess.HandleTable.GenerateHandle(port.ClientPort, out clientPortHandle); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - return Result; + return result; } - Result = CurrentProcess.HandleTable.GenerateHandle(Port.ServerPort, out ServerPortHandle); + result = currentProcess.HandleTable.GenerateHandle(port.ServerPort, out serverPortHandle); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - CurrentProcess.HandleTable.CloseHandle(ClientPortHandle); + currentProcess.HandleTable.CloseHandle(clientPortHandle); } - return Result; + return result; } - private void ManageNamedPort64(CpuThreadState State) + private void ManageNamedPort64(CpuThreadState state) { - long NameAddress = (long)State.X1; - int MaxSessions = (int)State.X2; + long nameAddress = (long)state.X1; + int maxSessions = (int)state.X2; - KernelResult Result = ManageNamedPort(NameAddress, MaxSessions, out int Handle); + KernelResult result = ManageNamedPort(nameAddress, maxSessions, out int handle); - State.X0 = (ulong)Result; - State.X1 = (ulong)Handle; + state.X0 = (ulong)result; + state.X1 = (ulong)handle; } - private KernelResult ManageNamedPort(long NameAddress, int MaxSessions, out int Handle) + private KernelResult ManageNamedPort(long nameAddress, int maxSessions, out int handle) { - Handle = 0; + handle = 0; - if (!KernelTransfer.UserToKernelString(System, NameAddress, 12, out string Name)) + if (!KernelTransfer.UserToKernelString(_system, nameAddress, 12, out string name)) { return KernelResult.UserCopyFailed; } - if (MaxSessions < 0 || Name.Length > 11) + if (maxSessions < 0 || name.Length > 11) { return KernelResult.MaximumExceeded; } - if (MaxSessions == 0) + if (maxSessions == 0) { - return KClientPort.RemoveName(System, Name); + return KClientPort.RemoveName(_system, name); } - KPort Port = new KPort(System); + KPort port = new KPort(_system); - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = _system.Scheduler.GetCurrentProcess(); - KernelResult Result = CurrentProcess.HandleTable.GenerateHandle(Port.ServerPort, out Handle); + KernelResult result = currentProcess.HandleTable.GenerateHandle(port.ServerPort, out handle); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - return Result; + return result; } - Port.Initialize(MaxSessions, false, 0); + port.Initialize(maxSessions, false, 0); - Result = Port.SetName(Name); + result = port.SetName(name); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - CurrentProcess.HandleTable.CloseHandle(Handle); + currentProcess.HandleTable.CloseHandle(handle); } - return Result; + return result; } } } diff --git a/Ryujinx.HLE/HOS/Kernel/SvcThread.cs b/Ryujinx.HLE/HOS/Kernel/SvcThread.cs index ded8f8dc..0121303d 100644 --- a/Ryujinx.HLE/HOS/Kernel/SvcThread.cs +++ b/Ryujinx.HLE/HOS/Kernel/SvcThread.cs @@ -7,458 +7,458 @@ namespace Ryujinx.HLE.HOS.Kernel { partial class SvcHandler { - private void CreateThread64(CpuThreadState ThreadState) + private void CreateThread64(CpuThreadState threadState) { - ulong Entrypoint = ThreadState.X1; - ulong ArgsPtr = ThreadState.X2; - ulong StackTop = ThreadState.X3; - int Priority = (int)ThreadState.X4; - int CpuCore = (int)ThreadState.X5; + ulong entrypoint = threadState.X1; + ulong argsPtr = threadState.X2; + ulong stackTop = threadState.X3; + int priority = (int)threadState.X4; + int cpuCore = (int)threadState.X5; - KernelResult Result = CreateThread(Entrypoint, ArgsPtr, StackTop, Priority, CpuCore, out int Handle); + KernelResult result = CreateThread(entrypoint, argsPtr, stackTop, priority, cpuCore, out int handle); - ThreadState.X0 = (ulong)Result; - ThreadState.X1 = (ulong)Handle; + threadState.X0 = (ulong)result; + threadState.X1 = (ulong)handle; } private KernelResult CreateThread( - ulong Entrypoint, - ulong ArgsPtr, - ulong StackTop, - int Priority, - int CpuCore, - out int Handle) + ulong entrypoint, + ulong argsPtr, + ulong stackTop, + int priority, + int cpuCore, + out int handle) { - Handle = 0; + handle = 0; - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = _system.Scheduler.GetCurrentProcess(); - if (CpuCore == -2) + if (cpuCore == -2) { - CpuCore = CurrentProcess.DefaultCpuCore; + cpuCore = currentProcess.DefaultCpuCore; } - if ((uint)CpuCore >= KScheduler.CpuCoresCount || !CurrentProcess.IsCpuCoreAllowed(CpuCore)) + if ((uint)cpuCore >= KScheduler.CpuCoresCount || !currentProcess.IsCpuCoreAllowed(cpuCore)) { return KernelResult.InvalidCpuCore; } - if ((uint)Priority >= KScheduler.PrioritiesCount || !CurrentProcess.IsPriorityAllowed(Priority)) + if ((uint)priority >= KScheduler.PrioritiesCount || !currentProcess.IsPriorityAllowed(priority)) { return KernelResult.InvalidPriority; } - long Timeout = KTimeManager.ConvertMillisecondsToNanoseconds(100); + long timeout = KTimeManager.ConvertMillisecondsToNanoseconds(100); - if (CurrentProcess.ResourceLimit != null && - !CurrentProcess.ResourceLimit.Reserve(LimitableResource.Thread, 1, Timeout)) + if (currentProcess.ResourceLimit != null && + !currentProcess.ResourceLimit.Reserve(LimitableResource.Thread, 1, timeout)) { return KernelResult.ResLimitExceeded; } - KThread Thread = new KThread(System); + KThread thread = new KThread(_system); - KernelResult Result = CurrentProcess.InitializeThread( - Thread, - Entrypoint, - ArgsPtr, - StackTop, - Priority, - CpuCore); + KernelResult result = currentProcess.InitializeThread( + thread, + entrypoint, + argsPtr, + stackTop, + priority, + cpuCore); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - CurrentProcess.ResourceLimit?.Release(LimitableResource.Thread, 1); + currentProcess.ResourceLimit?.Release(LimitableResource.Thread, 1); - return Result; + return result; } - Result = Process.HandleTable.GenerateHandle(Thread, out Handle); + result = _process.HandleTable.GenerateHandle(thread, out handle); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - Thread.Terminate(); + thread.Terminate(); - CurrentProcess.ResourceLimit?.Release(LimitableResource.Thread, 1); + currentProcess.ResourceLimit?.Release(LimitableResource.Thread, 1); } - return Result; + return result; } - private void SvcStartThread(CpuThreadState ThreadState) + private void SvcStartThread(CpuThreadState threadState) { - int Handle = (int)ThreadState.X0; + int handle = (int)threadState.X0; - KThread Thread = Process.HandleTable.GetObject(Handle); + KThread thread = _process.HandleTable.GetObject(handle); - if (Thread != null) + if (thread != null) { - KernelResult Result = Thread.Start(); + KernelResult result = thread.Start(); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error \"{Result}\"."); + Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error \"{result}\"."); } - ThreadState.X0 = (ulong)Result; + threadState.X0 = (ulong)result; } else { - Logger.PrintWarning(LogClass.KernelSvc, $"Invalid thread handle 0x{Handle:x8}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Invalid thread handle 0x{handle:x8}!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle); } } - private void SvcExitThread(CpuThreadState ThreadState) + private void SvcExitThread(CpuThreadState threadState) { - KThread CurrentThread = System.Scheduler.GetCurrentThread(); + KThread currentThread = _system.Scheduler.GetCurrentThread(); - System.Scheduler.ExitThread(CurrentThread); + _system.Scheduler.ExitThread(currentThread); - CurrentThread.Exit(); + currentThread.Exit(); } - private void SvcSleepThread(CpuThreadState ThreadState) + private void SvcSleepThread(CpuThreadState threadState) { - long Timeout = (long)ThreadState.X0; + long timeout = (long)threadState.X0; - Logger.PrintDebug(LogClass.KernelSvc, "Timeout = 0x" + Timeout.ToString("x16")); + Logger.PrintDebug(LogClass.KernelSvc, "Timeout = 0x" + timeout.ToString("x16")); - KThread CurrentThread = System.Scheduler.GetCurrentThread(); + KThread currentThread = _system.Scheduler.GetCurrentThread(); - if (Timeout < 1) + if (timeout < 1) { - switch (Timeout) + switch (timeout) { - case 0: CurrentThread.Yield(); break; - case -1: CurrentThread.YieldWithLoadBalancing(); break; - case -2: CurrentThread.YieldAndWaitForLoadBalancing(); break; + case 0: currentThread.Yield(); break; + case -1: currentThread.YieldWithLoadBalancing(); break; + case -2: currentThread.YieldAndWaitForLoadBalancing(); break; } } else { - CurrentThread.Sleep(Timeout); + currentThread.Sleep(timeout); - ThreadState.X0 = 0; + threadState.X0 = 0; } } - private void SvcGetThreadPriority(CpuThreadState ThreadState) + private void SvcGetThreadPriority(CpuThreadState threadState) { - int Handle = (int)ThreadState.X1; + int handle = (int)threadState.X1; - KThread Thread = Process.HandleTable.GetKThread(Handle); + KThread thread = _process.HandleTable.GetKThread(handle); - if (Thread != null) + if (thread != null) { - ThreadState.X0 = 0; - ThreadState.X1 = (ulong)Thread.DynamicPriority; + threadState.X0 = 0; + threadState.X1 = (ulong)thread.DynamicPriority; } else { - Logger.PrintWarning(LogClass.KernelSvc, $"Invalid thread handle 0x{Handle:x8}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Invalid thread handle 0x{handle:x8}!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle); } } - private void SvcSetThreadPriority(CpuThreadState ThreadState) + private void SvcSetThreadPriority(CpuThreadState threadState) { - int Handle = (int)ThreadState.X0; - int Priority = (int)ThreadState.X1; + int handle = (int)threadState.X0; + int priority = (int)threadState.X1; Logger.PrintDebug(LogClass.KernelSvc, - "Handle = 0x" + Handle .ToString("x8") + ", " + - "Priority = 0x" + Priority.ToString("x8")); + "Handle = 0x" + handle .ToString("x8") + ", " + + "Priority = 0x" + priority.ToString("x8")); //TODO: NPDM check. - KThread Thread = Process.HandleTable.GetKThread(Handle); + KThread thread = _process.HandleTable.GetKThread(handle); - if (Thread == null) + if (thread == null) { - Logger.PrintWarning(LogClass.KernelSvc, $"Invalid thread handle 0x{Handle:x8}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Invalid thread handle 0x{handle:x8}!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle); return; } - Thread.SetPriority(Priority); + thread.SetPriority(priority); - ThreadState.X0 = 0; + threadState.X0 = 0; } - private void SvcGetThreadCoreMask(CpuThreadState ThreadState) + private void SvcGetThreadCoreMask(CpuThreadState threadState) { - int Handle = (int)ThreadState.X2; + int handle = (int)threadState.X2; - Logger.PrintDebug(LogClass.KernelSvc, "Handle = 0x" + Handle.ToString("x8")); + Logger.PrintDebug(LogClass.KernelSvc, "Handle = 0x" + handle.ToString("x8")); - KThread Thread = Process.HandleTable.GetKThread(Handle); + KThread thread = _process.HandleTable.GetKThread(handle); - if (Thread != null) + if (thread != null) { - ThreadState.X0 = 0; - ThreadState.X1 = (ulong)Thread.PreferredCore; - ThreadState.X2 = (ulong)Thread.AffinityMask; + threadState.X0 = 0; + threadState.X1 = (ulong)thread.PreferredCore; + threadState.X2 = (ulong)thread.AffinityMask; } else { - Logger.PrintWarning(LogClass.KernelSvc, $"Invalid thread handle 0x{Handle:x8}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Invalid thread handle 0x{handle:x8}!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle); } } - private void SetThreadCoreMask64(CpuThreadState ThreadState) + private void SetThreadCoreMask64(CpuThreadState threadState) { - int Handle = (int)ThreadState.X0; - int PreferredCore = (int)ThreadState.X1; - long AffinityMask = (long)ThreadState.X2; + int handle = (int)threadState.X0; + int preferredCore = (int)threadState.X1; + long affinityMask = (long)threadState.X2; Logger.PrintDebug(LogClass.KernelSvc, - "Handle = 0x" + Handle .ToString("x8") + ", " + - "PreferredCore = 0x" + PreferredCore.ToString("x8") + ", " + - "AffinityMask = 0x" + AffinityMask .ToString("x16")); + "Handle = 0x" + handle .ToString("x8") + ", " + + "PreferredCore = 0x" + preferredCore.ToString("x8") + ", " + + "AffinityMask = 0x" + affinityMask .ToString("x16")); - KernelResult Result = SetThreadCoreMask(Handle, PreferredCore, AffinityMask); + KernelResult result = SetThreadCoreMask(handle, preferredCore, affinityMask); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error \"{Result}\"."); + Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error \"{result}\"."); } - ThreadState.X0 = (ulong)Result; + threadState.X0 = (ulong)result; } - private KernelResult SetThreadCoreMask(int Handle, int PreferredCore, long AffinityMask) + private KernelResult SetThreadCoreMask(int handle, int preferredCore, long affinityMask) { - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = _system.Scheduler.GetCurrentProcess(); - if (PreferredCore == -2) + if (preferredCore == -2) { - PreferredCore = CurrentProcess.DefaultCpuCore; + preferredCore = currentProcess.DefaultCpuCore; - AffinityMask = 1 << PreferredCore; + affinityMask = 1 << preferredCore; } else { - if ((CurrentProcess.Capabilities.AllowedCpuCoresMask | AffinityMask) != - CurrentProcess.Capabilities.AllowedCpuCoresMask) + if ((currentProcess.Capabilities.AllowedCpuCoresMask | affinityMask) != + currentProcess.Capabilities.AllowedCpuCoresMask) { return KernelResult.InvalidCpuCore; } - if (AffinityMask == 0) + if (affinityMask == 0) { return KernelResult.InvalidCombination; } - if ((uint)PreferredCore > 3) + if ((uint)preferredCore > 3) { - if ((PreferredCore | 2) != -1) + if ((preferredCore | 2) != -1) { return KernelResult.InvalidCpuCore; } } - else if ((AffinityMask & (1 << PreferredCore)) == 0) + else if ((affinityMask & (1 << preferredCore)) == 0) { return KernelResult.InvalidCombination; } } - KThread Thread = Process.HandleTable.GetKThread(Handle); + KThread thread = _process.HandleTable.GetKThread(handle); - if (Thread == null) + if (thread == null) { return KernelResult.InvalidHandle; } - return Thread.SetCoreAndAffinityMask(PreferredCore, AffinityMask); + return thread.SetCoreAndAffinityMask(preferredCore, affinityMask); } - private void SvcGetCurrentProcessorNumber(CpuThreadState ThreadState) + private void SvcGetCurrentProcessorNumber(CpuThreadState threadState) { - ThreadState.X0 = (ulong)System.Scheduler.GetCurrentThread().CurrentCore; + threadState.X0 = (ulong)_system.Scheduler.GetCurrentThread().CurrentCore; } - private void SvcGetThreadId(CpuThreadState ThreadState) + private void SvcGetThreadId(CpuThreadState threadState) { - int Handle = (int)ThreadState.X1; + int handle = (int)threadState.X1; - KThread Thread = Process.HandleTable.GetKThread(Handle); + KThread thread = _process.HandleTable.GetKThread(handle); - if (Thread != null) + if (thread != null) { - ThreadState.X0 = 0; - ThreadState.X1 = (ulong)Thread.ThreadUid; + threadState.X0 = 0; + threadState.X1 = (ulong)thread.ThreadUid; } else { - Logger.PrintWarning(LogClass.KernelSvc, $"Invalid thread handle 0x{Handle:x8}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Invalid thread handle 0x{handle:x8}!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle); } } - private void SvcSetThreadActivity(CpuThreadState ThreadState) + private void SvcSetThreadActivity(CpuThreadState threadState) { - int Handle = (int)ThreadState.X0; - bool Pause = (int)ThreadState.X1 == 1; + int handle = (int)threadState.X0; + bool pause = (int)threadState.X1 == 1; - KThread Thread = Process.HandleTable.GetObject(Handle); + KThread thread = _process.HandleTable.GetObject(handle); - if (Thread == null) + if (thread == null) { - Logger.PrintWarning(LogClass.KernelSvc, $"Invalid thread handle 0x{Handle:x8}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Invalid thread handle 0x{handle:x8}!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle); return; } - if (Thread.Owner != System.Scheduler.GetCurrentProcess()) + if (thread.Owner != _system.Scheduler.GetCurrentProcess()) { Logger.PrintWarning(LogClass.KernelSvc, $"Invalid thread, it belongs to another process."); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle); return; } - if (Thread == System.Scheduler.GetCurrentThread()) + if (thread == _system.Scheduler.GetCurrentThread()) { Logger.PrintWarning(LogClass.KernelSvc, "Invalid thread, current thread is not accepted."); - ThreadState.X0 = (ulong)KernelResult.InvalidThread; + threadState.X0 = (ulong)KernelResult.InvalidThread; return; } - long Result = Thread.SetActivity(Pause); + long result = thread.SetActivity(pause); - if (Result != 0) + if (result != 0) { - Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{Result:x}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); } - ThreadState.X0 = (ulong)Result; + threadState.X0 = (ulong)result; } - private void SvcGetThreadContext3(CpuThreadState ThreadState) + private void SvcGetThreadContext3(CpuThreadState threadState) { - long Position = (long)ThreadState.X0; - int Handle = (int)ThreadState.X1; + long position = (long)threadState.X0; + int handle = (int)threadState.X1; - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); - KThread CurrentThread = System.Scheduler.GetCurrentThread(); + KProcess currentProcess = _system.Scheduler.GetCurrentProcess(); + KThread currentThread = _system.Scheduler.GetCurrentThread(); - KThread Thread = Process.HandleTable.GetObject(Handle); + KThread thread = _process.HandleTable.GetObject(handle); - if (Thread == null) + if (thread == null) { - Logger.PrintWarning(LogClass.KernelSvc, $"Invalid thread handle 0x{Handle:x8}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Invalid thread handle 0x{handle:x8}!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle); return; } - if (Thread.Owner != CurrentProcess) + if (thread.Owner != currentProcess) { Logger.PrintWarning(LogClass.KernelSvc, $"Invalid thread, it belongs to another process."); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle); return; } - if (CurrentThread == Thread) + if (currentThread == thread) { Logger.PrintWarning(LogClass.KernelSvc, "Invalid thread, current thread is not accepted."); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidThread); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidThread); return; } - Memory.WriteUInt64(Position + 0x0, Thread.Context.ThreadState.X0); - Memory.WriteUInt64(Position + 0x8, Thread.Context.ThreadState.X1); - Memory.WriteUInt64(Position + 0x10, Thread.Context.ThreadState.X2); - Memory.WriteUInt64(Position + 0x18, Thread.Context.ThreadState.X3); - Memory.WriteUInt64(Position + 0x20, Thread.Context.ThreadState.X4); - Memory.WriteUInt64(Position + 0x28, Thread.Context.ThreadState.X5); - Memory.WriteUInt64(Position + 0x30, Thread.Context.ThreadState.X6); - Memory.WriteUInt64(Position + 0x38, Thread.Context.ThreadState.X7); - Memory.WriteUInt64(Position + 0x40, Thread.Context.ThreadState.X8); - Memory.WriteUInt64(Position + 0x48, Thread.Context.ThreadState.X9); - Memory.WriteUInt64(Position + 0x50, Thread.Context.ThreadState.X10); - Memory.WriteUInt64(Position + 0x58, Thread.Context.ThreadState.X11); - Memory.WriteUInt64(Position + 0x60, Thread.Context.ThreadState.X12); - Memory.WriteUInt64(Position + 0x68, Thread.Context.ThreadState.X13); - Memory.WriteUInt64(Position + 0x70, Thread.Context.ThreadState.X14); - Memory.WriteUInt64(Position + 0x78, Thread.Context.ThreadState.X15); - Memory.WriteUInt64(Position + 0x80, Thread.Context.ThreadState.X16); - Memory.WriteUInt64(Position + 0x88, Thread.Context.ThreadState.X17); - Memory.WriteUInt64(Position + 0x90, Thread.Context.ThreadState.X18); - Memory.WriteUInt64(Position + 0x98, Thread.Context.ThreadState.X19); - Memory.WriteUInt64(Position + 0xa0, Thread.Context.ThreadState.X20); - Memory.WriteUInt64(Position + 0xa8, Thread.Context.ThreadState.X21); - Memory.WriteUInt64(Position + 0xb0, Thread.Context.ThreadState.X22); - Memory.WriteUInt64(Position + 0xb8, Thread.Context.ThreadState.X23); - Memory.WriteUInt64(Position + 0xc0, Thread.Context.ThreadState.X24); - Memory.WriteUInt64(Position + 0xc8, Thread.Context.ThreadState.X25); - Memory.WriteUInt64(Position + 0xd0, Thread.Context.ThreadState.X26); - Memory.WriteUInt64(Position + 0xd8, Thread.Context.ThreadState.X27); - Memory.WriteUInt64(Position + 0xe0, Thread.Context.ThreadState.X28); - Memory.WriteUInt64(Position + 0xe8, Thread.Context.ThreadState.X29); - Memory.WriteUInt64(Position + 0xf0, Thread.Context.ThreadState.X30); - Memory.WriteUInt64(Position + 0xf8, Thread.Context.ThreadState.X31); + _memory.WriteUInt64(position + 0x0, thread.Context.ThreadState.X0); + _memory.WriteUInt64(position + 0x8, thread.Context.ThreadState.X1); + _memory.WriteUInt64(position + 0x10, thread.Context.ThreadState.X2); + _memory.WriteUInt64(position + 0x18, thread.Context.ThreadState.X3); + _memory.WriteUInt64(position + 0x20, thread.Context.ThreadState.X4); + _memory.WriteUInt64(position + 0x28, thread.Context.ThreadState.X5); + _memory.WriteUInt64(position + 0x30, thread.Context.ThreadState.X6); + _memory.WriteUInt64(position + 0x38, thread.Context.ThreadState.X7); + _memory.WriteUInt64(position + 0x40, thread.Context.ThreadState.X8); + _memory.WriteUInt64(position + 0x48, thread.Context.ThreadState.X9); + _memory.WriteUInt64(position + 0x50, thread.Context.ThreadState.X10); + _memory.WriteUInt64(position + 0x58, thread.Context.ThreadState.X11); + _memory.WriteUInt64(position + 0x60, thread.Context.ThreadState.X12); + _memory.WriteUInt64(position + 0x68, thread.Context.ThreadState.X13); + _memory.WriteUInt64(position + 0x70, thread.Context.ThreadState.X14); + _memory.WriteUInt64(position + 0x78, thread.Context.ThreadState.X15); + _memory.WriteUInt64(position + 0x80, thread.Context.ThreadState.X16); + _memory.WriteUInt64(position + 0x88, thread.Context.ThreadState.X17); + _memory.WriteUInt64(position + 0x90, thread.Context.ThreadState.X18); + _memory.WriteUInt64(position + 0x98, thread.Context.ThreadState.X19); + _memory.WriteUInt64(position + 0xa0, thread.Context.ThreadState.X20); + _memory.WriteUInt64(position + 0xa8, thread.Context.ThreadState.X21); + _memory.WriteUInt64(position + 0xb0, thread.Context.ThreadState.X22); + _memory.WriteUInt64(position + 0xb8, thread.Context.ThreadState.X23); + _memory.WriteUInt64(position + 0xc0, thread.Context.ThreadState.X24); + _memory.WriteUInt64(position + 0xc8, thread.Context.ThreadState.X25); + _memory.WriteUInt64(position + 0xd0, thread.Context.ThreadState.X26); + _memory.WriteUInt64(position + 0xd8, thread.Context.ThreadState.X27); + _memory.WriteUInt64(position + 0xe0, thread.Context.ThreadState.X28); + _memory.WriteUInt64(position + 0xe8, thread.Context.ThreadState.X29); + _memory.WriteUInt64(position + 0xf0, thread.Context.ThreadState.X30); + _memory.WriteUInt64(position + 0xf8, thread.Context.ThreadState.X31); - Memory.WriteInt64(Position + 0x100, Thread.LastPc); + _memory.WriteInt64(position + 0x100, thread.LastPc); - Memory.WriteUInt64(Position + 0x108, (ulong)Thread.Context.ThreadState.Psr); + _memory.WriteUInt64(position + 0x108, (ulong)thread.Context.ThreadState.Psr); - Memory.WriteVector128(Position + 0x110, Thread.Context.ThreadState.V0); - Memory.WriteVector128(Position + 0x120, Thread.Context.ThreadState.V1); - Memory.WriteVector128(Position + 0x130, Thread.Context.ThreadState.V2); - Memory.WriteVector128(Position + 0x140, Thread.Context.ThreadState.V3); - Memory.WriteVector128(Position + 0x150, Thread.Context.ThreadState.V4); - Memory.WriteVector128(Position + 0x160, Thread.Context.ThreadState.V5); - Memory.WriteVector128(Position + 0x170, Thread.Context.ThreadState.V6); - Memory.WriteVector128(Position + 0x180, Thread.Context.ThreadState.V7); - Memory.WriteVector128(Position + 0x190, Thread.Context.ThreadState.V8); - Memory.WriteVector128(Position + 0x1a0, Thread.Context.ThreadState.V9); - Memory.WriteVector128(Position + 0x1b0, Thread.Context.ThreadState.V10); - Memory.WriteVector128(Position + 0x1c0, Thread.Context.ThreadState.V11); - Memory.WriteVector128(Position + 0x1d0, Thread.Context.ThreadState.V12); - Memory.WriteVector128(Position + 0x1e0, Thread.Context.ThreadState.V13); - Memory.WriteVector128(Position + 0x1f0, Thread.Context.ThreadState.V14); - Memory.WriteVector128(Position + 0x200, Thread.Context.ThreadState.V15); - Memory.WriteVector128(Position + 0x210, Thread.Context.ThreadState.V16); - Memory.WriteVector128(Position + 0x220, Thread.Context.ThreadState.V17); - Memory.WriteVector128(Position + 0x230, Thread.Context.ThreadState.V18); - Memory.WriteVector128(Position + 0x240, Thread.Context.ThreadState.V19); - Memory.WriteVector128(Position + 0x250, Thread.Context.ThreadState.V20); - Memory.WriteVector128(Position + 0x260, Thread.Context.ThreadState.V21); - Memory.WriteVector128(Position + 0x270, Thread.Context.ThreadState.V22); - Memory.WriteVector128(Position + 0x280, Thread.Context.ThreadState.V23); - Memory.WriteVector128(Position + 0x290, Thread.Context.ThreadState.V24); - Memory.WriteVector128(Position + 0x2a0, Thread.Context.ThreadState.V25); - Memory.WriteVector128(Position + 0x2b0, Thread.Context.ThreadState.V26); - Memory.WriteVector128(Position + 0x2c0, Thread.Context.ThreadState.V27); - Memory.WriteVector128(Position + 0x2d0, Thread.Context.ThreadState.V28); - Memory.WriteVector128(Position + 0x2e0, Thread.Context.ThreadState.V29); - Memory.WriteVector128(Position + 0x2f0, Thread.Context.ThreadState.V30); - Memory.WriteVector128(Position + 0x300, Thread.Context.ThreadState.V31); + _memory.WriteVector128(position + 0x110, thread.Context.ThreadState.V0); + _memory.WriteVector128(position + 0x120, thread.Context.ThreadState.V1); + _memory.WriteVector128(position + 0x130, thread.Context.ThreadState.V2); + _memory.WriteVector128(position + 0x140, thread.Context.ThreadState.V3); + _memory.WriteVector128(position + 0x150, thread.Context.ThreadState.V4); + _memory.WriteVector128(position + 0x160, thread.Context.ThreadState.V5); + _memory.WriteVector128(position + 0x170, thread.Context.ThreadState.V6); + _memory.WriteVector128(position + 0x180, thread.Context.ThreadState.V7); + _memory.WriteVector128(position + 0x190, thread.Context.ThreadState.V8); + _memory.WriteVector128(position + 0x1a0, thread.Context.ThreadState.V9); + _memory.WriteVector128(position + 0x1b0, thread.Context.ThreadState.V10); + _memory.WriteVector128(position + 0x1c0, thread.Context.ThreadState.V11); + _memory.WriteVector128(position + 0x1d0, thread.Context.ThreadState.V12); + _memory.WriteVector128(position + 0x1e0, thread.Context.ThreadState.V13); + _memory.WriteVector128(position + 0x1f0, thread.Context.ThreadState.V14); + _memory.WriteVector128(position + 0x200, thread.Context.ThreadState.V15); + _memory.WriteVector128(position + 0x210, thread.Context.ThreadState.V16); + _memory.WriteVector128(position + 0x220, thread.Context.ThreadState.V17); + _memory.WriteVector128(position + 0x230, thread.Context.ThreadState.V18); + _memory.WriteVector128(position + 0x240, thread.Context.ThreadState.V19); + _memory.WriteVector128(position + 0x250, thread.Context.ThreadState.V20); + _memory.WriteVector128(position + 0x260, thread.Context.ThreadState.V21); + _memory.WriteVector128(position + 0x270, thread.Context.ThreadState.V22); + _memory.WriteVector128(position + 0x280, thread.Context.ThreadState.V23); + _memory.WriteVector128(position + 0x290, thread.Context.ThreadState.V24); + _memory.WriteVector128(position + 0x2a0, thread.Context.ThreadState.V25); + _memory.WriteVector128(position + 0x2b0, thread.Context.ThreadState.V26); + _memory.WriteVector128(position + 0x2c0, thread.Context.ThreadState.V27); + _memory.WriteVector128(position + 0x2d0, thread.Context.ThreadState.V28); + _memory.WriteVector128(position + 0x2e0, thread.Context.ThreadState.V29); + _memory.WriteVector128(position + 0x2f0, thread.Context.ThreadState.V30); + _memory.WriteVector128(position + 0x300, thread.Context.ThreadState.V31); - Memory.WriteInt32(Position + 0x310, Thread.Context.ThreadState.Fpcr); - Memory.WriteInt32(Position + 0x314, Thread.Context.ThreadState.Fpsr); - Memory.WriteInt64(Position + 0x318, Thread.Context.ThreadState.Tpidr); + _memory.WriteInt32(position + 0x310, thread.Context.ThreadState.Fpcr); + _memory.WriteInt32(position + 0x314, thread.Context.ThreadState.Fpsr); + _memory.WriteInt64(position + 0x318, thread.Context.ThreadState.Tpidr); - ThreadState.X0 = 0; + threadState.X0 = 0; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/SvcThreadSync.cs b/Ryujinx.HLE/HOS/Kernel/SvcThreadSync.cs index 3935df5d..11cfffe9 100644 --- a/Ryujinx.HLE/HOS/Kernel/SvcThreadSync.cs +++ b/Ryujinx.HLE/HOS/Kernel/SvcThreadSync.cs @@ -8,366 +8,366 @@ namespace Ryujinx.HLE.HOS.Kernel { partial class SvcHandler { - private void SvcWaitSynchronization(CpuThreadState ThreadState) + private void SvcWaitSynchronization(CpuThreadState threadState) { - long HandlesPtr = (long)ThreadState.X1; - int HandlesCount = (int)ThreadState.X2; - long Timeout = (long)ThreadState.X3; + long handlesPtr = (long)threadState.X1; + int handlesCount = (int)threadState.X2; + long timeout = (long)threadState.X3; Logger.PrintDebug(LogClass.KernelSvc, - "HandlesPtr = 0x" + HandlesPtr .ToString("x16") + ", " + - "HandlesCount = 0x" + HandlesCount.ToString("x8") + ", " + - "Timeout = 0x" + Timeout .ToString("x16")); + "HandlesPtr = 0x" + handlesPtr .ToString("x16") + ", " + + "HandlesCount = 0x" + handlesCount.ToString("x8") + ", " + + "Timeout = 0x" + timeout .ToString("x16")); - if ((uint)HandlesCount > 0x40) + if ((uint)handlesCount > 0x40) { - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.CountOutOfRange); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.CountOutOfRange); return; } - List SyncObjs = new List(); + List syncObjs = new List(); - for (int Index = 0; Index < HandlesCount; Index++) + for (int index = 0; index < handlesCount; index++) { - int Handle = Memory.ReadInt32(HandlesPtr + Index * 4); + int handle = _memory.ReadInt32(handlesPtr + index * 4); - Logger.PrintDebug(LogClass.KernelSvc, $"Sync handle 0x{Handle:x8}"); + Logger.PrintDebug(LogClass.KernelSvc, $"Sync handle 0x{handle:x8}"); - KSynchronizationObject SyncObj = Process.HandleTable.GetObject(Handle); + KSynchronizationObject syncObj = _process.HandleTable.GetObject(handle); - if (SyncObj == null) + if (syncObj == null) { break; } - SyncObjs.Add(SyncObj); + syncObjs.Add(syncObj); } - int HndIndex = (int)ThreadState.X1; + int hndIndex = (int)threadState.X1; - ulong High = ThreadState.X1 & (0xffffffffUL << 32); + ulong high = threadState.X1 & (0xffffffffUL << 32); - long Result = System.Synchronization.WaitFor(SyncObjs.ToArray(), Timeout, ref HndIndex); + long result = _system.Synchronization.WaitFor(syncObjs.ToArray(), timeout, ref hndIndex); - if (Result != 0) + if (result != 0) { - if (Result == MakeError(ErrorModule.Kernel, KernelErr.Timeout) || - Result == MakeError(ErrorModule.Kernel, KernelErr.Cancelled)) + if (result == MakeError(ErrorModule.Kernel, KernelErr.Timeout) || + result == MakeError(ErrorModule.Kernel, KernelErr.Cancelled)) { - Logger.PrintDebug(LogClass.KernelSvc, $"Operation failed with error 0x{Result:x}!"); + Logger.PrintDebug(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); } else { - Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{Result:x}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); } } - ThreadState.X0 = (ulong)Result; - ThreadState.X1 = (uint)HndIndex | High; + threadState.X0 = (ulong)result; + threadState.X1 = (uint)hndIndex | high; } - private void SvcCancelSynchronization(CpuThreadState ThreadState) + private void SvcCancelSynchronization(CpuThreadState threadState) { - int ThreadHandle = (int)ThreadState.X0; + int threadHandle = (int)threadState.X0; - Logger.PrintDebug(LogClass.KernelSvc, "ThreadHandle = 0x" + ThreadHandle.ToString("x8")); + Logger.PrintDebug(LogClass.KernelSvc, "ThreadHandle = 0x" + threadHandle.ToString("x8")); - KThread Thread = Process.HandleTable.GetKThread(ThreadHandle); + KThread thread = _process.HandleTable.GetKThread(threadHandle); - if (Thread == null) + if (thread == null) { - Logger.PrintWarning(LogClass.KernelSvc, $"Invalid thread handle 0x{ThreadHandle:x8}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Invalid thread handle 0x{threadHandle:x8}!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle); return; } - Thread.CancelSynchronization(); + thread.CancelSynchronization(); - ThreadState.X0 = 0; + threadState.X0 = 0; } - private void SvcArbitrateLock(CpuThreadState ThreadState) + private void SvcArbitrateLock(CpuThreadState threadState) { - int OwnerHandle = (int)ThreadState.X0; - long MutexAddress = (long)ThreadState.X1; - int RequesterHandle = (int)ThreadState.X2; + int ownerHandle = (int)threadState.X0; + long mutexAddress = (long)threadState.X1; + int requesterHandle = (int)threadState.X2; Logger.PrintDebug(LogClass.KernelSvc, - "OwnerHandle = 0x" + OwnerHandle .ToString("x8") + ", " + - "MutexAddress = 0x" + MutexAddress .ToString("x16") + ", " + - "RequesterHandle = 0x" + RequesterHandle.ToString("x8")); + "OwnerHandle = 0x" + ownerHandle .ToString("x8") + ", " + + "MutexAddress = 0x" + mutexAddress .ToString("x16") + ", " + + "RequesterHandle = 0x" + requesterHandle.ToString("x8")); - if (IsPointingInsideKernel(MutexAddress)) + if (IsPointingInsideKernel(mutexAddress)) { - Logger.PrintWarning(LogClass.KernelSvc, $"Invalid mutex address 0x{MutexAddress:x16}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Invalid mutex address 0x{mutexAddress:x16}!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); return; } - if (IsAddressNotWordAligned(MutexAddress)) + if (IsAddressNotWordAligned(mutexAddress)) { - Logger.PrintWarning(LogClass.KernelSvc, $"Unaligned mutex address 0x{MutexAddress:x16}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Unaligned mutex address 0x{mutexAddress:x16}!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidAddress); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidAddress); return; } - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = _system.Scheduler.GetCurrentProcess(); - long Result = CurrentProcess.AddressArbiter.ArbitrateLock(OwnerHandle, MutexAddress, RequesterHandle); + long result = currentProcess.AddressArbiter.ArbitrateLock(ownerHandle, mutexAddress, requesterHandle); - if (Result != 0) + if (result != 0) { - Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{Result:x}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); } - ThreadState.X0 = (ulong)Result; + threadState.X0 = (ulong)result; } - private void SvcArbitrateUnlock(CpuThreadState ThreadState) + private void SvcArbitrateUnlock(CpuThreadState threadState) { - long MutexAddress = (long)ThreadState.X0; + long mutexAddress = (long)threadState.X0; - Logger.PrintDebug(LogClass.KernelSvc, "MutexAddress = 0x" + MutexAddress.ToString("x16")); + Logger.PrintDebug(LogClass.KernelSvc, "MutexAddress = 0x" + mutexAddress.ToString("x16")); - if (IsPointingInsideKernel(MutexAddress)) + if (IsPointingInsideKernel(mutexAddress)) { - Logger.PrintWarning(LogClass.KernelSvc, $"Invalid mutex address 0x{MutexAddress:x16}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Invalid mutex address 0x{mutexAddress:x16}!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); return; } - if (IsAddressNotWordAligned(MutexAddress)) + if (IsAddressNotWordAligned(mutexAddress)) { - Logger.PrintWarning(LogClass.KernelSvc, $"Unaligned mutex address 0x{MutexAddress:x16}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Unaligned mutex address 0x{mutexAddress:x16}!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidAddress); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidAddress); return; } - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = _system.Scheduler.GetCurrentProcess(); - long Result = CurrentProcess.AddressArbiter.ArbitrateUnlock(MutexAddress); + long result = currentProcess.AddressArbiter.ArbitrateUnlock(mutexAddress); - if (Result != 0) + if (result != 0) { - Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{Result:x}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); } - ThreadState.X0 = (ulong)Result; + threadState.X0 = (ulong)result; } - private void SvcWaitProcessWideKeyAtomic(CpuThreadState ThreadState) + private void SvcWaitProcessWideKeyAtomic(CpuThreadState threadState) { - long MutexAddress = (long)ThreadState.X0; - long CondVarAddress = (long)ThreadState.X1; - int ThreadHandle = (int)ThreadState.X2; - long Timeout = (long)ThreadState.X3; + long mutexAddress = (long)threadState.X0; + long condVarAddress = (long)threadState.X1; + int threadHandle = (int)threadState.X2; + long timeout = (long)threadState.X3; Logger.PrintDebug(LogClass.KernelSvc, - "MutexAddress = 0x" + MutexAddress .ToString("x16") + ", " + - "CondVarAddress = 0x" + CondVarAddress.ToString("x16") + ", " + - "ThreadHandle = 0x" + ThreadHandle .ToString("x8") + ", " + - "Timeout = 0x" + Timeout .ToString("x16")); + "MutexAddress = 0x" + mutexAddress .ToString("x16") + ", " + + "CondVarAddress = 0x" + condVarAddress.ToString("x16") + ", " + + "ThreadHandle = 0x" + threadHandle .ToString("x8") + ", " + + "Timeout = 0x" + timeout .ToString("x16")); - if (IsPointingInsideKernel(MutexAddress)) + if (IsPointingInsideKernel(mutexAddress)) { - Logger.PrintWarning(LogClass.KernelSvc, $"Invalid mutex address 0x{MutexAddress:x16}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Invalid mutex address 0x{mutexAddress:x16}!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); return; } - if (IsAddressNotWordAligned(MutexAddress)) + if (IsAddressNotWordAligned(mutexAddress)) { - Logger.PrintWarning(LogClass.KernelSvc, $"Unaligned mutex address 0x{MutexAddress:x16}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Unaligned mutex address 0x{mutexAddress:x16}!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidAddress); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidAddress); return; } - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = _system.Scheduler.GetCurrentProcess(); - long Result = CurrentProcess.AddressArbiter.WaitProcessWideKeyAtomic( - MutexAddress, - CondVarAddress, - ThreadHandle, - Timeout); + long result = currentProcess.AddressArbiter.WaitProcessWideKeyAtomic( + mutexAddress, + condVarAddress, + threadHandle, + timeout); - if (Result != 0) + if (result != 0) { - if (Result == MakeError(ErrorModule.Kernel, KernelErr.Timeout)) + if (result == MakeError(ErrorModule.Kernel, KernelErr.Timeout)) { - Logger.PrintDebug(LogClass.KernelSvc, $"Operation failed with error 0x{Result:x}!"); + Logger.PrintDebug(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); } else { - Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{Result:x}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); } } - ThreadState.X0 = (ulong)Result; + threadState.X0 = (ulong)result; } - private void SvcSignalProcessWideKey(CpuThreadState ThreadState) + private void SvcSignalProcessWideKey(CpuThreadState threadState) { - long Address = (long)ThreadState.X0; - int Count = (int)ThreadState.X1; + long address = (long)threadState.X0; + int count = (int)threadState.X1; Logger.PrintDebug(LogClass.KernelSvc, - "Address = 0x" + Address.ToString("x16") + ", " + - "Count = 0x" + Count .ToString("x8")); + "Address = 0x" + address.ToString("x16") + ", " + + "Count = 0x" + count .ToString("x8")); - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = _system.Scheduler.GetCurrentProcess(); - CurrentProcess.AddressArbiter.SignalProcessWideKey(Address, Count); + currentProcess.AddressArbiter.SignalProcessWideKey(address, count); - ThreadState.X0 = 0; + threadState.X0 = 0; } - private void SvcWaitForAddress(CpuThreadState ThreadState) + private void SvcWaitForAddress(CpuThreadState threadState) { - long Address = (long)ThreadState.X0; - ArbitrationType Type = (ArbitrationType)ThreadState.X1; - int Value = (int)ThreadState.X2; - long Timeout = (long)ThreadState.X3; + long address = (long)threadState.X0; + ArbitrationType type = (ArbitrationType)threadState.X1; + int value = (int)threadState.X2; + long timeout = (long)threadState.X3; Logger.PrintDebug(LogClass.KernelSvc, - "Address = 0x" + Address.ToString("x16") + ", " + - "Type = " + Type .ToString() + ", " + - "Value = 0x" + Value .ToString("x8") + ", " + - "Timeout = 0x" + Timeout.ToString("x16")); + "Address = 0x" + address.ToString("x16") + ", " + + "Type = " + type .ToString() + ", " + + "Value = 0x" + value .ToString("x8") + ", " + + "Timeout = 0x" + timeout.ToString("x16")); - if (IsPointingInsideKernel(Address)) + if (IsPointingInsideKernel(address)) { - Logger.PrintWarning(LogClass.KernelSvc, $"Invalid address 0x{Address:x16}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Invalid address 0x{address:x16}!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); return; } - if (IsAddressNotWordAligned(Address)) + if (IsAddressNotWordAligned(address)) { - Logger.PrintWarning(LogClass.KernelSvc, $"Unaligned address 0x{Address:x16}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Unaligned address 0x{address:x16}!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidAddress); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidAddress); return; } - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = _system.Scheduler.GetCurrentProcess(); - long Result; + long result; - switch (Type) + switch (type) { case ArbitrationType.WaitIfLessThan: - Result = CurrentProcess.AddressArbiter.WaitForAddressIfLessThan(Address, Value, false, Timeout); + result = currentProcess.AddressArbiter.WaitForAddressIfLessThan(address, value, false, timeout); break; case ArbitrationType.DecrementAndWaitIfLessThan: - Result = CurrentProcess.AddressArbiter.WaitForAddressIfLessThan(Address, Value, true, Timeout); + result = currentProcess.AddressArbiter.WaitForAddressIfLessThan(address, value, true, timeout); break; case ArbitrationType.WaitIfEqual: - Result = CurrentProcess.AddressArbiter.WaitForAddressIfEqual(Address, Value, Timeout); + result = currentProcess.AddressArbiter.WaitForAddressIfEqual(address, value, timeout); break; default: - Result = MakeError(ErrorModule.Kernel, KernelErr.InvalidEnumValue); + result = MakeError(ErrorModule.Kernel, KernelErr.InvalidEnumValue); break; } - if (Result != 0) + if (result != 0) { - Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{Result:x}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); } - ThreadState.X0 = (ulong)Result; + threadState.X0 = (ulong)result; } - private void SvcSignalToAddress(CpuThreadState ThreadState) + private void SvcSignalToAddress(CpuThreadState threadState) { - long Address = (long)ThreadState.X0; - SignalType Type = (SignalType)ThreadState.X1; - int Value = (int)ThreadState.X2; - int Count = (int)ThreadState.X3; + long address = (long)threadState.X0; + SignalType type = (SignalType)threadState.X1; + int value = (int)threadState.X2; + int count = (int)threadState.X3; Logger.PrintDebug(LogClass.KernelSvc, - "Address = 0x" + Address.ToString("x16") + ", " + - "Type = " + Type .ToString() + ", " + - "Value = 0x" + Value .ToString("x8") + ", " + - "Count = 0x" + Count .ToString("x8")); + "Address = 0x" + address.ToString("x16") + ", " + + "Type = " + type .ToString() + ", " + + "Value = 0x" + value .ToString("x8") + ", " + + "Count = 0x" + count .ToString("x8")); - if (IsPointingInsideKernel(Address)) + if (IsPointingInsideKernel(address)) { - Logger.PrintWarning(LogClass.KernelSvc, $"Invalid address 0x{Address:x16}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Invalid address 0x{address:x16}!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); return; } - if (IsAddressNotWordAligned(Address)) + if (IsAddressNotWordAligned(address)) { - Logger.PrintWarning(LogClass.KernelSvc, $"Unaligned address 0x{Address:x16}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Unaligned address 0x{address:x16}!"); - ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidAddress); + threadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidAddress); return; } - KProcess CurrentProcess = System.Scheduler.GetCurrentProcess(); + KProcess currentProcess = _system.Scheduler.GetCurrentProcess(); - long Result; + long result; - switch (Type) + switch (type) { case SignalType.Signal: - Result = CurrentProcess.AddressArbiter.Signal(Address, Count); + result = currentProcess.AddressArbiter.Signal(address, count); break; case SignalType.SignalAndIncrementIfEqual: - Result = CurrentProcess.AddressArbiter.SignalAndIncrementIfEqual(Address, Value, Count); + result = currentProcess.AddressArbiter.SignalAndIncrementIfEqual(address, value, count); break; case SignalType.SignalAndModifyIfEqual: - Result = CurrentProcess.AddressArbiter.SignalAndModifyIfEqual(Address, Value, Count); + result = currentProcess.AddressArbiter.SignalAndModifyIfEqual(address, value, count); break; default: - Result = MakeError(ErrorModule.Kernel, KernelErr.InvalidEnumValue); + result = MakeError(ErrorModule.Kernel, KernelErr.InvalidEnumValue); break; } - if (Result != 0) + if (result != 0) { - Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{Result:x}!"); + Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); } - ThreadState.X0 = (ulong)Result; + threadState.X0 = (ulong)result; } - private bool IsPointingInsideKernel(long Address) + private bool IsPointingInsideKernel(long address) { - return ((ulong)Address + 0x1000000000) < 0xffffff000; + return ((ulong)address + 0x1000000000) < 0xffffff000; } - private bool IsAddressNotWordAligned(long Address) + private bool IsAddressNotWordAligned(long address) { - return (Address & 3) != 0; + return (address & 3) != 0; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/ProgramLoader.cs b/Ryujinx.HLE/HOS/ProgramLoader.cs index ddacd3fd..00fc6b93 100644 --- a/Ryujinx.HLE/HOS/ProgramLoader.cs +++ b/Ryujinx.HLE/HOS/ProgramLoader.cs @@ -15,278 +15,278 @@ namespace Ryujinx.HLE.HOS private const int ArgsDataSize = 0x9000; private const int ArgsTotalSize = ArgsHeaderSize + ArgsDataSize; - public static bool LoadKernelInitalProcess(Horizon System, KernelInitialProcess Kip) + public static bool LoadKernelInitalProcess(Horizon system, KernelInitialProcess kip) { - int EndOffset = Kip.DataOffset + Kip.Data.Length; + int endOffset = kip.DataOffset + kip.Data.Length; - if (Kip.BssSize != 0) + if (kip.BssSize != 0) { - EndOffset = Kip.BssOffset + Kip.BssSize; + endOffset = kip.BssOffset + kip.BssSize; } - int CodeSize = BitUtils.AlignUp(Kip.TextOffset + EndOffset, KMemoryManager.PageSize); + int codeSize = BitUtils.AlignUp(kip.TextOffset + endOffset, KMemoryManager.PageSize); - int CodePagesCount = CodeSize / KMemoryManager.PageSize; + int codePagesCount = codeSize / KMemoryManager.PageSize; - ulong CodeBaseAddress = Kip.Addr39Bits ? 0x8000000UL : 0x200000UL; + ulong codeBaseAddress = kip.Addr39Bits ? 0x8000000UL : 0x200000UL; - ulong CodeAddress = CodeBaseAddress + (ulong)Kip.TextOffset; + ulong codeAddress = codeBaseAddress + (ulong)kip.TextOffset; - int MmuFlags = 0; + int mmuFlags = 0; if (AslrEnabled) { //TODO: Randomization. - MmuFlags |= 0x20; + mmuFlags |= 0x20; } - if (Kip.Addr39Bits) + if (kip.Addr39Bits) { - MmuFlags |= (int)AddressSpaceType.Addr39Bits << 1; + mmuFlags |= (int)AddressSpaceType.Addr39Bits << 1; } - if (Kip.Is64Bits) + if (kip.Is64Bits) { - MmuFlags |= 1; + mmuFlags |= 1; } - ProcessCreationInfo CreationInfo = new ProcessCreationInfo( - Kip.Name, - Kip.ProcessCategory, - Kip.TitleId, - CodeAddress, - CodePagesCount, - MmuFlags, + ProcessCreationInfo creationInfo = new ProcessCreationInfo( + kip.Name, + kip.ProcessCategory, + kip.TitleId, + codeAddress, + codePagesCount, + mmuFlags, 0, 0); - MemoryRegion MemRegion = Kip.IsService + MemoryRegion memRegion = kip.IsService ? MemoryRegion.Service : MemoryRegion.Application; - KMemoryRegionManager Region = System.MemoryRegions[(int)MemRegion]; + KMemoryRegionManager region = system.MemoryRegions[(int)memRegion]; - KernelResult Result = Region.AllocatePages((ulong)CodePagesCount, false, out KPageList PageList); + KernelResult result = region.AllocatePages((ulong)codePagesCount, false, out KPageList pageList); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - Logger.PrintError(LogClass.Loader, $"Process initialization returned error \"{Result}\"."); + Logger.PrintError(LogClass.Loader, $"Process initialization returned error \"{result}\"."); return false; } - KProcess Process = new KProcess(System); + KProcess process = new KProcess(system); - Result = Process.InitializeKip( - CreationInfo, - Kip.Capabilities, - PageList, - System.ResourceLimit, - MemRegion); + result = process.InitializeKip( + creationInfo, + kip.Capabilities, + pageList, + system.ResourceLimit, + memRegion); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - Logger.PrintError(LogClass.Loader, $"Process initialization returned error \"{Result}\"."); + Logger.PrintError(LogClass.Loader, $"Process initialization returned error \"{result}\"."); return false; } - Result = LoadIntoMemory(Process, Kip, CodeBaseAddress); + result = LoadIntoMemory(process, kip, codeBaseAddress); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - Logger.PrintError(LogClass.Loader, $"Process initialization returned error \"{Result}\"."); + Logger.PrintError(LogClass.Loader, $"Process initialization returned error \"{result}\"."); return false; } - Result = Process.Start(Kip.MainThreadPriority, (ulong)Kip.MainThreadStackSize); + result = process.Start(kip.MainThreadPriority, (ulong)kip.MainThreadStackSize); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - Logger.PrintError(LogClass.Loader, $"Process start returned error \"{Result}\"."); + Logger.PrintError(LogClass.Loader, $"Process start returned error \"{result}\"."); return false; } - System.Processes.Add(Process.Pid, Process); + system.Processes.Add(process.Pid, process); return true; } public static bool LoadStaticObjects( - Horizon System, - Npdm MetaData, - IExecutable[] StaticObjects, - byte[] Arguments = null) + Horizon system, + Npdm metaData, + IExecutable[] staticObjects, + byte[] arguments = null) { - ulong ArgsStart = 0; - int ArgsSize = 0; - ulong CodeStart = 0x8000000; - int CodeSize = 0; + ulong argsStart = 0; + int argsSize = 0; + ulong codeStart = 0x8000000; + int codeSize = 0; - ulong[] NsoBase = new ulong[StaticObjects.Length]; + ulong[] nsoBase = new ulong[staticObjects.Length]; - for (int Index = 0; Index < StaticObjects.Length; Index++) + for (int index = 0; index < staticObjects.Length; index++) { - IExecutable StaticObject = StaticObjects[Index]; + IExecutable staticObject = staticObjects[index]; - int TextEnd = StaticObject.TextOffset + StaticObject.Text.Length; - int ROEnd = StaticObject.ROOffset + StaticObject.RO.Length; - int DataEnd = StaticObject.DataOffset + StaticObject.Data.Length + StaticObject.BssSize; + int textEnd = staticObject.TextOffset + staticObject.Text.Length; + int roEnd = staticObject.RoOffset + staticObject.Ro.Length; + int dataEnd = staticObject.DataOffset + staticObject.Data.Length + staticObject.BssSize; - int NsoSize = TextEnd; + int nsoSize = textEnd; - if ((uint)NsoSize < (uint)ROEnd) + if ((uint)nsoSize < (uint)roEnd) { - NsoSize = ROEnd; + nsoSize = roEnd; } - if ((uint)NsoSize < (uint)DataEnd) + if ((uint)nsoSize < (uint)dataEnd) { - NsoSize = DataEnd; + nsoSize = dataEnd; } - NsoSize = BitUtils.AlignUp(NsoSize, KMemoryManager.PageSize); + nsoSize = BitUtils.AlignUp(nsoSize, KMemoryManager.PageSize); - NsoBase[Index] = CodeStart + (ulong)CodeSize; + nsoBase[index] = codeStart + (ulong)codeSize; - CodeSize += NsoSize; + codeSize += nsoSize; - if (Arguments != null && ArgsSize == 0) + if (arguments != null && argsSize == 0) { - ArgsStart = (ulong)CodeSize; + argsStart = (ulong)codeSize; - ArgsSize = BitUtils.AlignDown(Arguments.Length * 2 + ArgsTotalSize - 1, KMemoryManager.PageSize); + argsSize = BitUtils.AlignDown(arguments.Length * 2 + ArgsTotalSize - 1, KMemoryManager.PageSize); - CodeSize += ArgsSize; + codeSize += argsSize; } } - int CodePagesCount = CodeSize / KMemoryManager.PageSize; + int codePagesCount = codeSize / KMemoryManager.PageSize; - int PersonalMmHeapPagesCount = MetaData.PersonalMmHeapSize / KMemoryManager.PageSize; + int personalMmHeapPagesCount = metaData.PersonalMmHeapSize / KMemoryManager.PageSize; - ProcessCreationInfo CreationInfo = new ProcessCreationInfo( - MetaData.TitleName, - MetaData.ProcessCategory, - MetaData.ACI0.TitleId, - CodeStart, - CodePagesCount, - MetaData.MmuFlags, + ProcessCreationInfo creationInfo = new ProcessCreationInfo( + metaData.TitleName, + metaData.ProcessCategory, + metaData.Aci0.TitleId, + codeStart, + codePagesCount, + metaData.MmuFlags, 0, - PersonalMmHeapPagesCount); + personalMmHeapPagesCount); - KernelResult Result; + KernelResult result; - KResourceLimit ResourceLimit = new KResourceLimit(System); + KResourceLimit resourceLimit = new KResourceLimit(system); - long ApplicationRgSize = (long)System.MemoryRegions[(int)MemoryRegion.Application].Size; + long applicationRgSize = (long)system.MemoryRegions[(int)MemoryRegion.Application].Size; - Result = ResourceLimit.SetLimitValue(LimitableResource.Memory, ApplicationRgSize); - Result |= ResourceLimit.SetLimitValue(LimitableResource.Thread, 608); - Result |= ResourceLimit.SetLimitValue(LimitableResource.Event, 700); - Result |= ResourceLimit.SetLimitValue(LimitableResource.TransferMemory, 128); - Result |= ResourceLimit.SetLimitValue(LimitableResource.Session, 894); + result = resourceLimit.SetLimitValue(LimitableResource.Memory, applicationRgSize); + result |= resourceLimit.SetLimitValue(LimitableResource.Thread, 608); + result |= resourceLimit.SetLimitValue(LimitableResource.Event, 700); + result |= resourceLimit.SetLimitValue(LimitableResource.TransferMemory, 128); + result |= resourceLimit.SetLimitValue(LimitableResource.Session, 894); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { Logger.PrintError(LogClass.Loader, $"Process initialization failed setting resource limit values."); return false; } - KProcess Process = new KProcess(System); + KProcess process = new KProcess(system); - Result = Process.Initialize( - CreationInfo, - MetaData.ACI0.KernelAccessControl.Capabilities, - ResourceLimit, + result = process.Initialize( + creationInfo, + metaData.Aci0.KernelAccessControl.Capabilities, + resourceLimit, MemoryRegion.Application); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - Logger.PrintError(LogClass.Loader, $"Process initialization returned error \"{Result}\"."); + Logger.PrintError(LogClass.Loader, $"Process initialization returned error \"{result}\"."); return false; } - for (int Index = 0; Index < StaticObjects.Length; Index++) + for (int index = 0; index < staticObjects.Length; index++) { - Logger.PrintInfo(LogClass.Loader, $"Loading image {Index} at 0x{NsoBase[Index]:x16}..."); + Logger.PrintInfo(LogClass.Loader, $"Loading image {index} at 0x{nsoBase[index]:x16}..."); - Result = LoadIntoMemory(Process, StaticObjects[Index], NsoBase[Index]); + result = LoadIntoMemory(process, staticObjects[index], nsoBase[index]); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - Logger.PrintError(LogClass.Loader, $"Process initialization returned error \"{Result}\"."); + Logger.PrintError(LogClass.Loader, $"Process initialization returned error \"{result}\"."); return false; } } - Result = Process.Start(MetaData.MainThreadPriority, (ulong)MetaData.MainThreadStackSize); + result = process.Start(metaData.MainThreadPriority, (ulong)metaData.MainThreadStackSize); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - Logger.PrintError(LogClass.Loader, $"Process start returned error \"{Result}\"."); + Logger.PrintError(LogClass.Loader, $"Process start returned error \"{result}\"."); return false; } - System.Processes.Add(Process.Pid, Process); + system.Processes.Add(process.Pid, process); return true; } - private static KernelResult LoadIntoMemory(KProcess Process, IExecutable Image, ulong BaseAddress) + private static KernelResult LoadIntoMemory(KProcess process, IExecutable image, ulong baseAddress) { - ulong TextStart = BaseAddress + (ulong)Image.TextOffset; - ulong ROStart = BaseAddress + (ulong)Image.ROOffset; - ulong DataStart = BaseAddress + (ulong)Image.DataOffset; - ulong BssStart = BaseAddress + (ulong)Image.BssOffset; + ulong textStart = baseAddress + (ulong)image.TextOffset; + ulong roStart = baseAddress + (ulong)image.RoOffset; + ulong dataStart = baseAddress + (ulong)image.DataOffset; + ulong bssStart = baseAddress + (ulong)image.BssOffset; - ulong End = DataStart + (ulong)Image.Data.Length; + ulong end = dataStart + (ulong)image.Data.Length; - if (Image.BssSize != 0) + if (image.BssSize != 0) { - End = BssStart + (ulong)Image.BssSize; + end = bssStart + (ulong)image.BssSize; } - Process.CpuMemory.WriteBytes((long)TextStart, Image.Text); - Process.CpuMemory.WriteBytes((long)ROStart, Image.RO); - Process.CpuMemory.WriteBytes((long)DataStart, Image.Data); + process.CpuMemory.WriteBytes((long)textStart, image.Text); + process.CpuMemory.WriteBytes((long)roStart, image.Ro); + process.CpuMemory.WriteBytes((long)dataStart, image.Data); - MemoryHelper.FillWithZeros(Process.CpuMemory, (long)BssStart, Image.BssSize); + MemoryHelper.FillWithZeros(process.CpuMemory, (long)bssStart, image.BssSize); - KernelResult SetProcessMemoryPermission(ulong Address, ulong Size, MemoryPermission Permission) + KernelResult SetProcessMemoryPermission(ulong address, ulong size, MemoryPermission permission) { - if (Size == 0) + if (size == 0) { return KernelResult.Success; } - Size = BitUtils.AlignUp(Size, KMemoryManager.PageSize); + size = BitUtils.AlignUp(size, KMemoryManager.PageSize); - return Process.MemoryManager.SetProcessMemoryPermission(Address, Size, Permission); + return process.MemoryManager.SetProcessMemoryPermission(address, size, permission); } - KernelResult Result = SetProcessMemoryPermission(TextStart, (ulong)Image.Text.Length, MemoryPermission.ReadAndExecute); + KernelResult result = SetProcessMemoryPermission(textStart, (ulong)image.Text.Length, MemoryPermission.ReadAndExecute); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - return Result; + return result; } - Result = SetProcessMemoryPermission(ROStart, (ulong)Image.RO.Length, MemoryPermission.Read); + result = SetProcessMemoryPermission(roStart, (ulong)image.Ro.Length, MemoryPermission.Read); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - return Result; + return result; } - return SetProcessMemoryPermission(DataStart, End - DataStart, MemoryPermission.ReadAndWrite); + return SetProcessMemoryPermission(dataStart, end - dataStart, MemoryPermission.ReadAndWrite); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/ServiceCtx.cs b/Ryujinx.HLE/HOS/ServiceCtx.cs index 76c426bc..f55e4546 100644 --- a/Ryujinx.HLE/HOS/ServiceCtx.cs +++ b/Ryujinx.HLE/HOS/ServiceCtx.cs @@ -17,23 +17,23 @@ namespace Ryujinx.HLE.HOS public BinaryWriter ResponseData { get; private set; } public ServiceCtx( - Switch Device, - KProcess Process, - MemoryManager Memory, - KSession Session, - IpcMessage Request, - IpcMessage Response, - BinaryReader RequestData, - BinaryWriter ResponseData) + Switch device, + KProcess process, + MemoryManager memory, + KSession session, + IpcMessage request, + IpcMessage response, + BinaryReader requestData, + BinaryWriter responseData) { - this.Device = Device; - this.Process = Process; - this.Memory = Memory; - this.Session = Session; - this.Request = Request; - this.Response = Response; - this.RequestData = RequestData; - this.ResponseData = ResponseData; + Device = device; + Process = process; + Memory = memory; + Session = session; + Request = request; + Response = response; + RequestData = requestData; + ResponseData = responseData; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Services/Acc/IAccountService.cs b/Ryujinx.HLE/HOS/Services/Acc/IAccountService.cs index f920c00b..7ff25c4b 100644 --- a/Ryujinx.HLE/HOS/Services/Acc/IAccountService.cs +++ b/Ryujinx.HLE/HOS/Services/Acc/IAccountService.cs @@ -10,13 +10,13 @@ namespace Ryujinx.HLE.HOS.Services.Acc { class IAccountService : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IAccountService() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, GetUserCount }, { 1, GetUserExistence }, @@ -32,131 +32,131 @@ namespace Ryujinx.HLE.HOS.Services.Acc } // GetUserCount() -> i32 - public long GetUserCount(ServiceCtx Context) + public long GetUserCount(ServiceCtx context) { - Context.ResponseData.Write(Context.Device.System.State.GetUserCount()); + context.ResponseData.Write(context.Device.System.State.GetUserCount()); return 0; } // GetUserExistence(nn::account::Uid) -> bool - public long GetUserExistence(ServiceCtx Context) + public long GetUserExistence(ServiceCtx context) { - UInt128 Uuid = new UInt128( - Context.RequestData.ReadInt64(), - Context.RequestData.ReadInt64()); + UInt128 uuid = new UInt128( + context.RequestData.ReadInt64(), + context.RequestData.ReadInt64()); - Context.ResponseData.Write(Context.Device.System.State.TryGetUser(Uuid, out _)); + context.ResponseData.Write(context.Device.System.State.TryGetUser(uuid, out _)); return 0; } // ListAllUsers() -> array - public long ListAllUsers(ServiceCtx Context) + public long ListAllUsers(ServiceCtx context) { - return WriteUserList(Context, Context.Device.System.State.GetAllUsers()); + return WriteUserList(context, context.Device.System.State.GetAllUsers()); } // ListOpenUsers() -> array - public long ListOpenUsers(ServiceCtx Context) + public long ListOpenUsers(ServiceCtx context) { - return WriteUserList(Context, Context.Device.System.State.GetOpenUsers()); + return WriteUserList(context, context.Device.System.State.GetOpenUsers()); } - private long WriteUserList(ServiceCtx Context, IEnumerable Profiles) + private long WriteUserList(ServiceCtx context, IEnumerable profiles) { - long OutputPosition = Context.Request.RecvListBuff[0].Position; - long OutputSize = Context.Request.RecvListBuff[0].Size; + long outputPosition = context.Request.RecvListBuff[0].Position; + long outputSize = context.Request.RecvListBuff[0].Size; - long Offset = 0; + long offset = 0; - foreach (UserProfile Profile in Profiles) + foreach (UserProfile profile in profiles) { - if ((ulong)Offset + 16 > (ulong)OutputSize) + if ((ulong)offset + 16 > (ulong)outputSize) { break; } - Context.Memory.WriteInt64(OutputPosition, Profile.Uuid.Low); - Context.Memory.WriteInt64(OutputPosition + 8, Profile.Uuid.High); + context.Memory.WriteInt64(outputPosition, profile.Uuid.Low); + context.Memory.WriteInt64(outputPosition + 8, profile.Uuid.High); } return 0; } // GetLastOpenedUser() -> nn::account::Uid - public long GetLastOpenedUser(ServiceCtx Context) + public long GetLastOpenedUser(ServiceCtx context) { - UserProfile LastOpened = Context.Device.System.State.LastOpenUser; + UserProfile lastOpened = context.Device.System.State.LastOpenUser; - LastOpened.Uuid.Write(Context.ResponseData); + lastOpened.Uuid.Write(context.ResponseData); return 0; } // GetProfile(nn::account::Uid) -> object - public long GetProfile(ServiceCtx Context) + public long GetProfile(ServiceCtx context) { - UInt128 Uuid = new UInt128( - Context.RequestData.ReadInt64(), - Context.RequestData.ReadInt64()); + UInt128 uuid = new UInt128( + context.RequestData.ReadInt64(), + context.RequestData.ReadInt64()); - if (!Context.Device.System.State.TryGetUser(Uuid, out UserProfile Profile)) + if (!context.Device.System.State.TryGetUser(uuid, out UserProfile profile)) { - Logger.PrintWarning(LogClass.ServiceAcc, $"User 0x{Uuid} not found!"); + Logger.PrintWarning(LogClass.ServiceAcc, $"User 0x{uuid} not found!"); return MakeError(ErrorModule.Account, AccErr.UserNotFound); } - MakeObject(Context, new IProfile(Profile)); + MakeObject(context, new IProfile(profile)); return 0; } // IsUserRegistrationRequestPermitted(u64, pid) -> bool - public long IsUserRegistrationRequestPermitted(ServiceCtx Context) + public long IsUserRegistrationRequestPermitted(ServiceCtx context) { - long Unknown = Context.RequestData.ReadInt64(); + long unknown = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceAcc, $"Stubbed. Unknown: {Unknown}"); + Logger.PrintStub(LogClass.ServiceAcc, $"Stubbed. Unknown: {unknown}"); - Context.ResponseData.Write(false); + context.ResponseData.Write(false); return 0; } // TrySelectUserWithoutInteraction(bool) -> nn::account::Uid - public long TrySelectUserWithoutInteraction(ServiceCtx Context) + public long TrySelectUserWithoutInteraction(ServiceCtx context) { - bool Unknown = Context.RequestData.ReadBoolean(); + bool unknown = context.RequestData.ReadBoolean(); - Logger.PrintStub(LogClass.ServiceAcc, $"Stubbed. Unknown: {Unknown}"); + Logger.PrintStub(LogClass.ServiceAcc, $"Stubbed. Unknown: {unknown}"); - UserProfile Profile = Context.Device.System.State.LastOpenUser; + UserProfile profile = context.Device.System.State.LastOpenUser; - Profile.Uuid.Write(Context.ResponseData); + profile.Uuid.Write(context.ResponseData); return 0; } // InitializeApplicationInfo(u64, pid) - public long InitializeApplicationInfo(ServiceCtx Context) + public long InitializeApplicationInfo(ServiceCtx context) { - long Unknown = Context.RequestData.ReadInt64(); + long unknown = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceAcc, $"Stubbed. Unknown: {Unknown}"); + Logger.PrintStub(LogClass.ServiceAcc, $"Stubbed. Unknown: {unknown}"); return 0; } // GetBaasAccountManagerForApplication(nn::account::Uid) -> object - public long GetBaasAccountManagerForApplication(ServiceCtx Context) + public long GetBaasAccountManagerForApplication(ServiceCtx context) { - UInt128 Uuid = new UInt128( - Context.RequestData.ReadInt64(), - Context.RequestData.ReadInt64()); + UInt128 uuid = new UInt128( + context.RequestData.ReadInt64(), + context.RequestData.ReadInt64()); - MakeObject(Context, new IManagerForApplication(Uuid)); + MakeObject(context, new IManagerForApplication(uuid)); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Acc/IManagerForApplication.cs b/Ryujinx.HLE/HOS/Services/Acc/IManagerForApplication.cs index 9312b2bc..93b4b4a1 100644 --- a/Ryujinx.HLE/HOS/Services/Acc/IManagerForApplication.cs +++ b/Ryujinx.HLE/HOS/Services/Acc/IManagerForApplication.cs @@ -7,25 +7,25 @@ namespace Ryujinx.HLE.HOS.Services.Acc { class IManagerForApplication : IpcService { - private UInt128 Uuid; + private UInt128 _uuid; - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - public IManagerForApplication(UInt128 Uuid) + public IManagerForApplication(UInt128 uuid) { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, CheckAvailability }, { 1, GetAccountId } }; - this.Uuid = Uuid; + _uuid = uuid; } // CheckAvailability() - public long CheckAvailability(ServiceCtx Context) + public long CheckAvailability(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceAcc, "Stubbed."); @@ -33,13 +33,13 @@ namespace Ryujinx.HLE.HOS.Services.Acc } // GetAccountId() -> nn::account::NetworkServiceAccountId - public long GetAccountId(ServiceCtx Context) + public long GetAccountId(ServiceCtx context) { - long NetworkServiceAccountId = 0xcafe; + long networkServiceAccountId = 0xcafe; - Logger.PrintStub(LogClass.ServiceAcc, $"Stubbed. NetworkServiceAccountId: {NetworkServiceAccountId}"); + Logger.PrintStub(LogClass.ServiceAcc, $"Stubbed. NetworkServiceAccountId: {networkServiceAccountId}"); - Context.ResponseData.Write(NetworkServiceAccountId); + context.ResponseData.Write(networkServiceAccountId); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Acc/IProfile.cs b/Ryujinx.HLE/HOS/Services/Acc/IProfile.cs index 1d1a15cb..c50e9540 100644 --- a/Ryujinx.HLE/HOS/Services/Acc/IProfile.cs +++ b/Ryujinx.HLE/HOS/Services/Acc/IProfile.cs @@ -12,76 +12,76 @@ namespace Ryujinx.HLE.HOS.Services.Acc { class IProfile : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - private UserProfile Profile; + private UserProfile _profile; - private Stream ProfilePictureStream; + private Stream _profilePictureStream; - public IProfile(UserProfile Profile) + public IProfile(UserProfile profile) { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, Get }, { 1, GetBase }, { 10, GetImageSize }, - { 11, LoadImage }, + { 11, LoadImage } }; - this.Profile = Profile; + _profile = profile; - ProfilePictureStream = Assembly.GetCallingAssembly().GetManifestResourceStream("Ryujinx.HLE.RyujinxProfileImage.jpg"); + _profilePictureStream = Assembly.GetCallingAssembly().GetManifestResourceStream("Ryujinx.HLE.RyujinxProfileImage.jpg"); } - public long Get(ServiceCtx Context) + public long Get(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceAcc, "Stubbed."); - long Position = Context.Request.ReceiveBuff[0].Position; + long position = context.Request.ReceiveBuff[0].Position; - MemoryHelper.FillWithZeros(Context.Memory, Position, 0x80); + MemoryHelper.FillWithZeros(context.Memory, position, 0x80); - Context.Memory.WriteInt32(Position, 0); - Context.Memory.WriteInt32(Position + 4, 1); - Context.Memory.WriteInt64(Position + 8, 1); + context.Memory.WriteInt32(position, 0); + context.Memory.WriteInt32(position + 4, 1); + context.Memory.WriteInt64(position + 8, 1); - return GetBase(Context); + return GetBase(context); } - public long GetBase(ServiceCtx Context) + public long GetBase(ServiceCtx context) { - Profile.Uuid.Write(Context.ResponseData); + _profile.Uuid.Write(context.ResponseData); - Context.ResponseData.Write(Profile.LastModifiedTimestamp); + context.ResponseData.Write(_profile.LastModifiedTimestamp); - byte[] Username = StringUtils.GetFixedLengthBytes(Profile.Name, 0x20, Encoding.UTF8); + byte[] username = StringUtils.GetFixedLengthBytes(_profile.Name, 0x20, Encoding.UTF8); - Context.ResponseData.Write(Username); + context.ResponseData.Write(username); return 0; } - private long LoadImage(ServiceCtx Context) + private long LoadImage(ServiceCtx context) { - long BufferPosition = Context.Request.ReceiveBuff[0].Position; - long BufferLen = Context.Request.ReceiveBuff[0].Size; + long bufferPosition = context.Request.ReceiveBuff[0].Position; + long bufferLen = context.Request.ReceiveBuff[0].Size; - byte[] ProfilePictureData = new byte[BufferLen]; + byte[] profilePictureData = new byte[bufferLen]; - ProfilePictureStream.Read(ProfilePictureData, 0, ProfilePictureData.Length); + _profilePictureStream.Read(profilePictureData, 0, profilePictureData.Length); - Context.Memory.WriteBytes(BufferPosition, ProfilePictureData); + context.Memory.WriteBytes(bufferPosition, profilePictureData); - Context.ResponseData.Write(ProfilePictureStream.Length); + context.ResponseData.Write(_profilePictureStream.Length); return 0; } - private long GetImageSize(ServiceCtx Context) + private long GetImageSize(ServiceCtx context) { - Context.ResponseData.Write(ProfilePictureStream.Length); + context.ResponseData.Write(_profilePictureStream.Length); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Am/IAllSystemAppletProxiesService.cs b/Ryujinx.HLE/HOS/Services/Am/IAllSystemAppletProxiesService.cs index 2d44526a..0d067b16 100644 --- a/Ryujinx.HLE/HOS/Services/Am/IAllSystemAppletProxiesService.cs +++ b/Ryujinx.HLE/HOS/Services/Am/IAllSystemAppletProxiesService.cs @@ -5,21 +5,21 @@ namespace Ryujinx.HLE.HOS.Services.Am { class IAllSystemAppletProxiesService : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IAllSystemAppletProxiesService() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 100, OpenSystemAppletProxy } }; } - public long OpenSystemAppletProxy(ServiceCtx Context) + public long OpenSystemAppletProxy(ServiceCtx context) { - MakeObject(Context, new ISystemAppletProxy()); + MakeObject(context, new ISystemAppletProxy()); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Am/IApplicationCreator.cs b/Ryujinx.HLE/HOS/Services/Am/IApplicationCreator.cs index c5ed09f5..eac609ed 100644 --- a/Ryujinx.HLE/HOS/Services/Am/IApplicationCreator.cs +++ b/Ryujinx.HLE/HOS/Services/Am/IApplicationCreator.cs @@ -5,13 +5,13 @@ namespace Ryujinx.HLE.HOS.Services.Am { class IApplicationCreator : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IApplicationCreator() { - m_Commands = new Dictionary() + _commands = new Dictionary { //... }; diff --git a/Ryujinx.HLE/HOS/Services/Am/IApplicationFunctions.cs b/Ryujinx.HLE/HOS/Services/Am/IApplicationFunctions.cs index 1934798b..fbc5dee5 100644 --- a/Ryujinx.HLE/HOS/Services/Am/IApplicationFunctions.cs +++ b/Ryujinx.HLE/HOS/Services/Am/IApplicationFunctions.cs @@ -6,13 +6,13 @@ namespace Ryujinx.HLE.HOS.Services.Am { class IApplicationFunctions : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IApplicationFunctions() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 1, PopLaunchParameter }, { 20, EnsureSaveData }, @@ -26,88 +26,88 @@ namespace Ryujinx.HLE.HOS.Services.Am }; } - public long PopLaunchParameter(ServiceCtx Context) + public long PopLaunchParameter(ServiceCtx context) { //Only the first 0x18 bytes of the Data seems to be actually used. - MakeObject(Context, new IStorage(StorageHelper.MakeLaunchParams())); + MakeObject(context, new IStorage(StorageHelper.MakeLaunchParams())); return 0; } - public long EnsureSaveData(ServiceCtx Context) + public long EnsureSaveData(ServiceCtx context) { - long UIdLow = Context.RequestData.ReadInt64(); - long UIdHigh = Context.RequestData.ReadInt64(); + long uIdLow = context.RequestData.ReadInt64(); + long uIdHigh = context.RequestData.ReadInt64(); Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); - Context.ResponseData.Write(0L); + context.ResponseData.Write(0L); return 0; } - public long GetDesiredLanguage(ServiceCtx Context) + public long GetDesiredLanguage(ServiceCtx context) { - Context.ResponseData.Write(Context.Device.System.State.DesiredLanguageCode); + context.ResponseData.Write(context.Device.System.State.DesiredLanguageCode); return 0; } - public long SetTerminateResult(ServiceCtx Context) + public long SetTerminateResult(ServiceCtx context) { - int ErrorCode = Context.RequestData.ReadInt32(); + int errorCode = context.RequestData.ReadInt32(); - string Result = GetFormattedErrorCode(ErrorCode); + string result = GetFormattedErrorCode(errorCode); - Logger.PrintInfo(LogClass.ServiceAm, $"Result = 0x{ErrorCode:x8} ({Result})."); + Logger.PrintInfo(LogClass.ServiceAm, $"Result = 0x{errorCode:x8} ({result})."); return 0; } - private string GetFormattedErrorCode(int ErrorCode) + private string GetFormattedErrorCode(int errorCode) { - int Module = (ErrorCode >> 0) & 0x1ff; - int Description = (ErrorCode >> 9) & 0x1fff; + int module = (errorCode >> 0) & 0x1ff; + int description = (errorCode >> 9) & 0x1fff; - return $"{(2000 + Module):d4}-{Description:d4}"; + return $"{(2000 + module):d4}-{description:d4}"; } - public long GetDisplayVersion(ServiceCtx Context) + public long GetDisplayVersion(ServiceCtx context) { //FIXME: Need to check correct version on a switch. - Context.ResponseData.Write(1L); - Context.ResponseData.Write(0L); + context.ResponseData.Write(1L); + context.ResponseData.Write(0L); return 0; } - public long NotifyRunning(ServiceCtx Context) + public long NotifyRunning(ServiceCtx context) { - Context.ResponseData.Write(1); + context.ResponseData.Write(1); return 0; } - public long GetPseudoDeviceId(ServiceCtx Context) + public long GetPseudoDeviceId(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); - Context.ResponseData.Write(0L); - Context.ResponseData.Write(0L); + context.ResponseData.Write(0L); + context.ResponseData.Write(0L); return 0; } - public long InitializeGamePlayRecording(ServiceCtx Context) + public long InitializeGamePlayRecording(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); return 0; } - public long SetGamePlayRecordingState(ServiceCtx Context) + public long SetGamePlayRecordingState(ServiceCtx context) { - int State = Context.RequestData.ReadInt32(); + int state = context.RequestData.ReadInt32(); Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); diff --git a/Ryujinx.HLE/HOS/Services/Am/IApplicationProxy.cs b/Ryujinx.HLE/HOS/Services/Am/IApplicationProxy.cs index 2aaeda78..fd785a70 100644 --- a/Ryujinx.HLE/HOS/Services/Am/IApplicationProxy.cs +++ b/Ryujinx.HLE/HOS/Services/Am/IApplicationProxy.cs @@ -5,13 +5,13 @@ namespace Ryujinx.HLE.HOS.Services.Am { class IApplicationProxy : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IApplicationProxy() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, GetCommonStateGetter }, { 1, GetSelfController }, @@ -24,58 +24,58 @@ namespace Ryujinx.HLE.HOS.Services.Am }; } - public long GetCommonStateGetter(ServiceCtx Context) + public long GetCommonStateGetter(ServiceCtx context) { - MakeObject(Context, new ICommonStateGetter(Context.Device.System)); + MakeObject(context, new ICommonStateGetter(context.Device.System)); return 0; } - public long GetSelfController(ServiceCtx Context) + public long GetSelfController(ServiceCtx context) { - MakeObject(Context, new ISelfController(Context.Device.System)); + MakeObject(context, new ISelfController(context.Device.System)); return 0; } - public long GetWindowController(ServiceCtx Context) + public long GetWindowController(ServiceCtx context) { - MakeObject(Context, new IWindowController()); + MakeObject(context, new IWindowController()); return 0; } - public long GetAudioController(ServiceCtx Context) + public long GetAudioController(ServiceCtx context) { - MakeObject(Context, new IAudioController()); + MakeObject(context, new IAudioController()); return 0; } - public long GetDisplayController(ServiceCtx Context) + public long GetDisplayController(ServiceCtx context) { - MakeObject(Context, new IDisplayController()); + MakeObject(context, new IDisplayController()); return 0; } - public long GetLibraryAppletCreator(ServiceCtx Context) + public long GetLibraryAppletCreator(ServiceCtx context) { - MakeObject(Context, new ILibraryAppletCreator()); + MakeObject(context, new ILibraryAppletCreator()); return 0; } - public long GetApplicationFunctions(ServiceCtx Context) + public long GetApplicationFunctions(ServiceCtx context) { - MakeObject(Context, new IApplicationFunctions()); + MakeObject(context, new IApplicationFunctions()); return 0; } - public long GetDebugFunctions(ServiceCtx Context) + public long GetDebugFunctions(ServiceCtx context) { - MakeObject(Context, new IDebugFunctions()); + MakeObject(context, new IDebugFunctions()); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Am/IApplicationProxyService.cs b/Ryujinx.HLE/HOS/Services/Am/IApplicationProxyService.cs index fb518af9..88792a16 100644 --- a/Ryujinx.HLE/HOS/Services/Am/IApplicationProxyService.cs +++ b/Ryujinx.HLE/HOS/Services/Am/IApplicationProxyService.cs @@ -5,21 +5,21 @@ namespace Ryujinx.HLE.HOS.Services.Am { class IApplicationProxyService : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IApplicationProxyService() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, OpenApplicationProxy } }; } - public long OpenApplicationProxy(ServiceCtx Context) + public long OpenApplicationProxy(ServiceCtx context) { - MakeObject(Context, new IApplicationProxy()); + MakeObject(context, new IApplicationProxy()); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Am/IAudioController.cs b/Ryujinx.HLE/HOS/Services/Am/IAudioController.cs index 062f2d86..a03a3266 100644 --- a/Ryujinx.HLE/HOS/Services/Am/IAudioController.cs +++ b/Ryujinx.HLE/HOS/Services/Am/IAudioController.cs @@ -6,13 +6,13 @@ namespace Ryujinx.HLE.HOS.Services.Am { class IAudioController : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IAudioController() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, SetExpectedMasterVolume }, { 1, GetMainAppletExpectedMasterVolume }, @@ -22,47 +22,47 @@ namespace Ryujinx.HLE.HOS.Services.Am }; } - public long SetExpectedMasterVolume(ServiceCtx Context) + public long SetExpectedMasterVolume(ServiceCtx context) { - float AppletVolume = Context.RequestData.ReadSingle(); - float LibraryAppletVolume = Context.RequestData.ReadSingle(); + float appletVolume = context.RequestData.ReadSingle(); + float libraryAppletVolume = context.RequestData.ReadSingle(); Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); return 0; } - public long GetMainAppletExpectedMasterVolume(ServiceCtx Context) + public long GetMainAppletExpectedMasterVolume(ServiceCtx context) { - Context.ResponseData.Write(1f); + context.ResponseData.Write(1f); Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); return 0; } - public long GetLibraryAppletExpectedMasterVolume(ServiceCtx Context) + public long GetLibraryAppletExpectedMasterVolume(ServiceCtx context) { - Context.ResponseData.Write(1f); + context.ResponseData.Write(1f); Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); return 0; } - public long ChangeMainAppletMasterVolume(ServiceCtx Context) + public long ChangeMainAppletMasterVolume(ServiceCtx context) { - float Unknown0 = Context.RequestData.ReadSingle(); - long Unknown1 = Context.RequestData.ReadInt64(); + float unknown0 = context.RequestData.ReadSingle(); + long unknown1 = context.RequestData.ReadInt64(); Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); return 0; } - public long SetTransparentVolumeRate(ServiceCtx Context) + public long SetTransparentVolumeRate(ServiceCtx context) { - float Unknown0 = Context.RequestData.ReadSingle(); + float unknown0 = context.RequestData.ReadSingle(); Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); diff --git a/Ryujinx.HLE/HOS/Services/Am/ICommonStateGetter.cs b/Ryujinx.HLE/HOS/Services/Am/ICommonStateGetter.cs index 2feaf8fc..8ec42152 100644 --- a/Ryujinx.HLE/HOS/Services/Am/ICommonStateGetter.cs +++ b/Ryujinx.HLE/HOS/Services/Am/ICommonStateGetter.cs @@ -10,15 +10,15 @@ namespace Ryujinx.HLE.HOS.Services.Am { class ICommonStateGetter : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - private KEvent DisplayResolutionChangeEvent; + private KEvent _displayResolutionChangeEvent; - public ICommonStateGetter(Horizon System) + public ICommonStateGetter(Horizon system) { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, GetEventHandle }, { 1, ReceiveMessage }, @@ -30,89 +30,89 @@ namespace Ryujinx.HLE.HOS.Services.Am { 61, GetDefaultDisplayResolutionChangeEvent } }; - DisplayResolutionChangeEvent = new KEvent(System); + _displayResolutionChangeEvent = new KEvent(system); } - public long GetEventHandle(ServiceCtx Context) + public long GetEventHandle(ServiceCtx context) { - KEvent Event = Context.Device.System.AppletState.MessageEvent; + KEvent Event = context.Device.System.AppletState.MessageEvent; - if (Context.Process.HandleTable.GenerateHandle(Event.ReadableEvent, out int Handle) != KernelResult.Success) + if (context.Process.HandleTable.GenerateHandle(Event.ReadableEvent, out int handle) != KernelResult.Success) { throw new InvalidOperationException("Out of handles!"); } - Context.Response.HandleDesc = IpcHandleDesc.MakeCopy(Handle); + context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); return 0; } - public long ReceiveMessage(ServiceCtx Context) + public long ReceiveMessage(ServiceCtx context) { - if (!Context.Device.System.AppletState.TryDequeueMessage(out MessageInfo Message)) + if (!context.Device.System.AppletState.TryDequeueMessage(out MessageInfo message)) { return MakeError(ErrorModule.Am, AmErr.NoMessages); } - Context.ResponseData.Write((int)Message); + context.ResponseData.Write((int)message); return 0; } - public long GetOperationMode(ServiceCtx Context) + public long GetOperationMode(ServiceCtx context) { - OperationMode Mode = Context.Device.System.State.DockedMode + OperationMode mode = context.Device.System.State.DockedMode ? OperationMode.Docked : OperationMode.Handheld; - Context.ResponseData.Write((byte)Mode); + context.ResponseData.Write((byte)mode); return 0; } - public long GetPerformanceMode(ServiceCtx Context) + public long GetPerformanceMode(ServiceCtx context) { - Apm.PerformanceMode Mode = Context.Device.System.State.DockedMode + Apm.PerformanceMode mode = context.Device.System.State.DockedMode ? Apm.PerformanceMode.Docked : Apm.PerformanceMode.Handheld; - Context.ResponseData.Write((int)Mode); + context.ResponseData.Write((int)mode); return 0; } - public long GetBootMode(ServiceCtx Context) + public long GetBootMode(ServiceCtx context) { - Context.ResponseData.Write((byte)0); //Unknown value. + context.ResponseData.Write((byte)0); //Unknown value. Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); return 0; } - public long GetCurrentFocusState(ServiceCtx Context) + public long GetCurrentFocusState(ServiceCtx context) { - Context.ResponseData.Write((byte)Context.Device.System.AppletState.FocusState); + context.ResponseData.Write((byte)context.Device.System.AppletState.FocusState); return 0; } - public long GetDefaultDisplayResolution(ServiceCtx Context) + public long GetDefaultDisplayResolution(ServiceCtx context) { - Context.ResponseData.Write(1280); - Context.ResponseData.Write(720); + context.ResponseData.Write(1280); + context.ResponseData.Write(720); return 0; } - public long GetDefaultDisplayResolutionChangeEvent(ServiceCtx Context) + public long GetDefaultDisplayResolutionChangeEvent(ServiceCtx context) { - if (Context.Process.HandleTable.GenerateHandle(DisplayResolutionChangeEvent.ReadableEvent, out int Handle) != KernelResult.Success) + if (context.Process.HandleTable.GenerateHandle(_displayResolutionChangeEvent.ReadableEvent, out int handle) != KernelResult.Success) { throw new InvalidOperationException("Out of handles!"); } - Context.Response.HandleDesc = IpcHandleDesc.MakeCopy(Handle); + context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); diff --git a/Ryujinx.HLE/HOS/Services/Am/IDebugFunctions.cs b/Ryujinx.HLE/HOS/Services/Am/IDebugFunctions.cs index d86743c0..f7ea253d 100644 --- a/Ryujinx.HLE/HOS/Services/Am/IDebugFunctions.cs +++ b/Ryujinx.HLE/HOS/Services/Am/IDebugFunctions.cs @@ -5,13 +5,13 @@ namespace Ryujinx.HLE.HOS.Services.Am { class IDebugFunctions : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IDebugFunctions() { - m_Commands = new Dictionary() + _commands = new Dictionary { //... }; diff --git a/Ryujinx.HLE/HOS/Services/Am/IDisplayController.cs b/Ryujinx.HLE/HOS/Services/Am/IDisplayController.cs index c4d49579..91fd864c 100644 --- a/Ryujinx.HLE/HOS/Services/Am/IDisplayController.cs +++ b/Ryujinx.HLE/HOS/Services/Am/IDisplayController.cs @@ -5,13 +5,13 @@ namespace Ryujinx.HLE.HOS.Services.Am { class IDisplayController : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IDisplayController() { - m_Commands = new Dictionary() + _commands = new Dictionary { //... }; diff --git a/Ryujinx.HLE/HOS/Services/Am/IGlobalStateController.cs b/Ryujinx.HLE/HOS/Services/Am/IGlobalStateController.cs index e646327f..b9387661 100644 --- a/Ryujinx.HLE/HOS/Services/Am/IGlobalStateController.cs +++ b/Ryujinx.HLE/HOS/Services/Am/IGlobalStateController.cs @@ -5,13 +5,13 @@ namespace Ryujinx.HLE.HOS.Services.Am { class IGlobalStateController : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IGlobalStateController() { - m_Commands = new Dictionary() + _commands = new Dictionary { //... }; diff --git a/Ryujinx.HLE/HOS/Services/Am/IHomeMenuFunctions.cs b/Ryujinx.HLE/HOS/Services/Am/IHomeMenuFunctions.cs index 3f026e2f..db116f33 100644 --- a/Ryujinx.HLE/HOS/Services/Am/IHomeMenuFunctions.cs +++ b/Ryujinx.HLE/HOS/Services/Am/IHomeMenuFunctions.cs @@ -8,39 +8,39 @@ namespace Ryujinx.HLE.HOS.Services.Am { class IHomeMenuFunctions : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - private KEvent ChannelEvent; + private KEvent _channelEvent; - public IHomeMenuFunctions(Horizon System) + public IHomeMenuFunctions(Horizon system) { - m_Commands = new Dictionary() + _commands = new Dictionary { { 10, RequestToGetForeground }, { 21, GetPopFromGeneralChannelEvent } }; //ToDo: Signal this Event somewhere in future. - ChannelEvent = new KEvent(System); + _channelEvent = new KEvent(system); } - public long RequestToGetForeground(ServiceCtx Context) + public long RequestToGetForeground(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); return 0; } - public long GetPopFromGeneralChannelEvent(ServiceCtx Context) + public long GetPopFromGeneralChannelEvent(ServiceCtx context) { - if (Context.Process.HandleTable.GenerateHandle(ChannelEvent.ReadableEvent, out int Handle) != KernelResult.Success) + if (context.Process.HandleTable.GenerateHandle(_channelEvent.ReadableEvent, out int handle) != KernelResult.Success) { throw new InvalidOperationException("Out of handles!"); } - Context.Response.HandleDesc = IpcHandleDesc.MakeCopy(Handle); + context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); diff --git a/Ryujinx.HLE/HOS/Services/Am/ILibraryAppletAccessor.cs b/Ryujinx.HLE/HOS/Services/Am/ILibraryAppletAccessor.cs index 9e0d0e70..7c4aa16c 100644 --- a/Ryujinx.HLE/HOS/Services/Am/ILibraryAppletAccessor.cs +++ b/Ryujinx.HLE/HOS/Services/Am/ILibraryAppletAccessor.cs @@ -8,15 +8,15 @@ namespace Ryujinx.HLE.HOS.Services.Am { class ILibraryAppletAccessor : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - private KEvent StateChangedEvent; + private KEvent _stateChangedEvent; - public ILibraryAppletAccessor(Horizon System) + public ILibraryAppletAccessor(Horizon system) { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, GetAppletStateChangedEvent }, { 10, Start }, @@ -25,49 +25,49 @@ namespace Ryujinx.HLE.HOS.Services.Am { 101, PopOutData } }; - StateChangedEvent = new KEvent(System); + _stateChangedEvent = new KEvent(system); } - public long GetAppletStateChangedEvent(ServiceCtx Context) + public long GetAppletStateChangedEvent(ServiceCtx context) { - StateChangedEvent.ReadableEvent.Signal(); + _stateChangedEvent.ReadableEvent.Signal(); - if (Context.Process.HandleTable.GenerateHandle(StateChangedEvent.ReadableEvent, out int Handle) != KernelResult.Success) + if (context.Process.HandleTable.GenerateHandle(_stateChangedEvent.ReadableEvent, out int handle) != KernelResult.Success) { throw new InvalidOperationException("Out of handles!"); } - Context.Response.HandleDesc = IpcHandleDesc.MakeCopy(Handle); + context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); return 0; } - public long Start(ServiceCtx Context) + public long Start(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); return 0; } - public long GetResult(ServiceCtx Context) + public long GetResult(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); return 0; } - public long PushInData(ServiceCtx Context) + public long PushInData(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); return 0; } - public long PopOutData(ServiceCtx Context) + public long PopOutData(ServiceCtx context) { - MakeObject(Context, new IStorage(StorageHelper.MakeLaunchParams())); + MakeObject(context, new IStorage(StorageHelper.MakeLaunchParams())); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Am/ILibraryAppletCreator.cs b/Ryujinx.HLE/HOS/Services/Am/ILibraryAppletCreator.cs index 5535a43c..3f88c545 100644 --- a/Ryujinx.HLE/HOS/Services/Am/ILibraryAppletCreator.cs +++ b/Ryujinx.HLE/HOS/Services/Am/ILibraryAppletCreator.cs @@ -5,31 +5,31 @@ namespace Ryujinx.HLE.HOS.Services.Am { class ILibraryAppletCreator : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public ILibraryAppletCreator() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, CreateLibraryApplet }, { 10, CreateStorage } }; } - public long CreateLibraryApplet(ServiceCtx Context) + public long CreateLibraryApplet(ServiceCtx context) { - MakeObject(Context, new ILibraryAppletAccessor(Context.Device.System)); + MakeObject(context, new ILibraryAppletAccessor(context.Device.System)); return 0; } - public long CreateStorage(ServiceCtx Context) + public long CreateStorage(ServiceCtx context) { - long Size = Context.RequestData.ReadInt64(); + long size = context.RequestData.ReadInt64(); - MakeObject(Context, new IStorage(new byte[Size])); + MakeObject(context, new IStorage(new byte[size])); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Am/ISelfController.cs b/Ryujinx.HLE/HOS/Services/Am/ISelfController.cs index 2abaee2e..dc922037 100644 --- a/Ryujinx.HLE/HOS/Services/Am/ISelfController.cs +++ b/Ryujinx.HLE/HOS/Services/Am/ISelfController.cs @@ -8,17 +8,17 @@ namespace Ryujinx.HLE.HOS.Services.Am { class ISelfController : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - private KEvent LaunchableEvent; + private KEvent _launchableEvent; - private int IdleTimeDetectionExtension; + private int _idleTimeDetectionExtension; - public ISelfController(Horizon System) + public ISelfController(Horizon system) { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, Exit }, { 1, LockExit }, @@ -36,114 +36,114 @@ namespace Ryujinx.HLE.HOS.Services.Am { 63, GetIdleTimeDetectionExtension } }; - LaunchableEvent = new KEvent(System); + _launchableEvent = new KEvent(system); } - public long Exit(ServiceCtx Context) + public long Exit(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); return 0; } - public long LockExit(ServiceCtx Context) + public long LockExit(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); return 0; } - public long UnlockExit(ServiceCtx Context) + public long UnlockExit(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); return 0; } - public long GetLibraryAppletLaunchableEvent(ServiceCtx Context) + public long GetLibraryAppletLaunchableEvent(ServiceCtx context) { - LaunchableEvent.ReadableEvent.Signal(); + _launchableEvent.ReadableEvent.Signal(); - if (Context.Process.HandleTable.GenerateHandle(LaunchableEvent.ReadableEvent, out int Handle) != KernelResult.Success) + if (context.Process.HandleTable.GenerateHandle(_launchableEvent.ReadableEvent, out int handle) != KernelResult.Success) { throw new InvalidOperationException("Out of handles!"); } - Context.Response.HandleDesc = IpcHandleDesc.MakeCopy(Handle); + context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); return 0; } - public long SetScreenShotPermission(ServiceCtx Context) + public long SetScreenShotPermission(ServiceCtx context) { - bool Enable = Context.RequestData.ReadByte() != 0 ? true : false; + bool enable = context.RequestData.ReadByte() != 0; Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); return 0; } - public long SetOperationModeChangedNotification(ServiceCtx Context) + public long SetOperationModeChangedNotification(ServiceCtx context) { - bool Enable = Context.RequestData.ReadByte() != 0 ? true : false; + bool enable = context.RequestData.ReadByte() != 0; Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); return 0; } - public long SetPerformanceModeChangedNotification(ServiceCtx Context) + public long SetPerformanceModeChangedNotification(ServiceCtx context) { - bool Enable = Context.RequestData.ReadByte() != 0 ? true : false; + bool enable = context.RequestData.ReadByte() != 0; Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); return 0; } - public long SetFocusHandlingMode(ServiceCtx Context) + public long SetFocusHandlingMode(ServiceCtx context) { - bool Flag1 = Context.RequestData.ReadByte() != 0 ? true : false; - bool Flag2 = Context.RequestData.ReadByte() != 0 ? true : false; - bool Flag3 = Context.RequestData.ReadByte() != 0 ? true : false; + bool flag1 = context.RequestData.ReadByte() != 0; + bool flag2 = context.RequestData.ReadByte() != 0; + bool flag3 = context.RequestData.ReadByte() != 0; Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); return 0; } - public long SetRestartMessageEnabled(ServiceCtx Context) + public long SetRestartMessageEnabled(ServiceCtx context) { - bool Enable = Context.RequestData.ReadByte() != 0 ? true : false; + bool enable = context.RequestData.ReadByte() != 0; Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); return 0; } - public long SetOutOfFocusSuspendingEnabled(ServiceCtx Context) + public long SetOutOfFocusSuspendingEnabled(ServiceCtx context) { - bool Enable = Context.RequestData.ReadByte() != 0 ? true : false; + bool enable = context.RequestData.ReadByte() != 0; Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); return 0; } - public long SetScreenShotImageOrientation(ServiceCtx Context) + public long SetScreenShotImageOrientation(ServiceCtx context) { - int Orientation = Context.RequestData.ReadInt32(); + int orientation = context.RequestData.ReadInt32(); Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); return 0; } - public long SetHandlesRequestToDisplay(ServiceCtx Context) + public long SetHandlesRequestToDisplay(ServiceCtx context) { - bool Enable = Context.RequestData.ReadByte() != 0 ? true : false; + bool enable = context.RequestData.ReadByte() != 0; Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); @@ -151,21 +151,21 @@ namespace Ryujinx.HLE.HOS.Services.Am } // SetIdleTimeDetectionExtension(u32) - public long SetIdleTimeDetectionExtension(ServiceCtx Context) + public long SetIdleTimeDetectionExtension(ServiceCtx context) { - IdleTimeDetectionExtension = Context.RequestData.ReadInt32(); + _idleTimeDetectionExtension = context.RequestData.ReadInt32(); - Logger.PrintStub(LogClass.ServiceAm, $"Stubbed. IdleTimeDetectionExtension: {IdleTimeDetectionExtension}"); + Logger.PrintStub(LogClass.ServiceAm, $"Stubbed. IdleTimeDetectionExtension: {_idleTimeDetectionExtension}"); return 0; } // GetIdleTimeDetectionExtension() -> u32 - public long GetIdleTimeDetectionExtension(ServiceCtx Context) + public long GetIdleTimeDetectionExtension(ServiceCtx context) { - Context.ResponseData.Write(IdleTimeDetectionExtension); + context.ResponseData.Write(_idleTimeDetectionExtension); - Logger.PrintStub(LogClass.ServiceAm, $"Stubbed. IdleTimeDetectionExtension: {IdleTimeDetectionExtension}"); + Logger.PrintStub(LogClass.ServiceAm, $"Stubbed. IdleTimeDetectionExtension: {_idleTimeDetectionExtension}"); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Am/IStorage.cs b/Ryujinx.HLE/HOS/Services/Am/IStorage.cs index 10778122..aff9c5da 100644 --- a/Ryujinx.HLE/HOS/Services/Am/IStorage.cs +++ b/Ryujinx.HLE/HOS/Services/Am/IStorage.cs @@ -5,25 +5,25 @@ namespace Ryujinx.HLE.HOS.Services.Am { class IStorage : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public byte[] Data { get; private set; } - public IStorage(byte[] Data) + public IStorage(byte[] data) { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, Open } }; - this.Data = Data; + Data = data; } - public long Open(ServiceCtx Context) + public long Open(ServiceCtx context) { - MakeObject(Context, new IStorageAccessor(this)); + MakeObject(context, new IStorageAccessor(this)); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Am/IStorageAccessor.cs b/Ryujinx.HLE/HOS/Services/Am/IStorageAccessor.cs index a60cf149..ac54069a 100644 --- a/Ryujinx.HLE/HOS/Services/Am/IStorageAccessor.cs +++ b/Ryujinx.HLE/HOS/Services/Am/IStorageAccessor.cs @@ -6,76 +6,76 @@ namespace Ryujinx.HLE.HOS.Services.Am { class IStorageAccessor : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - private IStorage Storage; + private IStorage _storage; - public IStorageAccessor(IStorage Storage) + public IStorageAccessor(IStorage storage) { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, GetSize }, { 10, Write }, { 11, Read } }; - this.Storage = Storage; + _storage = storage; } - public long GetSize(ServiceCtx Context) + public long GetSize(ServiceCtx context) { - Context.ResponseData.Write((long)Storage.Data.Length); + context.ResponseData.Write((long)_storage.Data.Length); return 0; } - public long Write(ServiceCtx Context) + public long Write(ServiceCtx context) { //TODO: Error conditions. - long WritePosition = Context.RequestData.ReadInt64(); + long writePosition = context.RequestData.ReadInt64(); - (long Position, long Size) = Context.Request.GetBufferType0x21(); + (long position, long size) = context.Request.GetBufferType0x21(); - if (Size > 0) + if (size > 0) { - long MaxSize = Storage.Data.Length - WritePosition; + long maxSize = _storage.Data.Length - writePosition; - if (Size > MaxSize) + if (size > maxSize) { - Size = MaxSize; + size = maxSize; } - byte[] Data = Context.Memory.ReadBytes(Position, Size); + byte[] data = context.Memory.ReadBytes(position, size); - Buffer.BlockCopy(Data, 0, Storage.Data, (int)WritePosition, (int)Size); + Buffer.BlockCopy(data, 0, _storage.Data, (int)writePosition, (int)size); } return 0; } - public long Read(ServiceCtx Context) + public long Read(ServiceCtx context) { //TODO: Error conditions. - long ReadPosition = Context.RequestData.ReadInt64(); + long readPosition = context.RequestData.ReadInt64(); - (long Position, long Size) = Context.Request.GetBufferType0x22(); + (long position, long size) = context.Request.GetBufferType0x22(); - byte[] Data; + byte[] data; - if (Storage.Data.Length > Size) + if (_storage.Data.Length > size) { - Data = new byte[Size]; + data = new byte[size]; - Buffer.BlockCopy(Storage.Data, 0, Data, 0, (int)Size); + Buffer.BlockCopy(_storage.Data, 0, data, 0, (int)size); } else { - Data = Storage.Data; + data = _storage.Data; } - Context.Memory.WriteBytes(Position, Data); + context.Memory.WriteBytes(position, data); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Am/ISystemAppletProxy.cs b/Ryujinx.HLE/HOS/Services/Am/ISystemAppletProxy.cs index 85e11e0f..e8a442ae 100644 --- a/Ryujinx.HLE/HOS/Services/Am/ISystemAppletProxy.cs +++ b/Ryujinx.HLE/HOS/Services/Am/ISystemAppletProxy.cs @@ -5,13 +5,13 @@ namespace Ryujinx.HLE.HOS.Services.Am { class ISystemAppletProxy : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public ISystemAppletProxy() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, GetCommonStateGetter }, { 1, GetSelfController }, @@ -26,72 +26,72 @@ namespace Ryujinx.HLE.HOS.Services.Am }; } - public long GetCommonStateGetter(ServiceCtx Context) + public long GetCommonStateGetter(ServiceCtx context) { - MakeObject(Context, new ICommonStateGetter(Context.Device.System)); + MakeObject(context, new ICommonStateGetter(context.Device.System)); return 0; } - public long GetSelfController(ServiceCtx Context) + public long GetSelfController(ServiceCtx context) { - MakeObject(Context, new ISelfController(Context.Device.System)); + MakeObject(context, new ISelfController(context.Device.System)); return 0; } - public long GetWindowController(ServiceCtx Context) + public long GetWindowController(ServiceCtx context) { - MakeObject(Context, new IWindowController()); + MakeObject(context, new IWindowController()); return 0; } - public long GetAudioController(ServiceCtx Context) + public long GetAudioController(ServiceCtx context) { - MakeObject(Context, new IAudioController()); + MakeObject(context, new IAudioController()); return 0; } - public long GetDisplayController(ServiceCtx Context) + public long GetDisplayController(ServiceCtx context) { - MakeObject(Context, new IDisplayController()); + MakeObject(context, new IDisplayController()); return 0; } - public long GetLibraryAppletCreator(ServiceCtx Context) + public long GetLibraryAppletCreator(ServiceCtx context) { - MakeObject(Context, new ILibraryAppletCreator()); + MakeObject(context, new ILibraryAppletCreator()); return 0; } - public long GetHomeMenuFunctions(ServiceCtx Context) + public long GetHomeMenuFunctions(ServiceCtx context) { - MakeObject(Context, new IHomeMenuFunctions(Context.Device.System)); + MakeObject(context, new IHomeMenuFunctions(context.Device.System)); return 0; } - public long GetGlobalStateController(ServiceCtx Context) + public long GetGlobalStateController(ServiceCtx context) { - MakeObject(Context, new IGlobalStateController()); + MakeObject(context, new IGlobalStateController()); return 0; } - public long GetApplicationCreator(ServiceCtx Context) + public long GetApplicationCreator(ServiceCtx context) { - MakeObject(Context, new IApplicationCreator()); + MakeObject(context, new IApplicationCreator()); return 0; } - public long GetDebugFunctions(ServiceCtx Context) + public long GetDebugFunctions(ServiceCtx context) { - MakeObject(Context, new IDebugFunctions()); + MakeObject(context, new IDebugFunctions()); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Am/IWindowController.cs b/Ryujinx.HLE/HOS/Services/Am/IWindowController.cs index de5137d1..aca7a666 100644 --- a/Ryujinx.HLE/HOS/Services/Am/IWindowController.cs +++ b/Ryujinx.HLE/HOS/Services/Am/IWindowController.cs @@ -6,29 +6,29 @@ namespace Ryujinx.HLE.HOS.Services.Am { class IWindowController : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IWindowController() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 1, GetAppletResourceUserId }, { 10, AcquireForegroundRights } }; } - public long GetAppletResourceUserId(ServiceCtx Context) + public long GetAppletResourceUserId(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); - Context.ResponseData.Write(0L); + context.ResponseData.Write(0L); return 0; } - public long AcquireForegroundRights(ServiceCtx Context) + public long AcquireForegroundRights(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); diff --git a/Ryujinx.HLE/HOS/Services/Am/StorageHelper.cs b/Ryujinx.HLE/HOS/Services/Am/StorageHelper.cs index b97ffc1e..39a4c6dd 100644 --- a/Ryujinx.HLE/HOS/Services/Am/StorageHelper.cs +++ b/Ryujinx.HLE/HOS/Services/Am/StorageHelper.cs @@ -9,18 +9,18 @@ namespace Ryujinx.HLE.HOS.Services.Am public static byte[] MakeLaunchParams() { //Size needs to be at least 0x88 bytes otherwise application errors. - using (MemoryStream MS = new MemoryStream()) + using (MemoryStream ms = new MemoryStream()) { - BinaryWriter Writer = new BinaryWriter(MS); + BinaryWriter writer = new BinaryWriter(ms); - MS.SetLength(0x88); + ms.SetLength(0x88); - Writer.Write(LaunchParamsMagic); - Writer.Write(1); //IsAccountSelected? Only lower 8 bits actually used. - Writer.Write(1L); //User Id Low (note: User Id needs to be != 0) - Writer.Write(0L); //User Id High + writer.Write(LaunchParamsMagic); + writer.Write(1); //IsAccountSelected? Only lower 8 bits actually used. + writer.Write(1L); //User Id Low (note: User Id needs to be != 0) + writer.Write(0L); //User Id High - return MS.ToArray(); + return ms.ToArray(); } } } diff --git a/Ryujinx.HLE/HOS/Services/Apm/IManager.cs b/Ryujinx.HLE/HOS/Services/Apm/IManager.cs index 50822def..cd86e516 100644 --- a/Ryujinx.HLE/HOS/Services/Apm/IManager.cs +++ b/Ryujinx.HLE/HOS/Services/Apm/IManager.cs @@ -5,21 +5,21 @@ namespace Ryujinx.HLE.HOS.Services.Apm { class IManager : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IManager() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, OpenSession } }; } - public long OpenSession(ServiceCtx Context) + public long OpenSession(ServiceCtx context) { - MakeObject(Context, new ISession()); + MakeObject(context, new ISession()); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Apm/ISession.cs b/Ryujinx.HLE/HOS/Services/Apm/ISession.cs index d04bcfc9..cef34383 100644 --- a/Ryujinx.HLE/HOS/Services/Apm/ISession.cs +++ b/Ryujinx.HLE/HOS/Services/Apm/ISession.cs @@ -6,32 +6,32 @@ namespace Ryujinx.HLE.HOS.Services.Apm { class ISession : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public ISession() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, SetPerformanceConfiguration }, { 1, GetPerformanceConfiguration } }; } - public long SetPerformanceConfiguration(ServiceCtx Context) + public long SetPerformanceConfiguration(ServiceCtx context) { - PerformanceMode PerfMode = (PerformanceMode)Context.RequestData.ReadInt32(); - PerformanceConfiguration PerfConfig = (PerformanceConfiguration)Context.RequestData.ReadInt32(); + PerformanceMode perfMode = (PerformanceMode)context.RequestData.ReadInt32(); + PerformanceConfiguration perfConfig = (PerformanceConfiguration)context.RequestData.ReadInt32(); return 0; } - public long GetPerformanceConfiguration(ServiceCtx Context) + public long GetPerformanceConfiguration(ServiceCtx context) { - PerformanceMode PerfMode = (PerformanceMode)Context.RequestData.ReadInt32(); + PerformanceMode perfMode = (PerformanceMode)context.RequestData.ReadInt32(); - Context.ResponseData.Write((uint)PerformanceConfiguration.PerformanceConfiguration1); + context.ResponseData.Write((uint)PerformanceConfiguration.PerformanceConfiguration1); Logger.PrintStub(LogClass.ServiceApm, "Stubbed."); diff --git a/Ryujinx.HLE/HOS/Services/Aud/AudioOut/IAudioOut.cs b/Ryujinx.HLE/HOS/Services/Aud/AudioOut/IAudioOut.cs index 1ad049c6..93bda210 100644 --- a/Ryujinx.HLE/HOS/Services/Aud/AudioOut/IAudioOut.cs +++ b/Ryujinx.HLE/HOS/Services/Aud/AudioOut/IAudioOut.cs @@ -9,19 +9,19 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioOut { class IAudioOut : IpcService, IDisposable { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - private IAalOutput AudioOut; + private IAalOutput _audioOut; - private KEvent ReleaseEvent; + private KEvent _releaseEvent; - private int Track; + private int _track; - public IAudioOut(IAalOutput AudioOut, KEvent ReleaseEvent, int Track) + public IAudioOut(IAalOutput audioOut, KEvent releaseEvent, int track) { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, GetAudioOutState }, { 1, StartAudioOut }, @@ -34,116 +34,116 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioOut { 8, GetReleasedAudioOutBufferAuto } }; - this.AudioOut = AudioOut; - this.ReleaseEvent = ReleaseEvent; - this.Track = Track; + _audioOut = audioOut; + _releaseEvent = releaseEvent; + _track = track; } - public long GetAudioOutState(ServiceCtx Context) + public long GetAudioOutState(ServiceCtx context) { - Context.ResponseData.Write((int)AudioOut.GetState(Track)); + context.ResponseData.Write((int)_audioOut.GetState(_track)); return 0; } - public long StartAudioOut(ServiceCtx Context) + public long StartAudioOut(ServiceCtx context) { - AudioOut.Start(Track); + _audioOut.Start(_track); return 0; } - public long StopAudioOut(ServiceCtx Context) + public long StopAudioOut(ServiceCtx context) { - AudioOut.Stop(Track); + _audioOut.Stop(_track); return 0; } - public long AppendAudioOutBuffer(ServiceCtx Context) + public long AppendAudioOutBuffer(ServiceCtx context) { - return AppendAudioOutBufferImpl(Context, Context.Request.SendBuff[0].Position); + return AppendAudioOutBufferImpl(context, context.Request.SendBuff[0].Position); } - public long RegisterBufferEvent(ServiceCtx Context) + public long RegisterBufferEvent(ServiceCtx context) { - if (Context.Process.HandleTable.GenerateHandle(ReleaseEvent.ReadableEvent, out int Handle) != KernelResult.Success) + if (context.Process.HandleTable.GenerateHandle(_releaseEvent.ReadableEvent, out int handle) != KernelResult.Success) { throw new InvalidOperationException("Out of handles!"); } - Context.Response.HandleDesc = IpcHandleDesc.MakeCopy(Handle); + context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); return 0; } - public long GetReleasedAudioOutBuffer(ServiceCtx Context) + public long GetReleasedAudioOutBuffer(ServiceCtx context) { - long Position = Context.Request.ReceiveBuff[0].Position; - long Size = Context.Request.ReceiveBuff[0].Size; + long position = context.Request.ReceiveBuff[0].Position; + long size = context.Request.ReceiveBuff[0].Size; - return GetReleasedAudioOutBufferImpl(Context, Position, Size); + return GetReleasedAudioOutBufferImpl(context, position, size); } - public long ContainsAudioOutBuffer(ServiceCtx Context) + public long ContainsAudioOutBuffer(ServiceCtx context) { - long Tag = Context.RequestData.ReadInt64(); + long tag = context.RequestData.ReadInt64(); - Context.ResponseData.Write(AudioOut.ContainsBuffer(Track, Tag) ? 1 : 0); + context.ResponseData.Write(_audioOut.ContainsBuffer(_track, tag) ? 1 : 0); return 0; } - public long AppendAudioOutBufferAuto(ServiceCtx Context) + public long AppendAudioOutBufferAuto(ServiceCtx context) { - (long Position, long Size) = Context.Request.GetBufferType0x21(); + (long position, long size) = context.Request.GetBufferType0x21(); - return AppendAudioOutBufferImpl(Context, Position); + return AppendAudioOutBufferImpl(context, position); } - public long AppendAudioOutBufferImpl(ServiceCtx Context, long Position) + public long AppendAudioOutBufferImpl(ServiceCtx context, long position) { - long Tag = Context.RequestData.ReadInt64(); + long tag = context.RequestData.ReadInt64(); - AudioOutData Data = MemoryHelper.Read( - Context.Memory, - Position); + AudioOutData data = MemoryHelper.Read( + context.Memory, + position); - byte[] Buffer = Context.Memory.ReadBytes( - Data.SampleBufferPtr, - Data.SampleBufferSize); + byte[] buffer = context.Memory.ReadBytes( + data.SampleBufferPtr, + data.SampleBufferSize); - AudioOut.AppendBuffer(Track, Tag, Buffer); + _audioOut.AppendBuffer(_track, tag, buffer); return 0; } - public long GetReleasedAudioOutBufferAuto(ServiceCtx Context) + public long GetReleasedAudioOutBufferAuto(ServiceCtx context) { - (long Position, long Size) = Context.Request.GetBufferType0x22(); + (long position, long size) = context.Request.GetBufferType0x22(); - return GetReleasedAudioOutBufferImpl(Context, Position, Size); + return GetReleasedAudioOutBufferImpl(context, position, size); } - public long GetReleasedAudioOutBufferImpl(ServiceCtx Context, long Position, long Size) + public long GetReleasedAudioOutBufferImpl(ServiceCtx context, long position, long size) { - uint Count = (uint)((ulong)Size >> 3); + uint count = (uint)((ulong)size >> 3); - long[] ReleasedBuffers = AudioOut.GetReleasedBuffers(Track, (int)Count); + long[] releasedBuffers = _audioOut.GetReleasedBuffers(_track, (int)count); - for (uint Index = 0; Index < Count; Index++) + for (uint index = 0; index < count; index++) { - long Tag = 0; + long tag = 0; - if (Index < ReleasedBuffers.Length) + if (index < releasedBuffers.Length) { - Tag = ReleasedBuffers[Index]; + tag = releasedBuffers[index]; } - Context.Memory.WriteInt64(Position + Index * 8, Tag); + context.Memory.WriteInt64(position + index * 8, tag); } - Context.ResponseData.Write(ReleasedBuffers.Length); + context.ResponseData.Write(releasedBuffers.Length); return 0; } @@ -153,11 +153,11 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioOut Dispose(true); } - protected virtual void Dispose(bool Disposing) + protected virtual void Dispose(bool disposing) { - if (Disposing) + if (disposing) { - AudioOut.CloseTrack(Track); + _audioOut.CloseTrack(_track); } } } diff --git a/Ryujinx.HLE/HOS/Services/Aud/AudioRenderer/IAudioRenderer.cs b/Ryujinx.HLE/HOS/Services/Aud/AudioRenderer/IAudioRenderer.cs index 50a87893..0ad193ca 100644 --- a/Ryujinx.HLE/HOS/Services/Aud/AudioRenderer/IAudioRenderer.cs +++ b/Ryujinx.HLE/HOS/Services/Aud/AudioRenderer/IAudioRenderer.cs @@ -22,33 +22,33 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer //high latency). private const int MixBufferSamplesCount = 960; - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - private KEvent UpdateEvent; + private KEvent _updateEvent; - private MemoryManager Memory; + private MemoryManager _memory; - private IAalOutput AudioOut; + private IAalOutput _audioOut; - private AudioRendererParameter Params; + private AudioRendererParameter _params; - private MemoryPoolContext[] MemoryPools; + private MemoryPoolContext[] _memoryPools; - private VoiceContext[] Voices; + private VoiceContext[] _voices; - private int Track; + private int _track; - private PlayState PlayState; + private PlayState _playState; public IAudioRenderer( - Horizon System, - MemoryManager Memory, - IAalOutput AudioOut, + Horizon system, + MemoryManager memory, + IAalOutput audioOut, AudioRendererParameter Params) { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, GetSampleRate }, { 1, GetSampleCount }, @@ -60,75 +60,75 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer { 7, QuerySystemEvent } }; - UpdateEvent = new KEvent(System); + _updateEvent = new KEvent(system); - this.Memory = Memory; - this.AudioOut = AudioOut; - this.Params = Params; + _memory = memory; + _audioOut = audioOut; + _params = Params; - Track = AudioOut.OpenTrack( + _track = audioOut.OpenTrack( AudioConsts.HostSampleRate, AudioConsts.HostChannelsCount, AudioCallback); - MemoryPools = CreateArray(Params.EffectCount + Params.VoiceCount * 4); + _memoryPools = CreateArray(Params.EffectCount + Params.VoiceCount * 4); - Voices = CreateArray(Params.VoiceCount); + _voices = CreateArray(Params.VoiceCount); InitializeAudioOut(); - PlayState = PlayState.Stopped; + _playState = PlayState.Stopped; } // GetSampleRate() -> u32 - public long GetSampleRate(ServiceCtx Context) + public long GetSampleRate(ServiceCtx context) { - Context.ResponseData.Write(Params.SampleRate); + context.ResponseData.Write(_params.SampleRate); return 0; } // GetSampleCount() -> u32 - public long GetSampleCount(ServiceCtx Context) + public long GetSampleCount(ServiceCtx context) { - Context.ResponseData.Write(Params.SampleCount); + context.ResponseData.Write(_params.SampleCount); return 0; } // GetMixBufferCount() -> u32 - public long GetMixBufferCount(ServiceCtx Context) + public long GetMixBufferCount(ServiceCtx context) { - Context.ResponseData.Write(Params.MixCount); + context.ResponseData.Write(_params.MixCount); return 0; } // GetState() -> u32 - private long GetState(ServiceCtx Context) + private long GetState(ServiceCtx context) { - Context.ResponseData.Write((int)PlayState); + context.ResponseData.Write((int)_playState); - Logger.PrintStub(LogClass.ServiceAudio, $"Stubbed. Renderer State: {Enum.GetName(typeof(PlayState), PlayState)}"); + Logger.PrintStub(LogClass.ServiceAudio, $"Stubbed. Renderer State: {Enum.GetName(typeof(PlayState), _playState)}"); return 0; } private void AudioCallback() { - UpdateEvent.ReadableEvent.Signal(); + _updateEvent.ReadableEvent.Signal(); } - private static T[] CreateArray(int Size) where T : new() + private static T[] CreateArray(int size) where T : new() { - T[] Output = new T[Size]; + T[] output = new T[size]; - for (int Index = 0; Index < Size; Index++) + for (int index = 0; index < size; index++) { - Output[Index] = new T(); + output[index] = new T(); } - return Output; + return output; } private void InitializeAudioOut() @@ -137,258 +137,258 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer AppendMixedBuffer(1); AppendMixedBuffer(2); - AudioOut.Start(Track); + _audioOut.Start(_track); } - public long RequestUpdateAudioRenderer(ServiceCtx Context) + public long RequestUpdateAudioRenderer(ServiceCtx context) { - long OutputPosition = Context.Request.ReceiveBuff[0].Position; - long OutputSize = Context.Request.ReceiveBuff[0].Size; + long outputPosition = context.Request.ReceiveBuff[0].Position; + long outputSize = context.Request.ReceiveBuff[0].Size; - MemoryHelper.FillWithZeros(Context.Memory, OutputPosition, (int)OutputSize); + MemoryHelper.FillWithZeros(context.Memory, outputPosition, (int)outputSize); - long InputPosition = Context.Request.SendBuff[0].Position; + long inputPosition = context.Request.SendBuff[0].Position; - StructReader Reader = new StructReader(Context.Memory, InputPosition); - StructWriter Writer = new StructWriter(Context.Memory, OutputPosition); + StructReader reader = new StructReader(context.Memory, inputPosition); + StructWriter writer = new StructWriter(context.Memory, outputPosition); - UpdateDataHeader InputHeader = Reader.Read(); + UpdateDataHeader inputHeader = reader.Read(); - Reader.Read(InputHeader.BehaviorSize); + reader.Read(inputHeader.BehaviorSize); - MemoryPoolIn[] MemoryPoolsIn = Reader.Read(InputHeader.MemoryPoolSize); + MemoryPoolIn[] memoryPoolsIn = reader.Read(inputHeader.MemoryPoolSize); - for (int Index = 0; Index < MemoryPoolsIn.Length; Index++) + for (int index = 0; index < memoryPoolsIn.Length; index++) { - MemoryPoolIn MemoryPool = MemoryPoolsIn[Index]; + MemoryPoolIn memoryPool = memoryPoolsIn[index]; - if (MemoryPool.State == MemoryPoolState.RequestAttach) + if (memoryPool.State == MemoryPoolState.RequestAttach) { - MemoryPools[Index].OutStatus.State = MemoryPoolState.Attached; + _memoryPools[index].OutStatus.State = MemoryPoolState.Attached; } - else if (MemoryPool.State == MemoryPoolState.RequestDetach) + else if (memoryPool.State == MemoryPoolState.RequestDetach) { - MemoryPools[Index].OutStatus.State = MemoryPoolState.Detached; + _memoryPools[index].OutStatus.State = MemoryPoolState.Detached; } } - Reader.Read(InputHeader.VoiceResourceSize); + reader.Read(inputHeader.VoiceResourceSize); - VoiceIn[] VoicesIn = Reader.Read(InputHeader.VoiceSize); + VoiceIn[] voicesIn = reader.Read(inputHeader.VoiceSize); - for (int Index = 0; Index < VoicesIn.Length; Index++) + for (int index = 0; index < voicesIn.Length; index++) { - VoiceIn Voice = VoicesIn[Index]; + VoiceIn voice = voicesIn[index]; - VoiceContext VoiceCtx = Voices[Index]; + VoiceContext voiceCtx = _voices[index]; - VoiceCtx.SetAcquireState(Voice.Acquired != 0); + voiceCtx.SetAcquireState(voice.Acquired != 0); - if (Voice.Acquired == 0) + if (voice.Acquired == 0) { continue; } - if (Voice.FirstUpdate != 0) + if (voice.FirstUpdate != 0) { - VoiceCtx.AdpcmCtx = GetAdpcmDecoderContext( - Voice.AdpcmCoeffsPosition, - Voice.AdpcmCoeffsSize); + voiceCtx.AdpcmCtx = GetAdpcmDecoderContext( + voice.AdpcmCoeffsPosition, + voice.AdpcmCoeffsSize); - VoiceCtx.SampleFormat = Voice.SampleFormat; - VoiceCtx.SampleRate = Voice.SampleRate; - VoiceCtx.ChannelsCount = Voice.ChannelsCount; + voiceCtx.SampleFormat = voice.SampleFormat; + voiceCtx.SampleRate = voice.SampleRate; + voiceCtx.ChannelsCount = voice.ChannelsCount; - VoiceCtx.SetBufferIndex(Voice.BaseWaveBufferIndex); + voiceCtx.SetBufferIndex(voice.BaseWaveBufferIndex); } - VoiceCtx.WaveBuffers[0] = Voice.WaveBuffer0; - VoiceCtx.WaveBuffers[1] = Voice.WaveBuffer1; - VoiceCtx.WaveBuffers[2] = Voice.WaveBuffer2; - VoiceCtx.WaveBuffers[3] = Voice.WaveBuffer3; - VoiceCtx.Volume = Voice.Volume; - VoiceCtx.PlayState = Voice.PlayState; + voiceCtx.WaveBuffers[0] = voice.WaveBuffer0; + voiceCtx.WaveBuffers[1] = voice.WaveBuffer1; + voiceCtx.WaveBuffers[2] = voice.WaveBuffer2; + voiceCtx.WaveBuffers[3] = voice.WaveBuffer3; + voiceCtx.Volume = voice.Volume; + voiceCtx.PlayState = voice.PlayState; } UpdateAudio(); - UpdateDataHeader OutputHeader = new UpdateDataHeader(); + UpdateDataHeader outputHeader = new UpdateDataHeader(); - int UpdateHeaderSize = Marshal.SizeOf(); + int updateHeaderSize = Marshal.SizeOf(); - OutputHeader.Revision = IAudioRendererManager.RevMagic; - OutputHeader.BehaviorSize = 0xb0; - OutputHeader.MemoryPoolSize = (Params.EffectCount + Params.VoiceCount * 4) * 0x10; - OutputHeader.VoiceSize = Params.VoiceCount * 0x10; - OutputHeader.EffectSize = Params.EffectCount * 0x10; - OutputHeader.SinkSize = Params.SinkCount * 0x20; - OutputHeader.PerformanceManagerSize = 0x10; - OutputHeader.TotalSize = UpdateHeaderSize + - OutputHeader.BehaviorSize + - OutputHeader.MemoryPoolSize + - OutputHeader.VoiceSize + - OutputHeader.EffectSize + - OutputHeader.SinkSize + - OutputHeader.PerformanceManagerSize; + outputHeader.Revision = IAudioRendererManager.RevMagic; + outputHeader.BehaviorSize = 0xb0; + outputHeader.MemoryPoolSize = (_params.EffectCount + _params.VoiceCount * 4) * 0x10; + outputHeader.VoiceSize = _params.VoiceCount * 0x10; + outputHeader.EffectSize = _params.EffectCount * 0x10; + outputHeader.SinkSize = _params.SinkCount * 0x20; + outputHeader.PerformanceManagerSize = 0x10; + outputHeader.TotalSize = updateHeaderSize + + outputHeader.BehaviorSize + + outputHeader.MemoryPoolSize + + outputHeader.VoiceSize + + outputHeader.EffectSize + + outputHeader.SinkSize + + outputHeader.PerformanceManagerSize; - Writer.Write(OutputHeader); + writer.Write(outputHeader); - foreach (MemoryPoolContext MemoryPool in MemoryPools) + foreach (MemoryPoolContext memoryPool in _memoryPools) { - Writer.Write(MemoryPool.OutStatus); + writer.Write(memoryPool.OutStatus); } - foreach (VoiceContext Voice in Voices) + foreach (VoiceContext voice in _voices) { - Writer.Write(Voice.OutStatus); + writer.Write(voice.OutStatus); } return 0; } - public long StartAudioRenderer(ServiceCtx Context) + public long StartAudioRenderer(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceAudio, "Stubbed."); - PlayState = PlayState.Playing; + _playState = PlayState.Playing; return 0; } - public long StopAudioRenderer(ServiceCtx Context) + public long StopAudioRenderer(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceAudio, "Stubbed."); - PlayState = PlayState.Stopped; + _playState = PlayState.Stopped; return 0; } - public long QuerySystemEvent(ServiceCtx Context) + public long QuerySystemEvent(ServiceCtx context) { - if (Context.Process.HandleTable.GenerateHandle(UpdateEvent.ReadableEvent, out int Handle) != KernelResult.Success) + if (context.Process.HandleTable.GenerateHandle(_updateEvent.ReadableEvent, out int handle) != KernelResult.Success) { throw new InvalidOperationException("Out of handles!"); } - Context.Response.HandleDesc = IpcHandleDesc.MakeCopy(Handle); + context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); return 0; } - private AdpcmDecoderContext GetAdpcmDecoderContext(long Position, long Size) + private AdpcmDecoderContext GetAdpcmDecoderContext(long position, long size) { - if (Size == 0) + if (size == 0) { return null; } - AdpcmDecoderContext Context = new AdpcmDecoderContext(); + AdpcmDecoderContext context = new AdpcmDecoderContext(); - Context.Coefficients = new short[Size >> 1]; + context.Coefficients = new short[size >> 1]; - for (int Offset = 0; Offset < Size; Offset += 2) + for (int offset = 0; offset < size; offset += 2) { - Context.Coefficients[Offset >> 1] = Memory.ReadInt16(Position + Offset); + context.Coefficients[offset >> 1] = _memory.ReadInt16(position + offset); } - return Context; + return context; } private void UpdateAudio() { - long[] Released = AudioOut.GetReleasedBuffers(Track, 2); + long[] released = _audioOut.GetReleasedBuffers(_track, 2); - for (int Index = 0; Index < Released.Length; Index++) + for (int index = 0; index < released.Length; index++) { - AppendMixedBuffer(Released[Index]); + AppendMixedBuffer(released[index]); } } - private unsafe void AppendMixedBuffer(long Tag) + private void AppendMixedBuffer(long tag) { - int[] MixBuffer = new int[MixBufferSamplesCount * AudioConsts.HostChannelsCount]; + int[] mixBuffer = new int[MixBufferSamplesCount * AudioConsts.HostChannelsCount]; - foreach (VoiceContext Voice in Voices) + foreach (VoiceContext voice in _voices) { - if (!Voice.Playing) + if (!voice.Playing) { continue; } - int OutOffset = 0; - int PendingSamples = MixBufferSamplesCount; - float Volume = Voice.Volume; + int outOffset = 0; + int pendingSamples = MixBufferSamplesCount; + float volume = voice.Volume; - while (PendingSamples > 0) + while (pendingSamples > 0) { - int[] Samples = Voice.GetBufferData(Memory, PendingSamples, out int ReturnedSamples); + int[] samples = voice.GetBufferData(_memory, pendingSamples, out int returnedSamples); - if (ReturnedSamples == 0) + if (returnedSamples == 0) { break; } - PendingSamples -= ReturnedSamples; + pendingSamples -= returnedSamples; - for (int Offset = 0; Offset < Samples.Length; Offset++) + for (int offset = 0; offset < samples.Length; offset++) { - MixBuffer[OutOffset++] += (int)(Samples[Offset] * Voice.Volume); + mixBuffer[outOffset++] += (int)(samples[offset] * voice.Volume); } } } - AudioOut.AppendBuffer(Track, Tag, GetFinalBuffer(MixBuffer)); + _audioOut.AppendBuffer(_track, tag, GetFinalBuffer(mixBuffer)); } - private unsafe static short[] GetFinalBuffer(int[] Buffer) + private unsafe static short[] GetFinalBuffer(int[] buffer) { - short[] Output = new short[Buffer.Length]; + short[] output = new short[buffer.Length]; - int Offset = 0; + int offset = 0; // Perform Saturation using SSE2 if supported if (Sse2.IsSupported) { - fixed (int* inptr = Buffer) - fixed (short* outptr = Output) + fixed (int* inptr = buffer) + fixed (short* outptr = output) { - for (; Offset + 32 <= Buffer.Length; Offset += 32) + for (; offset + 32 <= buffer.Length; offset += 32) { // Unroll the loop a little to ensure the CPU pipeline // is always full. - Vector128 block1A = Sse2.LoadVector128(inptr + Offset + 0); - Vector128 block1B = Sse2.LoadVector128(inptr + Offset + 4); + Vector128 block1A = Sse2.LoadVector128(inptr + offset + 0); + Vector128 block1B = Sse2.LoadVector128(inptr + offset + 4); - Vector128 block2A = Sse2.LoadVector128(inptr + Offset + 8); - Vector128 block2B = Sse2.LoadVector128(inptr + Offset + 12); + Vector128 block2A = Sse2.LoadVector128(inptr + offset + 8); + Vector128 block2B = Sse2.LoadVector128(inptr + offset + 12); - Vector128 block3A = Sse2.LoadVector128(inptr + Offset + 16); - Vector128 block3B = Sse2.LoadVector128(inptr + Offset + 20); + Vector128 block3A = Sse2.LoadVector128(inptr + offset + 16); + Vector128 block3B = Sse2.LoadVector128(inptr + offset + 20); - Vector128 block4A = Sse2.LoadVector128(inptr + Offset + 24); - Vector128 block4B = Sse2.LoadVector128(inptr + Offset + 28); + Vector128 block4A = Sse2.LoadVector128(inptr + offset + 24); + Vector128 block4B = Sse2.LoadVector128(inptr + offset + 28); Vector128 output1 = Sse2.PackSignedSaturate(block1A, block1B); Vector128 output2 = Sse2.PackSignedSaturate(block2A, block2B); Vector128 output3 = Sse2.PackSignedSaturate(block3A, block3B); Vector128 output4 = Sse2.PackSignedSaturate(block4A, block4B); - Sse2.Store(outptr + Offset + 0, output1); - Sse2.Store(outptr + Offset + 8, output2); - Sse2.Store(outptr + Offset + 16, output3); - Sse2.Store(outptr + Offset + 24, output4); + Sse2.Store(outptr + offset + 0, output1); + Sse2.Store(outptr + offset + 8, output2); + Sse2.Store(outptr + offset + 16, output3); + Sse2.Store(outptr + offset + 24, output4); } } } // Process left overs - for (; Offset < Buffer.Length; Offset++) + for (; offset < buffer.Length; offset++) { - Output[Offset] = DspUtils.Saturate(Buffer[Offset]); + output[offset] = DspUtils.Saturate(buffer[offset]); } - return Output; + return output; } public void Dispose() @@ -396,11 +396,11 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer Dispose(true); } - protected virtual void Dispose(bool Disposing) + protected virtual void Dispose(bool disposing) { - if (Disposing) + if (disposing) { - AudioOut.CloseTrack(Track); + _audioOut.CloseTrack(_track); } } } diff --git a/Ryujinx.HLE/HOS/Services/Aud/AudioRenderer/MemoryPoolState.cs b/Ryujinx.HLE/HOS/Services/Aud/AudioRenderer/MemoryPoolState.cs index 6baf507c..6a37c1af 100644 --- a/Ryujinx.HLE/HOS/Services/Aud/AudioRenderer/MemoryPoolState.cs +++ b/Ryujinx.HLE/HOS/Services/Aud/AudioRenderer/MemoryPoolState.cs @@ -1,6 +1,6 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer { - enum MemoryPoolState : int + enum MemoryPoolState { Invalid = 0, Unknown = 1, diff --git a/Ryujinx.HLE/HOS/Services/Aud/AudioRenderer/Resampler.cs b/Ryujinx.HLE/HOS/Services/Aud/AudioRenderer/Resampler.cs index baa0bc62..9714f6d8 100644 --- a/Ryujinx.HLE/HOS/Services/Aud/AudioRenderer/Resampler.cs +++ b/Ryujinx.HLE/HOS/Services/Aud/AudioRenderer/Resampler.cs @@ -5,7 +5,7 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer static class Resampler { #region "LookUp Tables" - private static short[] CurveLut0 = new short[] + private static short[] _curveLut0 = new short[] { 6600, 19426, 6722, 3, 6479, 19424, 6845, 9, 6359, 19419, 6968, 15, 6239, 19412, 7093, 22, 6121, 19403, 7219, 28, 6004, 19391, 7345, 34, 5888, 19377, 7472, 41, 5773, 19361, 7600, 48, @@ -41,7 +41,7 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer 22, 7093, 19412, 6239, 15, 6968, 19419, 6359, 9, 6845, 19424, 6479, 3, 6722, 19426, 6600 }; - private static short[] CurveLut1 = new short[] + private static short[] _curveLut1 = new short[] { -68, 32639, 69, -5, -200, 32630, 212, -15, -328, 32613, 359, -26, -450, 32586, 512, -36, -568, 32551, 669, -47, -680, 32507, 832, -58, -788, 32454, 1000, -69, -891, 32393, 1174, -80, @@ -77,7 +77,7 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer -36, 512, 32586, -450, -26, 359, 32613, -328, -15, 212, 32630, -200, -5, 69, 32639, -68 }; - private static short[] CurveLut2 = new short[] + private static short[] _curveLut2 = new short[] { 3195, 26287, 3329, -32, 3064, 26281, 3467, -34, 2936, 26270, 3608, -38, 2811, 26253, 3751, -42, 2688, 26230, 3897, -46, 2568, 26202, 4046, -50, 2451, 26169, 4199, -54, 2338, 26130, 4354, -58, @@ -115,77 +115,77 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer #endregion public static int[] Resample2Ch( - int[] Buffer, - int SrcSampleRate, - int DstSampleRate, - int SamplesCount, - ref int FracPart) + int[] buffer, + int srcSampleRate, + int dstSampleRate, + int samplesCount, + ref int fracPart) { - if (Buffer == null) + if (buffer == null) { - throw new ArgumentNullException(nameof(Buffer)); + throw new ArgumentNullException(nameof(buffer)); } - if (SrcSampleRate <= 0) + if (srcSampleRate <= 0) { - throw new ArgumentOutOfRangeException(nameof(SrcSampleRate)); + throw new ArgumentOutOfRangeException(nameof(srcSampleRate)); } - if (DstSampleRate <= 0) + if (dstSampleRate <= 0) { - throw new ArgumentOutOfRangeException(nameof(DstSampleRate)); + throw new ArgumentOutOfRangeException(nameof(dstSampleRate)); } - double Ratio = (double)SrcSampleRate / DstSampleRate; + double ratio = (double)srcSampleRate / dstSampleRate; - int NewSamplesCount = (int)(SamplesCount / Ratio); + int newSamplesCount = (int)(samplesCount / ratio); - int Step = (int)(Ratio * 0x8000); + int step = (int)(ratio * 0x8000); - int[] Output = new int[NewSamplesCount * 2]; + int[] output = new int[newSamplesCount * 2]; - short[] Lut; + short[] lut; - if (Step > 0xaaaa) + if (step > 0xaaaa) { - Lut = CurveLut0; + lut = _curveLut0; } - else if (Step <= 0x8000) + else if (step <= 0x8000) { - Lut = CurveLut1; + lut = _curveLut1; } else { - Lut = CurveLut2; + lut = _curveLut2; } - int InOffs = 0; + int inOffs = 0; - for (int OutOffs = 0; OutOffs < Output.Length; OutOffs += 2) + for (int outOffs = 0; outOffs < output.Length; outOffs += 2) { - int LutIndex = (FracPart >> 8) * 4; + int lutIndex = (fracPart >> 8) * 4; - int Sample0 = Buffer[(InOffs + 0) * 2 + 0] * Lut[LutIndex + 0] + - Buffer[(InOffs + 1) * 2 + 0] * Lut[LutIndex + 1] + - Buffer[(InOffs + 2) * 2 + 0] * Lut[LutIndex + 2] + - Buffer[(InOffs + 3) * 2 + 0] * Lut[LutIndex + 3]; + int sample0 = buffer[(inOffs + 0) * 2 + 0] * lut[lutIndex + 0] + + buffer[(inOffs + 1) * 2 + 0] * lut[lutIndex + 1] + + buffer[(inOffs + 2) * 2 + 0] * lut[lutIndex + 2] + + buffer[(inOffs + 3) * 2 + 0] * lut[lutIndex + 3]; - int Sample1 = Buffer[(InOffs + 0) * 2 + 1] * Lut[LutIndex + 0] + - Buffer[(InOffs + 1) * 2 + 1] * Lut[LutIndex + 1] + - Buffer[(InOffs + 2) * 2 + 1] * Lut[LutIndex + 2] + - Buffer[(InOffs + 3) * 2 + 1] * Lut[LutIndex + 3]; + int sample1 = buffer[(inOffs + 0) * 2 + 1] * lut[lutIndex + 0] + + buffer[(inOffs + 1) * 2 + 1] * lut[lutIndex + 1] + + buffer[(inOffs + 2) * 2 + 1] * lut[lutIndex + 2] + + buffer[(inOffs + 3) * 2 + 1] * lut[lutIndex + 3]; - int NewOffset = FracPart + Step; + int newOffset = fracPart + step; - InOffs += NewOffset >> 15; + inOffs += newOffset >> 15; - FracPart = NewOffset & 0x7fff; + fracPart = newOffset & 0x7fff; - Output[OutOffs + 0] = Sample0 >> 15; - Output[OutOffs + 1] = Sample1 >> 15; + output[outOffs + 0] = sample0 >> 15; + output[outOffs + 1] = sample1 >> 15; } - return Output; + return output; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Services/Aud/AudioRenderer/VoiceContext.cs b/Ryujinx.HLE/HOS/Services/Aud/AudioRenderer/VoiceContext.cs index 7d6e1c58..a877081d 100644 --- a/Ryujinx.HLE/HOS/Services/Aud/AudioRenderer/VoiceContext.cs +++ b/Ryujinx.HLE/HOS/Services/Aud/AudioRenderer/VoiceContext.cs @@ -6,13 +6,13 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer { class VoiceContext { - private bool Acquired; - private bool BufferReload; + private bool _acquired; + private bool _bufferReload; - private int ResamplerFracPart; + private int _resamplerFracPart; - private int BufferIndex; - private int Offset; + private int _bufferIndex; + private int _offset; public int SampleRate; public int ChannelsCount; @@ -29,138 +29,138 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer public VoiceOut OutStatus; - private int[] Samples; + private int[] _samples; - public bool Playing => Acquired && PlayState == PlayState.Playing; + public bool Playing => _acquired && PlayState == PlayState.Playing; public VoiceContext() { WaveBuffers = new WaveBuffer[4]; } - public void SetAcquireState(bool NewState) + public void SetAcquireState(bool newState) { - if (Acquired && !NewState) + if (_acquired && !newState) { //Release. Reset(); } - Acquired = NewState; + _acquired = newState; } private void Reset() { - BufferReload = true; + _bufferReload = true; - BufferIndex = 0; - Offset = 0; + _bufferIndex = 0; + _offset = 0; OutStatus.PlayedSamplesCount = 0; OutStatus.PlayedWaveBuffersCount = 0; OutStatus.VoiceDropsCount = 0; } - public int[] GetBufferData(MemoryManager Memory, int MaxSamples, out int SamplesCount) + public int[] GetBufferData(MemoryManager memory, int maxSamples, out int samplesCount) { if (!Playing) { - SamplesCount = 0; + samplesCount = 0; return null; } - if (BufferReload) + if (_bufferReload) { - BufferReload = false; + _bufferReload = false; - UpdateBuffer(Memory); + UpdateBuffer(memory); } - WaveBuffer Wb = WaveBuffers[BufferIndex]; + WaveBuffer wb = WaveBuffers[_bufferIndex]; - int MaxSize = Samples.Length - Offset; + int maxSize = _samples.Length - _offset; - int Size = MaxSamples * AudioConsts.HostChannelsCount; + int size = maxSamples * AudioConsts.HostChannelsCount; - if (Size > MaxSize) + if (size > maxSize) { - Size = MaxSize; + size = maxSize; } - int[] Output = new int[Size]; + int[] output = new int[size]; - Array.Copy(Samples, Offset, Output, 0, Size); + Array.Copy(_samples, _offset, output, 0, size); - SamplesCount = Size / AudioConsts.HostChannelsCount; + samplesCount = size / AudioConsts.HostChannelsCount; - OutStatus.PlayedSamplesCount += SamplesCount; + OutStatus.PlayedSamplesCount += samplesCount; - Offset += Size; + _offset += size; - if (Offset == Samples.Length) + if (_offset == _samples.Length) { - Offset = 0; + _offset = 0; - if (Wb.Looping == 0) + if (wb.Looping == 0) { - SetBufferIndex((BufferIndex + 1) & 3); + SetBufferIndex((_bufferIndex + 1) & 3); } OutStatus.PlayedWaveBuffersCount++; - if (Wb.LastBuffer != 0) + if (wb.LastBuffer != 0) { PlayState = PlayState.Paused; } } - return Output; + return output; } - private void UpdateBuffer(MemoryManager Memory) + private void UpdateBuffer(MemoryManager memory) { //TODO: Implement conversion for formats other //than interleaved stereo (2 channels). //As of now, it assumes that HostChannelsCount == 2. - WaveBuffer Wb = WaveBuffers[BufferIndex]; + WaveBuffer wb = WaveBuffers[_bufferIndex]; - if (Wb.Position == 0) + if (wb.Position == 0) { - Samples = new int[0]; + _samples = new int[0]; return; } if (SampleFormat == SampleFormat.PcmInt16) { - int SamplesCount = (int)(Wb.Size / (sizeof(short) * ChannelsCount)); + int samplesCount = (int)(wb.Size / (sizeof(short) * ChannelsCount)); - Samples = new int[SamplesCount * AudioConsts.HostChannelsCount]; + _samples = new int[samplesCount * AudioConsts.HostChannelsCount]; if (ChannelsCount == 1) { - for (int Index = 0; Index < SamplesCount; Index++) + for (int index = 0; index < samplesCount; index++) { - short Sample = Memory.ReadInt16(Wb.Position + Index * 2); + short sample = memory.ReadInt16(wb.Position + index * 2); - Samples[Index * 2 + 0] = Sample; - Samples[Index * 2 + 1] = Sample; + _samples[index * 2 + 0] = sample; + _samples[index * 2 + 1] = sample; } } else { - for (int Index = 0; Index < SamplesCount * 2; Index++) + for (int index = 0; index < samplesCount * 2; index++) { - Samples[Index] = Memory.ReadInt16(Wb.Position + Index * 2); + _samples[index] = memory.ReadInt16(wb.Position + index * 2); } } } else if (SampleFormat == SampleFormat.Adpcm) { - byte[] Buffer = Memory.ReadBytes(Wb.Position, Wb.Size); + byte[] buffer = memory.ReadBytes(wb.Position, wb.Size); - Samples = AdpcmDecoder.Decode(Buffer, AdpcmCtx); + _samples = AdpcmDecoder.Decode(buffer, AdpcmCtx); } else { @@ -172,24 +172,24 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer //TODO: We should keep the frames being discarded (see the 4 below) //on a buffer and include it on the next samples buffer, to allow //the resampler to do seamless interpolation between wave buffers. - int SamplesCount = Samples.Length / AudioConsts.HostChannelsCount; + int samplesCount = _samples.Length / AudioConsts.HostChannelsCount; - SamplesCount = Math.Max(SamplesCount - 4, 0); + samplesCount = Math.Max(samplesCount - 4, 0); - Samples = Resampler.Resample2Ch( - Samples, + _samples = Resampler.Resample2Ch( + _samples, SampleRate, AudioConsts.HostSampleRate, - SamplesCount, - ref ResamplerFracPart); + samplesCount, + ref _resamplerFracPart); } } - public void SetBufferIndex(int Index) + public void SetBufferIndex(int index) { - BufferIndex = Index & 3; + _bufferIndex = index & 3; - BufferReload = true; + _bufferReload = true; } } } diff --git a/Ryujinx.HLE/HOS/Services/Aud/IAudioDevice.cs b/Ryujinx.HLE/HOS/Services/Aud/IAudioDevice.cs index f9c0d315..585d7e43 100644 --- a/Ryujinx.HLE/HOS/Services/Aud/IAudioDevice.cs +++ b/Ryujinx.HLE/HOS/Services/Aud/IAudioDevice.cs @@ -10,15 +10,15 @@ namespace Ryujinx.HLE.HOS.Services.Aud { class IAudioDevice : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - private KEvent SystemEvent; + private KEvent _systemEvent; - public IAudioDevice(Horizon System) + public IAudioDevice(Horizon system) { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, ListAudioDeviceName }, { 1, SetAudioDeviceOutputVolume }, @@ -33,197 +33,197 @@ namespace Ryujinx.HLE.HOS.Services.Aud { 12, QueryAudioDeviceOutputEvent } }; - SystemEvent = new KEvent(System); + _systemEvent = new KEvent(system); //TODO: We shouldn't be signaling this here. - SystemEvent.ReadableEvent.Signal(); + _systemEvent.ReadableEvent.Signal(); } - public long ListAudioDeviceName(ServiceCtx Context) + public long ListAudioDeviceName(ServiceCtx context) { - string[] DeviceNames = SystemStateMgr.AudioOutputs; + string[] deviceNames = SystemStateMgr.AudioOutputs; - Context.ResponseData.Write(DeviceNames.Length); + context.ResponseData.Write(deviceNames.Length); - long Position = Context.Request.ReceiveBuff[0].Position; - long Size = Context.Request.ReceiveBuff[0].Size; + long position = context.Request.ReceiveBuff[0].Position; + long size = context.Request.ReceiveBuff[0].Size; - long BasePosition = Position; + long basePosition = position; - foreach (string Name in DeviceNames) + foreach (string name in deviceNames) { - byte[] Buffer = Encoding.ASCII.GetBytes(Name + "\0"); + byte[] buffer = Encoding.ASCII.GetBytes(name + "\0"); - if ((Position - BasePosition) + Buffer.Length > Size) + if ((position - basePosition) + buffer.Length > size) { - Logger.PrintError(LogClass.ServiceAudio, $"Output buffer size {Size} too small!"); + Logger.PrintError(LogClass.ServiceAudio, $"Output buffer size {size} too small!"); break; } - Context.Memory.WriteBytes(Position, Buffer); + context.Memory.WriteBytes(position, buffer); - Position += Buffer.Length; + position += buffer.Length; } return 0; } - public long SetAudioDeviceOutputVolume(ServiceCtx Context) + public long SetAudioDeviceOutputVolume(ServiceCtx context) { - float Volume = Context.RequestData.ReadSingle(); + float volume = context.RequestData.ReadSingle(); - long Position = Context.Request.SendBuff[0].Position; - long Size = Context.Request.SendBuff[0].Size; + long position = context.Request.SendBuff[0].Position; + long size = context.Request.SendBuff[0].Size; - byte[] DeviceNameBuffer = Context.Memory.ReadBytes(Position, Size); + byte[] deviceNameBuffer = context.Memory.ReadBytes(position, size); - string DeviceName = Encoding.ASCII.GetString(DeviceNameBuffer); + string deviceName = Encoding.ASCII.GetString(deviceNameBuffer); Logger.PrintStub(LogClass.ServiceAudio, "Stubbed."); return 0; } - public long GetActiveAudioDeviceName(ServiceCtx Context) + public long GetActiveAudioDeviceName(ServiceCtx context) { - string Name = Context.Device.System.State.ActiveAudioOutput; + string name = context.Device.System.State.ActiveAudioOutput; - long Position = Context.Request.ReceiveBuff[0].Position; - long Size = Context.Request.ReceiveBuff[0].Size; + long position = context.Request.ReceiveBuff[0].Position; + long size = context.Request.ReceiveBuff[0].Size; - byte[] DeviceNameBuffer = Encoding.ASCII.GetBytes(Name + "\0"); + byte[] deviceNameBuffer = Encoding.ASCII.GetBytes(name + "\0"); - if ((ulong)DeviceNameBuffer.Length <= (ulong)Size) + if ((ulong)deviceNameBuffer.Length <= (ulong)size) { - Context.Memory.WriteBytes(Position, DeviceNameBuffer); + context.Memory.WriteBytes(position, deviceNameBuffer); } else { - Logger.PrintError(LogClass.ServiceAudio, $"Output buffer size {Size} too small!"); + Logger.PrintError(LogClass.ServiceAudio, $"Output buffer size {size} too small!"); } return 0; } - public long QueryAudioDeviceSystemEvent(ServiceCtx Context) + public long QueryAudioDeviceSystemEvent(ServiceCtx context) { - if (Context.Process.HandleTable.GenerateHandle(SystemEvent.ReadableEvent, out int Handle) != KernelResult.Success) + if (context.Process.HandleTable.GenerateHandle(_systemEvent.ReadableEvent, out int handle) != KernelResult.Success) { throw new InvalidOperationException("Out of handles!"); } - Context.Response.HandleDesc = IpcHandleDesc.MakeCopy(Handle); + context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); Logger.PrintStub(LogClass.ServiceAudio, "Stubbed."); return 0; } - public long GetActiveChannelCount(ServiceCtx Context) + public long GetActiveChannelCount(ServiceCtx context) { - Context.ResponseData.Write(2); + context.ResponseData.Write(2); Logger.PrintStub(LogClass.ServiceAudio, "Stubbed."); return 0; } - public long ListAudioDeviceNameAuto(ServiceCtx Context) + public long ListAudioDeviceNameAuto(ServiceCtx context) { - string[] DeviceNames = SystemStateMgr.AudioOutputs; + string[] deviceNames = SystemStateMgr.AudioOutputs; - Context.ResponseData.Write(DeviceNames.Length); + context.ResponseData.Write(deviceNames.Length); - (long Position, long Size) = Context.Request.GetBufferType0x22(); + (long position, long size) = context.Request.GetBufferType0x22(); - long BasePosition = Position; + long basePosition = position; - foreach (string Name in DeviceNames) + foreach (string name in deviceNames) { - byte[] Buffer = Encoding.UTF8.GetBytes(Name + '\0'); + byte[] buffer = Encoding.UTF8.GetBytes(name + '\0'); - if ((Position - BasePosition) + Buffer.Length > Size) + if ((position - basePosition) + buffer.Length > size) { - Logger.PrintError(LogClass.ServiceAudio, $"Output buffer size {Size} too small!"); + Logger.PrintError(LogClass.ServiceAudio, $"Output buffer size {size} too small!"); break; } - Context.Memory.WriteBytes(Position, Buffer); + context.Memory.WriteBytes(position, buffer); - Position += Buffer.Length; + position += buffer.Length; } return 0; } - public long SetAudioDeviceOutputVolumeAuto(ServiceCtx Context) + public long SetAudioDeviceOutputVolumeAuto(ServiceCtx context) { - float Volume = Context.RequestData.ReadSingle(); + float volume = context.RequestData.ReadSingle(); - (long Position, long Size) = Context.Request.GetBufferType0x21(); + (long position, long size) = context.Request.GetBufferType0x21(); - byte[] DeviceNameBuffer = Context.Memory.ReadBytes(Position, Size); + byte[] deviceNameBuffer = context.Memory.ReadBytes(position, size); - string DeviceName = Encoding.UTF8.GetString(DeviceNameBuffer); + string deviceName = Encoding.UTF8.GetString(deviceNameBuffer); Logger.PrintStub(LogClass.ServiceAudio, "Stubbed."); return 0; } - public long GetAudioDeviceOutputVolumeAuto(ServiceCtx Context) + public long GetAudioDeviceOutputVolumeAuto(ServiceCtx context) { - Context.ResponseData.Write(1f); + context.ResponseData.Write(1f); Logger.PrintStub(LogClass.ServiceAudio, "Stubbed."); return 0; } - public long GetActiveAudioDeviceNameAuto(ServiceCtx Context) + public long GetActiveAudioDeviceNameAuto(ServiceCtx context) { - string Name = Context.Device.System.State.ActiveAudioOutput; + string name = context.Device.System.State.ActiveAudioOutput; - (long Position, long Size) = Context.Request.GetBufferType0x22(); + (long position, long size) = context.Request.GetBufferType0x22(); - byte[] DeviceNameBuffer = Encoding.UTF8.GetBytes(Name + '\0'); + byte[] deviceNameBuffer = Encoding.UTF8.GetBytes(name + '\0'); - if ((ulong)DeviceNameBuffer.Length <= (ulong)Size) + if ((ulong)deviceNameBuffer.Length <= (ulong)size) { - Context.Memory.WriteBytes(Position, DeviceNameBuffer); + context.Memory.WriteBytes(position, deviceNameBuffer); } else { - Logger.PrintError(LogClass.ServiceAudio, $"Output buffer size {Size} too small!"); + Logger.PrintError(LogClass.ServiceAudio, $"Output buffer size {size} too small!"); } return 0; } - public long QueryAudioDeviceInputEvent(ServiceCtx Context) + public long QueryAudioDeviceInputEvent(ServiceCtx context) { - if (Context.Process.HandleTable.GenerateHandle(SystemEvent.ReadableEvent, out int Handle) != KernelResult.Success) + if (context.Process.HandleTable.GenerateHandle(_systemEvent.ReadableEvent, out int handle) != KernelResult.Success) { throw new InvalidOperationException("Out of handles!"); } - Context.Response.HandleDesc = IpcHandleDesc.MakeCopy(Handle); + context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); Logger.PrintStub(LogClass.ServiceAudio, "Stubbed."); return 0; } - public long QueryAudioDeviceOutputEvent(ServiceCtx Context) + public long QueryAudioDeviceOutputEvent(ServiceCtx context) { - if (Context.Process.HandleTable.GenerateHandle(SystemEvent.ReadableEvent, out int Handle) != KernelResult.Success) + if (context.Process.HandleTable.GenerateHandle(_systemEvent.ReadableEvent, out int handle) != KernelResult.Success) { throw new InvalidOperationException("Out of handles!"); } - Context.Response.HandleDesc = IpcHandleDesc.MakeCopy(Handle); + context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); Logger.PrintStub(LogClass.ServiceAudio, "Stubbed."); diff --git a/Ryujinx.HLE/HOS/Services/Aud/IAudioOutManager.cs b/Ryujinx.HLE/HOS/Services/Aud/IAudioOutManager.cs index b08f7640..4b1440a0 100644 --- a/Ryujinx.HLE/HOS/Services/Aud/IAudioOutManager.cs +++ b/Ryujinx.HLE/HOS/Services/Aud/IAudioOutManager.cs @@ -19,13 +19,13 @@ namespace Ryujinx.HLE.HOS.Services.Aud private const int DefaultChannelsCount = 2; - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IAudioOutManager() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, ListAudioOuts }, { 1, OpenAudioOut }, @@ -34,135 +34,135 @@ namespace Ryujinx.HLE.HOS.Services.Aud }; } - public long ListAudioOuts(ServiceCtx Context) + public long ListAudioOuts(ServiceCtx context) { return ListAudioOutsImpl( - Context, - Context.Request.ReceiveBuff[0].Position, - Context.Request.ReceiveBuff[0].Size); + context, + context.Request.ReceiveBuff[0].Position, + context.Request.ReceiveBuff[0].Size); } - public long OpenAudioOut(ServiceCtx Context) + public long OpenAudioOut(ServiceCtx context) { return OpenAudioOutImpl( - Context, - Context.Request.SendBuff[0].Position, - Context.Request.SendBuff[0].Size, - Context.Request.ReceiveBuff[0].Position, - Context.Request.ReceiveBuff[0].Size); + context, + context.Request.SendBuff[0].Position, + context.Request.SendBuff[0].Size, + context.Request.ReceiveBuff[0].Position, + context.Request.ReceiveBuff[0].Size); } - public long ListAudioOutsAuto(ServiceCtx Context) + public long ListAudioOutsAuto(ServiceCtx context) { - (long RecvPosition, long RecvSize) = Context.Request.GetBufferType0x22(); + (long recvPosition, long recvSize) = context.Request.GetBufferType0x22(); - return ListAudioOutsImpl(Context, RecvPosition, RecvSize); + return ListAudioOutsImpl(context, recvPosition, recvSize); } - public long OpenAudioOutAuto(ServiceCtx Context) + public long OpenAudioOutAuto(ServiceCtx context) { - (long SendPosition, long SendSize) = Context.Request.GetBufferType0x21(); - (long RecvPosition, long RecvSize) = Context.Request.GetBufferType0x22(); + (long sendPosition, long sendSize) = context.Request.GetBufferType0x21(); + (long recvPosition, long recvSize) = context.Request.GetBufferType0x22(); return OpenAudioOutImpl( - Context, - SendPosition, - SendSize, - RecvPosition, - RecvSize); + context, + sendPosition, + sendSize, + recvPosition, + recvSize); } - private long ListAudioOutsImpl(ServiceCtx Context, long Position, long Size) + private long ListAudioOutsImpl(ServiceCtx context, long position, long size) { - int NameCount = 0; + int nameCount = 0; - byte[] DeviceNameBuffer = Encoding.ASCII.GetBytes(DefaultAudioOutput + "\0"); + byte[] deviceNameBuffer = Encoding.ASCII.GetBytes(DefaultAudioOutput + "\0"); - if ((ulong)DeviceNameBuffer.Length <= (ulong)Size) + if ((ulong)deviceNameBuffer.Length <= (ulong)size) { - Context.Memory.WriteBytes(Position, DeviceNameBuffer); + context.Memory.WriteBytes(position, deviceNameBuffer); - NameCount++; + nameCount++; } else { - Logger.PrintError(LogClass.ServiceAudio, $"Output buffer size {Size} too small!"); + Logger.PrintError(LogClass.ServiceAudio, $"Output buffer size {size} too small!"); } - Context.ResponseData.Write(NameCount); + context.ResponseData.Write(nameCount); return 0; } - private long OpenAudioOutImpl(ServiceCtx Context, long SendPosition, long SendSize, long ReceivePosition, long ReceiveSize) + private long OpenAudioOutImpl(ServiceCtx context, long sendPosition, long sendSize, long receivePosition, long receiveSize) { - string DeviceName = MemoryHelper.ReadAsciiString( - Context.Memory, - SendPosition, - SendSize); + string deviceName = MemoryHelper.ReadAsciiString( + context.Memory, + sendPosition, + sendSize); - if (DeviceName == string.Empty) + if (deviceName == string.Empty) { - DeviceName = DefaultAudioOutput; + deviceName = DefaultAudioOutput; } - if (DeviceName != DefaultAudioOutput) + if (deviceName != DefaultAudioOutput) { Logger.PrintWarning(LogClass.Audio, "Invalid device name!"); return MakeError(ErrorModule.Audio, AudErr.DeviceNotFound); } - byte[] DeviceNameBuffer = Encoding.ASCII.GetBytes(DeviceName + "\0"); + byte[] deviceNameBuffer = Encoding.ASCII.GetBytes(deviceName + "\0"); - if ((ulong)DeviceNameBuffer.Length <= (ulong)ReceiveSize) + if ((ulong)deviceNameBuffer.Length <= (ulong)receiveSize) { - Context.Memory.WriteBytes(ReceivePosition, DeviceNameBuffer); + context.Memory.WriteBytes(receivePosition, deviceNameBuffer); } else { - Logger.PrintError(LogClass.ServiceAudio, $"Output buffer size {ReceiveSize} too small!"); + Logger.PrintError(LogClass.ServiceAudio, $"Output buffer size {receiveSize} too small!"); } - int SampleRate = Context.RequestData.ReadInt32(); - int Channels = Context.RequestData.ReadInt32(); + int sampleRate = context.RequestData.ReadInt32(); + int channels = context.RequestData.ReadInt32(); - if (SampleRate == 0) + if (sampleRate == 0) { - SampleRate = DefaultSampleRate; + sampleRate = DefaultSampleRate; } - if (SampleRate != DefaultSampleRate) + if (sampleRate != DefaultSampleRate) { Logger.PrintWarning(LogClass.Audio, "Invalid sample rate!"); return MakeError(ErrorModule.Audio, AudErr.UnsupportedSampleRate); } - Channels = (ushort)Channels; + channels = (ushort)channels; - if (Channels == 0) + if (channels == 0) { - Channels = DefaultChannelsCount; + channels = DefaultChannelsCount; } - KEvent ReleaseEvent = new KEvent(Context.Device.System); + KEvent releaseEvent = new KEvent(context.Device.System); - ReleaseCallback Callback = () => + ReleaseCallback callback = () => { - ReleaseEvent.ReadableEvent.Signal(); + releaseEvent.ReadableEvent.Signal(); }; - IAalOutput AudioOut = Context.Device.AudioOut; + IAalOutput audioOut = context.Device.AudioOut; - int Track = AudioOut.OpenTrack(SampleRate, Channels, Callback); + int track = audioOut.OpenTrack(sampleRate, channels, callback); - MakeObject(Context, new IAudioOut(AudioOut, ReleaseEvent, Track)); + MakeObject(context, new IAudioOut(audioOut, releaseEvent, track)); - Context.ResponseData.Write(SampleRate); - Context.ResponseData.Write(Channels); - Context.ResponseData.Write((int)SampleFormat.PcmInt16); - Context.ResponseData.Write((int)PlaybackState.Stopped); + context.ResponseData.Write(sampleRate); + context.ResponseData.Write(channels); + context.ResponseData.Write((int)SampleFormat.PcmInt16); + context.ResponseData.Write((int)PlaybackState.Stopped); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Aud/IAudioRendererManager.cs b/Ryujinx.HLE/HOS/Services/Aud/IAudioRendererManager.cs index 48a449cc..a319537a 100644 --- a/Ryujinx.HLE/HOS/Services/Aud/IAudioRendererManager.cs +++ b/Ryujinx.HLE/HOS/Services/Aud/IAudioRendererManager.cs @@ -20,13 +20,13 @@ namespace Ryujinx.HLE.HOS.Services.Aud public const int RevMagic = Rev0Magic + (Rev << 24); - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IAudioRendererManager() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, OpenAudioRenderer }, { 1, GetAudioRendererWorkBufferSize }, @@ -35,81 +35,81 @@ namespace Ryujinx.HLE.HOS.Services.Aud }; } - public long OpenAudioRenderer(ServiceCtx Context) + public long OpenAudioRenderer(ServiceCtx context) { - IAalOutput AudioOut = Context.Device.AudioOut; + IAalOutput audioOut = context.Device.AudioOut; - AudioRendererParameter Params = GetAudioRendererParameter(Context); + AudioRendererParameter Params = GetAudioRendererParameter(context); - MakeObject(Context, new IAudioRenderer( - Context.Device.System, - Context.Memory, - AudioOut, + MakeObject(context, new IAudioRenderer( + context.Device.System, + context.Memory, + audioOut, Params)); return 0; } - public long GetAudioRendererWorkBufferSize(ServiceCtx Context) + public long GetAudioRendererWorkBufferSize(ServiceCtx context) { - AudioRendererParameter Params = GetAudioRendererParameter(Context); + AudioRendererParameter Params = GetAudioRendererParameter(context); - int Revision = (Params.Revision - Rev0Magic) >> 24; + int revision = (Params.Revision - Rev0Magic) >> 24; - if (Revision <= Rev) + if (revision <= Rev) { - bool IsSplitterSupported = Revision >= 3; + bool isSplitterSupported = revision >= 3; - long Size; + long size; - Size = IntUtils.AlignUp(Params.Unknown8 * 4, 64); - Size += Params.MixCount * 0x400; - Size += (Params.MixCount + 1) * 0x940; - Size += Params.VoiceCount * 0x3F0; - Size += IntUtils.AlignUp((Params.MixCount + 1) * 8, 16); - Size += IntUtils.AlignUp(Params.VoiceCount * 8, 16); - Size += IntUtils.AlignUp( + size = IntUtils.AlignUp(Params.Unknown8 * 4, 64); + size += Params.MixCount * 0x400; + size += (Params.MixCount + 1) * 0x940; + size += Params.VoiceCount * 0x3F0; + size += IntUtils.AlignUp((Params.MixCount + 1) * 8, 16); + size += IntUtils.AlignUp(Params.VoiceCount * 8, 16); + size += IntUtils.AlignUp( ((Params.SinkCount + Params.MixCount) * 0x3C0 + Params.SampleCount * 4) * (Params.Unknown8 + 6), 64); - Size += (Params.SinkCount + Params.MixCount) * 0x2C0; - Size += (Params.EffectCount + Params.VoiceCount * 4) * 0x30 + 0x50; + size += (Params.SinkCount + Params.MixCount) * 0x2C0; + size += (Params.EffectCount + Params.VoiceCount * 4) * 0x30 + 0x50; - if (IsSplitterSupported) + if (isSplitterSupported) { - Size += IntUtils.AlignUp(( + size += IntUtils.AlignUp(( NodeStatesGetWorkBufferSize(Params.MixCount + 1) + EdgeMatrixGetWorkBufferSize(Params.MixCount + 1)), 16); - Size += Params.SplitterDestinationDataCount * 0xE0; - Size += Params.SplitterCount * 0x20; - Size += IntUtils.AlignUp(Params.SplitterDestinationDataCount * 4, 16); + size += Params.SplitterDestinationDataCount * 0xE0; + size += Params.SplitterCount * 0x20; + size += IntUtils.AlignUp(Params.SplitterDestinationDataCount * 4, 16); } - Size = Params.EffectCount * 0x4C0 + + size = Params.EffectCount * 0x4C0 + Params.SinkCount * 0x170 + Params.VoiceCount * 0x100 + - IntUtils.AlignUp(Size, 64) + 0x40; + IntUtils.AlignUp(size, 64) + 0x40; if (Params.PerformanceManagerCount >= 1) { - Size += (((Params.EffectCount + + size += (((Params.EffectCount + Params.SinkCount + Params.VoiceCount + Params.MixCount + 1) * 16 + 0x658) * (Params.PerformanceManagerCount + 1) + 0x13F) & ~0x3FL; } - Size = (Size + 0x1907D) & ~0xFFFL; + size = (size + 0x1907D) & ~0xFFFL; - Context.ResponseData.Write(Size); + context.ResponseData.Write(size); - Logger.PrintDebug(LogClass.ServiceAudio, $"WorkBufferSize is 0x{Size:x16}."); + Logger.PrintDebug(LogClass.ServiceAudio, $"WorkBufferSize is 0x{size:x16}."); return 0; } else { - Context.ResponseData.Write(0L); + context.ResponseData.Write(0L); Logger.PrintWarning(LogClass.ServiceAudio, $"Library Revision 0x{Params.Revision:x8} is not supported!"); @@ -117,71 +117,71 @@ namespace Ryujinx.HLE.HOS.Services.Aud } } - private AudioRendererParameter GetAudioRendererParameter(ServiceCtx Context) + private AudioRendererParameter GetAudioRendererParameter(ServiceCtx context) { AudioRendererParameter Params = new AudioRendererParameter(); - Params.SampleRate = Context.RequestData.ReadInt32(); - Params.SampleCount = Context.RequestData.ReadInt32(); - Params.Unknown8 = Context.RequestData.ReadInt32(); - Params.MixCount = Context.RequestData.ReadInt32(); - Params.VoiceCount = Context.RequestData.ReadInt32(); - Params.SinkCount = Context.RequestData.ReadInt32(); - Params.EffectCount = Context.RequestData.ReadInt32(); - Params.PerformanceManagerCount = Context.RequestData.ReadInt32(); - Params.VoiceDropEnable = Context.RequestData.ReadInt32(); - Params.SplitterCount = Context.RequestData.ReadInt32(); - Params.SplitterDestinationDataCount = Context.RequestData.ReadInt32(); - Params.Unknown2C = Context.RequestData.ReadInt32(); - Params.Revision = Context.RequestData.ReadInt32(); + Params.SampleRate = context.RequestData.ReadInt32(); + Params.SampleCount = context.RequestData.ReadInt32(); + Params.Unknown8 = context.RequestData.ReadInt32(); + Params.MixCount = context.RequestData.ReadInt32(); + Params.VoiceCount = context.RequestData.ReadInt32(); + Params.SinkCount = context.RequestData.ReadInt32(); + Params.EffectCount = context.RequestData.ReadInt32(); + Params.PerformanceManagerCount = context.RequestData.ReadInt32(); + Params.VoiceDropEnable = context.RequestData.ReadInt32(); + Params.SplitterCount = context.RequestData.ReadInt32(); + Params.SplitterDestinationDataCount = context.RequestData.ReadInt32(); + Params.Unknown2C = context.RequestData.ReadInt32(); + Params.Revision = context.RequestData.ReadInt32(); return Params; } - private static int NodeStatesGetWorkBufferSize(int Value) + private static int NodeStatesGetWorkBufferSize(int value) { - int Result = IntUtils.AlignUp(Value, 64); + int result = IntUtils.AlignUp(value, 64); - if (Result < 0) + if (result < 0) { - Result |= 7; + result |= 7; } - return 4 * (Value * Value) + 0x12 * Value + 2 * (Result / 8); + return 4 * (value * value) + 0x12 * value + 2 * (result / 8); } - private static int EdgeMatrixGetWorkBufferSize(int Value) + private static int EdgeMatrixGetWorkBufferSize(int value) { - int Result = IntUtils.AlignUp(Value * Value, 64); + int result = IntUtils.AlignUp(value * value, 64); - if (Result < 0) + if (result < 0) { - Result |= 7; + result |= 7; } - return Result / 8; + return result / 8; } // GetAudioDeviceService(nn::applet::AppletResourceUserId) -> object - public long GetAudioDeviceService(ServiceCtx Context) + public long GetAudioDeviceService(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); - MakeObject(Context, new IAudioDevice(Context.Device.System)); + MakeObject(context, new IAudioDevice(context.Device.System)); return 0; } // GetAudioDeviceServiceWithRevisionInfo(nn::applet::AppletResourceUserId, u32) -> object - private long GetAudioDeviceServiceWithRevisionInfo(ServiceCtx Context) + private long GetAudioDeviceServiceWithRevisionInfo(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); - int RevisionInfo = Context.RequestData.ReadInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); + int revisionInfo = context.RequestData.ReadInt32(); - Logger.PrintStub(LogClass.ServiceAudio, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"RevisionInfo: {RevisionInfo}"); + Logger.PrintStub(LogClass.ServiceAudio, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"RevisionInfo: {revisionInfo}"); - return GetAudioDeviceService(Context); + return GetAudioDeviceService(context); } } } diff --git a/Ryujinx.HLE/HOS/Services/Aud/IHardwareOpusDecoder.cs b/Ryujinx.HLE/HOS/Services/Aud/IHardwareOpusDecoder.cs index a71b8602..fc0bd8db 100644 --- a/Ryujinx.HLE/HOS/Services/Aud/IHardwareOpusDecoder.cs +++ b/Ryujinx.HLE/HOS/Services/Aud/IHardwareOpusDecoder.cs @@ -10,80 +10,80 @@ namespace Ryujinx.HLE.HOS.Services.Aud { private const int FixedSampleRate = 48000; - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - private int SampleRate; - private int ChannelsCount; + private int _sampleRate; + private int _channelsCount; - private OpusDecoder Decoder; + private OpusDecoder _decoder; - public IHardwareOpusDecoder(int SampleRate, int ChannelsCount) + public IHardwareOpusDecoder(int sampleRate, int channelsCount) { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, DecodeInterleaved }, { 4, DecodeInterleavedWithPerf } }; - this.SampleRate = SampleRate; - this.ChannelsCount = ChannelsCount; + _sampleRate = sampleRate; + _channelsCount = channelsCount; - Decoder = new OpusDecoder(FixedSampleRate, ChannelsCount); + _decoder = new OpusDecoder(FixedSampleRate, channelsCount); } - public long DecodeInterleavedWithPerf(ServiceCtx Context) + public long DecodeInterleavedWithPerf(ServiceCtx context) { - long Result = DecodeInterleaved(Context); + long result = DecodeInterleaved(context); //TODO: Figure out what this value is. //According to switchbrew, it is now used. - Context.ResponseData.Write(0L); + context.ResponseData.Write(0L); - return Result; + return result; } - public long DecodeInterleaved(ServiceCtx Context) + public long DecodeInterleaved(ServiceCtx context) { - long InPosition = Context.Request.SendBuff[0].Position; - long InSize = Context.Request.SendBuff[0].Size; + long inPosition = context.Request.SendBuff[0].Position; + long inSize = context.Request.SendBuff[0].Size; - if (InSize < 8) + if (inSize < 8) { return MakeError(ErrorModule.Audio, AudErr.OpusInvalidInput); } - long OutPosition = Context.Request.ReceiveBuff[0].Position; - long OutSize = Context.Request.ReceiveBuff[0].Size; + long outPosition = context.Request.ReceiveBuff[0].Position; + long outSize = context.Request.ReceiveBuff[0].Size; - byte[] OpusData = Context.Memory.ReadBytes(InPosition, InSize); + byte[] opusData = context.Memory.ReadBytes(inPosition, inSize); - int Processed = ((OpusData[0] << 24) | - (OpusData[1] << 16) | - (OpusData[2] << 8) | - (OpusData[3] << 0)) + 8; + int processed = ((opusData[0] << 24) | + (opusData[1] << 16) | + (opusData[2] << 8) | + (opusData[3] << 0)) + 8; - if ((uint)Processed > (ulong)InSize) + if ((uint)processed > (ulong)inSize) { return MakeError(ErrorModule.Audio, AudErr.OpusInvalidInput); } - short[] Pcm = new short[OutSize / 2]; + short[] pcm = new short[outSize / 2]; - int FrameSize = Pcm.Length / (ChannelsCount * 2); + int frameSize = pcm.Length / (_channelsCount * 2); - int Samples = Decoder.Decode(OpusData, 0, OpusData.Length, Pcm, 0, FrameSize); + int samples = _decoder.Decode(opusData, 0, opusData.Length, pcm, 0, frameSize); - foreach (short Sample in Pcm) + foreach (short sample in pcm) { - Context.Memory.WriteInt16(OutPosition, Sample); + context.Memory.WriteInt16(outPosition, sample); - OutPosition += 2; + outPosition += 2; } - Context.ResponseData.Write(Processed); - Context.ResponseData.Write(Samples); + context.ResponseData.Write(processed); + context.ResponseData.Write(samples); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Aud/IHardwareOpusDecoderManager.cs b/Ryujinx.HLE/HOS/Services/Aud/IHardwareOpusDecoderManager.cs index 875dc74c..495c8ab4 100644 --- a/Ryujinx.HLE/HOS/Services/Aud/IHardwareOpusDecoderManager.cs +++ b/Ryujinx.HLE/HOS/Services/Aud/IHardwareOpusDecoderManager.cs @@ -5,68 +5,68 @@ namespace Ryujinx.HLE.HOS.Services.Aud { class IHardwareOpusDecoderManager : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IHardwareOpusDecoderManager() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, Initialize }, { 1, GetWorkBufferSize } }; } - public long Initialize(ServiceCtx Context) + public long Initialize(ServiceCtx context) { - int SampleRate = Context.RequestData.ReadInt32(); - int ChannelsCount = Context.RequestData.ReadInt32(); + int sampleRate = context.RequestData.ReadInt32(); + int channelsCount = context.RequestData.ReadInt32(); - MakeObject(Context, new IHardwareOpusDecoder(SampleRate, ChannelsCount)); + MakeObject(context, new IHardwareOpusDecoder(sampleRate, channelsCount)); return 0; } - public long GetWorkBufferSize(ServiceCtx Context) + public long GetWorkBufferSize(ServiceCtx context) { //Note: The sample rate is ignored because it is fixed to 48KHz. - int SampleRate = Context.RequestData.ReadInt32(); - int ChannelsCount = Context.RequestData.ReadInt32(); + int sampleRate = context.RequestData.ReadInt32(); + int channelsCount = context.RequestData.ReadInt32(); - Context.ResponseData.Write(GetOpusDecoderSize(ChannelsCount)); + context.ResponseData.Write(GetOpusDecoderSize(channelsCount)); return 0; } - private static int GetOpusDecoderSize(int ChannelsCount) + private static int GetOpusDecoderSize(int channelsCount) { - const int SilkDecoderSize = 0x2198; + const int silkDecoderSize = 0x2198; - if (ChannelsCount < 1 || ChannelsCount > 2) + if (channelsCount < 1 || channelsCount > 2) { return 0; } - int CeltDecoderSize = GetCeltDecoderSize(ChannelsCount); + int celtDecoderSize = GetCeltDecoderSize(channelsCount); - int OpusDecoderSize = (ChannelsCount * 0x800 + 0x4807) & -0x800 | 0x50; + int opusDecoderSize = (channelsCount * 0x800 + 0x4807) & -0x800 | 0x50; - return OpusDecoderSize + SilkDecoderSize + CeltDecoderSize; + return opusDecoderSize + silkDecoderSize + celtDecoderSize; } - private static int GetCeltDecoderSize(int ChannelsCount) + private static int GetCeltDecoderSize(int channelsCount) { - const int DecodeBufferSize = 0x2030; - const int CeltDecoderSize = 0x58; - const int CeltSigSize = 0x4; - const int Overlap = 120; - const int EBandsCount = 21; + const int decodeBufferSize = 0x2030; + const int celtDecoderSize = 0x58; + const int celtSigSize = 0x4; + const int overlap = 120; + const int eBandsCount = 21; - return (DecodeBufferSize + Overlap * 4) * ChannelsCount + - EBandsCount * 16 + - CeltDecoderSize + - CeltSigSize; + return (decodeBufferSize + overlap * 4) * channelsCount + + eBandsCount * 16 + + celtDecoderSize + + celtSigSize; } } } diff --git a/Ryujinx.HLE/HOS/Services/Bcat/IBcatService.cs b/Ryujinx.HLE/HOS/Services/Bcat/IBcatService.cs index 6263dfa8..051b75d6 100644 --- a/Ryujinx.HLE/HOS/Services/Bcat/IBcatService.cs +++ b/Ryujinx.HLE/HOS/Services/Bcat/IBcatService.cs @@ -5,13 +5,13 @@ namespace Ryujinx.HLE.HOS.Services.Bcat { class IBcatService : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IBcatService() { - m_Commands = new Dictionary() + _commands = new Dictionary { //... }; diff --git a/Ryujinx.HLE/HOS/Services/Bcat/IDeliveryCacheStorageService.cs b/Ryujinx.HLE/HOS/Services/Bcat/IDeliveryCacheStorageService.cs index 7a55c6c8..043cb607 100644 --- a/Ryujinx.HLE/HOS/Services/Bcat/IDeliveryCacheStorageService.cs +++ b/Ryujinx.HLE/HOS/Services/Bcat/IDeliveryCacheStorageService.cs @@ -5,13 +5,13 @@ namespace Ryujinx.HLE.HOS.Services.Bcat { class IDeliveryCacheStorageService : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IDeliveryCacheStorageService() { - m_Commands = new Dictionary() + _commands = new Dictionary { //... }; diff --git a/Ryujinx.HLE/HOS/Services/Bcat/IServiceCreator.cs b/Ryujinx.HLE/HOS/Services/Bcat/IServiceCreator.cs index 55583c94..6523aa63 100644 --- a/Ryujinx.HLE/HOS/Services/Bcat/IServiceCreator.cs +++ b/Ryujinx.HLE/HOS/Services/Bcat/IServiceCreator.cs @@ -5,33 +5,33 @@ namespace Ryujinx.HLE.HOS.Services.Bcat { class IServiceCreator : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IServiceCreator() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, CreateBcatService }, { 1, CreateDeliveryCacheStorageService } }; } - public long CreateBcatService(ServiceCtx Context) + public long CreateBcatService(ServiceCtx context) { - long Id = Context.RequestData.ReadInt64(); + long id = context.RequestData.ReadInt64(); - MakeObject(Context, new IBcatService()); + MakeObject(context, new IBcatService()); return 0; } - public long CreateDeliveryCacheStorageService(ServiceCtx Context) + public long CreateDeliveryCacheStorageService(ServiceCtx context) { - long Id = Context.RequestData.ReadInt64(); + long id = context.RequestData.ReadInt64(); - MakeObject(Context, new IDeliveryCacheStorageService()); + MakeObject(context, new IDeliveryCacheStorageService()); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Bsd/BsdIoctl.cs b/Ryujinx.HLE/HOS/Services/Bsd/BsdIoctl.cs index 15fc7a82..de6fa73f 100644 --- a/Ryujinx.HLE/HOS/Services/Bsd/BsdIoctl.cs +++ b/Ryujinx.HLE/HOS/Services/Bsd/BsdIoctl.cs @@ -2,6 +2,6 @@ { enum BsdIoctl { - AtMark = 0x40047307, + AtMark = 0x40047307 } } diff --git a/Ryujinx.HLE/HOS/Services/Bsd/IClient.cs b/Ryujinx.HLE/HOS/Services/Bsd/IClient.cs index 37d0fcfd..aac85021 100644 --- a/Ryujinx.HLE/HOS/Services/Bsd/IClient.cs +++ b/Ryujinx.HLE/HOS/Services/Bsd/IClient.cs @@ -11,101 +11,101 @@ namespace Ryujinx.HLE.HOS.Services.Bsd class IClient : IpcService { - private static Dictionary ErrorMap = new Dictionary + private static Dictionary _errorMap = new Dictionary { // WSAEINTR - {WSAError.WSAEINTR, LinuxError.EINTR}, + {WsaError.WSAEINTR, LinuxError.EINTR}, // WSAEWOULDBLOCK - {WSAError.WSAEWOULDBLOCK, LinuxError.EWOULDBLOCK}, + {WsaError.WSAEWOULDBLOCK, LinuxError.EWOULDBLOCK}, // WSAEINPROGRESS - {WSAError.WSAEINPROGRESS, LinuxError.EINPROGRESS}, + {WsaError.WSAEINPROGRESS, LinuxError.EINPROGRESS}, // WSAEALREADY - {WSAError.WSAEALREADY, LinuxError.EALREADY}, + {WsaError.WSAEALREADY, LinuxError.EALREADY}, // WSAENOTSOCK - {WSAError.WSAENOTSOCK, LinuxError.ENOTSOCK}, + {WsaError.WSAENOTSOCK, LinuxError.ENOTSOCK}, // WSAEDESTADDRREQ - {WSAError.WSAEDESTADDRREQ, LinuxError.EDESTADDRREQ}, + {WsaError.WSAEDESTADDRREQ, LinuxError.EDESTADDRREQ}, // WSAEMSGSIZE - {WSAError.WSAEMSGSIZE, LinuxError.EMSGSIZE}, + {WsaError.WSAEMSGSIZE, LinuxError.EMSGSIZE}, // WSAEPROTOTYPE - {WSAError.WSAEPROTOTYPE, LinuxError.EPROTOTYPE}, + {WsaError.WSAEPROTOTYPE, LinuxError.EPROTOTYPE}, // WSAENOPROTOOPT - {WSAError.WSAENOPROTOOPT, LinuxError.ENOPROTOOPT}, + {WsaError.WSAENOPROTOOPT, LinuxError.ENOPROTOOPT}, // WSAEPROTONOSUPPORT - {WSAError.WSAEPROTONOSUPPORT, LinuxError.EPROTONOSUPPORT}, + {WsaError.WSAEPROTONOSUPPORT, LinuxError.EPROTONOSUPPORT}, // WSAESOCKTNOSUPPORT - {WSAError.WSAESOCKTNOSUPPORT, LinuxError.ESOCKTNOSUPPORT}, + {WsaError.WSAESOCKTNOSUPPORT, LinuxError.ESOCKTNOSUPPORT}, // WSAEOPNOTSUPP - {WSAError.WSAEOPNOTSUPP, LinuxError.EOPNOTSUPP}, + {WsaError.WSAEOPNOTSUPP, LinuxError.EOPNOTSUPP}, // WSAEPFNOSUPPORT - {WSAError.WSAEPFNOSUPPORT, LinuxError.EPFNOSUPPORT}, + {WsaError.WSAEPFNOSUPPORT, LinuxError.EPFNOSUPPORT}, // WSAEAFNOSUPPORT - {WSAError.WSAEAFNOSUPPORT, LinuxError.EAFNOSUPPORT}, + {WsaError.WSAEAFNOSUPPORT, LinuxError.EAFNOSUPPORT}, // WSAEADDRINUSE - {WSAError.WSAEADDRINUSE, LinuxError.EADDRINUSE}, + {WsaError.WSAEADDRINUSE, LinuxError.EADDRINUSE}, // WSAEADDRNOTAVAIL - {WSAError.WSAEADDRNOTAVAIL, LinuxError.EADDRNOTAVAIL}, + {WsaError.WSAEADDRNOTAVAIL, LinuxError.EADDRNOTAVAIL}, // WSAENETDOWN - {WSAError.WSAENETDOWN, LinuxError.ENETDOWN}, + {WsaError.WSAENETDOWN, LinuxError.ENETDOWN}, // WSAENETUNREACH - {WSAError.WSAENETUNREACH, LinuxError.ENETUNREACH}, + {WsaError.WSAENETUNREACH, LinuxError.ENETUNREACH}, // WSAENETRESET - {WSAError.WSAENETRESET, LinuxError.ENETRESET}, + {WsaError.WSAENETRESET, LinuxError.ENETRESET}, // WSAECONNABORTED - {WSAError.WSAECONNABORTED, LinuxError.ECONNABORTED}, + {WsaError.WSAECONNABORTED, LinuxError.ECONNABORTED}, // WSAECONNRESET - {WSAError.WSAECONNRESET, LinuxError.ECONNRESET}, + {WsaError.WSAECONNRESET, LinuxError.ECONNRESET}, // WSAENOBUFS - {WSAError.WSAENOBUFS, LinuxError.ENOBUFS}, + {WsaError.WSAENOBUFS, LinuxError.ENOBUFS}, // WSAEISCONN - {WSAError.WSAEISCONN, LinuxError.EISCONN}, + {WsaError.WSAEISCONN, LinuxError.EISCONN}, // WSAENOTCONN - {WSAError.WSAENOTCONN, LinuxError.ENOTCONN}, + {WsaError.WSAENOTCONN, LinuxError.ENOTCONN}, // WSAESHUTDOWN - {WSAError.WSAESHUTDOWN, LinuxError.ESHUTDOWN}, + {WsaError.WSAESHUTDOWN, LinuxError.ESHUTDOWN}, // WSAETOOMANYREFS - {WSAError.WSAETOOMANYREFS, LinuxError.ETOOMANYREFS}, + {WsaError.WSAETOOMANYREFS, LinuxError.ETOOMANYREFS}, // WSAETIMEDOUT - {WSAError.WSAETIMEDOUT, LinuxError.ETIMEDOUT}, + {WsaError.WSAETIMEDOUT, LinuxError.ETIMEDOUT}, // WSAECONNREFUSED - {WSAError.WSAECONNREFUSED, LinuxError.ECONNREFUSED}, + {WsaError.WSAECONNREFUSED, LinuxError.ECONNREFUSED}, // WSAELOOP - {WSAError.WSAELOOP, LinuxError.ELOOP}, + {WsaError.WSAELOOP, LinuxError.ELOOP}, // WSAENAMETOOLONG - {WSAError.WSAENAMETOOLONG, LinuxError.ENAMETOOLONG}, + {WsaError.WSAENAMETOOLONG, LinuxError.ENAMETOOLONG}, // WSAEHOSTDOWN - {WSAError.WSAEHOSTDOWN, LinuxError.EHOSTDOWN}, + {WsaError.WSAEHOSTDOWN, LinuxError.EHOSTDOWN}, // WSAEHOSTUNREACH - {WSAError.WSAEHOSTUNREACH, LinuxError.EHOSTUNREACH}, + {WsaError.WSAEHOSTUNREACH, LinuxError.EHOSTUNREACH}, // WSAENOTEMPTY - {WSAError.WSAENOTEMPTY, LinuxError.ENOTEMPTY}, + {WsaError.WSAENOTEMPTY, LinuxError.ENOTEMPTY}, // WSAEUSERS - {WSAError.WSAEUSERS, LinuxError.EUSERS}, + {WsaError.WSAEUSERS, LinuxError.EUSERS}, // WSAEDQUOT - {WSAError.WSAEDQUOT, LinuxError.EDQUOT}, + {WsaError.WSAEDQUOT, LinuxError.EDQUOT}, // WSAESTALE - {WSAError.WSAESTALE, LinuxError.ESTALE}, + {WsaError.WSAESTALE, LinuxError.ESTALE}, // WSAEREMOTE - {WSAError.WSAEREMOTE, LinuxError.EREMOTE}, + {WsaError.WSAEREMOTE, LinuxError.EREMOTE}, // WSAEINVAL - {WSAError.WSAEINVAL, LinuxError.EINVAL}, + {WsaError.WSAEINVAL, LinuxError.EINVAL}, // WSAEFAULT - {WSAError.WSAEFAULT, LinuxError.EFAULT}, + {WsaError.WSAEFAULT, LinuxError.EFAULT}, // NOERROR {0, 0} }; - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - private bool IsPrivileged; + private bool _isPrivileged; - private List Sockets = new List(); + private List _sockets = new List(); - public IClient(bool IsPrivileged) + public IClient(bool isPrivileged) { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, RegisterClient }, { 1, StartMonitoring }, @@ -134,60 +134,60 @@ namespace Ryujinx.HLE.HOS.Services.Bsd { 24, Write }, { 25, Read }, { 26, Close }, - { 27, DuplicateSocket }, + { 27, DuplicateSocket } }; - this.IsPrivileged = IsPrivileged; + _isPrivileged = isPrivileged; } - private LinuxError ConvertError(WSAError ErrorCode) + private LinuxError ConvertError(WsaError errorCode) { - LinuxError Errno; + LinuxError errno; - if (!ErrorMap.TryGetValue(ErrorCode, out Errno)) + if (!_errorMap.TryGetValue(errorCode, out errno)) { - Errno = (LinuxError)ErrorCode; + errno = (LinuxError)errorCode; } - return Errno; + return errno; } - private long WriteWinSock2Error(ServiceCtx Context, WSAError ErrorCode) + private long WriteWinSock2Error(ServiceCtx context, WsaError errorCode) { - return WriteBsdResult(Context, -1, ConvertError(ErrorCode)); + return WriteBsdResult(context, -1, ConvertError(errorCode)); } - private long WriteBsdResult(ServiceCtx Context, int Result, LinuxError ErrorCode = 0) + private long WriteBsdResult(ServiceCtx context, int result, LinuxError errorCode = 0) { - if (ErrorCode != LinuxError.SUCCESS) + if (errorCode != LinuxError.SUCCESS) { - Result = -1; + result = -1; } - Context.ResponseData.Write(Result); - Context.ResponseData.Write((int)ErrorCode); + context.ResponseData.Write(result); + context.ResponseData.Write((int)errorCode); return 0; } - private BsdSocket RetrieveSocket(int SocketFd) + private BsdSocket RetrieveSocket(int socketFd) { - if (SocketFd >= 0 && Sockets.Count > SocketFd) + if (socketFd >= 0 && _sockets.Count > socketFd) { - return Sockets[SocketFd]; + return _sockets[socketFd]; } return null; } - private LinuxError SetResultErrno(Socket Socket, int Result) + private LinuxError SetResultErrno(Socket socket, int result) { - return Result == 0 && !Socket.Blocking ? LinuxError.EWOULDBLOCK : LinuxError.SUCCESS; + return result == 0 && !socket.Blocking ? LinuxError.EWOULDBLOCK : LinuxError.SUCCESS; } - private AddressFamily ConvertFromBsd(int Domain) + private AddressFamily ConvertFromBsd(int domain) { - if (Domain == 2) + if (domain == 2) { return AddressFamily.InterNetwork; } @@ -196,70 +196,70 @@ namespace Ryujinx.HLE.HOS.Services.Bsd return AddressFamily.Unknown; } - private long SocketInternal(ServiceCtx Context, bool Exempt) + private long SocketInternal(ServiceCtx context, bool exempt) { - AddressFamily Domain = (AddressFamily)Context.RequestData.ReadInt32(); - SocketType Type = (SocketType)Context.RequestData.ReadInt32(); - ProtocolType Protocol = (ProtocolType)Context.RequestData.ReadInt32(); + AddressFamily domain = (AddressFamily)context.RequestData.ReadInt32(); + SocketType type = (SocketType)context.RequestData.ReadInt32(); + ProtocolType protocol = (ProtocolType)context.RequestData.ReadInt32(); - if (Domain == AddressFamily.Unknown) + if (domain == AddressFamily.Unknown) { - return WriteBsdResult(Context, -1, LinuxError.EPROTONOSUPPORT); + return WriteBsdResult(context, -1, LinuxError.EPROTONOSUPPORT); } - else if ((Type == SocketType.Seqpacket || Type == SocketType.Raw) && !IsPrivileged) + else if ((type == SocketType.Seqpacket || type == SocketType.Raw) && !_isPrivileged) { - if (Domain != AddressFamily.InterNetwork || Type != SocketType.Raw || Protocol != ProtocolType.Icmp) + if (domain != AddressFamily.InterNetwork || type != SocketType.Raw || protocol != ProtocolType.Icmp) { - return WriteBsdResult(Context, -1, LinuxError.ENOENT); + return WriteBsdResult(context, -1, LinuxError.ENOENT); } } - BsdSocket NewBsdSocket = new BsdSocket + BsdSocket newBsdSocket = new BsdSocket { - Family = (int)Domain, - Type = (int)Type, - Protocol = (int)Protocol, - Handle = new Socket(Domain, Type, Protocol) + Family = (int)domain, + Type = (int)type, + Protocol = (int)protocol, + Handle = new Socket(domain, type, protocol) }; - Sockets.Add(NewBsdSocket); + _sockets.Add(newBsdSocket); - if (Exempt) + if (exempt) { - NewBsdSocket.Handle.Disconnect(true); + newBsdSocket.Handle.Disconnect(true); } - return WriteBsdResult(Context, Sockets.Count - 1); + return WriteBsdResult(context, _sockets.Count - 1); } - private IPEndPoint ParseSockAddr(ServiceCtx Context, long BufferPosition, long BufferSize) + private IPEndPoint ParseSockAddr(ServiceCtx context, long bufferPosition, long bufferSize) { - int Size = Context.Memory.ReadByte(BufferPosition); - int Family = Context.Memory.ReadByte(BufferPosition + 1); - int Port = EndianSwap.Swap16(Context.Memory.ReadUInt16(BufferPosition + 2)); + int size = context.Memory.ReadByte(bufferPosition); + int family = context.Memory.ReadByte(bufferPosition + 1); + int port = EndianSwap.Swap16(context.Memory.ReadUInt16(bufferPosition + 2)); - byte[] RawIp = Context.Memory.ReadBytes(BufferPosition + 4, 4); + byte[] rawIp = context.Memory.ReadBytes(bufferPosition + 4, 4); - return new IPEndPoint(new IPAddress(RawIp), Port); + return new IPEndPoint(new IPAddress(rawIp), port); } - private void WriteSockAddr(ServiceCtx Context, long BufferPosition, IPEndPoint EndPoint) + private void WriteSockAddr(ServiceCtx context, long bufferPosition, IPEndPoint endPoint) { - Context.Memory.WriteByte(BufferPosition, 0); - Context.Memory.WriteByte(BufferPosition + 1, (byte)EndPoint.AddressFamily); - Context.Memory.WriteUInt16(BufferPosition + 2, EndianSwap.Swap16((ushort)EndPoint.Port)); - Context.Memory.WriteBytes(BufferPosition + 4, EndPoint.Address.GetAddressBytes()); + context.Memory.WriteByte(bufferPosition, 0); + context.Memory.WriteByte(bufferPosition + 1, (byte)endPoint.AddressFamily); + context.Memory.WriteUInt16(bufferPosition + 2, EndianSwap.Swap16((ushort)endPoint.Port)); + context.Memory.WriteBytes(bufferPosition + 4, endPoint.Address.GetAddressBytes()); } - private void WriteSockAddr(ServiceCtx Context, long BufferPosition, BsdSocket Socket, bool IsRemote) + private void WriteSockAddr(ServiceCtx context, long bufferPosition, BsdSocket socket, bool isRemote) { - IPEndPoint EndPoint = (IsRemote ? Socket.Handle.RemoteEndPoint : Socket.Handle.LocalEndPoint) as IPEndPoint; + IPEndPoint endPoint = (isRemote ? socket.Handle.RemoteEndPoint : socket.Handle.LocalEndPoint) as IPEndPoint; - WriteSockAddr(Context, BufferPosition, EndPoint); + WriteSockAddr(context, bufferPosition, endPoint); } // Initialize(nn::socket::BsdBufferConfig config, u64 pid, u64 transferMemorySize, KObject, pid) -> u32 bsd_errno - public long RegisterClient(ServiceCtx Context) + public long RegisterClient(ServiceCtx context) { /* typedef struct { @@ -275,7 +275,7 @@ namespace Ryujinx.HLE.HOS.Services.Bsd */ // bsd_error - Context.ResponseData.Write(0); + context.ResponseData.Write(0); Logger.PrintStub(LogClass.ServiceBsd, "Stubbed."); @@ -283,49 +283,49 @@ namespace Ryujinx.HLE.HOS.Services.Bsd } // StartMonitoring(u64, pid) - public long StartMonitoring(ServiceCtx Context) + public long StartMonitoring(ServiceCtx context) { - ulong Unknown0 = Context.RequestData.ReadUInt64(); + ulong unknown0 = context.RequestData.ReadUInt64(); - Logger.PrintStub(LogClass.ServiceBsd, $"Stubbed. Unknown0: {Unknown0}"); + Logger.PrintStub(LogClass.ServiceBsd, $"Stubbed. Unknown0: {unknown0}"); return 0; } // Socket(u32 domain, u32 type, u32 protocol) -> (i32 ret, u32 bsd_errno) - public long Socket(ServiceCtx Context) + public long Socket(ServiceCtx context) { - return SocketInternal(Context, false); + return SocketInternal(context, false); } // SocketExempt(u32 domain, u32 type, u32 protocol) -> (i32 ret, u32 bsd_errno) - public long SocketExempt(ServiceCtx Context) + public long SocketExempt(ServiceCtx context) { - return SocketInternal(Context, true); + return SocketInternal(context, true); } // Open(u32 flags, array path) -> (i32 ret, u32 bsd_errno) - public long Open(ServiceCtx Context) + public long Open(ServiceCtx context) { - (long BufferPosition, long BufferSize) = Context.Request.GetBufferType0x21(); + (long bufferPosition, long bufferSize) = context.Request.GetBufferType0x21(); - int Flags = Context.RequestData.ReadInt32(); + int flags = context.RequestData.ReadInt32(); - byte[] RawPath = Context.Memory.ReadBytes(BufferPosition, BufferSize); - string Path = Encoding.ASCII.GetString(RawPath); + byte[] rawPath = context.Memory.ReadBytes(bufferPosition, bufferSize); + string path = Encoding.ASCII.GetString(rawPath); - WriteBsdResult(Context, -1, LinuxError.EOPNOTSUPP); + WriteBsdResult(context, -1, LinuxError.EOPNOTSUPP); - Logger.PrintStub(LogClass.ServiceBsd, $"Stubbed. Path: {Path} - " + - $"Flags: {Flags}"); + Logger.PrintStub(LogClass.ServiceBsd, $"Stubbed. Path: {path} - " + + $"Flags: {flags}"); return 0; } // Select(u32 nfds, nn::socket::timeout timeout, buffer readfds_in, buffer writefds_in, buffer errorfds_in) -> (i32 ret, u32 bsd_errno, buffer readfds_out, buffer writefds_out, buffer errorfds_out) - public long Select(ServiceCtx Context) + public long Select(ServiceCtx context) { - WriteBsdResult(Context, -1, LinuxError.EOPNOTSUPP); + WriteBsdResult(context, -1, LinuxError.EOPNOTSUPP); Logger.PrintStub(LogClass.ServiceBsd, $"Stubbed."); @@ -333,135 +333,134 @@ namespace Ryujinx.HLE.HOS.Services.Bsd } // Poll(u32 nfds, u32 timeout, buffer fds) -> (i32 ret, u32 bsd_errno, buffer) - public long Poll(ServiceCtx Context) + public long Poll(ServiceCtx context) { - int FdsCount = Context.RequestData.ReadInt32(); - int Timeout = Context.RequestData.ReadInt32(); + int fdsCount = context.RequestData.ReadInt32(); + int timeout = context.RequestData.ReadInt32(); - (long BufferPosition, long BufferSize) = Context.Request.GetBufferType0x21(); + (long bufferPosition, long bufferSize) = context.Request.GetBufferType0x21(); - if (Timeout < -1 || FdsCount < 0 || (FdsCount * 8) > BufferSize) + if (timeout < -1 || fdsCount < 0 || (fdsCount * 8) > bufferSize) { - return WriteBsdResult(Context, -1, LinuxError.EINVAL); + return WriteBsdResult(context, -1, LinuxError.EINVAL); } - PollEvent[] Events = new PollEvent[FdsCount]; + PollEvent[] events = new PollEvent[fdsCount]; - for (int i = 0; i < FdsCount; i++) + for (int i = 0; i < fdsCount; i++) { - int SocketFd = Context.Memory.ReadInt32(BufferPosition + i * 8); + int socketFd = context.Memory.ReadInt32(bufferPosition + i * 8); - BsdSocket Socket = RetrieveSocket(SocketFd); + BsdSocket socket = RetrieveSocket(socketFd); - if (Socket == null) + if (socket == null) { - return WriteBsdResult(Context, -1, LinuxError.EBADF); - } + return WriteBsdResult(context, -1, LinuxError.EBADF);} - PollEvent.EventTypeMask InputEvents = (PollEvent.EventTypeMask)Context.Memory.ReadInt16(BufferPosition + i * 8 + 4); - PollEvent.EventTypeMask OutputEvents = (PollEvent.EventTypeMask)Context.Memory.ReadInt16(BufferPosition + i * 8 + 6); + PollEvent.EventTypeMask inputEvents = (PollEvent.EventTypeMask)context.Memory.ReadInt16(bufferPosition + i * 8 + 4); + PollEvent.EventTypeMask outputEvents = (PollEvent.EventTypeMask)context.Memory.ReadInt16(bufferPosition + i * 8 + 6); - Events[i] = new PollEvent(SocketFd, Socket, InputEvents, OutputEvents); + events[i] = new PollEvent(socketFd, socket, inputEvents, outputEvents); } - List ReadEvents = new List(); - List WriteEvents = new List(); - List ErrorEvents = new List(); + List readEvents = new List(); + List writeEvents = new List(); + List errorEvents = new List(); - foreach (PollEvent Event in Events) + foreach (PollEvent Event in events) { - bool IsValidEvent = false; + bool isValidEvent = false; if ((Event.InputEvents & PollEvent.EventTypeMask.Input) != 0) { - ReadEvents.Add(Event.Socket.Handle); - ErrorEvents.Add(Event.Socket.Handle); + readEvents.Add(Event.Socket.Handle); + errorEvents.Add(Event.Socket.Handle); - IsValidEvent = true; + isValidEvent = true; } if ((Event.InputEvents & PollEvent.EventTypeMask.UrgentInput) != 0) { - ReadEvents.Add(Event.Socket.Handle); - ErrorEvents.Add(Event.Socket.Handle); + readEvents.Add(Event.Socket.Handle); + errorEvents.Add(Event.Socket.Handle); - IsValidEvent = true; + isValidEvent = true; } if ((Event.InputEvents & PollEvent.EventTypeMask.Output) != 0) { - WriteEvents.Add(Event.Socket.Handle); - ErrorEvents.Add(Event.Socket.Handle); + writeEvents.Add(Event.Socket.Handle); + errorEvents.Add(Event.Socket.Handle); - IsValidEvent = true; + isValidEvent = true; } if ((Event.InputEvents & PollEvent.EventTypeMask.Error) != 0) { - ErrorEvents.Add(Event.Socket.Handle); - IsValidEvent = true; + errorEvents.Add(Event.Socket.Handle); + isValidEvent = true; } - if (!IsValidEvent) + if (!isValidEvent) { Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported Poll input event type: {Event.InputEvents}"); - return WriteBsdResult(Context, -1, LinuxError.EINVAL); + return WriteBsdResult(context, -1, LinuxError.EINVAL); } } try { - System.Net.Sockets.Socket.Select(ReadEvents, WriteEvents, ErrorEvents, Timeout); + System.Net.Sockets.Socket.Select(readEvents, writeEvents, errorEvents, timeout); } - catch (SocketException Exception) + catch (SocketException exception) { - return WriteWinSock2Error(Context, (WSAError)Exception.ErrorCode); + return WriteWinSock2Error(context, (WsaError)exception.ErrorCode); } - for (int i = 0; i < FdsCount; i++) + for (int i = 0; i < fdsCount; i++) { - PollEvent Event = Events[i]; - Context.Memory.WriteInt32(BufferPosition + i * 8, Event.SocketFd); - Context.Memory.WriteInt16(BufferPosition + i * 8 + 4, (short)Event.InputEvents); + PollEvent Event = events[i]; + context.Memory.WriteInt32(bufferPosition + i * 8, Event.SocketFd); + context.Memory.WriteInt16(bufferPosition + i * 8 + 4, (short)Event.InputEvents); - PollEvent.EventTypeMask OutputEvents = 0; + PollEvent.EventTypeMask outputEvents = 0; - Socket Socket = Event.Socket.Handle; + Socket socket = Event.Socket.Handle; - if (ErrorEvents.Contains(Socket)) + if (errorEvents.Contains(socket)) { - OutputEvents |= PollEvent.EventTypeMask.Error; + outputEvents |= PollEvent.EventTypeMask.Error; - if (!Socket.Connected || !Socket.IsBound) + if (!socket.Connected || !socket.IsBound) { - OutputEvents |= PollEvent.EventTypeMask.Disconnected; + outputEvents |= PollEvent.EventTypeMask.Disconnected; } } - if (ReadEvents.Contains(Socket)) + if (readEvents.Contains(socket)) { if ((Event.InputEvents & PollEvent.EventTypeMask.Input) != 0) { - OutputEvents |= PollEvent.EventTypeMask.Input; + outputEvents |= PollEvent.EventTypeMask.Input; } } - if (WriteEvents.Contains(Socket)) + if (writeEvents.Contains(socket)) { - OutputEvents |= PollEvent.EventTypeMask.Output; + outputEvents |= PollEvent.EventTypeMask.Output; } - Context.Memory.WriteInt16(BufferPosition + i * 8 + 6, (short)OutputEvents); + context.Memory.WriteInt16(bufferPosition + i * 8 + 6, (short)outputEvents); } - return WriteBsdResult(Context, ReadEvents.Count + WriteEvents.Count + ErrorEvents.Count, LinuxError.SUCCESS); + return WriteBsdResult(context, readEvents.Count + writeEvents.Count + errorEvents.Count, LinuxError.SUCCESS); } // Sysctl(buffer, buffer) -> (i32 ret, u32 bsd_errno, u32, buffer) - public long Sysctl(ServiceCtx Context) + public long Sysctl(ServiceCtx context) { - WriteBsdResult(Context, -1, LinuxError.EOPNOTSUPP); + WriteBsdResult(context, -1, LinuxError.EOPNOTSUPP); Logger.PrintStub(LogClass.ServiceBsd, $"Stubbed."); @@ -469,452 +468,452 @@ namespace Ryujinx.HLE.HOS.Services.Bsd } // Recv(u32 socket, u32 flags) -> (i32 ret, u32 bsd_errno, array message) - public long Recv(ServiceCtx Context) + public long Recv(ServiceCtx context) { - int SocketFd = Context.RequestData.ReadInt32(); - SocketFlags SocketFlags = (SocketFlags)Context.RequestData.ReadInt32(); + int socketFd = context.RequestData.ReadInt32(); + SocketFlags socketFlags = (SocketFlags)context.RequestData.ReadInt32(); - (long ReceivePosition, long ReceiveLength) = Context.Request.GetBufferType0x22(); + (long receivePosition, long receiveLength) = context.Request.GetBufferType0x22(); - LinuxError Errno = LinuxError.EBADF; - BsdSocket Socket = RetrieveSocket(SocketFd); - int Result = -1; + LinuxError errno = LinuxError.EBADF; + BsdSocket socket = RetrieveSocket(socketFd); + int result = -1; - if (Socket != null) + if (socket != null) { - if (SocketFlags != SocketFlags.None && (SocketFlags & SocketFlags.OutOfBand) == 0 - && (SocketFlags & SocketFlags.Peek) == 0) + if (socketFlags != SocketFlags.None && (socketFlags & SocketFlags.OutOfBand) == 0 + && (socketFlags & SocketFlags.Peek) == 0) { - Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported Recv flags: {SocketFlags}"); - return WriteBsdResult(Context, -1, LinuxError.EOPNOTSUPP); + Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported Recv flags: {socketFlags}"); + return WriteBsdResult(context, -1, LinuxError.EOPNOTSUPP); } - byte[] ReceivedBuffer = new byte[ReceiveLength]; + byte[] receivedBuffer = new byte[receiveLength]; try { - Result = Socket.Handle.Receive(ReceivedBuffer, SocketFlags); - Errno = SetResultErrno(Socket.Handle, Result); + result = socket.Handle.Receive(receivedBuffer, socketFlags); + errno = SetResultErrno(socket.Handle, result); - Context.Memory.WriteBytes(ReceivePosition, ReceivedBuffer); + context.Memory.WriteBytes(receivePosition, receivedBuffer); } - catch (SocketException Exception) + catch (SocketException exception) { - Errno = ConvertError((WSAError)Exception.ErrorCode); + errno = ConvertError((WsaError)exception.ErrorCode); } } - return WriteBsdResult(Context, Result, Errno); + return WriteBsdResult(context, result, errno); } // RecvFrom(u32 sock, u32 flags) -> (i32 ret, u32 bsd_errno, u32 addrlen, buffer message, buffer) - public long RecvFrom(ServiceCtx Context) + public long RecvFrom(ServiceCtx context) { - int SocketFd = Context.RequestData.ReadInt32(); - SocketFlags SocketFlags = (SocketFlags)Context.RequestData.ReadInt32(); + int socketFd = context.RequestData.ReadInt32(); + SocketFlags socketFlags = (SocketFlags)context.RequestData.ReadInt32(); - (long ReceivePosition, long ReceiveLength) = Context.Request.GetBufferType0x22(); - (long SockAddrInPosition, long SockAddrInSize) = Context.Request.GetBufferType0x21(); - (long SockAddrOutPosition, long SockAddrOutSize) = Context.Request.GetBufferType0x22(1); + (long receivePosition, long receiveLength) = context.Request.GetBufferType0x22(); + (long sockAddrInPosition, long sockAddrInSize) = context.Request.GetBufferType0x21(); + (long sockAddrOutPosition, long sockAddrOutSize) = context.Request.GetBufferType0x22(1); - LinuxError Errno = LinuxError.EBADF; - BsdSocket Socket = RetrieveSocket(SocketFd); - int Result = -1; + LinuxError errno = LinuxError.EBADF; + BsdSocket socket = RetrieveSocket(socketFd); + int result = -1; - if (Socket != null) + if (socket != null) { - if (SocketFlags != SocketFlags.None && (SocketFlags & SocketFlags.OutOfBand) == 0 - && (SocketFlags & SocketFlags.Peek) == 0) + if (socketFlags != SocketFlags.None && (socketFlags & SocketFlags.OutOfBand) == 0 + && (socketFlags & SocketFlags.Peek) == 0) { - Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported Recv flags: {SocketFlags}"); + Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported Recv flags: {socketFlags}"); - return WriteBsdResult(Context, -1, LinuxError.EOPNOTSUPP); + return WriteBsdResult(context, -1, LinuxError.EOPNOTSUPP); } - byte[] ReceivedBuffer = new byte[ReceiveLength]; - EndPoint EndPoint = ParseSockAddr(Context, SockAddrInPosition, SockAddrInSize); + byte[] receivedBuffer = new byte[receiveLength]; + EndPoint endPoint = ParseSockAddr(context, sockAddrInPosition, sockAddrInSize); try { - Result = Socket.Handle.ReceiveFrom(ReceivedBuffer, ReceivedBuffer.Length, SocketFlags, ref EndPoint); - Errno = SetResultErrno(Socket.Handle, Result); + result = socket.Handle.ReceiveFrom(receivedBuffer, receivedBuffer.Length, socketFlags, ref endPoint); + errno = SetResultErrno(socket.Handle, result); - Context.Memory.WriteBytes(ReceivePosition, ReceivedBuffer); - WriteSockAddr(Context, SockAddrOutPosition, (IPEndPoint)EndPoint); + context.Memory.WriteBytes(receivePosition, receivedBuffer); + WriteSockAddr(context, sockAddrOutPosition, (IPEndPoint)endPoint); } - catch (SocketException Exception) + catch (SocketException exception) { - Errno = ConvertError((WSAError)Exception.ErrorCode); + errno = ConvertError((WsaError)exception.ErrorCode); } } - return WriteBsdResult(Context, Result, Errno); + return WriteBsdResult(context, result, errno); } // Send(u32 socket, u32 flags, buffer) -> (i32 ret, u32 bsd_errno) - public long Send(ServiceCtx Context) + public long Send(ServiceCtx context) { - int SocketFd = Context.RequestData.ReadInt32(); - SocketFlags SocketFlags = (SocketFlags)Context.RequestData.ReadInt32(); + int socketFd = context.RequestData.ReadInt32(); + SocketFlags socketFlags = (SocketFlags)context.RequestData.ReadInt32(); - (long SendPosition, long SendSize) = Context.Request.GetBufferType0x21(); + (long sendPosition, long sendSize) = context.Request.GetBufferType0x21(); - LinuxError Errno = LinuxError.EBADF; - BsdSocket Socket = RetrieveSocket(SocketFd); - int Result = -1; + LinuxError errno = LinuxError.EBADF; + BsdSocket socket = RetrieveSocket(socketFd); + int result = -1; - if (Socket != null) + if (socket != null) { - if (SocketFlags != SocketFlags.None && SocketFlags != SocketFlags.OutOfBand - && SocketFlags != SocketFlags.Peek && SocketFlags != SocketFlags.DontRoute) + if (socketFlags != SocketFlags.None && socketFlags != SocketFlags.OutOfBand + && socketFlags != SocketFlags.Peek && socketFlags != SocketFlags.DontRoute) { - Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported Send flags: {SocketFlags}"); + Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported Send flags: {socketFlags}"); - return WriteBsdResult(Context, -1, LinuxError.EOPNOTSUPP); + return WriteBsdResult(context, -1, LinuxError.EOPNOTSUPP); } - byte[] SendBuffer = Context.Memory.ReadBytes(SendPosition, SendSize); + byte[] sendBuffer = context.Memory.ReadBytes(sendPosition, sendSize); try { - Result = Socket.Handle.Send(SendBuffer, SocketFlags); - Errno = SetResultErrno(Socket.Handle, Result); + result = socket.Handle.Send(sendBuffer, socketFlags); + errno = SetResultErrno(socket.Handle, result); } - catch (SocketException Exception) + catch (SocketException exception) { - Errno = ConvertError((WSAError)Exception.ErrorCode); + errno = ConvertError((WsaError)exception.ErrorCode); } } - return WriteBsdResult(Context, Result, Errno); + return WriteBsdResult(context, result, errno); } // SendTo(u32 socket, u32 flags, buffer, buffer) -> (i32 ret, u32 bsd_errno) - public long SendTo(ServiceCtx Context) + public long SendTo(ServiceCtx context) { - int SocketFd = Context.RequestData.ReadInt32(); - SocketFlags SocketFlags = (SocketFlags)Context.RequestData.ReadInt32(); + int socketFd = context.RequestData.ReadInt32(); + SocketFlags socketFlags = (SocketFlags)context.RequestData.ReadInt32(); - (long SendPosition, long SendSize) = Context.Request.GetBufferType0x21(); - (long BufferPosition, long BufferSize) = Context.Request.GetBufferType0x21(1); + (long sendPosition, long sendSize) = context.Request.GetBufferType0x21(); + (long bufferPosition, long bufferSize) = context.Request.GetBufferType0x21(1); - LinuxError Errno = LinuxError.EBADF; - BsdSocket Socket = RetrieveSocket(SocketFd); - int Result = -1; + LinuxError errno = LinuxError.EBADF; + BsdSocket socket = RetrieveSocket(socketFd); + int result = -1; - if (Socket != null) + if (socket != null) { - if (SocketFlags != SocketFlags.None && SocketFlags != SocketFlags.OutOfBand - && SocketFlags != SocketFlags.Peek && SocketFlags != SocketFlags.DontRoute) + if (socketFlags != SocketFlags.None && socketFlags != SocketFlags.OutOfBand + && socketFlags != SocketFlags.Peek && socketFlags != SocketFlags.DontRoute) { - Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported Send flags: {SocketFlags}"); + Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported Send flags: {socketFlags}"); - return WriteBsdResult(Context, -1, LinuxError.EOPNOTSUPP); + return WriteBsdResult(context, -1, LinuxError.EOPNOTSUPP); } - byte[] SendBuffer = Context.Memory.ReadBytes(SendPosition, SendSize); - EndPoint EndPoint = ParseSockAddr(Context, BufferPosition, BufferSize); + byte[] sendBuffer = context.Memory.ReadBytes(sendPosition, sendSize); + EndPoint endPoint = ParseSockAddr(context, bufferPosition, bufferSize); try { - Result = Socket.Handle.SendTo(SendBuffer, SendBuffer.Length, SocketFlags, EndPoint); - Errno = SetResultErrno(Socket.Handle, Result); + result = socket.Handle.SendTo(sendBuffer, sendBuffer.Length, socketFlags, endPoint); + errno = SetResultErrno(socket.Handle, result); } - catch (SocketException Exception) + catch (SocketException exception) { - Errno = ConvertError((WSAError)Exception.ErrorCode); + errno = ConvertError((WsaError)exception.ErrorCode); } } - return WriteBsdResult(Context, Result, Errno); + return WriteBsdResult(context, result, errno); } // Accept(u32 socket) -> (i32 ret, u32 bsd_errno, u32 addrlen, buffer addr) - public long Accept(ServiceCtx Context) + public long Accept(ServiceCtx context) { - int SocketFd = Context.RequestData.ReadInt32(); + int socketFd = context.RequestData.ReadInt32(); - (long BufferPos, long BufferSize) = Context.Request.GetBufferType0x22(); + (long bufferPos, long bufferSize) = context.Request.GetBufferType0x22(); - LinuxError Errno = LinuxError.EBADF; - BsdSocket Socket = RetrieveSocket(SocketFd); + LinuxError errno = LinuxError.EBADF; + BsdSocket socket = RetrieveSocket(socketFd); - if (Socket != null) + if (socket != null) { - Errno = LinuxError.SUCCESS; + errno = LinuxError.SUCCESS; - Socket NewSocket = null; + Socket newSocket = null; try { - NewSocket = Socket.Handle.Accept(); + newSocket = socket.Handle.Accept(); } - catch (SocketException Exception) + catch (SocketException exception) { - Errno = ConvertError((WSAError)Exception.ErrorCode); + errno = ConvertError((WsaError)exception.ErrorCode); } - if (NewSocket == null && Errno == LinuxError.SUCCESS) + if (newSocket == null && errno == LinuxError.SUCCESS) { - Errno = LinuxError.EWOULDBLOCK; + errno = LinuxError.EWOULDBLOCK; } - else if (Errno == LinuxError.SUCCESS) + else if (errno == LinuxError.SUCCESS) { - BsdSocket NewBsdSocket = new BsdSocket + BsdSocket newBsdSocket = new BsdSocket { - Family = (int)NewSocket.AddressFamily, - Type = (int)NewSocket.SocketType, - Protocol = (int)NewSocket.ProtocolType, - Handle = NewSocket, + Family = (int)newSocket.AddressFamily, + Type = (int)newSocket.SocketType, + Protocol = (int)newSocket.ProtocolType, + Handle = newSocket }; - Sockets.Add(NewBsdSocket); + _sockets.Add(newBsdSocket); - WriteSockAddr(Context, BufferPos, NewBsdSocket, true); + WriteSockAddr(context, bufferPos, newBsdSocket, true); - WriteBsdResult(Context, Sockets.Count - 1, Errno); + WriteBsdResult(context, _sockets.Count - 1, errno); - Context.ResponseData.Write(0x10); + context.ResponseData.Write(0x10); return 0; } } - return WriteBsdResult(Context, -1, Errno); + return WriteBsdResult(context, -1, errno); } // Bind(u32 socket, buffer addr) -> (i32 ret, u32 bsd_errno) - public long Bind(ServiceCtx Context) + public long Bind(ServiceCtx context) { - int SocketFd = Context.RequestData.ReadInt32(); + int socketFd = context.RequestData.ReadInt32(); - (long BufferPos, long BufferSize) = Context.Request.GetBufferType0x21(); + (long bufferPos, long bufferSize) = context.Request.GetBufferType0x21(); - LinuxError Errno = LinuxError.EBADF; - BsdSocket Socket = RetrieveSocket(SocketFd); + LinuxError errno = LinuxError.EBADF; + BsdSocket socket = RetrieveSocket(socketFd); - if (Socket != null) + if (socket != null) { - Errno = LinuxError.SUCCESS; + errno = LinuxError.SUCCESS; try { - IPEndPoint EndPoint = ParseSockAddr(Context, BufferPos, BufferSize); + IPEndPoint endPoint = ParseSockAddr(context, bufferPos, bufferSize); - Socket.Handle.Bind(EndPoint); + socket.Handle.Bind(endPoint); } - catch (SocketException Exception) + catch (SocketException exception) { - Errno = ConvertError((WSAError)Exception.ErrorCode); + errno = ConvertError((WsaError)exception.ErrorCode); } } - return WriteBsdResult(Context, 0, Errno); + return WriteBsdResult(context, 0, errno); } // Connect(u32 socket, buffer) -> (i32 ret, u32 bsd_errno) - public long Connect(ServiceCtx Context) + public long Connect(ServiceCtx context) { - int SocketFd = Context.RequestData.ReadInt32(); + int socketFd = context.RequestData.ReadInt32(); - (long BufferPos, long BufferSize) = Context.Request.GetBufferType0x21(); + (long bufferPos, long bufferSize) = context.Request.GetBufferType0x21(); - LinuxError Errno = LinuxError.EBADF; - BsdSocket Socket = RetrieveSocket(SocketFd); + LinuxError errno = LinuxError.EBADF; + BsdSocket socket = RetrieveSocket(socketFd); - if (Socket != null) + if (socket != null) { - Errno = LinuxError.SUCCESS; + errno = LinuxError.SUCCESS; try { - IPEndPoint EndPoint = ParseSockAddr(Context, BufferPos, BufferSize); + IPEndPoint endPoint = ParseSockAddr(context, bufferPos, bufferSize); - Socket.Handle.Connect(EndPoint); + socket.Handle.Connect(endPoint); } - catch (SocketException Exception) + catch (SocketException exception) { - Errno = ConvertError((WSAError)Exception.ErrorCode); + errno = ConvertError((WsaError)exception.ErrorCode); } } - return WriteBsdResult(Context, 0, Errno); + return WriteBsdResult(context, 0, errno); } // GetPeerName(u32 socket) -> (i32 ret, u32 bsd_errno, u32 addrlen, buffer addr) - public long GetPeerName(ServiceCtx Context) + public long GetPeerName(ServiceCtx context) { - int SocketFd = Context.RequestData.ReadInt32(); + int socketFd = context.RequestData.ReadInt32(); - (long BufferPos, long BufferSize) = Context.Request.GetBufferType0x22(); + (long bufferPos, long bufferSize) = context.Request.GetBufferType0x22(); - LinuxError Errno = LinuxError.EBADF; - BsdSocket Socket = RetrieveSocket(SocketFd); + LinuxError errno = LinuxError.EBADF; + BsdSocket socket = RetrieveSocket(socketFd); - if (Socket != null) + if (socket != null) { - Errno = LinuxError.SUCCESS; + errno = LinuxError.SUCCESS; - WriteSockAddr(Context, BufferPos, Socket, true); - WriteBsdResult(Context, 0, Errno); - Context.ResponseData.Write(0x10); + WriteSockAddr(context, bufferPos, socket, true); + WriteBsdResult(context, 0, errno); + context.ResponseData.Write(0x10); } - return WriteBsdResult(Context, 0, Errno); + return WriteBsdResult(context, 0, errno); } // GetSockName(u32 socket) -> (i32 ret, u32 bsd_errno, u32 addrlen, buffer addr) - public long GetSockName(ServiceCtx Context) + public long GetSockName(ServiceCtx context) { - int SocketFd = Context.RequestData.ReadInt32(); + int socketFd = context.RequestData.ReadInt32(); - (long BufferPos, long BufferSize) = Context.Request.GetBufferType0x22(); + (long bufferPos, long bufferSize) = context.Request.GetBufferType0x22(); - LinuxError Errno = LinuxError.EBADF; - BsdSocket Socket = RetrieveSocket(SocketFd); + LinuxError errno = LinuxError.EBADF; + BsdSocket socket = RetrieveSocket(socketFd); - if (Socket != null) + if (socket != null) { - Errno = LinuxError.SUCCESS; + errno = LinuxError.SUCCESS; - WriteSockAddr(Context, BufferPos, Socket, false); - WriteBsdResult(Context, 0, Errno); - Context.ResponseData.Write(0x10); + WriteSockAddr(context, bufferPos, socket, false); + WriteBsdResult(context, 0, errno); + context.ResponseData.Write(0x10); } - return WriteBsdResult(Context, 0, Errno); + return WriteBsdResult(context, 0, errno); } // GetSockOpt(u32 socket, u32 level, u32 option_name) -> (i32 ret, u32 bsd_errno, u32, buffer) - public long GetSockOpt(ServiceCtx Context) + public long GetSockOpt(ServiceCtx context) { - int SocketFd = Context.RequestData.ReadInt32(); - int Level = Context.RequestData.ReadInt32(); - int OptionName = Context.RequestData.ReadInt32(); + int socketFd = context.RequestData.ReadInt32(); + int level = context.RequestData.ReadInt32(); + int optionName = context.RequestData.ReadInt32(); - (long BufferPosition, long BufferSize) = Context.Request.GetBufferType0x22(); + (long bufferPosition, long bufferSize) = context.Request.GetBufferType0x22(); - LinuxError Errno = LinuxError.EBADF; - BsdSocket Socket = RetrieveSocket(SocketFd); + LinuxError errno = LinuxError.EBADF; + BsdSocket socket = RetrieveSocket(socketFd); - if (Socket != null) + if (socket != null) { - Errno = LinuxError.ENOPROTOOPT; + errno = LinuxError.ENOPROTOOPT; - if (Level == 0xFFFF) + if (level == 0xFFFF) { - Errno = HandleGetSocketOption(Context, Socket, (SocketOptionName)OptionName, BufferPosition, BufferSize); + errno = HandleGetSocketOption(context, socket, (SocketOptionName)optionName, bufferPosition, bufferSize); } else { - Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported GetSockOpt Level: {(SocketOptionLevel)Level}"); + Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported GetSockOpt Level: {(SocketOptionLevel)level}"); } } - return WriteBsdResult(Context, 0, Errno); + return WriteBsdResult(context, 0, errno); } // Listen(u32 socket, u32 backlog) -> (i32 ret, u32 bsd_errno) - public long Listen(ServiceCtx Context) + public long Listen(ServiceCtx context) { - int SocketFd = Context.RequestData.ReadInt32(); - int Backlog = Context.RequestData.ReadInt32(); + int socketFd = context.RequestData.ReadInt32(); + int backlog = context.RequestData.ReadInt32(); - LinuxError Errno = LinuxError.EBADF; - BsdSocket Socket = RetrieveSocket(SocketFd); + LinuxError errno = LinuxError.EBADF; + BsdSocket socket = RetrieveSocket(socketFd); - if (Socket != null) + if (socket != null) { - Errno = LinuxError.SUCCESS; + errno = LinuxError.SUCCESS; try { - Socket.Handle.Listen(Backlog); + socket.Handle.Listen(backlog); } - catch (SocketException Exception) + catch (SocketException exception) { - Errno = ConvertError((WSAError)Exception.ErrorCode); + errno = ConvertError((WsaError)exception.ErrorCode); } } - return WriteBsdResult(Context, 0, Errno); + return WriteBsdResult(context, 0, errno); } // Ioctl(u32 fd, u32 request, u32 bufcount, buffer, buffer, buffer, buffer) -> (i32 ret, u32 bsd_errno, buffer, buffer, buffer, buffer) - public long Ioctl(ServiceCtx Context) + public long Ioctl(ServiceCtx context) { - int SocketFd = Context.RequestData.ReadInt32(); - BsdIoctl Cmd = (BsdIoctl)Context.RequestData.ReadInt32(); - int BufferCount = Context.RequestData.ReadInt32(); + int socketFd = context.RequestData.ReadInt32(); + BsdIoctl cmd = (BsdIoctl)context.RequestData.ReadInt32(); + int bufferCount = context.RequestData.ReadInt32(); - LinuxError Errno = LinuxError.EBADF; - BsdSocket Socket = RetrieveSocket(SocketFd); + LinuxError errno = LinuxError.EBADF; + BsdSocket socket = RetrieveSocket(socketFd); - if (Socket != null) + if (socket != null) { - switch (Cmd) + switch (cmd) { case BsdIoctl.AtMark: - Errno = LinuxError.SUCCESS; + errno = LinuxError.SUCCESS; - (long BufferPosition, long BufferSize) = Context.Request.GetBufferType0x22(); + (long bufferPosition, long bufferSize) = context.Request.GetBufferType0x22(); // FIXME: OOB not implemented. - Context.Memory.WriteInt32(BufferPosition, 0); + context.Memory.WriteInt32(bufferPosition, 0); break; default: - Errno = LinuxError.EOPNOTSUPP; + errno = LinuxError.EOPNOTSUPP; - Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported Ioctl Cmd: {Cmd}"); + Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported Ioctl Cmd: {cmd}"); break; } } - return WriteBsdResult(Context, 0, Errno); + return WriteBsdResult(context, 0, errno); } // Fcntl(u32 socket, u32 cmd, u32 arg) -> (i32 ret, u32 bsd_errno) - public long Fcntl(ServiceCtx Context) + public long Fcntl(ServiceCtx context) { - int SocketFd = Context.RequestData.ReadInt32(); - int Cmd = Context.RequestData.ReadInt32(); - int Arg = Context.RequestData.ReadInt32(); + int socketFd = context.RequestData.ReadInt32(); + int cmd = context.RequestData.ReadInt32(); + int arg = context.RequestData.ReadInt32(); - int Result = 0; - LinuxError Errno = LinuxError.EBADF; - BsdSocket Socket = RetrieveSocket(SocketFd); + int result = 0; + LinuxError errno = LinuxError.EBADF; + BsdSocket socket = RetrieveSocket(socketFd); - if (Socket != null) + if (socket != null) { - Errno = LinuxError.SUCCESS; + errno = LinuxError.SUCCESS; - if (Cmd == 0x3) + if (cmd == 0x3) { - Result = !Socket.Handle.Blocking ? 0x800 : 0; + result = !socket.Handle.Blocking ? 0x800 : 0; } - else if (Cmd == 0x4 && Arg == 0x800) + else if (cmd == 0x4 && arg == 0x800) { - Socket.Handle.Blocking = false; - Result = 0; + socket.Handle.Blocking = false; + result = 0; } else { - Errno = LinuxError.EOPNOTSUPP; + errno = LinuxError.EOPNOTSUPP; } } - return WriteBsdResult(Context, Result, Errno); + return WriteBsdResult(context, result, errno); } - private LinuxError HandleGetSocketOption(ServiceCtx Context, BsdSocket Socket, SocketOptionName OptionName, long OptionValuePosition, long OptionValueSize) + private LinuxError HandleGetSocketOption(ServiceCtx context, BsdSocket socket, SocketOptionName optionName, long optionValuePosition, long optionValueSize) { try { - byte[] OptionValue = new byte[OptionValueSize]; + byte[] optionValue = new byte[optionValueSize]; - switch (OptionName) + switch (optionName) { case SocketOptionName.Broadcast: case SocketOptionName.DontLinger: @@ -928,34 +927,34 @@ namespace Ryujinx.HLE.HOS.Services.Bsd case SocketOptionName.SendTimeout: case SocketOptionName.Type: case SocketOptionName.Linger: - Socket.Handle.GetSocketOption(SocketOptionLevel.Socket, OptionName, OptionValue); - Context.Memory.WriteBytes(OptionValuePosition, OptionValue); + socket.Handle.GetSocketOption(SocketOptionLevel.Socket, optionName, optionValue); + context.Memory.WriteBytes(optionValuePosition, optionValue); return LinuxError.SUCCESS; case (SocketOptionName)0x200: - Socket.Handle.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, OptionValue); - Context.Memory.WriteBytes(OptionValuePosition, OptionValue); + socket.Handle.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, optionValue); + context.Memory.WriteBytes(optionValuePosition, optionValue); return LinuxError.SUCCESS; default: - Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported SetSockOpt OptionName: {OptionName}"); + Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported SetSockOpt OptionName: {optionName}"); return LinuxError.EOPNOTSUPP; } } - catch (SocketException Exception) + catch (SocketException exception) { - return ConvertError((WSAError)Exception.ErrorCode); + return ConvertError((WsaError)exception.ErrorCode); } } - private LinuxError HandleSetSocketOption(ServiceCtx Context, BsdSocket Socket, SocketOptionName OptionName, long OptionValuePosition, long OptionValueSize) + private LinuxError HandleSetSocketOption(ServiceCtx context, BsdSocket socket, SocketOptionName optionName, long optionValuePosition, long optionValueSize) { try { - switch (OptionName) + switch (optionName) { case SocketOptionName.Broadcast: case SocketOptionName.DontLinger: @@ -969,225 +968,225 @@ namespace Ryujinx.HLE.HOS.Services.Bsd case SocketOptionName.SendTimeout: case SocketOptionName.Type: case SocketOptionName.ReuseAddress: - Socket.Handle.SetSocketOption(SocketOptionLevel.Socket, OptionName, Context.Memory.ReadInt32(OptionValuePosition)); + socket.Handle.SetSocketOption(SocketOptionLevel.Socket, optionName, context.Memory.ReadInt32(optionValuePosition)); return LinuxError.SUCCESS; case (SocketOptionName)0x200: - Socket.Handle.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, Context.Memory.ReadInt32(OptionValuePosition)); + socket.Handle.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, context.Memory.ReadInt32(optionValuePosition)); return LinuxError.SUCCESS; case SocketOptionName.Linger: - Socket.Handle.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, - new LingerOption(Context.Memory.ReadInt32(OptionValuePosition) != 0, Context.Memory.ReadInt32(OptionValuePosition + 4))); + socket.Handle.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, + new LingerOption(context.Memory.ReadInt32(optionValuePosition) != 0, context.Memory.ReadInt32(optionValuePosition + 4))); return LinuxError.SUCCESS; default: - Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported SetSockOpt OptionName: {OptionName}"); + Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported SetSockOpt OptionName: {optionName}"); return LinuxError.EOPNOTSUPP; } } - catch (SocketException Exception) + catch (SocketException exception) { - return ConvertError((WSAError)Exception.ErrorCode); + return ConvertError((WsaError)exception.ErrorCode); } } // SetSockOpt(u32 socket, u32 level, u32 option_name, buffer option_value) -> (i32 ret, u32 bsd_errno) - public long SetSockOpt(ServiceCtx Context) + public long SetSockOpt(ServiceCtx context) { - int SocketFd = Context.RequestData.ReadInt32(); - int Level = Context.RequestData.ReadInt32(); - int OptionName = Context.RequestData.ReadInt32(); + int socketFd = context.RequestData.ReadInt32(); + int level = context.RequestData.ReadInt32(); + int optionName = context.RequestData.ReadInt32(); - (long BufferPos, long BufferSize) = Context.Request.GetBufferType0x21(); + (long bufferPos, long bufferSize) = context.Request.GetBufferType0x21(); - LinuxError Errno = LinuxError.EBADF; - BsdSocket Socket = RetrieveSocket(SocketFd); + LinuxError errno = LinuxError.EBADF; + BsdSocket socket = RetrieveSocket(socketFd); - if (Socket != null) + if (socket != null) { - Errno = LinuxError.ENOPROTOOPT; + errno = LinuxError.ENOPROTOOPT; - if (Level == 0xFFFF) + if (level == 0xFFFF) { - Errno = HandleSetSocketOption(Context, Socket, (SocketOptionName)OptionName, BufferPos, BufferSize); + errno = HandleSetSocketOption(context, socket, (SocketOptionName)optionName, bufferPos, bufferSize); } else { - Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported SetSockOpt Level: {(SocketOptionLevel)Level}"); + Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported SetSockOpt Level: {(SocketOptionLevel)level}"); } } - return WriteBsdResult(Context, 0, Errno); + return WriteBsdResult(context, 0, errno); } // Shutdown(u32 socket, u32 how) -> (i32 ret, u32 bsd_errno) - public long Shutdown(ServiceCtx Context) + public long Shutdown(ServiceCtx context) { - int SocketFd = Context.RequestData.ReadInt32(); - int How = Context.RequestData.ReadInt32(); + int socketFd = context.RequestData.ReadInt32(); + int how = context.RequestData.ReadInt32(); - LinuxError Errno = LinuxError.EBADF; - BsdSocket Socket = RetrieveSocket(SocketFd); + LinuxError errno = LinuxError.EBADF; + BsdSocket socket = RetrieveSocket(socketFd); - if (Socket != null) + if (socket != null) { - Errno = LinuxError.EINVAL; + errno = LinuxError.EINVAL; - if (How >= 0 && How <= 2) + if (how >= 0 && how <= 2) { - Errno = LinuxError.SUCCESS; + errno = LinuxError.SUCCESS; try { - Socket.Handle.Shutdown((SocketShutdown)How); + socket.Handle.Shutdown((SocketShutdown)how); } - catch (SocketException Exception) + catch (SocketException exception) { - Errno = ConvertError((WSAError)Exception.ErrorCode); + errno = ConvertError((WsaError)exception.ErrorCode); } } } - return WriteBsdResult(Context, 0, Errno); + return WriteBsdResult(context, 0, errno); } // ShutdownAllSockets(u32 how) -> (i32 ret, u32 bsd_errno) - public long ShutdownAllSockets(ServiceCtx Context) + public long ShutdownAllSockets(ServiceCtx context) { - int How = Context.RequestData.ReadInt32(); + int how = context.RequestData.ReadInt32(); - LinuxError Errno = LinuxError.EINVAL; + LinuxError errno = LinuxError.EINVAL; - if (How >= 0 && How <= 2) + if (how >= 0 && how <= 2) { - Errno = LinuxError.SUCCESS; + errno = LinuxError.SUCCESS; - foreach (BsdSocket Socket in Sockets) + foreach (BsdSocket socket in _sockets) { - if (Socket != null) + if (socket != null) { try { - Socket.Handle.Shutdown((SocketShutdown)How); + socket.Handle.Shutdown((SocketShutdown)how); } - catch (SocketException Exception) + catch (SocketException exception) { - Errno = ConvertError((WSAError)Exception.ErrorCode); + errno = ConvertError((WsaError)exception.ErrorCode); break; } } } } - return WriteBsdResult(Context, 0, Errno); + return WriteBsdResult(context, 0, errno); } // Write(u32 socket, buffer message) -> (i32 ret, u32 bsd_errno) - public long Write(ServiceCtx Context) + public long Write(ServiceCtx context) { - int SocketFd = Context.RequestData.ReadInt32(); + int socketFd = context.RequestData.ReadInt32(); - (long SendPosition, long SendSize) = Context.Request.GetBufferType0x21(); + (long sendPosition, long sendSize) = context.Request.GetBufferType0x21(); - LinuxError Errno = LinuxError.EBADF; - BsdSocket Socket = RetrieveSocket(SocketFd); - int Result = -1; + LinuxError errno = LinuxError.EBADF; + BsdSocket socket = RetrieveSocket(socketFd); + int result = -1; - if (Socket != null) + if (socket != null) { - byte[] SendBuffer = Context.Memory.ReadBytes(SendPosition, SendSize); + byte[] sendBuffer = context.Memory.ReadBytes(sendPosition, sendSize); try { - Result = Socket.Handle.Send(SendBuffer); - Errno = SetResultErrno(Socket.Handle, Result); + result = socket.Handle.Send(sendBuffer); + errno = SetResultErrno(socket.Handle, result); } - catch (SocketException Exception) + catch (SocketException exception) { - Errno = ConvertError((WSAError)Exception.ErrorCode); + errno = ConvertError((WsaError)exception.ErrorCode); } } - return WriteBsdResult(Context, Result, Errno); + return WriteBsdResult(context, result, errno); } // Read(u32 socket) -> (i32 ret, u32 bsd_errno, buffer message) - public long Read(ServiceCtx Context) + public long Read(ServiceCtx context) { - int SocketFd = Context.RequestData.ReadInt32(); + int socketFd = context.RequestData.ReadInt32(); - (long ReceivePosition, long ReceiveLength) = Context.Request.GetBufferType0x22(); + (long receivePosition, long receiveLength) = context.Request.GetBufferType0x22(); - LinuxError Errno = LinuxError.EBADF; - BsdSocket Socket = RetrieveSocket(SocketFd); - int Result = -1; + LinuxError errno = LinuxError.EBADF; + BsdSocket socket = RetrieveSocket(socketFd); + int result = -1; - if (Socket != null) + if (socket != null) { - byte[] ReceivedBuffer = new byte[ReceiveLength]; + byte[] receivedBuffer = new byte[receiveLength]; try { - Result = Socket.Handle.Receive(ReceivedBuffer); - Errno = SetResultErrno(Socket.Handle, Result); + result = socket.Handle.Receive(receivedBuffer); + errno = SetResultErrno(socket.Handle, result); } - catch (SocketException Exception) + catch (SocketException exception) { - Errno = ConvertError((WSAError)Exception.ErrorCode); + errno = ConvertError((WsaError)exception.ErrorCode); } } - return WriteBsdResult(Context, Result, Errno); + return WriteBsdResult(context, result, errno); } // Close(u32 socket) -> (i32 ret, u32 bsd_errno) - public long Close(ServiceCtx Context) + public long Close(ServiceCtx context) { - int SocketFd = Context.RequestData.ReadInt32(); + int socketFd = context.RequestData.ReadInt32(); - LinuxError Errno = LinuxError.EBADF; - BsdSocket Socket = RetrieveSocket(SocketFd); + LinuxError errno = LinuxError.EBADF; + BsdSocket socket = RetrieveSocket(socketFd); - if (Socket != null) + if (socket != null) { - Socket.Handle.Close(); + socket.Handle.Close(); - Sockets[SocketFd] = null; + _sockets[socketFd] = null; - Errno = LinuxError.SUCCESS; + errno = LinuxError.SUCCESS; } - return WriteBsdResult(Context, 0, Errno); + return WriteBsdResult(context, 0, errno); } // DuplicateSocket(u32 socket, u64 reserved) -> (i32 ret, u32 bsd_errno) - public long DuplicateSocket(ServiceCtx Context) + public long DuplicateSocket(ServiceCtx context) { - int SocketFd = Context.RequestData.ReadInt32(); - ulong Reserved = Context.RequestData.ReadUInt64(); + int socketFd = context.RequestData.ReadInt32(); + ulong reserved = context.RequestData.ReadUInt64(); - LinuxError Errno = LinuxError.ENOENT; - int NewSockFd = -1; + LinuxError errno = LinuxError.ENOENT; + int newSockFd = -1; - if (IsPrivileged) + if (_isPrivileged) { - Errno = LinuxError.EBADF; + errno = LinuxError.EBADF; - BsdSocket OldSocket = RetrieveSocket(SocketFd); + BsdSocket oldSocket = RetrieveSocket(socketFd); - if (OldSocket != null) + if (oldSocket != null) { - Sockets.Add(OldSocket); - NewSockFd = Sockets.Count - 1; + _sockets.Add(oldSocket); + newSockFd = _sockets.Count - 1; } } - return WriteBsdResult(Context, NewSockFd, Errno); + return WriteBsdResult(context, newSockFd, errno); } } } diff --git a/Ryujinx.HLE/HOS/Services/Bsd/PollEvent.cs b/Ryujinx.HLE/HOS/Services/Bsd/PollEvent.cs index 49cd4877..c4ed6045 100644 --- a/Ryujinx.HLE/HOS/Services/Bsd/PollEvent.cs +++ b/Ryujinx.HLE/HOS/Services/Bsd/PollEvent.cs @@ -9,7 +9,7 @@ Output = 4, Error = 8, Disconnected = 0x10, - Invalid = 0x20, + Invalid = 0x20 } public int SocketFd { get; private set; } @@ -17,12 +17,12 @@ public EventTypeMask InputEvents { get; private set; } public EventTypeMask OutputEvents { get; private set; } - public PollEvent(int SocketFd, BsdSocket Socket, EventTypeMask InputEvents, EventTypeMask OutputEvents) + public PollEvent(int socketFd, BsdSocket socket, EventTypeMask inputEvents, EventTypeMask outputEvents) { - this.SocketFd = SocketFd; - this.Socket = Socket; - this.InputEvents = InputEvents; - this.OutputEvents = OutputEvents; + SocketFd = socketFd; + Socket = socket; + InputEvents = inputEvents; + OutputEvents = outputEvents; } } } diff --git a/Ryujinx.HLE/HOS/Services/Caps/IAlbumAccessorService.cs b/Ryujinx.HLE/HOS/Services/Caps/IAlbumAccessorService.cs index 6d96b769..7b334ac4 100644 --- a/Ryujinx.HLE/HOS/Services/Caps/IAlbumAccessorService.cs +++ b/Ryujinx.HLE/HOS/Services/Caps/IAlbumAccessorService.cs @@ -5,13 +5,13 @@ namespace Ryujinx.HLE.HOS.Services.Caps { class IAlbumAccessorService : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IAlbumAccessorService() { - m_Commands = new Dictionary() + _commands = new Dictionary { //... }; diff --git a/Ryujinx.HLE/HOS/Services/Caps/IScreenshotService.cs b/Ryujinx.HLE/HOS/Services/Caps/IScreenshotService.cs index 5a54d563..63b155e0 100644 --- a/Ryujinx.HLE/HOS/Services/Caps/IScreenshotService.cs +++ b/Ryujinx.HLE/HOS/Services/Caps/IScreenshotService.cs @@ -5,13 +5,13 @@ namespace Ryujinx.HLE.HOS.Services.Caps { class IScreenshotService : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IScreenshotService() { - m_Commands = new Dictionary() + _commands = new Dictionary { //... }; diff --git a/Ryujinx.HLE/HOS/Services/Es/IETicketService.cs b/Ryujinx.HLE/HOS/Services/Es/IETicketService.cs index f11c78cc..049e94db 100644 --- a/Ryujinx.HLE/HOS/Services/Es/IETicketService.cs +++ b/Ryujinx.HLE/HOS/Services/Es/IETicketService.cs @@ -1,20 +1,19 @@ using Ryujinx.HLE.HOS.Ipc; -using Ryujinx.HLE.HOS.Kernel; using System.Collections.Generic; namespace Ryujinx.HLE.HOS.Services.Es { - class IETicketService : IpcService + class IeTicketService : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - private bool IsInitialized; + private bool _isInitialized; - public IETicketService() + public IeTicketService() { - m_Commands = new Dictionary() + _commands = new Dictionary { }; diff --git a/Ryujinx.HLE/HOS/Services/Friend/IFriendService.cs b/Ryujinx.HLE/HOS/Services/Friend/IFriendService.cs index e20de267..98348125 100644 --- a/Ryujinx.HLE/HOS/Services/Friend/IFriendService.cs +++ b/Ryujinx.HLE/HOS/Services/Friend/IFriendService.cs @@ -8,13 +8,13 @@ namespace Ryujinx.HLE.HOS.Services.Friend { class IFriendService : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IFriendService() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 10101, GetFriendList }, { 10601, DeclareCloseOnlinePlaySession }, @@ -23,76 +23,76 @@ namespace Ryujinx.HLE.HOS.Services.Friend } // nn::friends::GetFriendListGetFriendListIds(nn::account::Uid, int Unknown0, nn::friends::detail::ipc::SizedFriendFilter, ulong Unknown1) -> int CounterIds, array - public long GetFriendList(ServiceCtx Context) + public long GetFriendList(ServiceCtx context) { - UInt128 Uuid = new UInt128( - Context.RequestData.ReadInt64(), - Context.RequestData.ReadInt64()); + UInt128 uuid = new UInt128( + context.RequestData.ReadInt64(), + context.RequestData.ReadInt64()); - int Unknown0 = Context.RequestData.ReadInt32(); + int unknown0 = context.RequestData.ReadInt32(); - FriendFilter Filter = new FriendFilter() + FriendFilter filter = new FriendFilter { - PresenceStatus = (PresenceStatusFilter)Context.RequestData.ReadInt32(), - IsFavoriteOnly = Context.RequestData.ReadBoolean(), - IsSameAppPresenceOnly = Context.RequestData.ReadBoolean(), - IsSameAppPlayedOnly = Context.RequestData.ReadBoolean(), - IsArbitraryAppPlayedOnly = Context.RequestData.ReadBoolean(), - PresenceGroupId = Context.RequestData.ReadInt64() + PresenceStatus = (PresenceStatusFilter)context.RequestData.ReadInt32(), + IsFavoriteOnly = context.RequestData.ReadBoolean(), + IsSameAppPresenceOnly = context.RequestData.ReadBoolean(), + IsSameAppPlayedOnly = context.RequestData.ReadBoolean(), + IsArbitraryAppPlayedOnly = context.RequestData.ReadBoolean(), + PresenceGroupId = context.RequestData.ReadInt64() }; - long Unknown1 = Context.RequestData.ReadInt64(); + long unknown1 = context.RequestData.ReadInt64(); // There are no friends online, so we return 0 because the nn::account::NetworkServiceAccountId array is empty. - Context.ResponseData.Write(0); + context.ResponseData.Write(0); - Logger.PrintStub(LogClass.ServiceFriend, $"Stubbed. UserId: {Uuid.ToString()} - " + - $"Unknown0: {Unknown0} - " + - $"PresenceStatus: {Filter.PresenceStatus} - " + - $"IsFavoriteOnly: {Filter.IsFavoriteOnly} - " + - $"IsSameAppPresenceOnly: {Filter.IsSameAppPresenceOnly} - " + - $"IsSameAppPlayedOnly: {Filter.IsSameAppPlayedOnly} - " + - $"IsArbitraryAppPlayedOnly: {Filter.IsArbitraryAppPlayedOnly} - " + - $"PresenceGroupId: {Filter.PresenceGroupId} - " + - $"Unknown1: {Unknown1}"); + Logger.PrintStub(LogClass.ServiceFriend, $"Stubbed. UserId: {uuid.ToString()} - " + + $"Unknown0: {unknown0} - " + + $"PresenceStatus: {filter.PresenceStatus} - " + + $"IsFavoriteOnly: {filter.IsFavoriteOnly} - " + + $"IsSameAppPresenceOnly: {filter.IsSameAppPresenceOnly} - " + + $"IsSameAppPlayedOnly: {filter.IsSameAppPlayedOnly} - " + + $"IsArbitraryAppPlayedOnly: {filter.IsArbitraryAppPlayedOnly} - " + + $"PresenceGroupId: {filter.PresenceGroupId} - " + + $"Unknown1: {unknown1}"); return 0; } // DeclareCloseOnlinePlaySession(nn::account::Uid) - public long DeclareCloseOnlinePlaySession(ServiceCtx Context) + public long DeclareCloseOnlinePlaySession(ServiceCtx context) { - UInt128 Uuid = new UInt128( - Context.RequestData.ReadInt64(), - Context.RequestData.ReadInt64()); + UInt128 uuid = new UInt128( + context.RequestData.ReadInt64(), + context.RequestData.ReadInt64()); - if (Context.Device.System.State.TryGetUser(Uuid, out UserProfile Profile)) + if (context.Device.System.State.TryGetUser(uuid, out UserProfile profile)) { - Profile.OnlinePlayState = OpenCloseState.Closed; + profile.OnlinePlayState = OpenCloseState.Closed; } - Logger.PrintStub(LogClass.ServiceFriend, $"Stubbed. Uuid: {Uuid.ToString()} - " + - $"OnlinePlayState: {Profile.OnlinePlayState}"); + Logger.PrintStub(LogClass.ServiceFriend, $"Stubbed. Uuid: {uuid.ToString()} - " + + $"OnlinePlayState: {profile.OnlinePlayState}"); return 0; } // UpdateUserPresence(nn::account::Uid, ulong Unknown0) -> buffer - public long UpdateUserPresence(ServiceCtx Context) + public long UpdateUserPresence(ServiceCtx context) { - UInt128 Uuid = new UInt128( - Context.RequestData.ReadInt64(), - Context.RequestData.ReadInt64()); + UInt128 uuid = new UInt128( + context.RequestData.ReadInt64(), + context.RequestData.ReadInt64()); - long Unknown0 = Context.RequestData.ReadInt64(); + long unknown0 = context.RequestData.ReadInt64(); - long Position = Context.Request.PtrBuff[0].Position; - long Size = Context.Request.PtrBuff[0].Size; + long position = context.Request.PtrBuff[0].Position; + long size = context.Request.PtrBuff[0].Size; //Todo: Write the buffer content. - Logger.PrintStub(LogClass.ServiceFriend, $"Stubbed. Uuid: {Uuid.ToString()} - " + - $"Unknown0: {Unknown0}"); + Logger.PrintStub(LogClass.ServiceFriend, $"Stubbed. Uuid: {uuid.ToString()} - " + + $"Unknown0: {unknown0}"); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Friend/IServiceCreator.cs b/Ryujinx.HLE/HOS/Services/Friend/IServiceCreator.cs index 065e230d..d7f99997 100644 --- a/Ryujinx.HLE/HOS/Services/Friend/IServiceCreator.cs +++ b/Ryujinx.HLE/HOS/Services/Friend/IServiceCreator.cs @@ -5,21 +5,21 @@ namespace Ryujinx.HLE.HOS.Services.Friend { class IServiceCreator : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IServiceCreator() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, CreateFriendService } }; } - public static long CreateFriendService(ServiceCtx Context) + public static long CreateFriendService(ServiceCtx context) { - MakeObject(Context, new IFriendService()); + MakeObject(context, new IFriendService()); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/FspSrv/DirectoryEntry.cs b/Ryujinx.HLE/HOS/Services/FspSrv/DirectoryEntry.cs index 74ebddc2..6c3dadb1 100644 --- a/Ryujinx.HLE/HOS/Services/FspSrv/DirectoryEntry.cs +++ b/Ryujinx.HLE/HOS/Services/FspSrv/DirectoryEntry.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Ryujinx.HLE.HOS.Services.FspSrv +namespace Ryujinx.HLE.HOS.Services.FspSrv { public struct DirectoryEntry { @@ -11,11 +7,11 @@ namespace Ryujinx.HLE.HOS.Services.FspSrv public DirectoryEntryType EntryType { get; set; } - public DirectoryEntry(string Path, DirectoryEntryType DirectoryEntryType, long Size = 0) + public DirectoryEntry(string path, DirectoryEntryType directoryEntryType, long size = 0) { - this.Path = Path; - EntryType = DirectoryEntryType; - this.Size = Size; + Path = path; + EntryType = directoryEntryType; + Size = size; } } } diff --git a/Ryujinx.HLE/HOS/Services/FspSrv/FileSystemType.cs b/Ryujinx.HLE/HOS/Services/FspSrv/FileSystemType.cs index 2fd59673..20fc9bdc 100644 --- a/Ryujinx.HLE/HOS/Services/FspSrv/FileSystemType.cs +++ b/Ryujinx.HLE/HOS/Services/FspSrv/FileSystemType.cs @@ -1,6 +1,6 @@ namespace Ryujinx.HLE.HOS.Services.FspSrv { - enum FileSystemType : int + enum FileSystemType { Logo = 2, ContentControl = 3, diff --git a/Ryujinx.HLE/HOS/Services/FspSrv/IDirectory.cs b/Ryujinx.HLE/HOS/Services/FspSrv/IDirectory.cs index c964eecb..5f6235a5 100644 --- a/Ryujinx.HLE/HOS/Services/FspSrv/IDirectory.cs +++ b/Ryujinx.HLE/HOS/Services/FspSrv/IDirectory.cs @@ -11,88 +11,88 @@ namespace Ryujinx.HLE.HOS.Services.FspSrv { private const int DirectoryEntrySize = 0x310; - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - private List DirectoryEntries; + private List _directoryEntries; - private int CurrentItemIndex; + private int _currentItemIndex; public event EventHandler Disposed; public string DirectoryPath { get; private set; } - private IFileSystemProvider Provider; + private IFileSystemProvider _provider; - public IDirectory(string DirectoryPath, int Flags, IFileSystemProvider Provider) + public IDirectory(string directoryPath, int flags, IFileSystemProvider provider) { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, Read }, { 1, GetEntryCount } }; - this.Provider = Provider; - this.DirectoryPath = DirectoryPath; + _provider = provider; + DirectoryPath = directoryPath; - DirectoryEntries = new List(); + _directoryEntries = new List(); - if ((Flags & 1) != 0) + if ((flags & 1) != 0) { - DirectoryEntries.AddRange(Provider.GetDirectories(DirectoryPath)); + _directoryEntries.AddRange(provider.GetDirectories(directoryPath)); } - if ((Flags & 2) != 0) + if ((flags & 2) != 0) { - DirectoryEntries.AddRange(Provider.GetFiles(DirectoryPath)); + _directoryEntries.AddRange(provider.GetFiles(directoryPath)); } - CurrentItemIndex = 0; + _currentItemIndex = 0; } // Read() -> (u64 count, buffer entries) - public long Read(ServiceCtx Context) + public long Read(ServiceCtx context) { - long BufferPosition = Context.Request.ReceiveBuff[0].Position; - long BufferLen = Context.Request.ReceiveBuff[0].Size; + long bufferPosition = context.Request.ReceiveBuff[0].Position; + long bufferLen = context.Request.ReceiveBuff[0].Size; - int MaxReadCount = (int)(BufferLen / DirectoryEntrySize); + int maxReadCount = (int)(bufferLen / DirectoryEntrySize); - int Count = Math.Min(DirectoryEntries.Count - CurrentItemIndex, MaxReadCount); + int count = Math.Min(_directoryEntries.Count - _currentItemIndex, maxReadCount); - for (int Index = 0; Index < Count; Index++) + for (int index = 0; index < count; index++) { - long Position = BufferPosition + Index * DirectoryEntrySize; + long position = bufferPosition + index * DirectoryEntrySize; - WriteDirectoryEntry(Context, Position, DirectoryEntries[CurrentItemIndex++]); + WriteDirectoryEntry(context, position, _directoryEntries[_currentItemIndex++]); } - Context.ResponseData.Write((long)Count); + context.ResponseData.Write((long)count); return 0; } - private void WriteDirectoryEntry(ServiceCtx Context, long Position, DirectoryEntry Entry) + private void WriteDirectoryEntry(ServiceCtx context, long position, DirectoryEntry entry) { - for (int Offset = 0; Offset < 0x300; Offset += 8) + for (int offset = 0; offset < 0x300; offset += 8) { - Context.Memory.WriteInt64(Position + Offset, 0); + context.Memory.WriteInt64(position + offset, 0); } - byte[] NameBuffer = Encoding.UTF8.GetBytes(Path.GetFileName(Entry.Path)); + byte[] nameBuffer = Encoding.UTF8.GetBytes(Path.GetFileName(entry.Path)); - Context.Memory.WriteBytes(Position, NameBuffer); + context.Memory.WriteBytes(position, nameBuffer); - Context.Memory.WriteInt32(Position + 0x300, 0); //Padding? - Context.Memory.WriteInt32(Position + 0x304, (byte)Entry.EntryType); - Context.Memory.WriteInt64(Position + 0x308, Entry.Size); + context.Memory.WriteInt32(position + 0x300, 0); //Padding? + context.Memory.WriteInt32(position + 0x304, (byte)entry.EntryType); + context.Memory.WriteInt64(position + 0x308, entry.Size); } // GetEntryCount() -> u64 - public long GetEntryCount(ServiceCtx Context) + public long GetEntryCount(ServiceCtx context) { - Context.ResponseData.Write((long)DirectoryEntries.Count); + context.ResponseData.Write((long)_directoryEntries.Count); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/FspSrv/IFile.cs b/Ryujinx.HLE/HOS/Services/FspSrv/IFile.cs index 9bf152c4..c0ff5c64 100644 --- a/Ryujinx.HLE/HOS/Services/FspSrv/IFile.cs +++ b/Ryujinx.HLE/HOS/Services/FspSrv/IFile.cs @@ -7,19 +7,19 @@ namespace Ryujinx.HLE.HOS.Services.FspSrv { class IFile : IpcService, IDisposable { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - private Stream BaseStream; + private Stream _baseStream; public event EventHandler Disposed; public string HostPath { get; private set; } - public IFile(Stream BaseStream, string HostPath) + public IFile(Stream baseStream, string hostPath) { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, Read }, { 1, Write }, @@ -28,71 +28,71 @@ namespace Ryujinx.HLE.HOS.Services.FspSrv { 4, GetSize } }; - this.BaseStream = BaseStream; - this.HostPath = HostPath; + _baseStream = baseStream; + HostPath = hostPath; } // Read(u32, u64 offset, u64 size) -> (u64 out_size, buffer out_buf) - public long Read(ServiceCtx Context) + public long Read(ServiceCtx context) { - long Position = Context.Request.ReceiveBuff[0].Position; + long position = context.Request.ReceiveBuff[0].Position; - long Zero = Context.RequestData.ReadInt64(); - long Offset = Context.RequestData.ReadInt64(); - long Size = Context.RequestData.ReadInt64(); + long zero = context.RequestData.ReadInt64(); + long offset = context.RequestData.ReadInt64(); + long size = context.RequestData.ReadInt64(); - byte[] Data = new byte[Size]; + byte[] data = new byte[size]; - BaseStream.Seek(Offset, SeekOrigin.Begin); + _baseStream.Seek(offset, SeekOrigin.Begin); - int ReadSize = BaseStream.Read(Data, 0, (int)Size); + int readSize = _baseStream.Read(data, 0, (int)size); - Context.Memory.WriteBytes(Position, Data); + context.Memory.WriteBytes(position, data); - Context.ResponseData.Write((long)ReadSize); + context.ResponseData.Write((long)readSize); return 0; } // Write(u32, u64 offset, u64 size, buffer) - public long Write(ServiceCtx Context) + public long Write(ServiceCtx context) { - long Position = Context.Request.SendBuff[0].Position; + long position = context.Request.SendBuff[0].Position; - long Zero = Context.RequestData.ReadInt64(); - long Offset = Context.RequestData.ReadInt64(); - long Size = Context.RequestData.ReadInt64(); + long zero = context.RequestData.ReadInt64(); + long offset = context.RequestData.ReadInt64(); + long size = context.RequestData.ReadInt64(); - byte[] Data = Context.Memory.ReadBytes(Position, Size); + byte[] data = context.Memory.ReadBytes(position, size); - BaseStream.Seek(Offset, SeekOrigin.Begin); - BaseStream.Write(Data, 0, (int)Size); + _baseStream.Seek(offset, SeekOrigin.Begin); + _baseStream.Write(data, 0, (int)size); return 0; } // Flush() - public long Flush(ServiceCtx Context) + public long Flush(ServiceCtx context) { - BaseStream.Flush(); + _baseStream.Flush(); return 0; } // SetSize(u64 size) - public long SetSize(ServiceCtx Context) + public long SetSize(ServiceCtx context) { - long Size = Context.RequestData.ReadInt64(); + long size = context.RequestData.ReadInt64(); - BaseStream.SetLength(Size); + _baseStream.SetLength(size); return 0; } // GetSize() -> u64 fileSize - public long GetSize(ServiceCtx Context) + public long GetSize(ServiceCtx context) { - Context.ResponseData.Write(BaseStream.Length); + context.ResponseData.Write(_baseStream.Length); return 0; } @@ -104,9 +104,9 @@ namespace Ryujinx.HLE.HOS.Services.FspSrv protected virtual void Dispose(bool disposing) { - if (disposing && BaseStream != null) + if (disposing && _baseStream != null) { - BaseStream.Dispose(); + _baseStream.Dispose(); Disposed?.Invoke(this, EventArgs.Empty); } diff --git a/Ryujinx.HLE/HOS/Services/FspSrv/IFileSystem.cs b/Ryujinx.HLE/HOS/Services/FspSrv/IFileSystem.cs index edcdfa58..9e294460 100644 --- a/Ryujinx.HLE/HOS/Services/FspSrv/IFileSystem.cs +++ b/Ryujinx.HLE/HOS/Services/FspSrv/IFileSystem.cs @@ -11,19 +11,19 @@ namespace Ryujinx.HLE.HOS.Services.FspSrv { class IFileSystem : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - private HashSet OpenPaths; + private HashSet _openPaths; - private string Path; + private string _path; - private IFileSystemProvider Provider; + private IFileSystemProvider _provider; - public IFileSystem(string Path, IFileSystemProvider Provider) + public IFileSystem(string path, IFileSystemProvider provider) { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, CreateFile }, { 1, DeleteFile }, @@ -38,196 +38,196 @@ namespace Ryujinx.HLE.HOS.Services.FspSrv { 10, Commit }, { 11, GetFreeSpaceSize }, { 12, GetTotalSpaceSize }, - { 13, CleanDirectoryRecursively }, + { 13, CleanDirectoryRecursively } //{ 14, GetFileTimeStampRaw } }; - OpenPaths = new HashSet(); + _openPaths = new HashSet(); - this.Path = Path; - this.Provider = Provider; + _path = path; + _provider = provider; } // CreateFile(u32 mode, u64 size, buffer, 0x19, 0x301> path) - public long CreateFile(ServiceCtx Context) + public long CreateFile(ServiceCtx context) { - string Name = ReadUtf8String(Context); + string name = ReadUtf8String(context); - long Mode = Context.RequestData.ReadInt64(); - int Size = Context.RequestData.ReadInt32(); + long mode = context.RequestData.ReadInt64(); + int size = context.RequestData.ReadInt32(); - string FileName = Provider.GetFullPath(Name); + string fileName = _provider.GetFullPath(name); - if (FileName == null) + if (fileName == null) { return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); } - if (Provider.FileExists(FileName)) + if (_provider.FileExists(fileName)) { return MakeError(ErrorModule.Fs, FsErr.PathAlreadyExists); } - if (IsPathAlreadyInUse(FileName)) + if (IsPathAlreadyInUse(fileName)) { return MakeError(ErrorModule.Fs, FsErr.PathAlreadyInUse); } - return Provider.CreateFile(FileName, Size); + return _provider.CreateFile(fileName, size); } // DeleteFile(buffer, 0x19, 0x301> path) - public long DeleteFile(ServiceCtx Context) + public long DeleteFile(ServiceCtx context) { - string Name = ReadUtf8String(Context); + string name = ReadUtf8String(context); - string FileName = Provider.GetFullPath(Name); + string fileName = _provider.GetFullPath(name); - if (!Provider.FileExists(FileName)) + if (!_provider.FileExists(fileName)) { return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); } - if (IsPathAlreadyInUse(FileName)) + if (IsPathAlreadyInUse(fileName)) { return MakeError(ErrorModule.Fs, FsErr.PathAlreadyInUse); } - return Provider.DeleteFile(FileName); + return _provider.DeleteFile(fileName); } // CreateDirectory(buffer, 0x19, 0x301> path) - public long CreateDirectory(ServiceCtx Context) + public long CreateDirectory(ServiceCtx context) { - string Name = ReadUtf8String(Context); + string name = ReadUtf8String(context); - string DirName = Provider.GetFullPath(Name); + string dirName = _provider.GetFullPath(name); - if (DirName == null) + if (dirName == null) { return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); } - if (Provider.DirectoryExists(DirName)) + if (_provider.DirectoryExists(dirName)) { return MakeError(ErrorModule.Fs, FsErr.PathAlreadyExists); } - if (IsPathAlreadyInUse(DirName)) + if (IsPathAlreadyInUse(dirName)) { return MakeError(ErrorModule.Fs, FsErr.PathAlreadyInUse); } - Provider.CreateDirectory(DirName); + _provider.CreateDirectory(dirName); return 0; } // DeleteDirectory(buffer, 0x19, 0x301> path) - public long DeleteDirectory(ServiceCtx Context) + public long DeleteDirectory(ServiceCtx context) { - return DeleteDirectory(Context, false); + return DeleteDirectory(context, false); } // DeleteDirectoryRecursively(buffer, 0x19, 0x301> path) - public long DeleteDirectoryRecursively(ServiceCtx Context) + public long DeleteDirectoryRecursively(ServiceCtx context) { - return DeleteDirectory(Context, true); + return DeleteDirectory(context, true); } - private long DeleteDirectory(ServiceCtx Context, bool Recursive) + private long DeleteDirectory(ServiceCtx context, bool recursive) { - string Name = ReadUtf8String(Context); + string name = ReadUtf8String(context); - string DirName = Provider.GetFullPath(Name); + string dirName = _provider.GetFullPath(name); - if (!Directory.Exists(DirName)) + if (!Directory.Exists(dirName)) { return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); } - if (IsPathAlreadyInUse(DirName)) + if (IsPathAlreadyInUse(dirName)) { return MakeError(ErrorModule.Fs, FsErr.PathAlreadyInUse); } - Provider.DeleteDirectory(DirName, Recursive); + _provider.DeleteDirectory(dirName, recursive); return 0; } // RenameFile(buffer, 0x19, 0x301> oldPath, buffer, 0x19, 0x301> newPath) - public long RenameFile(ServiceCtx Context) + public long RenameFile(ServiceCtx context) { - string OldName = ReadUtf8String(Context, 0); - string NewName = ReadUtf8String(Context, 1); + string oldName = ReadUtf8String(context, 0); + string newName = ReadUtf8String(context, 1); - string OldFileName = Provider.GetFullPath(OldName); - string NewFileName = Provider.GetFullPath(NewName); + string oldFileName = _provider.GetFullPath(oldName); + string newFileName = _provider.GetFullPath(newName); - if (Provider.FileExists(OldFileName)) + if (_provider.FileExists(oldFileName)) { return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); } - if (Provider.FileExists(NewFileName)) + if (_provider.FileExists(newFileName)) { return MakeError(ErrorModule.Fs, FsErr.PathAlreadyExists); } - if (IsPathAlreadyInUse(OldFileName)) + if (IsPathAlreadyInUse(oldFileName)) { return MakeError(ErrorModule.Fs, FsErr.PathAlreadyInUse); } - return Provider.RenameFile(OldFileName, NewFileName); + return _provider.RenameFile(oldFileName, newFileName); } // RenameDirectory(buffer, 0x19, 0x301> oldPath, buffer, 0x19, 0x301> newPath) - public long RenameDirectory(ServiceCtx Context) + public long RenameDirectory(ServiceCtx context) { - string OldName = ReadUtf8String(Context, 0); - string NewName = ReadUtf8String(Context, 1); + string oldName = ReadUtf8String(context, 0); + string newName = ReadUtf8String(context, 1); - string OldDirName = Provider.GetFullPath(OldName); - string NewDirName = Provider.GetFullPath(NewName); + string oldDirName = _provider.GetFullPath(oldName); + string newDirName = _provider.GetFullPath(newName); - if (!Provider.DirectoryExists(OldDirName)) + if (!_provider.DirectoryExists(oldDirName)) { return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); } - if (!Provider.DirectoryExists(NewDirName)) + if (!_provider.DirectoryExists(newDirName)) { return MakeError(ErrorModule.Fs, FsErr.PathAlreadyExists); } - if (IsPathAlreadyInUse(OldDirName)) + if (IsPathAlreadyInUse(oldDirName)) { return MakeError(ErrorModule.Fs, FsErr.PathAlreadyInUse); } - return Provider.RenameDirectory(OldDirName, NewDirName); + return _provider.RenameDirectory(oldDirName, newDirName); } // GetEntryType(buffer, 0x19, 0x301> path) -> nn::fssrv::sf::DirectoryEntryType - public long GetEntryType(ServiceCtx Context) + public long GetEntryType(ServiceCtx context) { - string Name = ReadUtf8String(Context); + string name = ReadUtf8String(context); - string FileName = Provider.GetFullPath(Name); + string fileName = _provider.GetFullPath(name); - if (Provider.FileExists(FileName)) + if (_provider.FileExists(fileName)) { - Context.ResponseData.Write(1); + context.ResponseData.Write(1); } - else if (Provider.DirectoryExists(FileName)) + else if (_provider.DirectoryExists(fileName)) { - Context.ResponseData.Write(0); + context.ResponseData.Write(0); } else { - Context.ResponseData.Write(0); + context.ResponseData.Write(0); return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); } @@ -236,167 +236,167 @@ namespace Ryujinx.HLE.HOS.Services.FspSrv } // OpenFile(u32 mode, buffer, 0x19, 0x301> path) -> object file - public long OpenFile(ServiceCtx Context) + public long OpenFile(ServiceCtx context) { - int FilterFlags = Context.RequestData.ReadInt32(); + int filterFlags = context.RequestData.ReadInt32(); - string Name = ReadUtf8String(Context); + string name = ReadUtf8String(context); - string FileName = Provider.GetFullPath(Name); + string fileName = _provider.GetFullPath(name); - if (!Provider.FileExists(FileName)) + if (!_provider.FileExists(fileName)) { return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); } - if (IsPathAlreadyInUse(FileName)) + if (IsPathAlreadyInUse(fileName)) { return MakeError(ErrorModule.Fs, FsErr.PathAlreadyInUse); } - long Error = Provider.OpenFile(FileName, out IFile FileInterface); + long error = _provider.OpenFile(fileName, out IFile fileInterface); - if (Error == 0) + if (error == 0) { - FileInterface.Disposed += RemoveFileInUse; + fileInterface.Disposed += RemoveFileInUse; - lock (OpenPaths) + lock (_openPaths) { - OpenPaths.Add(FileName); + _openPaths.Add(fileName); } - MakeObject(Context, FileInterface); + MakeObject(context, fileInterface); return 0; } - return Error; + return error; } // OpenDirectory(u32 filter_flags, buffer, 0x19, 0x301> path) -> object directory - public long OpenDirectory(ServiceCtx Context) + public long OpenDirectory(ServiceCtx context) { - int FilterFlags = Context.RequestData.ReadInt32(); + int filterFlags = context.RequestData.ReadInt32(); - string Name = ReadUtf8String(Context); + string name = ReadUtf8String(context); - string DirName = Provider.GetFullPath(Name); + string dirName = _provider.GetFullPath(name); - if (!Provider.DirectoryExists(DirName)) + if (!_provider.DirectoryExists(dirName)) { return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); } - if (IsPathAlreadyInUse(DirName)) + if (IsPathAlreadyInUse(dirName)) { return MakeError(ErrorModule.Fs, FsErr.PathAlreadyInUse); } - long Error = Provider.OpenDirectory(DirName, FilterFlags, out IDirectory DirInterface); + long error = _provider.OpenDirectory(dirName, filterFlags, out IDirectory dirInterface); - if (Error == 0) + if (error == 0) { - DirInterface.Disposed += RemoveDirectoryInUse; + dirInterface.Disposed += RemoveDirectoryInUse; - lock (OpenPaths) + lock (_openPaths) { - OpenPaths.Add(DirName); + _openPaths.Add(dirName); } - MakeObject(Context, DirInterface); + MakeObject(context, dirInterface); } - return Error; + return error; } // Commit() - public long Commit(ServiceCtx Context) + public long Commit(ServiceCtx context) { return 0; } // GetFreeSpaceSize(buffer, 0x19, 0x301> path) -> u64 totalFreeSpace - public long GetFreeSpaceSize(ServiceCtx Context) + public long GetFreeSpaceSize(ServiceCtx context) { - string Name = ReadUtf8String(Context); + string name = ReadUtf8String(context); - Context.ResponseData.Write(Provider.GetFreeSpace(Context)); + context.ResponseData.Write(_provider.GetFreeSpace(context)); return 0; } // GetTotalSpaceSize(buffer, 0x19, 0x301> path) -> u64 totalSize - public long GetTotalSpaceSize(ServiceCtx Context) + public long GetTotalSpaceSize(ServiceCtx context) { - string Name = ReadUtf8String(Context); + string name = ReadUtf8String(context); - Context.ResponseData.Write(Provider.GetFreeSpace(Context)); + context.ResponseData.Write(_provider.GetFreeSpace(context)); return 0; } // CleanDirectoryRecursively(buffer, 0x19, 0x301> path) - public long CleanDirectoryRecursively(ServiceCtx Context) + public long CleanDirectoryRecursively(ServiceCtx context) { - string Name = ReadUtf8String(Context); + string name = ReadUtf8String(context); - string DirName = Provider.GetFullPath(Name); + string dirName = _provider.GetFullPath(name); - if (!Provider.DirectoryExists(DirName)) + if (!_provider.DirectoryExists(dirName)) { return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); } - if (IsPathAlreadyInUse(DirName)) + if (IsPathAlreadyInUse(dirName)) { return MakeError(ErrorModule.Fs, FsErr.PathAlreadyInUse); } - foreach (DirectoryEntry Entry in Provider.GetEntries(DirName)) + foreach (DirectoryEntry entry in _provider.GetEntries(dirName)) { - if (Provider.DirectoryExists(Entry.Path)) + if (_provider.DirectoryExists(entry.Path)) { - Provider.DeleteDirectory(Entry.Path, true); + _provider.DeleteDirectory(entry.Path, true); } - else if (Provider.FileExists(Entry.Path)) + else if (_provider.FileExists(entry.Path)) { - Provider.DeleteFile(Entry.Path); + _provider.DeleteFile(entry.Path); } } return 0; } - private bool IsPathAlreadyInUse(string Path) + private bool IsPathAlreadyInUse(string path) { - lock (OpenPaths) + lock (_openPaths) { - return OpenPaths.Contains(Path); + return _openPaths.Contains(path); } } private void RemoveFileInUse(object sender, EventArgs e) { - IFile FileInterface = (IFile)sender; + IFile fileInterface = (IFile)sender; - lock (OpenPaths) + lock (_openPaths) { - FileInterface.Disposed -= RemoveFileInUse; + fileInterface.Disposed -= RemoveFileInUse; - OpenPaths.Remove(FileInterface.HostPath); + _openPaths.Remove(fileInterface.HostPath); } } private void RemoveDirectoryInUse(object sender, EventArgs e) { - IDirectory DirInterface = (IDirectory)sender; + IDirectory dirInterface = (IDirectory)sender; - lock (OpenPaths) + lock (_openPaths) { - DirInterface.Disposed -= RemoveDirectoryInUse; + dirInterface.Disposed -= RemoveDirectoryInUse; - OpenPaths.Remove(DirInterface.DirectoryPath); + _openPaths.Remove(dirInterface.DirectoryPath); } } } diff --git a/Ryujinx.HLE/HOS/Services/FspSrv/IFileSystemProxy.cs b/Ryujinx.HLE/HOS/Services/FspSrv/IFileSystemProxy.cs index 0fc1eb80..8764792c 100644 --- a/Ryujinx.HLE/HOS/Services/FspSrv/IFileSystemProxy.cs +++ b/Ryujinx.HLE/HOS/Services/FspSrv/IFileSystemProxy.cs @@ -14,13 +14,13 @@ namespace Ryujinx.HLE.HOS.Services.FspSrv { class IFileSystemProxy : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IFileSystemProxy() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 1, Initialize }, { 8, OpenFileSystemWithId }, @@ -36,246 +36,246 @@ namespace Ryujinx.HLE.HOS.Services.FspSrv } // Initialize(u64, pid) - public long Initialize(ServiceCtx Context) + public long Initialize(ServiceCtx context) { return 0; } // OpenFileSystemWithId(nn::fssrv::sf::FileSystemType filesystem_type, nn::ApplicationId tid, buffer, 0x19, 0x301> path) // -> object contentFs - public long OpenFileSystemWithId(ServiceCtx Context) + public long OpenFileSystemWithId(ServiceCtx context) { - FileSystemType FileSystemType = (FileSystemType)Context.RequestData.ReadInt32(); - long TitleId = Context.RequestData.ReadInt64(); - string SwitchPath = ReadUtf8String(Context); - string FullPath = Context.Device.FileSystem.SwitchPathToSystemPath(SwitchPath); + FileSystemType fileSystemType = (FileSystemType)context.RequestData.ReadInt32(); + long titleId = context.RequestData.ReadInt64(); + string switchPath = ReadUtf8String(context); + string fullPath = context.Device.FileSystem.SwitchPathToSystemPath(switchPath); - if (!File.Exists(FullPath)) + if (!File.Exists(fullPath)) { - if (FullPath.Contains(".")) + if (fullPath.Contains(".")) { - return OpenFileSystemFromInternalFile(Context, FullPath); + return OpenFileSystemFromInternalFile(context, fullPath); } return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); } - FileStream FileStream = new FileStream(FullPath, FileMode.Open, FileAccess.Read); - string Extension = Path.GetExtension(FullPath); + FileStream fileStream = new FileStream(fullPath, FileMode.Open, FileAccess.Read); + string extension = Path.GetExtension(fullPath); - if (Extension == ".nca") + if (extension == ".nca") { - return OpenNcaFs(Context, FullPath, FileStream); + return OpenNcaFs(context, fullPath, fileStream); } - else if (Extension == ".nsp") + else if (extension == ".nsp") { - return OpenNsp(Context, FullPath); + return OpenNsp(context, fullPath); } return MakeError(ErrorModule.Fs, FsErr.InvalidInput); } // OpenBisFileSystem(nn::fssrv::sf::Partition partitionID, buffer, 0x19, 0x301>) -> object Bis - public long OpenBisFileSystem(ServiceCtx Context) + public long OpenBisFileSystem(ServiceCtx context) { - int BisPartitionId = Context.RequestData.ReadInt32(); - string PartitionString = ReadUtf8String(Context); - string BisPartitonPath = string.Empty; + int bisPartitionId = context.RequestData.ReadInt32(); + string partitionString = ReadUtf8String(context); + string bisPartitonPath = string.Empty; - switch (BisPartitionId) + switch (bisPartitionId) { case 29: - BisPartitonPath = SafeNandPath; + bisPartitonPath = SafeNandPath; break; case 30: case 31: - BisPartitonPath = SystemNandPath; + bisPartitonPath = SystemNandPath; break; case 32: - BisPartitonPath = UserNandPath; + bisPartitonPath = UserNandPath; break; default: return MakeError(ErrorModule.Fs, FsErr.InvalidInput); } - string FullPath = Context.Device.FileSystem.GetFullPartitionPath(BisPartitonPath); + string fullPath = context.Device.FileSystem.GetFullPartitionPath(bisPartitonPath); - FileSystemProvider FileSystemProvider = new FileSystemProvider(FullPath, Context.Device.FileSystem.GetBasePath()); + FileSystemProvider fileSystemProvider = new FileSystemProvider(fullPath, context.Device.FileSystem.GetBasePath()); - MakeObject(Context, new IFileSystem(FullPath, FileSystemProvider)); + MakeObject(context, new IFileSystem(fullPath, fileSystemProvider)); return 0; } // OpenSdCardFileSystem() -> object - public long OpenSdCardFileSystem(ServiceCtx Context) + public long OpenSdCardFileSystem(ServiceCtx context) { - string SdCardPath = Context.Device.FileSystem.GetSdCardPath(); + string sdCardPath = context.Device.FileSystem.GetSdCardPath(); - FileSystemProvider FileSystemProvider = new FileSystemProvider(SdCardPath, Context.Device.FileSystem.GetBasePath()); + FileSystemProvider fileSystemProvider = new FileSystemProvider(sdCardPath, context.Device.FileSystem.GetBasePath()); - MakeObject(Context, new IFileSystem(SdCardPath, FileSystemProvider)); + MakeObject(context, new IFileSystem(sdCardPath, fileSystemProvider)); return 0; } // OpenSaveDataFileSystem(u8 save_data_space_id, nn::fssrv::sf::SaveStruct saveStruct) -> object saveDataFs - public long OpenSaveDataFileSystem(ServiceCtx Context) + public long OpenSaveDataFileSystem(ServiceCtx context) { - LoadSaveDataFileSystem(Context); + LoadSaveDataFileSystem(context); return 0; } // OpenSaveDataFileSystemBySystemSaveDataId(u8 save_data_space_id, nn::fssrv::sf::SaveStruct saveStruct) -> object systemSaveDataFs - public long OpenSaveDataFileSystemBySystemSaveDataId(ServiceCtx Context) + public long OpenSaveDataFileSystemBySystemSaveDataId(ServiceCtx context) { - LoadSaveDataFileSystem(Context); + LoadSaveDataFileSystem(context); return 0; } // OpenDataStorageByCurrentProcess() -> object dataStorage - public long OpenDataStorageByCurrentProcess(ServiceCtx Context) + public long OpenDataStorageByCurrentProcess(ServiceCtx context) { - MakeObject(Context, new IStorage(Context.Device.FileSystem.RomFs)); + MakeObject(context, new IStorage(context.Device.FileSystem.RomFs)); return 0; } // OpenDataStorageByDataId(u8 storageId, nn::ApplicationId tid) -> object dataStorage - public long OpenDataStorageByDataId(ServiceCtx Context) + public long OpenDataStorageByDataId(ServiceCtx context) { - StorageId StorageId = (StorageId)Context.RequestData.ReadByte(); - byte[] Padding = Context.RequestData.ReadBytes(7); - long TitleId = Context.RequestData.ReadInt64(); + StorageId storageId = (StorageId)context.RequestData.ReadByte(); + byte[] padding = context.RequestData.ReadBytes(7); + long titleId = context.RequestData.ReadInt64(); - StorageId InstalledStorage = - Context.Device.System.ContentManager.GetInstalledStorage(TitleId, ContentType.Data, StorageId); + StorageId installedStorage = + context.Device.System.ContentManager.GetInstalledStorage(titleId, ContentType.Data, storageId); - if (InstalledStorage == StorageId.None) + if (installedStorage == StorageId.None) { - InstalledStorage = - Context.Device.System.ContentManager.GetInstalledStorage(TitleId, ContentType.AocData, StorageId); + installedStorage = + context.Device.System.ContentManager.GetInstalledStorage(titleId, ContentType.AocData, storageId); } - if (InstalledStorage != StorageId.None) + if (installedStorage != StorageId.None) { - string ContentPath = Context.Device.System.ContentManager.GetInstalledContentPath(TitleId, StorageId, ContentType.AocData); + string contentPath = context.Device.System.ContentManager.GetInstalledContentPath(titleId, storageId, ContentType.AocData); - if (string.IsNullOrWhiteSpace(ContentPath)) + if (string.IsNullOrWhiteSpace(contentPath)) { - ContentPath = Context.Device.System.ContentManager.GetInstalledContentPath(TitleId, StorageId, ContentType.AocData); + contentPath = context.Device.System.ContentManager.GetInstalledContentPath(titleId, storageId, ContentType.AocData); } - string InstallPath = Context.Device.FileSystem.SwitchPathToSystemPath(ContentPath); + string installPath = context.Device.FileSystem.SwitchPathToSystemPath(contentPath); - if (!string.IsNullOrWhiteSpace(InstallPath)) + if (!string.IsNullOrWhiteSpace(installPath)) { - string NcaPath = InstallPath; + string ncaPath = installPath; - if (File.Exists(NcaPath)) + if (File.Exists(ncaPath)) { - FileStream NcaStream = new FileStream(NcaPath, FileMode.Open, FileAccess.Read); - Nca Nca = new Nca(Context.Device.System.KeySet, NcaStream, false); - NcaSection RomfsSection = Nca.Sections.FirstOrDefault(x => x?.Type == SectionType.Romfs); - Stream RomfsStream = Nca.OpenSection(RomfsSection.SectionNum, false, Context.Device.System.FsIntegrityCheckLevel); + FileStream ncaStream = new FileStream(ncaPath, FileMode.Open, FileAccess.Read); + Nca nca = new Nca(context.Device.System.KeySet, ncaStream, false); + NcaSection romfsSection = nca.Sections.FirstOrDefault(x => x?.Type == SectionType.Romfs); + Stream romfsStream = nca.OpenSection(romfsSection.SectionNum, false, context.Device.System.FsIntegrityCheckLevel); - MakeObject(Context, new IStorage(RomfsStream)); + MakeObject(context, new IStorage(romfsStream)); return 0; } else { - throw new FileNotFoundException($"No Nca found in Path `{NcaPath}`."); + throw new FileNotFoundException($"No Nca found in Path `{ncaPath}`."); } } else { - throw new DirectoryNotFoundException($"Path for title id {TitleId:x16} on Storage {StorageId} was not found in Path {InstallPath}."); + throw new DirectoryNotFoundException($"Path for title id {titleId:x16} on Storage {storageId} was not found in Path {installPath}."); } } - throw new FileNotFoundException($"System archive with titleid {TitleId:x16} was not found on Storage {StorageId}. Found in {InstalledStorage}."); + throw new FileNotFoundException($"System archive with titleid {titleId:x16} was not found on Storage {storageId}. Found in {installedStorage}."); } // OpenPatchDataStorageByCurrentProcess() -> object - public long OpenPatchDataStorageByCurrentProcess(ServiceCtx Context) + public long OpenPatchDataStorageByCurrentProcess(ServiceCtx context) { - MakeObject(Context, new IStorage(Context.Device.FileSystem.RomFs)); + MakeObject(context, new IStorage(context.Device.FileSystem.RomFs)); return 0; } // GetGlobalAccessLogMode() -> u32 logMode - public long GetGlobalAccessLogMode(ServiceCtx Context) + public long GetGlobalAccessLogMode(ServiceCtx context) { - Context.ResponseData.Write(0); + context.ResponseData.Write(0); return 0; } - public void LoadSaveDataFileSystem(ServiceCtx Context) + public void LoadSaveDataFileSystem(ServiceCtx context) { - SaveSpaceId SaveSpaceId = (SaveSpaceId)Context.RequestData.ReadInt64(); + SaveSpaceId saveSpaceId = (SaveSpaceId)context.RequestData.ReadInt64(); - long TitleId = Context.RequestData.ReadInt64(); + long titleId = context.RequestData.ReadInt64(); - UInt128 UserId = new UInt128( - Context.RequestData.ReadInt64(), - Context.RequestData.ReadInt64()); + UInt128 userId = new UInt128( + context.RequestData.ReadInt64(), + context.RequestData.ReadInt64()); - long SaveId = Context.RequestData.ReadInt64(); - SaveDataType SaveDataType = (SaveDataType)Context.RequestData.ReadByte(); - SaveInfo SaveInfo = new SaveInfo(TitleId, SaveId, SaveDataType, UserId, SaveSpaceId); - string SavePath = Context.Device.FileSystem.GetGameSavePath(SaveInfo, Context); - FileSystemProvider FileSystemProvider = new FileSystemProvider(SavePath, Context.Device.FileSystem.GetBasePath()); + long saveId = context.RequestData.ReadInt64(); + SaveDataType saveDataType = (SaveDataType)context.RequestData.ReadByte(); + SaveInfo saveInfo = new SaveInfo(titleId, saveId, saveDataType, userId, saveSpaceId); + string savePath = context.Device.FileSystem.GetGameSavePath(saveInfo, context); + FileSystemProvider fileSystemProvider = new FileSystemProvider(savePath, context.Device.FileSystem.GetBasePath()); - MakeObject(Context, new IFileSystem(SavePath, FileSystemProvider)); + MakeObject(context, new IFileSystem(savePath, fileSystemProvider)); } - private long OpenNsp(ServiceCtx Context, string PfsPath) + private long OpenNsp(ServiceCtx context, string pfsPath) { - FileStream PfsFile = new FileStream(PfsPath, FileMode.Open, FileAccess.Read); - Pfs Nsp = new Pfs(PfsFile); - PfsFileEntry TicketFile = Nsp.Files.FirstOrDefault(x => x.Name.EndsWith(".tik")); + FileStream pfsFile = new FileStream(pfsPath, FileMode.Open, FileAccess.Read); + Pfs nsp = new Pfs(pfsFile); + PfsFileEntry ticketFile = nsp.Files.FirstOrDefault(x => x.Name.EndsWith(".tik")); - if (TicketFile != null) + if (ticketFile != null) { - Ticket Ticket = new Ticket(Nsp.OpenFile(TicketFile)); + Ticket ticket = new Ticket(nsp.OpenFile(ticketFile)); - Context.Device.System.KeySet.TitleKeys[Ticket.RightsId] = - Ticket.GetTitleKey(Context.Device.System.KeySet); + context.Device.System.KeySet.TitleKeys[ticket.RightsId] = + ticket.GetTitleKey(context.Device.System.KeySet); } - IFileSystem NspFileSystem = new IFileSystem(PfsPath, new PFsProvider(Nsp)); + IFileSystem nspFileSystem = new IFileSystem(pfsPath, new PFsProvider(nsp)); - MakeObject(Context, NspFileSystem); + MakeObject(context, nspFileSystem); return 0; } - private long OpenNcaFs(ServiceCtx Context,string NcaPath, Stream NcaStream) + private long OpenNcaFs(ServiceCtx context,string ncaPath, Stream ncaStream) { - Nca Nca = new Nca(Context.Device.System.KeySet, NcaStream, false); + Nca nca = new Nca(context.Device.System.KeySet, ncaStream, false); - NcaSection RomfsSection = Nca.Sections.FirstOrDefault(x => x?.Type == SectionType.Romfs); - NcaSection PfsSection = Nca.Sections.FirstOrDefault(x => x?.Type == SectionType.Pfs0); + NcaSection romfsSection = nca.Sections.FirstOrDefault(x => x?.Type == SectionType.Romfs); + NcaSection pfsSection = nca.Sections.FirstOrDefault(x => x?.Type == SectionType.Pfs0); - if (RomfsSection != null) + if (romfsSection != null) { - Stream RomfsStream = Nca.OpenSection(RomfsSection.SectionNum, false, Context.Device.System.FsIntegrityCheckLevel); - IFileSystem NcaFileSystem = new IFileSystem(NcaPath, new RomFsProvider(RomfsStream)); + Stream romfsStream = nca.OpenSection(romfsSection.SectionNum, false, context.Device.System.FsIntegrityCheckLevel); + IFileSystem ncaFileSystem = new IFileSystem(ncaPath, new RomFsProvider(romfsStream)); - MakeObject(Context, NcaFileSystem); + MakeObject(context, ncaFileSystem); } - else if(PfsSection !=null) + else if(pfsSection !=null) { - Stream PfsStream = Nca.OpenSection(PfsSection.SectionNum, false, Context.Device.System.FsIntegrityCheckLevel); - Pfs Pfs = new Pfs(PfsStream); - IFileSystem NcaFileSystem = new IFileSystem(NcaPath, new PFsProvider(Pfs)); + Stream pfsStream = nca.OpenSection(pfsSection.SectionNum, false, context.Device.System.FsIntegrityCheckLevel); + Pfs pfs = new Pfs(pfsStream); + IFileSystem ncaFileSystem = new IFileSystem(ncaPath, new PFsProvider(pfs)); - MakeObject(Context, NcaFileSystem); + MakeObject(context, ncaFileSystem); } else { @@ -285,38 +285,38 @@ namespace Ryujinx.HLE.HOS.Services.FspSrv return 0; } - private long OpenFileSystemFromInternalFile(ServiceCtx Context, string FullPath) + private long OpenFileSystemFromInternalFile(ServiceCtx context, string fullPath) { - DirectoryInfo ArchivePath = new DirectoryInfo(FullPath).Parent; + DirectoryInfo archivePath = new DirectoryInfo(fullPath).Parent; - while (string.IsNullOrWhiteSpace(ArchivePath.Extension)) + while (string.IsNullOrWhiteSpace(archivePath.Extension)) { - ArchivePath = ArchivePath.Parent; + archivePath = archivePath.Parent; } - if (ArchivePath.Extension == ".nsp" && File.Exists(ArchivePath.FullName)) + if (archivePath.Extension == ".nsp" && File.Exists(archivePath.FullName)) { - FileStream PfsFile = new FileStream( - ArchivePath.FullName.TrimEnd(Path.DirectorySeparatorChar), + FileStream pfsFile = new FileStream( + archivePath.FullName.TrimEnd(Path.DirectorySeparatorChar), FileMode.Open, FileAccess.Read); - Pfs Nsp = new Pfs(PfsFile); - PfsFileEntry TicketFile = Nsp.Files.FirstOrDefault(x => x.Name.EndsWith(".tik")); + Pfs nsp = new Pfs(pfsFile); + PfsFileEntry ticketFile = nsp.Files.FirstOrDefault(x => x.Name.EndsWith(".tik")); - if (TicketFile != null) + if (ticketFile != null) { - Ticket Ticket = new Ticket(Nsp.OpenFile(TicketFile)); + Ticket ticket = new Ticket(nsp.OpenFile(ticketFile)); - Context.Device.System.KeySet.TitleKeys[Ticket.RightsId] = - Ticket.GetTitleKey(Context.Device.System.KeySet); + context.Device.System.KeySet.TitleKeys[ticket.RightsId] = + ticket.GetTitleKey(context.Device.System.KeySet); } - string Filename = FullPath.Replace(ArchivePath.FullName, string.Empty).TrimStart('\\'); + string filename = fullPath.Replace(archivePath.FullName, string.Empty).TrimStart('\\'); - if (Nsp.FileExists(Filename)) + if (nsp.FileExists(filename)) { - return OpenNcaFs(Context, FullPath, Nsp.OpenFile(Filename)); + return OpenNcaFs(context, fullPath, nsp.OpenFile(filename)); } } diff --git a/Ryujinx.HLE/HOS/Services/FspSrv/IStorage.cs b/Ryujinx.HLE/HOS/Services/FspSrv/IStorage.cs index 6a78cdfe..d000635d 100644 --- a/Ryujinx.HLE/HOS/Services/FspSrv/IStorage.cs +++ b/Ryujinx.HLE/HOS/Services/FspSrv/IStorage.cs @@ -6,47 +6,47 @@ namespace Ryujinx.HLE.HOS.Services.FspSrv { class IStorage : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - private Stream BaseStream; + private Stream _baseStream; - public IStorage(Stream BaseStream) + public IStorage(Stream baseStream) { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, Read } }; - this.BaseStream = BaseStream; + _baseStream = baseStream; } // Read(u64 offset, u64 length) -> buffer buffer - public long Read(ServiceCtx Context) + public long Read(ServiceCtx context) { - long Offset = Context.RequestData.ReadInt64(); - long Size = Context.RequestData.ReadInt64(); + long offset = context.RequestData.ReadInt64(); + long size = context.RequestData.ReadInt64(); - if (Context.Request.ReceiveBuff.Count > 0) + if (context.Request.ReceiveBuff.Count > 0) { - IpcBuffDesc BuffDesc = Context.Request.ReceiveBuff[0]; + IpcBuffDesc buffDesc = context.Request.ReceiveBuff[0]; //Use smaller length to avoid overflows. - if (Size > BuffDesc.Size) + if (size > buffDesc.Size) { - Size = BuffDesc.Size; + size = buffDesc.Size; } - byte[] Data = new byte[Size]; + byte[] data = new byte[size]; - lock (BaseStream) + lock (_baseStream) { - BaseStream.Seek(Offset, SeekOrigin.Begin); - BaseStream.Read(Data, 0, Data.Length); + _baseStream.Seek(offset, SeekOrigin.Begin); + _baseStream.Read(data, 0, data.Length); } - Context.Memory.WriteBytes(BuffDesc.Position, Data); + context.Memory.WriteBytes(buffDesc.Position, data); } return 0; diff --git a/Ryujinx.HLE/HOS/Services/Hid/HidNpad.cs b/Ryujinx.HLE/HOS/Services/Hid/HidNpad.cs index d2731857..14bff315 100644 --- a/Ryujinx.HLE/HOS/Services/Hid/HidNpad.cs +++ b/Ryujinx.HLE/HOS/Services/Hid/HidNpad.cs @@ -5,26 +5,26 @@ namespace Ryujinx.HLE.HOS.Services.Hid public enum HidNpadJoyAssignmentMode { Dual, - Single, + Single } public enum HidNpadHandheldActivationMode { Dual, Single, - None, + None } public enum HidNpadJoyDeviceType { Left, - Right, + Right } public enum HidNpadJoyHoldType { Vertical, - Horizontal, + Horizontal } [Flags] @@ -36,6 +36,6 @@ namespace Ryujinx.HLE.HOS.Services.Hid Dual = 1 << 2, Left = 1 << 3, Right = 1 << 4, - Invalid = 1 << 5, + Invalid = 1 << 5 } } diff --git a/Ryujinx.HLE/HOS/Services/Hid/HidVibration.cs b/Ryujinx.HLE/HOS/Services/Hid/HidVibration.cs index cb2427e7..9a22ff01 100644 --- a/Ryujinx.HLE/HOS/Services/Hid/HidVibration.cs +++ b/Ryujinx.HLE/HOS/Services/Hid/HidVibration.cs @@ -10,7 +10,7 @@ { None, Left, - Right, + Right } public struct HidVibrationDeviceValue diff --git a/Ryujinx.HLE/HOS/Services/Hid/IActiveVibrationDeviceList.cs b/Ryujinx.HLE/HOS/Services/Hid/IActiveVibrationDeviceList.cs index 6e666919..586b852d 100644 --- a/Ryujinx.HLE/HOS/Services/Hid/IActiveVibrationDeviceList.cs +++ b/Ryujinx.HLE/HOS/Services/Hid/IActiveVibrationDeviceList.cs @@ -5,21 +5,21 @@ namespace Ryujinx.HLE.HOS.Services.Hid { class IActiveApplicationDeviceList : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IActiveApplicationDeviceList() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, ActivateVibrationDevice } }; } - public long ActivateVibrationDevice(ServiceCtx Context) + public long ActivateVibrationDevice(ServiceCtx context) { - int VibrationDeviceHandle = Context.RequestData.ReadInt32(); + int vibrationDeviceHandle = context.RequestData.ReadInt32(); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Hid/IAppletResource.cs b/Ryujinx.HLE/HOS/Services/Hid/IAppletResource.cs index 89a17acf..e82b824e 100644 --- a/Ryujinx.HLE/HOS/Services/Hid/IAppletResource.cs +++ b/Ryujinx.HLE/HOS/Services/Hid/IAppletResource.cs @@ -7,30 +7,30 @@ namespace Ryujinx.HLE.HOS.Services.Hid { class IAppletResource : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - private KSharedMemory HidSharedMem; + private KSharedMemory _hidSharedMem; - public IAppletResource(KSharedMemory HidSharedMem) + public IAppletResource(KSharedMemory hidSharedMem) { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, GetSharedMemoryHandle } }; - this.HidSharedMem = HidSharedMem; + _hidSharedMem = hidSharedMem; } - public long GetSharedMemoryHandle(ServiceCtx Context) + public long GetSharedMemoryHandle(ServiceCtx context) { - if (Context.Process.HandleTable.GenerateHandle(HidSharedMem, out int Handle) != KernelResult.Success) + if (context.Process.HandleTable.GenerateHandle(_hidSharedMem, out int handle) != KernelResult.Success) { throw new InvalidOperationException("Out of handles!"); } - Context.Response.HandleDesc = IpcHandleDesc.MakeCopy(Handle); + context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Hid/IHidServer.cs b/Ryujinx.HLE/HOS/Services/Hid/IHidServer.cs index 1af734ff..4e14943b 100644 --- a/Ryujinx.HLE/HOS/Services/Hid/IHidServer.cs +++ b/Ryujinx.HLE/HOS/Services/Hid/IHidServer.cs @@ -9,39 +9,39 @@ namespace Ryujinx.HLE.HOS.Services.Hid { class IHidServer : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - private KEvent NpadStyleSetUpdateEvent; - private KEvent XpadIdEvent; - private KEvent PalmaOperationCompleteEvent; + private KEvent _npadStyleSetUpdateEvent; + private KEvent _xpadIdEvent; + private KEvent _palmaOperationCompleteEvent; - private int XpadIdEventHandle; + private int _xpadIdEventHandle; - private bool SixAxisSensorFusionEnabled; - private bool UnintendedHomeButtonInputProtectionEnabled; - private bool VibrationPermitted; - private bool UsbFullKeyControllerEnabled; + private bool _sixAxisSensorFusionEnabled; + private bool _unintendedHomeButtonInputProtectionEnabled; + private bool _vibrationPermitted; + private bool _usbFullKeyControllerEnabled; - private HidNpadJoyHoldType NpadJoyHoldType; - private HidNpadStyle NpadStyleSet; - private HidNpadJoyAssignmentMode NpadJoyAssignmentMode; - private HidNpadHandheldActivationMode NpadHandheldActivationMode; - private HidGyroscopeZeroDriftMode GyroscopeZeroDriftMode; + private HidNpadJoyHoldType _npadJoyHoldType; + private HidNpadStyle _npadStyleSet; + private HidNpadJoyAssignmentMode _npadJoyAssignmentMode; + private HidNpadHandheldActivationMode _npadHandheldActivationMode; + private HidGyroscopeZeroDriftMode _gyroscopeZeroDriftMode; - private long NpadCommunicationMode; - private uint AccelerometerPlayMode; - private long VibrationGcErmCommand; - private float SevenSixAxisSensorFusionStrength; + private long _npadCommunicationMode; + private uint _accelerometerPlayMode; + private long _vibrationGcErmCommand; + private float _sevenSixAxisSensorFusionStrength; - private HidSensorFusionParameters SensorFusionParams; - private HidAccelerometerParameters AccelerometerParams; - private HidVibrationValue VibrationValue; + private HidSensorFusionParameters _sensorFusionParams; + private HidAccelerometerParameters _accelerometerParams; + private HidVibrationValue _vibrationValue; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - public IHidServer(Horizon System) + public IHidServer(Horizon system) { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, CreateAppletResource }, { 1, ActivateDebugPad }, @@ -145,123 +145,123 @@ namespace Ryujinx.HLE.HOS.Services.Hid { 512, ReadPalmaUniqueCode }, { 513, SetPalmaUniqueCodeInvalid }, { 1000, SetNpadCommunicationMode }, - { 1001, GetNpadCommunicationMode }, + { 1001, GetNpadCommunicationMode } }; - NpadStyleSetUpdateEvent = new KEvent(System); - XpadIdEvent = new KEvent(System); - PalmaOperationCompleteEvent = new KEvent(System); + _npadStyleSetUpdateEvent = new KEvent(system); + _xpadIdEvent = new KEvent(system); + _palmaOperationCompleteEvent = new KEvent(system); - NpadJoyHoldType = HidNpadJoyHoldType.Vertical; - NpadStyleSet = HidNpadStyle.FullKey | HidNpadStyle.Dual | HidNpadStyle.Left | HidNpadStyle.Right | HidNpadStyle.Handheld; - NpadJoyAssignmentMode = HidNpadJoyAssignmentMode.Dual; - NpadHandheldActivationMode = HidNpadHandheldActivationMode.Dual; - GyroscopeZeroDriftMode = HidGyroscopeZeroDriftMode.Standard; + _npadJoyHoldType = HidNpadJoyHoldType.Vertical; + _npadStyleSet = HidNpadStyle.FullKey | HidNpadStyle.Dual | HidNpadStyle.Left | HidNpadStyle.Right | HidNpadStyle.Handheld; + _npadJoyAssignmentMode = HidNpadJoyAssignmentMode.Dual; + _npadHandheldActivationMode = HidNpadHandheldActivationMode.Dual; + _gyroscopeZeroDriftMode = HidGyroscopeZeroDriftMode.Standard; - SensorFusionParams = new HidSensorFusionParameters(); - AccelerometerParams = new HidAccelerometerParameters(); - VibrationValue = new HidVibrationValue(); + _sensorFusionParams = new HidSensorFusionParameters(); + _accelerometerParams = new HidAccelerometerParameters(); + _vibrationValue = new HidVibrationValue(); // TODO: signal event at right place - XpadIdEvent.ReadableEvent.Signal(); + _xpadIdEvent.ReadableEvent.Signal(); } // CreateAppletResource(nn::applet::AppletResourceUserId) -> object - public long CreateAppletResource(ServiceCtx Context) + public long CreateAppletResource(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); - MakeObject(Context, new IAppletResource(Context.Device.System.HidSharedMem)); + MakeObject(context, new IAppletResource(context.Device.System.HidSharedMem)); return 0; } // ActivateDebugPad(nn::applet::AppletResourceUserId) - public long ActivateDebugPad(ServiceCtx Context) + public long ActivateDebugPad(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId}"); return 0; } // ActivateTouchScreen(nn::applet::AppletResourceUserId) - public long ActivateTouchScreen(ServiceCtx Context) + public long ActivateTouchScreen(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId}"); return 0; } // ActivateMouse(nn::applet::AppletResourceUserId) - public long ActivateMouse(ServiceCtx Context) + public long ActivateMouse(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId}"); return 0; } // ActivateKeyboard(nn::applet::AppletResourceUserId) - public long ActivateKeyboard(ServiceCtx Context) + public long ActivateKeyboard(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId}"); return 0; } // AcquireXpadIdEventHandle(ulong XpadId) -> nn::sf::NativeHandle - public long AcquireXpadIdEventHandle(ServiceCtx Context) + public long AcquireXpadIdEventHandle(ServiceCtx context) { - long XpadId = Context.RequestData.ReadInt64(); + long xpadId = context.RequestData.ReadInt64(); - if (Context.Process.HandleTable.GenerateHandle(XpadIdEvent.ReadableEvent, out XpadIdEventHandle) != KernelResult.Success) + if (context.Process.HandleTable.GenerateHandle(_xpadIdEvent.ReadableEvent, out _xpadIdEventHandle) != KernelResult.Success) { throw new InvalidOperationException("Out of handles!"); } - Context.Response.HandleDesc = IpcHandleDesc.MakeCopy(XpadIdEventHandle); + context.Response.HandleDesc = IpcHandleDesc.MakeCopy(_xpadIdEventHandle); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. XpadId: {XpadId}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. XpadId: {xpadId}"); return 0; } // ReleaseXpadIdEventHandle(ulong XpadId) - public long ReleaseXpadIdEventHandle(ServiceCtx Context) + public long ReleaseXpadIdEventHandle(ServiceCtx context) { - long XpadId = Context.RequestData.ReadInt64(); + long xpadId = context.RequestData.ReadInt64(); - Context.Process.HandleTable.CloseHandle(XpadIdEventHandle); + context.Process.HandleTable.CloseHandle(_xpadIdEventHandle); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. XpadId: {XpadId}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. XpadId: {xpadId}"); return 0; } // ActivateXpad(nn::hid::BasicXpadId, nn::applet::AppletResourceUserId) - public long ActivateXpad(ServiceCtx Context) + public long ActivateXpad(ServiceCtx context) { - int BasicXpadId = Context.RequestData.ReadInt32(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + int basicXpadId = context.RequestData.ReadInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"BasicXpadId: {BasicXpadId}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"BasicXpadId: {basicXpadId}"); return 0; } // GetXpadIds() -> long IdsCount, buffer, type: 0xa> - public long GetXpadIds(ServiceCtx Context) + public long GetXpadIds(ServiceCtx context) { // There is any Xpad, so we return 0 and write nothing inside the type-0xa buffer. - Context.ResponseData.Write(0L); + context.ResponseData.Write(0L); Logger.PrintStub(LogClass.ServiceHid, $"Stubbed."); @@ -269,34 +269,34 @@ namespace Ryujinx.HLE.HOS.Services.Hid } // ActivateJoyXpad(nn::hid::JoyXpadId) - public long ActivateJoyXpad(ServiceCtx Context) + public long ActivateJoyXpad(ServiceCtx context) { - int JoyXpadId = Context.RequestData.ReadInt32(); + int joyXpadId = context.RequestData.ReadInt32(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. JoyXpadId: {JoyXpadId}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. JoyXpadId: {joyXpadId}"); return 0; } // GetJoyXpadLifoHandle(nn::hid::JoyXpadId) -> nn::sf::NativeHandle - public long GetJoyXpadLifoHandle(ServiceCtx Context) + public long GetJoyXpadLifoHandle(ServiceCtx context) { - int JoyXpadId = Context.RequestData.ReadInt32(); + int joyXpadId = context.RequestData.ReadInt32(); - int Handle = 0; + int handle = 0; - Context.Response.HandleDesc = IpcHandleDesc.MakeCopy(Handle); + context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. JoyXpadId: {JoyXpadId}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. JoyXpadId: {joyXpadId}"); return 0; } // GetJoyXpadIds() -> long IdsCount, buffer, type: 0xa> - public long GetJoyXpadIds(ServiceCtx Context) + public long GetJoyXpadIds(ServiceCtx context) { // There is any JoyXpad, so we return 0 and write nothing inside the type-0xa buffer. - Context.ResponseData.Write(0L); + context.ResponseData.Write(0L); Logger.PrintStub(LogClass.ServiceHid, $"Stubbed."); @@ -304,662 +304,662 @@ namespace Ryujinx.HLE.HOS.Services.Hid } // ActivateSixAxisSensor(nn::hid::BasicXpadId) - public long ActivateSixAxisSensor(ServiceCtx Context) + public long ActivateSixAxisSensor(ServiceCtx context) { - int BasicXpadId = Context.RequestData.ReadInt32(); + int basicXpadId = context.RequestData.ReadInt32(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. BasicXpadId: {BasicXpadId}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. BasicXpadId: {basicXpadId}"); return 0; } // DeactivateSixAxisSensor(nn::hid::BasicXpadId) - public long DeactivateSixAxisSensor(ServiceCtx Context) + public long DeactivateSixAxisSensor(ServiceCtx context) { - int BasicXpadId = Context.RequestData.ReadInt32(); + int basicXpadId = context.RequestData.ReadInt32(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. BasicXpadId: {BasicXpadId}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. BasicXpadId: {basicXpadId}"); return 0; } // GetSixAxisSensorLifoHandle(nn::hid::BasicXpadId) -> nn::sf::NativeHandle - public long GetSixAxisSensorLifoHandle(ServiceCtx Context) + public long GetSixAxisSensorLifoHandle(ServiceCtx context) { - int BasicXpadId = Context.RequestData.ReadInt32(); + int basicXpadId = context.RequestData.ReadInt32(); - int Handle = 0; + int handle = 0; - Context.Response.HandleDesc = IpcHandleDesc.MakeCopy(Handle); + context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. BasicXpadId: {BasicXpadId}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. BasicXpadId: {basicXpadId}"); return 0; } // ActivateJoySixAxisSensor(nn::hid::JoyXpadId) - public long ActivateJoySixAxisSensor(ServiceCtx Context) + public long ActivateJoySixAxisSensor(ServiceCtx context) { - int JoyXpadId = Context.RequestData.ReadInt32(); + int joyXpadId = context.RequestData.ReadInt32(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. JoyXpadId: {JoyXpadId}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. JoyXpadId: {joyXpadId}"); return 0; } // DeactivateJoySixAxisSensor(nn::hid::JoyXpadId) - public long DeactivateJoySixAxisSensor(ServiceCtx Context) + public long DeactivateJoySixAxisSensor(ServiceCtx context) { - int JoyXpadId = Context.RequestData.ReadInt32(); + int joyXpadId = context.RequestData.ReadInt32(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. JoyXpadId: {JoyXpadId}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. JoyXpadId: {joyXpadId}"); return 0; } // GetJoySixAxisSensorLifoHandle(nn::hid::JoyXpadId) -> nn::sf::NativeHandle - public long GetJoySixAxisSensorLifoHandle(ServiceCtx Context) + public long GetJoySixAxisSensorLifoHandle(ServiceCtx context) { - int JoyXpadId = Context.RequestData.ReadInt32(); + int joyXpadId = context.RequestData.ReadInt32(); - int Handle = 0; + int handle = 0; - Context.Response.HandleDesc = IpcHandleDesc.MakeCopy(Handle); + context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. JoyXpadId: {JoyXpadId}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. JoyXpadId: {joyXpadId}"); return 0; } // StartSixAxisSensor(nn::hid::SixAxisSensorHandle, nn::applet::AppletResourceUserId) - public long StartSixAxisSensor(ServiceCtx Context) + public long StartSixAxisSensor(ServiceCtx context) { - int SixAxisSensorHandle = Context.RequestData.ReadInt32(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + int sixAxisSensorHandle = context.RequestData.ReadInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"SixAxisSensorHandle: {SixAxisSensorHandle}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"SixAxisSensorHandle: {sixAxisSensorHandle}"); return 0; } // StopSixAxisSensor(nn::hid::SixAxisSensorHandle, nn::applet::AppletResourceUserId) - public long StopSixAxisSensor(ServiceCtx Context) + public long StopSixAxisSensor(ServiceCtx context) { - int SixAxisSensorHandle = Context.RequestData.ReadInt32(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + int sixAxisSensorHandle = context.RequestData.ReadInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"SixAxisSensorHandle: {SixAxisSensorHandle}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"SixAxisSensorHandle: {sixAxisSensorHandle}"); return 0; } // IsSixAxisSensorFusionEnabled(nn::hid::SixAxisSensorHandle, nn::applet::AppletResourceUserId) -> bool IsEnabled - public long IsSixAxisSensorFusionEnabled(ServiceCtx Context) + public long IsSixAxisSensorFusionEnabled(ServiceCtx context) { - int SixAxisSensorHandle = Context.RequestData.ReadInt32(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + int sixAxisSensorHandle = context.RequestData.ReadInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Context.ResponseData.Write(SixAxisSensorFusionEnabled); + context.ResponseData.Write(_sixAxisSensorFusionEnabled); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"SixAxisSensorHandle: {SixAxisSensorHandle} - " + - $"SixAxisSensorFusionEnabled: {SixAxisSensorFusionEnabled}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"SixAxisSensorHandle: {sixAxisSensorHandle} - " + + $"SixAxisSensorFusionEnabled: {_sixAxisSensorFusionEnabled}"); return 0; } // EnableSixAxisSensorFusion(bool Enabled, nn::hid::SixAxisSensorHandle, nn::applet::AppletResourceUserId) - public long EnableSixAxisSensorFusion(ServiceCtx Context) + public long EnableSixAxisSensorFusion(ServiceCtx context) { - SixAxisSensorFusionEnabled = Context.RequestData.ReadBoolean(); - int SixAxisSensorHandle = Context.RequestData.ReadInt32(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + _sixAxisSensorFusionEnabled = context.RequestData.ReadBoolean(); + int sixAxisSensorHandle = context.RequestData.ReadInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"SixAxisSensorHandle: {SixAxisSensorHandle} - " + - $"SixAxisSensorFusionEnabled: {SixAxisSensorFusionEnabled}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"SixAxisSensorHandle: {sixAxisSensorHandle} - " + + $"SixAxisSensorFusionEnabled: {_sixAxisSensorFusionEnabled}"); return 0; } // SetSixAxisSensorFusionParameters(nn::hid::SixAxisSensorHandle, float RevisePower, float ReviseRange, nn::applet::AppletResourceUserId) - public long SetSixAxisSensorFusionParameters(ServiceCtx Context) + public long SetSixAxisSensorFusionParameters(ServiceCtx context) { - int SixAxisSensorHandle = Context.RequestData.ReadInt32(); + int sixAxisSensorHandle = context.RequestData.ReadInt32(); - SensorFusionParams = new HidSensorFusionParameters() + _sensorFusionParams = new HidSensorFusionParameters { - RevisePower = Context.RequestData.ReadInt32(), - ReviseRange = Context.RequestData.ReadInt32(), + RevisePower = context.RequestData.ReadInt32(), + ReviseRange = context.RequestData.ReadInt32() }; - long AppletResourceUserId = Context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"SixAxisSensorHandle: {SixAxisSensorHandle} - " + - $"RevisePower: {SensorFusionParams.RevisePower} - " + - $"ReviseRange: {SensorFusionParams.ReviseRange}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"SixAxisSensorHandle: {sixAxisSensorHandle} - " + + $"RevisePower: {_sensorFusionParams.RevisePower} - " + + $"ReviseRange: {_sensorFusionParams.ReviseRange}"); return 0; } // GetSixAxisSensorFusionParameters(nn::hid::SixAxisSensorHandle, nn::applet::AppletResourceUserId) -> float RevisePower, float ReviseRange) - public long GetSixAxisSensorFusionParameters(ServiceCtx Context) + public long GetSixAxisSensorFusionParameters(ServiceCtx context) { - int SixAxisSensorHandle = Context.RequestData.ReadInt32(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + int sixAxisSensorHandle = context.RequestData.ReadInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Context.ResponseData.Write(SensorFusionParams.RevisePower); - Context.ResponseData.Write(SensorFusionParams.ReviseRange); + context.ResponseData.Write(_sensorFusionParams.RevisePower); + context.ResponseData.Write(_sensorFusionParams.ReviseRange); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"SixAxisSensorHandle: {SixAxisSensorHandle} - " + - $"RevisePower: {SensorFusionParams.RevisePower} - " + - $"ReviseRange: {SensorFusionParams.ReviseRange}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"SixAxisSensorHandle: {sixAxisSensorHandle} - " + + $"RevisePower: {_sensorFusionParams.RevisePower} - " + + $"ReviseRange: {_sensorFusionParams.ReviseRange}"); return 0; } // ResetSixAxisSensorFusionParameters(nn::hid::SixAxisSensorHandle, nn::applet::AppletResourceUserId) - public long ResetSixAxisSensorFusionParameters(ServiceCtx Context) + public long ResetSixAxisSensorFusionParameters(ServiceCtx context) { - int SixAxisSensorHandle = Context.RequestData.ReadInt32(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + int sixAxisSensorHandle = context.RequestData.ReadInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); - SensorFusionParams.RevisePower = 0; - SensorFusionParams.ReviseRange = 0; + _sensorFusionParams.RevisePower = 0; + _sensorFusionParams.ReviseRange = 0; - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"SixAxisSensorHandle: {SixAxisSensorHandle} - " + - $"RevisePower: {SensorFusionParams.RevisePower} - " + - $"ReviseRange: {SensorFusionParams.ReviseRange}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"SixAxisSensorHandle: {sixAxisSensorHandle} - " + + $"RevisePower: {_sensorFusionParams.RevisePower} - " + + $"ReviseRange: {_sensorFusionParams.ReviseRange}"); return 0; } // SetAccelerometerParameters(nn::hid::SixAxisSensorHandle, float X, float Y, nn::applet::AppletResourceUserId) - public long SetAccelerometerParameters(ServiceCtx Context) + public long SetAccelerometerParameters(ServiceCtx context) { - int SixAxisSensorHandle = Context.RequestData.ReadInt32(); + int sixAxisSensorHandle = context.RequestData.ReadInt32(); - AccelerometerParams = new HidAccelerometerParameters() + _accelerometerParams = new HidAccelerometerParameters { - X = Context.RequestData.ReadInt32(), - Y = Context.RequestData.ReadInt32(), + X = context.RequestData.ReadInt32(), + Y = context.RequestData.ReadInt32() }; - long AppletResourceUserId = Context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"SixAxisSensorHandle: {SixAxisSensorHandle} - " + - $"X: {AccelerometerParams.X} - " + - $"Y: {AccelerometerParams.Y}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"SixAxisSensorHandle: {sixAxisSensorHandle} - " + + $"X: {_accelerometerParams.X} - " + + $"Y: {_accelerometerParams.Y}"); return 0; } // GetAccelerometerParameters(nn::hid::SixAxisSensorHandle, nn::applet::AppletResourceUserId) -> float X, float Y - public long GetAccelerometerParameters(ServiceCtx Context) + public long GetAccelerometerParameters(ServiceCtx context) { - int SixAxisSensorHandle = Context.RequestData.ReadInt32(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + int sixAxisSensorHandle = context.RequestData.ReadInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Context.ResponseData.Write(AccelerometerParams.X); - Context.ResponseData.Write(AccelerometerParams.Y); + context.ResponseData.Write(_accelerometerParams.X); + context.ResponseData.Write(_accelerometerParams.Y); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"SixAxisSensorHandle: {SixAxisSensorHandle} - " + - $"X: {AccelerometerParams.X} - " + - $"Y: {AccelerometerParams.Y}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"SixAxisSensorHandle: {sixAxisSensorHandle} - " + + $"X: {_accelerometerParams.X} - " + + $"Y: {_accelerometerParams.Y}"); return 0; } // ResetAccelerometerParameters(nn::hid::SixAxisSensorHandle, nn::applet::AppletResourceUserId) - public long ResetAccelerometerParameters(ServiceCtx Context) + public long ResetAccelerometerParameters(ServiceCtx context) { - int SixAxisSensorHandle = Context.RequestData.ReadInt32(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + int sixAxisSensorHandle = context.RequestData.ReadInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); - AccelerometerParams.X = 0; - AccelerometerParams.Y = 0; + _accelerometerParams.X = 0; + _accelerometerParams.Y = 0; - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"SixAxisSensorHandle: {SixAxisSensorHandle} - " + - $"X: {AccelerometerParams.X} - " + - $"Y: {AccelerometerParams.Y}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"SixAxisSensorHandle: {sixAxisSensorHandle} - " + + $"X: {_accelerometerParams.X} - " + + $"Y: {_accelerometerParams.Y}"); return 0; } // SetAccelerometerPlayMode(nn::hid::SixAxisSensorHandle, uint PlayMode, nn::applet::AppletResourceUserId) - public long SetAccelerometerPlayMode(ServiceCtx Context) + public long SetAccelerometerPlayMode(ServiceCtx context) { - int SixAxisSensorHandle = Context.RequestData.ReadInt32(); - AccelerometerPlayMode = Context.RequestData.ReadUInt32(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + int sixAxisSensorHandle = context.RequestData.ReadInt32(); + _accelerometerPlayMode = context.RequestData.ReadUInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"SixAxisSensorHandle: {SixAxisSensorHandle} - " + - $"PlayMode: {AccelerometerPlayMode}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"SixAxisSensorHandle: {sixAxisSensorHandle} - " + + $"PlayMode: {_accelerometerPlayMode}"); return 0; } // GetAccelerometerPlayMode(nn::hid::SixAxisSensorHandle, nn::applet::AppletResourceUserId) -> uint PlayMode - public long GetAccelerometerPlayMode(ServiceCtx Context) + public long GetAccelerometerPlayMode(ServiceCtx context) { - int SixAxisSensorHandle = Context.RequestData.ReadInt32(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + int sixAxisSensorHandle = context.RequestData.ReadInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Context.ResponseData.Write(AccelerometerPlayMode); + context.ResponseData.Write(_accelerometerPlayMode); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"SixAxisSensorHandle: {SixAxisSensorHandle} - " + - $"PlayMode: {AccelerometerPlayMode}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"SixAxisSensorHandle: {sixAxisSensorHandle} - " + + $"PlayMode: {_accelerometerPlayMode}"); return 0; } // ResetAccelerometerPlayMode(nn::hid::SixAxisSensorHandle, nn::applet::AppletResourceUserId) - public long ResetAccelerometerPlayMode(ServiceCtx Context) + public long ResetAccelerometerPlayMode(ServiceCtx context) { - int SixAxisSensorHandle = Context.RequestData.ReadInt32(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + int sixAxisSensorHandle = context.RequestData.ReadInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); - AccelerometerPlayMode = 0; + _accelerometerPlayMode = 0; - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"SixAxisSensorHandle: {SixAxisSensorHandle} - " + - $"PlayMode: {AccelerometerPlayMode}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"SixAxisSensorHandle: {sixAxisSensorHandle} - " + + $"PlayMode: {_accelerometerPlayMode}"); return 0; } // SetGyroscopeZeroDriftMode(nn::hid::SixAxisSensorHandle, uint GyroscopeZeroDriftMode, nn::applet::AppletResourceUserId) - public long SetGyroscopeZeroDriftMode(ServiceCtx Context) + public long SetGyroscopeZeroDriftMode(ServiceCtx context) { - int SixAxisSensorHandle = Context.RequestData.ReadInt32(); - GyroscopeZeroDriftMode = (HidGyroscopeZeroDriftMode)Context.RequestData.ReadInt32(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + int sixAxisSensorHandle = context.RequestData.ReadInt32(); + _gyroscopeZeroDriftMode = (HidGyroscopeZeroDriftMode)context.RequestData.ReadInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"SixAxisSensorHandle: {SixAxisSensorHandle} - " + - $"GyroscopeZeroDriftMode: {GyroscopeZeroDriftMode}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"SixAxisSensorHandle: {sixAxisSensorHandle} - " + + $"GyroscopeZeroDriftMode: {_gyroscopeZeroDriftMode}"); return 0; } // GetGyroscopeZeroDriftMode(nn::applet::AppletResourceUserId, nn::hid::SixAxisSensorHandle) -> int GyroscopeZeroDriftMode - public long GetGyroscopeZeroDriftMode(ServiceCtx Context) + public long GetGyroscopeZeroDriftMode(ServiceCtx context) { - int SixAxisSensorHandle = Context.RequestData.ReadInt32(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + int sixAxisSensorHandle = context.RequestData.ReadInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Context.ResponseData.Write((int)GyroscopeZeroDriftMode); + context.ResponseData.Write((int)_gyroscopeZeroDriftMode); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"SixAxisSensorHandle: {SixAxisSensorHandle} - " + - $"GyroscopeZeroDriftMode: {GyroscopeZeroDriftMode}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"SixAxisSensorHandle: {sixAxisSensorHandle} - " + + $"GyroscopeZeroDriftMode: {_gyroscopeZeroDriftMode}"); return 0; } // ResetGyroscopeZeroDriftMode(nn::hid::SixAxisSensorHandle, nn::applet::AppletResourceUserId) - public long ResetGyroscopeZeroDriftMode(ServiceCtx Context) + public long ResetGyroscopeZeroDriftMode(ServiceCtx context) { - int SixAxisSensorHandle = Context.RequestData.ReadInt32(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + int sixAxisSensorHandle = context.RequestData.ReadInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); - GyroscopeZeroDriftMode = HidGyroscopeZeroDriftMode.Standard; + _gyroscopeZeroDriftMode = HidGyroscopeZeroDriftMode.Standard; - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"SixAxisSensorHandle: {SixAxisSensorHandle} - " + - $"GyroscopeZeroDriftMode: {GyroscopeZeroDriftMode}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"SixAxisSensorHandle: {sixAxisSensorHandle} - " + + $"GyroscopeZeroDriftMode: {_gyroscopeZeroDriftMode}"); return 0; } // IsSixAxisSensorAtRest(nn::hid::SixAxisSensorHandle, nn::applet::AppletResourceUserId) -> bool IsAsRest - public long IsSixAxisSensorAtRest(ServiceCtx Context) + public long IsSixAxisSensorAtRest(ServiceCtx context) { - int SixAxisSensorHandle = Context.RequestData.ReadInt32(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + int sixAxisSensorHandle = context.RequestData.ReadInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); - bool IsAtRest = true; + bool isAtRest = true; - Context.ResponseData.Write(IsAtRest); + context.ResponseData.Write(isAtRest); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"SixAxisSensorHandle: {SixAxisSensorHandle} - " + - $"IsAtRest: {IsAtRest}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"SixAxisSensorHandle: {sixAxisSensorHandle} - " + + $"IsAtRest: {isAtRest}"); return 0; } // ActivateGesture(nn::applet::AppletResourceUserId, int Unknown0) - public long ActivateGesture(ServiceCtx Context) + public long ActivateGesture(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); - int Unknown0 = Context.RequestData.ReadInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); + int unknown0 = context.RequestData.ReadInt32(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"Unknown0: {Unknown0}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"Unknown0: {unknown0}"); return 0; } // SetSupportedNpadStyleSet(nn::applet::AppletResourceUserId, nn::hid::NpadStyleTag) - public long SetSupportedNpadStyleSet(ServiceCtx Context) + public long SetSupportedNpadStyleSet(ServiceCtx context) { - NpadStyleSet = (HidNpadStyle)Context.RequestData.ReadInt32(); + _npadStyleSet = (HidNpadStyle)context.RequestData.ReadInt32(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"NpadStyleSet: {NpadStyleSet}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"NpadStyleSet: {_npadStyleSet}"); - NpadStyleSetUpdateEvent.ReadableEvent.Signal(); + _npadStyleSetUpdateEvent.ReadableEvent.Signal(); return 0; } // GetSupportedNpadStyleSet(nn::applet::AppletResourceUserId) -> uint nn::hid::NpadStyleTag - public long GetSupportedNpadStyleSet(ServiceCtx Context) + public long GetSupportedNpadStyleSet(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Context.ResponseData.Write((int)NpadStyleSet); + context.ResponseData.Write((int)_npadStyleSet); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"NpadStyleSet: {NpadStyleSet}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"NpadStyleSet: {_npadStyleSet}"); return 0; } // SetSupportedNpadIdType(nn::applet::AppletResourceUserId, array) - public long SetSupportedNpadIdType(ServiceCtx Context) + public long SetSupportedNpadIdType(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); - HidControllerId NpadIdType = (HidControllerId)Context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); + HidControllerId npadIdType = (HidControllerId)context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"NpadIdType: {NpadIdType}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"NpadIdType: {npadIdType}"); return 0; } // ActivateNpad(nn::applet::AppletResourceUserId) - public long ActivateNpad(ServiceCtx Context) + public long ActivateNpad(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId}"); return 0; } // DeactivateNpad(nn::applet::AppletResourceUserId) - public long DeactivateNpad(ServiceCtx Context) + public long DeactivateNpad(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId}"); return 0; } // AcquireNpadStyleSetUpdateEventHandle(nn::applet::AppletResourceUserId, uint, ulong) -> nn::sf::NativeHandle - public long AcquireNpadStyleSetUpdateEventHandle(ServiceCtx Context) + public long AcquireNpadStyleSetUpdateEventHandle(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); - int NpadId = Context.RequestData.ReadInt32(); - long NpadStyleSet = Context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); + int npadId = context.RequestData.ReadInt32(); + long npadStyleSet = context.RequestData.ReadInt64(); - if (Context.Process.HandleTable.GenerateHandle(NpadStyleSetUpdateEvent.ReadableEvent, out int Handle) != KernelResult.Success) + if (context.Process.HandleTable.GenerateHandle(_npadStyleSetUpdateEvent.ReadableEvent, out int handle) != KernelResult.Success) { throw new InvalidOperationException("Out of handles!"); } - Context.Response.HandleDesc = IpcHandleDesc.MakeCopy(Handle); + context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"NpadId: {NpadId} - " + - $"NpadStyleSet: {NpadStyleSet}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"NpadId: {npadId} - " + + $"NpadStyleSet: {npadStyleSet}"); return 0; } // DisconnectNpad(nn::applet::AppletResourceUserId, uint NpadIdType) - public long DisconnectNpad(ServiceCtx Context) + public long DisconnectNpad(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); - int NpadIdType = Context.RequestData.ReadInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); + int npadIdType = context.RequestData.ReadInt32(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"NpadIdType: {NpadIdType}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"NpadIdType: {npadIdType}"); return 0; } // GetPlayerLedPattern(uint NpadId) -> ulong LedPattern - public long GetPlayerLedPattern(ServiceCtx Context) + public long GetPlayerLedPattern(ServiceCtx context) { - int NpadId = Context.RequestData.ReadInt32(); + int npadId = context.RequestData.ReadInt32(); - long LedPattern = 0; + long ledPattern = 0; - Context.ResponseData.Write(LedPattern); + context.ResponseData.Write(ledPattern); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. NpadId: {NpadId} - Pattern: {LedPattern}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. NpadId: {npadId} - Pattern: {ledPattern}"); return 0; } // ActivateNpadWithRevision(nn::applet::AppletResourceUserId, int Unknown) - public long ActivateNpadWithRevision(ServiceCtx Context) + public long ActivateNpadWithRevision(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); - int Unknown = Context.RequestData.ReadInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); + int unknown = context.RequestData.ReadInt32(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - Unknown: {Unknown}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - Unknown: {unknown}"); return 0; } // SetNpadJoyHoldType(nn::applet::AppletResourceUserId, long NpadJoyHoldType) - public long SetNpadJoyHoldType(ServiceCtx Context) + public long SetNpadJoyHoldType(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); - NpadJoyHoldType = (HidNpadJoyHoldType)Context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); + _npadJoyHoldType = (HidNpadJoyHoldType)context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"NpadJoyHoldType: {NpadJoyHoldType}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"NpadJoyHoldType: {_npadJoyHoldType}"); return 0; } // GetNpadJoyHoldType(nn::applet::AppletResourceUserId) -> long NpadJoyHoldType - public long GetNpadJoyHoldType(ServiceCtx Context) + public long GetNpadJoyHoldType(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Context.ResponseData.Write((long)NpadJoyHoldType); + context.ResponseData.Write((long)_npadJoyHoldType); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"NpadJoyHoldTypeValue: {NpadJoyHoldType}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"NpadJoyHoldTypeValue: {_npadJoyHoldType}"); return 0; } // SetNpadJoyAssignmentModeSingleByDefault(uint HidControllerId, nn::applet::AppletResourceUserId) - public long SetNpadJoyAssignmentModeSingleByDefault(ServiceCtx Context) + public long SetNpadJoyAssignmentModeSingleByDefault(ServiceCtx context) { - HidControllerId HidControllerId = (HidControllerId)Context.RequestData.ReadInt32(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + HidControllerId hidControllerId = (HidControllerId)context.RequestData.ReadInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); - NpadJoyAssignmentMode = HidNpadJoyAssignmentMode.Single; + _npadJoyAssignmentMode = HidNpadJoyAssignmentMode.Single; - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"HidControllerId: {HidControllerId} - " + - $"NpadJoyAssignmentModeValue: {NpadJoyAssignmentMode}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"HidControllerId: {hidControllerId} - " + + $"NpadJoyAssignmentModeValue: {_npadJoyAssignmentMode}"); return 0; } // SetNpadJoyAssignmentModeSingle(uint HidControllerId, nn::applet::AppletResourceUserId, long HidNpadJoyDeviceType) - public long SetNpadJoyAssignmentModeSingle(ServiceCtx Context) + public long SetNpadJoyAssignmentModeSingle(ServiceCtx context) { - HidControllerId HidControllerId = (HidControllerId)Context.RequestData.ReadInt32(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); - HidNpadJoyDeviceType HidNpadJoyDeviceType = (HidNpadJoyDeviceType)Context.RequestData.ReadInt64(); + HidControllerId hidControllerId = (HidControllerId)context.RequestData.ReadInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); + HidNpadJoyDeviceType hidNpadJoyDeviceType = (HidNpadJoyDeviceType)context.RequestData.ReadInt64(); - NpadJoyAssignmentMode = HidNpadJoyAssignmentMode.Single; + _npadJoyAssignmentMode = HidNpadJoyAssignmentMode.Single; - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"HidControllerId: {HidControllerId} - " + - $"HidNpadJoyDeviceType: {HidNpadJoyDeviceType} - " + - $"NpadJoyAssignmentModeValue: {NpadJoyAssignmentMode}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"HidControllerId: {hidControllerId} - " + + $"HidNpadJoyDeviceType: {hidNpadJoyDeviceType} - " + + $"NpadJoyAssignmentModeValue: {_npadJoyAssignmentMode}"); return 0; } // SetNpadJoyAssignmentModeDual(uint HidControllerId, nn::applet::AppletResourceUserId) - public long SetNpadJoyAssignmentModeDual(ServiceCtx Context) + public long SetNpadJoyAssignmentModeDual(ServiceCtx context) { - HidControllerId HidControllerId = (HidControllerId)Context.RequestData.ReadInt32(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + HidControllerId hidControllerId = (HidControllerId)context.RequestData.ReadInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); - NpadJoyAssignmentMode = HidNpadJoyAssignmentMode.Dual; + _npadJoyAssignmentMode = HidNpadJoyAssignmentMode.Dual; - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"HidControllerId: {HidControllerId} - " + - $"NpadJoyAssignmentModeValue: {NpadJoyAssignmentMode}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"HidControllerId: {hidControllerId} - " + + $"NpadJoyAssignmentModeValue: {_npadJoyAssignmentMode}"); return 0; } // MergeSingleJoyAsDualJoy(uint SingleJoyId0, uint SingleJoyId1, nn::applet::AppletResourceUserId) - public long MergeSingleJoyAsDualJoy(ServiceCtx Context) + public long MergeSingleJoyAsDualJoy(ServiceCtx context) { - long SingleJoyId0 = Context.RequestData.ReadInt32(); - long SingleJoyId1 = Context.RequestData.ReadInt32(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + long singleJoyId0 = context.RequestData.ReadInt32(); + long singleJoyId1 = context.RequestData.ReadInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"SingleJoyId0: {SingleJoyId0} - " + - $"SingleJoyId1: {SingleJoyId1}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"SingleJoyId0: {singleJoyId0} - " + + $"SingleJoyId1: {singleJoyId1}"); return 0; } // StartLrAssignmentMode(nn::applet::AppletResourceUserId) - public long StartLrAssignmentMode(ServiceCtx Context) + public long StartLrAssignmentMode(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId}"); return 0; } // StopLrAssignmentMode(nn::applet::AppletResourceUserId) - public long StopLrAssignmentMode(ServiceCtx Context) + public long StopLrAssignmentMode(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId}"); return 0; } // SetNpadHandheldActivationMode(nn::applet::AppletResourceUserId, long HidNpadHandheldActivationMode) - public long SetNpadHandheldActivationMode(ServiceCtx Context) + public long SetNpadHandheldActivationMode(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); - NpadHandheldActivationMode = (HidNpadHandheldActivationMode)Context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); + _npadHandheldActivationMode = (HidNpadHandheldActivationMode)context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"NpadHandheldActivationMode: {NpadHandheldActivationMode}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"NpadHandheldActivationMode: {_npadHandheldActivationMode}"); return 0; } // GetNpadHandheldActivationMode(nn::applet::AppletResourceUserId) -> long HidNpadHandheldActivationMode - public long GetNpadHandheldActivationMode(ServiceCtx Context) + public long GetNpadHandheldActivationMode(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Context.ResponseData.Write((long)NpadHandheldActivationMode); + context.ResponseData.Write((long)_npadHandheldActivationMode); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"NpadHandheldActivationMode: {NpadHandheldActivationMode}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"NpadHandheldActivationMode: {_npadHandheldActivationMode}"); return 0; } // SwapNpadAssignment(uint OldNpadAssignment, uint NewNpadAssignment, nn::applet::AppletResourceUserId) - public long SwapNpadAssignment(ServiceCtx Context) + public long SwapNpadAssignment(ServiceCtx context) { - int OldNpadAssignment = Context.RequestData.ReadInt32(); - int NewNpadAssignment = Context.RequestData.ReadInt32(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + int oldNpadAssignment = context.RequestData.ReadInt32(); + int newNpadAssignment = context.RequestData.ReadInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"OldNpadAssignment: {OldNpadAssignment} - " + - $"NewNpadAssignment: {NewNpadAssignment}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"OldNpadAssignment: {oldNpadAssignment} - " + + $"NewNpadAssignment: {newNpadAssignment}"); return 0; } // IsUnintendedHomeButtonInputProtectionEnabled(uint Unknown0, nn::applet::AppletResourceUserId) -> bool IsEnabled - public long IsUnintendedHomeButtonInputProtectionEnabled(ServiceCtx Context) + public long IsUnintendedHomeButtonInputProtectionEnabled(ServiceCtx context) { - uint Unknown0 = Context.RequestData.ReadUInt32(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + uint unknown0 = context.RequestData.ReadUInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Context.ResponseData.Write(UnintendedHomeButtonInputProtectionEnabled); + context.ResponseData.Write(_unintendedHomeButtonInputProtectionEnabled); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"Unknown0: {Unknown0} - " + - $"UnintendedHomeButtonInputProtectionEnabled: {UnintendedHomeButtonInputProtectionEnabled}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"Unknown0: {unknown0} - " + + $"UnintendedHomeButtonInputProtectionEnabled: {_unintendedHomeButtonInputProtectionEnabled}"); return 0; } // EnableUnintendedHomeButtonInputProtection(bool Enable, uint Unknown0, nn::applet::AppletResourceUserId) - public long EnableUnintendedHomeButtonInputProtection(ServiceCtx Context) + public long EnableUnintendedHomeButtonInputProtection(ServiceCtx context) { - UnintendedHomeButtonInputProtectionEnabled = Context.RequestData.ReadBoolean(); - uint Unknown0 = Context.RequestData.ReadUInt32(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + _unintendedHomeButtonInputProtectionEnabled = context.RequestData.ReadBoolean(); + uint unknown0 = context.RequestData.ReadUInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"Unknown0: {Unknown0} - " + - $"UnintendedHomeButtonInputProtectionEnable: {UnintendedHomeButtonInputProtectionEnabled}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"Unknown0: {unknown0} - " + + $"UnintendedHomeButtonInputProtectionEnable: {_unintendedHomeButtonInputProtectionEnabled}"); return 0; } // SetNpadJoyAssignmentModeSingleWithDestination(uint HidControllerId, long HidNpadJoyDeviceType, nn::applet::AppletResourceUserId) -> bool Unknown0, uint Unknown1 - public long SetNpadJoyAssignmentModeSingleWithDestination(ServiceCtx Context) + public long SetNpadJoyAssignmentModeSingleWithDestination(ServiceCtx context) { - HidControllerId HidControllerId = (HidControllerId)Context.RequestData.ReadInt32(); - HidNpadJoyDeviceType HidNpadJoyDeviceType = (HidNpadJoyDeviceType)Context.RequestData.ReadInt64(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + HidControllerId hidControllerId = (HidControllerId)context.RequestData.ReadInt32(); + HidNpadJoyDeviceType hidNpadJoyDeviceType = (HidNpadJoyDeviceType)context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); - NpadJoyAssignmentMode = HidNpadJoyAssignmentMode.Single; + _npadJoyAssignmentMode = HidNpadJoyAssignmentMode.Single; - Context.ResponseData.Write(0); //Unknown0 - Context.ResponseData.Write(0); //Unknown1 + context.ResponseData.Write(0); //Unknown0 + context.ResponseData.Write(0); //Unknown1 - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"HidControllerId: {HidControllerId} - " + - $"HidNpadJoyDeviceType: {HidNpadJoyDeviceType} - " + - $"NpadJoyAssignmentModeValue: {NpadJoyAssignmentMode} - " + + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"HidControllerId: {hidControllerId} - " + + $"HidNpadJoyDeviceType: {hidNpadJoyDeviceType} - " + + $"NpadJoyAssignmentModeValue: {_npadJoyAssignmentMode} - " + $"Unknown0: 0 - " + $"Unknown1: 0"); @@ -967,163 +967,163 @@ namespace Ryujinx.HLE.HOS.Services.Hid } // GetVibrationDeviceInfo(nn::hid::VibrationDeviceHandle) -> nn::hid::VibrationDeviceInfo - public long GetVibrationDeviceInfo(ServiceCtx Context) + public long GetVibrationDeviceInfo(ServiceCtx context) { - int VibrationDeviceHandle = Context.RequestData.ReadInt32(); + int vibrationDeviceHandle = context.RequestData.ReadInt32(); - HidVibrationDeviceValue DeviceInfo = new HidVibrationDeviceValue + HidVibrationDeviceValue deviceInfo = new HidVibrationDeviceValue { DeviceType = HidVibrationDeviceType.None, Position = HidVibrationDevicePosition.None }; - Context.ResponseData.Write((int)DeviceInfo.DeviceType); - Context.ResponseData.Write((int)DeviceInfo.Position); + context.ResponseData.Write((int)deviceInfo.DeviceType); + context.ResponseData.Write((int)deviceInfo.Position); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. VibrationDeviceHandle: {VibrationDeviceHandle} - " + - $"DeviceType: {DeviceInfo.DeviceType} - " + - $"Position: {DeviceInfo.Position}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. VibrationDeviceHandle: {vibrationDeviceHandle} - " + + $"DeviceType: {deviceInfo.DeviceType} - " + + $"Position: {deviceInfo.Position}"); return 0; } // SendVibrationValue(nn::hid::VibrationDeviceHandle, nn::hid::VibrationValue, nn::applet::AppletResourceUserId) - public long SendVibrationValue(ServiceCtx Context) + public long SendVibrationValue(ServiceCtx context) { - int VibrationDeviceHandle = Context.RequestData.ReadInt32(); + int vibrationDeviceHandle = context.RequestData.ReadInt32(); - VibrationValue = new HidVibrationValue + _vibrationValue = new HidVibrationValue { - AmplitudeLow = Context.RequestData.ReadSingle(), - FrequencyLow = Context.RequestData.ReadSingle(), - AmplitudeHigh = Context.RequestData.ReadSingle(), - FrequencyHigh = Context.RequestData.ReadSingle() + AmplitudeLow = context.RequestData.ReadSingle(), + FrequencyLow = context.RequestData.ReadSingle(), + AmplitudeHigh = context.RequestData.ReadSingle(), + FrequencyHigh = context.RequestData.ReadSingle() }; - long AppletResourceUserId = Context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"VibrationDeviceHandle: {VibrationDeviceHandle} - " + - $"AmplitudeLow: {VibrationValue.AmplitudeLow} - " + - $"FrequencyLow: {VibrationValue.FrequencyLow} - " + - $"AmplitudeHigh: {VibrationValue.AmplitudeHigh} - " + - $"FrequencyHigh: {VibrationValue.FrequencyHigh}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"VibrationDeviceHandle: {vibrationDeviceHandle} - " + + $"AmplitudeLow: {_vibrationValue.AmplitudeLow} - " + + $"FrequencyLow: {_vibrationValue.FrequencyLow} - " + + $"AmplitudeHigh: {_vibrationValue.AmplitudeHigh} - " + + $"FrequencyHigh: {_vibrationValue.FrequencyHigh}"); return 0; } // GetActualVibrationValue(nn::hid::VibrationDeviceHandle, nn::applet::AppletResourceUserId) -> nn::hid::VibrationValue - public long GetActualVibrationValue(ServiceCtx Context) + public long GetActualVibrationValue(ServiceCtx context) { - int VibrationDeviceHandle = Context.RequestData.ReadInt32(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + int vibrationDeviceHandle = context.RequestData.ReadInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Context.ResponseData.Write(VibrationValue.AmplitudeLow); - Context.ResponseData.Write(VibrationValue.FrequencyLow); - Context.ResponseData.Write(VibrationValue.AmplitudeHigh); - Context.ResponseData.Write(VibrationValue.FrequencyHigh); + context.ResponseData.Write(_vibrationValue.AmplitudeLow); + context.ResponseData.Write(_vibrationValue.FrequencyLow); + context.ResponseData.Write(_vibrationValue.AmplitudeHigh); + context.ResponseData.Write(_vibrationValue.FrequencyHigh); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"VibrationDeviceHandle: {VibrationDeviceHandle} - " + - $"AmplitudeLow: {VibrationValue.AmplitudeLow} - " + - $"FrequencyLow: {VibrationValue.FrequencyLow} - " + - $"AmplitudeHigh: {VibrationValue.AmplitudeHigh} - " + - $"FrequencyHigh: {VibrationValue.FrequencyHigh}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"VibrationDeviceHandle: {vibrationDeviceHandle} - " + + $"AmplitudeLow: {_vibrationValue.AmplitudeLow} - " + + $"FrequencyLow: {_vibrationValue.FrequencyLow} - " + + $"AmplitudeHigh: {_vibrationValue.AmplitudeHigh} - " + + $"FrequencyHigh: {_vibrationValue.FrequencyHigh}"); return 0; } // CreateActiveVibrationDeviceList() -> object - public long CreateActiveVibrationDeviceList(ServiceCtx Context) + public long CreateActiveVibrationDeviceList(ServiceCtx context) { - MakeObject(Context, new IActiveApplicationDeviceList()); + MakeObject(context, new IActiveApplicationDeviceList()); return 0; } // PermitVibration(bool Enable) - public long PermitVibration(ServiceCtx Context) + public long PermitVibration(ServiceCtx context) { - VibrationPermitted = Context.RequestData.ReadBoolean(); + _vibrationPermitted = context.RequestData.ReadBoolean(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. VibrationPermitted: {VibrationPermitted}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. VibrationPermitted: {_vibrationPermitted}"); return 0; } // IsVibrationPermitted() -> bool IsEnabled - public long IsVibrationPermitted(ServiceCtx Context) + public long IsVibrationPermitted(ServiceCtx context) { - Context.ResponseData.Write(VibrationPermitted); + context.ResponseData.Write(_vibrationPermitted); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. VibrationPermitted: {VibrationPermitted}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. VibrationPermitted: {_vibrationPermitted}"); return 0; } // SendVibrationValues(nn::applet::AppletResourceUserId, buffer, type: 9>, buffer, type: 9>) - public long SendVibrationValues(ServiceCtx Context) + public long SendVibrationValues(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); - byte[] VibrationDeviceHandleBuffer = Context.Memory.ReadBytes( - Context.Request.PtrBuff[0].Position, - Context.Request.PtrBuff[0].Size); + byte[] vibrationDeviceHandleBuffer = context.Memory.ReadBytes( + context.Request.PtrBuff[0].Position, + context.Request.PtrBuff[0].Size); - byte[] VibrationValueBuffer = Context.Memory.ReadBytes( - Context.Request.PtrBuff[1].Position, - Context.Request.PtrBuff[1].Size); + byte[] vibrationValueBuffer = context.Memory.ReadBytes( + context.Request.PtrBuff[1].Position, + context.Request.PtrBuff[1].Size); //Todo: Read all handles and values from buffer. - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"VibrationDeviceHandleBufferLength: {VibrationDeviceHandleBuffer.Length} - " + - $"VibrationValueBufferLength: {VibrationValueBuffer.Length}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"VibrationDeviceHandleBufferLength: {vibrationDeviceHandleBuffer.Length} - " + + $"VibrationValueBufferLength: {vibrationValueBuffer.Length}"); return 0; } // SendVibrationGcErmCommand(nn::hid::VibrationDeviceHandle, nn::hid::VibrationGcErmCommand, nn::applet::AppletResourceUserId) - public long SendVibrationGcErmCommand(ServiceCtx Context) + public long SendVibrationGcErmCommand(ServiceCtx context) { - int VibrationDeviceHandle = Context.RequestData.ReadInt32(); - long VibrationGcErmCommand = Context.RequestData.ReadInt64(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + int vibrationDeviceHandle = context.RequestData.ReadInt32(); + long vibrationGcErmCommand = context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"VibrationDeviceHandle: {VibrationDeviceHandle} - " + - $"VibrationGcErmCommand: {VibrationGcErmCommand}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"VibrationDeviceHandle: {vibrationDeviceHandle} - " + + $"VibrationGcErmCommand: {vibrationGcErmCommand}"); return 0; } // GetActualVibrationGcErmCommand(nn::hid::VibrationDeviceHandle, nn::applet::AppletResourceUserId) -> nn::hid::VibrationGcErmCommand - public long GetActualVibrationGcErmCommand(ServiceCtx Context) + public long GetActualVibrationGcErmCommand(ServiceCtx context) { - int VibrationDeviceHandle = Context.RequestData.ReadInt32(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + int vibrationDeviceHandle = context.RequestData.ReadInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Context.ResponseData.Write(VibrationGcErmCommand); + context.ResponseData.Write(_vibrationGcErmCommand); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"VibrationDeviceHandle: {VibrationDeviceHandle} - " + - $"VibrationGcErmCommand: {VibrationGcErmCommand}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"VibrationDeviceHandle: {vibrationDeviceHandle} - " + + $"VibrationGcErmCommand: {_vibrationGcErmCommand}"); return 0; } // BeginPermitVibrationSession(nn::applet::AppletResourceUserId) - public long BeginPermitVibrationSession(ServiceCtx Context) + public long BeginPermitVibrationSession(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId}"); return 0; } // EndPermitVibrationSession() - public long EndPermitVibrationSession(ServiceCtx Context) + public long EndPermitVibrationSession(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceHid, $"Stubbed."); @@ -1131,198 +1131,198 @@ namespace Ryujinx.HLE.HOS.Services.Hid } // ActivateConsoleSixAxisSensor(nn::applet::AppletResourceUserId) - public long ActivateConsoleSixAxisSensor(ServiceCtx Context) + public long ActivateConsoleSixAxisSensor(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId}"); return 0; } // StartConsoleSixAxisSensor(nn::hid::ConsoleSixAxisSensorHandle, nn::applet::AppletResourceUserId) - public long StartConsoleSixAxisSensor(ServiceCtx Context) + public long StartConsoleSixAxisSensor(ServiceCtx context) { - int ConsoleSixAxisSensorHandle = Context.RequestData.ReadInt32(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + int consoleSixAxisSensorHandle = context.RequestData.ReadInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"ConsoleSixAxisSensorHandle: {ConsoleSixAxisSensorHandle}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"ConsoleSixAxisSensorHandle: {consoleSixAxisSensorHandle}"); return 0; } // StopConsoleSixAxisSensor(nn::hid::ConsoleSixAxisSensorHandle, nn::applet::AppletResourceUserId) - public long StopConsoleSixAxisSensor(ServiceCtx Context) + public long StopConsoleSixAxisSensor(ServiceCtx context) { - int ConsoleSixAxisSensorHandle = Context.RequestData.ReadInt32(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + int consoleSixAxisSensorHandle = context.RequestData.ReadInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"ConsoleSixAxisSensorHandle: {ConsoleSixAxisSensorHandle}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"ConsoleSixAxisSensorHandle: {consoleSixAxisSensorHandle}"); return 0; } // ActivateSevenSixAxisSensor(nn::applet::AppletResourceUserId) - public long ActivateSevenSixAxisSensor(ServiceCtx Context) + public long ActivateSevenSixAxisSensor(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId}"); return 0; } // StartSevenSixAxisSensor(nn::applet::AppletResourceUserId) - public long StartSevenSixAxisSensor(ServiceCtx Context) + public long StartSevenSixAxisSensor(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId}"); return 0; } // StopSevenSixAxisSensor(nn::applet::AppletResourceUserId) - public long StopSevenSixAxisSensor(ServiceCtx Context) + public long StopSevenSixAxisSensor(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId}"); return 0; } // InitializeSevenSixAxisSensor(array, ulong Counter0, array, ulong Counter1, nn::applet::AppletResourceUserId) - public long InitializeSevenSixAxisSensor(ServiceCtx Context) + public long InitializeSevenSixAxisSensor(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); - long Counter0 = Context.RequestData.ReadInt64(); - long Counter1 = Context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); + long counter0 = context.RequestData.ReadInt64(); + long counter1 = context.RequestData.ReadInt64(); // Todo: Determine if array is a buffer or not... - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"Counter0: {Counter0} - " + - $"Counter1: {Counter1}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"Counter0: {counter0} - " + + $"Counter1: {counter1}"); return 0; } // FinalizeSevenSixAxisSensor(nn::applet::AppletResourceUserId) - public long FinalizeSevenSixAxisSensor(ServiceCtx Context) + public long FinalizeSevenSixAxisSensor(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); - - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId}"); + long appletResourceUserId = context.RequestData.ReadInt64(); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId}"); + return 0; } // SetSevenSixAxisSensorFusionStrength(float Strength, nn::applet::AppletResourceUserId) - public long SetSevenSixAxisSensorFusionStrength(ServiceCtx Context) + public long SetSevenSixAxisSensorFusionStrength(ServiceCtx context) { - SevenSixAxisSensorFusionStrength = Context.RequestData.ReadSingle(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + _sevenSixAxisSensorFusionStrength = context.RequestData.ReadSingle(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"SevenSixAxisSensorFusionStrength: {SevenSixAxisSensorFusionStrength}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"SevenSixAxisSensorFusionStrength: {_sevenSixAxisSensorFusionStrength}"); return 0; } // GetSevenSixAxisSensorFusionStrength(nn::applet::AppletResourceUserId) -> float Strength - public long GetSevenSixAxisSensorFusionStrength(ServiceCtx Context) + public long GetSevenSixAxisSensorFusionStrength(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Context.ResponseData.Write(SevenSixAxisSensorFusionStrength); + context.ResponseData.Write(_sevenSixAxisSensorFusionStrength); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"SevenSixAxisSensorFusionStrength: {SevenSixAxisSensorFusionStrength}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"SevenSixAxisSensorFusionStrength: {_sevenSixAxisSensorFusionStrength}"); return 0; } // IsUsbFullKeyControllerEnabled() -> bool IsEnabled - public long IsUsbFullKeyControllerEnabled(ServiceCtx Context) + public long IsUsbFullKeyControllerEnabled(ServiceCtx context) { - Context.ResponseData.Write(UsbFullKeyControllerEnabled); + context.ResponseData.Write(_usbFullKeyControllerEnabled); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. UsbFullKeyControllerEnabled: {UsbFullKeyControllerEnabled}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. UsbFullKeyControllerEnabled: {_usbFullKeyControllerEnabled}"); return 0; } // EnableUsbFullKeyController(bool Enable) - public long EnableUsbFullKeyController(ServiceCtx Context) + public long EnableUsbFullKeyController(ServiceCtx context) { - UsbFullKeyControllerEnabled = Context.RequestData.ReadBoolean(); + _usbFullKeyControllerEnabled = context.RequestData.ReadBoolean(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. UsbFullKeyControllerEnabled: {UsbFullKeyControllerEnabled}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. UsbFullKeyControllerEnabled: {_usbFullKeyControllerEnabled}"); return 0; } // IsUsbFullKeyControllerConnected(uint Unknown0) -> bool Connected - public long IsUsbFullKeyControllerConnected(ServiceCtx Context) + public long IsUsbFullKeyControllerConnected(ServiceCtx context) { - int Unknown0 = Context.RequestData.ReadInt32(); + int unknown0 = context.RequestData.ReadInt32(); - Context.ResponseData.Write(true); //FullKeyController is always connected ? + context.ResponseData.Write(true); //FullKeyController is always connected ? - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. Unknown0: {Unknown0} - Connected: true"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. Unknown0: {unknown0} - Connected: true"); return 0; } // HasBattery(uint NpadId) -> bool HasBattery - public long HasBattery(ServiceCtx Context) + public long HasBattery(ServiceCtx context) { - int NpadId = Context.RequestData.ReadInt32(); + int npadId = context.RequestData.ReadInt32(); - Context.ResponseData.Write(true); //Npad always got a battery ? + context.ResponseData.Write(true); //Npad always got a battery ? - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. NpadId: {NpadId} - HasBattery: true"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. NpadId: {npadId} - HasBattery: true"); return 0; } // HasLeftRightBattery(uint NpadId) -> bool HasLeftBattery, bool HasRightBattery - public long HasLeftRightBattery(ServiceCtx Context) + public long HasLeftRightBattery(ServiceCtx context) { - int NpadId = Context.RequestData.ReadInt32(); + int npadId = context.RequestData.ReadInt32(); - Context.ResponseData.Write(true); //Npad always got a left battery ? - Context.ResponseData.Write(true); //Npad always got a right battery ? + context.ResponseData.Write(true); //Npad always got a left battery ? + context.ResponseData.Write(true); //Npad always got a right battery ? - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. NpadId: {NpadId} - HasLeftBattery: true - HasRightBattery: true"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. NpadId: {npadId} - HasLeftBattery: true - HasRightBattery: true"); return 0; } // GetNpadInterfaceType(uint NpadId) -> uchar InterfaceType - public long GetNpadInterfaceType(ServiceCtx Context) + public long GetNpadInterfaceType(ServiceCtx context) { - int NpadId = Context.RequestData.ReadInt32(); + int npadId = context.RequestData.ReadInt32(); - Context.ResponseData.Write((byte)0); + context.ResponseData.Write((byte)0); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. NpadId: {NpadId} - NpadInterfaceType: 0"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. NpadId: {npadId} - NpadInterfaceType: 0"); return 0; } // GetNpadLeftRightInterfaceType(uint NpadId) -> uchar LeftInterfaceType, uchar RightInterfaceType - public long GetNpadLeftRightInterfaceType(ServiceCtx Context) + public long GetNpadLeftRightInterfaceType(ServiceCtx context) { - int NpadId = Context.RequestData.ReadInt32(); + int npadId = context.RequestData.ReadInt32(); - Context.ResponseData.Write((byte)0); - Context.ResponseData.Write((byte)0); + context.ResponseData.Write((byte)0); + context.ResponseData.Write((byte)0); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. NpadId: {NpadId} - " + + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. NpadId: {npadId} - " + $"LeftInterfaceType: 0 - " + $"RightInterfaceType: 0"); @@ -1330,211 +1330,211 @@ namespace Ryujinx.HLE.HOS.Services.Hid } // GetPalmaConnectionHandle(uint Unknown0, nn::applet::AppletResourceUserId) -> nn::hid::PalmaConnectionHandle - public long GetPalmaConnectionHandle(ServiceCtx Context) + public long GetPalmaConnectionHandle(ServiceCtx context) { - int Unknown0 = Context.RequestData.ReadInt32(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + int unknown0 = context.RequestData.ReadInt32(); + long appletResourceUserId = context.RequestData.ReadInt64(); - int PalmaConnectionHandle = 0; + int palmaConnectionHandle = 0; - Context.ResponseData.Write(PalmaConnectionHandle); + context.ResponseData.Write(palmaConnectionHandle); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"Unknown0: {Unknown0} - " + - $"PalmaConnectionHandle: {PalmaConnectionHandle}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"Unknown0: {unknown0} - " + + $"PalmaConnectionHandle: {palmaConnectionHandle}"); return 0; } // InitializePalma(nn::hid::PalmaConnectionHandle) - public long InitializePalma(ServiceCtx Context) + public long InitializePalma(ServiceCtx context) { - int PalmaConnectionHandle = Context.RequestData.ReadInt32(); + int palmaConnectionHandle = context.RequestData.ReadInt32(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. PalmaConnectionHandle: {PalmaConnectionHandle}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. PalmaConnectionHandle: {palmaConnectionHandle}"); - PalmaOperationCompleteEvent.ReadableEvent.Signal(); + _palmaOperationCompleteEvent.ReadableEvent.Signal(); return 0; } // AcquirePalmaOperationCompleteEvent(nn::hid::PalmaConnectionHandle) -> nn::sf::NativeHandle - public long AcquirePalmaOperationCompleteEvent(ServiceCtx Context) + public long AcquirePalmaOperationCompleteEvent(ServiceCtx context) { - int PalmaConnectionHandle = Context.RequestData.ReadInt32(); + int palmaConnectionHandle = context.RequestData.ReadInt32(); - if (Context.Process.HandleTable.GenerateHandle(PalmaOperationCompleteEvent.ReadableEvent, out int Handle) != KernelResult.Success) + if (context.Process.HandleTable.GenerateHandle(_palmaOperationCompleteEvent.ReadableEvent, out int handle) != KernelResult.Success) { throw new InvalidOperationException("Out of handles!"); } - Context.Response.HandleDesc = IpcHandleDesc.MakeCopy(Handle); + context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. PalmaConnectionHandle: {PalmaConnectionHandle}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. PalmaConnectionHandle: {palmaConnectionHandle}"); return 0; } // GetPalmaOperationInfo(nn::hid::PalmaConnectionHandle) -> long Unknown0, buffer - public long GetPalmaOperationInfo(ServiceCtx Context) + public long GetPalmaOperationInfo(ServiceCtx context) { - int PalmaConnectionHandle = Context.RequestData.ReadInt32(); + int palmaConnectionHandle = context.RequestData.ReadInt32(); - long Unknown0 = 0; //Counter? + long unknown0 = 0; //Counter? - Context.ResponseData.Write(Unknown0); + context.ResponseData.Write(unknown0); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. PalmaConnectionHandle: {PalmaConnectionHandle} - " + - $"Unknown0: {Unknown0}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. PalmaConnectionHandle: {palmaConnectionHandle} - " + + $"Unknown0: {unknown0}"); return 0; } // PlayPalmaActivity(nn::hid::PalmaConnectionHandle, ulong Unknown0) - public long PlayPalmaActivity(ServiceCtx Context) + public long PlayPalmaActivity(ServiceCtx context) { - int PalmaConnectionHandle = Context.RequestData.ReadInt32(); - long Unknown0 = Context.RequestData.ReadInt64(); + int palmaConnectionHandle = context.RequestData.ReadInt32(); + long unknown0 = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. PalmaConnectionHandle: {PalmaConnectionHandle} - " + - $"Unknown0: {Unknown0}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. PalmaConnectionHandle: {palmaConnectionHandle} - " + + $"Unknown0: {unknown0}"); - PalmaOperationCompleteEvent.ReadableEvent.Signal(); + _palmaOperationCompleteEvent.ReadableEvent.Signal(); return 0; } // SetPalmaFrModeType(nn::hid::PalmaConnectionHandle, ulong FrModeType) - public long SetPalmaFrModeType(ServiceCtx Context) + public long SetPalmaFrModeType(ServiceCtx context) { - int PalmaConnectionHandle = Context.RequestData.ReadInt32(); - long FrModeType = Context.RequestData.ReadInt64(); + int palmaConnectionHandle = context.RequestData.ReadInt32(); + long frModeType = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. PalmaConnectionHandle: {PalmaConnectionHandle} - " + - $"FrModeType: {FrModeType}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. PalmaConnectionHandle: {palmaConnectionHandle} - " + + $"FrModeType: {frModeType}"); - PalmaOperationCompleteEvent.ReadableEvent.Signal(); + _palmaOperationCompleteEvent.ReadableEvent.Signal(); return 0; } // ReadPalmaStep(nn::hid::PalmaConnectionHandle) - public long ReadPalmaStep(ServiceCtx Context) + public long ReadPalmaStep(ServiceCtx context) { - int PalmaConnectionHandle = Context.RequestData.ReadInt32(); + int palmaConnectionHandle = context.RequestData.ReadInt32(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. PalmaConnectionHandle: {PalmaConnectionHandle}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. PalmaConnectionHandle: {palmaConnectionHandle}"); return 0; } // EnablePalmaStep(nn::hid::PalmaConnectionHandle, bool Enable) - public long EnablePalmaStep(ServiceCtx Context) + public long EnablePalmaStep(ServiceCtx context) { - int PalmaConnectionHandle = Context.RequestData.ReadInt32(); - bool EnabledPalmaStep = Context.RequestData.ReadBoolean(); + int palmaConnectionHandle = context.RequestData.ReadInt32(); + bool enabledPalmaStep = context.RequestData.ReadBoolean(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. PalmaConnectionHandle: {PalmaConnectionHandle} - " + - $"EnabledPalmaStep: {EnabledPalmaStep}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. PalmaConnectionHandle: {palmaConnectionHandle} - " + + $"EnabledPalmaStep: {enabledPalmaStep}"); - PalmaOperationCompleteEvent.ReadableEvent.Signal(); + _palmaOperationCompleteEvent.ReadableEvent.Signal(); return 0; } // SuspendPalmaStep(nn::hid::PalmaConnectionHandle) - public long SuspendPalmaStep(ServiceCtx Context) + public long SuspendPalmaStep(ServiceCtx context) { - int PalmaConnectionHandle = Context.RequestData.ReadInt32(); + int palmaConnectionHandle = context.RequestData.ReadInt32(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. PalmaConnectionHandle: {PalmaConnectionHandle}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. PalmaConnectionHandle: {palmaConnectionHandle}"); - PalmaOperationCompleteEvent.ReadableEvent.Signal(); + _palmaOperationCompleteEvent.ReadableEvent.Signal(); return 0; } // ResetPalmaStep(nn::hid::PalmaConnectionHandle) - public long ResetPalmaStep(ServiceCtx Context) + public long ResetPalmaStep(ServiceCtx context) { - int PalmaConnectionHandle = Context.RequestData.ReadInt32(); + int palmaConnectionHandle = context.RequestData.ReadInt32(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. PalmaConnectionHandle: {PalmaConnectionHandle}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. PalmaConnectionHandle: {palmaConnectionHandle}"); - PalmaOperationCompleteEvent.ReadableEvent.Signal(); + _palmaOperationCompleteEvent.ReadableEvent.Signal(); return 0; } // ReadPalmaApplicationSection(nn::hid::PalmaConnectionHandle, ulong Unknown0, ulong Unknown1) - public long ReadPalmaApplicationSection(ServiceCtx Context) + public long ReadPalmaApplicationSection(ServiceCtx context) { - int PalmaConnectionHandle = Context.RequestData.ReadInt32(); - long Unknown0 = Context.RequestData.ReadInt64(); - long Unknown1 = Context.RequestData.ReadInt64(); + int palmaConnectionHandle = context.RequestData.ReadInt32(); + long unknown0 = context.RequestData.ReadInt64(); + long unknown1 = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. PalmaConnectionHandle: {PalmaConnectionHandle} - " + - $"Unknown0: {Unknown0} - " + - $"Unknown1: {Unknown1}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. PalmaConnectionHandle: {palmaConnectionHandle} - " + + $"Unknown0: {unknown0} - " + + $"Unknown1: {unknown1}"); return 0; } // WritePalmaApplicationSection(nn::hid::PalmaConnectionHandle, ulong Unknown0, ulong Unknown1, nn::hid::PalmaApplicationSectionAccessBuffer) - public long WritePalmaApplicationSection(ServiceCtx Context) + public long WritePalmaApplicationSection(ServiceCtx context) { - int PalmaConnectionHandle = Context.RequestData.ReadInt32(); - long Unknown0 = Context.RequestData.ReadInt64(); - long Unknown1 = Context.RequestData.ReadInt64(); + int palmaConnectionHandle = context.RequestData.ReadInt32(); + long unknown0 = context.RequestData.ReadInt64(); + long unknown1 = context.RequestData.ReadInt64(); // nn::hid::PalmaApplicationSectionAccessBuffer cast is unknown - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. PalmaConnectionHandle: {PalmaConnectionHandle} - " + - $"Unknown0: {Unknown0} - " + - $"Unknown1: {Unknown1}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. PalmaConnectionHandle: {palmaConnectionHandle} - " + + $"Unknown0: {unknown0} - " + + $"Unknown1: {unknown1}"); - PalmaOperationCompleteEvent.ReadableEvent.Signal(); + _palmaOperationCompleteEvent.ReadableEvent.Signal(); return 0; } // ReadPalmaUniqueCode(nn::hid::PalmaConnectionHandle) - public long ReadPalmaUniqueCode(ServiceCtx Context) + public long ReadPalmaUniqueCode(ServiceCtx context) { - int PalmaConnectionHandle = Context.RequestData.ReadInt32(); + int palmaConnectionHandle = context.RequestData.ReadInt32(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. PalmaConnectionHandle: {PalmaConnectionHandle}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. PalmaConnectionHandle: {palmaConnectionHandle}"); return 0; } // SetPalmaUniqueCodeInvalid(nn::hid::PalmaConnectionHandle) - public long SetPalmaUniqueCodeInvalid(ServiceCtx Context) + public long SetPalmaUniqueCodeInvalid(ServiceCtx context) { - int PalmaConnectionHandle = Context.RequestData.ReadInt32(); + int palmaConnectionHandle = context.RequestData.ReadInt32(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. PalmaConnectionHandle: {PalmaConnectionHandle}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. PalmaConnectionHandle: {palmaConnectionHandle}"); return 0; } // SetNpadCommunicationMode(long CommunicationMode, nn::applet::AppletResourceUserId) - public long SetNpadCommunicationMode(ServiceCtx Context) + public long SetNpadCommunicationMode(ServiceCtx context) { - NpadCommunicationMode = Context.RequestData.ReadInt64(); - long AppletResourceUserId = Context.RequestData.ReadInt64(); + _npadCommunicationMode = context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId} - " + - $"NpadCommunicationMode: {NpadCommunicationMode}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {appletResourceUserId} - " + + $"NpadCommunicationMode: {_npadCommunicationMode}"); return 0; } // GetNpadCommunicationMode() -> long CommunicationMode - public long GetNpadCommunicationMode(ServiceCtx Context) + public long GetNpadCommunicationMode(ServiceCtx context) { - Context.ResponseData.Write(NpadCommunicationMode); + context.ResponseData.Write(_npadCommunicationMode); - Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. CommunicationMode: {NpadCommunicationMode}"); + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. CommunicationMode: {_npadCommunicationMode}"); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/IpcService.cs b/Ryujinx.HLE/HOS/Services/IpcService.cs index 60a4431e..ec43430e 100644 --- a/Ryujinx.HLE/HOS/Services/IpcService.cs +++ b/Ryujinx.HLE/HOS/Services/IpcService.cs @@ -11,176 +11,176 @@ namespace Ryujinx.HLE.HOS.Services { public abstract IReadOnlyDictionary Commands { get; } - private IdDictionary DomainObjects; + private IdDictionary _domainObjects; - private int SelfId; + private int _selfId; - private bool IsDomain; + private bool _isDomain; public IpcService() { - DomainObjects = new IdDictionary(); + _domainObjects = new IdDictionary(); - SelfId = -1; + _selfId = -1; } public int ConvertToDomain() { - if (SelfId == -1) + if (_selfId == -1) { - SelfId = DomainObjects.Add(this); + _selfId = _domainObjects.Add(this); } - IsDomain = true; + _isDomain = true; - return SelfId; + return _selfId; } public void ConvertToSession() { - IsDomain = false; + _isDomain = false; } - public void CallMethod(ServiceCtx Context) + public void CallMethod(ServiceCtx context) { - IIpcService Service = this; + IIpcService service = this; - if (IsDomain) + if (_isDomain) { - int DomainWord0 = Context.RequestData.ReadInt32(); - int DomainObjId = Context.RequestData.ReadInt32(); + int domainWord0 = context.RequestData.ReadInt32(); + int domainObjId = context.RequestData.ReadInt32(); - int DomainCmd = (DomainWord0 >> 0) & 0xff; - int InputObjCount = (DomainWord0 >> 8) & 0xff; - int DataPayloadSize = (DomainWord0 >> 16) & 0xffff; + int domainCmd = (domainWord0 >> 0) & 0xff; + int inputObjCount = (domainWord0 >> 8) & 0xff; + int dataPayloadSize = (domainWord0 >> 16) & 0xffff; - Context.RequestData.BaseStream.Seek(0x10 + DataPayloadSize, SeekOrigin.Begin); + context.RequestData.BaseStream.Seek(0x10 + dataPayloadSize, SeekOrigin.Begin); - for (int Index = 0; Index < InputObjCount; Index++) + for (int index = 0; index < inputObjCount; index++) { - Context.Request.ObjectIds.Add(Context.RequestData.ReadInt32()); + context.Request.ObjectIds.Add(context.RequestData.ReadInt32()); } - Context.RequestData.BaseStream.Seek(0x10, SeekOrigin.Begin); + context.RequestData.BaseStream.Seek(0x10, SeekOrigin.Begin); - if (DomainCmd == 1) + if (domainCmd == 1) { - Service = GetObject(DomainObjId); + service = GetObject(domainObjId); - Context.ResponseData.Write(0L); - Context.ResponseData.Write(0L); + context.ResponseData.Write(0L); + context.ResponseData.Write(0L); } - else if (DomainCmd == 2) + else if (domainCmd == 2) { - Delete(DomainObjId); + Delete(domainObjId); - Context.ResponseData.Write(0L); + context.ResponseData.Write(0L); return; } else { - throw new NotImplementedException($"Domain command: {DomainCmd}"); + throw new NotImplementedException($"Domain command: {domainCmd}"); } } - long SfciMagic = Context.RequestData.ReadInt64(); - int CommandId = (int)Context.RequestData.ReadInt64(); + long sfciMagic = context.RequestData.ReadInt64(); + int commandId = (int)context.RequestData.ReadInt64(); - if (Service.Commands.TryGetValue(CommandId, out ServiceProcessRequest ProcessRequest)) + if (service.Commands.TryGetValue(commandId, out ServiceProcessRequest processRequest)) { - Context.ResponseData.BaseStream.Seek(IsDomain ? 0x20 : 0x10, SeekOrigin.Begin); + context.ResponseData.BaseStream.Seek(_isDomain ? 0x20 : 0x10, SeekOrigin.Begin); - Logger.PrintDebug(LogClass.KernelIpc, $"{Service.GetType().Name}: {ProcessRequest.Method.Name}"); + Logger.PrintDebug(LogClass.KernelIpc, $"{service.GetType().Name}: {processRequest.Method.Name}"); - long Result = ProcessRequest(Context); + long result = processRequest(context); - if (IsDomain) + if (_isDomain) { - foreach (int Id in Context.Response.ObjectIds) + foreach (int id in context.Response.ObjectIds) { - Context.ResponseData.Write(Id); + context.ResponseData.Write(id); } - Context.ResponseData.BaseStream.Seek(0, SeekOrigin.Begin); + context.ResponseData.BaseStream.Seek(0, SeekOrigin.Begin); - Context.ResponseData.Write(Context.Response.ObjectIds.Count); + context.ResponseData.Write(context.Response.ObjectIds.Count); } - Context.ResponseData.BaseStream.Seek(IsDomain ? 0x10 : 0, SeekOrigin.Begin); + context.ResponseData.BaseStream.Seek(_isDomain ? 0x10 : 0, SeekOrigin.Begin); - Context.ResponseData.Write(IpcMagic.Sfco); - Context.ResponseData.Write(Result); + context.ResponseData.Write(IpcMagic.Sfco); + context.ResponseData.Write(result); } else { - string DbgMessage = $"{Context.Session.ServiceName} {Service.GetType().Name}: {CommandId}"; + string dbgMessage = $"{context.Session.ServiceName} {service.GetType().Name}: {commandId}"; - throw new NotImplementedException(DbgMessage); + throw new NotImplementedException(dbgMessage); } } - protected static void MakeObject(ServiceCtx Context, IpcService Obj) + protected static void MakeObject(ServiceCtx context, IpcService obj) { - IpcService Service = Context.Session.Service; + IpcService service = context.Session.Service; - if (Service.IsDomain) + if (service._isDomain) { - Context.Response.ObjectIds.Add(Service.Add(Obj)); + context.Response.ObjectIds.Add(service.Add(obj)); } else { - KSession Session = new KSession(Obj, Context.Session.ServiceName); + KSession session = new KSession(obj, context.Session.ServiceName); - if (Context.Process.HandleTable.GenerateHandle(Session, out int Handle) != KernelResult.Success) + if (context.Process.HandleTable.GenerateHandle(session, out int handle) != KernelResult.Success) { throw new InvalidOperationException("Out of handles!"); } - Context.Response.HandleDesc = IpcHandleDesc.MakeMove(Handle); + context.Response.HandleDesc = IpcHandleDesc.MakeMove(handle); } } - protected static T GetObject(ServiceCtx Context, int Index) where T : IpcService + protected static T GetObject(ServiceCtx context, int index) where T : IpcService { - IpcService Service = Context.Session.Service; + IpcService service = context.Session.Service; - if (!Service.IsDomain) + if (!service._isDomain) { - int Handle = Context.Request.HandleDesc.ToMove[Index]; + int handle = context.Request.HandleDesc.ToMove[index]; - KSession Session = Context.Process.HandleTable.GetObject(Handle); + KSession session = context.Process.HandleTable.GetObject(handle); - return Session?.Service is T ? (T)Session.Service : null; + return session?.Service is T ? (T)session.Service : null; } - int ObjId = Context.Request.ObjectIds[Index]; + int objId = context.Request.ObjectIds[index]; - IIpcService Obj = Service.GetObject(ObjId); + IIpcService obj = service.GetObject(objId); - return Obj is T ? (T)Obj : null; + return obj is T ? (T)obj : null; } - private int Add(IIpcService Obj) + private int Add(IIpcService obj) { - return DomainObjects.Add(Obj); + return _domainObjects.Add(obj); } - private bool Delete(int Id) + private bool Delete(int id) { - object Obj = DomainObjects.Delete(Id); + object obj = _domainObjects.Delete(id); - if (Obj is IDisposable DisposableObj) + if (obj is IDisposable disposableObj) { - DisposableObj.Dispose(); + disposableObj.Dispose(); } - return Obj != null; + return obj != null; } - private IIpcService GetObject(int Id) + private IIpcService GetObject(int id) { - return DomainObjects.GetData(Id); + return _domainObjects.GetData(id); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Services/Irs/IIrSensorServer.cs b/Ryujinx.HLE/HOS/Services/Irs/IIrSensorServer.cs index 155faea3..d6683877 100644 --- a/Ryujinx.HLE/HOS/Services/Irs/IIrSensorServer.cs +++ b/Ryujinx.HLE/HOS/Services/Irs/IIrSensorServer.cs @@ -6,15 +6,15 @@ namespace Ryujinx.HLE.HOS.Services.Irs { class IIrSensorServer : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - private bool Activated; + private bool _activated; public IIrSensorServer() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 302, ActivateIrsensor }, { 303, DeactivateIrsensor } @@ -22,21 +22,21 @@ namespace Ryujinx.HLE.HOS.Services.Irs } // ActivateIrsensor(nn::applet::AppletResourceUserId, pid) - public long ActivateIrsensor(ServiceCtx Context) + public long ActivateIrsensor(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceIrs, $"Stubbed. AppletResourceUserId: {AppletResourceUserId}"); + Logger.PrintStub(LogClass.ServiceIrs, $"Stubbed. AppletResourceUserId: {appletResourceUserId}"); return 0; } // DeactivateIrsensor(nn::applet::AppletResourceUserId, pid) - public long DeactivateIrsensor(ServiceCtx Context) + public long DeactivateIrsensor(ServiceCtx context) { - long AppletResourceUserId = Context.RequestData.ReadInt64(); + long appletResourceUserId = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceIrs, $"Stubbed. AppletResourceUserId: {AppletResourceUserId}"); + Logger.PrintStub(LogClass.ServiceIrs, $"Stubbed. AppletResourceUserId: {appletResourceUserId}"); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Ldr/IRoInterface.cs b/Ryujinx.HLE/HOS/Services/Ldr/IRoInterface.cs index f0899bd4..1ee30a6c 100644 --- a/Ryujinx.HLE/HOS/Services/Ldr/IRoInterface.cs +++ b/Ryujinx.HLE/HOS/Services/Ldr/IRoInterface.cs @@ -4,7 +4,6 @@ using Ryujinx.HLE.HOS.Ipc; using Ryujinx.HLE.HOS.Kernel; using Ryujinx.HLE.Loaders.Executables; using Ryujinx.HLE.Utilities; -using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -55,11 +54,11 @@ namespace Ryujinx.HLE.HOS.Services.Ldr public List Hashes { get; private set; } public long NrrAddress { get; private set; } - public NrrInfo(long NrrAddress, NrrHeader Header, List Hashes) + public NrrInfo(long nrrAddress, NrrHeader header, List hashes) { - this.NrrAddress = NrrAddress; - this.Header = Header; - this.Hashes = Hashes; + NrrAddress = nrrAddress; + Header = header; + Hashes = hashes; } } @@ -76,29 +75,29 @@ namespace Ryujinx.HLE.HOS.Services.Ldr public ulong NroMappedAddress { get; set; } public NroInfo( - NxRelocatableObject Executable, - byte[] Hash, - ulong NroAddress, - ulong NroSize, - ulong BssAddress, - ulong BssSize, - ulong TotalSize) + NxRelocatableObject executable, + byte[] hash, + ulong nroAddress, + ulong nroSize, + ulong bssAddress, + ulong bssSize, + ulong totalSize) { - this.Executable = Executable; - this.Hash = Hash; - this.NroAddress = NroAddress; - this.NroSize = NroSize; - this.BssAddress = BssAddress; - this.BssSize = BssSize; - this.TotalSize = TotalSize; + Executable = executable; + Hash = hash; + NroAddress = nroAddress; + NroSize = nroSize; + BssAddress = bssAddress; + BssSize = bssSize; + TotalSize = totalSize; } } class IRoInterface : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; private const int MaxNrr = 0x40; private const int MaxNro = 0x40; @@ -106,70 +105,70 @@ namespace Ryujinx.HLE.HOS.Services.Ldr private const uint NrrMagic = 0x3052524E; private const uint NroMagic = 0x304F524E; - private List NrrInfos; - private List NroInfos; + private List _nrrInfos; + private List _nroInfos; - private bool IsInitialized; + private bool _isInitialized; public IRoInterface() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, LoadNro }, { 1, UnloadNro }, { 2, LoadNrr }, { 3, UnloadNrr }, - { 4, Initialize }, + { 4, Initialize } }; - NrrInfos = new List(MaxNrr); - NroInfos = new List(MaxNro); + _nrrInfos = new List(MaxNrr); + _nroInfos = new List(MaxNro); } - private long ParseNrr(out NrrInfo NrrInfo, ServiceCtx Context, long NrrAddress, long NrrSize) + private long ParseNrr(out NrrInfo nrrInfo, ServiceCtx context, long nrrAddress, long nrrSize) { - NrrInfo = null; + nrrInfo = null; - if (NrrSize == 0 || NrrAddress + NrrSize <= NrrAddress || (NrrSize & 0xFFF) != 0) + if (nrrSize == 0 || nrrAddress + nrrSize <= nrrAddress || (nrrSize & 0xFFF) != 0) { return MakeError(ErrorModule.Loader, LoaderErr.BadSize); } - else if ((NrrAddress & 0xFFF) != 0) + else if ((nrrAddress & 0xFFF) != 0) { return MakeError(ErrorModule.Loader, LoaderErr.UnalignedAddress); } - StructReader Reader = new StructReader(Context.Memory, NrrAddress); - NrrHeader Header = Reader.Read(); + StructReader reader = new StructReader(context.Memory, nrrAddress); + NrrHeader header = reader.Read(); - if (Header.Magic != NrrMagic) + if (header.Magic != NrrMagic) { return MakeError(ErrorModule.Loader, LoaderErr.InvalidNrr); } - else if (Header.NrrSize != NrrSize) + else if (header.NrrSize != nrrSize) { return MakeError(ErrorModule.Loader, LoaderErr.BadSize); } - List Hashes = new List(); + List hashes = new List(); - for (int i = 0; i < Header.HashCount; i++) + for (int i = 0; i < header.HashCount; i++) { - Hashes.Add(Context.Memory.ReadBytes(NrrAddress + Header.HashOffset + (i * 0x20), 0x20)); + hashes.Add(context.Memory.ReadBytes(nrrAddress + header.HashOffset + (i * 0x20), 0x20)); } - NrrInfo = new NrrInfo(NrrAddress, Header, Hashes); + nrrInfo = new NrrInfo(nrrAddress, header, hashes); return 0; } - public bool IsNroHashPresent(byte[] NroHash) + public bool IsNroHashPresent(byte[] nroHash) { - foreach (NrrInfo Info in NrrInfos) + foreach (NrrInfo info in _nrrInfos) { - foreach (byte[] Hash in Info.Hashes) + foreach (byte[] hash in info.Hashes) { - if (Hash.SequenceEqual(NroHash)) + if (hash.SequenceEqual(nroHash)) { return true; } @@ -179,11 +178,11 @@ namespace Ryujinx.HLE.HOS.Services.Ldr return false; } - public bool IsNroLoaded(byte[] NroHash) + public bool IsNroLoaded(byte[] nroHash) { - foreach (NroInfo Info in NroInfos) + foreach (NroInfo info in _nroInfos) { - if (Info.Hash.SequenceEqual(NroHash)) + if (info.Hash.SequenceEqual(nroHash)) { return true; } @@ -192,206 +191,206 @@ namespace Ryujinx.HLE.HOS.Services.Ldr return false; } - public long ParseNro(out NroInfo Res, ServiceCtx Context, ulong NroAddress, ulong NroSize, ulong BssAddress, ulong BssSize) + public long ParseNro(out NroInfo res, ServiceCtx context, ulong nroAddress, ulong nroSize, ulong bssAddress, ulong bssSize) { - Res = null; + res = null; - if (NroInfos.Count >= MaxNro) + if (_nroInfos.Count >= MaxNro) { return MakeError(ErrorModule.Loader, LoaderErr.MaxNro); } - else if (NroSize == 0 || NroAddress + NroSize <= NroAddress || (NroSize & 0xFFF) != 0) + else if (nroSize == 0 || nroAddress + nroSize <= nroAddress || (nroSize & 0xFFF) != 0) { return MakeError(ErrorModule.Loader, LoaderErr.BadSize); } - else if (BssSize != 0 && BssAddress + BssSize <= BssAddress) + else if (bssSize != 0 && bssAddress + bssSize <= bssAddress) { return MakeError(ErrorModule.Loader, LoaderErr.BadSize); } - else if ((NroAddress & 0xFFF) != 0) + else if ((nroAddress & 0xFFF) != 0) { return MakeError(ErrorModule.Loader, LoaderErr.UnalignedAddress); } - uint Magic = Context.Memory.ReadUInt32((long)NroAddress + 0x10); - uint NroFileSize = Context.Memory.ReadUInt32((long)NroAddress + 0x18); + uint magic = context.Memory.ReadUInt32((long)nroAddress + 0x10); + uint nroFileSize = context.Memory.ReadUInt32((long)nroAddress + 0x18); - if (Magic != NroMagic || NroSize != NroFileSize) + if (magic != NroMagic || nroSize != nroFileSize) { return MakeError(ErrorModule.Loader, LoaderErr.InvalidNro); } - byte[] NroData = Context.Memory.ReadBytes((long)NroAddress, (long)NroSize); - byte[] NroHash = null; + byte[] nroData = context.Memory.ReadBytes((long)nroAddress, (long)nroSize); + byte[] nroHash = null; - MemoryStream Stream = new MemoryStream(NroData); + MemoryStream stream = new MemoryStream(nroData); - using (SHA256 Hasher = SHA256.Create()) + using (SHA256 hasher = SHA256.Create()) { - NroHash = Hasher.ComputeHash(Stream); + nroHash = hasher.ComputeHash(stream); } - if (!IsNroHashPresent(NroHash)) + if (!IsNroHashPresent(nroHash)) { return MakeError(ErrorModule.Loader, LoaderErr.NroHashNotPresent); } - if (IsNroLoaded(NroHash)) + if (IsNroLoaded(nroHash)) { return MakeError(ErrorModule.Loader, LoaderErr.NroAlreadyLoaded); } - Stream.Position = 0; + stream.Position = 0; - NxRelocatableObject Executable = new NxRelocatableObject(Stream, NroAddress, BssAddress); + NxRelocatableObject executable = new NxRelocatableObject(stream, nroAddress, bssAddress); // check if everything is page align. - if ((Executable.Text.Length & 0xFFF) != 0 || (Executable.RO.Length & 0xFFF) != 0 || - (Executable.Data.Length & 0xFFF) != 0 || (Executable.BssSize & 0xFFF) != 0) + if ((executable.Text.Length & 0xFFF) != 0 || (executable.Ro.Length & 0xFFF) != 0 || + (executable.Data.Length & 0xFFF) != 0 || (executable.BssSize & 0xFFF) != 0) { return MakeError(ErrorModule.Loader, LoaderErr.InvalidNro); } // check if everything is contiguous. - if (Executable.ROOffset != Executable.TextOffset + Executable.Text.Length || - Executable.DataOffset != Executable.ROOffset + Executable.RO.Length || - NroFileSize != Executable.DataOffset + Executable.Data.Length) + if (executable.RoOffset != executable.TextOffset + executable.Text.Length || + executable.DataOffset != executable.RoOffset + executable.Ro.Length || + nroFileSize != executable.DataOffset + executable.Data.Length) { return MakeError(ErrorModule.Loader, LoaderErr.InvalidNro); } // finally check the bss size match. - if ((ulong)Executable.BssSize != BssSize) + if ((ulong)executable.BssSize != bssSize) { return MakeError(ErrorModule.Loader, LoaderErr.InvalidNro); } - int TotalSize = Executable.Text.Length + Executable.RO.Length + Executable.Data.Length + Executable.BssSize; + int totalSize = executable.Text.Length + executable.Ro.Length + executable.Data.Length + executable.BssSize; - Res = new NroInfo( - Executable, - NroHash, - NroAddress, - NroSize, - BssAddress, - BssSize, - (ulong)TotalSize); + res = new NroInfo( + executable, + nroHash, + nroAddress, + nroSize, + bssAddress, + bssSize, + (ulong)totalSize); return 0; } - private long MapNro(ServiceCtx Context, NroInfo Info, out ulong NroMappedAddress) + private long MapNro(ServiceCtx context, NroInfo info, out ulong nroMappedAddress) { - NroMappedAddress = 0; + nroMappedAddress = 0; - KMemoryManager MemMgr = Context.Process.MemoryManager; + KMemoryManager memMgr = context.Process.MemoryManager; - ulong TargetAddress = MemMgr.GetAddrSpaceBaseAddr(); + ulong targetAddress = memMgr.GetAddrSpaceBaseAddr(); while (true) { - if (TargetAddress + Info.TotalSize >= MemMgr.AddrSpaceEnd) + if (targetAddress + info.TotalSize >= memMgr.AddrSpaceEnd) { return MakeError(ErrorModule.Loader, LoaderErr.InvalidMemoryState); } - KMemoryInfo MemInfo = MemMgr.QueryMemory(TargetAddress); + KMemoryInfo memInfo = memMgr.QueryMemory(targetAddress); - if (MemInfo.State == MemoryState.Unmapped && MemInfo.Size >= Info.TotalSize) + if (memInfo.State == MemoryState.Unmapped && memInfo.Size >= info.TotalSize) { - if (!MemMgr.InsideHeapRegion (TargetAddress, Info.TotalSize) && - !MemMgr.InsideAliasRegion(TargetAddress, Info.TotalSize)) + if (!memMgr.InsideHeapRegion (targetAddress, info.TotalSize) && + !memMgr.InsideAliasRegion(targetAddress, info.TotalSize)) { break; } } - TargetAddress += MemInfo.Size; + targetAddress += memInfo.Size; } - KernelResult Result = MemMgr.MapProcessCodeMemory(TargetAddress, Info.NroAddress, Info.NroSize); + KernelResult result = memMgr.MapProcessCodeMemory(targetAddress, info.NroAddress, info.NroSize); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { return MakeError(ErrorModule.Loader, LoaderErr.InvalidMemoryState); } - ulong BssTargetAddress = TargetAddress + Info.NroSize; + ulong bssTargetAddress = targetAddress + info.NroSize; - if (Info.BssSize != 0) + if (info.BssSize != 0) { - Result = MemMgr.MapProcessCodeMemory(BssTargetAddress, Info.BssAddress, Info.BssSize); + result = memMgr.MapProcessCodeMemory(bssTargetAddress, info.BssAddress, info.BssSize); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - MemMgr.UnmapProcessCodeMemory(TargetAddress, Info.NroAddress, Info.NroSize); + memMgr.UnmapProcessCodeMemory(targetAddress, info.NroAddress, info.NroSize); return MakeError(ErrorModule.Loader, LoaderErr.InvalidMemoryState); } } - Result = LoadNroIntoMemory(Context.Process, Info.Executable, TargetAddress); + result = LoadNroIntoMemory(context.Process, info.Executable, targetAddress); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - MemMgr.UnmapProcessCodeMemory(TargetAddress, Info.NroAddress, Info.NroSize); + memMgr.UnmapProcessCodeMemory(targetAddress, info.NroAddress, info.NroSize); - if (Info.BssSize != 0) + if (info.BssSize != 0) { - MemMgr.UnmapProcessCodeMemory(BssTargetAddress, Info.BssAddress, Info.BssSize); + memMgr.UnmapProcessCodeMemory(bssTargetAddress, info.BssAddress, info.BssSize); } return 0; } - Info.NroMappedAddress = TargetAddress; - NroMappedAddress = TargetAddress; + info.NroMappedAddress = targetAddress; + nroMappedAddress = targetAddress; return 0; } - private KernelResult LoadNroIntoMemory(KProcess Process, IExecutable RelocatableObject, ulong BaseAddress) + private KernelResult LoadNroIntoMemory(KProcess process, IExecutable relocatableObject, ulong baseAddress) { - ulong TextStart = BaseAddress + (ulong)RelocatableObject.TextOffset; - ulong ROStart = BaseAddress + (ulong)RelocatableObject.ROOffset; - ulong DataStart = BaseAddress + (ulong)RelocatableObject.DataOffset; + ulong textStart = baseAddress + (ulong)relocatableObject.TextOffset; + ulong roStart = baseAddress + (ulong)relocatableObject.RoOffset; + ulong dataStart = baseAddress + (ulong)relocatableObject.DataOffset; - ulong BssStart = DataStart + (ulong)RelocatableObject.Data.Length; + ulong bssStart = dataStart + (ulong)relocatableObject.Data.Length; - ulong BssEnd = BitUtils.AlignUp(BssStart + (ulong)RelocatableObject.BssSize, KMemoryManager.PageSize); + ulong bssEnd = BitUtils.AlignUp(bssStart + (ulong)relocatableObject.BssSize, KMemoryManager.PageSize); - Process.CpuMemory.WriteBytes((long)TextStart, RelocatableObject.Text); - Process.CpuMemory.WriteBytes((long)ROStart, RelocatableObject.RO); - Process.CpuMemory.WriteBytes((long)DataStart, RelocatableObject.Data); + process.CpuMemory.WriteBytes((long)textStart, relocatableObject.Text); + process.CpuMemory.WriteBytes((long)roStart, relocatableObject.Ro); + process.CpuMemory.WriteBytes((long)dataStart, relocatableObject.Data); - MemoryHelper.FillWithZeros(Process.CpuMemory, (long)BssStart, (int)(BssEnd - BssStart)); + MemoryHelper.FillWithZeros(process.CpuMemory, (long)bssStart, (int)(bssEnd - bssStart)); - KernelResult Result; + KernelResult result; - Result = Process.MemoryManager.SetProcessMemoryPermission(TextStart, ROStart - TextStart, MemoryPermission.ReadAndExecute); + result = process.MemoryManager.SetProcessMemoryPermission(textStart, roStart - textStart, MemoryPermission.ReadAndExecute); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - return Result; + return result; } - Result = Process.MemoryManager.SetProcessMemoryPermission(ROStart, DataStart - ROStart, MemoryPermission.Read); + result = process.MemoryManager.SetProcessMemoryPermission(roStart, dataStart - roStart, MemoryPermission.Read); - if (Result != KernelResult.Success) + if (result != KernelResult.Success) { - return Result; + return result; } - return Process.MemoryManager.SetProcessMemoryPermission(DataStart, BssEnd - DataStart, MemoryPermission.ReadAndWrite); + return process.MemoryManager.SetProcessMemoryPermission(dataStart, bssEnd - dataStart, MemoryPermission.ReadAndWrite); } - private long RemoveNrrInfo(long NrrAddress) + private long RemoveNrrInfo(long nrrAddress) { - foreach (NrrInfo Info in NrrInfos) + foreach (NrrInfo info in _nrrInfos) { - if (Info.NrrAddress == NrrAddress) + if (info.NrrAddress == nrrAddress) { - NrrInfos.Remove(Info); + _nrrInfos.Remove(info); return 0; } @@ -400,46 +399,46 @@ namespace Ryujinx.HLE.HOS.Services.Ldr return MakeError(ErrorModule.Loader, LoaderErr.BadNrrAddress); } - private long RemoveNroInfo(ServiceCtx Context, ulong NroMappedAddress) + private long RemoveNroInfo(ServiceCtx context, ulong nroMappedAddress) { - foreach (NroInfo Info in NroInfos) + foreach (NroInfo info in _nroInfos) { - if (Info.NroMappedAddress == NroMappedAddress) + if (info.NroMappedAddress == nroMappedAddress) { - NroInfos.Remove(Info); + _nroInfos.Remove(info); - ulong TextSize = (ulong)Info.Executable.Text.Length; - ulong ROSize = (ulong)Info.Executable.RO.Length; - ulong DataSize = (ulong)Info.Executable.Data.Length; - ulong BssSize = (ulong)Info.Executable.BssSize; + ulong textSize = (ulong)info.Executable.Text.Length; + ulong roSize = (ulong)info.Executable.Ro.Length; + ulong dataSize = (ulong)info.Executable.Data.Length; + ulong bssSize = (ulong)info.Executable.BssSize; - KernelResult Result = KernelResult.Success; + KernelResult result = KernelResult.Success; - if (Info.Executable.BssSize != 0) + if (info.Executable.BssSize != 0) { - Result = Context.Process.MemoryManager.UnmapProcessCodeMemory( - Info.NroMappedAddress + TextSize + ROSize + DataSize, - Info.Executable.BssAddress, - BssSize); + result = context.Process.MemoryManager.UnmapProcessCodeMemory( + info.NroMappedAddress + textSize + roSize + dataSize, + info.Executable.BssAddress, + bssSize); } - if (Result == KernelResult.Success) + if (result == KernelResult.Success) { - Result = Context.Process.MemoryManager.UnmapProcessCodeMemory( - Info.NroMappedAddress + TextSize + ROSize, - Info.Executable.SourceAddress + TextSize + ROSize, - DataSize); + result = context.Process.MemoryManager.UnmapProcessCodeMemory( + info.NroMappedAddress + textSize + roSize, + info.Executable.SourceAddress + textSize + roSize, + dataSize); - if (Result == KernelResult.Success) + if (result == KernelResult.Success) { - Result = Context.Process.MemoryManager.UnmapProcessCodeMemory( - Info.NroMappedAddress, - Info.Executable.SourceAddress, - TextSize + ROSize); + result = context.Process.MemoryManager.UnmapProcessCodeMemory( + info.NroMappedAddress, + info.Executable.SourceAddress, + textSize + roSize); } } - return (long)Result; + return (long)result; } } @@ -447,125 +446,125 @@ namespace Ryujinx.HLE.HOS.Services.Ldr } // LoadNro(u64, u64, u64, u64, u64, pid) -> u64 - public long LoadNro(ServiceCtx Context) + public long LoadNro(ServiceCtx context) { - long Result = MakeError(ErrorModule.Loader, LoaderErr.BadInitialization); + long result = MakeError(ErrorModule.Loader, LoaderErr.BadInitialization); // Zero - Context.RequestData.ReadUInt64(); + context.RequestData.ReadUInt64(); - ulong NroHeapAddress = Context.RequestData.ReadUInt64(); - ulong NroSize = Context.RequestData.ReadUInt64(); - ulong BssHeapAddress = Context.RequestData.ReadUInt64(); - ulong BssSize = Context.RequestData.ReadUInt64(); + ulong nroHeapAddress = context.RequestData.ReadUInt64(); + ulong nroSize = context.RequestData.ReadUInt64(); + ulong bssHeapAddress = context.RequestData.ReadUInt64(); + ulong bssSize = context.RequestData.ReadUInt64(); - ulong NroMappedAddress = 0; + ulong nroMappedAddress = 0; - if (IsInitialized) + if (_isInitialized) { - NroInfo Info; + NroInfo info; - Result = ParseNro(out Info, Context, NroHeapAddress, NroSize, BssHeapAddress, BssSize); + result = ParseNro(out info, context, nroHeapAddress, nroSize, bssHeapAddress, bssSize); - if (Result == 0) + if (result == 0) { - Result = MapNro(Context, Info, out NroMappedAddress); + result = MapNro(context, info, out nroMappedAddress); - if (Result == 0) + if (result == 0) { - NroInfos.Add(Info); + _nroInfos.Add(info); } } } - Context.ResponseData.Write(NroMappedAddress); + context.ResponseData.Write(nroMappedAddress); - return Result; + return result; } // UnloadNro(u64, u64, pid) - public long UnloadNro(ServiceCtx Context) + public long UnloadNro(ServiceCtx context) { - long Result = MakeError(ErrorModule.Loader, LoaderErr.BadInitialization); + long result = MakeError(ErrorModule.Loader, LoaderErr.BadInitialization); // Zero - Context.RequestData.ReadUInt64(); + context.RequestData.ReadUInt64(); - ulong NroMappedAddress = Context.RequestData.ReadUInt64(); + ulong nroMappedAddress = context.RequestData.ReadUInt64(); - if (IsInitialized) + if (_isInitialized) { - if ((NroMappedAddress & 0xFFF) != 0) + if ((nroMappedAddress & 0xFFF) != 0) { return MakeError(ErrorModule.Loader, LoaderErr.UnalignedAddress); } - Result = RemoveNroInfo(Context, NroMappedAddress); + result = RemoveNroInfo(context, nroMappedAddress); } - return Result; + return result; } // LoadNrr(u64, u64, u64, pid) - public long LoadNrr(ServiceCtx Context) + public long LoadNrr(ServiceCtx context) { - long Result = MakeError(ErrorModule.Loader, LoaderErr.BadInitialization); + long result = MakeError(ErrorModule.Loader, LoaderErr.BadInitialization); // Zero - Context.RequestData.ReadUInt64(); + context.RequestData.ReadUInt64(); - long NrrAddress = Context.RequestData.ReadInt64(); - long NrrSize = Context.RequestData.ReadInt64(); + long nrrAddress = context.RequestData.ReadInt64(); + long nrrSize = context.RequestData.ReadInt64(); - if (IsInitialized) + if (_isInitialized) { - NrrInfo Info; - Result = ParseNrr(out Info, Context, NrrAddress, NrrSize); + NrrInfo info; + result = ParseNrr(out info, context, nrrAddress, nrrSize); - if(Result == 0) + if(result == 0) { - if (NrrInfos.Count >= MaxNrr) + if (_nrrInfos.Count >= MaxNrr) { - Result = MakeError(ErrorModule.Loader, LoaderErr.MaxNrr); + result = MakeError(ErrorModule.Loader, LoaderErr.MaxNrr); } else { - NrrInfos.Add(Info); + _nrrInfos.Add(info); } } } - return Result; + return result; } // UnloadNrr(u64, u64, pid) - public long UnloadNrr(ServiceCtx Context) + public long UnloadNrr(ServiceCtx context) { - long Result = MakeError(ErrorModule.Loader, LoaderErr.BadInitialization); + long result = MakeError(ErrorModule.Loader, LoaderErr.BadInitialization); // Zero - Context.RequestData.ReadUInt64(); + context.RequestData.ReadUInt64(); - long NrrHeapAddress = Context.RequestData.ReadInt64(); + long nrrHeapAddress = context.RequestData.ReadInt64(); - if (IsInitialized) + if (_isInitialized) { - if ((NrrHeapAddress & 0xFFF) != 0) + if ((nrrHeapAddress & 0xFFF) != 0) { return MakeError(ErrorModule.Loader, LoaderErr.UnalignedAddress); } - Result = RemoveNrrInfo(NrrHeapAddress); + result = RemoveNrrInfo(nrrHeapAddress); } - return Result; + return result; } // Initialize(u64, pid, KObject) - public long Initialize(ServiceCtx Context) + public long Initialize(ServiceCtx context) { // TODO: we actually ignore the pid and process handle receive, we will need to use them when we will have multi process support. - IsInitialized = true; + _isInitialized = true; return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Lm/ILogService.cs b/Ryujinx.HLE/HOS/Services/Lm/ILogService.cs index d79da515..37621c31 100644 --- a/Ryujinx.HLE/HOS/Services/Lm/ILogService.cs +++ b/Ryujinx.HLE/HOS/Services/Lm/ILogService.cs @@ -5,21 +5,21 @@ namespace Ryujinx.HLE.HOS.Services.Lm { class ILogService : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public ILogService() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, Initialize } }; } - public long Initialize(ServiceCtx Context) + public long Initialize(ServiceCtx context) { - MakeObject(Context, new ILogger()); + MakeObject(context, new ILogger()); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Lm/ILogger.cs b/Ryujinx.HLE/HOS/Services/Lm/ILogger.cs index 20579dfd..070cf9ae 100644 --- a/Ryujinx.HLE/HOS/Services/Lm/ILogger.cs +++ b/Ryujinx.HLE/HOS/Services/Lm/ILogger.cs @@ -8,91 +8,91 @@ namespace Ryujinx.HLE.HOS.Services.Lm { class ILogger : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public ILogger() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, Log } }; } - public long Log(ServiceCtx Context) + public long Log(ServiceCtx context) { - (long BufPos, long BufSize) = Context.Request.GetBufferType0x21(); - byte[] LogBuffer = Context.Memory.ReadBytes(BufPos, BufSize); + (long bufPos, long bufSize) = context.Request.GetBufferType0x21(); + byte[] logBuffer = context.Memory.ReadBytes(bufPos, bufSize); - using (MemoryStream MS = new MemoryStream(LogBuffer)) + using (MemoryStream ms = new MemoryStream(logBuffer)) { - BinaryReader Reader = new BinaryReader(MS); + BinaryReader reader = new BinaryReader(ms); - long Pid = Reader.ReadInt64(); - long ThreadContext = Reader.ReadInt64(); - short Flags = Reader.ReadInt16(); - byte Level = Reader.ReadByte(); - byte Verbosity = Reader.ReadByte(); - int PayloadLength = Reader.ReadInt32(); + long pid = reader.ReadInt64(); + long threadContext = reader.ReadInt64(); + short flags = reader.ReadInt16(); + byte level = reader.ReadByte(); + byte verbosity = reader.ReadByte(); + int payloadLength = reader.ReadInt32(); - StringBuilder SB = new StringBuilder(); + StringBuilder sb = new StringBuilder(); - SB.AppendLine("Guest log:"); + sb.AppendLine("Guest log:"); - while (MS.Position < MS.Length) + while (ms.Position < ms.Length) { - byte Type = Reader.ReadByte(); - byte Size = Reader.ReadByte(); + byte type = reader.ReadByte(); + byte size = reader.ReadByte(); - LmLogField Field = (LmLogField)Type; + LmLogField field = (LmLogField)type; - string FieldStr = string.Empty; + string fieldStr = string.Empty; - if (Field == LmLogField.Start) + if (field == LmLogField.Start) { - Reader.ReadBytes(Size); + reader.ReadBytes(size); continue; } - else if (Field == LmLogField.Stop) + else if (field == LmLogField.Stop) { break; } - else if (Field == LmLogField.Line) + else if (field == LmLogField.Line) { - FieldStr = $"{Field}: {Reader.ReadInt32()}"; + fieldStr = $"{field}: {reader.ReadInt32()}"; } - else if (Field == LmLogField.DropCount) + else if (field == LmLogField.DropCount) { - FieldStr = $"{Field}: {Reader.ReadInt64()}"; + fieldStr = $"{field}: {reader.ReadInt64()}"; } - else if (Field == LmLogField.Time) + else if (field == LmLogField.Time) { - FieldStr = $"{Field}: {Reader.ReadInt64()}s"; + fieldStr = $"{field}: {reader.ReadInt64()}s"; } - else if (Field < LmLogField.Count) + else if (field < LmLogField.Count) { - FieldStr = $"{Field}: '{Encoding.UTF8.GetString(Reader.ReadBytes(Size)).TrimEnd()}'"; + fieldStr = $"{field}: '{Encoding.UTF8.GetString(reader.ReadBytes(size)).TrimEnd()}'"; } else { - FieldStr = $"Field{Field}: '{Encoding.UTF8.GetString(Reader.ReadBytes(Size)).TrimEnd()}'"; + fieldStr = $"Field{field}: '{Encoding.UTF8.GetString(reader.ReadBytes(size)).TrimEnd()}'"; } - SB.AppendLine(" " + FieldStr); + sb.AppendLine(" " + fieldStr); } - string Text = SB.ToString(); + string text = sb.ToString(); - switch((LmLogLevel)Level) + switch((LmLogLevel)level) { - case LmLogLevel.Trace: Logger.PrintDebug (LogClass.ServiceLm, Text); break; - case LmLogLevel.Info: Logger.PrintInfo (LogClass.ServiceLm, Text); break; - case LmLogLevel.Warning: Logger.PrintWarning(LogClass.ServiceLm, Text); break; - case LmLogLevel.Error: Logger.PrintError (LogClass.ServiceLm, Text); break; - case LmLogLevel.Critical: Logger.PrintError (LogClass.ServiceLm, Text); break; + case LmLogLevel.Trace: Logger.PrintDebug (LogClass.ServiceLm, text); break; + case LmLogLevel.Info: Logger.PrintInfo (LogClass.ServiceLm, text); break; + case LmLogLevel.Warning: Logger.PrintWarning(LogClass.ServiceLm, text); break; + case LmLogLevel.Error: Logger.PrintError (LogClass.ServiceLm, text); break; + case LmLogLevel.Critical: Logger.PrintError (LogClass.ServiceLm, text); break; } } diff --git a/Ryujinx.HLE/HOS/Services/Lr/ILocationResolver.cs b/Ryujinx.HLE/HOS/Services/Lr/ILocationResolver.cs index dc057bc1..6c2f1970 100644 --- a/Ryujinx.HLE/HOS/Services/Lr/ILocationResolver.cs +++ b/Ryujinx.HLE/HOS/Services/Lr/ILocationResolver.cs @@ -12,15 +12,15 @@ namespace Ryujinx.HLE.HOS.Services.Lr { class ILocationResolver : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - private StorageId StorageId; + private StorageId _storageId; - public ILocationResolver(StorageId StorageId) + public ILocationResolver(StorageId storageId) { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, ResolveProgramPath }, { 1, RedirectProgramPath }, @@ -40,103 +40,103 @@ namespace Ryujinx.HLE.HOS.Services.Lr { 15, DeleteInfoHtmlNcaPath } }; - this.StorageId = StorageId; + _storageId = storageId; } // DeleteInfoHtmlNcaPath() - public long DeleteInfoHtmlNcaPath(ServiceCtx Context) + public long DeleteInfoHtmlNcaPath(ServiceCtx context) { - long TitleId = Context.RequestData.ReadInt64(); + long titleId = context.RequestData.ReadInt64(); - DeleteContentPath(Context, TitleId, ContentType.Manual); + DeleteContentPath(context, titleId, ContentType.Manual); return 0; } // DeleteDocHtmlNcaPath() - public long DeleteDocHtmlNcaPath(ServiceCtx Context) + public long DeleteDocHtmlNcaPath(ServiceCtx context) { - long TitleId = Context.RequestData.ReadInt64(); + long titleId = context.RequestData.ReadInt64(); - DeleteContentPath(Context, TitleId, ContentType.Manual); + DeleteContentPath(context, titleId, ContentType.Manual); return 0; } // DeleteControlNcaPath() - public long DeleteControlNcaPath(ServiceCtx Context) + public long DeleteControlNcaPath(ServiceCtx context) { - long TitleId = Context.RequestData.ReadInt64(); + long titleId = context.RequestData.ReadInt64(); - DeleteContentPath(Context, TitleId, ContentType.Control); + DeleteContentPath(context, titleId, ContentType.Control); return 0; } // DeleteProgramNcaPath() - public long DeleteProgramNcaPath(ServiceCtx Context) + public long DeleteProgramNcaPath(ServiceCtx context) { - long TitleId = Context.RequestData.ReadInt64(); + long titleId = context.RequestData.ReadInt64(); - DeleteContentPath(Context, TitleId, ContentType.Program); + DeleteContentPath(context, titleId, ContentType.Program); return 0; } // ClearLocationResolver2() - public long ClearLocationResolver2(ServiceCtx Context) + public long ClearLocationResolver2(ServiceCtx context) { - Context.Device.System.ContentManager.RefreshEntries(StorageId, 1); + context.Device.System.ContentManager.RefreshEntries(_storageId, 1); return 0; } // SetProgramNcaPath2() - public long SetProgramNcaPath2(ServiceCtx Context) + public long SetProgramNcaPath2(ServiceCtx context) { - long TitleId = Context.RequestData.ReadInt64(); + long titleId = context.RequestData.ReadInt64(); - RedirectPath(Context, TitleId, 1, ContentType.Program); + RedirectPath(context, titleId, 1, ContentType.Program); return 0; } // RedirectApplicationControlPath() - public long RedirectApplicationControlPath(ServiceCtx Context) + public long RedirectApplicationControlPath(ServiceCtx context) { - long TitleId = Context.RequestData.ReadInt64(); + long titleId = context.RequestData.ReadInt64(); - RedirectPath(Context, TitleId, 1, ContentType.Control); + RedirectPath(context, titleId, 1, ContentType.Control); return 0; } // RedirectApplicationHtmlDocumentPath() - public long RedirectApplicationHtmlDocumentPath(ServiceCtx Context) + public long RedirectApplicationHtmlDocumentPath(ServiceCtx context) { - long TitleId = Context.RequestData.ReadInt64(); + long titleId = context.RequestData.ReadInt64(); - RedirectPath(Context, TitleId, 1, ContentType.Manual); + RedirectPath(context, titleId, 1, ContentType.Manual); return 0; } // RedirectApplicationLegalInformationPath() - public long RedirectApplicationLegalInformationPath(ServiceCtx Context) + public long RedirectApplicationLegalInformationPath(ServiceCtx context) { - long TitleId = Context.RequestData.ReadInt64(); + long titleId = context.RequestData.ReadInt64(); - RedirectPath(Context, TitleId, 1, ContentType.Manual); + RedirectPath(context, titleId, 1, ContentType.Manual); return 0; } // ResolveDataPath() - public long ResolveDataPath(ServiceCtx Context) + public long ResolveDataPath(ServiceCtx context) { - long TitleId = Context.RequestData.ReadInt64(); + long titleId = context.RequestData.ReadInt64(); - if (ResolvePath(Context, TitleId, ContentType.Data) || ResolvePath(Context, TitleId, ContentType.AocData)) + if (ResolvePath(context, titleId, ContentType.Data) || ResolvePath(context, titleId, ContentType.AocData)) { return 0; } @@ -147,11 +147,11 @@ namespace Ryujinx.HLE.HOS.Services.Lr } // ResolveApplicationHtmlDocumentPath() - public long ResolveApplicationHtmlDocumentPath(ServiceCtx Context) + public long ResolveApplicationHtmlDocumentPath(ServiceCtx context) { - long TitleId = Context.RequestData.ReadInt64(); + long titleId = context.RequestData.ReadInt64(); - if (ResolvePath(Context, TitleId, ContentType.Manual)) + if (ResolvePath(context, titleId, ContentType.Manual)) { return 0; } @@ -162,11 +162,11 @@ namespace Ryujinx.HLE.HOS.Services.Lr } // ResolveApplicationLegalInformationPath() - public long ResolveApplicationLegalInformationPath(ServiceCtx Context) + public long ResolveApplicationLegalInformationPath(ServiceCtx context) { - long TitleId = Context.RequestData.ReadInt64(); + long titleId = context.RequestData.ReadInt64(); - if (ResolvePath(Context, TitleId, ContentType.Manual)) + if (ResolvePath(context, titleId, ContentType.Manual)) { return 0; } @@ -177,11 +177,11 @@ namespace Ryujinx.HLE.HOS.Services.Lr } // ResolveApplicationControlPath() - public long ResolveApplicationControlPath(ServiceCtx Context) + public long ResolveApplicationControlPath(ServiceCtx context) { - long TitleId = Context.RequestData.ReadInt64(); + long titleId = context.RequestData.ReadInt64(); - if (ResolvePath(Context, TitleId, ContentType.Control)) + if (ResolvePath(context, titleId, ContentType.Control)) { return 0; } @@ -192,29 +192,29 @@ namespace Ryujinx.HLE.HOS.Services.Lr } // RedirectProgramPath() - public long RedirectProgramPath(ServiceCtx Context) + public long RedirectProgramPath(ServiceCtx context) { - long TitleId = Context.RequestData.ReadInt64(); + long titleId = context.RequestData.ReadInt64(); - RedirectPath(Context, TitleId, 0, ContentType.Program); + RedirectPath(context, titleId, 0, ContentType.Program); return 0; } // Refresh() - public long Refresh(ServiceCtx Context) + public long Refresh(ServiceCtx context) { - Context.Device.System.ContentManager.RefreshEntries(StorageId, 1); + context.Device.System.ContentManager.RefreshEntries(_storageId, 1); return 0; } // ResolveProgramPath() - public long ResolveProgramPath(ServiceCtx Context) + public long ResolveProgramPath(ServiceCtx context) { - long TitleId = Context.RequestData.ReadInt64(); + long titleId = context.RequestData.ReadInt64(); - if (ResolvePath(Context, TitleId, ContentType.Program)) + if (ResolvePath(context, titleId, ContentType.Program)) { return 0; } @@ -224,27 +224,27 @@ namespace Ryujinx.HLE.HOS.Services.Lr } } - private void RedirectPath(ServiceCtx Context, long TitleId, int Flag, ContentType ContentType) + private void RedirectPath(ServiceCtx context, long titleId, int flag, ContentType contentType) { - string ContentPath = ReadUtf8String(Context); - LocationEntry NewLocation = new LocationEntry(ContentPath, Flag, TitleId, ContentType); + string contentPath = ReadUtf8String(context); + LocationEntry newLocation = new LocationEntry(contentPath, flag, titleId, contentType); - Context.Device.System.ContentManager.RedirectLocation(NewLocation, StorageId); + context.Device.System.ContentManager.RedirectLocation(newLocation, _storageId); } - private bool ResolvePath(ServiceCtx Context, long TitleId,ContentType ContentType) + private bool ResolvePath(ServiceCtx context, long titleId,ContentType contentType) { - ContentManager ContentManager = Context.Device.System.ContentManager; - string ContentPath = ContentManager.GetInstalledContentPath(TitleId, StorageId, ContentType.Program); + ContentManager contentManager = context.Device.System.ContentManager; + string contentPath = contentManager.GetInstalledContentPath(titleId, _storageId, ContentType.Program); - if (!string.IsNullOrWhiteSpace(ContentPath)) + if (!string.IsNullOrWhiteSpace(contentPath)) { - long Position = Context.Request.RecvListBuff[0].Position; - long Size = Context.Request.RecvListBuff[0].Size; + long position = context.Request.RecvListBuff[0].Position; + long size = context.Request.RecvListBuff[0].Size; - byte[] ContentPathBuffer = Encoding.UTF8.GetBytes(ContentPath); + byte[] contentPathBuffer = Encoding.UTF8.GetBytes(contentPath); - Context.Memory.WriteBytes(Position, ContentPathBuffer); + context.Memory.WriteBytes(position, contentPathBuffer); } else { @@ -254,12 +254,12 @@ namespace Ryujinx.HLE.HOS.Services.Lr return true; } - private void DeleteContentPath(ServiceCtx Context, long TitleId, ContentType ContentType) + private void DeleteContentPath(ServiceCtx context, long titleId, ContentType contentType) { - ContentManager ContentManager = Context.Device.System.ContentManager; - string ContentPath = ContentManager.GetInstalledContentPath(TitleId, StorageId, ContentType.Manual); + ContentManager contentManager = context.Device.System.ContentManager; + string contentPath = contentManager.GetInstalledContentPath(titleId, _storageId, ContentType.Manual); - ContentManager.ClearEntry(TitleId, ContentType.Manual, StorageId); + contentManager.ClearEntry(titleId, ContentType.Manual, _storageId); } } } diff --git a/Ryujinx.HLE/HOS/Services/Lr/ILocationResolverManager.cs b/Ryujinx.HLE/HOS/Services/Lr/ILocationResolverManager.cs index 77710f76..4b2de6b3 100644 --- a/Ryujinx.HLE/HOS/Services/Lr/ILocationResolverManager.cs +++ b/Ryujinx.HLE/HOS/Services/Lr/ILocationResolverManager.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using Ryujinx.HLE.HOS.Ipc; using Ryujinx.HLE.FileSystem; @@ -7,24 +6,24 @@ namespace Ryujinx.HLE.HOS.Services.Lr { class ILocationResolverManager : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public ILocationResolverManager() { - m_Commands = new Dictionary() + _commands = new Dictionary { - { 0, OpenLocationResolver }, + { 0, OpenLocationResolver } }; } // OpenLocationResolver() - private long OpenLocationResolver(ServiceCtx Context) + private long OpenLocationResolver(ServiceCtx context) { - StorageId StorageId = (StorageId)Context.RequestData.ReadByte(); + StorageId storageId = (StorageId)context.RequestData.ReadByte(); - MakeObject(Context, new ILocationResolver(StorageId)); + MakeObject(context, new ILocationResolver(storageId)); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Mm/IRequest.cs b/Ryujinx.HLE/HOS/Services/Mm/IRequest.cs index 72067d71..f1c6d6c9 100644 --- a/Ryujinx.HLE/HOS/Services/Mm/IRequest.cs +++ b/Ryujinx.HLE/HOS/Services/Mm/IRequest.cs @@ -6,13 +6,13 @@ namespace Ryujinx.HLE.HOS.Services.Mm { class IRequest : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IRequest() { - m_Commands = new Dictionary() + _commands = new Dictionary() { { 1, InitializeOld }, { 4, Initialize }, @@ -23,43 +23,43 @@ namespace Ryujinx.HLE.HOS.Services.Mm } // InitializeOld(u32, u32, u32) - public long InitializeOld(ServiceCtx Context) + public long InitializeOld(ServiceCtx context) { - int Unknown0 = Context.RequestData.ReadInt32(); - int Unknown1 = Context.RequestData.ReadInt32(); - int Unknown2 = Context.RequestData.ReadInt32(); + int unknown0 = context.RequestData.ReadInt32(); + int unknown1 = context.RequestData.ReadInt32(); + int unknown2 = context.RequestData.ReadInt32(); Logger.PrintStub(LogClass.ServiceMm, "Stubbed."); return 0; } - public long Initialize(ServiceCtx Context) + public long Initialize(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceMm, "Stubbed."); return 0; } - public long Finalize(ServiceCtx Context) + public long Finalize(ServiceCtx context) { - Context.Device.Gpu.UninitializeVideoDecoder(); + context.Device.Gpu.UninitializeVideoDecoder(); Logger.PrintStub(LogClass.ServiceMm, "Stubbed."); return 0; } - public long SetAndWait(ServiceCtx Context) + public long SetAndWait(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceMm, "Stubbed."); return 0; } - public long Get(ServiceCtx Context) + public long Get(ServiceCtx context) { - Context.ResponseData.Write(0); + context.ResponseData.Write(0); Logger.PrintStub(LogClass.ServiceMm, "Stubbed."); diff --git a/Ryujinx.HLE/HOS/Services/Ncm/IContentManager.cs b/Ryujinx.HLE/HOS/Services/Ncm/IContentManager.cs index 29792a1b..bd92a450 100644 --- a/Ryujinx.HLE/HOS/Services/Ncm/IContentManager.cs +++ b/Ryujinx.HLE/HOS/Services/Ncm/IContentManager.cs @@ -5,13 +5,13 @@ namespace Ryujinx.HLE.HOS.Services.Ncm { class IContentManager : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IContentManager() { - m_Commands = new Dictionary() + _commands = new Dictionary { }; diff --git a/Ryujinx.HLE/HOS/Services/Ncm/IContentStorage.cs b/Ryujinx.HLE/HOS/Services/Ncm/IContentStorage.cs index a19fe079..7134bb4c 100644 --- a/Ryujinx.HLE/HOS/Services/Ncm/IContentStorage.cs +++ b/Ryujinx.HLE/HOS/Services/Ncm/IContentStorage.cs @@ -5,13 +5,13 @@ namespace Ryujinx.HLE.HOS.Services.Ncm { class IContentStorage : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IContentStorage() { - m_Commands = new Dictionary() + _commands = new Dictionary { }; diff --git a/Ryujinx.HLE/HOS/Services/Nfp/IUser.cs b/Ryujinx.HLE/HOS/Services/Nfp/IUser.cs index f0dc825b..9e19e77f 100644 --- a/Ryujinx.HLE/HOS/Services/Nfp/IUser.cs +++ b/Ryujinx.HLE/HOS/Services/Nfp/IUser.cs @@ -9,25 +9,25 @@ namespace Ryujinx.HLE.HOS.Services.Nfp { class IUser : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - private const HidControllerId NpadId = HidControllerId.CONTROLLER_PLAYER_1; + private const HidControllerId NpadId = HidControllerId.ControllerPlayer1; - private State State = State.NonInitialized; + private State _state = State.NonInitialized; - private DeviceState DeviceState = DeviceState.Initialized; + private DeviceState _deviceState = DeviceState.Initialized; - private KEvent ActivateEvent; + private KEvent _activateEvent; - private KEvent DeactivateEvent; + private KEvent _deactivateEvent; - private KEvent AvailabilityChangeEvent; + private KEvent _availabilityChangeEvent; - public IUser(Horizon System) + public IUser(Horizon system) { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, Initialize }, { 17, AttachActivateEvent }, @@ -38,85 +38,85 @@ namespace Ryujinx.HLE.HOS.Services.Nfp { 23, AttachAvailabilityChangeEvent } }; - ActivateEvent = new KEvent(System); - DeactivateEvent = new KEvent(System); - AvailabilityChangeEvent = new KEvent(System); + _activateEvent = new KEvent(system); + _deactivateEvent = new KEvent(system); + _availabilityChangeEvent = new KEvent(system); } - public long Initialize(ServiceCtx Context) + public long Initialize(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceNfp, "Stubbed."); - State = State.Initialized; + _state = State.Initialized; return 0; } - public long AttachActivateEvent(ServiceCtx Context) + public long AttachActivateEvent(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceNfp, "Stubbed."); - if (Context.Process.HandleTable.GenerateHandle(ActivateEvent.ReadableEvent, out int Handle) != KernelResult.Success) + if (context.Process.HandleTable.GenerateHandle(_activateEvent.ReadableEvent, out int handle) != KernelResult.Success) { throw new InvalidOperationException("Out of handles!"); } - Context.Response.HandleDesc = IpcHandleDesc.MakeCopy(Handle);; + context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); return 0; } - public long AttachDeactivateEvent(ServiceCtx Context) + public long AttachDeactivateEvent(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceNfp, "Stubbed."); - if (Context.Process.HandleTable.GenerateHandle(DeactivateEvent.ReadableEvent, out int Handle) != KernelResult.Success) + if (context.Process.HandleTable.GenerateHandle(_deactivateEvent.ReadableEvent, out int handle) != KernelResult.Success) { throw new InvalidOperationException("Out of handles!"); } - Context.Response.HandleDesc = IpcHandleDesc.MakeCopy(Handle); + context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); return 0; } - public long GetState(ServiceCtx Context) + public long GetState(ServiceCtx context) { - Context.ResponseData.Write((int)State); + context.ResponseData.Write((int)_state); Logger.PrintStub(LogClass.ServiceNfp, "Stubbed."); return 0; } - public long GetDeviceState(ServiceCtx Context) + public long GetDeviceState(ServiceCtx context) { - Context.ResponseData.Write((int)DeviceState); + context.ResponseData.Write((int)_deviceState); Logger.PrintStub(LogClass.ServiceNfp, "Stubbed."); return 0; } - public long GetNpadId(ServiceCtx Context) + public long GetNpadId(ServiceCtx context) { - Context.ResponseData.Write((int)NpadId); + context.ResponseData.Write((int)NpadId); Logger.PrintStub(LogClass.ServiceNfp, "Stubbed."); return 0; } - public long AttachAvailabilityChangeEvent(ServiceCtx Context) + public long AttachAvailabilityChangeEvent(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceNfp, "Stubbed."); - if (Context.Process.HandleTable.GenerateHandle(AvailabilityChangeEvent.ReadableEvent, out int Handle) != KernelResult.Success) + if (context.Process.HandleTable.GenerateHandle(_availabilityChangeEvent.ReadableEvent, out int handle) != KernelResult.Success) { throw new InvalidOperationException("Out of handles!"); } - Context.Response.HandleDesc = IpcHandleDesc.MakeCopy(Handle); + context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Nfp/IUserManager.cs b/Ryujinx.HLE/HOS/Services/Nfp/IUserManager.cs index e5d5a4f1..1bf93746 100644 --- a/Ryujinx.HLE/HOS/Services/Nfp/IUserManager.cs +++ b/Ryujinx.HLE/HOS/Services/Nfp/IUserManager.cs @@ -5,21 +5,21 @@ namespace Ryujinx.HLE.HOS.Services.Nfp { class IUserManager : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IUserManager() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, GetUserInterface } }; } - public long GetUserInterface(ServiceCtx Context) + public long GetUserInterface(ServiceCtx context) { - MakeObject(Context, new IUser(Context.Device.System)); + MakeObject(context, new IUser(context.Device.System)); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Nifm/IGeneralService.cs b/Ryujinx.HLE/HOS/Services/Nifm/IGeneralService.cs index bc23ea91..4b87c2c7 100644 --- a/Ryujinx.HLE/HOS/Services/Nifm/IGeneralService.cs +++ b/Ryujinx.HLE/HOS/Services/Nifm/IGeneralService.cs @@ -13,44 +13,44 @@ namespace Ryujinx.HLE.HOS.Services.Nifm { class IGeneralService : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IGeneralService() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 4, CreateRequest }, { 12, GetCurrentIpAddress } }; } - public long CreateRequest(ServiceCtx Context) + public long CreateRequest(ServiceCtx context) { - int Unknown = Context.RequestData.ReadInt32(); + int unknown = context.RequestData.ReadInt32(); - MakeObject(Context, new IRequest(Context.Device.System)); + MakeObject(context, new IRequest(context.Device.System)); Logger.PrintStub(LogClass.ServiceNifm, "Stubbed."); return 0; } - public long GetCurrentIpAddress(ServiceCtx Context) + public long GetCurrentIpAddress(ServiceCtx context) { if (!NetworkInterface.GetIsNetworkAvailable()) { return MakeError(ErrorModule.Nifm, NifmErr.NoInternetConnection); } - IPHostEntry Host = Dns.GetHostEntry(Dns.GetHostName()); + IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName()); - IPAddress Address = Host.AddressList.FirstOrDefault(A => A.AddressFamily == AddressFamily.InterNetwork); + IPAddress address = host.AddressList.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork); - Context.ResponseData.Write(BitConverter.ToUInt32(Address.GetAddressBytes())); + context.ResponseData.Write(BitConverter.ToUInt32(address.GetAddressBytes())); - Logger.PrintInfo(LogClass.ServiceNifm, $"Console's local IP is \"{Address}\"."); + Logger.PrintInfo(LogClass.ServiceNifm, $"Console's local IP is \"{address}\"."); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Nifm/IRequest.cs b/Ryujinx.HLE/HOS/Services/Nifm/IRequest.cs index 98327860..52adce9e 100644 --- a/Ryujinx.HLE/HOS/Services/Nifm/IRequest.cs +++ b/Ryujinx.HLE/HOS/Services/Nifm/IRequest.cs @@ -8,16 +8,16 @@ namespace Ryujinx.HLE.HOS.Services.Nifm { class IRequest : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - private KEvent Event0; - private KEvent Event1; + private KEvent _event0; + private KEvent _event1; - public IRequest(Horizon System) + public IRequest(Horizon system) { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, GetRequestState }, { 1, GetResult }, @@ -27,58 +27,58 @@ namespace Ryujinx.HLE.HOS.Services.Nifm { 11, SetConnectionConfirmationOption } }; - Event0 = new KEvent(System); - Event1 = new KEvent(System); + _event0 = new KEvent(system); + _event1 = new KEvent(system); } - public long GetRequestState(ServiceCtx Context) + public long GetRequestState(ServiceCtx context) { - Context.ResponseData.Write(1); + context.ResponseData.Write(1); Logger.PrintStub(LogClass.ServiceNifm, "Stubbed."); return 0; } - public long GetResult(ServiceCtx Context) + public long GetResult(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceNifm, "Stubbed."); return 0; } - public long GetSystemEventReadableHandles(ServiceCtx Context) + public long GetSystemEventReadableHandles(ServiceCtx context) { - if (Context.Process.HandleTable.GenerateHandle(Event0.ReadableEvent, out int Handle0) != KernelResult.Success) + if (context.Process.HandleTable.GenerateHandle(_event0.ReadableEvent, out int handle0) != KernelResult.Success) { throw new InvalidOperationException("Out of handles!"); } - if (Context.Process.HandleTable.GenerateHandle(Event1.ReadableEvent, out int Handle1) != KernelResult.Success) + if (context.Process.HandleTable.GenerateHandle(_event1.ReadableEvent, out int handle1) != KernelResult.Success) { throw new InvalidOperationException("Out of handles!"); } - Context.Response.HandleDesc = IpcHandleDesc.MakeCopy(Handle0, Handle1); + context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle0, handle1); return 0; } - public long Cancel(ServiceCtx Context) + public long Cancel(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceNifm, "Stubbed."); return 0; } - public long Submit(ServiceCtx Context) + public long Submit(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceNifm, "Stubbed."); return 0; } - public long SetConnectionConfirmationOption(ServiceCtx Context) + public long SetConnectionConfirmationOption(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceNifm, "Stubbed."); diff --git a/Ryujinx.HLE/HOS/Services/Nifm/IStaticService.cs b/Ryujinx.HLE/HOS/Services/Nifm/IStaticService.cs index 19e7d247..42d9c78e 100644 --- a/Ryujinx.HLE/HOS/Services/Nifm/IStaticService.cs +++ b/Ryujinx.HLE/HOS/Services/Nifm/IStaticService.cs @@ -5,29 +5,29 @@ namespace Ryujinx.HLE.HOS.Services.Nifm { class IStaticService : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IStaticService() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 4, CreateGeneralServiceOld }, { 5, CreateGeneralService } }; } - public long CreateGeneralServiceOld(ServiceCtx Context) + public long CreateGeneralServiceOld(ServiceCtx context) { - MakeObject(Context, new IGeneralService()); + MakeObject(context, new IGeneralService()); return 0; } - public long CreateGeneralService(ServiceCtx Context) + public long CreateGeneralService(ServiceCtx context) { - MakeObject(Context, new IGeneralService()); + MakeObject(context, new IGeneralService()); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Ns/IAddOnContentManager.cs b/Ryujinx.HLE/HOS/Services/Ns/IAddOnContentManager.cs index 82fce6b9..8bbd0dea 100644 --- a/Ryujinx.HLE/HOS/Services/Ns/IAddOnContentManager.cs +++ b/Ryujinx.HLE/HOS/Services/Ns/IAddOnContentManager.cs @@ -6,35 +6,35 @@ namespace Ryujinx.HLE.HOS.Services.Ns { class IAddOnContentManager : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IAddOnContentManager() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 2, CountAddOnContent }, { 3, ListAddOnContent } }; } - public static long CountAddOnContent(ServiceCtx Context) + public static long CountAddOnContent(ServiceCtx context) { - Context.ResponseData.Write(0); + context.ResponseData.Write(0); Logger.PrintStub(LogClass.ServiceNs, "Stubbed."); return 0; } - public static long ListAddOnContent(ServiceCtx Context) + public static long ListAddOnContent(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceNs, "Stubbed."); //TODO: This is supposed to write a u32 array aswell. //It's unknown what it contains. - Context.ResponseData.Write(0); + context.ResponseData.Write(0); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Ns/IApplicationManagerInterface.cs b/Ryujinx.HLE/HOS/Services/Ns/IApplicationManagerInterface.cs index ee438d99..72d7787f 100644 --- a/Ryujinx.HLE/HOS/Services/Ns/IApplicationManagerInterface.cs +++ b/Ryujinx.HLE/HOS/Services/Ns/IApplicationManagerInterface.cs @@ -1,20 +1,19 @@ using Ryujinx.HLE.HOS.Ipc; -using Ryujinx.HLE.HOS.Kernel; using System.Collections.Generic; namespace Ryujinx.HLE.HOS.Services.Ns { class IApplicationManagerInterface : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - private bool IsInitialized; + private bool _isInitialized; public IApplicationManagerInterface() { - m_Commands = new Dictionary() + _commands = new Dictionary { }; diff --git a/Ryujinx.HLE/HOS/Services/Ns/IServiceGetterInterface.cs b/Ryujinx.HLE/HOS/Services/Ns/IServiceGetterInterface.cs index a27cfe60..12f7b69b 100644 --- a/Ryujinx.HLE/HOS/Services/Ns/IServiceGetterInterface.cs +++ b/Ryujinx.HLE/HOS/Services/Ns/IServiceGetterInterface.cs @@ -5,13 +5,13 @@ namespace Ryujinx.HLE.HOS.Services.Ns { class IServiceGetterInterface : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IServiceGetterInterface() { - m_Commands = new Dictionary() + _commands = new Dictionary { //... }; diff --git a/Ryujinx.HLE/HOS/Services/Ns/ISystemUpdateInterface.cs b/Ryujinx.HLE/HOS/Services/Ns/ISystemUpdateInterface.cs index 6ade8865..1b898561 100644 --- a/Ryujinx.HLE/HOS/Services/Ns/ISystemUpdateInterface.cs +++ b/Ryujinx.HLE/HOS/Services/Ns/ISystemUpdateInterface.cs @@ -5,13 +5,13 @@ namespace Ryujinx.HLE.HOS.Services.Ns { class ISystemUpdateInterface : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public ISystemUpdateInterface() { - m_Commands = new Dictionary() + _commands = new Dictionary { //... }; diff --git a/Ryujinx.HLE/HOS/Services/Ns/IVulnerabilityManagerInterface.cs b/Ryujinx.HLE/HOS/Services/Ns/IVulnerabilityManagerInterface.cs index cff334c0..922703ec 100644 --- a/Ryujinx.HLE/HOS/Services/Ns/IVulnerabilityManagerInterface.cs +++ b/Ryujinx.HLE/HOS/Services/Ns/IVulnerabilityManagerInterface.cs @@ -5,13 +5,13 @@ namespace Ryujinx.HLE.HOS.Services.Ns { class IVulnerabilityManagerInterface : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IVulnerabilityManagerInterface() { - m_Commands = new Dictionary() + _commands = new Dictionary { //... }; diff --git a/Ryujinx.HLE/HOS/Services/Nv/INvDrvServices.cs b/Ryujinx.HLE/HOS/Services/Nv/INvDrvServices.cs index 1b034bfa..1ed97dde 100644 --- a/Ryujinx.HLE/HOS/Services/Nv/INvDrvServices.cs +++ b/Ryujinx.HLE/HOS/Services/Nv/INvDrvServices.cs @@ -14,13 +14,13 @@ namespace Ryujinx.HLE.HOS.Services.Nv { class INvDrvServices : IpcService { - private delegate int IoctlProcessor(ServiceCtx Context, int Cmd); + private delegate int IoctlProcessor(ServiceCtx context, int cmd); - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - private static Dictionary IoctlProcessors = + private static Dictionary _ioctlProcessors = new Dictionary() { { "/dev/nvhost-as-gpu", ProcessIoctlNvGpuAS }, @@ -34,11 +34,11 @@ namespace Ryujinx.HLE.HOS.Services.Nv public static GlobalStateTable Fds { get; private set; } - private KEvent Event; + private KEvent _event; - public INvDrvServices(Horizon System) + public INvDrvServices(Horizon system) { - m_Commands = new Dictionary() + _commands = new Dictionary() { { 0, Open }, { 1, Ioctl }, @@ -50,7 +50,7 @@ namespace Ryujinx.HLE.HOS.Services.Nv { 13, FinishInitialize } }; - Event = new KEvent(System); + _event = new KEvent(system); } static INvDrvServices() @@ -58,166 +58,166 @@ namespace Ryujinx.HLE.HOS.Services.Nv Fds = new GlobalStateTable(); } - public long Open(ServiceCtx Context) + public long Open(ServiceCtx context) { - long NamePtr = Context.Request.SendBuff[0].Position; + long namePtr = context.Request.SendBuff[0].Position; - string Name = MemoryHelper.ReadAsciiString(Context.Memory, NamePtr); + string name = MemoryHelper.ReadAsciiString(context.Memory, namePtr); - int Fd = Fds.Add(Context.Process, new NvFd(Name)); + int fd = Fds.Add(context.Process, new NvFd(name)); - Context.ResponseData.Write(Fd); - Context.ResponseData.Write(0); + context.ResponseData.Write(fd); + context.ResponseData.Write(0); return 0; } - public long Ioctl(ServiceCtx Context) + public long Ioctl(ServiceCtx context) { - int Fd = Context.RequestData.ReadInt32(); - int Cmd = Context.RequestData.ReadInt32(); + int fd = context.RequestData.ReadInt32(); + int cmd = context.RequestData.ReadInt32(); - NvFd FdData = Fds.GetData(Context.Process, Fd); + NvFd fdData = Fds.GetData(context.Process, fd); - int Result; + int result; - if (IoctlProcessors.TryGetValue(FdData.Name, out IoctlProcessor Process)) + if (_ioctlProcessors.TryGetValue(fdData.Name, out IoctlProcessor process)) { - Result = Process(Context, Cmd); + result = process(context, cmd); } else { - throw new NotImplementedException($"{FdData.Name} {Cmd:x4}"); + throw new NotImplementedException($"{fdData.Name} {cmd:x4}"); } //TODO: Verify if the error codes needs to be translated. - Context.ResponseData.Write(Result); + context.ResponseData.Write(result); return 0; } - public long Close(ServiceCtx Context) + public long Close(ServiceCtx context) { - int Fd = Context.RequestData.ReadInt32(); + int fd = context.RequestData.ReadInt32(); - Fds.Delete(Context.Process, Fd); + Fds.Delete(context.Process, fd); - Context.ResponseData.Write(0); + context.ResponseData.Write(0); return 0; } - public long Initialize(ServiceCtx Context) + public long Initialize(ServiceCtx context) { - long TransferMemSize = Context.RequestData.ReadInt64(); - int TransferMemHandle = Context.Request.HandleDesc.ToCopy[0]; + long transferMemSize = context.RequestData.ReadInt64(); + int transferMemHandle = context.Request.HandleDesc.ToCopy[0]; - NvMapIoctl.InitializeNvMap(Context); + NvMapIoctl.InitializeNvMap(context); - Context.ResponseData.Write(0); + context.ResponseData.Write(0); return 0; } - public long QueryEvent(ServiceCtx Context) + public long QueryEvent(ServiceCtx context) { - int Fd = Context.RequestData.ReadInt32(); - int EventId = Context.RequestData.ReadInt32(); + int fd = context.RequestData.ReadInt32(); + int eventId = context.RequestData.ReadInt32(); //TODO: Use Fd/EventId, different channels have different events. - if (Context.Process.HandleTable.GenerateHandle(Event.ReadableEvent, out int Handle) != KernelResult.Success) + if (context.Process.HandleTable.GenerateHandle(_event.ReadableEvent, out int handle) != KernelResult.Success) { throw new InvalidOperationException("Out of handles!"); } - Context.Response.HandleDesc = IpcHandleDesc.MakeCopy(Handle); + context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); - Context.ResponseData.Write(0); + context.ResponseData.Write(0); return 0; } - public long SetClientPid(ServiceCtx Context) + public long SetClientPid(ServiceCtx context) { - long Pid = Context.RequestData.ReadInt64(); + long pid = context.RequestData.ReadInt64(); - Context.ResponseData.Write(0); + context.ResponseData.Write(0); return 0; } - public long FinishInitialize(ServiceCtx Context) + public long FinishInitialize(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceNv, "Stubbed."); return 0; } - private static int ProcessIoctlNvGpuAS(ServiceCtx Context, int Cmd) + private static int ProcessIoctlNvGpuAS(ServiceCtx context, int cmd) { - return ProcessIoctl(Context, Cmd, NvGpuASIoctl.ProcessIoctl); + return ProcessIoctl(context, cmd, NvGpuASIoctl.ProcessIoctl); } - private static int ProcessIoctlNvHostCtrl(ServiceCtx Context, int Cmd) + private static int ProcessIoctlNvHostCtrl(ServiceCtx context, int cmd) { - return ProcessIoctl(Context, Cmd, NvHostCtrlIoctl.ProcessIoctl); + return ProcessIoctl(context, cmd, NvHostCtrlIoctl.ProcessIoctl); } - private static int ProcessIoctlNvGpuGpu(ServiceCtx Context, int Cmd) + private static int ProcessIoctlNvGpuGpu(ServiceCtx context, int cmd) { - return ProcessIoctl(Context, Cmd, NvGpuGpuIoctl.ProcessIoctl); + return ProcessIoctl(context, cmd, NvGpuGpuIoctl.ProcessIoctl); } - private static int ProcessIoctlNvHostChannel(ServiceCtx Context, int Cmd) + private static int ProcessIoctlNvHostChannel(ServiceCtx context, int cmd) { - return ProcessIoctl(Context, Cmd, NvHostChannelIoctl.ProcessIoctl); + return ProcessIoctl(context, cmd, NvHostChannelIoctl.ProcessIoctl); } - private static int ProcessIoctlNvMap(ServiceCtx Context, int Cmd) + private static int ProcessIoctlNvMap(ServiceCtx context, int cmd) { - return ProcessIoctl(Context, Cmd, NvMapIoctl.ProcessIoctl); + return ProcessIoctl(context, cmd, NvMapIoctl.ProcessIoctl); } - private static int ProcessIoctl(ServiceCtx Context, int Cmd, IoctlProcessor Processor) + private static int ProcessIoctl(ServiceCtx context, int cmd, IoctlProcessor processor) { - if (CmdIn(Cmd) && Context.Request.GetBufferType0x21().Position == 0) + if (CmdIn(cmd) && context.Request.GetBufferType0x21().Position == 0) { Logger.PrintError(LogClass.ServiceNv, "Input buffer is null!"); return NvResult.InvalidInput; } - if (CmdOut(Cmd) && Context.Request.GetBufferType0x22().Position == 0) + if (CmdOut(cmd) && context.Request.GetBufferType0x22().Position == 0) { Logger.PrintError(LogClass.ServiceNv, "Output buffer is null!"); return NvResult.InvalidInput; } - return Processor(Context, Cmd); + return processor(context, cmd); } - private static bool CmdIn(int Cmd) + private static bool CmdIn(int cmd) { - return ((Cmd >> 30) & 1) != 0; + return ((cmd >> 30) & 1) != 0; } - private static bool CmdOut(int Cmd) + private static bool CmdOut(int cmd) { - return ((Cmd >> 31) & 1) != 0; + return ((cmd >> 31) & 1) != 0; } - public static void UnloadProcess(KProcess Process) + public static void UnloadProcess(KProcess process) { - Fds.DeleteProcess(Process); + Fds.DeleteProcess(process); - NvGpuASIoctl.UnloadProcess(Process); + NvGpuASIoctl.UnloadProcess(process); - NvHostChannelIoctl.UnloadProcess(Process); + NvHostChannelIoctl.UnloadProcess(process); - NvHostCtrlIoctl.UnloadProcess(Process); + NvHostCtrlIoctl.UnloadProcess(process); - NvMapIoctl.UnloadProcess(Process); + NvMapIoctl.UnloadProcess(process); } } } diff --git a/Ryujinx.HLE/HOS/Services/Nv/NvFd.cs b/Ryujinx.HLE/HOS/Services/Nv/NvFd.cs index 96f97f41..b6c654e4 100644 --- a/Ryujinx.HLE/HOS/Services/Nv/NvFd.cs +++ b/Ryujinx.HLE/HOS/Services/Nv/NvFd.cs @@ -4,9 +4,9 @@ namespace Ryujinx.HLE.HOS.Services.Nv { public string Name { get; private set; } - public NvFd(string Name) + public NvFd(string name) { - this.Name = Name; + Name = name; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Services/Nv/NvGpuAS/NvGpuASCtx.cs b/Ryujinx.HLE/HOS/Services/Nv/NvGpuAS/NvGpuASCtx.cs index 70275b2a..67b80e33 100644 --- a/Ryujinx.HLE/HOS/Services/Nv/NvGpuAS/NvGpuASCtx.cs +++ b/Ryujinx.HLE/HOS/Services/Nv/NvGpuAS/NvGpuASCtx.cs @@ -12,10 +12,10 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvGpuAS public ulong Start { get; private set; } public ulong End { get; private set; } - public Range(long Position, long Size) + public Range(long position, long size) { - Start = (ulong)Position; - End = (ulong)Size + Start; + Start = (ulong)position; + End = (ulong)size + Start; } } @@ -25,53 +25,53 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvGpuAS public bool VaAllocated { get; private set; } public MappedMemory( - long Position, - long Size, - long PhysicalAddress, - bool VaAllocated) : base(Position, Size) + long position, + long size, + long physicalAddress, + bool vaAllocated) : base(position, size) { - this.PhysicalAddress = PhysicalAddress; - this.VaAllocated = VaAllocated; + PhysicalAddress = physicalAddress; + VaAllocated = vaAllocated; } } - private SortedList Maps; - private SortedList Reservations; + private SortedList _maps; + private SortedList _reservations; - public NvGpuASCtx(ServiceCtx Context) + public NvGpuASCtx(ServiceCtx context) { - Vmm = new NvGpuVmm(Context.Memory); + Vmm = new NvGpuVmm(context.Memory); - Maps = new SortedList(); - Reservations = new SortedList(); + _maps = new SortedList(); + _reservations = new SortedList(); } - public bool ValidateFixedBuffer(long Position, long Size) + public bool ValidateFixedBuffer(long position, long size) { - long MapEnd = Position + Size; + long mapEnd = position + size; //Check if size is valid (0 is also not allowed). - if ((ulong)MapEnd <= (ulong)Position) + if ((ulong)mapEnd <= (ulong)position) { return false; } //Check if address is page aligned. - if ((Position & NvGpuVmm.PageMask) != 0) + if ((position & NvGpuVmm.PageMask) != 0) { return false; } //Check if region is reserved. - if (BinarySearch(Reservations, Position) == null) + if (BinarySearch(_reservations, position) == null) { return false; } //Check for overlap with already mapped buffers. - Range Map = BinarySearchLt(Maps, MapEnd); + Range map = BinarySearchLt(_maps, mapEnd); - if (Map != null && Map.End > (ulong)Position) + if (map != null && map.End > (ulong)position) { return false; } @@ -80,25 +80,25 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvGpuAS } public void AddMap( - long Position, - long Size, - long PhysicalAddress, - bool VaAllocated) + long position, + long size, + long physicalAddress, + bool vaAllocated) { - Maps.Add(Position, new MappedMemory(Position, Size, PhysicalAddress, VaAllocated)); + _maps.Add(position, new MappedMemory(position, size, physicalAddress, vaAllocated)); } - public bool RemoveMap(long Position, out long Size) + public bool RemoveMap(long position, out long size) { - Size = 0; + size = 0; - if (Maps.Remove(Position, out Range Value)) + if (_maps.Remove(position, out Range value)) { - MappedMemory Map = (MappedMemory)Value; + MappedMemory map = (MappedMemory)value; - if (Map.VaAllocated) + if (map.VaAllocated) { - Size = (long)(Map.End - Map.Start); + size = (long)(map.End - map.Start); } return true; @@ -107,94 +107,94 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvGpuAS return false; } - public bool TryGetMapPhysicalAddress(long Position, out long PhysicalAddress) + public bool TryGetMapPhysicalAddress(long position, out long physicalAddress) { - Range Map = BinarySearch(Maps, Position); + Range map = BinarySearch(_maps, position); - if (Map != null) + if (map != null) { - PhysicalAddress = ((MappedMemory)Map).PhysicalAddress; + physicalAddress = ((MappedMemory)map).PhysicalAddress; return true; } - PhysicalAddress = 0; + physicalAddress = 0; return false; } - public void AddReservation(long Position, long Size) + public void AddReservation(long position, long size) { - Reservations.Add(Position, new Range(Position, Size)); + _reservations.Add(position, new Range(position, size)); } - public bool RemoveReservation(long Position) + public bool RemoveReservation(long position) { - return Reservations.Remove(Position); + return _reservations.Remove(position); } - private Range BinarySearch(SortedList Lst, long Position) + private Range BinarySearch(SortedList lst, long position) { - int Left = 0; - int Right = Lst.Count - 1; + int left = 0; + int right = lst.Count - 1; - while (Left <= Right) + while (left <= right) { - int Size = Right - Left; + int size = right - left; - int Middle = Left + (Size >> 1); + int middle = left + (size >> 1); - Range Rg = Lst.Values[Middle]; + Range rg = lst.Values[middle]; - if ((ulong)Position >= Rg.Start && (ulong)Position < Rg.End) + if ((ulong)position >= rg.Start && (ulong)position < rg.End) { - return Rg; + return rg; } - if ((ulong)Position < Rg.Start) + if ((ulong)position < rg.Start) { - Right = Middle - 1; + right = middle - 1; } else { - Left = Middle + 1; + left = middle + 1; } } return null; } - private Range BinarySearchLt(SortedList Lst, long Position) + private Range BinarySearchLt(SortedList lst, long position) { - Range LtRg = null; + Range ltRg = null; - int Left = 0; - int Right = Lst.Count - 1; + int left = 0; + int right = lst.Count - 1; - while (Left <= Right) + while (left <= right) { - int Size = Right - Left; + int size = right - left; - int Middle = Left + (Size >> 1); + int middle = left + (size >> 1); - Range Rg = Lst.Values[Middle]; + Range rg = lst.Values[middle]; - if ((ulong)Position < Rg.Start) + if ((ulong)position < rg.Start) { - Right = Middle - 1; + right = middle - 1; } else { - Left = Middle + 1; + left = middle + 1; - if ((ulong)Position > Rg.Start) + if ((ulong)position > rg.Start) { - LtRg = Rg; + ltRg = rg; } } } - return LtRg; + return ltRg; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Services/Nv/NvGpuAS/NvGpuASIoctl.cs b/Ryujinx.HLE/HOS/Services/Nv/NvGpuAS/NvGpuASIoctl.cs index 7fe3bbed..8e128a0d 100644 --- a/Ryujinx.HLE/HOS/Services/Nv/NvGpuAS/NvGpuASIoctl.cs +++ b/Ryujinx.HLE/HOS/Services/Nv/NvGpuAS/NvGpuASIoctl.cs @@ -14,182 +14,182 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvGpuAS private const int FlagRemapSubRange = 0x100; - private static ConcurrentDictionary ASCtxs; + private static ConcurrentDictionary _asCtxs; static NvGpuASIoctl() { - ASCtxs = new ConcurrentDictionary(); + _asCtxs = new ConcurrentDictionary(); } - public static int ProcessIoctl(ServiceCtx Context, int Cmd) + public static int ProcessIoctl(ServiceCtx context, int cmd) { - switch (Cmd & 0xffff) + switch (cmd & 0xffff) { - case 0x4101: return BindChannel (Context); - case 0x4102: return AllocSpace (Context); - case 0x4103: return FreeSpace (Context); - case 0x4105: return UnmapBuffer (Context); - case 0x4106: return MapBufferEx (Context); - case 0x4108: return GetVaRegions(Context); - case 0x4109: return InitializeEx(Context); - case 0x4114: return Remap (Context, Cmd); + case 0x4101: return BindChannel (context); + case 0x4102: return AllocSpace (context); + case 0x4103: return FreeSpace (context); + case 0x4105: return UnmapBuffer (context); + case 0x4106: return MapBufferEx (context); + case 0x4108: return GetVaRegions(context); + case 0x4109: return InitializeEx(context); + case 0x4114: return Remap (context, cmd); } - throw new NotImplementedException(Cmd.ToString("x8")); + throw new NotImplementedException(cmd.ToString("x8")); } - private static int BindChannel(ServiceCtx Context) + private static int BindChannel(ServiceCtx context) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; Logger.PrintStub(LogClass.ServiceNv, "Stubbed."); return NvResult.Success; } - private static int AllocSpace(ServiceCtx Context) + private static int AllocSpace(ServiceCtx context) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; - NvGpuASAllocSpace Args = MemoryHelper.Read(Context.Memory, InputPosition); + NvGpuASAllocSpace args = MemoryHelper.Read(context.Memory, inputPosition); - NvGpuASCtx ASCtx = GetASCtx(Context); + NvGpuASCtx asCtx = GetASCtx(context); - ulong Size = (ulong)Args.Pages * - (ulong)Args.PageSize; + ulong size = (ulong)args.Pages * + (ulong)args.PageSize; - int Result = NvResult.Success; + int result = NvResult.Success; - lock (ASCtx) + lock (asCtx) { //Note: When the fixed offset flag is not set, //the Offset field holds the alignment size instead. - if ((Args.Flags & FlagFixedOffset) != 0) + if ((args.Flags & FlagFixedOffset) != 0) { - Args.Offset = ASCtx.Vmm.ReserveFixed(Args.Offset, (long)Size); + args.Offset = asCtx.Vmm.ReserveFixed(args.Offset, (long)size); } else { - Args.Offset = ASCtx.Vmm.Reserve((long)Size, Args.Offset); + args.Offset = asCtx.Vmm.Reserve((long)size, args.Offset); } - if (Args.Offset < 0) + if (args.Offset < 0) { - Args.Offset = 0; + args.Offset = 0; - Logger.PrintWarning(LogClass.ServiceNv, $"Failed to allocate size {Size:x16}!"); + Logger.PrintWarning(LogClass.ServiceNv, $"Failed to allocate size {size:x16}!"); - Result = NvResult.OutOfMemory; + result = NvResult.OutOfMemory; } else { - ASCtx.AddReservation(Args.Offset, (long)Size); + asCtx.AddReservation(args.Offset, (long)size); } } - MemoryHelper.Write(Context.Memory, OutputPosition, Args); + MemoryHelper.Write(context.Memory, outputPosition, args); - return Result; + return result; } - private static int FreeSpace(ServiceCtx Context) + private static int FreeSpace(ServiceCtx context) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; - NvGpuASAllocSpace Args = MemoryHelper.Read(Context.Memory, InputPosition); + NvGpuASAllocSpace args = MemoryHelper.Read(context.Memory, inputPosition); - NvGpuASCtx ASCtx = GetASCtx(Context); + NvGpuASCtx asCtx = GetASCtx(context); - int Result = NvResult.Success; + int result = NvResult.Success; - lock (ASCtx) + lock (asCtx) { - ulong Size = (ulong)Args.Pages * - (ulong)Args.PageSize; + ulong size = (ulong)args.Pages * + (ulong)args.PageSize; - if (ASCtx.RemoveReservation(Args.Offset)) + if (asCtx.RemoveReservation(args.Offset)) { - ASCtx.Vmm.Free(Args.Offset, (long)Size); + asCtx.Vmm.Free(args.Offset, (long)size); } else { Logger.PrintWarning(LogClass.ServiceNv, - $"Failed to free offset 0x{Args.Offset:x16} size 0x{Size:x16}!"); + $"Failed to free offset 0x{args.Offset:x16} size 0x{size:x16}!"); - Result = NvResult.InvalidInput; + result = NvResult.InvalidInput; } } - return Result; + return result; } - private static int UnmapBuffer(ServiceCtx Context) + private static int UnmapBuffer(ServiceCtx context) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; - NvGpuASUnmapBuffer Args = MemoryHelper.Read(Context.Memory, InputPosition); + NvGpuASUnmapBuffer args = MemoryHelper.Read(context.Memory, inputPosition); - NvGpuASCtx ASCtx = GetASCtx(Context); + NvGpuASCtx asCtx = GetASCtx(context); - lock (ASCtx) + lock (asCtx) { - if (ASCtx.RemoveMap(Args.Offset, out long Size)) + if (asCtx.RemoveMap(args.Offset, out long size)) { - if (Size != 0) + if (size != 0) { - ASCtx.Vmm.Free(Args.Offset, Size); + asCtx.Vmm.Free(args.Offset, size); } } else { - Logger.PrintWarning(LogClass.ServiceNv, $"Invalid buffer offset {Args.Offset:x16}!"); + Logger.PrintWarning(LogClass.ServiceNv, $"Invalid buffer offset {args.Offset:x16}!"); } } return NvResult.Success; } - private static int MapBufferEx(ServiceCtx Context) + private static int MapBufferEx(ServiceCtx context) { - const string MapErrorMsg = "Failed to map fixed buffer with offset 0x{0:x16} and size 0x{1:x16}!"; + const string mapErrorMsg = "Failed to map fixed buffer with offset 0x{0:x16} and size 0x{1:x16}!"; - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; - NvGpuASMapBufferEx Args = MemoryHelper.Read(Context.Memory, InputPosition); + NvGpuASMapBufferEx args = MemoryHelper.Read(context.Memory, inputPosition); - NvGpuASCtx ASCtx = GetASCtx(Context); + NvGpuASCtx asCtx = GetASCtx(context); - NvMapHandle Map = NvMapIoctl.GetNvMapWithFb(Context, Args.NvMapHandle); + NvMapHandle map = NvMapIoctl.GetNvMapWithFb(context, args.NvMapHandle); - if (Map == null) + if (map == null) { - Logger.PrintWarning(LogClass.ServiceNv, $"Invalid NvMap handle 0x{Args.NvMapHandle:x8}!"); + Logger.PrintWarning(LogClass.ServiceNv, $"Invalid NvMap handle 0x{args.NvMapHandle:x8}!"); return NvResult.InvalidInput; } - long PA; + long pa; - if ((Args.Flags & FlagRemapSubRange) != 0) + if ((args.Flags & FlagRemapSubRange) != 0) { - lock (ASCtx) + lock (asCtx) { - if (ASCtx.TryGetMapPhysicalAddress(Args.Offset, out PA)) + if (asCtx.TryGetMapPhysicalAddress(args.Offset, out pa)) { - long VA = Args.Offset + Args.BufferOffset; + long va = args.Offset + args.BufferOffset; - PA += Args.BufferOffset; + pa += args.BufferOffset; - if (ASCtx.Vmm.Map(PA, VA, Args.MappingSize) < 0) + if (asCtx.Vmm.Map(pa, va, args.MappingSize) < 0) { - string Msg = string.Format(MapErrorMsg, VA, Args.MappingSize); + string msg = string.Format(mapErrorMsg, va, args.MappingSize); - Logger.PrintWarning(LogClass.ServiceNv, Msg); + Logger.PrintWarning(LogClass.ServiceNv, msg); return NvResult.InvalidInput; } @@ -198,117 +198,117 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvGpuAS } else { - Logger.PrintWarning(LogClass.ServiceNv, $"Address 0x{Args.Offset:x16} not mapped!"); + Logger.PrintWarning(LogClass.ServiceNv, $"Address 0x{args.Offset:x16} not mapped!"); return NvResult.InvalidInput; } } } - PA = Map.Address + Args.BufferOffset; + pa = map.Address + args.BufferOffset; - long Size = Args.MappingSize; + long size = args.MappingSize; - if (Size == 0) + if (size == 0) { - Size = (uint)Map.Size; + size = (uint)map.Size; } - int Result = NvResult.Success; + int result = NvResult.Success; - lock (ASCtx) + lock (asCtx) { //Note: When the fixed offset flag is not set, //the Offset field holds the alignment size instead. - bool VaAllocated = (Args.Flags & FlagFixedOffset) == 0; + bool vaAllocated = (args.Flags & FlagFixedOffset) == 0; - if (!VaAllocated) + if (!vaAllocated) { - if (ASCtx.ValidateFixedBuffer(Args.Offset, Size)) + if (asCtx.ValidateFixedBuffer(args.Offset, size)) { - Args.Offset = ASCtx.Vmm.Map(PA, Args.Offset, Size); + args.Offset = asCtx.Vmm.Map(pa, args.Offset, size); } else { - string Msg = string.Format(MapErrorMsg, Args.Offset, Size); + string msg = string.Format(mapErrorMsg, args.Offset, size); - Logger.PrintWarning(LogClass.ServiceNv, Msg); + Logger.PrintWarning(LogClass.ServiceNv, msg); - Result = NvResult.InvalidInput; + result = NvResult.InvalidInput; } } else { - Args.Offset = ASCtx.Vmm.Map(PA, Size); + args.Offset = asCtx.Vmm.Map(pa, size); } - if (Args.Offset < 0) + if (args.Offset < 0) { - Args.Offset = 0; + args.Offset = 0; - Logger.PrintWarning(LogClass.ServiceNv, $"Failed to map size 0x{Size:x16}!"); + Logger.PrintWarning(LogClass.ServiceNv, $"Failed to map size 0x{size:x16}!"); - Result = NvResult.InvalidInput; + result = NvResult.InvalidInput; } else { - ASCtx.AddMap(Args.Offset, Size, PA, VaAllocated); + asCtx.AddMap(args.Offset, size, pa, vaAllocated); } } - MemoryHelper.Write(Context.Memory, OutputPosition, Args); + MemoryHelper.Write(context.Memory, outputPosition, args); - return Result; + return result; } - private static int GetVaRegions(ServiceCtx Context) + private static int GetVaRegions(ServiceCtx context) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; Logger.PrintStub(LogClass.ServiceNv, "Stubbed."); return NvResult.Success; } - private static int InitializeEx(ServiceCtx Context) + private static int InitializeEx(ServiceCtx context) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; Logger.PrintStub(LogClass.ServiceNv, "Stubbed."); return NvResult.Success; } - private static int Remap(ServiceCtx Context, int Cmd) + private static int Remap(ServiceCtx context, int cmd) { - int Count = ((Cmd >> 16) & 0xff) / 0x14; + int count = ((cmd >> 16) & 0xff) / 0x14; - long InputPosition = Context.Request.GetBufferType0x21().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; - for (int Index = 0; Index < Count; Index++, InputPosition += 0x14) + for (int index = 0; index < count; index++, inputPosition += 0x14) { - NvGpuASRemap Args = MemoryHelper.Read(Context.Memory, InputPosition); + NvGpuASRemap args = MemoryHelper.Read(context.Memory, inputPosition); - NvGpuVmm Vmm = GetASCtx(Context).Vmm; + NvGpuVmm vmm = GetASCtx(context).Vmm; - NvMapHandle Map = NvMapIoctl.GetNvMapWithFb(Context, Args.NvMapHandle); + NvMapHandle map = NvMapIoctl.GetNvMapWithFb(context, args.NvMapHandle); - if (Map == null) + if (map == null) { - Logger.PrintWarning(LogClass.ServiceNv, $"Invalid NvMap handle 0x{Args.NvMapHandle:x8}!"); + Logger.PrintWarning(LogClass.ServiceNv, $"Invalid NvMap handle 0x{args.NvMapHandle:x8}!"); return NvResult.InvalidInput; } - long Result = Vmm.Map(Map.Address, (long)(uint)Args.Offset << 16, - (long)(uint)Args.Pages << 16); + long result = vmm.Map(map.Address, (long)(uint)args.Offset << 16, + (long)(uint)args.Pages << 16); - if (Result < 0) + if (result < 0) { Logger.PrintWarning(LogClass.ServiceNv, - $"Page 0x{Args.Offset:x16} size 0x{Args.Pages:x16} not allocated!"); + $"Page 0x{args.Offset:x16} size 0x{args.Pages:x16} not allocated!"); return NvResult.InvalidInput; } @@ -317,14 +317,14 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvGpuAS return NvResult.Success; } - public static NvGpuASCtx GetASCtx(ServiceCtx Context) + public static NvGpuASCtx GetASCtx(ServiceCtx context) { - return ASCtxs.GetOrAdd(Context.Process, (Key) => new NvGpuASCtx(Context)); + return _asCtxs.GetOrAdd(context.Process, (key) => new NvGpuASCtx(context)); } - public static void UnloadProcess(KProcess Process) + public static void UnloadProcess(KProcess process) { - ASCtxs.TryRemove(Process, out _); + _asCtxs.TryRemove(process, out _); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Services/Nv/NvGpuGpu/NvGpuGpuIoctl.cs b/Ryujinx.HLE/HOS/Services/Nv/NvGpuGpu/NvGpuGpuIoctl.cs index 7ee770f4..5680fb8e 100644 --- a/Ryujinx.HLE/HOS/Services/Nv/NvGpuGpu/NvGpuGpuIoctl.cs +++ b/Ryujinx.HLE/HOS/Services/Nv/NvGpuGpu/NvGpuGpuIoctl.cs @@ -7,181 +7,181 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvGpuGpu { class NvGpuGpuIoctl { - private static Stopwatch PTimer; + private static Stopwatch _pTimer; - private static double TicksToNs; + private static double _ticksToNs; static NvGpuGpuIoctl() { - PTimer = new Stopwatch(); + _pTimer = new Stopwatch(); - PTimer.Start(); + _pTimer.Start(); - TicksToNs = (1.0 / Stopwatch.Frequency) * 1_000_000_000; + _ticksToNs = (1.0 / Stopwatch.Frequency) * 1_000_000_000; } - public static int ProcessIoctl(ServiceCtx Context, int Cmd) + public static int ProcessIoctl(ServiceCtx context, int cmd) { - switch (Cmd & 0xffff) + switch (cmd & 0xffff) { - case 0x4701: return ZcullGetCtxSize (Context); - case 0x4702: return ZcullGetInfo (Context); - case 0x4703: return ZbcSetTable (Context); - case 0x4705: return GetCharacteristics(Context); - case 0x4706: return GetTpcMasks (Context); - case 0x4714: return GetActiveSlotMask (Context); - case 0x471c: return GetGpuTime (Context); + case 0x4701: return ZcullGetCtxSize (context); + case 0x4702: return ZcullGetInfo (context); + case 0x4703: return ZbcSetTable (context); + case 0x4705: return GetCharacteristics(context); + case 0x4706: return GetTpcMasks (context); + case 0x4714: return GetActiveSlotMask (context); + case 0x471c: return GetGpuTime (context); } - throw new NotImplementedException(Cmd.ToString("x8")); + throw new NotImplementedException(cmd.ToString("x8")); } - private static int ZcullGetCtxSize(ServiceCtx Context) + private static int ZcullGetCtxSize(ServiceCtx context) { - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; - NvGpuGpuZcullGetCtxSize Args = new NvGpuGpuZcullGetCtxSize(); + NvGpuGpuZcullGetCtxSize args = new NvGpuGpuZcullGetCtxSize(); - Args.Size = 1; + args.Size = 1; - MemoryHelper.Write(Context.Memory, OutputPosition, Args); + MemoryHelper.Write(context.Memory, outputPosition, args); Logger.PrintStub(LogClass.ServiceNv, "Stubbed."); return NvResult.Success; } - private static int ZcullGetInfo(ServiceCtx Context) + private static int ZcullGetInfo(ServiceCtx context) { - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; - NvGpuGpuZcullGetInfo Args = new NvGpuGpuZcullGetInfo(); + NvGpuGpuZcullGetInfo args = new NvGpuGpuZcullGetInfo(); - Args.WidthAlignPixels = 0x20; - Args.HeightAlignPixels = 0x20; - Args.PixelSquaresByAliquots = 0x400; - Args.AliquotTotal = 0x800; - Args.RegionByteMultiplier = 0x20; - Args.RegionHeaderSize = 0x20; - Args.SubregionHeaderSize = 0xc0; - Args.SubregionWidthAlignPixels = 0x20; - Args.SubregionHeightAlignPixels = 0x40; - Args.SubregionCount = 0x10; + args.WidthAlignPixels = 0x20; + args.HeightAlignPixels = 0x20; + args.PixelSquaresByAliquots = 0x400; + args.AliquotTotal = 0x800; + args.RegionByteMultiplier = 0x20; + args.RegionHeaderSize = 0x20; + args.SubregionHeaderSize = 0xc0; + args.SubregionWidthAlignPixels = 0x20; + args.SubregionHeightAlignPixels = 0x40; + args.SubregionCount = 0x10; - MemoryHelper.Write(Context.Memory, OutputPosition, Args); + MemoryHelper.Write(context.Memory, outputPosition, args); Logger.PrintStub(LogClass.ServiceNv, "Stubbed."); return NvResult.Success; } - private static int ZbcSetTable(ServiceCtx Context) + private static int ZbcSetTable(ServiceCtx context) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; Logger.PrintStub(LogClass.ServiceNv, "Stubbed."); return NvResult.Success; } - private static int GetCharacteristics(ServiceCtx Context) + private static int GetCharacteristics(ServiceCtx context) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; - NvGpuGpuGetCharacteristics Args = MemoryHelper.Read(Context.Memory, InputPosition); + NvGpuGpuGetCharacteristics args = MemoryHelper.Read(context.Memory, inputPosition); - Args.BufferSize = 0xa0; + args.BufferSize = 0xa0; - Args.Arch = 0x120; - Args.Impl = 0xb; - Args.Rev = 0xa1; - Args.NumGpc = 0x1; - Args.L2CacheSize = 0x40000; - Args.OnBoardVideoMemorySize = 0x0; - Args.NumTpcPerGpc = 0x2; - Args.BusType = 0x20; - Args.BigPageSize = 0x20000; - Args.CompressionPageSize = 0x20000; - Args.PdeCoverageBitCount = 0x1b; - Args.AvailableBigPageSizes = 0x30000; - Args.GpcMask = 0x1; - Args.SmArchSmVersion = 0x503; - Args.SmArchSpaVersion = 0x503; - Args.SmArchWarpCount = 0x80; - Args.GpuVaBitCount = 0x28; - Args.Reserved = 0x0; - Args.Flags = 0x55; - Args.TwodClass = 0x902d; - Args.ThreedClass = 0xb197; - Args.ComputeClass = 0xb1c0; - Args.GpfifoClass = 0xb06f; - Args.InlineToMemoryClass = 0xa140; - Args.DmaCopyClass = 0xb0b5; - Args.MaxFbpsCount = 0x1; - Args.FbpEnMask = 0x0; - Args.MaxLtcPerFbp = 0x2; - Args.MaxLtsPerLtc = 0x1; - Args.MaxTexPerTpc = 0x0; - Args.MaxGpcCount = 0x1; - Args.RopL2EnMask0 = 0x21d70; - Args.RopL2EnMask1 = 0x0; - Args.ChipName = 0x6230326d67; - Args.GrCompbitStoreBaseHw = 0x0; + args.Arch = 0x120; + args.Impl = 0xb; + args.Rev = 0xa1; + args.NumGpc = 0x1; + args.L2CacheSize = 0x40000; + args.OnBoardVideoMemorySize = 0x0; + args.NumTpcPerGpc = 0x2; + args.BusType = 0x20; + args.BigPageSize = 0x20000; + args.CompressionPageSize = 0x20000; + args.PdeCoverageBitCount = 0x1b; + args.AvailableBigPageSizes = 0x30000; + args.GpcMask = 0x1; + args.SmArchSmVersion = 0x503; + args.SmArchSpaVersion = 0x503; + args.SmArchWarpCount = 0x80; + args.GpuVaBitCount = 0x28; + args.Reserved = 0x0; + args.Flags = 0x55; + args.TwodClass = 0x902d; + args.ThreedClass = 0xb197; + args.ComputeClass = 0xb1c0; + args.GpfifoClass = 0xb06f; + args.InlineToMemoryClass = 0xa140; + args.DmaCopyClass = 0xb0b5; + args.MaxFbpsCount = 0x1; + args.FbpEnMask = 0x0; + args.MaxLtcPerFbp = 0x2; + args.MaxLtsPerLtc = 0x1; + args.MaxTexPerTpc = 0x0; + args.MaxGpcCount = 0x1; + args.RopL2EnMask0 = 0x21d70; + args.RopL2EnMask1 = 0x0; + args.ChipName = 0x6230326d67; + args.GrCompbitStoreBaseHw = 0x0; - MemoryHelper.Write(Context.Memory, OutputPosition, Args); + MemoryHelper.Write(context.Memory, outputPosition, args); return NvResult.Success; } - private static int GetTpcMasks(ServiceCtx Context) + private static int GetTpcMasks(ServiceCtx context) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; - NvGpuGpuGetTpcMasks Args = MemoryHelper.Read(Context.Memory, InputPosition); + NvGpuGpuGetTpcMasks args = MemoryHelper.Read(context.Memory, inputPosition); - if (Args.MaskBufferSize != 0) + if (args.MaskBufferSize != 0) { - Args.TpcMask = 3; + args.TpcMask = 3; } - MemoryHelper.Write(Context.Memory, OutputPosition, Args); + MemoryHelper.Write(context.Memory, outputPosition, args); return NvResult.Success; } - private static int GetActiveSlotMask(ServiceCtx Context) + private static int GetActiveSlotMask(ServiceCtx context) { - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; - NvGpuGpuGetActiveSlotMask Args = new NvGpuGpuGetActiveSlotMask(); + NvGpuGpuGetActiveSlotMask args = new NvGpuGpuGetActiveSlotMask(); - Args.Slot = 0x07; - Args.Mask = 0x01; + args.Slot = 0x07; + args.Mask = 0x01; - MemoryHelper.Write(Context.Memory, OutputPosition, Args); + MemoryHelper.Write(context.Memory, outputPosition, args); Logger.PrintStub(LogClass.ServiceNv, "Stubbed."); return NvResult.Success; } - private static int GetGpuTime(ServiceCtx Context) + private static int GetGpuTime(ServiceCtx context) { - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; - Context.Memory.WriteInt64(OutputPosition, GetPTimerNanoSeconds()); + context.Memory.WriteInt64(outputPosition, GetPTimerNanoSeconds()); return NvResult.Success; } private static long GetPTimerNanoSeconds() { - double Ticks = PTimer.ElapsedTicks; + double ticks = _pTimer.ElapsedTicks; - return (long)(Ticks * TicksToNs) & 0xff_ffff_ffff_ffff; + return (long)(ticks * _ticksToNs) & 0xff_ffff_ffff_ffff; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Services/Nv/NvHostChannel/NvHostChannelIoctl.cs b/Ryujinx.HLE/HOS/Services/Nv/NvHostChannel/NvHostChannelIoctl.cs index 466f3e9b..a3b55309 100644 --- a/Ryujinx.HLE/HOS/Services/Nv/NvHostChannel/NvHostChannelIoctl.cs +++ b/Ryujinx.HLE/HOS/Services/Nv/NvHostChannel/NvHostChannelIoctl.cs @@ -11,62 +11,62 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvHostChannel { class NvHostChannelIoctl { - private static ConcurrentDictionary Channels; + private static ConcurrentDictionary _channels; static NvHostChannelIoctl() { - Channels = new ConcurrentDictionary(); + _channels = new ConcurrentDictionary(); } - public static int ProcessIoctl(ServiceCtx Context, int Cmd) + public static int ProcessIoctl(ServiceCtx context, int cmd) { - switch (Cmd & 0xffff) + switch (cmd & 0xffff) { - case 0x0001: return Submit (Context); - case 0x0002: return GetSyncpoint (Context); - case 0x0003: return GetWaitBase (Context); - case 0x0009: return MapBuffer (Context); - case 0x000a: return UnmapBuffer (Context); - case 0x4714: return SetUserData (Context); - case 0x4801: return SetNvMap (Context); - case 0x4803: return SetTimeout (Context); - case 0x4808: return SubmitGpfifo (Context); - case 0x4809: return AllocObjCtx (Context); - case 0x480b: return ZcullBind (Context); - case 0x480c: return SetErrorNotifier (Context); - case 0x480d: return SetPriority (Context); - case 0x481a: return AllocGpfifoEx2 (Context); - case 0x481b: return KickoffPbWithAttr(Context); + case 0x0001: return Submit (context); + case 0x0002: return GetSyncpoint (context); + case 0x0003: return GetWaitBase (context); + case 0x0009: return MapBuffer (context); + case 0x000a: return UnmapBuffer (context); + case 0x4714: return SetUserData (context); + case 0x4801: return SetNvMap (context); + case 0x4803: return SetTimeout (context); + case 0x4808: return SubmitGpfifo (context); + case 0x4809: return AllocObjCtx (context); + case 0x480b: return ZcullBind (context); + case 0x480c: return SetErrorNotifier (context); + case 0x480d: return SetPriority (context); + case 0x481a: return AllocGpfifoEx2 (context); + case 0x481b: return KickoffPbWithAttr(context); } - throw new NotImplementedException(Cmd.ToString("x8")); + throw new NotImplementedException(cmd.ToString("x8")); } - private static int Submit(ServiceCtx Context) + private static int Submit(ServiceCtx context) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; - NvHostChannelSubmit Args = MemoryHelper.Read(Context.Memory, InputPosition); + NvHostChannelSubmit args = MemoryHelper.Read(context.Memory, inputPosition); - NvGpuVmm Vmm = NvGpuASIoctl.GetASCtx(Context).Vmm; + NvGpuVmm vmm = NvGpuASIoctl.GetASCtx(context).Vmm; - for (int Index = 0; Index < Args.CmdBufsCount; Index++) + for (int index = 0; index < args.CmdBufsCount; index++) { - long CmdBufOffset = InputPosition + 0x10 + Index * 0xc; + long cmdBufOffset = inputPosition + 0x10 + index * 0xc; - NvHostChannelCmdBuf CmdBuf = MemoryHelper.Read(Context.Memory, CmdBufOffset); + NvHostChannelCmdBuf cmdBuf = MemoryHelper.Read(context.Memory, cmdBufOffset); - NvMapHandle Map = NvMapIoctl.GetNvMap(Context, CmdBuf.MemoryId); + NvMapHandle map = NvMapIoctl.GetNvMap(context, cmdBuf.MemoryId); - int[] CmdBufData = new int[CmdBuf.WordsCount]; + int[] cmdBufData = new int[cmdBuf.WordsCount]; - for (int Offset = 0; Offset < CmdBufData.Length; Offset++) + for (int offset = 0; offset < cmdBufData.Length; offset++) { - CmdBufData[Offset] = Context.Memory.ReadInt32(Map.Address + CmdBuf.Offset + Offset * 4); + cmdBufData[offset] = context.Memory.ReadInt32(map.Address + cmdBuf.Offset + offset * 4); } - Context.Device.Gpu.PushCommandBuffer(Vmm, CmdBufData); + context.Device.Gpu.PushCommandBuffer(vmm, cmdBufData); } //TODO: Relocation, waitchecks, etc. @@ -74,99 +74,99 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvHostChannel return NvResult.Success; } - private static int GetSyncpoint(ServiceCtx Context) + private static int GetSyncpoint(ServiceCtx context) { //TODO - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; - NvHostChannelGetParamArg Args = MemoryHelper.Read(Context.Memory, InputPosition); + NvHostChannelGetParamArg args = MemoryHelper.Read(context.Memory, inputPosition); - Args.Value = 0; + args.Value = 0; - MemoryHelper.Write(Context.Memory, OutputPosition, Args); + MemoryHelper.Write(context.Memory, outputPosition, args); return NvResult.Success; } - private static int GetWaitBase(ServiceCtx Context) + private static int GetWaitBase(ServiceCtx context) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; - NvHostChannelGetParamArg Args = MemoryHelper.Read(Context.Memory, InputPosition); + NvHostChannelGetParamArg args = MemoryHelper.Read(context.Memory, inputPosition); - Args.Value = 0; + args.Value = 0; - MemoryHelper.Write(Context.Memory, OutputPosition, Args); + MemoryHelper.Write(context.Memory, outputPosition, args); return NvResult.Success; } - private static int MapBuffer(ServiceCtx Context) + private static int MapBuffer(ServiceCtx context) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; - NvHostChannelMapBuffer Args = MemoryHelper.Read(Context.Memory, InputPosition); + NvHostChannelMapBuffer args = MemoryHelper.Read(context.Memory, inputPosition); - NvGpuVmm Vmm = NvGpuASIoctl.GetASCtx(Context).Vmm; + NvGpuVmm vmm = NvGpuASIoctl.GetASCtx(context).Vmm; - for (int Index = 0; Index < Args.NumEntries; Index++) + for (int index = 0; index < args.NumEntries; index++) { - int Handle = Context.Memory.ReadInt32(InputPosition + 0xc + Index * 8); + int handle = context.Memory.ReadInt32(inputPosition + 0xc + index * 8); - NvMapHandle Map = NvMapIoctl.GetNvMap(Context, Handle); + NvMapHandle map = NvMapIoctl.GetNvMap(context, handle); - if (Map == null) + if (map == null) { - Logger.PrintWarning(LogClass.ServiceNv, $"Invalid handle 0x{Handle:x8}!"); + Logger.PrintWarning(LogClass.ServiceNv, $"Invalid handle 0x{handle:x8}!"); return NvResult.InvalidInput; } - lock (Map) + lock (map) { - if (Map.DmaMapAddress == 0) + if (map.DmaMapAddress == 0) { - Map.DmaMapAddress = Vmm.MapLow(Map.Address, Map.Size); + map.DmaMapAddress = vmm.MapLow(map.Address, map.Size); } - Context.Memory.WriteInt32(OutputPosition + 0xc + 4 + Index * 8, (int)Map.DmaMapAddress); + context.Memory.WriteInt32(outputPosition + 0xc + 4 + index * 8, (int)map.DmaMapAddress); } } return NvResult.Success; } - private static int UnmapBuffer(ServiceCtx Context) + private static int UnmapBuffer(ServiceCtx context) { - long InputPosition = Context.Request.GetBufferType0x21().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; - NvHostChannelMapBuffer Args = MemoryHelper.Read(Context.Memory, InputPosition); + NvHostChannelMapBuffer args = MemoryHelper.Read(context.Memory, inputPosition); - NvGpuVmm Vmm = NvGpuASIoctl.GetASCtx(Context).Vmm; + NvGpuVmm vmm = NvGpuASIoctl.GetASCtx(context).Vmm; - for (int Index = 0; Index < Args.NumEntries; Index++) + for (int index = 0; index < args.NumEntries; index++) { - int Handle = Context.Memory.ReadInt32(InputPosition + 0xc + Index * 8); + int handle = context.Memory.ReadInt32(inputPosition + 0xc + index * 8); - NvMapHandle Map = NvMapIoctl.GetNvMap(Context, Handle); + NvMapHandle map = NvMapIoctl.GetNvMap(context, handle); - if (Map == null) + if (map == null) { - Logger.PrintWarning(LogClass.ServiceNv, $"Invalid handle 0x{Handle:x8}!"); + Logger.PrintWarning(LogClass.ServiceNv, $"Invalid handle 0x{handle:x8}!"); return NvResult.InvalidInput; } - lock (Map) + lock (map) { - if (Map.DmaMapAddress != 0) + if (map.DmaMapAddress != 0) { - Vmm.Free(Map.DmaMapAddress, Map.Size); + vmm.Free(map.DmaMapAddress, map.Size); - Map.DmaMapAddress = 0; + map.DmaMapAddress = 0; } } } @@ -174,146 +174,146 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvHostChannel return NvResult.Success; } - private static int SetUserData(ServiceCtx Context) + private static int SetUserData(ServiceCtx context) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; Logger.PrintStub(LogClass.ServiceNv, "Stubbed."); return NvResult.Success; } - private static int SetNvMap(ServiceCtx Context) + private static int SetNvMap(ServiceCtx context) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; Logger.PrintStub(LogClass.ServiceNv, "Stubbed."); return NvResult.Success; } - private static int SetTimeout(ServiceCtx Context) + private static int SetTimeout(ServiceCtx context) { - long InputPosition = Context.Request.GetBufferType0x21().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; - GetChannel(Context).Timeout = Context.Memory.ReadInt32(InputPosition); + GetChannel(context).Timeout = context.Memory.ReadInt32(inputPosition); return NvResult.Success; } - private static int SubmitGpfifo(ServiceCtx Context) + private static int SubmitGpfifo(ServiceCtx context) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; - NvHostChannelSubmitGpfifo Args = MemoryHelper.Read(Context.Memory, InputPosition); + NvHostChannelSubmitGpfifo args = MemoryHelper.Read(context.Memory, inputPosition); - NvGpuVmm Vmm = NvGpuASIoctl.GetASCtx(Context).Vmm;; + NvGpuVmm vmm = NvGpuASIoctl.GetASCtx(context).Vmm; - for (int Index = 0; Index < Args.NumEntries; Index++) + for (int index = 0; index < args.NumEntries; index++) { - long Gpfifo = Context.Memory.ReadInt64(InputPosition + 0x18 + Index * 8); + long gpfifo = context.Memory.ReadInt64(inputPosition + 0x18 + index * 8); - PushGpfifo(Context, Vmm, Gpfifo); + PushGpfifo(context, vmm, gpfifo); } - Args.SyncptId = 0; - Args.SyncptValue = 0; + args.SyncptId = 0; + args.SyncptValue = 0; - MemoryHelper.Write(Context.Memory, OutputPosition, Args); + MemoryHelper.Write(context.Memory, outputPosition, args); return NvResult.Success; } - private static int AllocObjCtx(ServiceCtx Context) + private static int AllocObjCtx(ServiceCtx context) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; Logger.PrintStub(LogClass.ServiceNv, "Stubbed."); return NvResult.Success; } - private static int ZcullBind(ServiceCtx Context) + private static int ZcullBind(ServiceCtx context) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; Logger.PrintStub(LogClass.ServiceNv, "Stubbed."); return NvResult.Success; } - private static int SetErrorNotifier(ServiceCtx Context) + private static int SetErrorNotifier(ServiceCtx context) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; Logger.PrintStub(LogClass.ServiceNv, "Stubbed."); return NvResult.Success; } - private static int SetPriority(ServiceCtx Context) + private static int SetPriority(ServiceCtx context) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; Logger.PrintStub(LogClass.ServiceNv, "Stubbed."); return NvResult.Success; } - private static int AllocGpfifoEx2(ServiceCtx Context) + private static int AllocGpfifoEx2(ServiceCtx context) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; Logger.PrintStub(LogClass.ServiceNv, "Stubbed."); return NvResult.Success; } - private static int KickoffPbWithAttr(ServiceCtx Context) + private static int KickoffPbWithAttr(ServiceCtx context) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; - NvHostChannelSubmitGpfifo Args = MemoryHelper.Read(Context.Memory, InputPosition); + NvHostChannelSubmitGpfifo args = MemoryHelper.Read(context.Memory, inputPosition); - NvGpuVmm Vmm = NvGpuASIoctl.GetASCtx(Context).Vmm;; + NvGpuVmm vmm = NvGpuASIoctl.GetASCtx(context).Vmm; - for (int Index = 0; Index < Args.NumEntries; Index++) + for (int index = 0; index < args.NumEntries; index++) { - long Gpfifo = Context.Memory.ReadInt64(Args.Address + Index * 8); + long gpfifo = context.Memory.ReadInt64(args.Address + index * 8); - PushGpfifo(Context, Vmm, Gpfifo); + PushGpfifo(context, vmm, gpfifo); } - Args.SyncptId = 0; - Args.SyncptValue = 0; + args.SyncptId = 0; + args.SyncptValue = 0; - MemoryHelper.Write(Context.Memory, OutputPosition, Args); + MemoryHelper.Write(context.Memory, outputPosition, args); return NvResult.Success; } - private static void PushGpfifo(ServiceCtx Context, NvGpuVmm Vmm, long Gpfifo) + private static void PushGpfifo(ServiceCtx context, NvGpuVmm vmm, long gpfifo) { - Context.Device.Gpu.Pusher.Push(Vmm, Gpfifo); + context.Device.Gpu.Pusher.Push(vmm, gpfifo); } - public static NvChannel GetChannel(ServiceCtx Context) + public static NvChannel GetChannel(ServiceCtx context) { - return Channels.GetOrAdd(Context.Process, (Key) => new NvChannel()); + return _channels.GetOrAdd(context.Process, (key) => new NvChannel()); } - public static void UnloadProcess(KProcess Process) + public static void UnloadProcess(KProcess process) { - Channels.TryRemove(Process, out _); + _channels.TryRemove(process, out _); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Services/Nv/NvHostCtrl/NvHostCtrlIoctl.cs b/Ryujinx.HLE/HOS/Services/Nv/NvHostCtrl/NvHostCtrlIoctl.cs index bf92afb4..f13f7a68 100644 --- a/Ryujinx.HLE/HOS/Services/Nv/NvHostCtrl/NvHostCtrlIoctl.cs +++ b/Ryujinx.HLE/HOS/Services/Nv/NvHostCtrl/NvHostCtrlIoctl.cs @@ -10,116 +10,116 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvHostCtrl { class NvHostCtrlIoctl { - private static ConcurrentDictionary UserCtxs; + private static ConcurrentDictionary _userCtxs; - private static bool IsProductionMode = true; + private static bool _isProductionMode = true; static NvHostCtrlIoctl() { - UserCtxs = new ConcurrentDictionary(); + _userCtxs = new ConcurrentDictionary(); - if (Set.NxSettings.Settings.TryGetValue("nv!rmos_set_production_mode", out object ProductionModeSetting)) + if (Set.NxSettings.Settings.TryGetValue("nv!rmos_set_production_mode", out object productionModeSetting)) { - IsProductionMode = ((string)ProductionModeSetting) != "0"; // Default value is "" + _isProductionMode = ((string)productionModeSetting) != "0"; // Default value is "" } } - public static int ProcessIoctl(ServiceCtx Context, int Cmd) + public static int ProcessIoctl(ServiceCtx context, int cmd) { - switch (Cmd & 0xffff) + switch (cmd & 0xffff) { - case 0x0014: return SyncptRead (Context); - case 0x0015: return SyncptIncr (Context); - case 0x0016: return SyncptWait (Context); - case 0x0019: return SyncptWaitEx (Context); - case 0x001a: return SyncptReadMax (Context); - case 0x001b: return GetConfig (Context); - case 0x001d: return EventWait (Context); - case 0x001e: return EventWaitAsync(Context); - case 0x001f: return EventRegister (Context); + case 0x0014: return SyncptRead (context); + case 0x0015: return SyncptIncr (context); + case 0x0016: return SyncptWait (context); + case 0x0019: return SyncptWaitEx (context); + case 0x001a: return SyncptReadMax (context); + case 0x001b: return GetConfig (context); + case 0x001d: return EventWait (context); + case 0x001e: return EventWaitAsync(context); + case 0x001f: return EventRegister (context); } - throw new NotImplementedException(Cmd.ToString("x8")); + throw new NotImplementedException(cmd.ToString("x8")); } - private static int SyncptRead(ServiceCtx Context) + private static int SyncptRead(ServiceCtx context) { - return SyncptReadMinOrMax(Context, Max: false); + return SyncptReadMinOrMax(context, max: false); } - private static int SyncptIncr(ServiceCtx Context) + private static int SyncptIncr(ServiceCtx context) { - long InputPosition = Context.Request.GetBufferType0x21().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; - int Id = Context.Memory.ReadInt32(InputPosition); + int id = context.Memory.ReadInt32(inputPosition); - if ((uint)Id >= NvHostSyncpt.SyncptsCount) + if ((uint)id >= NvHostSyncpt.SyncptsCount) { return NvResult.InvalidInput; } - GetUserCtx(Context).Syncpt.Increment(Id); + GetUserCtx(context).Syncpt.Increment(id); return NvResult.Success; } - private static int SyncptWait(ServiceCtx Context) + private static int SyncptWait(ServiceCtx context) { - return SyncptWait(Context, Extended: false); + return SyncptWait(context, extended: false); } - private static int SyncptWaitEx(ServiceCtx Context) + private static int SyncptWaitEx(ServiceCtx context) { - return SyncptWait(Context, Extended: true); + return SyncptWait(context, extended: true); } - private static int SyncptReadMax(ServiceCtx Context) + private static int SyncptReadMax(ServiceCtx context) { - return SyncptReadMinOrMax(Context, Max: true); + return SyncptReadMinOrMax(context, max: true); } - private static int GetConfig(ServiceCtx Context) + private static int GetConfig(ServiceCtx context) { - if (!IsProductionMode) + if (!_isProductionMode) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; - string Domain = MemoryHelper.ReadAsciiString(Context.Memory, InputPosition + 0, 0x41); - string Name = MemoryHelper.ReadAsciiString(Context.Memory, InputPosition + 0x41, 0x41); + string domain = MemoryHelper.ReadAsciiString(context.Memory, inputPosition + 0, 0x41); + string name = MemoryHelper.ReadAsciiString(context.Memory, inputPosition + 0x41, 0x41); - if (Set.NxSettings.Settings.TryGetValue($"{Domain}!{Name}", out object NvSetting)) + if (Set.NxSettings.Settings.TryGetValue($"{domain}!{name}", out object nvSetting)) { - byte[] SettingBuffer = new byte[0x101]; + byte[] settingBuffer = new byte[0x101]; - if (NvSetting is string StringValue) + if (nvSetting is string stringValue) { - if (StringValue.Length > 0x100) + if (stringValue.Length > 0x100) { - Logger.PrintError(LogClass.ServiceNv, $"{Domain}!{Name} String value size is too big!"); + Logger.PrintError(LogClass.ServiceNv, $"{domain}!{name} String value size is too big!"); } else { - SettingBuffer = Encoding.ASCII.GetBytes(StringValue + "\0"); + settingBuffer = Encoding.ASCII.GetBytes(stringValue + "\0"); } } - if (NvSetting is int IntValue) + if (nvSetting is int intValue) { - SettingBuffer = BitConverter.GetBytes(IntValue); + settingBuffer = BitConverter.GetBytes(intValue); } - else if (NvSetting is bool BoolValue) + else if (nvSetting is bool boolValue) { - SettingBuffer[0] = BoolValue ? (byte)1 : (byte)0; + settingBuffer[0] = boolValue ? (byte)1 : (byte)0; } else { - throw new NotImplementedException(NvSetting.GetType().Name); + throw new NotImplementedException(nvSetting.GetType().Name); } - Context.Memory.WriteBytes(OutputPosition + 0x82, SettingBuffer); + context.Memory.WriteBytes(outputPosition + 0x82, settingBuffer); - Logger.PrintDebug(LogClass.ServiceNv, $"Got setting {Domain}!{Name}"); + Logger.PrintDebug(LogClass.ServiceNv, $"Got setting {domain}!{name}"); } return NvResult.Success; @@ -128,156 +128,156 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvHostCtrl return NvResult.NotAvailableInProduction; } - private static int EventWait(ServiceCtx Context) + private static int EventWait(ServiceCtx context) { - return EventWait(Context, Async: false); + return EventWait(context, async: false); } - private static int EventWaitAsync(ServiceCtx Context) + private static int EventWaitAsync(ServiceCtx context) { - return EventWait(Context, Async: true); + return EventWait(context, async: true); } - private static int EventRegister(ServiceCtx Context) + private static int EventRegister(ServiceCtx context) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; - int EventId = Context.Memory.ReadInt32(InputPosition); + int eventId = context.Memory.ReadInt32(inputPosition); Logger.PrintStub(LogClass.ServiceNv, "Stubbed."); return NvResult.Success; } - private static int SyncptReadMinOrMax(ServiceCtx Context, bool Max) + private static int SyncptReadMinOrMax(ServiceCtx context, bool max) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; - NvHostCtrlSyncptRead Args = MemoryHelper.Read(Context.Memory, InputPosition); + NvHostCtrlSyncptRead args = MemoryHelper.Read(context.Memory, inputPosition); - if ((uint)Args.Id >= NvHostSyncpt.SyncptsCount) + if ((uint)args.Id >= NvHostSyncpt.SyncptsCount) { return NvResult.InvalidInput; } - if (Max) + if (max) { - Args.Value = GetUserCtx(Context).Syncpt.GetMax(Args.Id); + args.Value = GetUserCtx(context).Syncpt.GetMax(args.Id); } else { - Args.Value = GetUserCtx(Context).Syncpt.GetMin(Args.Id); + args.Value = GetUserCtx(context).Syncpt.GetMin(args.Id); } - MemoryHelper.Write(Context.Memory, OutputPosition, Args); + MemoryHelper.Write(context.Memory, outputPosition, args); return NvResult.Success; } - private static int SyncptWait(ServiceCtx Context, bool Extended) + private static int SyncptWait(ServiceCtx context, bool extended) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; - NvHostCtrlSyncptWait Args = MemoryHelper.Read(Context.Memory, InputPosition); + NvHostCtrlSyncptWait args = MemoryHelper.Read(context.Memory, inputPosition); - NvHostSyncpt Syncpt = GetUserCtx(Context).Syncpt; + NvHostSyncpt syncpt = GetUserCtx(context).Syncpt; - if ((uint)Args.Id >= NvHostSyncpt.SyncptsCount) + if ((uint)args.Id >= NvHostSyncpt.SyncptsCount) { return NvResult.InvalidInput; } - int Result; + int result; - if (Syncpt.MinCompare(Args.Id, Args.Thresh)) + if (syncpt.MinCompare(args.Id, args.Thresh)) { - Result = NvResult.Success; + result = NvResult.Success; } - else if (Args.Timeout == 0) + else if (args.Timeout == 0) { - Result = NvResult.TryAgain; + result = NvResult.TryAgain; } else { - Logger.PrintDebug(LogClass.ServiceNv, "Waiting syncpt with timeout of " + Args.Timeout + "ms..."); + Logger.PrintDebug(LogClass.ServiceNv, "Waiting syncpt with timeout of " + args.Timeout + "ms..."); - using (ManualResetEvent WaitEvent = new ManualResetEvent(false)) + using (ManualResetEvent waitEvent = new ManualResetEvent(false)) { - Syncpt.AddWaiter(Args.Thresh, WaitEvent); + syncpt.AddWaiter(args.Thresh, waitEvent); //Note: Negative (> INT_MAX) timeouts aren't valid on .NET, //in this case we just use the maximum timeout possible. - int Timeout = Args.Timeout; + int timeout = args.Timeout; - if (Timeout < -1) + if (timeout < -1) { - Timeout = int.MaxValue; + timeout = int.MaxValue; } - if (Timeout == -1) + if (timeout == -1) { - WaitEvent.WaitOne(); + waitEvent.WaitOne(); - Result = NvResult.Success; + result = NvResult.Success; } - else if (WaitEvent.WaitOne(Timeout)) + else if (waitEvent.WaitOne(timeout)) { - Result = NvResult.Success; + result = NvResult.Success; } else { - Result = NvResult.TimedOut; + result = NvResult.TimedOut; } } Logger.PrintDebug(LogClass.ServiceNv, "Resuming..."); } - if (Extended) + if (extended) { - Context.Memory.WriteInt32(OutputPosition + 0xc, Syncpt.GetMin(Args.Id)); + context.Memory.WriteInt32(outputPosition + 0xc, syncpt.GetMin(args.Id)); } - return Result; + return result; } - private static int EventWait(ServiceCtx Context, bool Async) + private static int EventWait(ServiceCtx context, bool async) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; - NvHostCtrlSyncptWaitEx Args = MemoryHelper.Read(Context.Memory, InputPosition); + NvHostCtrlSyncptWaitEx args = MemoryHelper.Read(context.Memory, inputPosition); - if ((uint)Args.Id >= NvHostSyncpt.SyncptsCount) + if ((uint)args.Id >= NvHostSyncpt.SyncptsCount) { return NvResult.InvalidInput; } void WriteArgs() { - MemoryHelper.Write(Context.Memory, OutputPosition, Args); + MemoryHelper.Write(context.Memory, outputPosition, args); } - NvHostSyncpt Syncpt = GetUserCtx(Context).Syncpt; + NvHostSyncpt syncpt = GetUserCtx(context).Syncpt; - if (Syncpt.MinCompare(Args.Id, Args.Thresh)) + if (syncpt.MinCompare(args.Id, args.Thresh)) { - Args.Value = Syncpt.GetMin(Args.Id); + args.Value = syncpt.GetMin(args.Id); WriteArgs(); return NvResult.Success; } - if (!Async) + if (!async) { - Args.Value = 0; + args.Value = 0; } - if (Args.Timeout == 0) + if (args.Timeout == 0) { WriteArgs(); @@ -286,114 +286,114 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvHostCtrl NvHostEvent Event; - int Result, EventIndex; + int result, eventIndex; - if (Async) + if (async) { - EventIndex = Args.Value; + eventIndex = args.Value; - if ((uint)EventIndex >= NvHostCtrlUserCtx.EventsCount) + if ((uint)eventIndex >= NvHostCtrlUserCtx.EventsCount) { return NvResult.InvalidInput; } - Event = GetUserCtx(Context).Events[EventIndex]; + Event = GetUserCtx(context).Events[eventIndex]; } else { - Event = GetFreeEvent(Context, Syncpt, Args.Id, out EventIndex); + Event = GetFreeEvent(context, syncpt, args.Id, out eventIndex); } if (Event != null && (Event.State == NvHostEventState.Registered || Event.State == NvHostEventState.Free)) { - Event.Id = Args.Id; - Event.Thresh = Args.Thresh; + Event.Id = args.Id; + Event.Thresh = args.Thresh; Event.State = NvHostEventState.Waiting; - if (!Async) + if (!async) { - Args.Value = ((Args.Id & 0xfff) << 16) | 0x10000000; + args.Value = ((args.Id & 0xfff) << 16) | 0x10000000; } else { - Args.Value = Args.Id << 4; + args.Value = args.Id << 4; } - Args.Value |= EventIndex; + args.Value |= eventIndex; - Result = NvResult.TryAgain; + result = NvResult.TryAgain; } else { - Result = NvResult.InvalidInput; + result = NvResult.InvalidInput; } WriteArgs(); - return Result; + return result; } private static NvHostEvent GetFreeEvent( - ServiceCtx Context, - NvHostSyncpt Syncpt, - int Id, - out int EventIndex) + ServiceCtx context, + NvHostSyncpt syncpt, + int id, + out int eventIndex) { - NvHostEvent[] Events = GetUserCtx(Context).Events; + NvHostEvent[] events = GetUserCtx(context).Events; - EventIndex = NvHostCtrlUserCtx.EventsCount; + eventIndex = NvHostCtrlUserCtx.EventsCount; - int NullIndex = NvHostCtrlUserCtx.EventsCount; + int nullIndex = NvHostCtrlUserCtx.EventsCount; - for (int Index = 0; Index < NvHostCtrlUserCtx.EventsCount; Index++) + for (int index = 0; index < NvHostCtrlUserCtx.EventsCount; index++) { - NvHostEvent Event = Events[Index]; + NvHostEvent Event = events[index]; if (Event != null) { if (Event.State == NvHostEventState.Registered || Event.State == NvHostEventState.Free) { - EventIndex = Index; + eventIndex = index; - if (Event.Id == Id) + if (Event.Id == id) { return Event; } } } - else if (NullIndex == NvHostCtrlUserCtx.EventsCount) + else if (nullIndex == NvHostCtrlUserCtx.EventsCount) { - NullIndex = Index; + nullIndex = index; } } - if (NullIndex < NvHostCtrlUserCtx.EventsCount) + if (nullIndex < NvHostCtrlUserCtx.EventsCount) { - EventIndex = NullIndex; + eventIndex = nullIndex; - return Events[NullIndex] = new NvHostEvent(); + return events[nullIndex] = new NvHostEvent(); } - if (EventIndex < NvHostCtrlUserCtx.EventsCount) + if (eventIndex < NvHostCtrlUserCtx.EventsCount) { - return Events[EventIndex]; + return events[eventIndex]; } return null; } - public static NvHostCtrlUserCtx GetUserCtx(ServiceCtx Context) + public static NvHostCtrlUserCtx GetUserCtx(ServiceCtx context) { - return UserCtxs.GetOrAdd(Context.Process, (Key) => new NvHostCtrlUserCtx()); + return _userCtxs.GetOrAdd(context.Process, (key) => new NvHostCtrlUserCtx()); } - public static void UnloadProcess(KProcess Process) + public static void UnloadProcess(KProcess process) { - UserCtxs.TryRemove(Process, out _); + _userCtxs.TryRemove(process, out _); } } } diff --git a/Ryujinx.HLE/HOS/Services/Nv/NvHostCtrl/NvHostSyncPt.cs b/Ryujinx.HLE/HOS/Services/Nv/NvHostCtrl/NvHostSyncPt.cs index 9ffa93f2..d27f7c53 100644 --- a/Ryujinx.HLE/HOS/Services/Nv/NvHostCtrl/NvHostSyncPt.cs +++ b/Ryujinx.HLE/HOS/Services/Nv/NvHostCtrl/NvHostSyncPt.cs @@ -9,98 +9,98 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvHostCtrl { public const int SyncptsCount = 192; - private int[] CounterMin; - private int[] CounterMax; + private int[] _counterMin; + private int[] _counterMax; - private long EventMask; + private long _eventMask; - private ConcurrentDictionary Waiters; + private ConcurrentDictionary _waiters; public NvHostSyncpt() { - CounterMin = new int[SyncptsCount]; - CounterMax = new int[SyncptsCount]; + _counterMin = new int[SyncptsCount]; + _counterMax = new int[SyncptsCount]; - Waiters = new ConcurrentDictionary(); + _waiters = new ConcurrentDictionary(); } - public int GetMin(int Id) + public int GetMin(int id) { - return CounterMin[Id]; + return _counterMin[id]; } - public int GetMax(int Id) + public int GetMax(int id) { - return CounterMax[Id]; + return _counterMax[id]; } - public int Increment(int Id) + public int Increment(int id) { - if (((EventMask >> Id) & 1) != 0) + if (((_eventMask >> id) & 1) != 0) { - Interlocked.Increment(ref CounterMax[Id]); + Interlocked.Increment(ref _counterMax[id]); } - return IncrementMin(Id); + return IncrementMin(id); } - public int IncrementMin(int Id) + public int IncrementMin(int id) { - int Value = Interlocked.Increment(ref CounterMin[Id]); + int value = Interlocked.Increment(ref _counterMin[id]); - WakeUpWaiters(Id, Value); + WakeUpWaiters(id, value); - return Value; + return value; } - public int IncrementMax(int Id) + public int IncrementMax(int id) { - return Interlocked.Increment(ref CounterMax[Id]); + return Interlocked.Increment(ref _counterMax[id]); } - public void AddWaiter(int Threshold, EventWaitHandle WaitEvent) + public void AddWaiter(int threshold, EventWaitHandle waitEvent) { - if (!Waiters.TryAdd(WaitEvent, Threshold)) + if (!_waiters.TryAdd(waitEvent, threshold)) { throw new InvalidOperationException(); } } - public bool RemoveWaiter(EventWaitHandle WaitEvent) + public bool RemoveWaiter(EventWaitHandle waitEvent) { - return Waiters.TryRemove(WaitEvent, out _); + return _waiters.TryRemove(waitEvent, out _); } - private void WakeUpWaiters(int Id, int NewValue) + private void WakeUpWaiters(int id, int newValue) { - foreach (KeyValuePair KV in Waiters) + foreach (KeyValuePair kv in _waiters) { - if (MinCompare(Id, NewValue, CounterMax[Id], KV.Value)) + if (MinCompare(id, newValue, _counterMax[id], kv.Value)) { - KV.Key.Set(); + kv.Key.Set(); - Waiters.TryRemove(KV.Key, out _); + _waiters.TryRemove(kv.Key, out _); } } } - public bool MinCompare(int Id, int Threshold) + public bool MinCompare(int id, int threshold) { - return MinCompare(Id, CounterMin[Id], CounterMax[Id], Threshold); + return MinCompare(id, _counterMin[id], _counterMax[id], threshold); } - private bool MinCompare(int Id, int Min, int Max, int Threshold) + private bool MinCompare(int id, int min, int max, int threshold) { - int MinDiff = Min - Threshold; - int MaxDiff = Max - Threshold; + int minDiff = min - threshold; + int maxDiff = max - threshold; - if (((EventMask >> Id) & 1) != 0) + if (((_eventMask >> id) & 1) != 0) { - return MinDiff >= 0; + return minDiff >= 0; } else { - return (uint)MaxDiff >= (uint)MinDiff; + return (uint)maxDiff >= (uint)minDiff; } } } diff --git a/Ryujinx.HLE/HOS/Services/Nv/NvMap/NvMapHandle.cs b/Ryujinx.HLE/HOS/Services/Nv/NvMap/NvMapHandle.cs index e97e4ff4..31bf8329 100644 --- a/Ryujinx.HLE/HOS/Services/Nv/NvMap/NvMapHandle.cs +++ b/Ryujinx.HLE/HOS/Services/Nv/NvMap/NvMapHandle.cs @@ -13,26 +13,26 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvMap public bool Allocated; public long DmaMapAddress; - private long Dupes; + private long _dupes; public NvMapHandle() { - Dupes = 1; + _dupes = 1; } - public NvMapHandle(int Size) : this() + public NvMapHandle(int size) : this() { - this.Size = Size; + Size = size; } public void IncrementRefCount() { - Interlocked.Increment(ref Dupes); + Interlocked.Increment(ref _dupes); } public long DecrementRefCount() { - return Interlocked.Decrement(ref Dupes); + return Interlocked.Decrement(ref _dupes); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Services/Nv/NvMap/NvMapIoctl.cs b/Ryujinx.HLE/HOS/Services/Nv/NvMap/NvMapIoctl.cs index adc523e5..75a76b91 100644 --- a/Ryujinx.HLE/HOS/Services/Nv/NvMap/NvMapIoctl.cs +++ b/Ryujinx.HLE/HOS/Services/Nv/NvMap/NvMapIoctl.cs @@ -11,290 +11,290 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvMap { private const int FlagNotFreedYet = 1; - private static ConcurrentDictionary Maps; + private static ConcurrentDictionary _maps; static NvMapIoctl() { - Maps = new ConcurrentDictionary(); + _maps = new ConcurrentDictionary(); } - public static int ProcessIoctl(ServiceCtx Context, int Cmd) + public static int ProcessIoctl(ServiceCtx context, int cmd) { - switch (Cmd & 0xffff) + switch (cmd & 0xffff) { - case 0x0101: return Create(Context); - case 0x0103: return FromId(Context); - case 0x0104: return Alloc (Context); - case 0x0105: return Free (Context); - case 0x0109: return Param (Context); - case 0x010e: return GetId (Context); + case 0x0101: return Create(context); + case 0x0103: return FromId(context); + case 0x0104: return Alloc (context); + case 0x0105: return Free (context); + case 0x0109: return Param (context); + case 0x010e: return GetId (context); } - Logger.PrintWarning(LogClass.ServiceNv, $"Unsupported Ioctl command 0x{Cmd:x8}!"); + Logger.PrintWarning(LogClass.ServiceNv, $"Unsupported Ioctl command 0x{cmd:x8}!"); return NvResult.NotSupported; } - private static int Create(ServiceCtx Context) + private static int Create(ServiceCtx context) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; - NvMapCreate Args = MemoryHelper.Read(Context.Memory, InputPosition); + NvMapCreate args = MemoryHelper.Read(context.Memory, inputPosition); - if (Args.Size == 0) + if (args.Size == 0) { - Logger.PrintWarning(LogClass.ServiceNv, $"Invalid size 0x{Args.Size:x8}!"); + Logger.PrintWarning(LogClass.ServiceNv, $"Invalid size 0x{args.Size:x8}!"); return NvResult.InvalidInput; } - int Size = IntUtils.AlignUp(Args.Size, NvGpuVmm.PageSize); + int size = IntUtils.AlignUp(args.Size, NvGpuVmm.PageSize); - Args.Handle = AddNvMap(Context, new NvMapHandle(Size)); + args.Handle = AddNvMap(context, new NvMapHandle(size)); - Logger.PrintInfo(LogClass.ServiceNv, $"Created map {Args.Handle} with size 0x{Size:x8}!"); + Logger.PrintInfo(LogClass.ServiceNv, $"Created map {args.Handle} with size 0x{size:x8}!"); - MemoryHelper.Write(Context.Memory, OutputPosition, Args); + MemoryHelper.Write(context.Memory, outputPosition, args); return NvResult.Success; } - private static int FromId(ServiceCtx Context) + private static int FromId(ServiceCtx context) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; - NvMapFromId Args = MemoryHelper.Read(Context.Memory, InputPosition); + NvMapFromId args = MemoryHelper.Read(context.Memory, inputPosition); - NvMapHandle Map = GetNvMap(Context, Args.Id); + NvMapHandle map = GetNvMap(context, args.Id); - if (Map == null) + if (map == null) { - Logger.PrintWarning(LogClass.ServiceNv, $"Invalid handle 0x{Args.Handle:x8}!"); + Logger.PrintWarning(LogClass.ServiceNv, $"Invalid handle 0x{args.Handle:x8}!"); return NvResult.InvalidInput; } - Map.IncrementRefCount(); + map.IncrementRefCount(); - Args.Handle = Args.Id; + args.Handle = args.Id; - MemoryHelper.Write(Context.Memory, OutputPosition, Args); + MemoryHelper.Write(context.Memory, outputPosition, args); return NvResult.Success; } - private static int Alloc(ServiceCtx Context) + private static int Alloc(ServiceCtx context) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; - NvMapAlloc Args = MemoryHelper.Read(Context.Memory, InputPosition); + NvMapAlloc args = MemoryHelper.Read(context.Memory, inputPosition); - NvMapHandle Map = GetNvMap(Context, Args.Handle); + NvMapHandle map = GetNvMap(context, args.Handle); - if (Map == null) + if (map == null) { - Logger.PrintWarning(LogClass.ServiceNv, $"Invalid handle 0x{Args.Handle:x8}!"); + Logger.PrintWarning(LogClass.ServiceNv, $"Invalid handle 0x{args.Handle:x8}!"); return NvResult.InvalidInput; } - if ((Args.Align & (Args.Align - 1)) != 0) + if ((args.Align & (args.Align - 1)) != 0) { - Logger.PrintWarning(LogClass.ServiceNv, $"Invalid alignment 0x{Args.Align:x8}!"); + Logger.PrintWarning(LogClass.ServiceNv, $"Invalid alignment 0x{args.Align:x8}!"); return NvResult.InvalidInput; } - if ((uint)Args.Align < NvGpuVmm.PageSize) + if ((uint)args.Align < NvGpuVmm.PageSize) { - Args.Align = NvGpuVmm.PageSize; + args.Align = NvGpuVmm.PageSize; } - int Result = NvResult.Success; + int result = NvResult.Success; - if (!Map.Allocated) + if (!map.Allocated) { - Map.Allocated = true; + map.Allocated = true; - Map.Align = Args.Align; - Map.Kind = (byte)Args.Kind; + map.Align = args.Align; + map.Kind = (byte)args.Kind; - int Size = IntUtils.AlignUp(Map.Size, NvGpuVmm.PageSize); + int size = IntUtils.AlignUp(map.Size, NvGpuVmm.PageSize); - long Address = Args.Address; + long address = args.Address; - if (Address == 0) + if (address == 0) { //When the address is zero, we need to allocate //our own backing memory for the NvMap. //TODO: Is this allocation inside the transfer memory? - Result = NvResult.OutOfMemory; + result = NvResult.OutOfMemory; } - if (Result == NvResult.Success) + if (result == NvResult.Success) { - Map.Size = Size; - Map.Address = Address; + map.Size = size; + map.Address = address; } } - MemoryHelper.Write(Context.Memory, OutputPosition, Args); + MemoryHelper.Write(context.Memory, outputPosition, args); - return Result; + return result; } - private static int Free(ServiceCtx Context) + private static int Free(ServiceCtx context) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; - NvMapFree Args = MemoryHelper.Read(Context.Memory, InputPosition); + NvMapFree args = MemoryHelper.Read(context.Memory, inputPosition); - NvMapHandle Map = GetNvMap(Context, Args.Handle); + NvMapHandle map = GetNvMap(context, args.Handle); - if (Map == null) + if (map == null) { - Logger.PrintWarning(LogClass.ServiceNv, $"Invalid handle 0x{Args.Handle:x8}!"); + Logger.PrintWarning(LogClass.ServiceNv, $"Invalid handle 0x{args.Handle:x8}!"); return NvResult.InvalidInput; } - if (Map.DecrementRefCount() <= 0) + if (map.DecrementRefCount() <= 0) { - DeleteNvMap(Context, Args.Handle); + DeleteNvMap(context, args.Handle); - Logger.PrintInfo(LogClass.ServiceNv, $"Deleted map {Args.Handle}!"); + Logger.PrintInfo(LogClass.ServiceNv, $"Deleted map {args.Handle}!"); - Args.Address = Map.Address; - Args.Flags = 0; + args.Address = map.Address; + args.Flags = 0; } else { - Args.Address = 0; - Args.Flags = FlagNotFreedYet; + args.Address = 0; + args.Flags = FlagNotFreedYet; } - Args.Size = Map.Size; + args.Size = map.Size; - MemoryHelper.Write(Context.Memory, OutputPosition, Args); + MemoryHelper.Write(context.Memory, outputPosition, args); return NvResult.Success; } - private static int Param(ServiceCtx Context) + private static int Param(ServiceCtx context) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; - NvMapParam Args = MemoryHelper.Read(Context.Memory, InputPosition); + NvMapParam args = MemoryHelper.Read(context.Memory, inputPosition); - NvMapHandle Map = GetNvMap(Context, Args.Handle); + NvMapHandle map = GetNvMap(context, args.Handle); - if (Map == null) + if (map == null) { - Logger.PrintWarning(LogClass.ServiceNv, $"Invalid handle 0x{Args.Handle:x8}!"); + Logger.PrintWarning(LogClass.ServiceNv, $"Invalid handle 0x{args.Handle:x8}!"); return NvResult.InvalidInput; } - switch ((NvMapHandleParam)Args.Param) + switch ((NvMapHandleParam)args.Param) { - case NvMapHandleParam.Size: Args.Result = Map.Size; break; - case NvMapHandleParam.Align: Args.Result = Map.Align; break; - case NvMapHandleParam.Heap: Args.Result = 0x40000000; break; - case NvMapHandleParam.Kind: Args.Result = Map.Kind; break; - case NvMapHandleParam.Compr: Args.Result = 0; break; + case NvMapHandleParam.Size: args.Result = map.Size; break; + case NvMapHandleParam.Align: args.Result = map.Align; break; + case NvMapHandleParam.Heap: args.Result = 0x40000000; break; + case NvMapHandleParam.Kind: args.Result = map.Kind; break; + case NvMapHandleParam.Compr: args.Result = 0; break; //Note: Base is not supported and returns an error. //Any other value also returns an error. default: return NvResult.InvalidInput; } - MemoryHelper.Write(Context.Memory, OutputPosition, Args); + MemoryHelper.Write(context.Memory, outputPosition, args); return NvResult.Success; } - private static int GetId(ServiceCtx Context) + private static int GetId(ServiceCtx context) { - long InputPosition = Context.Request.GetBufferType0x21().Position; - long OutputPosition = Context.Request.GetBufferType0x22().Position; + long inputPosition = context.Request.GetBufferType0x21().Position; + long outputPosition = context.Request.GetBufferType0x22().Position; - NvMapGetId Args = MemoryHelper.Read(Context.Memory, InputPosition); + NvMapGetId args = MemoryHelper.Read(context.Memory, inputPosition); - NvMapHandle Map = GetNvMap(Context, Args.Handle); + NvMapHandle map = GetNvMap(context, args.Handle); - if (Map == null) + if (map == null) { - Logger.PrintWarning(LogClass.ServiceNv, $"Invalid handle 0x{Args.Handle:x8}!"); + Logger.PrintWarning(LogClass.ServiceNv, $"Invalid handle 0x{args.Handle:x8}!"); return NvResult.InvalidInput; } - Args.Id = Args.Handle; + args.Id = args.Handle; - MemoryHelper.Write(Context.Memory, OutputPosition, Args); + MemoryHelper.Write(context.Memory, outputPosition, args); return NvResult.Success; } - private static int AddNvMap(ServiceCtx Context, NvMapHandle Map) + private static int AddNvMap(ServiceCtx context, NvMapHandle map) { - IdDictionary Dict = Maps.GetOrAdd(Context.Process, (Key) => + IdDictionary dict = _maps.GetOrAdd(context.Process, (key) => { - IdDictionary NewDict = new IdDictionary(); + IdDictionary newDict = new IdDictionary(); - NewDict.Add(0, new NvMapHandle()); + newDict.Add(0, new NvMapHandle()); - return NewDict; + return newDict; }); - return Dict.Add(Map); + return dict.Add(map); } - private static bool DeleteNvMap(ServiceCtx Context, int Handle) + private static bool DeleteNvMap(ServiceCtx context, int handle) { - if (Maps.TryGetValue(Context.Process, out IdDictionary Dict)) + if (_maps.TryGetValue(context.Process, out IdDictionary dict)) { - return Dict.Delete(Handle) != null; + return dict.Delete(handle) != null; } return false; } - public static void InitializeNvMap(ServiceCtx Context) + public static void InitializeNvMap(ServiceCtx context) { - IdDictionary Dict = Maps.GetOrAdd(Context.Process, (Key) =>new IdDictionary()); + IdDictionary dict = _maps.GetOrAdd(context.Process, (key) =>new IdDictionary()); - Dict.Add(0, new NvMapHandle()); + dict.Add(0, new NvMapHandle()); } - public static NvMapHandle GetNvMapWithFb(ServiceCtx Context, int Handle) + public static NvMapHandle GetNvMapWithFb(ServiceCtx context, int handle) { - if (Maps.TryGetValue(Context.Process, out IdDictionary Dict)) + if (_maps.TryGetValue(context.Process, out IdDictionary dict)) { - return Dict.GetData(Handle); + return dict.GetData(handle); } return null; } - public static NvMapHandle GetNvMap(ServiceCtx Context, int Handle) + public static NvMapHandle GetNvMap(ServiceCtx context, int handle) { - if (Handle != 0 && Maps.TryGetValue(Context.Process, out IdDictionary Dict)) + if (handle != 0 && _maps.TryGetValue(context.Process, out IdDictionary dict)) { - return Dict.GetData(Handle); + return dict.GetData(handle); } return null; } - public static void UnloadProcess(KProcess Process) + public static void UnloadProcess(KProcess process) { - Maps.TryRemove(Process, out _); + _maps.TryRemove(process, out _); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Services/Pctl/IParentalControlService.cs b/Ryujinx.HLE/HOS/Services/Pctl/IParentalControlService.cs index 3e9d276a..0c539aa1 100644 --- a/Ryujinx.HLE/HOS/Services/Pctl/IParentalControlService.cs +++ b/Ryujinx.HLE/HOS/Services/Pctl/IParentalControlService.cs @@ -6,29 +6,29 @@ namespace Ryujinx.HLE.HOS.Services.Pctl { class IParentalControlService : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - private bool Initialized = false; + private bool _initialized = false; - private bool NeedInitialize; + private bool _needInitialize; - public IParentalControlService(bool NeedInitialize = true) + public IParentalControlService(bool needInitialize = true) { - m_Commands = new Dictionary() + _commands = new Dictionary { { 1, Initialize } }; - this.NeedInitialize = NeedInitialize; + _needInitialize = needInitialize; } - public long Initialize(ServiceCtx Context) + public long Initialize(ServiceCtx context) { - if (NeedInitialize && !Initialized) + if (_needInitialize && !_initialized) { - Initialized = true; + _initialized = true; } else { diff --git a/Ryujinx.HLE/HOS/Services/Pctl/IParentalControlServiceFactory.cs b/Ryujinx.HLE/HOS/Services/Pctl/IParentalControlServiceFactory.cs index 157d594d..92500187 100644 --- a/Ryujinx.HLE/HOS/Services/Pctl/IParentalControlServiceFactory.cs +++ b/Ryujinx.HLE/HOS/Services/Pctl/IParentalControlServiceFactory.cs @@ -5,29 +5,29 @@ namespace Ryujinx.HLE.HOS.Services.Pctl { class IParentalControlServiceFactory : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IParentalControlServiceFactory() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, CreateService }, { 1, CreateServiceWithoutInitialize } }; } - public long CreateService(ServiceCtx Context) + public long CreateService(ServiceCtx context) { - MakeObject(Context, new IParentalControlService()); + MakeObject(context, new IParentalControlService()); return 0; } - public long CreateServiceWithoutInitialize(ServiceCtx Context) + public long CreateServiceWithoutInitialize(ServiceCtx context) { - MakeObject(Context, new IParentalControlService(false)); + MakeObject(context, new IParentalControlService(false)); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Pl/ISharedFontManager.cs b/Ryujinx.HLE/HOS/Services/Pl/ISharedFontManager.cs index 0495a388..c555c504 100644 --- a/Ryujinx.HLE/HOS/Services/Pl/ISharedFontManager.cs +++ b/Ryujinx.HLE/HOS/Services/Pl/ISharedFontManager.cs @@ -8,13 +8,13 @@ namespace Ryujinx.HLE.HOS.Services.Pl { class ISharedFontManager : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public ISharedFontManager() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, RequestLoad }, { 1, GetLoadState }, @@ -25,104 +25,104 @@ namespace Ryujinx.HLE.HOS.Services.Pl }; } - public long RequestLoad(ServiceCtx Context) + public long RequestLoad(ServiceCtx context) { - SharedFontType FontType = (SharedFontType)Context.RequestData.ReadInt32(); + SharedFontType fontType = (SharedFontType)context.RequestData.ReadInt32(); //We don't need to do anything here because we do lazy initialization //on SharedFontManager (the font is loaded when necessary). return 0; } - public long GetLoadState(ServiceCtx Context) + public long GetLoadState(ServiceCtx context) { - SharedFontType FontType = (SharedFontType)Context.RequestData.ReadInt32(); + SharedFontType fontType = (SharedFontType)context.RequestData.ReadInt32(); //1 (true) indicates that the font is already loaded. //All fonts are already loaded. - Context.ResponseData.Write(1); + context.ResponseData.Write(1); return 0; } - public long GetFontSize(ServiceCtx Context) + public long GetFontSize(ServiceCtx context) { - SharedFontType FontType = (SharedFontType)Context.RequestData.ReadInt32(); + SharedFontType fontType = (SharedFontType)context.RequestData.ReadInt32(); - Context.ResponseData.Write(Context.Device.System.Font.GetFontSize(FontType)); + context.ResponseData.Write(context.Device.System.Font.GetFontSize(fontType)); return 0; } - public long GetSharedMemoryAddressOffset(ServiceCtx Context) + public long GetSharedMemoryAddressOffset(ServiceCtx context) { - SharedFontType FontType = (SharedFontType)Context.RequestData.ReadInt32(); + SharedFontType fontType = (SharedFontType)context.RequestData.ReadInt32(); - Context.ResponseData.Write(Context.Device.System.Font.GetSharedMemoryAddressOffset(FontType)); + context.ResponseData.Write(context.Device.System.Font.GetSharedMemoryAddressOffset(fontType)); return 0; } - public long GetSharedMemoryNativeHandle(ServiceCtx Context) + public long GetSharedMemoryNativeHandle(ServiceCtx context) { - Context.Device.System.Font.EnsureInitialized(Context.Device.System.ContentManager); + context.Device.System.Font.EnsureInitialized(context.Device.System.ContentManager); - if (Context.Process.HandleTable.GenerateHandle(Context.Device.System.FontSharedMem, out int Handle) != KernelResult.Success) + if (context.Process.HandleTable.GenerateHandle(context.Device.System.FontSharedMem, out int handle) != KernelResult.Success) { throw new InvalidOperationException("Out of handles!"); } - Context.Response.HandleDesc = IpcHandleDesc.MakeCopy(Handle); + context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); return 0; } - public long GetSharedFontInOrderOfPriority(ServiceCtx Context) + public long GetSharedFontInOrderOfPriority(ServiceCtx context) { - long LanguageCode = Context.RequestData.ReadInt64(); - int LoadedCount = 0; + long languageCode = context.RequestData.ReadInt64(); + int loadedCount = 0; - for (SharedFontType Type = 0; Type < SharedFontType.Count; Type++) + for (SharedFontType type = 0; type < SharedFontType.Count; type++) { - int Offset = (int)Type * 4; + int offset = (int)type * 4; - if (!AddFontToOrderOfPriorityList(Context, (SharedFontType)Type, Offset)) + if (!AddFontToOrderOfPriorityList(context, type, offset)) { break; } - LoadedCount++; + loadedCount++; } - Context.ResponseData.Write(LoadedCount); - Context.ResponseData.Write((int)SharedFontType.Count); + context.ResponseData.Write(loadedCount); + context.ResponseData.Write((int)SharedFontType.Count); return 0; } - private bool AddFontToOrderOfPriorityList(ServiceCtx Context, SharedFontType FontType, int Offset) + private bool AddFontToOrderOfPriorityList(ServiceCtx context, SharedFontType fontType, int offset) { - long TypesPosition = Context.Request.ReceiveBuff[0].Position; - long TypesSize = Context.Request.ReceiveBuff[0].Size; + long typesPosition = context.Request.ReceiveBuff[0].Position; + long typesSize = context.Request.ReceiveBuff[0].Size; - long OffsetsPosition = Context.Request.ReceiveBuff[1].Position; - long OffsetsSize = Context.Request.ReceiveBuff[1].Size; + long offsetsPosition = context.Request.ReceiveBuff[1].Position; + long offsetsSize = context.Request.ReceiveBuff[1].Size; - long FontSizeBufferPosition = Context.Request.ReceiveBuff[2].Position; - long FontSizeBufferSize = Context.Request.ReceiveBuff[2].Size; + long fontSizeBufferPosition = context.Request.ReceiveBuff[2].Position; + long fontSizeBufferSize = context.Request.ReceiveBuff[2].Size; - if ((uint)Offset + 4 > (uint)TypesSize || - (uint)Offset + 4 > (uint)OffsetsSize || - (uint)Offset + 4 > (uint)FontSizeBufferSize) + if ((uint)offset + 4 > (uint)typesSize || + (uint)offset + 4 > (uint)offsetsSize || + (uint)offset + 4 > (uint)fontSizeBufferSize) { return false; } - Context.Memory.WriteInt32(TypesPosition + Offset, (int)FontType); + context.Memory.WriteInt32(typesPosition + offset, (int)fontType); - Context.Memory.WriteInt32(OffsetsPosition + Offset, Context.Device.System.Font.GetSharedMemoryAddressOffset(FontType)); + context.Memory.WriteInt32(offsetsPosition + offset, context.Device.System.Font.GetSharedMemoryAddressOffset(fontType)); - Context.Memory.WriteInt32(FontSizeBufferPosition + Offset, Context.Device.System.Font.GetFontSize(FontType)); + context.Memory.WriteInt32(fontSizeBufferPosition + offset, context.Device.System.Font.GetFontSize(fontType)); return true; } diff --git a/Ryujinx.HLE/HOS/Services/Prepo/IPrepoService.cs b/Ryujinx.HLE/HOS/Services/Prepo/IPrepoService.cs index cc96a5c9..f8198fa9 100644 --- a/Ryujinx.HLE/HOS/Services/Prepo/IPrepoService.cs +++ b/Ryujinx.HLE/HOS/Services/Prepo/IPrepoService.cs @@ -6,19 +6,19 @@ namespace Ryujinx.HLE.HOS.Services.Prepo { class IPrepoService : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IPrepoService() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 10101, SaveReportWithUser } }; } - public static long SaveReportWithUser(ServiceCtx Context) + public static long SaveReportWithUser(ServiceCtx context) { Logger.PrintStub(LogClass.ServicePrepo, "Stubbed."); diff --git a/Ryujinx.HLE/HOS/Services/Psm/IPsmServer.cs b/Ryujinx.HLE/HOS/Services/Psm/IPsmServer.cs index 0b45e3c9..c7f6083c 100644 --- a/Ryujinx.HLE/HOS/Services/Psm/IPsmServer.cs +++ b/Ryujinx.HLE/HOS/Services/Psm/IPsmServer.cs @@ -6,20 +6,20 @@ namespace Ryujinx.HLE.HOS.Services.Psm { class IPsmServer : IpcService { - enum ChargerType : int + enum ChargerType { None, ChargerOrDock, UsbC } - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IPsmServer() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, GetBatteryChargePercentage }, { 1, GetChargerType }, @@ -28,21 +28,21 @@ namespace Ryujinx.HLE.HOS.Services.Psm } // GetBatteryChargePercentage() -> u32 - public static long GetBatteryChargePercentage(ServiceCtx Context) + public static long GetBatteryChargePercentage(ServiceCtx context) { - int ChargePercentage = 100; + int chargePercentage = 100; - Context.ResponseData.Write(ChargePercentage); + context.ResponseData.Write(chargePercentage); - Logger.PrintStub(LogClass.ServicePsm, $"Stubbed. ChargePercentage: {ChargePercentage}"); + Logger.PrintStub(LogClass.ServicePsm, $"Stubbed. ChargePercentage: {chargePercentage}"); return 0; } // GetChargerType() -> u32 - public static long GetChargerType(ServiceCtx Context) + public static long GetChargerType(ServiceCtx context) { - Context.ResponseData.Write((int)ChargerType.ChargerOrDock); + context.ResponseData.Write((int)ChargerType.ChargerOrDock); Logger.PrintStub(LogClass.ServicePsm, $"Stubbed. ChargerType: {ChargerType.ChargerOrDock}"); @@ -50,9 +50,9 @@ namespace Ryujinx.HLE.HOS.Services.Psm } // OpenSession() -> IPsmSession - public long OpenSession(ServiceCtx Context) + public long OpenSession(ServiceCtx context) { - MakeObject(Context, new IPsmSession(Context.Device.System)); + MakeObject(context, new IPsmSession(context.Device.System)); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Psm/IPsmSession.cs b/Ryujinx.HLE/HOS/Services/Psm/IPsmSession.cs index 30e5d532..4763f2d5 100644 --- a/Ryujinx.HLE/HOS/Services/Psm/IPsmSession.cs +++ b/Ryujinx.HLE/HOS/Services/Psm/IPsmSession.cs @@ -7,16 +7,16 @@ namespace Ryujinx.HLE.HOS.Services.Psm { class IPsmSession : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - private KEvent StateChangeEvent; - private int StateChangeEventHandle; + private KEvent _stateChangeEvent; + private int _stateChangeEventHandle; - public IPsmSession(Horizon System) + public IPsmSession(Horizon system) { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, BindStateChangeEvent }, { 1, UnbindStateChangeEvent }, @@ -25,24 +25,24 @@ namespace Ryujinx.HLE.HOS.Services.Psm { 4, SetBatteryVoltageStateChangeEventEnabled } }; - StateChangeEvent = new KEvent(System); - StateChangeEventHandle = -1; + _stateChangeEvent = new KEvent(system); + _stateChangeEventHandle = -1; } // BindStateChangeEvent() -> KObject - public long BindStateChangeEvent(ServiceCtx Context) + public long BindStateChangeEvent(ServiceCtx context) { - if (StateChangeEventHandle == -1) + if (_stateChangeEventHandle == -1) { - KernelResult ResultCode = Context.Process.HandleTable.GenerateHandle(StateChangeEvent, out int StateChangeEventHandle); + KernelResult resultCode = context.Process.HandleTable.GenerateHandle(_stateChangeEvent, out int stateChangeEventHandle); - if (ResultCode != KernelResult.Success) + if (resultCode != KernelResult.Success) { - return (long)ResultCode; + return (long)resultCode; } } - Context.Response.HandleDesc = IpcHandleDesc.MakeCopy(StateChangeEventHandle); + context.Response.HandleDesc = IpcHandleDesc.MakeCopy(_stateChangeEventHandle); Logger.PrintStub(LogClass.ServicePsm, "Stubbed."); @@ -50,12 +50,12 @@ namespace Ryujinx.HLE.HOS.Services.Psm } // UnbindStateChangeEvent() - public long UnbindStateChangeEvent(ServiceCtx Context) + public long UnbindStateChangeEvent(ServiceCtx context) { - if (StateChangeEventHandle != -1) + if (_stateChangeEventHandle != -1) { - Context.Process.HandleTable.CloseHandle(StateChangeEventHandle); - StateChangeEventHandle = -1; + context.Process.HandleTable.CloseHandle(_stateChangeEventHandle); + _stateChangeEventHandle = -1; } Logger.PrintStub(LogClass.ServicePsm, "Stubbed."); @@ -64,31 +64,31 @@ namespace Ryujinx.HLE.HOS.Services.Psm } // SetChargerTypeChangeEventEnabled(u8) - public long SetChargerTypeChangeEventEnabled(ServiceCtx Context) + public long SetChargerTypeChangeEventEnabled(ServiceCtx context) { - bool ChargerTypeChangeEventEnabled = Context.RequestData.ReadBoolean(); + bool chargerTypeChangeEventEnabled = context.RequestData.ReadBoolean(); - Logger.PrintStub(LogClass.ServicePsm, $"Stubbed. ChargerTypeChangeEventEnabled: {ChargerTypeChangeEventEnabled}"); + Logger.PrintStub(LogClass.ServicePsm, $"Stubbed. ChargerTypeChangeEventEnabled: {chargerTypeChangeEventEnabled}"); return 0; } // SetPowerSupplyChangeEventEnabled(u8) - public long SetPowerSupplyChangeEventEnabled(ServiceCtx Context) + public long SetPowerSupplyChangeEventEnabled(ServiceCtx context) { - bool PowerSupplyChangeEventEnabled = Context.RequestData.ReadBoolean(); + bool powerSupplyChangeEventEnabled = context.RequestData.ReadBoolean(); - Logger.PrintStub(LogClass.ServicePsm, $"Stubbed. PowerSupplyChangeEventEnabled: {PowerSupplyChangeEventEnabled}"); + Logger.PrintStub(LogClass.ServicePsm, $"Stubbed. PowerSupplyChangeEventEnabled: {powerSupplyChangeEventEnabled}"); return 0; } // SetBatteryVoltageStateChangeEventEnabled(u8) - public long SetBatteryVoltageStateChangeEventEnabled(ServiceCtx Context) + public long SetBatteryVoltageStateChangeEventEnabled(ServiceCtx context) { - bool BatteryVoltageStateChangeEventEnabled = Context.RequestData.ReadBoolean(); + bool batteryVoltageStateChangeEventEnabled = context.RequestData.ReadBoolean(); - Logger.PrintStub(LogClass.ServicePsm, $"Stubbed. BatteryVoltageStateChangeEventEnabled: {BatteryVoltageStateChangeEventEnabled}"); + Logger.PrintStub(LogClass.ServicePsm, $"Stubbed. BatteryVoltageStateChangeEventEnabled: {batteryVoltageStateChangeEventEnabled}"); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/ServiceFactory.cs b/Ryujinx.HLE/HOS/Services/ServiceFactory.cs index 2be1db70..3853d82e 100644 --- a/Ryujinx.HLE/HOS/Services/ServiceFactory.cs +++ b/Ryujinx.HLE/HOS/Services/ServiceFactory.cs @@ -31,9 +31,9 @@ namespace Ryujinx.HLE.HOS.Services { static class ServiceFactory { - public static IpcService MakeService(Horizon System, string Name) + public static IpcService MakeService(Horizon system, string name) { - switch (Name) + switch (name) { case "acc:u0": return new IAccountService(); @@ -90,7 +90,7 @@ namespace Ryujinx.HLE.HOS.Services return new IRandomInterface(); case "es": - return new IETicketService(); + return new IeTicketService(); case "friend:a": return new Friend.IServiceCreator(); @@ -102,7 +102,7 @@ namespace Ryujinx.HLE.HOS.Services return new IFileSystemProxy(); case "hid": - return new IHidServer(System); + return new IHidServer(system); case "irs": return new IIrSensorServer(); @@ -141,10 +141,10 @@ namespace Ryujinx.HLE.HOS.Services return new IVulnerabilityManagerInterface(); case "nvdrv": - return new INvDrvServices(System); + return new INvDrvServices(system); case "nvdrv:a": - return new INvDrvServices(System); + return new INvDrvServices(system); case "pctl:s": return new IParentalControlServiceFactory(); @@ -204,7 +204,7 @@ namespace Ryujinx.HLE.HOS.Services return new IApplicationRootService(); } - throw new NotImplementedException(Name); + throw new NotImplementedException(name); } } } diff --git a/Ryujinx.HLE/HOS/Services/Set/ISettingsServer.cs b/Ryujinx.HLE/HOS/Services/Set/ISettingsServer.cs index 690d6de9..bc812d5c 100644 --- a/Ryujinx.HLE/HOS/Services/Set/ISettingsServer.cs +++ b/Ryujinx.HLE/HOS/Services/Set/ISettingsServer.cs @@ -6,13 +6,13 @@ namespace Ryujinx.HLE.HOS.Services.Set { class ISettingsServer : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public ISettingsServer() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, GetLanguageCode }, { 1, GetAvailableLanguageCodes }, @@ -21,57 +21,57 @@ namespace Ryujinx.HLE.HOS.Services.Set }; } - public static long GetLanguageCode(ServiceCtx Context) + public static long GetLanguageCode(ServiceCtx context) { - Context.ResponseData.Write(Context.Device.System.State.DesiredLanguageCode); + context.ResponseData.Write(context.Device.System.State.DesiredLanguageCode); return 0; } - public static long GetAvailableLanguageCodes(ServiceCtx Context) + public static long GetAvailableLanguageCodes(ServiceCtx context) { GetAvailableLanguagesCodesImpl( - Context, - Context.Request.RecvListBuff[0].Position, - Context.Request.RecvListBuff[0].Size); + context, + context.Request.RecvListBuff[0].Position, + context.Request.RecvListBuff[0].Size); return 0; } - public static long GetAvailableLanguageCodeCount(ServiceCtx Context) + public static long GetAvailableLanguageCodeCount(ServiceCtx context) { - Context.ResponseData.Write(SystemStateMgr.LanguageCodes.Length); + context.ResponseData.Write(SystemStateMgr.LanguageCodes.Length); return 0; } - public static long GetAvailableLanguageCodes2(ServiceCtx Context) + public static long GetAvailableLanguageCodes2(ServiceCtx context) { GetAvailableLanguagesCodesImpl( - Context, - Context.Request.ReceiveBuff[0].Position, - Context.Request.ReceiveBuff[0].Size); + context, + context.Request.ReceiveBuff[0].Position, + context.Request.ReceiveBuff[0].Size); return 0; } - public static long GetAvailableLanguagesCodesImpl(ServiceCtx Context, long Position, long Size) + public static long GetAvailableLanguagesCodesImpl(ServiceCtx context, long position, long size) { - int Count = (int)(Size / 8); + int count = (int)(size / 8); - if (Count > SystemStateMgr.LanguageCodes.Length) + if (count > SystemStateMgr.LanguageCodes.Length) { - Count = SystemStateMgr.LanguageCodes.Length; + count = SystemStateMgr.LanguageCodes.Length; } - for (int Index = 0; Index < Count; Index++) + for (int index = 0; index < count; index++) { - Context.Memory.WriteInt64(Position, SystemStateMgr.GetLanguageCode(Index)); + context.Memory.WriteInt64(position, SystemStateMgr.GetLanguageCode(index)); - Position += 8; + position += 8; } - Context.ResponseData.Write(Count); + context.ResponseData.Write(count); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Set/ISystemSettingsServer.cs b/Ryujinx.HLE/HOS/Services/Set/ISystemSettingsServer.cs index 416ea1fb..b4464b77 100644 --- a/Ryujinx.HLE/HOS/Services/Set/ISystemSettingsServer.cs +++ b/Ryujinx.HLE/HOS/Services/Set/ISystemSettingsServer.cs @@ -12,13 +12,13 @@ namespace Ryujinx.HLE.HOS.Services.Set { class ISystemSettingsServer : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public ISystemSettingsServer() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 3, GetFirmwareVersion }, { 4, GetFirmwareVersion2 }, @@ -29,185 +29,185 @@ namespace Ryujinx.HLE.HOS.Services.Set } // GetFirmwareVersion() -> buffer - public static long GetFirmwareVersion(ServiceCtx Context) + public static long GetFirmwareVersion(ServiceCtx context) { - return GetFirmwareVersion2(Context); + return GetFirmwareVersion2(context); } // GetFirmwareVersion2() -> buffer - public static long GetFirmwareVersion2(ServiceCtx Context) + public static long GetFirmwareVersion2(ServiceCtx context) { - long ReplyPos = Context.Request.RecvListBuff[0].Position; - long ReplySize = Context.Request.RecvListBuff[0].Size; + long replyPos = context.Request.RecvListBuff[0].Position; + long replySize = context.Request.RecvListBuff[0].Size; - byte[] FirmwareData = GetFirmwareData(Context.Device); + byte[] firmwareData = GetFirmwareData(context.Device); - if (FirmwareData != null) + if (firmwareData != null) { - Context.Memory.WriteBytes(ReplyPos, FirmwareData); + context.Memory.WriteBytes(replyPos, firmwareData); return 0; } - const byte MajorFWVersion = 0x03; - const byte MinorFWVersion = 0x00; - const byte MicroFWVersion = 0x00; - const byte Unknown = 0x00; //Build? + const byte majorFwVersion = 0x03; + const byte minorFwVersion = 0x00; + const byte microFwVersion = 0x00; + const byte unknown = 0x00; //Build? - const int RevisionNumber = 0x0A; + const int revisionNumber = 0x0A; - const string Platform = "NX"; - const string UnknownHex = "7fbde2b0bba4d14107bf836e4643043d9f6c8e47"; - const string Version = "3.0.0"; - const string Build = "NintendoSDK Firmware for NX 3.0.0-10.0"; + const string platform = "NX"; + const string unknownHex = "7fbde2b0bba4d14107bf836e4643043d9f6c8e47"; + const string version = "3.0.0"; + const string build = "NintendoSDK Firmware for NX 3.0.0-10.0"; //http://switchbrew.org/index.php?title=System_Version_Title - using (MemoryStream MS = new MemoryStream(0x100)) + using (MemoryStream ms = new MemoryStream(0x100)) { - BinaryWriter Writer = new BinaryWriter(MS); + BinaryWriter writer = new BinaryWriter(ms); - Writer.Write(MajorFWVersion); - Writer.Write(MinorFWVersion); - Writer.Write(MicroFWVersion); - Writer.Write(Unknown); + writer.Write(majorFwVersion); + writer.Write(minorFwVersion); + writer.Write(microFwVersion); + writer.Write(unknown); - Writer.Write(RevisionNumber); + writer.Write(revisionNumber); - Writer.Write(Encoding.ASCII.GetBytes(Platform)); + writer.Write(Encoding.ASCII.GetBytes(platform)); - MS.Seek(0x28, SeekOrigin.Begin); + ms.Seek(0x28, SeekOrigin.Begin); - Writer.Write(Encoding.ASCII.GetBytes(UnknownHex)); + writer.Write(Encoding.ASCII.GetBytes(unknownHex)); - MS.Seek(0x68, SeekOrigin.Begin); + ms.Seek(0x68, SeekOrigin.Begin); - Writer.Write(Encoding.ASCII.GetBytes(Version)); + writer.Write(Encoding.ASCII.GetBytes(version)); - MS.Seek(0x80, SeekOrigin.Begin); + ms.Seek(0x80, SeekOrigin.Begin); - Writer.Write(Encoding.ASCII.GetBytes(Build)); + writer.Write(Encoding.ASCII.GetBytes(build)); - Context.Memory.WriteBytes(ReplyPos, MS.ToArray()); + context.Memory.WriteBytes(replyPos, ms.ToArray()); } return 0; } // GetColorSetId() -> i32 - public static long GetColorSetId(ServiceCtx Context) + public static long GetColorSetId(ServiceCtx context) { - Context.ResponseData.Write((int)Context.Device.System.State.ThemeColor); + context.ResponseData.Write((int)context.Device.System.State.ThemeColor); return 0; } // GetColorSetId() -> i32 - public static long SetColorSetId(ServiceCtx Context) + public static long SetColorSetId(ServiceCtx context) { - int ColorSetId = Context.RequestData.ReadInt32(); + int colorSetId = context.RequestData.ReadInt32(); - Context.Device.System.State.ThemeColor = (ColorSet)ColorSetId; + context.Device.System.State.ThemeColor = (ColorSet)colorSetId; return 0; } // GetSettingsItemValue(buffer, buffer) -> (u64, buffer) - public static long GetSettingsItemValue(ServiceCtx Context) + public static long GetSettingsItemValue(ServiceCtx context) { - long ClassPos = Context.Request.PtrBuff[0].Position; - long ClassSize = Context.Request.PtrBuff[0].Size; + long classPos = context.Request.PtrBuff[0].Position; + long classSize = context.Request.PtrBuff[0].Size; - long NamePos = Context.Request.PtrBuff[1].Position; - long NameSize = Context.Request.PtrBuff[1].Size; + long namePos = context.Request.PtrBuff[1].Position; + long nameSize = context.Request.PtrBuff[1].Size; - long ReplyPos = Context.Request.ReceiveBuff[0].Position; - long ReplySize = Context.Request.ReceiveBuff[0].Size; + long replyPos = context.Request.ReceiveBuff[0].Position; + long replySize = context.Request.ReceiveBuff[0].Size; - byte[] Class = Context.Memory.ReadBytes(ClassPos, ClassSize); - byte[] Name = Context.Memory.ReadBytes(NamePos, NameSize); + byte[] Class = context.Memory.ReadBytes(classPos, classSize); + byte[] name = context.Memory.ReadBytes(namePos, nameSize); - string AskedSetting = Encoding.ASCII.GetString(Class).Trim('\0') + "!" + Encoding.ASCII.GetString(Name).Trim('\0'); + string askedSetting = Encoding.ASCII.GetString(Class).Trim('\0') + "!" + Encoding.ASCII.GetString(name).Trim('\0'); - NxSettings.Settings.TryGetValue(AskedSetting, out object NxSetting); + NxSettings.Settings.TryGetValue(askedSetting, out object nxSetting); - if (NxSetting != null) + if (nxSetting != null) { - byte[] SettingBuffer = new byte[ReplySize]; + byte[] settingBuffer = new byte[replySize]; - if (NxSetting is string StringValue) + if (nxSetting is string stringValue) { - if (StringValue.Length + 1 > ReplySize) + if (stringValue.Length + 1 > replySize) { - Logger.PrintError(LogClass.ServiceSet, $"{AskedSetting} String value size is too big!"); + Logger.PrintError(LogClass.ServiceSet, $"{askedSetting} String value size is too big!"); } else { - SettingBuffer = Encoding.ASCII.GetBytes(StringValue + "\0"); + settingBuffer = Encoding.ASCII.GetBytes(stringValue + "\0"); } } - if (NxSetting is int IntValue) + if (nxSetting is int intValue) { - SettingBuffer = BitConverter.GetBytes(IntValue); + settingBuffer = BitConverter.GetBytes(intValue); } - else if (NxSetting is bool BoolValue) + else if (nxSetting is bool boolValue) { - SettingBuffer[0] = BoolValue ? (byte)1 : (byte)0; + settingBuffer[0] = boolValue ? (byte)1 : (byte)0; } else { - throw new NotImplementedException(NxSetting.GetType().Name); + throw new NotImplementedException(nxSetting.GetType().Name); } - Context.Memory.WriteBytes(ReplyPos, SettingBuffer); + context.Memory.WriteBytes(replyPos, settingBuffer); - Logger.PrintDebug(LogClass.ServiceSet, $"{AskedSetting} set value: {NxSetting} as {NxSetting.GetType()}"); + Logger.PrintDebug(LogClass.ServiceSet, $"{askedSetting} set value: {nxSetting} as {nxSetting.GetType()}"); } else { - Logger.PrintError(LogClass.ServiceSet, $"{AskedSetting} not found!"); + Logger.PrintError(LogClass.ServiceSet, $"{askedSetting} not found!"); } return 0; } - public static byte[] GetFirmwareData(Switch Device) + public static byte[] GetFirmwareData(Switch device) { - byte[] Data = null; - long TitleId = 0x0100000000000809; - string ContentPath = Device.System.ContentManager.GetInstalledContentPath(TitleId, StorageId.NandSystem, ContentType.Data); + byte[] data = null; + long titleId = 0x0100000000000809; + string contentPath = device.System.ContentManager.GetInstalledContentPath(titleId, StorageId.NandSystem, ContentType.Data); - if(string.IsNullOrWhiteSpace(ContentPath)) + if(string.IsNullOrWhiteSpace(contentPath)) { return null; } - string FirmwareTitlePath = Device.FileSystem.SwitchPathToSystemPath(ContentPath); - FileStream FirmwareStream = File.Open(FirmwareTitlePath, FileMode.Open, FileAccess.Read); - Nca FirmwareContent = new Nca(Device.System.KeySet, FirmwareStream, false); - Stream RomFsStream = FirmwareContent.OpenSection(0, false, Device.System.FsIntegrityCheckLevel); + string firmwareTitlePath = device.FileSystem.SwitchPathToSystemPath(contentPath); + FileStream firmwareStream = File.Open(firmwareTitlePath, FileMode.Open, FileAccess.Read); + Nca firmwareContent = new Nca(device.System.KeySet, firmwareStream, false); + Stream romFsStream = firmwareContent.OpenSection(0, false, device.System.FsIntegrityCheckLevel); - if(RomFsStream == null) + if(romFsStream == null) { return null; } - Romfs FirmwareRomFs = new Romfs(RomFsStream); + Romfs firmwareRomFs = new Romfs(romFsStream); - using(MemoryStream MemoryStream = new MemoryStream()) + using(MemoryStream memoryStream = new MemoryStream()) { - using (Stream FirmwareFile = FirmwareRomFs.OpenFile("/file")) + using (Stream firmwareFile = firmwareRomFs.OpenFile("/file")) { - FirmwareFile.CopyTo(MemoryStream); + firmwareFile.CopyTo(memoryStream); } - Data = MemoryStream.ToArray(); + data = memoryStream.ToArray(); } - FirmwareContent.Dispose(); - FirmwareStream.Dispose(); + firmwareContent.Dispose(); + firmwareStream.Dispose(); - return Data; + return data; } } } diff --git a/Ryujinx.HLE/HOS/Services/Set/NxSettings.cs b/Ryujinx.HLE/HOS/Services/Set/NxSettings.cs index 7d1dd2ed..70ab55f9 100644 --- a/Ryujinx.HLE/HOS/Services/Set/NxSettings.cs +++ b/Ryujinx.HLE/HOS/Services/Set/NxSettings.cs @@ -5,7 +5,7 @@ namespace Ryujinx.HLE.HOS.Services.Set static class NxSettings { //Generated automatically from a Switch 3.0 config file (Tid: 0100000000000818). - public static Dictionary Settings = new Dictionary() + public static Dictionary Settings = new Dictionary { { "account!na_required_for_network_service", true }, { "account.daemon!background_awaking_periodicity", 10800 }, @@ -1705,7 +1705,7 @@ namespace Ryujinx.HLE.HOS.Services.Set { "time!standard_steady_clock_rtc_update_interval_minutes", 5 }, { "time!standard_network_clock_sufficient_accuracy_minutes", 43200 }, { "usb!usb30_force_enabled", false }, - { "wlan_debug!skip_wlan_boot", false }, + { "wlan_debug!skip_wlan_boot", false } }; } } diff --git a/Ryujinx.HLE/HOS/Services/Sfdnsres/GaiError.cs b/Ryujinx.HLE/HOS/Services/Sfdnsres/GaiError.cs index 65d54577..2d3d8e9b 100644 --- a/Ryujinx.HLE/HOS/Services/Sfdnsres/GaiError.cs +++ b/Ryujinx.HLE/HOS/Services/Sfdnsres/GaiError.cs @@ -17,6 +17,6 @@ BadHints, Protocol, Overflow, - Max, + Max } } diff --git a/Ryujinx.HLE/HOS/Services/Sfdnsres/IResolver.cs b/Ryujinx.HLE/HOS/Services/Sfdnsres/IResolver.cs index a351e3de..5de03551 100644 --- a/Ryujinx.HLE/HOS/Services/Sfdnsres/IResolver.cs +++ b/Ryujinx.HLE/HOS/Services/Sfdnsres/IResolver.cs @@ -12,13 +12,13 @@ namespace Ryujinx.HLE.HOS.Services.Sfdnsres { class IResolver : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IResolver() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, SetDnsAddressesPrivate }, { 1, GetDnsAddressesPrivate }, @@ -28,65 +28,65 @@ namespace Ryujinx.HLE.HOS.Services.Sfdnsres { 5, GetGaiStringError }, { 8, RequestCancelHandle }, { 9, CancelSocketCall }, - { 11, ClearDnsAddresses }, + { 11, ClearDnsAddresses } }; } - private long SerializeHostEnt(ServiceCtx Context, IPHostEntry HostEntry, List Addresses = null) + private long SerializeHostEnt(ServiceCtx context, IPHostEntry hostEntry, List addresses = null) { - long OriginalBufferPosition = Context.Request.ReceiveBuff[0].Position; - long BufferPosition = OriginalBufferPosition; - long BufferSize = Context.Request.ReceiveBuff[0].Size; + long originalBufferPosition = context.Request.ReceiveBuff[0].Position; + long bufferPosition = originalBufferPosition; + long bufferSize = context.Request.ReceiveBuff[0].Size; - string HostName = HostEntry.HostName + '\0'; + string hostName = hostEntry.HostName + '\0'; // h_name - Context.Memory.WriteBytes(BufferPosition, Encoding.ASCII.GetBytes(HostName)); - BufferPosition += HostName.Length; + context.Memory.WriteBytes(bufferPosition, Encoding.ASCII.GetBytes(hostName)); + bufferPosition += hostName.Length; // h_aliases list size - Context.Memory.WriteInt32(BufferPosition, IPAddress.HostToNetworkOrder(HostEntry.Aliases.Length)); - BufferPosition += 4; + context.Memory.WriteInt32(bufferPosition, IPAddress.HostToNetworkOrder(hostEntry.Aliases.Length)); + bufferPosition += 4; // Actual aliases - foreach (string Alias in HostEntry.Aliases) + foreach (string alias in hostEntry.Aliases) { - Context.Memory.WriteBytes(BufferPosition, Encoding.ASCII.GetBytes(Alias + '\0')); - BufferPosition += Alias.Length + 1; + context.Memory.WriteBytes(bufferPosition, Encoding.ASCII.GetBytes(alias + '\0')); + bufferPosition += alias.Length + 1; } // h_addrtype but it's a short (also only support IPv4) - Context.Memory.WriteInt16(BufferPosition, IPAddress.HostToNetworkOrder((short)2)); - BufferPosition += 2; + context.Memory.WriteInt16(bufferPosition, IPAddress.HostToNetworkOrder((short)2)); + bufferPosition += 2; // h_length but it's a short - Context.Memory.WriteInt16(BufferPosition, IPAddress.HostToNetworkOrder((short)4)); - BufferPosition += 2; + context.Memory.WriteInt16(bufferPosition, IPAddress.HostToNetworkOrder((short)4)); + bufferPosition += 2; // Ip address count, we can only support ipv4 (blame Nintendo) - Context.Memory.WriteInt32(BufferPosition, Addresses != null ? IPAddress.HostToNetworkOrder(Addresses.Count) : 0); - BufferPosition += 4; + context.Memory.WriteInt32(bufferPosition, addresses != null ? IPAddress.HostToNetworkOrder(addresses.Count) : 0); + bufferPosition += 4; - if (Addresses != null) + if (addresses != null) { - foreach (IPAddress Ip in Addresses) + foreach (IPAddress ip in addresses) { - Context.Memory.WriteInt32(BufferPosition, IPAddress.HostToNetworkOrder(BitConverter.ToInt32(Ip.GetAddressBytes(), 0))); - BufferPosition += 4; + context.Memory.WriteInt32(bufferPosition, IPAddress.HostToNetworkOrder(BitConverter.ToInt32(ip.GetAddressBytes(), 0))); + bufferPosition += 4; } } - return BufferPosition - OriginalBufferPosition; + return bufferPosition - originalBufferPosition; } - private string GetGaiStringErrorFromErrorCode(GaiError ErrorCode) + private string GetGaiStringErrorFromErrorCode(GaiError errorCode) { - if (ErrorCode > GaiError.Max) + if (errorCode > GaiError.Max) { - ErrorCode = GaiError.Max; + errorCode = GaiError.Max; } - switch (ErrorCode) + switch (errorCode) { case GaiError.AddressFamily: return "Address family for hostname not supported"; @@ -123,275 +123,275 @@ namespace Ryujinx.HLE.HOS.Services.Sfdnsres } } - private string GetHostStringErrorFromErrorCode(NetDBError ErrorCode) + private string GetHostStringErrorFromErrorCode(NetDbError errorCode) { - if (ErrorCode <= NetDBError.Internal) + if (errorCode <= NetDbError.Internal) { return "Resolver internal error"; } - switch (ErrorCode) + switch (errorCode) { - case NetDBError.Success: + case NetDbError.Success: return "Resolver Error 0 (no error)"; - case NetDBError.HostNotFound: + case NetDbError.HostNotFound: return "Unknown host"; - case NetDBError.TryAgain: + case NetDbError.TryAgain: return "Host name lookup failure"; - case NetDBError.NoRecovery: + case NetDbError.NoRecovery: return "Unknown server error"; - case NetDBError.NoData: + case NetDbError.NoData: return "No address associated with name"; default: return "Unknown resolver error"; } } - private List GetIPV4Addresses(IPHostEntry HostEntry) + private List GetIpv4Addresses(IPHostEntry hostEntry) { - List Result = new List(); - foreach (IPAddress Ip in HostEntry.AddressList) + List result = new List(); + foreach (IPAddress ip in hostEntry.AddressList) { - if (Ip.AddressFamily == AddressFamily.InterNetwork) - Result.Add(Ip); + if (ip.AddressFamily == AddressFamily.InterNetwork) + result.Add(ip); } - return Result; + return result; } // SetDnsAddressesPrivate(u32, buffer) - public long SetDnsAddressesPrivate(ServiceCtx Context) + public long SetDnsAddressesPrivate(ServiceCtx context) { - uint Unknown0 = Context.RequestData.ReadUInt32(); - long BufferPosition = Context.Request.SendBuff[0].Position; - long BufferSize = Context.Request.SendBuff[0].Size; + uint unknown0 = context.RequestData.ReadUInt32(); + long bufferPosition = context.Request.SendBuff[0].Position; + long bufferSize = context.Request.SendBuff[0].Size; // TODO: This is stubbed in 2.0.0+, reverse 1.0.0 version for the sake completeness. - Logger.PrintStub(LogClass.ServiceSfdnsres, $"Stubbed. Unknown0: {Unknown0}"); + Logger.PrintStub(LogClass.ServiceSfdnsres, $"Stubbed. Unknown0: {unknown0}"); return MakeError(ErrorModule.Os, 1023); } // GetDnsAddressPrivate(u32) -> buffer - public long GetDnsAddressesPrivate(ServiceCtx Context) + public long GetDnsAddressesPrivate(ServiceCtx context) { - uint Unknown0 = Context.RequestData.ReadUInt32(); + uint unknown0 = context.RequestData.ReadUInt32(); // TODO: This is stubbed in 2.0.0+, reverse 1.0.0 version for the sake completeness. - Logger.PrintStub(LogClass.ServiceSfdnsres, $"Stubbed. Unknown0: {Unknown0}"); + Logger.PrintStub(LogClass.ServiceSfdnsres, $"Stubbed. Unknown0: {unknown0}"); return MakeError(ErrorModule.Os, 1023); } // GetHostByName(u8, u32, u64, pid, buffer) -> (u32, u32, u32, buffer) - public long GetHostByName(ServiceCtx Context) + public long GetHostByName(ServiceCtx context) { - byte[] RawName = Context.Memory.ReadBytes(Context.Request.SendBuff[0].Position, Context.Request.SendBuff[0].Size); - string Name = Encoding.ASCII.GetString(RawName).TrimEnd('\0'); + byte[] rawName = context.Memory.ReadBytes(context.Request.SendBuff[0].Position, context.Request.SendBuff[0].Size); + string name = Encoding.ASCII.GetString(rawName).TrimEnd('\0'); // TODO: use params - bool EnableNsdResolve = Context.RequestData.ReadInt32() == 1; - int TimeOut = Context.RequestData.ReadInt32(); - ulong PidPlaceholder = Context.RequestData.ReadUInt64(); + bool enableNsdResolve = context.RequestData.ReadInt32() == 1; + int timeOut = context.RequestData.ReadInt32(); + ulong pidPlaceholder = context.RequestData.ReadUInt64(); - IPHostEntry HostEntry = null; + IPHostEntry hostEntry = null; - NetDBError NetDBErrorCode = NetDBError.Success; - GaiError Errno = GaiError.Overflow; - long SerializedSize = 0; + NetDbError netDbErrorCode = NetDbError.Success; + GaiError errno = GaiError.Overflow; + long serializedSize = 0; - if (Name.Length <= 255) + if (name.Length <= 255) { try { - HostEntry = Dns.GetHostEntry(Name); + hostEntry = Dns.GetHostEntry(name); } - catch (SocketException Exception) + catch (SocketException exception) { - NetDBErrorCode = NetDBError.Internal; + netDbErrorCode = NetDbError.Internal; - if (Exception.ErrorCode == 11001) + if (exception.ErrorCode == 11001) { - NetDBErrorCode = NetDBError.HostNotFound; - Errno = GaiError.NoData; + netDbErrorCode = NetDbError.HostNotFound; + errno = GaiError.NoData; } - else if (Exception.ErrorCode == 11002) + else if (exception.ErrorCode == 11002) { - NetDBErrorCode = NetDBError.TryAgain; + netDbErrorCode = NetDbError.TryAgain; } - else if (Exception.ErrorCode == 11003) + else if (exception.ErrorCode == 11003) { - NetDBErrorCode = NetDBError.NoRecovery; + netDbErrorCode = NetDbError.NoRecovery; } - else if (Exception.ErrorCode == 11004) + else if (exception.ErrorCode == 11004) { - NetDBErrorCode = NetDBError.NoData; + netDbErrorCode = NetDbError.NoData; } - else if (Exception.ErrorCode == 10060) + else if (exception.ErrorCode == 10060) { - Errno = GaiError.Again; + errno = GaiError.Again; } } } else { - NetDBErrorCode = NetDBError.HostNotFound; + netDbErrorCode = NetDbError.HostNotFound; } - if (HostEntry != null) + if (hostEntry != null) { - Errno = GaiError.Success; + errno = GaiError.Success; - List Addresses = GetIPV4Addresses(HostEntry); + List addresses = GetIpv4Addresses(hostEntry); - if (Addresses.Count == 0) + if (addresses.Count == 0) { - Errno = GaiError.NoData; - NetDBErrorCode = NetDBError.NoAddress; + errno = GaiError.NoData; + netDbErrorCode = NetDbError.NoAddress; } else { - SerializedSize = SerializeHostEnt(Context, HostEntry, Addresses); + serializedSize = SerializeHostEnt(context, hostEntry, addresses); } } - Context.ResponseData.Write((int)NetDBErrorCode); - Context.ResponseData.Write((int)Errno); - Context.ResponseData.Write(SerializedSize); + context.ResponseData.Write((int)netDbErrorCode); + context.ResponseData.Write((int)errno); + context.ResponseData.Write(serializedSize); return 0; } // GetHostByAddr(u32, u32, u32, u64, pid, buffer) -> (u32, u32, u32, buffer) - public long GetHostByAddress(ServiceCtx Context) + public long GetHostByAddress(ServiceCtx context) { - byte[] RawIp = Context.Memory.ReadBytes(Context.Request.SendBuff[0].Position, Context.Request.SendBuff[0].Size); + byte[] rawIp = context.Memory.ReadBytes(context.Request.SendBuff[0].Position, context.Request.SendBuff[0].Size); // TODO: use params - uint SocketLength = Context.RequestData.ReadUInt32(); - uint Type = Context.RequestData.ReadUInt32(); - int TimeOut = Context.RequestData.ReadInt32(); - ulong PidPlaceholder = Context.RequestData.ReadUInt64(); + uint socketLength = context.RequestData.ReadUInt32(); + uint type = context.RequestData.ReadUInt32(); + int timeOut = context.RequestData.ReadInt32(); + ulong pidPlaceholder = context.RequestData.ReadUInt64(); - IPHostEntry HostEntry = null; + IPHostEntry hostEntry = null; - NetDBError NetDBErrorCode = NetDBError.Success; - GaiError Errno = GaiError.AddressFamily; - long SerializedSize = 0; + NetDbError netDbErrorCode = NetDbError.Success; + GaiError errno = GaiError.AddressFamily; + long serializedSize = 0; - if (RawIp.Length == 4) + if (rawIp.Length == 4) { try { - IPAddress Address = new IPAddress(RawIp); + IPAddress address = new IPAddress(rawIp); - HostEntry = Dns.GetHostEntry(Address); + hostEntry = Dns.GetHostEntry(address); } - catch (SocketException Exception) + catch (SocketException exception) { - NetDBErrorCode = NetDBError.Internal; - if (Exception.ErrorCode == 11001) + netDbErrorCode = NetDbError.Internal; + if (exception.ErrorCode == 11001) { - NetDBErrorCode = NetDBError.HostNotFound; - Errno = GaiError.NoData; + netDbErrorCode = NetDbError.HostNotFound; + errno = GaiError.NoData; } - else if (Exception.ErrorCode == 11002) + else if (exception.ErrorCode == 11002) { - NetDBErrorCode = NetDBError.TryAgain; + netDbErrorCode = NetDbError.TryAgain; } - else if (Exception.ErrorCode == 11003) + else if (exception.ErrorCode == 11003) { - NetDBErrorCode = NetDBError.NoRecovery; + netDbErrorCode = NetDbError.NoRecovery; } - else if (Exception.ErrorCode == 11004) + else if (exception.ErrorCode == 11004) { - NetDBErrorCode = NetDBError.NoData; + netDbErrorCode = NetDbError.NoData; } - else if (Exception.ErrorCode == 10060) + else if (exception.ErrorCode == 10060) { - Errno = GaiError.Again; + errno = GaiError.Again; } } } else { - NetDBErrorCode = NetDBError.NoAddress; + netDbErrorCode = NetDbError.NoAddress; } - if (HostEntry != null) + if (hostEntry != null) { - Errno = GaiError.Success; - SerializedSize = SerializeHostEnt(Context, HostEntry, GetIPV4Addresses(HostEntry)); + errno = GaiError.Success; + serializedSize = SerializeHostEnt(context, hostEntry, GetIpv4Addresses(hostEntry)); } - Context.ResponseData.Write((int)NetDBErrorCode); - Context.ResponseData.Write((int)Errno); - Context.ResponseData.Write(SerializedSize); + context.ResponseData.Write((int)netDbErrorCode); + context.ResponseData.Write((int)errno); + context.ResponseData.Write(serializedSize); return 0; } // GetHostStringError(u32) -> buffer - public long GetHostStringError(ServiceCtx Context) + public long GetHostStringError(ServiceCtx context) { - long ResultCode = MakeError(ErrorModule.Os, 1023); - NetDBError ErrorCode = (NetDBError)Context.RequestData.ReadInt32(); - string ErrorString = GetHostStringErrorFromErrorCode(ErrorCode); + long resultCode = MakeError(ErrorModule.Os, 1023); + NetDbError errorCode = (NetDbError)context.RequestData.ReadInt32(); + string errorString = GetHostStringErrorFromErrorCode(errorCode); - if (ErrorString.Length + 1 <= Context.Request.ReceiveBuff[0].Size) + if (errorString.Length + 1 <= context.Request.ReceiveBuff[0].Size) { - ResultCode = 0; - Context.Memory.WriteBytes(Context.Request.ReceiveBuff[0].Position, Encoding.ASCII.GetBytes(ErrorString + '\0')); + resultCode = 0; + context.Memory.WriteBytes(context.Request.ReceiveBuff[0].Position, Encoding.ASCII.GetBytes(errorString + '\0')); } - return ResultCode; + return resultCode; } // GetGaiStringError(u32) -> buffer - public long GetGaiStringError(ServiceCtx Context) + public long GetGaiStringError(ServiceCtx context) { - long ResultCode = MakeError(ErrorModule.Os, 1023); - GaiError ErrorCode = (GaiError)Context.RequestData.ReadInt32(); - string ErrorString = GetGaiStringErrorFromErrorCode(ErrorCode); + long resultCode = MakeError(ErrorModule.Os, 1023); + GaiError errorCode = (GaiError)context.RequestData.ReadInt32(); + string errorString = GetGaiStringErrorFromErrorCode(errorCode); - if (ErrorString.Length + 1 <= Context.Request.ReceiveBuff[0].Size) + if (errorString.Length + 1 <= context.Request.ReceiveBuff[0].Size) { - ResultCode = 0; - Context.Memory.WriteBytes(Context.Request.ReceiveBuff[0].Position, Encoding.ASCII.GetBytes(ErrorString + '\0')); + resultCode = 0; + context.Memory.WriteBytes(context.Request.ReceiveBuff[0].Position, Encoding.ASCII.GetBytes(errorString + '\0')); } - return ResultCode; + return resultCode; } // RequestCancelHandle(u64, pid) -> u32 - public long RequestCancelHandle(ServiceCtx Context) + public long RequestCancelHandle(ServiceCtx context) { - ulong Unknown0 = Context.RequestData.ReadUInt64(); + ulong unknown0 = context.RequestData.ReadUInt64(); - Context.ResponseData.Write(0); + context.ResponseData.Write(0); - Logger.PrintStub(LogClass.ServiceSfdnsres, $"Stubbed. Unknown0: {Unknown0}"); + Logger.PrintStub(LogClass.ServiceSfdnsres, $"Stubbed. Unknown0: {unknown0}"); return 0; } // CancelSocketCall(u32, u64, pid) - public long CancelSocketCall(ServiceCtx Context) + public long CancelSocketCall(ServiceCtx context) { - uint Unknown0 = Context.RequestData.ReadUInt32(); - ulong Unknown1 = Context.RequestData.ReadUInt64(); + uint unknown0 = context.RequestData.ReadUInt32(); + ulong unknown1 = context.RequestData.ReadUInt64(); - Logger.PrintStub(LogClass.ServiceSfdnsres, $"Stubbed. Unknown0: {Unknown0} - " + - $"Unknown1: {Unknown1}"); + Logger.PrintStub(LogClass.ServiceSfdnsres, $"Stubbed. Unknown0: {unknown0} - " + + $"Unknown1: {unknown1}"); return 0; } // ClearDnsAddresses(u32) - public long ClearDnsAddresses(ServiceCtx Context) + public long ClearDnsAddresses(ServiceCtx context) { - uint Unknown0 = Context.RequestData.ReadUInt32(); + uint unknown0 = context.RequestData.ReadUInt32(); - Logger.PrintStub(LogClass.ServiceSfdnsres, $"Stubbed. Unknown0: {Unknown0}"); + Logger.PrintStub(LogClass.ServiceSfdnsres, $"Stubbed. Unknown0: {unknown0}"); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Sfdnsres/NetDBError.cs b/Ryujinx.HLE/HOS/Services/Sfdnsres/NetDBError.cs index 6c1b7825..dad02cf2 100644 --- a/Ryujinx.HLE/HOS/Services/Sfdnsres/NetDBError.cs +++ b/Ryujinx.HLE/HOS/Services/Sfdnsres/NetDBError.cs @@ -1,6 +1,6 @@ namespace Ryujinx.HLE.HOS.Services.Sfdnsres { - enum NetDBError + enum NetDbError { Internal = -1, Success, @@ -8,6 +8,6 @@ TryAgain, NoRecovery, NoData, - NoAddress = NoData, + NoAddress = NoData } } diff --git a/Ryujinx.HLE/HOS/Services/Sm/IUserInterface.cs b/Ryujinx.HLE/HOS/Services/Sm/IUserInterface.cs index 0c26b7d9..2bfafd95 100644 --- a/Ryujinx.HLE/HOS/Services/Sm/IUserInterface.cs +++ b/Ryujinx.HLE/HOS/Services/Sm/IUserInterface.cs @@ -7,15 +7,15 @@ namespace Ryujinx.HLE.HOS.Services.Sm { class IUserInterface : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - private bool IsInitialized; + private bool _isInitialized; public IUserInterface() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, Initialize }, { 1, GetService } @@ -24,48 +24,48 @@ namespace Ryujinx.HLE.HOS.Services.Sm private const int SmNotInitialized = 0x415; - public long Initialize(ServiceCtx Context) + public long Initialize(ServiceCtx context) { - IsInitialized = true; + _isInitialized = true; return 0; } - public long GetService(ServiceCtx Context) + public long GetService(ServiceCtx context) { //Only for kernel version > 3.0.0. - if (!IsInitialized) + if (!_isInitialized) { //return SmNotInitialized; } - string Name = string.Empty; + string name = string.Empty; - for (int Index = 0; Index < 8 && - Context.RequestData.BaseStream.Position < - Context.RequestData.BaseStream.Length; Index++) + for (int index = 0; index < 8 && + context.RequestData.BaseStream.Position < + context.RequestData.BaseStream.Length; index++) { - byte Chr = Context.RequestData.ReadByte(); + byte chr = context.RequestData.ReadByte(); - if (Chr >= 0x20 && Chr < 0x7f) + if (chr >= 0x20 && chr < 0x7f) { - Name += (char)Chr; + name += (char)chr; } } - if (Name == string.Empty) + if (name == string.Empty) { return 0; } - KSession Session = new KSession(ServiceFactory.MakeService(Context.Device.System, Name), Name); + KSession session = new KSession(ServiceFactory.MakeService(context.Device.System, name), name); - if (Context.Process.HandleTable.GenerateHandle(Session, out int Handle) != KernelResult.Success) + if (context.Process.HandleTable.GenerateHandle(session, out int handle) != KernelResult.Success) { throw new InvalidOperationException("Out of handles!"); } - Context.Response.HandleDesc = IpcHandleDesc.MakeMove(Handle); + context.Response.HandleDesc = IpcHandleDesc.MakeMove(handle); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Spl/IRandomInterface.cs b/Ryujinx.HLE/HOS/Services/Spl/IRandomInterface.cs index 6391d981..cae8d8d0 100644 --- a/Ryujinx.HLE/HOS/Services/Spl/IRandomInterface.cs +++ b/Ryujinx.HLE/HOS/Services/Spl/IRandomInterface.cs @@ -7,29 +7,29 @@ namespace Ryujinx.HLE.HOS.Services.Spl { class IRandomInterface : IpcService, IDisposable { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - private RNGCryptoServiceProvider Rng; + private RNGCryptoServiceProvider _rng; public IRandomInterface() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, GetRandomBytes } }; - Rng = new RNGCryptoServiceProvider(); + _rng = new RNGCryptoServiceProvider(); } - public long GetRandomBytes(ServiceCtx Context) + public long GetRandomBytes(ServiceCtx context) { - byte[] RandomBytes = new byte[Context.Request.ReceiveBuff[0].Size]; + byte[] randomBytes = new byte[context.Request.ReceiveBuff[0].Size]; - Rng.GetBytes(RandomBytes); + _rng.GetBytes(randomBytes); - Context.Memory.WriteBytes(Context.Request.ReceiveBuff[0].Position, RandomBytes); + context.Memory.WriteBytes(context.Request.ReceiveBuff[0].Position, randomBytes); return 0; } @@ -39,11 +39,11 @@ namespace Ryujinx.HLE.HOS.Services.Spl Dispose(true); } - protected virtual void Dispose(bool Disposing) + protected virtual void Dispose(bool disposing) { - if (Disposing) + if (disposing) { - Rng.Dispose(); + _rng.Dispose(); } } } diff --git a/Ryujinx.HLE/HOS/Services/Ssl/ISslContext.cs b/Ryujinx.HLE/HOS/Services/Ssl/ISslContext.cs index 8f3a0649..cf58ed87 100644 --- a/Ryujinx.HLE/HOS/Services/Ssl/ISslContext.cs +++ b/Ryujinx.HLE/HOS/Services/Ssl/ISslContext.cs @@ -5,13 +5,13 @@ namespace Ryujinx.HLE.HOS.Services.Ssl { class ISslContext : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public ISslContext() { - m_Commands = new Dictionary() + _commands = new Dictionary { //... }; diff --git a/Ryujinx.HLE/HOS/Services/Ssl/ISslService.cs b/Ryujinx.HLE/HOS/Services/Ssl/ISslService.cs index 3046aab7..b40e9473 100644 --- a/Ryujinx.HLE/HOS/Services/Ssl/ISslService.cs +++ b/Ryujinx.HLE/HOS/Services/Ssl/ISslService.cs @@ -6,13 +6,13 @@ namespace Ryujinx.HLE.HOS.Services.Ssl { class ISslService : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public ISslService() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, CreateContext }, { 5, SetInterfaceVersion } @@ -20,24 +20,24 @@ namespace Ryujinx.HLE.HOS.Services.Ssl } // CreateContext(nn::ssl::sf::SslVersion, u64, pid) -> object - public long CreateContext(ServiceCtx Context) + public long CreateContext(ServiceCtx context) { - int SslVersion = Context.RequestData.ReadInt32(); - long Unknown = Context.RequestData.ReadInt64(); + int sslVersion = context.RequestData.ReadInt32(); + long unknown = context.RequestData.ReadInt64(); - Logger.PrintStub(LogClass.ServiceSsl, $"Stubbed. SslVersion: {SslVersion} - Unknown: {Unknown}"); + Logger.PrintStub(LogClass.ServiceSsl, $"Stubbed. SslVersion: {sslVersion} - Unknown: {unknown}"); - MakeObject(Context, new ISslContext()); + MakeObject(context, new ISslContext()); return 0; } // SetInterfaceVersion(u32) - public long SetInterfaceVersion(ServiceCtx Context) + public long SetInterfaceVersion(ServiceCtx context) { - int Version = Context.RequestData.ReadInt32(); + int version = context.RequestData.ReadInt32(); - Logger.PrintStub(LogClass.ServiceSsl, $"Stubbed. Version: {Version}"); + Logger.PrintStub(LogClass.ServiceSsl, $"Stubbed. Version: {version}"); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Time/IStaticService.cs b/Ryujinx.HLE/HOS/Services/Time/IStaticService.cs index 66f16501..fcbaa492 100644 --- a/Ryujinx.HLE/HOS/Services/Time/IStaticService.cs +++ b/Ryujinx.HLE/HOS/Services/Time/IStaticService.cs @@ -6,15 +6,15 @@ namespace Ryujinx.HLE.HOS.Services.Time { class IStaticService : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; private static readonly DateTime StartupDate = DateTime.UtcNow; public IStaticService() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, GetStandardUserSystemClock }, { 1, GetStandardNetworkSystemClock }, @@ -25,47 +25,47 @@ namespace Ryujinx.HLE.HOS.Services.Time }; } - public long GetStandardUserSystemClock(ServiceCtx Context) + public long GetStandardUserSystemClock(ServiceCtx context) { - MakeObject(Context, new ISystemClock(SystemClockType.User)); + MakeObject(context, new ISystemClock(SystemClockType.User)); return 0; } - public long GetStandardNetworkSystemClock(ServiceCtx Context) + public long GetStandardNetworkSystemClock(ServiceCtx context) { - MakeObject(Context, new ISystemClock(SystemClockType.Network)); + MakeObject(context, new ISystemClock(SystemClockType.Network)); return 0; } - public long GetStandardSteadyClock(ServiceCtx Context) + public long GetStandardSteadyClock(ServiceCtx context) { - MakeObject(Context, new ISteadyClock()); + MakeObject(context, new ISteadyClock()); return 0; } - public long GetTimeZoneService(ServiceCtx Context) + public long GetTimeZoneService(ServiceCtx context) { - MakeObject(Context, new ITimeZoneService()); + MakeObject(context, new ITimeZoneService()); return 0; } - public long GetStandardLocalSystemClock(ServiceCtx Context) + public long GetStandardLocalSystemClock(ServiceCtx context) { - MakeObject(Context, new ISystemClock(SystemClockType.Local)); + MakeObject(context, new ISystemClock(SystemClockType.Local)); return 0; } - public long CalculateMonotonicSystemClockBaseTimePoint(ServiceCtx Context) + public long CalculateMonotonicSystemClockBaseTimePoint(ServiceCtx context) { - long TimeOffset = (long)(DateTime.UtcNow - StartupDate).TotalSeconds; - long SystemClockContextEpoch = Context.RequestData.ReadInt64(); + long timeOffset = (long)(DateTime.UtcNow - StartupDate).TotalSeconds; + long systemClockContextEpoch = context.RequestData.ReadInt64(); - Context.ResponseData.Write(TimeOffset + SystemClockContextEpoch); + context.ResponseData.Write(timeOffset + systemClockContextEpoch); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Time/ISteadyClock.cs b/Ryujinx.HLE/HOS/Services/Time/ISteadyClock.cs index e4020bb1..f535ed9c 100644 --- a/Ryujinx.HLE/HOS/Services/Time/ISteadyClock.cs +++ b/Ryujinx.HLE/HOS/Services/Time/ISteadyClock.cs @@ -6,46 +6,46 @@ namespace Ryujinx.HLE.HOS.Services.Time { class ISteadyClock : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - private ulong TestOffset; + private ulong _testOffset; public ISteadyClock() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, GetCurrentTimePoint }, { 1, GetTestOffset }, { 2, SetTestOffset } }; - TestOffset = 0; + _testOffset = 0; } - public long GetCurrentTimePoint(ServiceCtx Context) + public long GetCurrentTimePoint(ServiceCtx context) { - Context.ResponseData.Write((long)(System.Diagnostics.Process.GetCurrentProcess().StartTime - DateTime.Now).TotalSeconds); + context.ResponseData.Write((long)(System.Diagnostics.Process.GetCurrentProcess().StartTime - DateTime.Now).TotalSeconds); for (int i = 0; i < 0x10; i++) { - Context.ResponseData.Write((byte)0); + context.ResponseData.Write((byte)0); } return 0; } - public long GetTestOffset(ServiceCtx Context) + public long GetTestOffset(ServiceCtx context) { - Context.ResponseData.Write(TestOffset); + context.ResponseData.Write(_testOffset); return 0; } - public long SetTestOffset(ServiceCtx Context) + public long SetTestOffset(ServiceCtx context) { - TestOffset = Context.RequestData.ReadUInt64(); + _testOffset = context.RequestData.ReadUInt64(); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Time/ISystemClock.cs b/Ryujinx.HLE/HOS/Services/Time/ISystemClock.cs index f574826a..1dfd7d74 100644 --- a/Ryujinx.HLE/HOS/Services/Time/ISystemClock.cs +++ b/Ryujinx.HLE/HOS/Services/Time/ISystemClock.cs @@ -6,25 +6,25 @@ namespace Ryujinx.HLE.HOS.Services.Time { class ISystemClock : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); - private SystemClockType ClockType; + private SystemClockType _clockType; - private DateTime SystemClockContextEpoch; + private DateTime _systemClockContextEpoch; - private long SystemClockTimePoint; + private long _systemClockTimePoint; - private byte[] SystemClockContextEnding; + private byte[] _systemClockContextEnding; - private long TimeOffset; + private long _timeOffset; - public ISystemClock(SystemClockType ClockType) + public ISystemClock(SystemClockType clockType) { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, GetCurrentTime }, { 1, SetCurrentTime }, @@ -32,74 +32,74 @@ namespace Ryujinx.HLE.HOS.Services.Time { 3, SetSystemClockContext } }; - this.ClockType = ClockType; - SystemClockContextEpoch = System.Diagnostics.Process.GetCurrentProcess().StartTime; - SystemClockContextEnding = new byte[0x10]; - TimeOffset = 0; + _clockType = clockType; + _systemClockContextEpoch = System.Diagnostics.Process.GetCurrentProcess().StartTime; + _systemClockContextEnding = new byte[0x10]; + _timeOffset = 0; - if (ClockType == SystemClockType.User || - ClockType == SystemClockType.Network) + if (clockType == SystemClockType.User || + clockType == SystemClockType.Network) { - SystemClockContextEpoch = SystemClockContextEpoch.ToUniversalTime(); + _systemClockContextEpoch = _systemClockContextEpoch.ToUniversalTime(); } - SystemClockTimePoint = (long)(SystemClockContextEpoch - Epoch).TotalSeconds; + _systemClockTimePoint = (long)(_systemClockContextEpoch - Epoch).TotalSeconds; } - public long GetCurrentTime(ServiceCtx Context) + public long GetCurrentTime(ServiceCtx context) { - DateTime CurrentTime = DateTime.Now; + DateTime currentTime = DateTime.Now; - if (ClockType == SystemClockType.User || - ClockType == SystemClockType.Network) + if (_clockType == SystemClockType.User || + _clockType == SystemClockType.Network) { - CurrentTime = CurrentTime.ToUniversalTime(); + currentTime = currentTime.ToUniversalTime(); } - Context.ResponseData.Write((long)((CurrentTime - Epoch).TotalSeconds) + TimeOffset); + context.ResponseData.Write((long)((currentTime - Epoch).TotalSeconds) + _timeOffset); return 0; } - public long SetCurrentTime(ServiceCtx Context) + public long SetCurrentTime(ServiceCtx context) { - DateTime CurrentTime = DateTime.Now; + DateTime currentTime = DateTime.Now; - if (ClockType == SystemClockType.User || - ClockType == SystemClockType.Network) + if (_clockType == SystemClockType.User || + _clockType == SystemClockType.Network) { - CurrentTime = CurrentTime.ToUniversalTime(); + currentTime = currentTime.ToUniversalTime(); } - TimeOffset = (Context.RequestData.ReadInt64() - (long)(CurrentTime - Epoch).TotalSeconds); + _timeOffset = (context.RequestData.ReadInt64() - (long)(currentTime - Epoch).TotalSeconds); return 0; } - public long GetSystemClockContext(ServiceCtx Context) + public long GetSystemClockContext(ServiceCtx context) { - Context.ResponseData.Write((long)(SystemClockContextEpoch - Epoch).TotalSeconds); + context.ResponseData.Write((long)(_systemClockContextEpoch - Epoch).TotalSeconds); // The point in time, TODO: is there a link between epoch and this? - Context.ResponseData.Write(SystemClockTimePoint); + context.ResponseData.Write(_systemClockTimePoint); // This seems to be some kind of identifier? for (int i = 0; i < 0x10; i++) { - Context.ResponseData.Write(SystemClockContextEnding[i]); + context.ResponseData.Write(_systemClockContextEnding[i]); } return 0; } - public long SetSystemClockContext(ServiceCtx Context) + public long SetSystemClockContext(ServiceCtx context) { - long NewSystemClockEpoch = Context.RequestData.ReadInt64(); - long NewSystemClockTimePoint = Context.RequestData.ReadInt64(); + long newSystemClockEpoch = context.RequestData.ReadInt64(); + long newSystemClockTimePoint = context.RequestData.ReadInt64(); - SystemClockContextEpoch = Epoch.Add(TimeSpan.FromSeconds(NewSystemClockEpoch)); - SystemClockTimePoint = NewSystemClockTimePoint; - SystemClockContextEnding = Context.RequestData.ReadBytes(0x10); + _systemClockContextEpoch = Epoch.Add(TimeSpan.FromSeconds(newSystemClockEpoch)); + _systemClockTimePoint = newSystemClockTimePoint; + _systemClockContextEnding = context.RequestData.ReadBytes(0x10); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Time/ITimeZoneService.cs b/Ryujinx.HLE/HOS/Services/Time/ITimeZoneService.cs index 0e321e44..563a9753 100644 --- a/Ryujinx.HLE/HOS/Services/Time/ITimeZoneService.cs +++ b/Ryujinx.HLE/HOS/Services/Time/ITimeZoneService.cs @@ -10,17 +10,17 @@ namespace Ryujinx.HLE.HOS.Services.Time { class ITimeZoneService : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); - private TimeZoneInfo TimeZone = TimeZoneInfo.Local; + private TimeZoneInfo _timeZone = TimeZoneInfo.Local; public ITimeZoneService() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, GetDeviceLocationName }, { 1, SetDeviceLocationName }, @@ -34,245 +34,245 @@ namespace Ryujinx.HLE.HOS.Services.Time }; } - public long GetDeviceLocationName(ServiceCtx Context) + public long GetDeviceLocationName(ServiceCtx context) { - char[] TzName = TimeZone.Id.ToCharArray(); + char[] tzName = _timeZone.Id.ToCharArray(); - Context.ResponseData.Write(TzName); + context.ResponseData.Write(tzName); - int Padding = 0x24 - TzName.Length; + int padding = 0x24 - tzName.Length; - for (int Index = 0; Index < Padding; Index++) + for (int index = 0; index < padding; index++) { - Context.ResponseData.Write((byte)0); + context.ResponseData.Write((byte)0); } return 0; } - public long SetDeviceLocationName(ServiceCtx Context) + public long SetDeviceLocationName(ServiceCtx context) { - byte[] LocationName = Context.RequestData.ReadBytes(0x24); + byte[] locationName = context.RequestData.ReadBytes(0x24); - string TzID = Encoding.ASCII.GetString(LocationName).TrimEnd('\0'); + string tzId = Encoding.ASCII.GetString(locationName).TrimEnd('\0'); - long ResultCode = 0; + long resultCode = 0; try { - TimeZone = TimeZoneInfo.FindSystemTimeZoneById(TzID); + _timeZone = TimeZoneInfo.FindSystemTimeZoneById(tzId); } catch (TimeZoneNotFoundException) { - ResultCode = MakeError(ErrorModule.Time, 0x3dd); + resultCode = MakeError(ErrorModule.Time, 0x3dd); } - return ResultCode; + return resultCode; } - public long GetTotalLocationNameCount(ServiceCtx Context) + public long GetTotalLocationNameCount(ServiceCtx context) { - Context.ResponseData.Write(TimeZoneInfo.GetSystemTimeZones().Count); + context.ResponseData.Write(TimeZoneInfo.GetSystemTimeZones().Count); return 0; } - public long LoadLocationNameList(ServiceCtx Context) + public long LoadLocationNameList(ServiceCtx context) { - long BufferPosition = Context.Response.SendBuff[0].Position; - long BufferSize = Context.Response.SendBuff[0].Size; + long bufferPosition = context.Response.SendBuff[0].Position; + long bufferSize = context.Response.SendBuff[0].Size; - int Offset = 0; + int offset = 0; foreach (TimeZoneInfo info in TimeZoneInfo.GetSystemTimeZones()) { - byte[] TzData = Encoding.ASCII.GetBytes(info.Id); + byte[] tzData = Encoding.ASCII.GetBytes(info.Id); - Context.Memory.WriteBytes(BufferPosition + Offset, TzData); + context.Memory.WriteBytes(bufferPosition + offset, tzData); - int Padding = 0x24 - TzData.Length; + int padding = 0x24 - tzData.Length; - for (int Index = 0; Index < Padding; Index++) + for (int index = 0; index < padding; index++) { - Context.ResponseData.Write((byte)0); + context.ResponseData.Write((byte)0); } - Offset += 0x24; + offset += 0x24; } return 0; } - public long LoadTimeZoneRule(ServiceCtx Context) + public long LoadTimeZoneRule(ServiceCtx context) { - long BufferPosition = Context.Request.ReceiveBuff[0].Position; - long BufferSize = Context.Request.ReceiveBuff[0].Size; + long bufferPosition = context.Request.ReceiveBuff[0].Position; + long bufferSize = context.Request.ReceiveBuff[0].Size; - if (BufferSize != 0x4000) + if (bufferSize != 0x4000) { - Logger.PrintWarning(LogClass.ServiceTime, $"TimeZoneRule buffer size is 0x{BufferSize:x} (expected 0x4000)"); + Logger.PrintWarning(LogClass.ServiceTime, $"TimeZoneRule buffer size is 0x{bufferSize:x} (expected 0x4000)"); } - long ResultCode = 0; + long resultCode = 0; - byte[] LocationName = Context.RequestData.ReadBytes(0x24); + byte[] locationName = context.RequestData.ReadBytes(0x24); - string TzID = Encoding.ASCII.GetString(LocationName).TrimEnd('\0'); + string tzId = Encoding.ASCII.GetString(locationName).TrimEnd('\0'); // Check if the Time Zone exists, otherwise error out. try { - TimeZoneInfo Info = TimeZoneInfo.FindSystemTimeZoneById(TzID); + TimeZoneInfo info = TimeZoneInfo.FindSystemTimeZoneById(tzId); - byte[] TzData = Encoding.ASCII.GetBytes(Info.Id); + byte[] tzData = Encoding.ASCII.GetBytes(info.Id); // FIXME: This is not in ANY cases accurate, but the games don't care about the content of the buffer, they only pass it. // TODO: Reverse the TZif2 conversion in PCV to make this match with real hardware. - Context.Memory.WriteBytes(BufferPosition, TzData); + context.Memory.WriteBytes(bufferPosition, tzData); } catch (TimeZoneNotFoundException) { - Logger.PrintWarning(LogClass.ServiceTime, $"Timezone not found for string: {TzID} (len: {TzID.Length})"); + Logger.PrintWarning(LogClass.ServiceTime, $"Timezone not found for string: {tzId} (len: {tzId.Length})"); - ResultCode = MakeError(ErrorModule.Time, 0x3dd); + resultCode = MakeError(ErrorModule.Time, 0x3dd); } - return ResultCode; + return resultCode; } - private long ToCalendarTimeWithTz(ServiceCtx Context, long PosixTime, TimeZoneInfo Info) + private long ToCalendarTimeWithTz(ServiceCtx context, long posixTime, TimeZoneInfo info) { - DateTime CurrentTime = Epoch.AddSeconds(PosixTime); + DateTime currentTime = Epoch.AddSeconds(posixTime); - CurrentTime = TimeZoneInfo.ConvertTimeFromUtc(CurrentTime, Info); + currentTime = TimeZoneInfo.ConvertTimeFromUtc(currentTime, info); - Context.ResponseData.Write((ushort)CurrentTime.Year); - Context.ResponseData.Write((byte)CurrentTime.Month); - Context.ResponseData.Write((byte)CurrentTime.Day); - Context.ResponseData.Write((byte)CurrentTime.Hour); - Context.ResponseData.Write((byte)CurrentTime.Minute); - Context.ResponseData.Write((byte)CurrentTime.Second); - Context.ResponseData.Write((byte)0); //MilliSecond ? - Context.ResponseData.Write((int)CurrentTime.DayOfWeek); - Context.ResponseData.Write(CurrentTime.DayOfYear - 1); - Context.ResponseData.Write(new byte[8]); //TODO: Find out the names used. - Context.ResponseData.Write((byte)(CurrentTime.IsDaylightSavingTime() ? 1 : 0)); - Context.ResponseData.Write((int)Info.GetUtcOffset(CurrentTime).TotalSeconds); + context.ResponseData.Write((ushort)currentTime.Year); + context.ResponseData.Write((byte)currentTime.Month); + context.ResponseData.Write((byte)currentTime.Day); + context.ResponseData.Write((byte)currentTime.Hour); + context.ResponseData.Write((byte)currentTime.Minute); + context.ResponseData.Write((byte)currentTime.Second); + context.ResponseData.Write((byte)0); //MilliSecond ? + context.ResponseData.Write((int)currentTime.DayOfWeek); + context.ResponseData.Write(currentTime.DayOfYear - 1); + context.ResponseData.Write(new byte[8]); //TODO: Find out the names used. + context.ResponseData.Write((byte)(currentTime.IsDaylightSavingTime() ? 1 : 0)); + context.ResponseData.Write((int)info.GetUtcOffset(currentTime).TotalSeconds); return 0; } - public long ToCalendarTime(ServiceCtx Context) + public long ToCalendarTime(ServiceCtx context) { - long PosixTime = Context.RequestData.ReadInt64(); - long BufferPosition = Context.Request.SendBuff[0].Position; - long BufferSize = Context.Request.SendBuff[0].Size; + long posixTime = context.RequestData.ReadInt64(); + long bufferPosition = context.Request.SendBuff[0].Position; + long bufferSize = context.Request.SendBuff[0].Size; - if (BufferSize != 0x4000) + if (bufferSize != 0x4000) { - Logger.PrintWarning(LogClass.ServiceTime, $"TimeZoneRule buffer size is 0x{BufferSize:x} (expected 0x4000)"); + Logger.PrintWarning(LogClass.ServiceTime, $"TimeZoneRule buffer size is 0x{bufferSize:x} (expected 0x4000)"); } // TODO: Reverse the TZif2 conversion in PCV to make this match with real hardware. - byte[] TzData = Context.Memory.ReadBytes(BufferPosition, 0x24); + byte[] tzData = context.Memory.ReadBytes(bufferPosition, 0x24); - string TzID = Encoding.ASCII.GetString(TzData).TrimEnd('\0'); + string tzId = Encoding.ASCII.GetString(tzData).TrimEnd('\0'); - long ResultCode = 0; + long resultCode = 0; // Check if the Time Zone exists, otherwise error out. try { - TimeZoneInfo Info = TimeZoneInfo.FindSystemTimeZoneById(TzID); + TimeZoneInfo info = TimeZoneInfo.FindSystemTimeZoneById(tzId); - ResultCode = ToCalendarTimeWithTz(Context, PosixTime, Info); + resultCode = ToCalendarTimeWithTz(context, posixTime, info); } catch (TimeZoneNotFoundException) { - Logger.PrintWarning(LogClass.ServiceTime, $"Timezone not found for string: {TzID} (len: {TzID.Length})"); + Logger.PrintWarning(LogClass.ServiceTime, $"Timezone not found for string: {tzId} (len: {tzId.Length})"); - ResultCode = MakeError(ErrorModule.Time, 0x3dd); + resultCode = MakeError(ErrorModule.Time, 0x3dd); } - return ResultCode; + return resultCode; } - public long ToCalendarTimeWithMyRule(ServiceCtx Context) + public long ToCalendarTimeWithMyRule(ServiceCtx context) { - long PosixTime = Context.RequestData.ReadInt64(); + long posixTime = context.RequestData.ReadInt64(); - return ToCalendarTimeWithTz(Context, PosixTime, TimeZone); + return ToCalendarTimeWithTz(context, posixTime, _timeZone); } - public long ToPosixTime(ServiceCtx Context) + public long ToPosixTime(ServiceCtx context) { - long BufferPosition = Context.Request.SendBuff[0].Position; - long BufferSize = Context.Request.SendBuff[0].Size; + long bufferPosition = context.Request.SendBuff[0].Position; + long bufferSize = context.Request.SendBuff[0].Size; - ushort Year = Context.RequestData.ReadUInt16(); - byte Month = Context.RequestData.ReadByte(); - byte Day = Context.RequestData.ReadByte(); - byte Hour = Context.RequestData.ReadByte(); - byte Minute = Context.RequestData.ReadByte(); - byte Second = Context.RequestData.ReadByte(); + ushort year = context.RequestData.ReadUInt16(); + byte month = context.RequestData.ReadByte(); + byte day = context.RequestData.ReadByte(); + byte hour = context.RequestData.ReadByte(); + byte minute = context.RequestData.ReadByte(); + byte second = context.RequestData.ReadByte(); - DateTime CalendarTime = new DateTime(Year, Month, Day, Hour, Minute, Second); + DateTime calendarTime = new DateTime(year, month, day, hour, minute, second); - if (BufferSize != 0x4000) + if (bufferSize != 0x4000) { - Logger.PrintWarning(LogClass.ServiceTime, $"TimeZoneRule buffer size is 0x{BufferSize:x} (expected 0x4000)"); + Logger.PrintWarning(LogClass.ServiceTime, $"TimeZoneRule buffer size is 0x{bufferSize:x} (expected 0x4000)"); } // TODO: Reverse the TZif2 conversion in PCV to make this match with real hardware. - byte[] TzData = Context.Memory.ReadBytes(BufferPosition, 0x24); + byte[] tzData = context.Memory.ReadBytes(bufferPosition, 0x24); - string TzID = Encoding.ASCII.GetString(TzData).TrimEnd('\0'); + string tzId = Encoding.ASCII.GetString(tzData).TrimEnd('\0'); - long ResultCode = 0; + long resultCode = 0; // Check if the Time Zone exists, otherwise error out. try { - TimeZoneInfo Info = TimeZoneInfo.FindSystemTimeZoneById(TzID); + TimeZoneInfo info = TimeZoneInfo.FindSystemTimeZoneById(tzId); - return ToPosixTimeWithTz(Context, CalendarTime, Info); + return ToPosixTimeWithTz(context, calendarTime, info); } catch (TimeZoneNotFoundException) { - Logger.PrintWarning(LogClass.ServiceTime, $"Timezone not found for string: {TzID} (len: {TzID.Length})"); + Logger.PrintWarning(LogClass.ServiceTime, $"Timezone not found for string: {tzId} (len: {tzId.Length})"); - ResultCode = MakeError(ErrorModule.Time, 0x3dd); + resultCode = MakeError(ErrorModule.Time, 0x3dd); } - return ResultCode; + return resultCode; } - public long ToPosixTimeWithMyRule(ServiceCtx Context) + public long ToPosixTimeWithMyRule(ServiceCtx context) { - ushort Year = Context.RequestData.ReadUInt16(); - byte Month = Context.RequestData.ReadByte(); - byte Day = Context.RequestData.ReadByte(); - byte Hour = Context.RequestData.ReadByte(); - byte Minute = Context.RequestData.ReadByte(); - byte Second = Context.RequestData.ReadByte(); + ushort year = context.RequestData.ReadUInt16(); + byte month = context.RequestData.ReadByte(); + byte day = context.RequestData.ReadByte(); + byte hour = context.RequestData.ReadByte(); + byte minute = context.RequestData.ReadByte(); + byte second = context.RequestData.ReadByte(); - DateTime CalendarTime = new DateTime(Year, Month, Day, Hour, Minute, Second, DateTimeKind.Local); + DateTime calendarTime = new DateTime(year, month, day, hour, minute, second, DateTimeKind.Local); - return ToPosixTimeWithTz(Context, CalendarTime, TimeZone); + return ToPosixTimeWithTz(context, calendarTime, _timeZone); } - private long ToPosixTimeWithTz(ServiceCtx Context, DateTime CalendarTime, TimeZoneInfo Info) + private long ToPosixTimeWithTz(ServiceCtx context, DateTime calendarTime, TimeZoneInfo info) { - DateTime CalenderTimeUTC = TimeZoneInfo.ConvertTimeToUtc(CalendarTime, Info); + DateTime calenderTimeUtc = TimeZoneInfo.ConvertTimeToUtc(calendarTime, info); - long PosixTime = ((DateTimeOffset)CalenderTimeUTC).ToUnixTimeSeconds(); + long posixTime = ((DateTimeOffset)calenderTimeUtc).ToUnixTimeSeconds(); - long Position = Context.Request.RecvListBuff[0].Position; - long Size = Context.Request.RecvListBuff[0].Size; + long position = context.Request.RecvListBuff[0].Position; + long size = context.Request.RecvListBuff[0].Size; - Context.Memory.WriteInt64(Position, PosixTime); + context.Memory.WriteInt64(position, posixTime); - Context.ResponseData.Write(1); + context.ResponseData.Write(1); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Vi/Display.cs b/Ryujinx.HLE/HOS/Services/Vi/Display.cs index 50fe5e1d..47c7b2ae 100644 --- a/Ryujinx.HLE/HOS/Services/Vi/Display.cs +++ b/Ryujinx.HLE/HOS/Services/Vi/Display.cs @@ -4,9 +4,9 @@ namespace Ryujinx.HLE.HOS.Services.Vi { public string Name { get; private set; } - public Display(string Name) + public Display(string name) { - this.Name = Name; + Name = name; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Services/Vi/GbpBuffer.cs b/Ryujinx.HLE/HOS/Services/Vi/GbpBuffer.cs index 4f00c3de..41cbacf9 100644 --- a/Ryujinx.HLE/HOS/Services/Vi/GbpBuffer.cs +++ b/Ryujinx.HLE/HOS/Services/Vi/GbpBuffer.cs @@ -21,40 +21,40 @@ namespace Ryujinx.HLE.HOS.Services.Android public int Size => RawData.Length + 10 * 4; - public GbpBuffer(BinaryReader Reader) + public GbpBuffer(BinaryReader reader) { - Magic = Reader.ReadInt32(); - Width = Reader.ReadInt32(); - Height = Reader.ReadInt32(); - Stride = Reader.ReadInt32(); - Format = Reader.ReadInt32(); - Usage = Reader.ReadInt32(); + Magic = reader.ReadInt32(); + Width = reader.ReadInt32(); + Height = reader.ReadInt32(); + Stride = reader.ReadInt32(); + Format = reader.ReadInt32(); + Usage = reader.ReadInt32(); - Pid = Reader.ReadInt32(); - RefCount = Reader.ReadInt32(); + Pid = reader.ReadInt32(); + RefCount = reader.ReadInt32(); - FdsCount = Reader.ReadInt32(); - IntsCount = Reader.ReadInt32(); + FdsCount = reader.ReadInt32(); + IntsCount = reader.ReadInt32(); - RawData = Reader.ReadBytes((FdsCount + IntsCount) * 4); + RawData = reader.ReadBytes((FdsCount + IntsCount) * 4); } - public void Write(BinaryWriter Writer) + public void Write(BinaryWriter writer) { - Writer.Write(Magic); - Writer.Write(Width); - Writer.Write(Height); - Writer.Write(Stride); - Writer.Write(Format); - Writer.Write(Usage); + writer.Write(Magic); + writer.Write(Width); + writer.Write(Height); + writer.Write(Stride); + writer.Write(Format); + writer.Write(Usage); - Writer.Write(Pid); - Writer.Write(RefCount); + writer.Write(Pid); + writer.Write(RefCount); - Writer.Write(FdsCount); - Writer.Write(IntsCount); + writer.Write(FdsCount); + writer.Write(IntsCount); - Writer.Write(RawData); + writer.Write(RawData); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Services/Vi/IApplicationDisplayService.cs b/Ryujinx.HLE/HOS/Services/Vi/IApplicationDisplayService.cs index 5d1ddd84..63e542d2 100644 --- a/Ryujinx.HLE/HOS/Services/Vi/IApplicationDisplayService.cs +++ b/Ryujinx.HLE/HOS/Services/Vi/IApplicationDisplayService.cs @@ -12,15 +12,15 @@ namespace Ryujinx.HLE.HOS.Services.Vi { class IApplicationDisplayService : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - private IdDictionary Displays; + private IdDictionary _displays; public IApplicationDisplayService() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 100, GetRelayService }, { 101, GetSystemDisplayService }, @@ -38,205 +38,205 @@ namespace Ryujinx.HLE.HOS.Services.Vi { 5202, GetDisplayVSyncEvent } }; - Displays = new IdDictionary(); + _displays = new IdDictionary(); } - public long GetRelayService(ServiceCtx Context) + public long GetRelayService(ServiceCtx context) { - MakeObject(Context, new IHOSBinderDriver( - Context.Device.System, - Context.Device.Gpu.Renderer)); + MakeObject(context, new IhosBinderDriver( + context.Device.System, + context.Device.Gpu.Renderer)); return 0; } - public long GetSystemDisplayService(ServiceCtx Context) + public long GetSystemDisplayService(ServiceCtx context) { - MakeObject(Context, new ISystemDisplayService()); + MakeObject(context, new ISystemDisplayService()); return 0; } - public long GetManagerDisplayService(ServiceCtx Context) + public long GetManagerDisplayService(ServiceCtx context) { - MakeObject(Context, new IManagerDisplayService()); + MakeObject(context, new IManagerDisplayService()); return 0; } - public long GetIndirectDisplayTransactionService(ServiceCtx Context) + public long GetIndirectDisplayTransactionService(ServiceCtx context) { - MakeObject(Context, new IHOSBinderDriver( - Context.Device.System, - Context.Device.Gpu.Renderer)); + MakeObject(context, new IhosBinderDriver( + context.Device.System, + context.Device.Gpu.Renderer)); return 0; } - public long ListDisplays(ServiceCtx Context) + public long ListDisplays(ServiceCtx context) { - long RecBuffPtr = Context.Request.ReceiveBuff[0].Position; + long recBuffPtr = context.Request.ReceiveBuff[0].Position; - MemoryHelper.FillWithZeros(Context.Memory, RecBuffPtr, 0x60); + MemoryHelper.FillWithZeros(context.Memory, recBuffPtr, 0x60); //Add only the default display to buffer - Context.Memory.WriteBytes(RecBuffPtr, Encoding.ASCII.GetBytes("Default")); - Context.Memory.WriteInt64(RecBuffPtr + 0x40, 0x1L); - Context.Memory.WriteInt64(RecBuffPtr + 0x48, 0x1L); - Context.Memory.WriteInt64(RecBuffPtr + 0x50, 1920L); - Context.Memory.WriteInt64(RecBuffPtr + 0x58, 1080L); + context.Memory.WriteBytes(recBuffPtr, Encoding.ASCII.GetBytes("Default")); + context.Memory.WriteInt64(recBuffPtr + 0x40, 0x1L); + context.Memory.WriteInt64(recBuffPtr + 0x48, 0x1L); + context.Memory.WriteInt64(recBuffPtr + 0x50, 1920L); + context.Memory.WriteInt64(recBuffPtr + 0x58, 1080L); - Context.ResponseData.Write(1L); + context.ResponseData.Write(1L); return 0; } - public long OpenDisplay(ServiceCtx Context) + public long OpenDisplay(ServiceCtx context) { - string Name = GetDisplayName(Context); + string name = GetDisplayName(context); - long DisplayId = Displays.Add(new Display(Name)); + long displayId = _displays.Add(new Display(name)); - Context.ResponseData.Write(DisplayId); + context.ResponseData.Write(displayId); return 0; } - public long CloseDisplay(ServiceCtx Context) + public long CloseDisplay(ServiceCtx context) { - int DisplayId = Context.RequestData.ReadInt32(); + int displayId = context.RequestData.ReadInt32(); - Displays.Delete(DisplayId); + _displays.Delete(displayId); return 0; } - public long GetDisplayResolution(ServiceCtx Context) + public long GetDisplayResolution(ServiceCtx context) { - long DisplayId = Context.RequestData.ReadInt32(); + long displayId = context.RequestData.ReadInt32(); - Context.ResponseData.Write(1280); - Context.ResponseData.Write(720); + context.ResponseData.Write(1280); + context.ResponseData.Write(720); return 0; } - public long OpenLayer(ServiceCtx Context) + public long OpenLayer(ServiceCtx context) { - long LayerId = Context.RequestData.ReadInt64(); - long UserId = Context.RequestData.ReadInt64(); + long layerId = context.RequestData.ReadInt64(); + long userId = context.RequestData.ReadInt64(); - long ParcelPtr = Context.Request.ReceiveBuff[0].Position; + long parcelPtr = context.Request.ReceiveBuff[0].Position; - byte[] Parcel = MakeIGraphicsBufferProducer(ParcelPtr); + byte[] parcel = MakeIGraphicsBufferProducer(parcelPtr); - Context.Memory.WriteBytes(ParcelPtr, Parcel); + context.Memory.WriteBytes(parcelPtr, parcel); - Context.ResponseData.Write((long)Parcel.Length); + context.ResponseData.Write((long)parcel.Length); return 0; } - public long CloseLayer(ServiceCtx Context) + public long CloseLayer(ServiceCtx context) { - long LayerId = Context.RequestData.ReadInt64(); + long layerId = context.RequestData.ReadInt64(); return 0; } - public long CreateStrayLayer(ServiceCtx Context) + public long CreateStrayLayer(ServiceCtx context) { - long LayerFlags = Context.RequestData.ReadInt64(); - long DisplayId = Context.RequestData.ReadInt64(); + long layerFlags = context.RequestData.ReadInt64(); + long displayId = context.RequestData.ReadInt64(); - long ParcelPtr = Context.Request.ReceiveBuff[0].Position; + long parcelPtr = context.Request.ReceiveBuff[0].Position; - Display Disp = Displays.GetData((int)DisplayId); + Display disp = _displays.GetData((int)displayId); - byte[] Parcel = MakeIGraphicsBufferProducer(ParcelPtr); + byte[] parcel = MakeIGraphicsBufferProducer(parcelPtr); - Context.Memory.WriteBytes(ParcelPtr, Parcel); + context.Memory.WriteBytes(parcelPtr, parcel); - Context.ResponseData.Write(0L); - Context.ResponseData.Write((long)Parcel.Length); + context.ResponseData.Write(0L); + context.ResponseData.Write((long)parcel.Length); return 0; } - public long DestroyStrayLayer(ServiceCtx Context) + public long DestroyStrayLayer(ServiceCtx context) { return 0; } - public long SetLayerScalingMode(ServiceCtx Context) + public long SetLayerScalingMode(ServiceCtx context) { - int ScalingMode = Context.RequestData.ReadInt32(); - long Unknown = Context.RequestData.ReadInt64(); + int scalingMode = context.RequestData.ReadInt32(); + long unknown = context.RequestData.ReadInt64(); return 0; } - public long GetDisplayVSyncEvent(ServiceCtx Context) + public long GetDisplayVSyncEvent(ServiceCtx context) { - string Name = GetDisplayName(Context); + string name = GetDisplayName(context); - if (Context.Process.HandleTable.GenerateHandle(Context.Device.System.VsyncEvent.ReadableEvent, out int Handle) != KernelResult.Success) + if (context.Process.HandleTable.GenerateHandle(context.Device.System.VsyncEvent.ReadableEvent, out int handle) != KernelResult.Success) { throw new InvalidOperationException("Out of handles!"); } - Context.Response.HandleDesc = IpcHandleDesc.MakeCopy(Handle); + context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); return 0; } - private byte[] MakeIGraphicsBufferProducer(long BasePtr) + private byte[] MakeIGraphicsBufferProducer(long basePtr) { - long Id = 0x20; - long CookiePtr = 0L; + long id = 0x20; + long cookiePtr = 0L; - using (MemoryStream MS = new MemoryStream()) + using (MemoryStream ms = new MemoryStream()) { - BinaryWriter Writer = new BinaryWriter(MS); + BinaryWriter writer = new BinaryWriter(ms); //flat_binder_object (size is 0x28) - Writer.Write(2); //Type (BINDER_TYPE_WEAK_BINDER) - Writer.Write(0); //Flags - Writer.Write((int)(Id >> 0)); - Writer.Write((int)(Id >> 32)); - Writer.Write((int)(CookiePtr >> 0)); - Writer.Write((int)(CookiePtr >> 32)); - Writer.Write((byte)'d'); - Writer.Write((byte)'i'); - Writer.Write((byte)'s'); - Writer.Write((byte)'p'); - Writer.Write((byte)'d'); - Writer.Write((byte)'r'); - Writer.Write((byte)'v'); - Writer.Write((byte)'\0'); - Writer.Write(0L); //Pad + writer.Write(2); //Type (BINDER_TYPE_WEAK_BINDER) + writer.Write(0); //Flags + writer.Write((int)(id >> 0)); + writer.Write((int)(id >> 32)); + writer.Write((int)(cookiePtr >> 0)); + writer.Write((int)(cookiePtr >> 32)); + writer.Write((byte)'d'); + writer.Write((byte)'i'); + writer.Write((byte)'s'); + writer.Write((byte)'p'); + writer.Write((byte)'d'); + writer.Write((byte)'r'); + writer.Write((byte)'v'); + writer.Write((byte)'\0'); + writer.Write(0L); //Pad - return MakeParcel(MS.ToArray(), new byte[] { 0, 0, 0, 0 }); + return MakeParcel(ms.ToArray(), new byte[] { 0, 0, 0, 0 }); } } - private string GetDisplayName(ServiceCtx Context) + private string GetDisplayName(ServiceCtx context) { - string Name = string.Empty; + string name = string.Empty; - for (int Index = 0; Index < 8 && - Context.RequestData.BaseStream.Position < - Context.RequestData.BaseStream.Length; Index++) + for (int index = 0; index < 8 && + context.RequestData.BaseStream.Position < + context.RequestData.BaseStream.Length; index++) { - byte Chr = Context.RequestData.ReadByte(); + byte chr = context.RequestData.ReadByte(); - if (Chr >= 0x20 && Chr < 0x7f) + if (chr >= 0x20 && chr < 0x7f) { - Name += (char)Chr; + name += (char)chr; } } - return Name; + return name; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Services/Vi/IApplicationRootService.cs b/Ryujinx.HLE/HOS/Services/Vi/IApplicationRootService.cs index e86734e6..66ab16bd 100644 --- a/Ryujinx.HLE/HOS/Services/Vi/IApplicationRootService.cs +++ b/Ryujinx.HLE/HOS/Services/Vi/IApplicationRootService.cs @@ -5,23 +5,23 @@ namespace Ryujinx.HLE.HOS.Services.Vi { class IApplicationRootService : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IApplicationRootService() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, GetDisplayService } }; } - public long GetDisplayService(ServiceCtx Context) + public long GetDisplayService(ServiceCtx context) { - int ServiceType = Context.RequestData.ReadInt32(); + int serviceType = context.RequestData.ReadInt32(); - MakeObject(Context, new IApplicationDisplayService()); + MakeObject(context, new IApplicationDisplayService()); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Vi/IHOSBinderDriver.cs b/Ryujinx.HLE/HOS/Services/Vi/IHOSBinderDriver.cs index 09a37b0f..7ca3053d 100644 --- a/Ryujinx.HLE/HOS/Services/Vi/IHOSBinderDriver.cs +++ b/Ryujinx.HLE/HOS/Services/Vi/IHOSBinderDriver.cs @@ -7,19 +7,19 @@ using System.Collections.Generic; namespace Ryujinx.HLE.HOS.Services.Vi { - class IHOSBinderDriver : IpcService, IDisposable + class IhosBinderDriver : IpcService, IDisposable { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; - private KEvent BinderEvent; + private KEvent _binderEvent; - private NvFlinger Flinger; + private NvFlinger _flinger; - public IHOSBinderDriver(Horizon System, IGalRenderer Renderer) + public IhosBinderDriver(Horizon system, IGalRenderer renderer) { - m_Commands = new Dictionary() + _commands = new Dictionary { { 0, TransactParcel }, { 1, AdjustRefcount }, @@ -27,62 +27,62 @@ namespace Ryujinx.HLE.HOS.Services.Vi { 3, TransactParcelAuto } }; - BinderEvent = new KEvent(System); + _binderEvent = new KEvent(system); - BinderEvent.ReadableEvent.Signal(); + _binderEvent.ReadableEvent.Signal(); - Flinger = new NvFlinger(Renderer, BinderEvent); + _flinger = new NvFlinger(renderer, _binderEvent); } - public long TransactParcel(ServiceCtx Context) + public long TransactParcel(ServiceCtx context) { - int Id = Context.RequestData.ReadInt32(); - int Code = Context.RequestData.ReadInt32(); + int id = context.RequestData.ReadInt32(); + int code = context.RequestData.ReadInt32(); - long DataPos = Context.Request.SendBuff[0].Position; - long DataSize = Context.Request.SendBuff[0].Size; + long dataPos = context.Request.SendBuff[0].Position; + long dataSize = context.Request.SendBuff[0].Size; - byte[] Data = Context.Memory.ReadBytes(DataPos, DataSize); + byte[] data = context.Memory.ReadBytes(dataPos, dataSize); - Data = Parcel.GetParcelData(Data); + data = Parcel.GetParcelData(data); - return Flinger.ProcessParcelRequest(Context, Data, Code); + return _flinger.ProcessParcelRequest(context, data, code); } - public long TransactParcelAuto(ServiceCtx Context) + public long TransactParcelAuto(ServiceCtx context) { - int Id = Context.RequestData.ReadInt32(); - int Code = Context.RequestData.ReadInt32(); + int id = context.RequestData.ReadInt32(); + int code = context.RequestData.ReadInt32(); - (long DataPos, long DataSize) = Context.Request.GetBufferType0x21(); + (long dataPos, long dataSize) = context.Request.GetBufferType0x21(); - byte[] Data = Context.Memory.ReadBytes(DataPos, DataSize); + byte[] data = context.Memory.ReadBytes(dataPos, dataSize); - Data = Parcel.GetParcelData(Data); + data = Parcel.GetParcelData(data); - return Flinger.ProcessParcelRequest(Context, Data, Code); + return _flinger.ProcessParcelRequest(context, data, code); } - public long AdjustRefcount(ServiceCtx Context) + public long AdjustRefcount(ServiceCtx context) { - int Id = Context.RequestData.ReadInt32(); - int AddVal = Context.RequestData.ReadInt32(); - int Type = Context.RequestData.ReadInt32(); + int id = context.RequestData.ReadInt32(); + int addVal = context.RequestData.ReadInt32(); + int type = context.RequestData.ReadInt32(); return 0; } - public long GetNativeHandle(ServiceCtx Context) + public long GetNativeHandle(ServiceCtx context) { - int Id = Context.RequestData.ReadInt32(); - uint Unk = Context.RequestData.ReadUInt32(); + int id = context.RequestData.ReadInt32(); + uint unk = context.RequestData.ReadUInt32(); - if (Context.Process.HandleTable.GenerateHandle(BinderEvent.ReadableEvent, out int Handle) != KernelResult.Success) + if (context.Process.HandleTable.GenerateHandle(_binderEvent.ReadableEvent, out int handle) != KernelResult.Success) { throw new InvalidOperationException("Out of handles!"); } - Context.Response.HandleDesc = IpcHandleDesc.MakeMove(Handle); + context.Response.HandleDesc = IpcHandleDesc.MakeMove(handle); return 0; } @@ -92,11 +92,11 @@ namespace Ryujinx.HLE.HOS.Services.Vi Dispose(true); } - protected virtual void Dispose(bool Disposing) + protected virtual void Dispose(bool disposing) { - if (Disposing) + if (disposing) { - Flinger.Dispose(); + _flinger.Dispose(); } } } diff --git a/Ryujinx.HLE/HOS/Services/Vi/IManagerDisplayService.cs b/Ryujinx.HLE/HOS/Services/Vi/IManagerDisplayService.cs index a78f1812..369c376f 100644 --- a/Ryujinx.HLE/HOS/Services/Vi/IManagerDisplayService.cs +++ b/Ryujinx.HLE/HOS/Services/Vi/IManagerDisplayService.cs @@ -6,13 +6,13 @@ namespace Ryujinx.HLE.HOS.Services.Vi { class IManagerDisplayService : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IManagerDisplayService() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 2010, CreateManagedLayer }, { 2011, DestroyManagedLayer }, @@ -21,30 +21,30 @@ namespace Ryujinx.HLE.HOS.Services.Vi }; } - public static long CreateManagedLayer(ServiceCtx Context) + public static long CreateManagedLayer(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceVi, "Stubbed."); - Context.ResponseData.Write(0L); //LayerId + context.ResponseData.Write(0L); //LayerId return 0; } - public long DestroyManagedLayer(ServiceCtx Context) + public long DestroyManagedLayer(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceVi, "Stubbed."); return 0; } - public static long AddToLayerStack(ServiceCtx Context) + public static long AddToLayerStack(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceVi, "Stubbed."); return 0; } - public static long SetLayerVisibility(ServiceCtx Context) + public static long SetLayerVisibility(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceVi, "Stubbed."); diff --git a/Ryujinx.HLE/HOS/Services/Vi/IManagerRootService.cs b/Ryujinx.HLE/HOS/Services/Vi/IManagerRootService.cs index 14b8fc3c..0f0a4f26 100644 --- a/Ryujinx.HLE/HOS/Services/Vi/IManagerRootService.cs +++ b/Ryujinx.HLE/HOS/Services/Vi/IManagerRootService.cs @@ -5,23 +5,23 @@ namespace Ryujinx.HLE.HOS.Services.Vi { class IManagerRootService : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public IManagerRootService() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 2, GetDisplayService } }; } - public long GetDisplayService(ServiceCtx Context) + public long GetDisplayService(ServiceCtx context) { - int ServiceType = Context.RequestData.ReadInt32(); + int serviceType = context.RequestData.ReadInt32(); - MakeObject(Context, new IApplicationDisplayService()); + MakeObject(context, new IApplicationDisplayService()); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Vi/ISystemDisplayService.cs b/Ryujinx.HLE/HOS/Services/Vi/ISystemDisplayService.cs index 4545579b..5266a253 100644 --- a/Ryujinx.HLE/HOS/Services/Vi/ISystemDisplayService.cs +++ b/Ryujinx.HLE/HOS/Services/Vi/ISystemDisplayService.cs @@ -6,13 +6,13 @@ namespace Ryujinx.HLE.HOS.Services.Vi { class ISystemDisplayService : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public ISystemDisplayService() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 2205, SetLayerZ }, { 2207, SetLayerVisibility }, @@ -20,27 +20,27 @@ namespace Ryujinx.HLE.HOS.Services.Vi }; } - public static long SetLayerZ(ServiceCtx Context) + public static long SetLayerZ(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceVi, "Stubbed."); return 0; } - public static long SetLayerVisibility(ServiceCtx Context) + public static long SetLayerVisibility(ServiceCtx context) { Logger.PrintStub(LogClass.ServiceVi, "Stubbed."); return 0; } - public static long GetDisplayMode(ServiceCtx Context) + public static long GetDisplayMode(ServiceCtx context) { //TODO: De-hardcode resolution. - Context.ResponseData.Write(1280); - Context.ResponseData.Write(720); - Context.ResponseData.Write(60.0f); - Context.ResponseData.Write(0); + context.ResponseData.Write(1280); + context.ResponseData.Write(720); + context.ResponseData.Write(60.0f); + context.ResponseData.Write(0); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Vi/ISystemRootService.cs b/Ryujinx.HLE/HOS/Services/Vi/ISystemRootService.cs index d9b7c220..5e255ce5 100644 --- a/Ryujinx.HLE/HOS/Services/Vi/ISystemRootService.cs +++ b/Ryujinx.HLE/HOS/Services/Vi/ISystemRootService.cs @@ -5,23 +5,23 @@ namespace Ryujinx.HLE.HOS.Services.Vi { class ISystemRootService : IpcService { - private Dictionary m_Commands; + private Dictionary _commands; - public override IReadOnlyDictionary Commands => m_Commands; + public override IReadOnlyDictionary Commands => _commands; public ISystemRootService() { - m_Commands = new Dictionary() + _commands = new Dictionary { { 1, GetDisplayService } }; } - public long GetDisplayService(ServiceCtx Context) + public long GetDisplayService(ServiceCtx context) { - int ServiceType = Context.RequestData.ReadInt32(); + int serviceType = context.RequestData.ReadInt32(); - MakeObject(Context, new IApplicationDisplayService()); + MakeObject(context, new IApplicationDisplayService()); return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Vi/NvFlinger.cs b/Ryujinx.HLE/HOS/Services/Vi/NvFlinger.cs index facfbe60..1b57b331 100644 --- a/Ryujinx.HLE/HOS/Services/Vi/NvFlinger.cs +++ b/Ryujinx.HLE/HOS/Services/Vi/NvFlinger.cs @@ -16,13 +16,13 @@ namespace Ryujinx.HLE.HOS.Services.Android { class NvFlinger : IDisposable { - private delegate long ServiceProcessParcel(ServiceCtx Context, BinaryReader ParcelReader); + private delegate long ServiceProcessParcel(ServiceCtx context, BinaryReader parcelReader); - private Dictionary<(string, int), ServiceProcessParcel> Commands; + private Dictionary<(string, int), ServiceProcessParcel> _commands; - private KEvent BinderEvent; + private KEvent _binderEvent; - private IGalRenderer Renderer; + private IGalRenderer _renderer; private const int BufferQueueCount = 0x40; private const int BufferQueueMask = BufferQueueCount - 1; @@ -62,15 +62,15 @@ namespace Ryujinx.HLE.HOS.Services.Android public GbpBuffer Data; } - private BufferEntry[] BufferQueue; + private BufferEntry[] _bufferQueue; - private AutoResetEvent WaitBufferFree; + private AutoResetEvent _waitBufferFree; - private bool Disposed; + private bool _disposed; - public NvFlinger(IGalRenderer Renderer, KEvent BinderEvent) + public NvFlinger(IGalRenderer renderer, KEvent binderEvent) { - Commands = new Dictionary<(string, int), ServiceProcessParcel>() + _commands = new Dictionary<(string, int), ServiceProcessParcel> { { ("android.gui.IGraphicBufferProducer", 0x1), GbpRequestBuffer }, { ("android.gui.IGraphicBufferProducer", 0x3), GbpDequeueBuffer }, @@ -83,307 +83,307 @@ namespace Ryujinx.HLE.HOS.Services.Android { ("android.gui.IGraphicBufferProducer", 0xe), GbpPreallocBuffer } }; - this.Renderer = Renderer; - this.BinderEvent = BinderEvent; + _renderer = renderer; + _binderEvent = binderEvent; - BufferQueue = new BufferEntry[0x40]; + _bufferQueue = new BufferEntry[0x40]; - WaitBufferFree = new AutoResetEvent(false); + _waitBufferFree = new AutoResetEvent(false); } - public long ProcessParcelRequest(ServiceCtx Context, byte[] ParcelData, int Code) + public long ProcessParcelRequest(ServiceCtx context, byte[] parcelData, int code) { - using (MemoryStream MS = new MemoryStream(ParcelData)) + using (MemoryStream ms = new MemoryStream(parcelData)) { - BinaryReader Reader = new BinaryReader(MS); + BinaryReader reader = new BinaryReader(ms); - MS.Seek(4, SeekOrigin.Current); + ms.Seek(4, SeekOrigin.Current); - int StrSize = Reader.ReadInt32(); + int strSize = reader.ReadInt32(); - string InterfaceName = Encoding.Unicode.GetString(Reader.ReadBytes(StrSize * 2)); + string interfaceName = Encoding.Unicode.GetString(reader.ReadBytes(strSize * 2)); - long Remainder = MS.Position & 0xf; + long remainder = ms.Position & 0xf; - if (Remainder != 0) + if (remainder != 0) { - MS.Seek(0x10 - Remainder, SeekOrigin.Current); + ms.Seek(0x10 - remainder, SeekOrigin.Current); } - MS.Seek(0x50, SeekOrigin.Begin); + ms.Seek(0x50, SeekOrigin.Begin); - if (Commands.TryGetValue((InterfaceName, Code), out ServiceProcessParcel ProcReq)) + if (_commands.TryGetValue((interfaceName, code), out ServiceProcessParcel procReq)) { - Logger.PrintDebug(LogClass.ServiceVi, $"{InterfaceName} {ProcReq.Method.Name}"); + Logger.PrintDebug(LogClass.ServiceVi, $"{interfaceName} {procReq.Method.Name}"); - return ProcReq(Context, Reader); + return procReq(context, reader); } else { - throw new NotImplementedException($"{InterfaceName} {Code}"); + throw new NotImplementedException($"{interfaceName} {code}"); } } } - private long GbpRequestBuffer(ServiceCtx Context, BinaryReader ParcelReader) + private long GbpRequestBuffer(ServiceCtx context, BinaryReader parcelReader) { - int Slot = ParcelReader.ReadInt32(); + int slot = parcelReader.ReadInt32(); - using (MemoryStream MS = new MemoryStream()) + using (MemoryStream ms = new MemoryStream()) { - BinaryWriter Writer = new BinaryWriter(MS); + BinaryWriter writer = new BinaryWriter(ms); - BufferEntry Entry = BufferQueue[Slot]; + BufferEntry entry = _bufferQueue[slot]; - int BufferCount = 1; //? - long BufferSize = Entry.Data.Size; + int bufferCount = 1; //? + long bufferSize = entry.Data.Size; - Writer.Write(BufferCount); - Writer.Write(BufferSize); + writer.Write(bufferCount); + writer.Write(bufferSize); - Entry.Data.Write(Writer); + entry.Data.Write(writer); - Writer.Write(0); + writer.Write(0); - return MakeReplyParcel(Context, MS.ToArray()); + return MakeReplyParcel(context, ms.ToArray()); } } - private long GbpDequeueBuffer(ServiceCtx Context, BinaryReader ParcelReader) + private long GbpDequeueBuffer(ServiceCtx context, BinaryReader parcelReader) { //TODO: Errors. - int Format = ParcelReader.ReadInt32(); - int Width = ParcelReader.ReadInt32(); - int Height = ParcelReader.ReadInt32(); - int GetTimestamps = ParcelReader.ReadInt32(); - int Usage = ParcelReader.ReadInt32(); + int format = parcelReader.ReadInt32(); + int width = parcelReader.ReadInt32(); + int height = parcelReader.ReadInt32(); + int getTimestamps = parcelReader.ReadInt32(); + int usage = parcelReader.ReadInt32(); - int Slot = GetFreeSlotBlocking(Width, Height); + int slot = GetFreeSlotBlocking(width, height); - return MakeReplyParcel(Context, Slot, 1, 0x24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + return MakeReplyParcel(context, slot, 1, 0x24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } - private long GbpQueueBuffer(ServiceCtx Context, BinaryReader ParcelReader) + private long GbpQueueBuffer(ServiceCtx context, BinaryReader parcelReader) { - Context.Device.Statistics.RecordGameFrameTime(); + context.Device.Statistics.RecordGameFrameTime(); //TODO: Errors. - int Slot = ParcelReader.ReadInt32(); - int Unknown4 = ParcelReader.ReadInt32(); - int Unknown8 = ParcelReader.ReadInt32(); - int Unknownc = ParcelReader.ReadInt32(); - int Timestamp = ParcelReader.ReadInt32(); - int IsAutoTimestamp = ParcelReader.ReadInt32(); - int CropTop = ParcelReader.ReadInt32(); - int CropLeft = ParcelReader.ReadInt32(); - int CropRight = ParcelReader.ReadInt32(); - int CropBottom = ParcelReader.ReadInt32(); - int ScalingMode = ParcelReader.ReadInt32(); - int Transform = ParcelReader.ReadInt32(); - int StickyTransform = ParcelReader.ReadInt32(); - int Unknown34 = ParcelReader.ReadInt32(); - int Unknown38 = ParcelReader.ReadInt32(); - int IsFenceValid = ParcelReader.ReadInt32(); - int Fence0Id = ParcelReader.ReadInt32(); - int Fence0Value = ParcelReader.ReadInt32(); - int Fence1Id = ParcelReader.ReadInt32(); - int Fence1Value = ParcelReader.ReadInt32(); + int slot = parcelReader.ReadInt32(); + int unknown4 = parcelReader.ReadInt32(); + int unknown8 = parcelReader.ReadInt32(); + int unknownC = parcelReader.ReadInt32(); + int timestamp = parcelReader.ReadInt32(); + int isAutoTimestamp = parcelReader.ReadInt32(); + int cropTop = parcelReader.ReadInt32(); + int cropLeft = parcelReader.ReadInt32(); + int cropRight = parcelReader.ReadInt32(); + int cropBottom = parcelReader.ReadInt32(); + int scalingMode = parcelReader.ReadInt32(); + int transform = parcelReader.ReadInt32(); + int stickyTransform = parcelReader.ReadInt32(); + int unknown34 = parcelReader.ReadInt32(); + int unknown38 = parcelReader.ReadInt32(); + int isFenceValid = parcelReader.ReadInt32(); + int fence0Id = parcelReader.ReadInt32(); + int fence0Value = parcelReader.ReadInt32(); + int fence1Id = parcelReader.ReadInt32(); + int fence1Value = parcelReader.ReadInt32(); - BufferQueue[Slot].Transform = (HalTransform)Transform; + _bufferQueue[slot].Transform = (HalTransform)transform; - BufferQueue[Slot].Crop.Top = CropTop; - BufferQueue[Slot].Crop.Left = CropLeft; - BufferQueue[Slot].Crop.Right = CropRight; - BufferQueue[Slot].Crop.Bottom = CropBottom; + _bufferQueue[slot].Crop.Top = cropTop; + _bufferQueue[slot].Crop.Left = cropLeft; + _bufferQueue[slot].Crop.Right = cropRight; + _bufferQueue[slot].Crop.Bottom = cropBottom; - BufferQueue[Slot].State = BufferState.Queued; + _bufferQueue[slot].State = BufferState.Queued; - SendFrameBuffer(Context, Slot); + SendFrameBuffer(context, slot); - if (Context.Device.EnableDeviceVsync) + if (context.Device.EnableDeviceVsync) { - Context.Device.VsyncEvent.WaitOne(); + context.Device.VsyncEvent.WaitOne(); } - return MakeReplyParcel(Context, 1280, 720, 0, 0, 0); + return MakeReplyParcel(context, 1280, 720, 0, 0, 0); } - private long GbpDetachBuffer(ServiceCtx Context, BinaryReader ParcelReader) + private long GbpDetachBuffer(ServiceCtx context, BinaryReader parcelReader) { - return MakeReplyParcel(Context, 0); + return MakeReplyParcel(context, 0); } - private long GbpCancelBuffer(ServiceCtx Context, BinaryReader ParcelReader) + private long GbpCancelBuffer(ServiceCtx context, BinaryReader parcelReader) { //TODO: Errors. - int Slot = ParcelReader.ReadInt32(); + int slot = parcelReader.ReadInt32(); - BufferQueue[Slot].State = BufferState.Free; + _bufferQueue[slot].State = BufferState.Free; - WaitBufferFree.Set(); + _waitBufferFree.Set(); - return MakeReplyParcel(Context, 0); + return MakeReplyParcel(context, 0); } - private long GbpQuery(ServiceCtx Context, BinaryReader ParcelReader) + private long GbpQuery(ServiceCtx context, BinaryReader parcelReader) { - return MakeReplyParcel(Context, 0, 0); + return MakeReplyParcel(context, 0, 0); } - private long GbpConnect(ServiceCtx Context, BinaryReader ParcelReader) + private long GbpConnect(ServiceCtx context, BinaryReader parcelReader) { - return MakeReplyParcel(Context, 1280, 720, 0, 0, 0); + return MakeReplyParcel(context, 1280, 720, 0, 0, 0); } - private long GbpDisconnect(ServiceCtx Context, BinaryReader ParcelReader) + private long GbpDisconnect(ServiceCtx context, BinaryReader parcelReader) { - return MakeReplyParcel(Context, 0); + return MakeReplyParcel(context, 0); } - private long GbpPreallocBuffer(ServiceCtx Context, BinaryReader ParcelReader) + private long GbpPreallocBuffer(ServiceCtx context, BinaryReader parcelReader) { - int Slot = ParcelReader.ReadInt32(); + int slot = parcelReader.ReadInt32(); - int BufferCount = ParcelReader.ReadInt32(); + int bufferCount = parcelReader.ReadInt32(); - if (BufferCount > 0) + if (bufferCount > 0) { - long BufferSize = ParcelReader.ReadInt64(); + long bufferSize = parcelReader.ReadInt64(); - BufferQueue[Slot].State = BufferState.Free; + _bufferQueue[slot].State = BufferState.Free; - BufferQueue[Slot].Data = new GbpBuffer(ParcelReader); + _bufferQueue[slot].Data = new GbpBuffer(parcelReader); } - return MakeReplyParcel(Context, 0); + return MakeReplyParcel(context, 0); } - private long MakeReplyParcel(ServiceCtx Context, params int[] Ints) + private long MakeReplyParcel(ServiceCtx context, params int[] ints) { - using (MemoryStream MS = new MemoryStream()) + using (MemoryStream ms = new MemoryStream()) { - BinaryWriter Writer = new BinaryWriter(MS); + BinaryWriter writer = new BinaryWriter(ms); - foreach (int Int in Ints) + foreach (int Int in ints) { - Writer.Write(Int); + writer.Write(Int); } - return MakeReplyParcel(Context, MS.ToArray()); + return MakeReplyParcel(context, ms.ToArray()); } } - private long MakeReplyParcel(ServiceCtx Context, byte[] Data) + private long MakeReplyParcel(ServiceCtx context, byte[] data) { - (long ReplyPos, long ReplySize) = Context.Request.GetBufferType0x22(); + (long replyPos, long replySize) = context.Request.GetBufferType0x22(); - byte[] Reply = MakeParcel(Data, new byte[0]); + byte[] reply = MakeParcel(data, new byte[0]); - Context.Memory.WriteBytes(ReplyPos, Reply); + context.Memory.WriteBytes(replyPos, reply); return 0; } - private void SendFrameBuffer(ServiceCtx Context, int Slot) + private void SendFrameBuffer(ServiceCtx context, int slot) { - int FbWidth = BufferQueue[Slot].Data.Width; - int FbHeight = BufferQueue[Slot].Data.Height; + int fbWidth = _bufferQueue[slot].Data.Width; + int fbHeight = _bufferQueue[slot].Data.Height; - int NvMapHandle = BitConverter.ToInt32(BufferQueue[Slot].Data.RawData, 0x4c); - int BufferOffset = BitConverter.ToInt32(BufferQueue[Slot].Data.RawData, 0x50); + int nvMapHandle = BitConverter.ToInt32(_bufferQueue[slot].Data.RawData, 0x4c); + int bufferOffset = BitConverter.ToInt32(_bufferQueue[slot].Data.RawData, 0x50); - NvMapHandle Map = NvMapIoctl.GetNvMap(Context, NvMapHandle);; + NvMapHandle map = NvMapIoctl.GetNvMap(context, nvMapHandle); - long FbAddr = Map.Address + BufferOffset; + long fbAddr = map.Address + bufferOffset; - BufferQueue[Slot].State = BufferState.Acquired; + _bufferQueue[slot].State = BufferState.Acquired; - Rect Crop = BufferQueue[Slot].Crop; + Rect crop = _bufferQueue[slot].Crop; - bool FlipX = BufferQueue[Slot].Transform.HasFlag(HalTransform.FlipX); - bool FlipY = BufferQueue[Slot].Transform.HasFlag(HalTransform.FlipY); + bool flipX = _bufferQueue[slot].Transform.HasFlag(HalTransform.FlipX); + bool flipY = _bufferQueue[slot].Transform.HasFlag(HalTransform.FlipY); //Note: Rotation is being ignored. - int Top = Crop.Top; - int Left = Crop.Left; - int Right = Crop.Right; - int Bottom = Crop.Bottom; + int top = crop.Top; + int left = crop.Left; + int right = crop.Right; + int bottom = crop.Bottom; - NvGpuVmm Vmm = NvGpuASIoctl.GetASCtx(Context).Vmm; + NvGpuVmm vmm = NvGpuASIoctl.GetASCtx(context).Vmm; - Renderer.QueueAction(() => + _renderer.QueueAction(() => { - if (!Renderer.Texture.TryGetImage(FbAddr, out GalImage Image)) + if (!_renderer.Texture.TryGetImage(fbAddr, out GalImage image)) { - Image = new GalImage( - FbWidth, - FbHeight, 1, 16, + image = new GalImage( + fbWidth, + fbHeight, 1, 16, GalMemoryLayout.BlockLinear, GalImageFormat.RGBA8 | GalImageFormat.Unorm); } - Context.Device.Gpu.ResourceManager.ClearPbCache(); - Context.Device.Gpu.ResourceManager.SendTexture(Vmm, FbAddr, Image); + context.Device.Gpu.ResourceManager.ClearPbCache(); + context.Device.Gpu.ResourceManager.SendTexture(vmm, fbAddr, image); - Renderer.RenderTarget.SetTransform(FlipX, FlipY, Top, Left, Right, Bottom); - Renderer.RenderTarget.Present(FbAddr); + _renderer.RenderTarget.SetTransform(flipX, flipY, top, left, right, bottom); + _renderer.RenderTarget.Present(fbAddr); - ReleaseBuffer(Slot); + ReleaseBuffer(slot); }); } - private void ReleaseBuffer(int Slot) + private void ReleaseBuffer(int slot) { - BufferQueue[Slot].State = BufferState.Free; + _bufferQueue[slot].State = BufferState.Free; - BinderEvent.ReadableEvent.Signal(); + _binderEvent.ReadableEvent.Signal(); - WaitBufferFree.Set(); + _waitBufferFree.Set(); } - private int GetFreeSlotBlocking(int Width, int Height) + private int GetFreeSlotBlocking(int width, int height) { - int Slot; + int slot; do { - if ((Slot = GetFreeSlot(Width, Height)) != -1) + if ((slot = GetFreeSlot(width, height)) != -1) { break; } - if (Disposed) + if (_disposed) { break; } - WaitBufferFree.WaitOne(); + _waitBufferFree.WaitOne(); } - while (!Disposed); + while (!_disposed); - return Slot; + return slot; } - private int GetFreeSlot(int Width, int Height) + private int GetFreeSlot(int width, int height) { - lock (BufferQueue) + lock (_bufferQueue) { - for (int Slot = 0; Slot < BufferQueue.Length; Slot++) + for (int slot = 0; slot < _bufferQueue.Length; slot++) { - if (BufferQueue[Slot].State != BufferState.Free) + if (_bufferQueue[slot].State != BufferState.Free) { continue; } - GbpBuffer Data = BufferQueue[Slot].Data; + GbpBuffer data = _bufferQueue[slot].Data; - if (Data.Width == Width && - Data.Height == Height) + if (data.Width == width && + data.Height == height) { - BufferQueue[Slot].State = BufferState.Dequeued; + _bufferQueue[slot].State = BufferState.Dequeued; - return Slot; + return slot; } } } @@ -396,14 +396,14 @@ namespace Ryujinx.HLE.HOS.Services.Android Dispose(true); } - protected virtual void Dispose(bool Disposing) + protected virtual void Dispose(bool disposing) { - if (Disposing && !Disposed) + if (disposing && !_disposed) { - Disposed = true; + _disposed = true; - WaitBufferFree.Set(); - WaitBufferFree.Dispose(); + _waitBufferFree.Set(); + _waitBufferFree.Dispose(); } } } diff --git a/Ryujinx.HLE/HOS/Services/Vi/Parcel.cs b/Ryujinx.HLE/HOS/Services/Vi/Parcel.cs index bb842795..63c5a82f 100644 --- a/Ryujinx.HLE/HOS/Services/Vi/Parcel.cs +++ b/Ryujinx.HLE/HOS/Services/Vi/Parcel.cs @@ -5,53 +5,53 @@ namespace Ryujinx.HLE.HOS.Services.Android { static class Parcel { - public static byte[] GetParcelData(byte[] Parcel) + public static byte[] GetParcelData(byte[] parcel) { - if (Parcel == null) + if (parcel == null) { - throw new ArgumentNullException(nameof(Parcel)); + throw new ArgumentNullException(nameof(parcel)); } - using (MemoryStream MS = new MemoryStream(Parcel)) + using (MemoryStream ms = new MemoryStream(parcel)) { - BinaryReader Reader = new BinaryReader(MS); + BinaryReader reader = new BinaryReader(ms); - int DataSize = Reader.ReadInt32(); - int DataOffset = Reader.ReadInt32(); - int ObjsSize = Reader.ReadInt32(); - int ObjsOffset = Reader.ReadInt32(); + int dataSize = reader.ReadInt32(); + int dataOffset = reader.ReadInt32(); + int objsSize = reader.ReadInt32(); + int objsOffset = reader.ReadInt32(); - MS.Seek(DataOffset - 0x10, SeekOrigin.Current); + ms.Seek(dataOffset - 0x10, SeekOrigin.Current); - return Reader.ReadBytes(DataSize); + return reader.ReadBytes(dataSize); } } - public static byte[] MakeParcel(byte[] Data, byte[] Objs) + public static byte[] MakeParcel(byte[] data, byte[] objs) { - if (Data == null) + if (data == null) { - throw new ArgumentNullException(nameof(Data)); + throw new ArgumentNullException(nameof(data)); } - if (Objs == null) + if (objs == null) { - throw new ArgumentNullException(nameof(Objs)); + throw new ArgumentNullException(nameof(objs)); } - using (MemoryStream MS = new MemoryStream()) + using (MemoryStream ms = new MemoryStream()) { - BinaryWriter Writer = new BinaryWriter(MS); + BinaryWriter writer = new BinaryWriter(ms); - Writer.Write(Data.Length); - Writer.Write(0x10); - Writer.Write(Objs.Length); - Writer.Write(Data.Length + 0x10); + writer.Write(data.Length); + writer.Write(0x10); + writer.Write(objs.Length); + writer.Write(data.Length + 0x10); - Writer.Write(Data); - Writer.Write(Objs); + writer.Write(data); + writer.Write(objs); - return MS.ToArray(); + return ms.ToArray(); } } } diff --git a/Ryujinx.HLE/HOS/SystemState/AppletStateMgr.cs b/Ryujinx.HLE/HOS/SystemState/AppletStateMgr.cs index 274892c0..f46a7c30 100644 --- a/Ryujinx.HLE/HOS/SystemState/AppletStateMgr.cs +++ b/Ryujinx.HLE/HOS/SystemState/AppletStateMgr.cs @@ -6,43 +6,43 @@ namespace Ryujinx.HLE.HOS.SystemState { class AppletStateMgr { - private ConcurrentQueue Messages; + private ConcurrentQueue _messages; public FocusState FocusState { get; private set; } public KEvent MessageEvent { get; private set; } - public AppletStateMgr(Horizon System) + public AppletStateMgr(Horizon system) { - Messages = new ConcurrentQueue(); + _messages = new ConcurrentQueue(); - MessageEvent = new KEvent(System); + MessageEvent = new KEvent(system); } - public void SetFocus(bool IsFocused) + public void SetFocus(bool isFocused) { - FocusState = IsFocused + FocusState = isFocused ? FocusState.InFocus : FocusState.OutOfFocus; EnqueueMessage(MessageInfo.FocusStateChanged); } - public void EnqueueMessage(MessageInfo Message) + public void EnqueueMessage(MessageInfo message) { - Messages.Enqueue(Message); + _messages.Enqueue(message); MessageEvent.ReadableEvent.Signal(); } - public bool TryDequeueMessage(out MessageInfo Message) + public bool TryDequeueMessage(out MessageInfo message) { - if (Messages.Count < 2) + if (_messages.Count < 2) { MessageEvent.ReadableEvent.Clear(); } - return Messages.TryDequeue(out Message); + return _messages.TryDequeue(out message); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/SystemState/SystemStateMgr.cs b/Ryujinx.HLE/HOS/SystemState/SystemStateMgr.cs index aa96a416..74513795 100644 --- a/Ryujinx.HLE/HOS/SystemState/SystemStateMgr.cs +++ b/Ryujinx.HLE/HOS/SystemState/SystemStateMgr.cs @@ -48,7 +48,7 @@ namespace Ryujinx.HLE.HOS.SystemState public bool InstallContents { get; set; } - private ConcurrentDictionary Profiles; + private ConcurrentDictionary _profiles; internal UserProfile LastOpenUser { get; private set; } @@ -58,20 +58,20 @@ namespace Ryujinx.HLE.HOS.SystemState SetAudioOutputAsBuiltInSpeaker(); - Profiles = new ConcurrentDictionary(); + _profiles = new ConcurrentDictionary(); - UInt128 DefaultUuid = new UInt128("00000000000000000000000000000001"); + UInt128 defaultUuid = new UInt128("00000000000000000000000000000001"); - AddUser(DefaultUuid, "Player"); + AddUser(defaultUuid, "Player"); - OpenUser(DefaultUuid); + OpenUser(defaultUuid); } - public void SetLanguage(SystemLanguage Language) + public void SetLanguage(SystemLanguage language) { - DesiredLanguageCode = GetLanguageCode((int)Language); + DesiredLanguageCode = GetLanguageCode((int)language); - DesiredTitleLanguage = Enum.Parse(Enum.GetName(typeof(SystemLanguage), Language)); + DesiredTitleLanguage = Enum.Parse(Enum.GetName(typeof(SystemLanguage), language)); } public void SetAudioOutputAsTv() @@ -89,65 +89,65 @@ namespace Ryujinx.HLE.HOS.SystemState ActiveAudioOutput = AudioOutputs[2]; } - public void AddUser(UInt128 Uuid, string Name) + public void AddUser(UInt128 uuid, string name) { - UserProfile Profile = new UserProfile(Uuid, Name); + UserProfile profile = new UserProfile(uuid, name); - Profiles.AddOrUpdate(Uuid.ToString(), Profile, (Key, Old) => Profile); + _profiles.AddOrUpdate(uuid.ToString(), profile, (key, old) => profile); } - public void OpenUser(UInt128 Uuid) + public void OpenUser(UInt128 uuid) { - if (Profiles.TryGetValue(Uuid.ToString(), out UserProfile Profile)) + if (_profiles.TryGetValue(uuid.ToString(), out UserProfile profile)) { - (LastOpenUser = Profile).AccountState = OpenCloseState.Open; + (LastOpenUser = profile).AccountState = OpenCloseState.Open; } } - public void CloseUser(UInt128 Uuid) + public void CloseUser(UInt128 uuid) { - if (Profiles.TryGetValue(Uuid.ToString(), out UserProfile Profile)) + if (_profiles.TryGetValue(uuid.ToString(), out UserProfile profile)) { - Profile.AccountState = OpenCloseState.Closed; + profile.AccountState = OpenCloseState.Closed; } } public int GetUserCount() { - return Profiles.Count; + return _profiles.Count; } - internal bool TryGetUser(UInt128 Uuid, out UserProfile Profile) + internal bool TryGetUser(UInt128 uuid, out UserProfile profile) { - return Profiles.TryGetValue(Uuid.ToString(), out Profile); + return _profiles.TryGetValue(uuid.ToString(), out profile); } internal IEnumerable GetAllUsers() { - return Profiles.Values; + return _profiles.Values; } internal IEnumerable GetOpenUsers() { - return Profiles.Values.Where(x => x.AccountState == OpenCloseState.Open); + return _profiles.Values.Where(x => x.AccountState == OpenCloseState.Open); } - internal static long GetLanguageCode(int Index) + internal static long GetLanguageCode(int index) { - if ((uint)Index >= LanguageCodes.Length) + if ((uint)index >= LanguageCodes.Length) { - throw new ArgumentOutOfRangeException(nameof(Index)); + throw new ArgumentOutOfRangeException(nameof(index)); } - long Code = 0; - int Shift = 0; + long code = 0; + int shift = 0; - foreach (char Chr in LanguageCodes[Index]) + foreach (char chr in LanguageCodes[index]) { - Code |= (long)(byte)Chr << Shift++ * 8; + code |= (long)(byte)chr << shift++ * 8; } - return Code; + return code; } } } diff --git a/Ryujinx.HLE/HOS/SystemState/UserProfile.cs b/Ryujinx.HLE/HOS/SystemState/UserProfile.cs index e08bc48a..9240389c 100644 --- a/Ryujinx.HLE/HOS/SystemState/UserProfile.cs +++ b/Ryujinx.HLE/HOS/SystemState/UserProfile.cs @@ -16,10 +16,10 @@ namespace Ryujinx.HLE.HOS.SystemState public OpenCloseState AccountState { get; set; } public OpenCloseState OnlinePlayState { get; set; } - public UserProfile(UInt128 Uuid, string Name) + public UserProfile(UInt128 uuid, string name) { - this.Uuid = Uuid; - this.Name = Name; + Uuid = uuid; + Name = name; LastModifiedTimestamp = 0; diff --git a/Ryujinx.HLE/Input/Hid.cs b/Ryujinx.HLE/Input/Hid.cs index edcfe42d..c35fb07c 100644 --- a/Ryujinx.HLE/Input/Hid.cs +++ b/Ryujinx.HLE/Input/Hid.cs @@ -5,130 +5,130 @@ namespace Ryujinx.HLE.Input { public partial class Hid { - private Switch Device; + private Switch _device; public HidControllerBase PrimaryController { get; private set; } internal long HidPosition; - public Hid(Switch Device, long HidPosition) + public Hid(Switch device, long hidPosition) { - this.Device = Device; - this.HidPosition = HidPosition; + _device = device; + HidPosition = hidPosition; - Device.Memory.FillWithZeros(HidPosition, Horizon.HidSize); + device.Memory.FillWithZeros(hidPosition, Horizon.HidSize); } - public void InitilizePrimaryController(HidControllerType ControllerType) + public void InitilizePrimaryController(HidControllerType controllerType) { - HidControllerId ControllerId = ControllerType == HidControllerType.Handheld ? - HidControllerId.CONTROLLER_HANDHELD : HidControllerId.CONTROLLER_PLAYER_1; + HidControllerId controllerId = controllerType == HidControllerType.Handheld ? + HidControllerId.ControllerHandheld : HidControllerId.ControllerPlayer1; - if (ControllerType == HidControllerType.ProController) + if (controllerType == HidControllerType.ProController) { - PrimaryController = new HidProController(Device); + PrimaryController = new HidProController(_device); } else { - PrimaryController = new HidNpadController(ControllerType, - Device, - (NpadColor.Body_Neon_Red, NpadColor.Body_Neon_Red), - (NpadColor.Buttons_Neon_Blue, NpadColor.Buttons_Neon_Blue)); + PrimaryController = new HidNpadController(controllerType, + _device, + (NpadColor.BodyNeonRed, NpadColor.BodyNeonRed), + (NpadColor.ButtonsNeonBlue, NpadColor.ButtonsNeonBlue)); } - PrimaryController.Connect(ControllerId); + PrimaryController.Connect(controllerId); } private HidControllerButtons UpdateStickButtons( - HidJoystickPosition LeftStick, - HidJoystickPosition RightStick) + HidJoystickPosition leftStick, + HidJoystickPosition rightStick) { - HidControllerButtons Result = 0; + HidControllerButtons result = 0; - if (RightStick.DX < 0) + if (rightStick.Dx < 0) { - Result |= HidControllerButtons.RStickLeft; + result |= HidControllerButtons.RStickLeft; } - if (RightStick.DX > 0) + if (rightStick.Dx > 0) { - Result |= HidControllerButtons.RStickRight; + result |= HidControllerButtons.RStickRight; } - if (RightStick.DY < 0) + if (rightStick.Dy < 0) { - Result |= HidControllerButtons.RStickDown; + result |= HidControllerButtons.RStickDown; } - if (RightStick.DY > 0) + if (rightStick.Dy > 0) { - Result |= HidControllerButtons.RStickUp; + result |= HidControllerButtons.RStickUp; } - if (LeftStick.DX < 0) + if (leftStick.Dx < 0) { - Result |= HidControllerButtons.LStickLeft; + result |= HidControllerButtons.LStickLeft; } - if (LeftStick.DX > 0) + if (leftStick.Dx > 0) { - Result |= HidControllerButtons.LStickRight; + result |= HidControllerButtons.LStickRight; } - if (LeftStick.DY < 0) + if (leftStick.Dy < 0) { - Result |= HidControllerButtons.LStickDown; + result |= HidControllerButtons.LStickDown; } - if (LeftStick.DY > 0) + if (leftStick.Dy > 0) { - Result |= HidControllerButtons.LStickUp; + result |= HidControllerButtons.LStickUp; } - return Result; + return result; } - public void SetTouchPoints(params HidTouchPoint[] Points) + public void SetTouchPoints(params HidTouchPoint[] points) { - long TouchScreenOffset = HidPosition + HidTouchScreenOffset; - long LastEntry = Device.Memory.ReadInt64(TouchScreenOffset + 0x10); - long CurrEntry = (LastEntry + 1) % HidEntryCount; - long Timestamp = GetTimestamp(); + long touchScreenOffset = HidPosition + HidTouchScreenOffset; + long lastEntry = _device.Memory.ReadInt64(touchScreenOffset + 0x10); + long currEntry = (lastEntry + 1) % HidEntryCount; + long timestamp = GetTimestamp(); - Device.Memory.WriteInt64(TouchScreenOffset + 0x00, Timestamp); - Device.Memory.WriteInt64(TouchScreenOffset + 0x08, HidEntryCount); - Device.Memory.WriteInt64(TouchScreenOffset + 0x10, CurrEntry); - Device.Memory.WriteInt64(TouchScreenOffset + 0x18, HidEntryCount - 1); - Device.Memory.WriteInt64(TouchScreenOffset + 0x20, Timestamp); + _device.Memory.WriteInt64(touchScreenOffset + 0x00, timestamp); + _device.Memory.WriteInt64(touchScreenOffset + 0x08, HidEntryCount); + _device.Memory.WriteInt64(touchScreenOffset + 0x10, currEntry); + _device.Memory.WriteInt64(touchScreenOffset + 0x18, HidEntryCount - 1); + _device.Memory.WriteInt64(touchScreenOffset + 0x20, timestamp); - long TouchEntryOffset = TouchScreenOffset + HidTouchHeaderSize; - long LastEntryOffset = TouchEntryOffset + LastEntry * HidTouchEntrySize; - long SampleCounter = Device.Memory.ReadInt64(LastEntryOffset) + 1; + long touchEntryOffset = touchScreenOffset + HidTouchHeaderSize; + long lastEntryOffset = touchEntryOffset + lastEntry * HidTouchEntrySize; + long sampleCounter = _device.Memory.ReadInt64(lastEntryOffset) + 1; - TouchEntryOffset += CurrEntry * HidTouchEntrySize; + touchEntryOffset += currEntry * HidTouchEntrySize; - Device.Memory.WriteInt64(TouchEntryOffset + 0x00, SampleCounter); - Device.Memory.WriteInt64(TouchEntryOffset + 0x08, Points.Length); + _device.Memory.WriteInt64(touchEntryOffset + 0x00, sampleCounter); + _device.Memory.WriteInt64(touchEntryOffset + 0x08, points.Length); - TouchEntryOffset += HidTouchEntryHeaderSize; + touchEntryOffset += HidTouchEntryHeaderSize; - const int Padding = 0; + const int padding = 0; - int Index = 0; + int index = 0; - foreach (HidTouchPoint Point in Points) + foreach (HidTouchPoint point in points) { - Device.Memory.WriteInt64(TouchEntryOffset + 0x00, SampleCounter); - Device.Memory.WriteInt32(TouchEntryOffset + 0x08, Padding); - Device.Memory.WriteInt32(TouchEntryOffset + 0x0c, Index++); - Device.Memory.WriteInt32(TouchEntryOffset + 0x10, Point.X); - Device.Memory.WriteInt32(TouchEntryOffset + 0x14, Point.Y); - Device.Memory.WriteInt32(TouchEntryOffset + 0x18, Point.DiameterX); - Device.Memory.WriteInt32(TouchEntryOffset + 0x1c, Point.DiameterY); - Device.Memory.WriteInt32(TouchEntryOffset + 0x20, Point.Angle); - Device.Memory.WriteInt32(TouchEntryOffset + 0x24, Padding); + _device.Memory.WriteInt64(touchEntryOffset + 0x00, sampleCounter); + _device.Memory.WriteInt32(touchEntryOffset + 0x08, padding); + _device.Memory.WriteInt32(touchEntryOffset + 0x0c, index++); + _device.Memory.WriteInt32(touchEntryOffset + 0x10, point.X); + _device.Memory.WriteInt32(touchEntryOffset + 0x14, point.Y); + _device.Memory.WriteInt32(touchEntryOffset + 0x18, point.DiameterX); + _device.Memory.WriteInt32(touchEntryOffset + 0x1c, point.DiameterY); + _device.Memory.WriteInt32(touchEntryOffset + 0x20, point.Angle); + _device.Memory.WriteInt32(touchEntryOffset + 0x24, padding); - TouchEntryOffset += HidTouchEntryTouchSize; + touchEntryOffset += HidTouchEntryTouchSize; } } diff --git a/Ryujinx.HLE/Input/HidBaseController.cs b/Ryujinx.HLE/Input/HidBaseController.cs index 9b9bb7ea..8b29d891 100644 --- a/Ryujinx.HLE/Input/HidBaseController.cs +++ b/Ryujinx.HLE/Input/HidBaseController.cs @@ -11,18 +11,18 @@ namespace Ryujinx.HLE.Input public long Offset { get; private set; } public bool Connected { get; protected set; } - public HidControllerBase(HidControllerType ControllerType, Switch Device) + public HidControllerBase(HidControllerType controllerType, Switch device) { - this.Device = Device; + Device = device; - HidControllerType = ControllerType; + HidControllerType = controllerType; } - public virtual void Connect(HidControllerId ControllerId) + public virtual void Connect(HidControllerId controllerId) { - this.ControllerId = ControllerId; + ControllerId = controllerId; - Offset = Device.Hid.HidPosition + HidControllersOffset + (int)ControllerId * HidControllerSize; + Offset = Device.Hid.HidPosition + HidControllersOffset + (int)controllerId * HidControllerSize; Device.Memory.FillWithZeros(Offset, 0x5000); @@ -30,47 +30,47 @@ namespace Ryujinx.HLE.Input } public abstract void SendInput( - HidControllerButtons Buttons, - HidJoystickPosition LeftStick, - HidJoystickPosition RightStick); + HidControllerButtons buttons, + HidJoystickPosition leftStick, + HidJoystickPosition rightStick); protected long WriteInput( - HidControllerButtons Buttons, - HidJoystickPosition LeftStick, - HidJoystickPosition RightStick, - HidControllerLayouts ControllerLayout) + HidControllerButtons buttons, + HidJoystickPosition leftStick, + HidJoystickPosition rightStick, + HidControllerLayouts controllerLayout) { - long ControllerOffset = Offset + HidControllerHeaderSize; + long controllerOffset = Offset + HidControllerHeaderSize; - ControllerOffset += (int)ControllerLayout * HidControllerLayoutsSize; + controllerOffset += (int)controllerLayout * HidControllerLayoutsSize; - long LastEntry = Device.Memory.ReadInt64(ControllerOffset + 0x10); - long CurrEntry = (LastEntry + 1) % HidEntryCount; - long Timestamp = GetTimestamp(); + long lastEntry = Device.Memory.ReadInt64(controllerOffset + 0x10); + long currEntry = (lastEntry + 1) % HidEntryCount; + long timestamp = GetTimestamp(); - Device.Memory.WriteInt64(ControllerOffset + 0x00, Timestamp); - Device.Memory.WriteInt64(ControllerOffset + 0x08, HidEntryCount); - Device.Memory.WriteInt64(ControllerOffset + 0x10, CurrEntry); - Device.Memory.WriteInt64(ControllerOffset + 0x18, HidEntryCount - 1); + Device.Memory.WriteInt64(controllerOffset + 0x00, timestamp); + Device.Memory.WriteInt64(controllerOffset + 0x08, HidEntryCount); + Device.Memory.WriteInt64(controllerOffset + 0x10, currEntry); + Device.Memory.WriteInt64(controllerOffset + 0x18, HidEntryCount - 1); - ControllerOffset += HidControllersLayoutHeaderSize; + controllerOffset += HidControllersLayoutHeaderSize; - long LastEntryOffset = ControllerOffset + LastEntry * HidControllersInputEntrySize; + long lastEntryOffset = controllerOffset + lastEntry * HidControllersInputEntrySize; - ControllerOffset += CurrEntry * HidControllersInputEntrySize; + controllerOffset += currEntry * HidControllersInputEntrySize; - long SampleCounter = Device.Memory.ReadInt64(LastEntryOffset) + 1; + long sampleCounter = Device.Memory.ReadInt64(lastEntryOffset) + 1; - Device.Memory.WriteInt64(ControllerOffset + 0x00, SampleCounter); - Device.Memory.WriteInt64(ControllerOffset + 0x08, SampleCounter); - Device.Memory.WriteInt64(ControllerOffset + 0x10, (uint)Buttons); + Device.Memory.WriteInt64(controllerOffset + 0x00, sampleCounter); + Device.Memory.WriteInt64(controllerOffset + 0x08, sampleCounter); + Device.Memory.WriteInt64(controllerOffset + 0x10, (uint)buttons); - Device.Memory.WriteInt32(ControllerOffset + 0x18, LeftStick.DX); - Device.Memory.WriteInt32(ControllerOffset + 0x1c, LeftStick.DY); - Device.Memory.WriteInt32(ControllerOffset + 0x20, RightStick.DX); - Device.Memory.WriteInt32(ControllerOffset + 0x24, RightStick.DY); + Device.Memory.WriteInt32(controllerOffset + 0x18, leftStick.Dx); + Device.Memory.WriteInt32(controllerOffset + 0x1c, leftStick.Dy); + Device.Memory.WriteInt32(controllerOffset + 0x20, rightStick.Dx); + Device.Memory.WriteInt32(controllerOffset + 0x24, rightStick.Dy); - return ControllerOffset; + return controllerOffset; } } } diff --git a/Ryujinx.HLE/Input/HidControllerColorDesc.cs b/Ryujinx.HLE/Input/HidControllerColorDesc.cs index b8cf2a5e..85ece5f1 100644 --- a/Ryujinx.HLE/Input/HidControllerColorDesc.cs +++ b/Ryujinx.HLE/Input/HidControllerColorDesc.cs @@ -5,6 +5,6 @@ namespace Ryujinx.HLE.Input [Flags] public enum HidControllerColorDesc { - ColorDesc_ColorsNonexistent = (1 << 1) + ColorDescColorsNonexistent = (1 << 1) } } \ No newline at end of file diff --git a/Ryujinx.HLE/Input/HidControllerConnState.cs b/Ryujinx.HLE/Input/HidControllerConnState.cs index 1fc9482a..ef41cbb8 100644 --- a/Ryujinx.HLE/Input/HidControllerConnState.cs +++ b/Ryujinx.HLE/Input/HidControllerConnState.cs @@ -5,7 +5,7 @@ namespace Ryujinx.HLE.Input [Flags] public enum HidControllerConnState { - Controller_State_Connected = (1 << 0), - Controller_State_Wired = (1 << 1) + ControllerStateConnected = (1 << 0), + ControllerStateWired = (1 << 1) } } \ No newline at end of file diff --git a/Ryujinx.HLE/Input/HidControllerId.cs b/Ryujinx.HLE/Input/HidControllerId.cs index e4a0e26c..60faf822 100644 --- a/Ryujinx.HLE/Input/HidControllerId.cs +++ b/Ryujinx.HLE/Input/HidControllerId.cs @@ -2,15 +2,15 @@ namespace Ryujinx.HLE.Input { public enum HidControllerId { - CONTROLLER_PLAYER_1 = 0, - CONTROLLER_PLAYER_2 = 1, - CONTROLLER_PLAYER_3 = 2, - CONTROLLER_PLAYER_4 = 3, - CONTROLLER_PLAYER_5 = 4, - CONTROLLER_PLAYER_6 = 5, - CONTROLLER_PLAYER_7 = 6, - CONTROLLER_PLAYER_8 = 7, - CONTROLLER_HANDHELD = 8, - CONTROLLER_UNKNOWN = 9 + ControllerPlayer1 = 0, + ControllerPlayer2 = 1, + ControllerPlayer3 = 2, + ControllerPlayer4 = 3, + ControllerPlayer5 = 4, + ControllerPlayer6 = 5, + ControllerPlayer7 = 6, + ControllerPlayer8 = 7, + ControllerHandheld = 8, + ControllerUnknown = 9 } } \ No newline at end of file diff --git a/Ryujinx.HLE/Input/HidControllerLayouts.cs b/Ryujinx.HLE/Input/HidControllerLayouts.cs index 39fdd3fe..3548175f 100644 --- a/Ryujinx.HLE/Input/HidControllerLayouts.cs +++ b/Ryujinx.HLE/Input/HidControllerLayouts.cs @@ -2,12 +2,12 @@ namespace Ryujinx.HLE.Input { public enum HidControllerLayouts { - Pro_Controller = 0, - Handheld_Joined = 1, - Joined = 2, - Left = 3, - Right = 4, - Main_No_Analog = 5, - Main = 6 + ProController = 0, + HandheldJoined = 1, + Joined = 2, + Left = 3, + Right = 4, + MainNoAnalog = 5, + Main = 6 } } \ No newline at end of file diff --git a/Ryujinx.HLE/Input/HidJoystickPosition.cs b/Ryujinx.HLE/Input/HidJoystickPosition.cs index a06ef7b2..a1fe1608 100644 --- a/Ryujinx.HLE/Input/HidJoystickPosition.cs +++ b/Ryujinx.HLE/Input/HidJoystickPosition.cs @@ -2,7 +2,7 @@ namespace Ryujinx.HLE.Input { public struct HidJoystickPosition { - public int DX; - public int DY; + public int Dx; + public int Dy; } } \ No newline at end of file diff --git a/Ryujinx.HLE/Input/HidNpadController.cs b/Ryujinx.HLE/Input/HidNpadController.cs index 7b3fa64c..90cffbdd 100644 --- a/Ryujinx.HLE/Input/HidNpadController.cs +++ b/Ryujinx.HLE/Input/HidNpadController.cs @@ -2,85 +2,85 @@ { public class HidNpadController : HidControllerBase { - private (NpadColor Left, NpadColor Right) NpadBodyColors; - private (NpadColor Left, NpadColor Right) NpadButtonColors; + private (NpadColor Left, NpadColor Right) _npadBodyColors; + private (NpadColor Left, NpadColor Right) _npadButtonColors; - private HidControllerLayouts CurrentLayout; + private HidControllerLayouts _currentLayout; - private bool IsHalf; + private bool _isHalf; public HidNpadController( - HidControllerType ControllerType, - Switch Device, - (NpadColor, NpadColor) NpadBodyColors, - (NpadColor, NpadColor) NpadButtonColors) : base(ControllerType, Device) + HidControllerType controllerType, + Switch device, + (NpadColor, NpadColor) npadBodyColors, + (NpadColor, NpadColor) npadButtonColors) : base(controllerType, device) { - this.NpadBodyColors = NpadBodyColors; - this.NpadButtonColors = NpadButtonColors; + _npadBodyColors = npadBodyColors; + _npadButtonColors = npadButtonColors; - CurrentLayout = HidControllerLayouts.Handheld_Joined; + _currentLayout = HidControllerLayouts.HandheldJoined; - switch (ControllerType) + switch (controllerType) { case HidControllerType.NpadLeft: - CurrentLayout = HidControllerLayouts.Left; + _currentLayout = HidControllerLayouts.Left; break; case HidControllerType.NpadRight: - CurrentLayout = HidControllerLayouts.Right; + _currentLayout = HidControllerLayouts.Right; break; case HidControllerType.NpadPair: - CurrentLayout = HidControllerLayouts.Joined; + _currentLayout = HidControllerLayouts.Joined; break; } } - public override void Connect(HidControllerId ControllerId) + public override void Connect(HidControllerId controllerId) { if(HidControllerType != HidControllerType.NpadLeft && HidControllerType != HidControllerType.NpadRight) { - IsHalf = false; + _isHalf = false; } - base.Connect(CurrentLayout == HidControllerLayouts.Handheld_Joined ? HidControllerId.CONTROLLER_HANDHELD : ControllerId); + base.Connect(_currentLayout == HidControllerLayouts.HandheldJoined ? HidControllerId.ControllerHandheld : controllerId); - HidControllerColorDesc SingleColorDesc = - HidControllerColorDesc.ColorDesc_ColorsNonexistent; + HidControllerColorDesc singleColorDesc = + HidControllerColorDesc.ColorDescColorsNonexistent; - HidControllerColorDesc SplitColorDesc = 0; + HidControllerColorDesc splitColorDesc = 0; - NpadColor SingleColorBody = NpadColor.Black; - NpadColor SingleColorButtons = NpadColor.Black; + NpadColor singleColorBody = NpadColor.Black; + NpadColor singleColorButtons = NpadColor.Black; - Device.Memory.WriteInt32(Offset + 0x04, IsHalf ? 1 : 0); + Device.Memory.WriteInt32(Offset + 0x04, _isHalf ? 1 : 0); - if (IsHalf) + if (_isHalf) { - Device.Memory.WriteInt32(Offset + 0x08, (int)SingleColorDesc); - Device.Memory.WriteInt32(Offset + 0x0c, (int)SingleColorBody); - Device.Memory.WriteInt32(Offset + 0x10, (int)SingleColorButtons); - Device.Memory.WriteInt32(Offset + 0x14, (int)SplitColorDesc); + Device.Memory.WriteInt32(Offset + 0x08, (int)singleColorDesc); + Device.Memory.WriteInt32(Offset + 0x0c, (int)singleColorBody); + Device.Memory.WriteInt32(Offset + 0x10, (int)singleColorButtons); + Device.Memory.WriteInt32(Offset + 0x14, (int)splitColorDesc); } else { - Device.Memory.WriteInt32(Offset + 0x18, (int)NpadBodyColors.Left); - Device.Memory.WriteInt32(Offset + 0x1c, (int)NpadButtonColors.Left); - Device.Memory.WriteInt32(Offset + 0x20, (int)NpadBodyColors.Right); - Device.Memory.WriteInt32(Offset + 0x24, (int)NpadButtonColors.Right); + Device.Memory.WriteInt32(Offset + 0x18, (int)_npadBodyColors.Left); + Device.Memory.WriteInt32(Offset + 0x1c, (int)_npadButtonColors.Left); + Device.Memory.WriteInt32(Offset + 0x20, (int)_npadBodyColors.Right); + Device.Memory.WriteInt32(Offset + 0x24, (int)_npadButtonColors.Right); } Connected = true; } public override void SendInput - (HidControllerButtons Buttons, - HidJoystickPosition LeftStick, - HidJoystickPosition RightStick) + (HidControllerButtons buttons, + HidJoystickPosition leftStick, + HidJoystickPosition rightStick) { - long ControllerOffset = WriteInput(Buttons, LeftStick, RightStick, CurrentLayout); + long controllerOffset = WriteInput(buttons, leftStick, rightStick, _currentLayout); - Device.Memory.WriteInt64(ControllerOffset + 0x28, - (Connected ? (uint)HidControllerConnState.Controller_State_Connected : 0) | - (CurrentLayout == HidControllerLayouts.Handheld_Joined ? (uint)HidControllerConnState.Controller_State_Wired : 0)); + Device.Memory.WriteInt64(controllerOffset + 0x28, + (Connected ? (uint)HidControllerConnState.ControllerStateConnected : 0) | + (_currentLayout == HidControllerLayouts.HandheldJoined ? (uint)HidControllerConnState.ControllerStateWired : 0)); } } } diff --git a/Ryujinx.HLE/Input/HidProController.cs b/Ryujinx.HLE/Input/HidProController.cs index 40c79fed..f08fb085 100644 --- a/Ryujinx.HLE/Input/HidProController.cs +++ b/Ryujinx.HLE/Input/HidProController.cs @@ -2,43 +2,43 @@ { public class HidProController : HidControllerBase { - bool Wired = false; + bool _wired = false; - public HidProController(Switch Device) : base(HidControllerType.ProController, Device) + public HidProController(Switch device) : base(HidControllerType.ProController, device) { - Wired = true; + _wired = true; } - public override void Connect(HidControllerId ControllerId) + public override void Connect(HidControllerId controllerId) { - base.Connect(ControllerId); + base.Connect(controllerId); - HidControllerColorDesc SingleColorDesc = - HidControllerColorDesc.ColorDesc_ColorsNonexistent; + HidControllerColorDesc singleColorDesc = + HidControllerColorDesc.ColorDescColorsNonexistent; - HidControllerColorDesc SplitColorDesc = 0; + HidControllerColorDesc splitColorDesc = 0; - NpadColor SingleColorBody = NpadColor.Black; - NpadColor SingleColorButtons = NpadColor.Black; + NpadColor singleColorBody = NpadColor.Black; + NpadColor singleColorButtons = NpadColor.Black; - Device.Memory.WriteInt32(Offset + 0x08, (int)SingleColorDesc); - Device.Memory.WriteInt32(Offset + 0x0c, (int)SingleColorBody); - Device.Memory.WriteInt32(Offset + 0x10, (int)SingleColorButtons); - Device.Memory.WriteInt32(Offset + 0x14, (int)SplitColorDesc); + Device.Memory.WriteInt32(Offset + 0x08, (int)singleColorDesc); + Device.Memory.WriteInt32(Offset + 0x0c, (int)singleColorBody); + Device.Memory.WriteInt32(Offset + 0x10, (int)singleColorButtons); + Device.Memory.WriteInt32(Offset + 0x14, (int)splitColorDesc); Connected = true; } public override void SendInput( - HidControllerButtons Buttons, - HidJoystickPosition LeftStick, - HidJoystickPosition RightStick) + HidControllerButtons buttons, + HidJoystickPosition leftStick, + HidJoystickPosition rightStick) { - long ControllerOffset = WriteInput(Buttons, LeftStick, RightStick, HidControllerLayouts.Pro_Controller); + long controllerOffset = WriteInput(buttons, leftStick, rightStick, HidControllerLayouts.ProController); - Device.Memory.WriteInt64(ControllerOffset + 0x28, - (Connected ? (uint)HidControllerConnState.Controller_State_Connected : 0) | - (Wired ? (uint)HidControllerConnState.Controller_State_Wired : 0)); + Device.Memory.WriteInt64(controllerOffset + 0x28, + (Connected ? (uint)HidControllerConnState.ControllerStateConnected : 0) | + (_wired ? (uint)HidControllerConnState.ControllerStateWired : 0)); } } } diff --git a/Ryujinx.HLE/Input/HidValues.cs b/Ryujinx.HLE/Input/HidValues.cs index 62bf0707..ae02bb42 100644 --- a/Ryujinx.HLE/Input/HidValues.cs +++ b/Ryujinx.HLE/Input/HidValues.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Ryujinx.HLE.Input +namespace Ryujinx.HLE.Input { public partial class Hid { diff --git a/Ryujinx.HLE/Input/IHidDevice.cs b/Ryujinx.HLE/Input/IHidDevice.cs index cc67b01a..0b07e767 100644 --- a/Ryujinx.HLE/Input/IHidDevice.cs +++ b/Ryujinx.HLE/Input/IHidDevice.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Ryujinx.HLE.Input +namespace Ryujinx.HLE.Input { interface IHidDevice { diff --git a/Ryujinx.HLE/Input/NpadColor.cs b/Ryujinx.HLE/Input/NpadColor.cs index b152b789..b15c45d8 100644 --- a/Ryujinx.HLE/Input/NpadColor.cs +++ b/Ryujinx.HLE/Input/NpadColor.cs @@ -4,20 +4,20 @@ namespace Ryujinx.HLE.Input { Black = 0, - Body_Grey = 0x828282, - Body_Neon_Blue = 0x0AB9E6, - Body_Neon_Red = 0xFF3C28, - Body_Neon_Yellow = 0xE6FF00, - Body_Neon_Pink = 0xFF3278, - Body_Neon_Green = 0x1EDC00, - Body_Red = 0xE10F00, + BodyGrey = 0x828282, + BodyNeonBlue = 0x0AB9E6, + BodyNeonRed = 0xFF3C28, + BodyNeonYellow = 0xE6FF00, + BodyNeonPink = 0xFF3278, + BodyNeonGreen = 0x1EDC00, + BodyRed = 0xE10F00, - Buttons_Grey = 0x0F0F0F, - Buttons_Neon_Blue = 0x001E1E, - Buttons_Neon_Red = 0x1E0A0A, - Buttons_Neon_Yellow = 0x142800, - Buttons_Neon_Pink = 0x28001E, - Buttons_Neon_Green = 0x002800, - Buttons_Red = 0x280A0A + ButtonsGrey = 0x0F0F0F, + ButtonsNeonBlue = 0x001E1E, + ButtonsNeonRed = 0x1E0A0A, + ButtonsNeonYellow = 0x142800, + ButtonsNeonPink = 0x28001E, + ButtonsNeonGreen = 0x002800, + ButtonsRed = 0x280A0A } } \ No newline at end of file diff --git a/Ryujinx.HLE/Loaders/Compression/BackwardsLz.cs b/Ryujinx.HLE/Loaders/Compression/BackwardsLz.cs index 43cc601f..166ae60a 100644 --- a/Ryujinx.HLE/Loaders/Compression/BackwardsLz.cs +++ b/Ryujinx.HLE/Loaders/Compression/BackwardsLz.cs @@ -7,22 +7,22 @@ namespace Ryujinx.HLE.Loaders.Compression { private class BackwardsReader { - private Stream BaseStream; + private Stream _baseStream; - public BackwardsReader(Stream BaseStream) + public BackwardsReader(Stream baseStream) { - this.BaseStream = BaseStream; + _baseStream = baseStream; } public byte ReadByte() { - BaseStream.Seek(-1, SeekOrigin.Current); + _baseStream.Seek(-1, SeekOrigin.Current); - byte Value = (byte)BaseStream.ReadByte(); + byte value = (byte)_baseStream.ReadByte(); - BaseStream.Seek(-1, SeekOrigin.Current); + _baseStream.Seek(-1, SeekOrigin.Current); - return Value; + return value; } public short ReadInt16() @@ -39,67 +39,67 @@ namespace Ryujinx.HLE.Loaders.Compression } } - public static byte[] Decompress(Stream Input, int DecompressedLength) + public static byte[] Decompress(Stream input, int decompressedLength) { - long End = Input.Position; + long end = input.Position; - BackwardsReader Reader = new BackwardsReader(Input); + BackwardsReader reader = new BackwardsReader(input); - int AdditionalDecLength = Reader.ReadInt32(); - int StartOffset = Reader.ReadInt32(); - int CompressedLength = Reader.ReadInt32(); + int additionalDecLength = reader.ReadInt32(); + int startOffset = reader.ReadInt32(); + int compressedLength = reader.ReadInt32(); - Input.Seek(12 - StartOffset, SeekOrigin.Current); + input.Seek(12 - startOffset, SeekOrigin.Current); - byte[] Dec = new byte[DecompressedLength]; + byte[] dec = new byte[decompressedLength]; - int DecompressedLengthUnpadded = CompressedLength + AdditionalDecLength; + int decompressedLengthUnpadded = compressedLength + additionalDecLength; - int DecompressionStart = DecompressedLength - DecompressedLengthUnpadded; + int decompressionStart = decompressedLength - decompressedLengthUnpadded; - int DecPos = Dec.Length; + int decPos = dec.Length; - byte Mask = 0; - byte Header = 0; + byte mask = 0; + byte header = 0; - while (DecPos > DecompressionStart) + while (decPos > decompressionStart) { - if ((Mask >>= 1) == 0) + if ((mask >>= 1) == 0) { - Header = Reader.ReadByte(); - Mask = 0x80; + header = reader.ReadByte(); + mask = 0x80; } - if ((Header & Mask) == 0) + if ((header & mask) == 0) { - Dec[--DecPos] = Reader.ReadByte(); + dec[--decPos] = reader.ReadByte(); } else { - ushort Pair = (ushort)Reader.ReadInt16(); + ushort pair = (ushort)reader.ReadInt16(); - int Length = (Pair >> 12) + 3; - int Position = (Pair & 0xfff) + 3; + int length = (pair >> 12) + 3; + int position = (pair & 0xfff) + 3; - DecPos -= Length; + decPos -= length; - if (Length <= Position) + if (length <= position) { - int SrcPos = DecPos + Position; + int srcPos = decPos + position; - Buffer.BlockCopy(Dec, SrcPos, Dec, DecPos, Length); + Buffer.BlockCopy(dec, srcPos, dec, decPos, length); } else { - for (int Offset = 0; Offset < Length; Offset++) + for (int offset = 0; offset < length; offset++) { - Dec[DecPos + Offset] = Dec[DecPos + Position + Offset]; + dec[decPos + offset] = dec[decPos + position + offset]; } } } } - return Dec; + return dec; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/Loaders/Compression/Lz4.cs b/Ryujinx.HLE/Loaders/Compression/Lz4.cs index cfb49551..e405b107 100644 --- a/Ryujinx.HLE/Loaders/Compression/Lz4.cs +++ b/Ryujinx.HLE/Loaders/Compression/Lz4.cs @@ -4,75 +4,75 @@ namespace Ryujinx.HLE.Loaders.Compression { static class Lz4 { - public static byte[] Decompress(byte[] Cmp, int DecLength) + public static byte[] Decompress(byte[] cmp, int decLength) { - byte[] Dec = new byte[DecLength]; + byte[] dec = new byte[decLength]; - int CmpPos = 0; - int DecPos = 0; + int cmpPos = 0; + int decPos = 0; - int GetLength(int Length) + int GetLength(int length) { - byte Sum; + byte sum; - if (Length == 0xf) + if (length == 0xf) { do { - Length += (Sum = Cmp[CmpPos++]); + length += (sum = cmp[cmpPos++]); } - while (Sum == 0xff); + while (sum == 0xff); } - return Length; + return length; } do { - byte Token = Cmp[CmpPos++]; + byte token = cmp[cmpPos++]; - int EncCount = (Token >> 0) & 0xf; - int LitCount = (Token >> 4) & 0xf; + int encCount = (token >> 0) & 0xf; + int litCount = (token >> 4) & 0xf; //Copy literal chunck - LitCount = GetLength(LitCount); + litCount = GetLength(litCount); - Buffer.BlockCopy(Cmp, CmpPos, Dec, DecPos, LitCount); + Buffer.BlockCopy(cmp, cmpPos, dec, decPos, litCount); - CmpPos += LitCount; - DecPos += LitCount; + cmpPos += litCount; + decPos += litCount; - if (CmpPos >= Cmp.Length) + if (cmpPos >= cmp.Length) { break; } //Copy compressed chunck - int Back = Cmp[CmpPos++] << 0 | - Cmp[CmpPos++] << 8; + int back = cmp[cmpPos++] << 0 | + cmp[cmpPos++] << 8; - EncCount = GetLength(EncCount) + 4; + encCount = GetLength(encCount) + 4; - int EncPos = DecPos - Back; + int encPos = decPos - back; - if (EncCount <= Back) + if (encCount <= back) { - Buffer.BlockCopy(Dec, EncPos, Dec, DecPos, EncCount); + Buffer.BlockCopy(dec, encPos, dec, decPos, encCount); - DecPos += EncCount; + decPos += encCount; } else { - while (EncCount-- > 0) + while (encCount-- > 0) { - Dec[DecPos++] = Dec[EncPos++]; + dec[decPos++] = dec[encPos++]; } } } - while (CmpPos < Cmp.Length && - DecPos < Dec.Length); + while (cmpPos < cmp.Length && + decPos < dec.Length); - return Dec; + return dec; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/Loaders/Elf/ElfDynamic.cs b/Ryujinx.HLE/Loaders/Elf/ElfDynamic.cs index fb0ea53e..f489e85a 100644 --- a/Ryujinx.HLE/Loaders/Elf/ElfDynamic.cs +++ b/Ryujinx.HLE/Loaders/Elf/ElfDynamic.cs @@ -6,10 +6,10 @@ namespace Ryujinx.HLE.Loaders.Elf public long Value { get; private set; } - public ElfDynamic(ElfDynamicTag Tag, long Value) + public ElfDynamic(ElfDynamicTag tag, long value) { - this.Tag = Tag; - this.Value = Value; + Tag = tag; + Value = value; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/Loaders/Elf/ElfDynamicTag.cs b/Ryujinx.HLE/Loaders/Elf/ElfDynamicTag.cs index 9d7ad72e..eb37d612 100644 --- a/Ryujinx.HLE/Loaders/Elf/ElfDynamicTag.cs +++ b/Ryujinx.HLE/Loaders/Elf/ElfDynamicTag.cs @@ -1,5 +1,8 @@ +using System.Diagnostics.CodeAnalysis; + namespace Ryujinx.HLE.Loaders.Elf { + [SuppressMessage("ReSharper", "InconsistentNaming")] enum ElfDynamicTag { DT_NULL = 0, diff --git a/Ryujinx.HLE/Loaders/Elf/ElfSymbol.cs b/Ryujinx.HLE/Loaders/Elf/ElfSymbol.cs index 3f3a2a79..b655816f 100644 --- a/Ryujinx.HLE/Loaders/Elf/ElfSymbol.cs +++ b/Ryujinx.HLE/Loaders/Elf/ElfSymbol.cs @@ -9,32 +9,32 @@ namespace Ryujinx.HLE.Loaders.Elf public ElfSymbolVisibility Visibility { get; private set; } public bool IsFuncOrObject => - Type == ElfSymbolType.STT_FUNC || - Type == ElfSymbolType.STT_OBJECT; + Type == ElfSymbolType.SttFunc || + Type == ElfSymbolType.SttObject; public bool IsGlobalOrWeak => - Binding == ElfSymbolBinding.STB_GLOBAL || - Binding == ElfSymbolBinding.STB_WEAK; + Binding == ElfSymbolBinding.StbGlobal || + Binding == ElfSymbolBinding.StbWeak; - public int SHIdx { get; private set; } + public int ShIdx { get; private set; } public long Value { get; private set; } public long Size { get; private set; } public ElfSymbol( - string Name, - int Info, - int Other, - int SHIdx, - long Value, - long Size) + string name, + int info, + int other, + int shIdx, + long value, + long size) { - this.Name = Name; - this.Type = (ElfSymbolType)(Info & 0xf); - this.Binding = (ElfSymbolBinding)(Info >> 4); - this.Visibility = (ElfSymbolVisibility)Other; - this.SHIdx = SHIdx; - this.Value = Value; - this.Size = Size; + Name = name; + Type = (ElfSymbolType)(info & 0xf); + Binding = (ElfSymbolBinding)(info >> 4); + Visibility = (ElfSymbolVisibility)other; + ShIdx = shIdx; + Value = value; + Size = size; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/Loaders/Elf/ElfSymbolBinding.cs b/Ryujinx.HLE/Loaders/Elf/ElfSymbolBinding.cs index 3c915311..92274fde 100644 --- a/Ryujinx.HLE/Loaders/Elf/ElfSymbolBinding.cs +++ b/Ryujinx.HLE/Loaders/Elf/ElfSymbolBinding.cs @@ -2,8 +2,8 @@ namespace Ryujinx.HLE.Loaders.Elf { enum ElfSymbolBinding { - STB_LOCAL = 0, - STB_GLOBAL = 1, - STB_WEAK = 2 + StbLocal = 0, + StbGlobal = 1, + StbWeak = 2 } } \ No newline at end of file diff --git a/Ryujinx.HLE/Loaders/Elf/ElfSymbolType.cs b/Ryujinx.HLE/Loaders/Elf/ElfSymbolType.cs index f22e6c45..4110d4c3 100644 --- a/Ryujinx.HLE/Loaders/Elf/ElfSymbolType.cs +++ b/Ryujinx.HLE/Loaders/Elf/ElfSymbolType.cs @@ -2,12 +2,12 @@ namespace Ryujinx.HLE.Loaders.Elf { enum ElfSymbolType { - STT_NOTYPE = 0, - STT_OBJECT = 1, - STT_FUNC = 2, - STT_SECTION = 3, - STT_FILE = 4, - STT_COMMON = 5, - STT_TLS = 6 + SttNoType = 0, + SttObject = 1, + SttFunc = 2, + SttSection = 3, + SttFile = 4, + SttCommon = 5, + SttTls = 6 } } \ No newline at end of file diff --git a/Ryujinx.HLE/Loaders/Elf/ElfSymbolVisibility.cs b/Ryujinx.HLE/Loaders/Elf/ElfSymbolVisibility.cs index 4bec50a3..f026fca8 100644 --- a/Ryujinx.HLE/Loaders/Elf/ElfSymbolVisibility.cs +++ b/Ryujinx.HLE/Loaders/Elf/ElfSymbolVisibility.cs @@ -2,9 +2,9 @@ namespace Ryujinx.HLE.Loaders.Elf { enum ElfSymbolVisibility { - STV_DEFAULT = 0, - STV_INTERNAL = 1, - STV_HIDDEN = 2, - STV_PROTECTED = 3 + StvDefault = 0, + StvInternal = 1, + StvHidden = 2, + StvProtected = 3 } } \ No newline at end of file diff --git a/Ryujinx.HLE/Loaders/Executables/IExecutable.cs b/Ryujinx.HLE/Loaders/Executables/IExecutable.cs index d3eefde6..440e8f5f 100644 --- a/Ryujinx.HLE/Loaders/Executables/IExecutable.cs +++ b/Ryujinx.HLE/Loaders/Executables/IExecutable.cs @@ -3,11 +3,11 @@ namespace Ryujinx.HLE.Loaders.Executables interface IExecutable { byte[] Text { get; } - byte[] RO { get; } + byte[] Ro { get; } byte[] Data { get; } int TextOffset { get; } - int ROOffset { get; } + int RoOffset { get; } int DataOffset { get; } int BssOffset { get; } int BssSize { get; } diff --git a/Ryujinx.HLE/Loaders/Executables/KernelInitialProcess.cs b/Ryujinx.HLE/Loaders/Executables/KernelInitialProcess.cs index 1395d56f..8b09bfcd 100644 --- a/Ryujinx.HLE/Loaders/Executables/KernelInitialProcess.cs +++ b/Ryujinx.HLE/Loaders/Executables/KernelInitialProcess.cs @@ -19,11 +19,11 @@ namespace Ryujinx.HLE.Loaders.Executables public bool IsService { get; private set; } public byte[] Text { get; private set; } - public byte[] RO { get; private set; } + public byte[] Ro { get; private set; } public byte[] Data { get; private set; } public int TextOffset { get; private set; } - public int ROOffset { get; private set; } + public int RoOffset { get; private set; } public int DataOffset { get; private set; } public int BssOffset { get; private set; } public int BssSize { get; private set; } @@ -40,110 +40,110 @@ namespace Ryujinx.HLE.Loaders.Executables public int Attribute { get; private set; } public SegmentHeader( - int Offset, - int DecompressedSize, - int CompressedSize, - int Attribute) + int offset, + int decompressedSize, + int compressedSize, + int attribute) { - this.Offset = Offset; - this.DecompressedSize = DecompressedSize; - this.CompressedSize = CompressedSize; - this.Attribute = Attribute; + Offset = offset; + DecompressedSize = decompressedSize; + CompressedSize = compressedSize; + Attribute = attribute; } } - public KernelInitialProcess(Stream Input) + public KernelInitialProcess(Stream input) { - BinaryReader Reader = new BinaryReader(Input); + BinaryReader reader = new BinaryReader(input); - string Magic = ReadString(Reader, 4); + string magic = ReadString(reader, 4); - if (Magic != "KIP1") + if (magic != "KIP1") { } - Name = ReadString(Reader, 12); + Name = ReadString(reader, 12); - TitleId = Reader.ReadInt64(); + TitleId = reader.ReadInt64(); - ProcessCategory = Reader.ReadInt32(); + ProcessCategory = reader.ReadInt32(); - MainThreadPriority = Reader.ReadByte(); - DefaultProcessorId = Reader.ReadByte(); + MainThreadPriority = reader.ReadByte(); + DefaultProcessorId = reader.ReadByte(); - byte Reserved = Reader.ReadByte(); - byte Flags = Reader.ReadByte(); + byte reserved = reader.ReadByte(); + byte flags = reader.ReadByte(); - Is64Bits = (Flags & 0x08) != 0; - Addr39Bits = (Flags & 0x10) != 0; - IsService = (Flags & 0x20) != 0; + Is64Bits = (flags & 0x08) != 0; + Addr39Bits = (flags & 0x10) != 0; + IsService = (flags & 0x20) != 0; - SegmentHeader[] Segments = new SegmentHeader[6]; + SegmentHeader[] segments = new SegmentHeader[6]; - for (int Index = 0; Index < Segments.Length; Index++) + for (int index = 0; index < segments.Length; index++) { - Segments[Index] = new SegmentHeader( - Reader.ReadInt32(), - Reader.ReadInt32(), - Reader.ReadInt32(), - Reader.ReadInt32()); + segments[index] = new SegmentHeader( + reader.ReadInt32(), + reader.ReadInt32(), + reader.ReadInt32(), + reader.ReadInt32()); } - TextOffset = Segments[0].Offset; - ROOffset = Segments[1].Offset; - DataOffset = Segments[2].Offset; - BssOffset = Segments[3].Offset; - BssSize = Segments[3].DecompressedSize; + TextOffset = segments[0].Offset; + RoOffset = segments[1].Offset; + DataOffset = segments[2].Offset; + BssOffset = segments[3].Offset; + BssSize = segments[3].DecompressedSize; - MainThreadStackSize = Segments[1].Attribute; + MainThreadStackSize = segments[1].Attribute; Capabilities = new int[8]; - for (int Index = 0; Index < Capabilities.Length; Index++) + for (int index = 0; index < Capabilities.Length; index++) { - Capabilities[Index] = Reader.ReadInt32(); + Capabilities[index] = reader.ReadInt32(); } - Input.Seek(0x100, SeekOrigin.Begin); + input.Seek(0x100, SeekOrigin.Begin); - Text = ReadSegment(Segments[0], Input); - RO = ReadSegment(Segments[1], Input); - Data = ReadSegment(Segments[2], Input); + Text = ReadSegment(segments[0], input); + Ro = ReadSegment(segments[1], input); + Data = ReadSegment(segments[2], input); } - private byte[] ReadSegment(SegmentHeader Header, Stream Input) + private byte[] ReadSegment(SegmentHeader header, Stream input) { - long End = Input.Position + Header.CompressedSize; + long end = input.Position + header.CompressedSize; - Input.Seek(End, SeekOrigin.Begin); + input.Seek(end, SeekOrigin.Begin); - byte[] Data = BackwardsLz.Decompress(Input, Header.DecompressedSize); + byte[] data = BackwardsLz.Decompress(input, header.DecompressedSize); - Input.Seek(End, SeekOrigin.Begin); + input.Seek(end, SeekOrigin.Begin); - return Data; + return data; } - private static string ReadString(BinaryReader Reader, int MaxSize) + private static string ReadString(BinaryReader reader, int maxSize) { - string Value = string.Empty; + string value = string.Empty; - for (int Index = 0; Index < MaxSize; Index++) + for (int index = 0; index < maxSize; index++) { - char Chr = (char)Reader.ReadByte(); + char chr = (char)reader.ReadByte(); - if (Chr == '\0') + if (chr == '\0') { - Reader.BaseStream.Seek(MaxSize - Index - 1, SeekOrigin.Current); + reader.BaseStream.Seek(maxSize - index - 1, SeekOrigin.Current); break; } - Value += Chr; + value += chr; } - return Value; + return value; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/Loaders/Executables/NxRelocatableObject.cs b/Ryujinx.HLE/Loaders/Executables/NxRelocatableObject.cs index 20de5b5d..eb3ca94a 100644 --- a/Ryujinx.HLE/Loaders/Executables/NxRelocatableObject.cs +++ b/Ryujinx.HLE/Loaders/Executables/NxRelocatableObject.cs @@ -5,12 +5,12 @@ namespace Ryujinx.HLE.Loaders.Executables class NxRelocatableObject : IExecutable { public byte[] Text { get; private set; } - public byte[] RO { get; private set; } + public byte[] Ro { get; private set; } public byte[] Data { get; private set; } public int Mod0Offset { get; private set; } public int TextOffset { get; private set; } - public int ROOffset { get; private set; } + public int RoOffset { get; private set; } public int DataOffset { get; private set; } public int BssSize { get; private set; } @@ -19,46 +19,46 @@ namespace Ryujinx.HLE.Loaders.Executables public ulong SourceAddress { get; private set; } public ulong BssAddress { get; private set; } - public NxRelocatableObject(Stream Input, ulong SourceAddress = 0, ulong BssAddress = 0) + public NxRelocatableObject(Stream input, ulong sourceAddress = 0, ulong bssAddress = 0) { - this.SourceAddress = SourceAddress; - this.BssAddress = BssAddress; + SourceAddress = sourceAddress; + BssAddress = bssAddress; - BinaryReader Reader = new BinaryReader(Input); + BinaryReader reader = new BinaryReader(input); - Input.Seek(4, SeekOrigin.Begin); + input.Seek(4, SeekOrigin.Begin); - int Mod0Offset = Reader.ReadInt32(); - int Padding8 = Reader.ReadInt32(); - int Paddingc = Reader.ReadInt32(); - int NroMagic = Reader.ReadInt32(); - int Unknown14 = Reader.ReadInt32(); - int FileSize = Reader.ReadInt32(); - int Unknown1c = Reader.ReadInt32(); - int TextOffset = Reader.ReadInt32(); - int TextSize = Reader.ReadInt32(); - int ROOffset = Reader.ReadInt32(); - int ROSize = Reader.ReadInt32(); - int DataOffset = Reader.ReadInt32(); - int DataSize = Reader.ReadInt32(); - int BssSize = Reader.ReadInt32(); + int mod0Offset = reader.ReadInt32(); + int padding8 = reader.ReadInt32(); + int paddingC = reader.ReadInt32(); + int nroMagic = reader.ReadInt32(); + int unknown14 = reader.ReadInt32(); + int fileSize = reader.ReadInt32(); + int unknown1C = reader.ReadInt32(); + int textOffset = reader.ReadInt32(); + int textSize = reader.ReadInt32(); + int roOffset = reader.ReadInt32(); + int roSize = reader.ReadInt32(); + int dataOffset = reader.ReadInt32(); + int dataSize = reader.ReadInt32(); + int bssSize = reader.ReadInt32(); - this.Mod0Offset = Mod0Offset; - this.TextOffset = TextOffset; - this.ROOffset = ROOffset; - this.DataOffset = DataOffset; - this.BssSize = BssSize; + Mod0Offset = mod0Offset; + TextOffset = textOffset; + RoOffset = roOffset; + DataOffset = dataOffset; + BssSize = bssSize; - byte[] Read(long Position, int Size) + byte[] Read(long position, int size) { - Input.Seek(Position, SeekOrigin.Begin); + input.Seek(position, SeekOrigin.Begin); - return Reader.ReadBytes(Size); + return reader.ReadBytes(size); } - Text = Read(TextOffset, TextSize); - RO = Read(ROOffset, ROSize); - Data = Read(DataOffset, DataSize); + Text = Read(textOffset, textSize); + Ro = Read(roOffset, roSize); + Data = Read(dataOffset, dataSize); } } } \ No newline at end of file diff --git a/Ryujinx.HLE/Loaders/Executables/NxStaticObject.cs b/Ryujinx.HLE/Loaders/Executables/NxStaticObject.cs index 9fecb650..c0b2e947 100644 --- a/Ryujinx.HLE/Loaders/Executables/NxStaticObject.cs +++ b/Ryujinx.HLE/Loaders/Executables/NxStaticObject.cs @@ -7,11 +7,11 @@ namespace Ryujinx.HLE.Loaders.Executables class NxStaticObject : IExecutable { public byte[] Text { get; private set; } - public byte[] RO { get; private set; } + public byte[] Ro { get; private set; } public byte[] Data { get; private set; } public int TextOffset { get; private set; } - public int ROOffset { get; private set; } + public int RoOffset { get; private set; } public int DataOffset { get; private set; } public int BssSize { get; private set; } @@ -21,88 +21,88 @@ namespace Ryujinx.HLE.Loaders.Executables private enum NsoFlags { IsTextCompressed = 1 << 0, - IsROCompressed = 1 << 1, + IsRoCompressed = 1 << 1, IsDataCompressed = 1 << 2, HasTextHash = 1 << 3, - HasROHash = 1 << 4, + HasRoHash = 1 << 4, HasDataHash = 1 << 5 } - public NxStaticObject(Stream Input) + public NxStaticObject(Stream input) { - BinaryReader Reader = new BinaryReader(Input); + BinaryReader reader = new BinaryReader(input); - Input.Seek(0, SeekOrigin.Begin); + input.Seek(0, SeekOrigin.Begin); - int NsoMagic = Reader.ReadInt32(); - int Version = Reader.ReadInt32(); - int Reserved = Reader.ReadInt32(); - int FlagsMsk = Reader.ReadInt32(); - int TextOffset = Reader.ReadInt32(); - int TextMemOffset = Reader.ReadInt32(); - int TextDecSize = Reader.ReadInt32(); - int ModNameOffset = Reader.ReadInt32(); - int ROOffset = Reader.ReadInt32(); - int ROMemOffset = Reader.ReadInt32(); - int RODecSize = Reader.ReadInt32(); - int ModNameSize = Reader.ReadInt32(); - int DataOffset = Reader.ReadInt32(); - int DataMemOffset = Reader.ReadInt32(); - int DataDecSize = Reader.ReadInt32(); - int BssSize = Reader.ReadInt32(); + int nsoMagic = reader.ReadInt32(); + int version = reader.ReadInt32(); + int reserved = reader.ReadInt32(); + int flagsMsk = reader.ReadInt32(); + int textOffset = reader.ReadInt32(); + int textMemOffset = reader.ReadInt32(); + int textDecSize = reader.ReadInt32(); + int modNameOffset = reader.ReadInt32(); + int roOffset = reader.ReadInt32(); + int roMemOffset = reader.ReadInt32(); + int roDecSize = reader.ReadInt32(); + int modNameSize = reader.ReadInt32(); + int dataOffset = reader.ReadInt32(); + int dataMemOffset = reader.ReadInt32(); + int dataDecSize = reader.ReadInt32(); + int bssSize = reader.ReadInt32(); - byte[] BuildId = Reader.ReadBytes(0x20); + byte[] buildId = reader.ReadBytes(0x20); - int TextSize = Reader.ReadInt32(); - int ROSize = Reader.ReadInt32(); - int DataSize = Reader.ReadInt32(); + int textSize = reader.ReadInt32(); + int roSize = reader.ReadInt32(); + int dataSize = reader.ReadInt32(); - Input.Seek(0x24, SeekOrigin.Current); + input.Seek(0x24, SeekOrigin.Current); - int DynStrOffset = Reader.ReadInt32(); - int DynStrSize = Reader.ReadInt32(); - int DynSymOffset = Reader.ReadInt32(); - int DynSymSize = Reader.ReadInt32(); + int dynStrOffset = reader.ReadInt32(); + int dynStrSize = reader.ReadInt32(); + int dynSymOffset = reader.ReadInt32(); + int dynSymSize = reader.ReadInt32(); - byte[] TextHash = Reader.ReadBytes(0x20); - byte[] ROHash = Reader.ReadBytes(0x20); - byte[] DataHash = Reader.ReadBytes(0x20); + byte[] textHash = reader.ReadBytes(0x20); + byte[] roHash = reader.ReadBytes(0x20); + byte[] dataHash = reader.ReadBytes(0x20); - NsoFlags Flags = (NsoFlags)FlagsMsk; + NsoFlags flags = (NsoFlags)flagsMsk; - this.TextOffset = TextMemOffset; - this.ROOffset = ROMemOffset; - this.DataOffset = DataMemOffset; - this.BssSize = BssSize; + TextOffset = textMemOffset; + RoOffset = roMemOffset; + DataOffset = dataMemOffset; + BssSize = bssSize; //Text segment - Input.Seek(TextOffset, SeekOrigin.Begin); + input.Seek(textOffset, SeekOrigin.Begin); - Text = Reader.ReadBytes(TextSize); + Text = reader.ReadBytes(textSize); - if (Flags.HasFlag(NsoFlags.IsTextCompressed)) + if (flags.HasFlag(NsoFlags.IsTextCompressed)) { - Text = Lz4.Decompress(Text, TextDecSize); + Text = Lz4.Decompress(Text, textDecSize); } //Read-only data segment - Input.Seek(ROOffset, SeekOrigin.Begin); + input.Seek(roOffset, SeekOrigin.Begin); - RO = Reader.ReadBytes(ROSize); + Ro = reader.ReadBytes(roSize); - if (Flags.HasFlag(NsoFlags.IsROCompressed)) + if (flags.HasFlag(NsoFlags.IsRoCompressed)) { - RO = Lz4.Decompress(RO, RODecSize); + Ro = Lz4.Decompress(Ro, roDecSize); } //Data segment - Input.Seek(DataOffset, SeekOrigin.Begin); + input.Seek(dataOffset, SeekOrigin.Begin); - Data = Reader.ReadBytes(DataSize); + Data = reader.ReadBytes(dataSize); - if (Flags.HasFlag(NsoFlags.IsDataCompressed)) + if (flags.HasFlag(NsoFlags.IsDataCompressed)) { - Data = Lz4.Decompress(Data, DataDecSize); + Data = Lz4.Decompress(Data, dataDecSize); } } } diff --git a/Ryujinx.HLE/Loaders/Npdm/ACI0.cs b/Ryujinx.HLE/Loaders/Npdm/ACI0.cs index 4bec93e4..55f3319d 100644 --- a/Ryujinx.HLE/Loaders/Npdm/ACI0.cs +++ b/Ryujinx.HLE/Loaders/Npdm/ACI0.cs @@ -3,9 +3,9 @@ using System.IO; namespace Ryujinx.HLE.Loaders.Npdm { - class ACI0 + class Aci0 { - private const int ACI0Magic = 'A' << 0 | 'C' << 8 | 'I' << 16 | '0' << 24; + private const int Aci0Magic = 'A' << 0 | 'C' << 8 | 'I' << 16 | '0' << 24; public long TitleId { get; private set; } @@ -15,39 +15,39 @@ namespace Ryujinx.HLE.Loaders.Npdm public ServiceAccessControl ServiceAccessControl { get; private set; } public KernelAccessControl KernelAccessControl { get; private set; } - public ACI0(Stream Stream, int Offset) + public Aci0(Stream stream, int offset) { - Stream.Seek(Offset, SeekOrigin.Begin); + stream.Seek(offset, SeekOrigin.Begin); - BinaryReader Reader = new BinaryReader(Stream); + BinaryReader reader = new BinaryReader(stream); - if (Reader.ReadInt32() != ACI0Magic) + if (reader.ReadInt32() != Aci0Magic) { throw new InvalidNpdmException("ACI0 Stream doesn't contain ACI0 section!"); } - Stream.Seek(0xc, SeekOrigin.Current); + stream.Seek(0xc, SeekOrigin.Current); - TitleId = Reader.ReadInt64(); + TitleId = reader.ReadInt64(); //Reserved. - Stream.Seek(8, SeekOrigin.Current); + stream.Seek(8, SeekOrigin.Current); - int FsAccessHeaderOffset = Reader.ReadInt32(); - int FsAccessHeaderSize = Reader.ReadInt32(); - int ServiceAccessControlOffset = Reader.ReadInt32(); - int ServiceAccessControlSize = Reader.ReadInt32(); - int KernelAccessControlOffset = Reader.ReadInt32(); - int KernelAccessControlSize = Reader.ReadInt32(); + int fsAccessHeaderOffset = reader.ReadInt32(); + int fsAccessHeaderSize = reader.ReadInt32(); + int serviceAccessControlOffset = reader.ReadInt32(); + int serviceAccessControlSize = reader.ReadInt32(); + int kernelAccessControlOffset = reader.ReadInt32(); + int kernelAccessControlSize = reader.ReadInt32(); - FsAccessHeader FsAccessHeader = new FsAccessHeader(Stream, Offset + FsAccessHeaderOffset, FsAccessHeaderSize); + FsAccessHeader fsAccessHeader = new FsAccessHeader(stream, offset + fsAccessHeaderOffset, fsAccessHeaderSize); - FsVersion = FsAccessHeader.Version; - FsPermissionsBitmask = FsAccessHeader.PermissionsBitmask; + FsVersion = fsAccessHeader.Version; + FsPermissionsBitmask = fsAccessHeader.PermissionsBitmask; - ServiceAccessControl = new ServiceAccessControl(Stream, Offset + ServiceAccessControlOffset, ServiceAccessControlSize); + ServiceAccessControl = new ServiceAccessControl(stream, offset + serviceAccessControlOffset, serviceAccessControlSize); - KernelAccessControl = new KernelAccessControl(Stream, Offset + KernelAccessControlOffset, KernelAccessControlSize); + KernelAccessControl = new KernelAccessControl(stream, offset + kernelAccessControlOffset, kernelAccessControlSize); } } } diff --git a/Ryujinx.HLE/Loaders/Npdm/ACID.cs b/Ryujinx.HLE/Loaders/Npdm/ACID.cs index 9206ee7b..57c5cf3e 100644 --- a/Ryujinx.HLE/Loaders/Npdm/ACID.cs +++ b/Ryujinx.HLE/Loaders/Npdm/ACID.cs @@ -3,12 +3,12 @@ using System.IO; namespace Ryujinx.HLE.Loaders.Npdm { - class ACID + class Acid { - private const int ACIDMagic = 'A' << 0 | 'C' << 8 | 'I' << 16 | 'D' << 24; + private const int AcidMagic = 'A' << 0 | 'C' << 8 | 'I' << 16 | 'D' << 24; - public byte[] RSA2048Signature { get; private set; } - public byte[] RSA2048Modulus { get; private set; } + public byte[] Rsa2048Signature { get; private set; } + public byte[] Rsa2048Modulus { get; private set; } public int Unknown1 { get; private set; } public int Flags { get; private set; } @@ -19,43 +19,43 @@ namespace Ryujinx.HLE.Loaders.Npdm public ServiceAccessControl ServiceAccessControl { get; private set; } public KernelAccessControl KernelAccessControl { get; private set; } - public ACID(Stream Stream, int Offset) + public Acid(Stream stream, int offset) { - Stream.Seek(Offset, SeekOrigin.Begin); + stream.Seek(offset, SeekOrigin.Begin); - BinaryReader Reader = new BinaryReader(Stream); + BinaryReader reader = new BinaryReader(stream); - RSA2048Signature = Reader.ReadBytes(0x100); - RSA2048Modulus = Reader.ReadBytes(0x100); + Rsa2048Signature = reader.ReadBytes(0x100); + Rsa2048Modulus = reader.ReadBytes(0x100); - if (Reader.ReadInt32() != ACIDMagic) + if (reader.ReadInt32() != AcidMagic) { throw new InvalidNpdmException("ACID Stream doesn't contain ACID section!"); } //Size field used with the above signature (?). - Unknown1 = Reader.ReadInt32(); + Unknown1 = reader.ReadInt32(); - Reader.ReadInt32(); + reader.ReadInt32(); //Bit0 must be 1 on retail, on devunit 0 is also allowed. Bit1 is unknown. - Flags = Reader.ReadInt32(); + Flags = reader.ReadInt32(); - TitleIdRangeMin = Reader.ReadInt64(); - TitleIdRangeMax = Reader.ReadInt64(); + TitleIdRangeMin = reader.ReadInt64(); + TitleIdRangeMax = reader.ReadInt64(); - int FsAccessControlOffset = Reader.ReadInt32(); - int FsAccessControlSize = Reader.ReadInt32(); - int ServiceAccessControlOffset = Reader.ReadInt32(); - int ServiceAccessControlSize = Reader.ReadInt32(); - int KernelAccessControlOffset = Reader.ReadInt32(); - int KernelAccessControlSize = Reader.ReadInt32(); + int fsAccessControlOffset = reader.ReadInt32(); + int fsAccessControlSize = reader.ReadInt32(); + int serviceAccessControlOffset = reader.ReadInt32(); + int serviceAccessControlSize = reader.ReadInt32(); + int kernelAccessControlOffset = reader.ReadInt32(); + int kernelAccessControlSize = reader.ReadInt32(); - FsAccessControl = new FsAccessControl(Stream, Offset + FsAccessControlOffset, FsAccessControlSize); + FsAccessControl = new FsAccessControl(stream, offset + fsAccessControlOffset, fsAccessControlSize); - ServiceAccessControl = new ServiceAccessControl(Stream, Offset + ServiceAccessControlOffset, ServiceAccessControlSize); + ServiceAccessControl = new ServiceAccessControl(stream, offset + serviceAccessControlOffset, serviceAccessControlSize); - KernelAccessControl = new KernelAccessControl(Stream, Offset + KernelAccessControlOffset, KernelAccessControlSize); + KernelAccessControl = new KernelAccessControl(stream, offset + kernelAccessControlOffset, kernelAccessControlSize); } } } diff --git a/Ryujinx.HLE/Loaders/Npdm/FsAccessControl.cs b/Ryujinx.HLE/Loaders/Npdm/FsAccessControl.cs index 00faf321..3359435d 100644 --- a/Ryujinx.HLE/Loaders/Npdm/FsAccessControl.cs +++ b/Ryujinx.HLE/Loaders/Npdm/FsAccessControl.cs @@ -11,18 +11,18 @@ namespace Ryujinx.HLE.Loaders.Npdm public int Unknown3 { get; private set; } public int Unknown4 { get; private set; } - public FsAccessControl(Stream Stream, int Offset, int Size) + public FsAccessControl(Stream stream, int offset, int size) { - Stream.Seek(Offset, SeekOrigin.Begin); + stream.Seek(offset, SeekOrigin.Begin); - BinaryReader Reader = new BinaryReader(Stream); + BinaryReader reader = new BinaryReader(stream); - Version = Reader.ReadInt32(); - PermissionsBitmask = Reader.ReadUInt64(); - Unknown1 = Reader.ReadInt32(); - Unknown2 = Reader.ReadInt32(); - Unknown3 = Reader.ReadInt32(); - Unknown4 = Reader.ReadInt32(); + Version = reader.ReadInt32(); + PermissionsBitmask = reader.ReadUInt64(); + Unknown1 = reader.ReadInt32(); + Unknown2 = reader.ReadInt32(); + Unknown3 = reader.ReadInt32(); + Unknown4 = reader.ReadInt32(); } } } diff --git a/Ryujinx.HLE/Loaders/Npdm/FsAccessHeader.cs b/Ryujinx.HLE/Loaders/Npdm/FsAccessHeader.cs index 50e82309..564b8dc3 100644 --- a/Ryujinx.HLE/Loaders/Npdm/FsAccessHeader.cs +++ b/Ryujinx.HLE/Loaders/Npdm/FsAccessHeader.cs @@ -9,26 +9,26 @@ namespace Ryujinx.HLE.Loaders.Npdm public int Version { get; private set; } public ulong PermissionsBitmask { get; private set; } - public FsAccessHeader(Stream Stream, int Offset, int Size) + public FsAccessHeader(Stream stream, int offset, int size) { - Stream.Seek(Offset, SeekOrigin.Begin); + stream.Seek(offset, SeekOrigin.Begin); - BinaryReader Reader = new BinaryReader(Stream); + BinaryReader reader = new BinaryReader(stream); - Version = Reader.ReadInt32(); - PermissionsBitmask = Reader.ReadUInt64(); + Version = reader.ReadInt32(); + PermissionsBitmask = reader.ReadUInt64(); - int DataSize = Reader.ReadInt32(); + int dataSize = reader.ReadInt32(); - if (DataSize != 0x1c) + if (dataSize != 0x1c) { throw new InvalidNpdmException("FsAccessHeader is corrupted!"); } - int ContentOwnerIdSize = Reader.ReadInt32(); - int DataAndContentOwnerIdSize = Reader.ReadInt32(); + int contentOwnerIdSize = reader.ReadInt32(); + int dataAndContentOwnerIdSize = reader.ReadInt32(); - if (DataAndContentOwnerIdSize != 0x1c) + if (dataAndContentOwnerIdSize != 0x1c) { throw new NotImplementedException("ContentOwnerId section is not implemented!"); } diff --git a/Ryujinx.HLE/Loaders/Npdm/KernelAccessControl.cs b/Ryujinx.HLE/Loaders/Npdm/KernelAccessControl.cs index 611eda39..d8e40d0b 100644 --- a/Ryujinx.HLE/Loaders/Npdm/KernelAccessControl.cs +++ b/Ryujinx.HLE/Loaders/Npdm/KernelAccessControl.cs @@ -6,17 +6,17 @@ namespace Ryujinx.HLE.Loaders.Npdm { public int[] Capabilities { get; private set; } - public KernelAccessControl(Stream Stream, int Offset, int Size) + public KernelAccessControl(Stream stream, int offset, int size) { - Stream.Seek(Offset, SeekOrigin.Begin); + stream.Seek(offset, SeekOrigin.Begin); - Capabilities = new int[Size / 4]; + Capabilities = new int[size / 4]; - BinaryReader Reader = new BinaryReader(Stream); + BinaryReader reader = new BinaryReader(stream); - for (int Index = 0; Index < Capabilities.Length; Index++) + for (int index = 0; index < Capabilities.Length; index++) { - Capabilities[Index] = Reader.ReadInt32(); + Capabilities[index] = reader.ReadInt32(); } } } diff --git a/Ryujinx.HLE/Loaders/Npdm/Npdm.cs b/Ryujinx.HLE/Loaders/Npdm/Npdm.cs index 6d74668a..cef2673e 100644 --- a/Ryujinx.HLE/Loaders/Npdm/Npdm.cs +++ b/Ryujinx.HLE/Loaders/Npdm/Npdm.cs @@ -21,52 +21,52 @@ namespace Ryujinx.HLE.Loaders.Npdm public string TitleName { get; private set; } public byte[] ProductCode { get; private set; } - public ACI0 ACI0 { get; private set; } - public ACID ACID { get; private set; } + public Aci0 Aci0 { get; private set; } + public Acid Acid { get; private set; } - public Npdm(Stream Stream) + public Npdm(Stream stream) { - BinaryReader Reader = new BinaryReader(Stream); + BinaryReader reader = new BinaryReader(stream); - if (Reader.ReadInt32() != MetaMagic) + if (reader.ReadInt32() != MetaMagic) { throw new InvalidNpdmException("NPDM Stream doesn't contain NPDM file!"); } - Reader.ReadInt64(); + reader.ReadInt64(); - MmuFlags = Reader.ReadByte(); + MmuFlags = reader.ReadByte(); Is64Bits = (MmuFlags & 1) != 0; - Reader.ReadByte(); + reader.ReadByte(); - MainThreadPriority = Reader.ReadByte(); - DefaultCpuId = Reader.ReadByte(); + MainThreadPriority = reader.ReadByte(); + DefaultCpuId = reader.ReadByte(); - Reader.ReadInt32(); + reader.ReadInt32(); - PersonalMmHeapSize = Reader.ReadInt32(); + PersonalMmHeapSize = reader.ReadInt32(); - ProcessCategory = Reader.ReadInt32(); + ProcessCategory = reader.ReadInt32(); - MainThreadStackSize = Reader.ReadInt32(); + MainThreadStackSize = reader.ReadInt32(); - byte[] TempTitleName = Reader.ReadBytes(0x10); + byte[] tempTitleName = reader.ReadBytes(0x10); - TitleName = Encoding.UTF8.GetString(TempTitleName, 0, TempTitleName.Length).Trim('\0'); + TitleName = Encoding.UTF8.GetString(tempTitleName, 0, tempTitleName.Length).Trim('\0'); - ProductCode = Reader.ReadBytes(0x10); + ProductCode = reader.ReadBytes(0x10); - Stream.Seek(0x30, SeekOrigin.Current); + stream.Seek(0x30, SeekOrigin.Current); - int ACI0Offset = Reader.ReadInt32(); - int ACI0Size = Reader.ReadInt32(); - int ACIDOffset = Reader.ReadInt32(); - int ACIDSize = Reader.ReadInt32(); + int aci0Offset = reader.ReadInt32(); + int aci0Size = reader.ReadInt32(); + int acidOffset = reader.ReadInt32(); + int acidSize = reader.ReadInt32(); - ACI0 = new ACI0(Stream, ACI0Offset); - ACID = new ACID(Stream, ACIDOffset); + Aci0 = new Aci0(stream, aci0Offset); + Acid = new Acid(stream, acidOffset); } } } diff --git a/Ryujinx.HLE/Loaders/Npdm/ServiceAccessControl.cs b/Ryujinx.HLE/Loaders/Npdm/ServiceAccessControl.cs index 707be603..368dbae7 100644 --- a/Ryujinx.HLE/Loaders/Npdm/ServiceAccessControl.cs +++ b/Ryujinx.HLE/Loaders/Npdm/ServiceAccessControl.cs @@ -9,34 +9,34 @@ namespace Ryujinx.HLE.Loaders.Npdm { public IReadOnlyDictionary Services { get; private set; } - public ServiceAccessControl(Stream Stream, int Offset, int Size) + public ServiceAccessControl(Stream stream, int offset, int size) { - Stream.Seek(Offset, SeekOrigin.Begin); + stream.Seek(offset, SeekOrigin.Begin); - BinaryReader Reader = new BinaryReader(Stream); + BinaryReader reader = new BinaryReader(stream); - int ByteReaded = 0; + int byteReaded = 0; - Dictionary Services = new Dictionary(); + Dictionary services = new Dictionary(); - while (ByteReaded != Size) + while (byteReaded != size) { - byte ControlByte = Reader.ReadByte(); + byte controlByte = reader.ReadByte(); - if (ControlByte == 0) + if (controlByte == 0) { break; } - int Length = (ControlByte & 0x07) + 1; - bool RegisterAllowed = (ControlByte & 0x80) != 0; + int length = (controlByte & 0x07) + 1; + bool registerAllowed = (controlByte & 0x80) != 0; - Services.Add(Encoding.ASCII.GetString(Reader.ReadBytes(Length), 0, Length), RegisterAllowed); + services.Add(Encoding.ASCII.GetString(reader.ReadBytes(length), 0, length), registerAllowed); - ByteReaded += Length + 1; + byteReaded += length + 1; } - this.Services = new ReadOnlyDictionary(Services); + Services = new ReadOnlyDictionary(services); } } } diff --git a/Ryujinx.HLE/PerformanceStatistics.cs b/Ryujinx.HLE/PerformanceStatistics.cs index 2dabd9a0..408e5d72 100644 --- a/Ryujinx.HLE/PerformanceStatistics.cs +++ b/Ryujinx.HLE/PerformanceStatistics.cs @@ -10,43 +10,43 @@ namespace Ryujinx.HLE private const int FrameTypeSystem = 0; private const int FrameTypeGame = 1; - private double[] AverageFrameRate; - private double[] AccumulatedFrameTime; - private double[] PreviousFrameTime; + private double[] _averageFrameRate; + private double[] _accumulatedFrameTime; + private double[] _previousFrameTime; - private long[] FramesRendered; + private long[] _framesRendered; - private object[] FrameLock; + private object[] _frameLock; - private double TicksToSeconds; + private double _ticksToSeconds; - private Stopwatch ExecutionTime; + private Stopwatch _executionTime; - private Timer ResetTimer; + private Timer _resetTimer; public PerformanceStatistics() { - AverageFrameRate = new double[2]; - AccumulatedFrameTime = new double[2]; - PreviousFrameTime = new double[2]; + _averageFrameRate = new double[2]; + _accumulatedFrameTime = new double[2]; + _previousFrameTime = new double[2]; - FramesRendered = new long[2]; + _framesRendered = new long[2]; - FrameLock = new object[] { new object(), new object() }; + _frameLock = new object[] { new object(), new object() }; - ExecutionTime = new Stopwatch(); + _executionTime = new Stopwatch(); - ExecutionTime.Start(); + _executionTime.Start(); - ResetTimer = new Timer(1000); + _resetTimer = new Timer(1000); - ResetTimer.Elapsed += ResetTimerElapsed; + _resetTimer.Elapsed += ResetTimerElapsed; - ResetTimer.AutoReset = true; + _resetTimer.AutoReset = true; - ResetTimer.Start(); + _resetTimer.Start(); - TicksToSeconds = 1.0 / Stopwatch.Frequency; + _ticksToSeconds = 1.0 / Stopwatch.Frequency; } private void ResetTimerElapsed(object sender, ElapsedEventArgs e) @@ -55,28 +55,28 @@ namespace Ryujinx.HLE CalculateAverageFrameRate(FrameTypeGame); } - private void CalculateAverageFrameRate(int FrameType) + private void CalculateAverageFrameRate(int frameType) { - double FrameRate = 0; + double frameRate = 0; - if (AccumulatedFrameTime[FrameType] > 0) + if (_accumulatedFrameTime[frameType] > 0) { - FrameRate = FramesRendered[FrameType] / AccumulatedFrameTime[FrameType]; + frameRate = _framesRendered[frameType] / _accumulatedFrameTime[frameType]; } - lock (FrameLock[FrameType]) + lock (_frameLock[frameType]) { - AverageFrameRate[FrameType] = LinearInterpolate(AverageFrameRate[FrameType], FrameRate); + _averageFrameRate[frameType] = LinearInterpolate(_averageFrameRate[frameType], frameRate); - FramesRendered[FrameType] = 0; + _framesRendered[frameType] = 0; - AccumulatedFrameTime[FrameType] = 0; + _accumulatedFrameTime[frameType] = 0; } } - private double LinearInterpolate(double Old, double New) + private double LinearInterpolate(double old, double New) { - return Old * (1.0 - FrameRateWeight) + New * FrameRateWeight; + return old * (1.0 - FrameRateWeight) + New * FrameRateWeight; } public void RecordSystemFrameTime() @@ -89,30 +89,30 @@ namespace Ryujinx.HLE RecordFrameTime(FrameTypeGame); } - private void RecordFrameTime(int FrameType) + private void RecordFrameTime(int frameType) { - double CurrentFrameTime = ExecutionTime.ElapsedTicks * TicksToSeconds; + double currentFrameTime = _executionTime.ElapsedTicks * _ticksToSeconds; - double ElapsedFrameTime = CurrentFrameTime - PreviousFrameTime[FrameType]; + double elapsedFrameTime = currentFrameTime - _previousFrameTime[frameType]; - PreviousFrameTime[FrameType] = CurrentFrameTime; + _previousFrameTime[frameType] = currentFrameTime; - lock (FrameLock[FrameType]) + lock (_frameLock[frameType]) { - AccumulatedFrameTime[FrameType] += ElapsedFrameTime; + _accumulatedFrameTime[frameType] += elapsedFrameTime; - FramesRendered[FrameType]++; + _framesRendered[frameType]++; } } public double GetSystemFrameRate() { - return AverageFrameRate[FrameTypeSystem]; + return _averageFrameRate[FrameTypeSystem]; } public double GetGameFrameRate() { - return AverageFrameRate[FrameTypeGame]; + return _averageFrameRate[FrameTypeGame]; } } } diff --git a/Ryujinx.HLE/Switch.cs b/Ryujinx.HLE/Switch.cs index 5b3b36d0..d661b273 100644 --- a/Ryujinx.HLE/Switch.cs +++ b/Ryujinx.HLE/Switch.cs @@ -31,23 +31,23 @@ namespace Ryujinx.HLE public event EventHandler Finish; - public Switch(IGalRenderer Renderer, IAalOutput AudioOut) + public Switch(IGalRenderer renderer, IAalOutput audioOut) { - if (Renderer == null) + if (renderer == null) { - throw new ArgumentNullException(nameof(Renderer)); + throw new ArgumentNullException(nameof(renderer)); } - if (AudioOut == null) + if (audioOut == null) { - throw new ArgumentNullException(nameof(AudioOut)); + throw new ArgumentNullException(nameof(audioOut)); } - this.AudioOut = AudioOut; + AudioOut = audioOut; Memory = new DeviceMemory(); - Gpu = new NvGpu(Renderer); + Gpu = new NvGpu(renderer); FileSystem = new VirtualFileSystem(); @@ -60,29 +60,29 @@ namespace Ryujinx.HLE VsyncEvent = new AutoResetEvent(true); } - public void LoadCart(string ExeFsDir, string RomFsFile = null) + public void LoadCart(string exeFsDir, string romFsFile = null) { - System.LoadCart(ExeFsDir, RomFsFile); + System.LoadCart(exeFsDir, romFsFile); } - public void LoadXci(string XciFile) + public void LoadXci(string xciFile) { - System.LoadXci(XciFile); + System.LoadXci(xciFile); } - public void LoadNca(string NcaFile) + public void LoadNca(string ncaFile) { - System.LoadNca(NcaFile); + System.LoadNca(ncaFile); } - public void LoadNsp(string NspFile) + public void LoadNsp(string nspFile) { - System.LoadNsp(NspFile); + System.LoadNsp(nspFile); } - public void LoadProgram(string FileName) + public void LoadProgram(string fileName) { - System.LoadProgram(FileName); + System.LoadProgram(fileName); } public bool WaitFifo() @@ -107,9 +107,9 @@ namespace Ryujinx.HLE Dispose(true); } - protected virtual void Dispose(bool Disposing) + protected virtual void Dispose(bool disposing) { - if (Disposing) + if (disposing) { System.Dispose(); diff --git a/Ryujinx.HLE/Utilities/EndianSwap.cs b/Ryujinx.HLE/Utilities/EndianSwap.cs index 5d0c8a84..df08191a 100644 --- a/Ryujinx.HLE/Utilities/EndianSwap.cs +++ b/Ryujinx.HLE/Utilities/EndianSwap.cs @@ -2,16 +2,16 @@ { static class EndianSwap { - public static ushort Swap16(ushort Value) => (ushort)(((Value >> 8) & 0xff) | (Value << 8)); + public static ushort Swap16(ushort value) => (ushort)(((value >> 8) & 0xff) | (value << 8)); - public static int Swap32(int Value) + public static int Swap32(int value) { - uint UintVal = (uint)Value; + uint uintVal = (uint)value; - return (int)(((UintVal >> 24) & 0x000000ff) | - ((UintVal >> 8) & 0x0000ff00) | - ((UintVal << 8) & 0x00ff0000) | - ((UintVal << 24) & 0xff000000)); + return (int)(((uintVal >> 24) & 0x000000ff) | + ((uintVal >> 8) & 0x0000ff00) | + ((uintVal << 8) & 0x00ff0000) | + ((uintVal << 24) & 0xff000000)); } } } diff --git a/Ryujinx.HLE/Utilities/FontUtils.cs b/Ryujinx.HLE/Utilities/FontUtils.cs index efe7560c..3da0ef68 100644 --- a/Ryujinx.HLE/Utilities/FontUtils.cs +++ b/Ryujinx.HLE/Utilities/FontUtils.cs @@ -6,29 +6,29 @@ namespace Ryujinx.HLE.Utilities { private static readonly uint FontKey = 0x06186249; - public static byte[] DecryptFont(Stream BFTTFStream) + public static byte[] DecryptFont(Stream bfttfStream) { uint KXor(uint In) => In ^ 0x06186249; - using (BinaryReader Reader = new BinaryReader(BFTTFStream)) + using (BinaryReader reader = new BinaryReader(bfttfStream)) { - using (MemoryStream TTFStream = new MemoryStream()) + using (MemoryStream ttfStream = new MemoryStream()) { - using (BinaryWriter Output = new BinaryWriter(TTFStream)) + using (BinaryWriter output = new BinaryWriter(ttfStream)) { - if (KXor(Reader.ReadUInt32()) != 0x18029a7f) + if (KXor(reader.ReadUInt32()) != 0x18029a7f) { throw new InvalidDataException("Error: Input file is not in BFTTF format!"); } - BFTTFStream.Position += 4; + bfttfStream.Position += 4; - for (int i = 0; i < (BFTTFStream.Length - 8) / 4; i++) + for (int i = 0; i < (bfttfStream.Length - 8) / 4; i++) { - Output.Write(KXor(Reader.ReadUInt32())); + output.Write(KXor(reader.ReadUInt32())); } - return TTFStream.ToArray(); + return ttfStream.ToArray(); } } } diff --git a/Ryujinx.HLE/Utilities/IntUtils.cs b/Ryujinx.HLE/Utilities/IntUtils.cs index 57e9d396..a7178d80 100644 --- a/Ryujinx.HLE/Utilities/IntUtils.cs +++ b/Ryujinx.HLE/Utilities/IntUtils.cs @@ -2,24 +2,24 @@ namespace Ryujinx.HLE.Utilities { static class IntUtils { - public static int AlignUp(int Value, int Size) + public static int AlignUp(int value, int size) { - return (Value + (Size - 1)) & ~(Size - 1); + return (value + (size - 1)) & ~(size - 1); } - public static long AlignUp(long Value, int Size) + public static long AlignUp(long value, int size) { - return (Value + (Size - 1)) & ~((long)Size - 1); + return (value + (size - 1)) & ~((long)size - 1); } - public static int AlignDown(int Value, int Size) + public static int AlignDown(int value, int size) { - return Value & ~(Size - 1); + return value & ~(size - 1); } - public static long AlignDown(long Value, int Size) + public static long AlignDown(long value, int size) { - return Value & ~((long)Size - 1); + return value & ~((long)size - 1); } } } diff --git a/Ryujinx.HLE/Utilities/LinuxError.cs b/Ryujinx.HLE/Utilities/LinuxError.cs index 5c322f83..81a9d7be 100644 --- a/Ryujinx.HLE/Utilities/LinuxError.cs +++ b/Ryujinx.HLE/Utilities/LinuxError.cs @@ -1,5 +1,8 @@ +using System.Diagnostics.CodeAnalysis; + namespace Ryujinx.HLE.Utilities { + [SuppressMessage("ReSharper", "InconsistentNaming")] enum LinuxError { SUCCESS = 0, @@ -147,6 +150,6 @@ namespace Ryujinx.HLE.Utilities ERFKILL = 132 /* Operation not possible due to RF-kill */, - EHWPOISON = 133 /* Memory page has hardware error */, + EHWPOISON = 133 /* Memory page has hardware error */ } } \ No newline at end of file diff --git a/Ryujinx.HLE/Utilities/StringUtils.cs b/Ryujinx.HLE/Utilities/StringUtils.cs index a10273ee..e6602f48 100644 --- a/Ryujinx.HLE/Utilities/StringUtils.cs +++ b/Ryujinx.HLE/Utilities/StringUtils.cs @@ -9,67 +9,67 @@ namespace Ryujinx.HLE.Utilities { static class StringUtils { - public static byte[] GetFixedLengthBytes(string InputString, int Size, Encoding Encoding) + public static byte[] GetFixedLengthBytes(string inputString, int size, Encoding encoding) { - InputString = InputString + "\0"; + inputString = inputString + "\0"; - int BytesCount = Encoding.GetByteCount(InputString); + int bytesCount = encoding.GetByteCount(inputString); - byte[] Output = new byte[Size]; + byte[] output = new byte[size]; - if (BytesCount < Size) + if (bytesCount < size) { - Encoding.GetBytes(InputString, 0, InputString.Length, Output, 0); + encoding.GetBytes(inputString, 0, inputString.Length, output, 0); } else { - int NullSize = Encoding.GetByteCount("\0"); + int nullSize = encoding.GetByteCount("\0"); - Output = Encoding.GetBytes(InputString); + output = encoding.GetBytes(inputString); - Array.Resize(ref Output, Size - NullSize); + Array.Resize(ref output, size - nullSize); - Output = Output.Concat(Encoding.GetBytes("\0")).ToArray(); + output = output.Concat(encoding.GetBytes("\0")).ToArray(); } - return Output; + return output; } - public static byte[] HexToBytes(string HexString) + public static byte[] HexToBytes(string hexString) { //Ignore last charactor if HexLength % 2 != 0. - int BytesInHex = HexString.Length / 2; + int bytesInHex = hexString.Length / 2; - byte[] Output = new byte[BytesInHex]; + byte[] output = new byte[bytesInHex]; - for (int Index = 0; Index < BytesInHex; Index++) + for (int index = 0; index < bytesInHex; index++) { - Output[Index] = byte.Parse(HexString.Substring(Index * 2, 2), NumberStyles.HexNumber); + output[index] = byte.Parse(hexString.Substring(index * 2, 2), NumberStyles.HexNumber); } - return Output; + return output; } - public static string ReadUtf8String(ServiceCtx Context, int Index = 0) + public static string ReadUtf8String(ServiceCtx context, int index = 0) { - long Position = Context.Request.PtrBuff[Index].Position; - long Size = Context.Request.PtrBuff[Index].Size; + long position = context.Request.PtrBuff[index].Position; + long size = context.Request.PtrBuff[index].Size; - using (MemoryStream MS = new MemoryStream()) + using (MemoryStream ms = new MemoryStream()) { - while (Size-- > 0) + while (size-- > 0) { - byte Value = Context.Memory.ReadByte(Position++); + byte value = context.Memory.ReadByte(position++); - if (Value == 0) + if (value == 0) { break; } - MS.WriteByte(Value); + ms.WriteByte(value); } - return Encoding.UTF8.GetString(MS.ToArray()); + return Encoding.UTF8.GetString(ms.ToArray()); } } } diff --git a/Ryujinx.HLE/Utilities/StructReader.cs b/Ryujinx.HLE/Utilities/StructReader.cs index 19fd2674..441dfd19 100644 --- a/Ryujinx.HLE/Utilities/StructReader.cs +++ b/Ryujinx.HLE/Utilities/StructReader.cs @@ -5,41 +5,41 @@ namespace Ryujinx.HLE.Utilities { class StructReader { - private MemoryManager Memory; + private MemoryManager _memory; public long Position { get; private set; } - public StructReader(MemoryManager Memory, long Position) + public StructReader(MemoryManager memory, long position) { - this.Memory = Memory; - this.Position = Position; + _memory = memory; + Position = position; } public T Read() where T : struct { - T Value = MemoryHelper.Read(Memory, Position); + T value = MemoryHelper.Read(_memory, Position); Position += Marshal.SizeOf(); - return Value; + return value; } - public T[] Read(int Size) where T : struct + public T[] Read(int size) where T : struct { - int StructSize = Marshal.SizeOf(); + int structSize = Marshal.SizeOf(); - int Count = Size / StructSize; + int count = size / structSize; - T[] Output = new T[Count]; + T[] output = new T[count]; - for (int Index = 0; Index < Count; Index++) + for (int index = 0; index < count; index++) { - Output[Index] = MemoryHelper.Read(Memory, Position); + output[index] = MemoryHelper.Read(_memory, Position); - Position += StructSize; + Position += structSize; } - return Output; + return output; } } } diff --git a/Ryujinx.HLE/Utilities/StructWriter.cs b/Ryujinx.HLE/Utilities/StructWriter.cs index a537e7a4..86cfeedd 100644 --- a/Ryujinx.HLE/Utilities/StructWriter.cs +++ b/Ryujinx.HLE/Utilities/StructWriter.cs @@ -5,19 +5,19 @@ namespace Ryujinx.HLE.Utilities { class StructWriter { - private MemoryManager Memory; + private MemoryManager _memory; public long Position { get; private set; } - public StructWriter(MemoryManager Memory, long Position) + public StructWriter(MemoryManager memory, long position) { - this.Memory = Memory; - this.Position = Position; + _memory = memory; + Position = position; } - public void Write(T Value) where T : struct + public void Write(T value) where T : struct { - MemoryHelper.Write(Memory, Position, Value); + MemoryHelper.Write(_memory, Position, value); Position += Marshal.SizeOf(); } diff --git a/Ryujinx.HLE/Utilities/UInt128.cs b/Ryujinx.HLE/Utilities/UInt128.cs index 14e04e4a..aa348e7e 100644 --- a/Ryujinx.HLE/Utilities/UInt128.cs +++ b/Ryujinx.HLE/Utilities/UInt128.cs @@ -9,27 +9,27 @@ namespace Ryujinx.HLE.Utilities public long High { get; private set; } public long Low { get; private set; } - public UInt128(long Low, long High) + public UInt128(long low, long high) { - this.Low = Low; - this.High = High; + Low = low; + High = high; } - public UInt128(string UInt128Hex) + public UInt128(string hex) { - if (UInt128Hex == null || UInt128Hex.Length != 32 || !UInt128Hex.All("0123456789abcdefABCDEF".Contains)) + if (hex == null || hex.Length != 32 || !hex.All("0123456789abcdefABCDEF".Contains)) { - throw new ArgumentException("Invalid Hex value!", nameof(UInt128Hex)); + throw new ArgumentException("Invalid Hex value!", nameof(hex)); } - Low = Convert.ToInt64(UInt128Hex.Substring(16), 16); - High = Convert.ToInt64(UInt128Hex.Substring(0, 16), 16); + Low = Convert.ToInt64(hex.Substring(16), 16); + High = Convert.ToInt64(hex.Substring(0, 16), 16); } - public void Write(BinaryWriter BinaryWriter) + public void Write(BinaryWriter binaryWriter) { - BinaryWriter.Write(Low); - BinaryWriter.Write(High); + binaryWriter.Write(Low); + binaryWriter.Write(High); } public override string ToString() diff --git a/Ryujinx.HLE/Utilities/WSAError.cs b/Ryujinx.HLE/Utilities/WSAError.cs index ff0896d4..81294b8b 100644 --- a/Ryujinx.HLE/Utilities/WSAError.cs +++ b/Ryujinx.HLE/Utilities/WSAError.cs @@ -1,6 +1,9 @@ -namespace Ryujinx.HLE.Utilities +using System.Diagnostics.CodeAnalysis; + +namespace Ryujinx.HLE.Utilities { - enum WSAError + [SuppressMessage("ReSharper", "InconsistentNaming")] + enum WsaError { /* * All Windows Sockets error constants are biased by WSABASEERR from @@ -21,43 +24,43 @@ /* * Windows Sockets definitions of regular Berkeley error constants */ - WSAEWOULDBLOCK = (WSABASEERR + 35), - WSAEINPROGRESS = (WSABASEERR + 36), - WSAEALREADY = (WSABASEERR + 37), - WSAENOTSOCK = (WSABASEERR + 38), - WSAEDESTADDRREQ = (WSABASEERR + 39), - WSAEMSGSIZE = (WSABASEERR + 40), - WSAEPROTOTYPE = (WSABASEERR + 41), - WSAENOPROTOOPT = (WSABASEERR + 42), - WSAEPROTONOSUPPORT = (WSABASEERR + 43), - WSAESOCKTNOSUPPORT = (WSABASEERR + 44), - WSAEOPNOTSUPP = (WSABASEERR + 45), - WSAEPFNOSUPPORT = (WSABASEERR + 46), - WSAEAFNOSUPPORT = (WSABASEERR + 47), - WSAEADDRINUSE = (WSABASEERR + 48), - WSAEADDRNOTAVAIL = (WSABASEERR + 49), - WSAENETDOWN = (WSABASEERR + 50), - WSAENETUNREACH = (WSABASEERR + 51), - WSAENETRESET = (WSABASEERR + 52), - WSAECONNABORTED = (WSABASEERR + 53), - WSAECONNRESET = (WSABASEERR + 54), - WSAENOBUFS = (WSABASEERR + 55), - WSAEISCONN = (WSABASEERR + 56), - WSAENOTCONN = (WSABASEERR + 57), - WSAESHUTDOWN = (WSABASEERR + 58), - WSAETOOMANYREFS = (WSABASEERR + 59), - WSAETIMEDOUT = (WSABASEERR + 60), - WSAECONNREFUSED = (WSABASEERR + 61), - WSAELOOP = (WSABASEERR + 62), - WSAENAMETOOLONG = (WSABASEERR + 63), - WSAEHOSTDOWN = (WSABASEERR + 64), - WSAEHOSTUNREACH = (WSABASEERR + 65), - WSAENOTEMPTY = (WSABASEERR + 66), - WSAEPROCLIM = (WSABASEERR + 67), - WSAEUSERS = (WSABASEERR + 68), - WSAEDQUOT = (WSABASEERR + 69), - WSAESTALE = (WSABASEERR + 70), - WSAEREMOTE = (WSABASEERR + 71), + WSAEWOULDBLOCK = (WSABASEERR + 35), + WSAEINPROGRESS = (WSABASEERR + 36), + WSAEALREADY = (WSABASEERR + 37), + WSAENOTSOCK = (WSABASEERR + 38), + WSAEDESTADDRREQ = (WSABASEERR + 39), + WSAEMSGSIZE = (WSABASEERR + 40), + WSAEPROTOTYPE = (WSABASEERR + 41), + WSAENOPROTOOPT = (WSABASEERR + 42), + WSAEPROTONOSUPPORT = (WSABASEERR + 43), + WSAESOCKTNOSUPPORT = (WSABASEERR + 44), + WSAEOPNOTSUPP = (WSABASEERR + 45), + WSAEPFNOSUPPORT = (WSABASEERR + 46), + WSAEAFNOSUPPORT = (WSABASEERR + 47), + WSAEADDRINUSE = (WSABASEERR + 48), + WSAEADDRNOTAVAIL = (WSABASEERR + 49), + WSAENETDOWN = (WSABASEERR + 50), + WSAENETUNREACH = (WSABASEERR + 51), + WSAENETRESET = (WSABASEERR + 52), + WSAECONNABORTED = (WSABASEERR + 53), + WSAECONNRESET = (WSABASEERR + 54), + WSAENOBUFS = (WSABASEERR + 55), + WSAEISCONN = (WSABASEERR + 56), + WSAENOTCONN = (WSABASEERR + 57), + WSAESHUTDOWN = (WSABASEERR + 58), + WSAETOOMANYREFS = (WSABASEERR + 59), + WSAETIMEDOUT = (WSABASEERR + 60), + WSAECONNREFUSED = (WSABASEERR + 61), + WSAELOOP = (WSABASEERR + 62), + WSAENAMETOOLONG = (WSABASEERR + 63), + WSAEHOSTDOWN = (WSABASEERR + 64), + WSAEHOSTUNREACH = (WSABASEERR + 65), + WSAENOTEMPTY = (WSABASEERR + 66), + WSAEPROCLIM = (WSABASEERR + 67), + WSAEUSERS = (WSABASEERR + 68), + WSAEDQUOT = (WSABASEERR + 69), + WSAESTALE = (WSABASEERR + 70), + WSAEREMOTE = (WSABASEERR + 71), /* * Extended Windows Sockets error constant definitions @@ -126,6 +129,6 @@ * buffer in general */ WSA_QOS_TRAFFIC_CTRL_ERROR = (WSABASEERR + 1014), /* problem with some part of the flowspec */ - WSA_QOS_GENERIC_ERROR = (WSABASEERR + 1015), + WSA_QOS_GENERIC_ERROR = (WSABASEERR + 1015) } } diff --git a/Ryujinx.sln.DotSettings b/Ryujinx.sln.DotSettings new file mode 100644 index 00000000..737b5688 --- /dev/null +++ b/Ryujinx.sln.DotSettings @@ -0,0 +1,7 @@ + + WARNING + WARNING + UseExplicitType + UseExplicitType + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb"><ExtraRule Prefix="I" Suffix="" Style="AaBb" /></Policy> + \ No newline at end of file diff --git a/Ryujinx/Ui/GLScreen.cs b/Ryujinx/Ui/GLScreen.cs index 6acb199c..02335999 100644 --- a/Ryujinx/Ui/GLScreen.cs +++ b/Ryujinx/Ui/GLScreen.cs @@ -164,14 +164,14 @@ namespace Ryujinx leftJoystick = new HidJoystickPosition { - DX = leftJoystickDx, - DY = leftJoystickDy + Dx = leftJoystickDx, + Dy = leftJoystickDy }; rightJoystick = new HidJoystickPosition { - DX = rightJoystickDx, - DY = rightJoystickDy + Dx = rightJoystickDx, + Dy = rightJoystickDy }; bool hasTouch = false;