From 3615a70cae3f89197fe185dfc5d0a47fa42151d9 Mon Sep 17 00:00:00 2001 From: gdkchan Date: Tue, 4 Dec 2018 22:52:39 -0200 Subject: [PATCH] Revert "Adjust naming conventions and general refactoring in HLE Project (#490)" (#526) This reverts commit 85dbb9559ad317a657dafd24da27fec4b3f5250f. --- Ryujinx.HLE/DeviceMemory.cs | 84 +- .../Exceptions/InvalidNpdmException.cs | 2 +- .../UndefinedInstructionException.cs | 2 +- .../FileSystem/Content/ContentManager.cs | 252 +-- .../FileSystem/Content/LocationEntry.cs | 25 +- .../FileSystem/Content/LocationHelper.cs | 36 +- Ryujinx.HLE/FileSystem/FileSystemProvider.cs | 192 +- Ryujinx.HLE/FileSystem/IFileSystemProvider.cs | 33 +- Ryujinx.HLE/FileSystem/PFsProvider.cs | 84 +- Ryujinx.HLE/FileSystem/RomFsProvider.cs | 100 +- Ryujinx.HLE/FileSystem/SaveHelper.cs | 32 +- Ryujinx.HLE/FileSystem/SaveInfo.cs | 30 +- Ryujinx.HLE/FileSystem/VirtualFileSystem.cs | 88 +- .../Ast/ArraySubscriptingExpression.cs | 22 +- .../Diagnostics/Demangler/Ast/ArrayType.cs | 40 +- .../HOS/Diagnostics/Demangler/Ast/BaseNode.cs | 22 +- .../Demangler/Ast/BinaryExpression.cs | 38 +- .../Demangler/Ast/BracedExpression.cs | 34 +- .../Demangler/Ast/BracedRangeExpression.cs | 32 +- .../Demangler/Ast/CallExpression.cs | 16 +- .../Demangler/Ast/CastExpression.cs | 28 +- .../Demangler/Ast/ConditionalExpression.cs | 30 +- .../Demangler/Ast/ConversionExpression.cs | 20 +- .../Demangler/Ast/ConversionOperatorType.cs | 8 +- .../Demangler/Ast/CtorDtorNameType.cs | 14 +- .../Demangler/Ast/CtorVtableSpecialName.cs | 20 +- .../Demangler/Ast/DeleteExpression.cs | 24 +- .../HOS/Diagnostics/Demangler/Ast/DtorName.cs | 8 +- .../Demangler/Ast/DynamicExceptionSpec.cs | 10 +- .../Demangler/Ast/ElaboratedType.cs | 14 +- .../Demangler/Ast/EnclosedExpression.cs | 22 +- .../Demangler/Ast/EncodedFunction.cs | 64 +- .../Demangler/Ast/FoldExpression.cs | 52 +- .../Demangler/Ast/ForwardTemplateReference.cs | 14 +- .../Demangler/Ast/FunctionParameter.cs | 14 +- .../Diagnostics/Demangler/Ast/FunctionType.cs | 52 +- .../Demangler/Ast/GlobalQualifiedName.cs | 8 +- .../Demangler/Ast/InitListExpression.cs | 22 +- .../Demangler/Ast/IntegerCastExpression.cs | 16 +- .../Demangler/Ast/IntegerLiteral.cs | 32 +- .../Demangler/Ast/LiteralOperator.cs | 10 +- .../Diagnostics/Demangler/Ast/LocalName.cs | 18 +- .../Demangler/Ast/MemberExpression.cs | 22 +- .../HOS/Diagnostics/Demangler/Ast/NameType.cs | 16 +- .../Ast/NameTypeWithTemplateArguments.cs | 18 +- .../Diagnostics/Demangler/Ast/NestedName.cs | 16 +- .../Demangler/Ast/NewExpression.cs | 52 +- .../Diagnostics/Demangler/Ast/NodeArray.cs | 12 +- .../Diagnostics/Demangler/Ast/NoexceptSpec.cs | 10 +- .../Demangler/Ast/PackedTemplateParameter.cs | 18 +- .../Ast/PackedTemplateParameterExpansion.cs | 8 +- .../Diagnostics/Demangler/Ast/ParentNode.cs | 6 +- .../Diagnostics/Demangler/Ast/PointerType.cs | 30 +- .../Demangler/Ast/PostfixExpression.cs | 16 +- .../Demangler/Ast/PostfixQualifiedType.cs | 12 +- .../Demangler/Ast/PrefixExpression.cs | 16 +- .../Demangler/Ast/QualifiedName.cs | 18 +- .../Diagnostics/Demangler/Ast/Qualifier.cs | 56 +- .../Demangler/Ast/ReferenceType.cs | 34 +- .../Diagnostics/Demangler/Ast/SpecialName.cs | 12 +- .../Demangler/Ast/SpecialSubstitution.cs | 20 +- .../Demangler/Ast/StdQualifiedName.cs | 8 +- .../Demangler/Ast/TemplateArguments.cs | 12 +- .../Demangler/Ast/ThrowExpression.cs | 12 +- .../HOS/Diagnostics/Demangler/Demangler.cs | 1806 ++++++++-------- Ryujinx.HLE/HOS/ErrorCode.cs | 4 +- Ryujinx.HLE/HOS/ErrorModule.cs | 36 +- Ryujinx.HLE/HOS/Font/SharedFontManager.cs | 128 +- Ryujinx.HLE/HOS/GlobalStateTable.cs | 40 +- Ryujinx.HLE/HOS/Homebrew.cs | 58 +- Ryujinx.HLE/HOS/Horizon.cs | 366 ++-- Ryujinx.HLE/HOS/IdDictionary.cs | 40 +- Ryujinx.HLE/HOS/Ipc/IpcBuffDesc.cs | 26 +- Ryujinx.HLE/HOS/Ipc/IpcHandleDesc.cs | 70 +- Ryujinx.HLE/HOS/Ipc/IpcHandler.cs | 112 +- Ryujinx.HLE/HOS/Ipc/IpcMessage.cs | 182 +- Ryujinx.HLE/HOS/Ipc/IpcPtrBuffDesc.cs | 24 +- Ryujinx.HLE/HOS/Ipc/IpcRecvListBuffDesc.cs | 12 +- Ryujinx.HLE/HOS/Ipc/ServiceProcessRequest.cs | 2 +- Ryujinx.HLE/HOS/Kernel/HleCoreManager.cs | 38 +- Ryujinx.HLE/HOS/Kernel/HleProcessDebugger.cs | 226 +- Ryujinx.HLE/HOS/Kernel/HleScheduler.cs | 76 +- Ryujinx.HLE/HOS/Kernel/KAddressArbiter.cs | 504 ++--- Ryujinx.HLE/HOS/Kernel/KAutoObject.cs | 18 +- Ryujinx.HLE/HOS/Kernel/KClientPort.cs | 24 +- Ryujinx.HLE/HOS/Kernel/KConditionVariable.cs | 56 +- Ryujinx.HLE/HOS/Kernel/KContextIdManager.cs | 52 +- Ryujinx.HLE/HOS/Kernel/KCoreContext.cs | 30 +- Ryujinx.HLE/HOS/Kernel/KCriticalSection.cs | 50 +- Ryujinx.HLE/HOS/Kernel/KEvent.cs | 8 +- Ryujinx.HLE/HOS/Kernel/KHandleEntry.cs | 6 +- Ryujinx.HLE/HOS/Kernel/KHandleTable.cs | 158 +- Ryujinx.HLE/HOS/Kernel/KMemoryArrange.cs | 24 +- .../HOS/Kernel/KMemoryArrangeRegion.cs | 10 +- Ryujinx.HLE/HOS/Kernel/KMemoryBlock.cs | 24 +- .../HOS/Kernel/KMemoryBlockAllocator.cs | 10 +- Ryujinx.HLE/HOS/Kernel/KMemoryInfo.cs | 42 +- Ryujinx.HLE/HOS/Kernel/KMemoryManager.cs | 1846 ++++++++--------- Ryujinx.HLE/HOS/Kernel/KMemoryRegionBlock.cs | 18 +- .../HOS/Kernel/KMemoryRegionManager.cs | 330 +-- Ryujinx.HLE/HOS/Kernel/KPageList.cs | 42 +- Ryujinx.HLE/HOS/Kernel/KPageNode.cs | 6 +- Ryujinx.HLE/HOS/Kernel/KPort.cs | 22 +- Ryujinx.HLE/HOS/Kernel/KProcess.cs | 660 +++--- .../HOS/Kernel/KProcessCapabilities.cs | 166 +- Ryujinx.HLE/HOS/Kernel/KReadableEvent.cs | 28 +- Ryujinx.HLE/HOS/Kernel/KResourceLimit.cs | 114 +- Ryujinx.HLE/HOS/Kernel/KScheduler.cs | 122 +- Ryujinx.HLE/HOS/Kernel/KSchedulingData.cs | 162 +- Ryujinx.HLE/HOS/Kernel/KServerPort.cs | 8 +- Ryujinx.HLE/HOS/Kernel/KSession.cs | 16 +- Ryujinx.HLE/HOS/Kernel/KSharedMemory.cs | 62 +- Ryujinx.HLE/HOS/Kernel/KSlabHeap.cs | 32 +- Ryujinx.HLE/HOS/Kernel/KSynchronization.cs | 108 +- .../HOS/Kernel/KSynchronizationObject.cs | 10 +- Ryujinx.HLE/HOS/Kernel/KThread.cs | 488 ++--- Ryujinx.HLE/HOS/Kernel/KTimeManager.cs | 94 +- Ryujinx.HLE/HOS/Kernel/KTlsPageInfo.cs | 48 +- Ryujinx.HLE/HOS/Kernel/KTlsPageManager.cs | 42 +- Ryujinx.HLE/HOS/Kernel/KTransferMemory.cs | 10 +- Ryujinx.HLE/HOS/Kernel/KWritableEvent.cs | 10 +- Ryujinx.HLE/HOS/Kernel/KernelInit.cs | 118 +- Ryujinx.HLE/HOS/Kernel/KernelTransfer.cs | 44 +- Ryujinx.HLE/HOS/Kernel/MersenneTwister.cs | 106 +- Ryujinx.HLE/HOS/Kernel/ProcessCreationInfo.cs | 48 +- Ryujinx.HLE/HOS/Kernel/SvcHandler.cs | 58 +- Ryujinx.HLE/HOS/Kernel/SvcMemory.cs | 464 ++--- Ryujinx.HLE/HOS/Kernel/SvcSystem.cs | 628 +++--- Ryujinx.HLE/HOS/Kernel/SvcThread.cs | 454 ++-- Ryujinx.HLE/HOS/Kernel/SvcThreadSync.cs | 310 +-- Ryujinx.HLE/HOS/ProgramLoader.cs | 252 +-- Ryujinx.HLE/HOS/ServiceCtx.cs | 48 +- .../HOS/Services/Acc/IAccountService.cs | 98 +- .../Services/Acc/IManagerForApplication.cs | 22 +- Ryujinx.HLE/HOS/Services/Acc/IProfile.cs | 60 +- .../Am/IAllSystemAppletProxiesService.cs | 10 +- .../HOS/Services/Am/IApplicationCreator.cs | 6 +- .../HOS/Services/Am/IApplicationFunctions.cs | 60 +- .../HOS/Services/Am/IApplicationProxy.cs | 38 +- .../Services/Am/IApplicationProxyService.cs | 10 +- .../HOS/Services/Am/IAudioController.cs | 30 +- .../HOS/Services/Am/ICommonStateGetter.cs | 58 +- .../HOS/Services/Am/IDebugFunctions.cs | 6 +- .../HOS/Services/Am/IDisplayController.cs | 6 +- .../HOS/Services/Am/IGlobalStateController.cs | 6 +- .../HOS/Services/Am/IHomeMenuFunctions.cs | 20 +- .../HOS/Services/Am/ILibraryAppletAccessor.cs | 30 +- .../HOS/Services/Am/ILibraryAppletCreator.cs | 16 +- .../HOS/Services/Am/ISelfController.cs | 76 +- Ryujinx.HLE/HOS/Services/Am/IStorage.cs | 16 +- .../HOS/Services/Am/IStorageAccessor.cs | 52 +- .../HOS/Services/Am/ISystemAppletProxy.cs | 46 +- .../HOS/Services/Am/IWindowController.cs | 12 +- Ryujinx.HLE/HOS/Services/Am/StorageHelper.cs | 16 +- Ryujinx.HLE/HOS/Services/Apm/IManager.cs | 10 +- Ryujinx.HLE/HOS/Services/Apm/ISession.cs | 18 +- .../HOS/Services/Aud/AudioOut/IAudioOut.cs | 110 +- .../Aud/AudioRenderer/IAudioRenderer.cs | 302 +-- .../Aud/AudioRenderer/MemoryPoolState.cs | 2 +- .../Services/Aud/AudioRenderer/Resampler.cs | 82 +- .../Aud/AudioRenderer/VoiceContext.cs | 114 +- Ryujinx.HLE/HOS/Services/Aud/IAudioDevice.cs | 138 +- .../HOS/Services/Aud/IAudioOutManager.cs | 124 +- .../HOS/Services/Aud/IAudioRendererManager.cs | 140 +- .../HOS/Services/Aud/IHardwareOpusDecoder.cs | 68 +- .../Aud/IHardwareOpusDecoderManager.cs | 54 +- Ryujinx.HLE/HOS/Services/Bcat/IBcatService.cs | 6 +- .../Bcat/IDeliveryCacheStorageService.cs | 6 +- .../HOS/Services/Bcat/IServiceCreator.cs | 18 +- Ryujinx.HLE/HOS/Services/Bsd/BsdIoctl.cs | 2 +- Ryujinx.HLE/HOS/Services/Bsd/IClient.cs | 959 ++++----- Ryujinx.HLE/HOS/Services/Bsd/PollEvent.cs | 20 +- .../Services/Caps/IAlbumAccessorService.cs | 6 +- .../HOS/Services/Caps/IScreenshotService.cs | 6 +- .../HOS/Services/Es/IETicketService.cs | 13 +- .../HOS/Services/Friend/IFriendService.cs | 86 +- .../HOS/Services/Friend/IServiceCreator.cs | 10 +- .../HOS/Services/FspSrv/DirectoryEntry.cs | 18 +- .../HOS/Services/FspSrv/FileSystemType.cs | 2 +- Ryujinx.HLE/HOS/Services/FspSrv/IDirectory.cs | 70 +- Ryujinx.HLE/HOS/Services/FspSrv/IFile.cs | 70 +- .../HOS/Services/FspSrv/IFileSystem.cs | 246 +-- .../HOS/Services/FspSrv/IFileSystemProxy.cs | 238 +-- Ryujinx.HLE/HOS/Services/FspSrv/IStorage.cs | 36 +- Ryujinx.HLE/HOS/Services/Hid/HidNpad.cs | 10 +- Ryujinx.HLE/HOS/Services/Hid/HidVibration.cs | 2 +- .../Hid/IActiveVibrationDeviceList.cs | 10 +- .../HOS/Services/Hid/IAppletResource.cs | 18 +- Ryujinx.HLE/HOS/Services/Hid/IHidServer.cs | 1184 +++++------ Ryujinx.HLE/HOS/Services/IpcService.cs | 142 +- .../HOS/Services/Irs/IIrSensorServer.cs | 20 +- Ryujinx.HLE/HOS/Services/Ldr/IRoInterface.cs | 417 ++-- Ryujinx.HLE/HOS/Services/Lm/ILogService.cs | 10 +- Ryujinx.HLE/HOS/Services/Lm/ILogger.cs | 82 +- .../HOS/Services/Lr/ILocationResolver.cs | 136 +- .../Services/Lr/ILocationResolverManager.cs | 17 +- Ryujinx.HLE/HOS/Services/Mm/IRequest.cs | 26 +- .../HOS/Services/Ncm/IContentManager.cs | 6 +- .../HOS/Services/Ncm/IContentStorage.cs | 6 +- Ryujinx.HLE/HOS/Services/Nfp/IUser.cs | 60 +- Ryujinx.HLE/HOS/Services/Nfp/IUserManager.cs | 10 +- .../HOS/Services/Nifm/IGeneralService.cs | 22 +- Ryujinx.HLE/HOS/Services/Nifm/IRequest.cs | 36 +- .../HOS/Services/Nifm/IStaticService.cs | 14 +- .../HOS/Services/Ns/IAddOnContentManager.cs | 14 +- .../Ns/IApplicationManagerInterface.cs | 9 +- .../Services/Ns/IServiceGetterInterface.cs | 6 +- .../HOS/Services/Ns/ISystemUpdateInterface.cs | 6 +- .../Ns/IVulnerabilityManagerInterface.cs | 6 +- Ryujinx.HLE/HOS/Services/Nv/INvDrvServices.cs | 138 +- Ryujinx.HLE/HOS/Services/Nv/NvFd.cs | 6 +- .../HOS/Services/Nv/NvGpuAS/NvGpuASCtx.cs | 146 +- .../HOS/Services/Nv/NvGpuAS/NvGpuASIoctl.cs | 244 +-- .../HOS/Services/Nv/NvGpuGpu/NvGpuGpuIoctl.cs | 192 +- .../Nv/NvHostChannel/NvHostChannelIoctl.cs | 243 +-- .../Services/Nv/NvHostCtrl/NvHostCtrlIoctl.cs | 282 +-- .../Nv/NvHostCtrl/NvHostCtrlUserCtx.cs | 4 +- .../Services/Nv/NvHostCtrl/NvHostSyncPt.cs | 76 +- .../HOS/Services/Nv/NvMap/NvMapHandle.cs | 12 +- .../HOS/Services/Nv/NvMap/NvMapIoctl.cs | 230 +- .../Services/Pctl/IParentalControlService.cs | 20 +- .../Pctl/IParentalControlServiceFactory.cs | 14 +- .../HOS/Services/Pl/ISharedFontManager.cs | 80 +- .../HOS/Services/Prepo/IPrepoService.cs | 8 +- Ryujinx.HLE/HOS/Services/Psm/IPsmServer.cs | 24 +- Ryujinx.HLE/HOS/Services/Psm/IPsmSession.cs | 54 +- Ryujinx.HLE/HOS/Services/ServiceFactory.cs | 14 +- .../HOS/Services/Set/ISettingsServer.cs | 46 +- .../HOS/Services/Set/ISystemSettingsServer.cs | 166 +- Ryujinx.HLE/HOS/Services/Set/NxSettings.cs | 4 +- Ryujinx.HLE/HOS/Services/Sfdnsres/GaiError.cs | 2 +- .../HOS/Services/Sfdnsres/IResolver.cs | 300 +-- .../HOS/Services/Sfdnsres/NetDBError.cs | 4 +- Ryujinx.HLE/HOS/Services/Sm/IUserInterface.cs | 38 +- .../HOS/Services/Spl/IRandomInterface.cs | 24 +- Ryujinx.HLE/HOS/Services/Ssl/ISslContext.cs | 6 +- Ryujinx.HLE/HOS/Services/Ssl/ISslService.cs | 22 +- .../HOS/Services/Time/IStaticService.cs | 34 +- Ryujinx.HLE/HOS/Services/Time/ISteadyClock.cs | 24 +- Ryujinx.HLE/HOS/Services/Time/ISystemClock.cs | 78 +- .../HOS/Services/Time/ITimeZoneService.cs | 222 +- Ryujinx.HLE/HOS/Services/Vi/Display.cs | 6 +- Ryujinx.HLE/HOS/Services/Vi/GbpBuffer.cs | 70 +- .../Services/Vi/IApplicationDisplayService.cs | 186 +- .../Services/Vi/IApplicationRootService.cs | 12 +- .../HOS/Services/Vi/IHOSBinderDriver.cs | 74 +- .../HOS/Services/Vi/IManagerDisplayService.cs | 16 +- .../HOS/Services/Vi/IManagerRootService.cs | 12 +- .../HOS/Services/Vi/ISystemDisplayService.cs | 20 +- .../HOS/Services/Vi/ISystemRootService.cs | 12 +- Ryujinx.HLE/HOS/Services/Vi/NvFlinger.cs | 322 +-- Ryujinx.HLE/HOS/Services/Vi/Parcel.cs | 50 +- Ryujinx.HLE/HOS/SystemState/AppletStateMgr.cs | 24 +- Ryujinx.HLE/HOS/SystemState/SystemStateMgr.cs | 60 +- Ryujinx.HLE/HOS/SystemState/UserProfile.cs | 10 +- Ryujinx.HLE/Input/Hid.cs | 130 +- Ryujinx.HLE/Input/HidBaseController.cs | 68 +- Ryujinx.HLE/Input/HidControllerColorDesc.cs | 2 +- Ryujinx.HLE/Input/HidControllerConnState.cs | 4 +- Ryujinx.HLE/Input/HidControllerId.cs | 20 +- Ryujinx.HLE/Input/HidControllerLayouts.cs | 14 +- Ryujinx.HLE/Input/HidJoystickPosition.cs | 4 +- Ryujinx.HLE/Input/HidNpadController.cs | 80 +- Ryujinx.HLE/Input/HidProController.cs | 42 +- Ryujinx.HLE/Input/HidValues.cs | 6 +- Ryujinx.HLE/Input/IHidDevice.cs | 6 +- Ryujinx.HLE/Input/NpadColor.cs | 28 +- .../Loaders/Compression/BackwardsLz.cs | 72 +- Ryujinx.HLE/Loaders/Compression/Lz4.cs | 60 +- Ryujinx.HLE/Loaders/Elf/ElfDynamic.cs | 10 +- Ryujinx.HLE/Loaders/Elf/ElfDynamicTag.cs | 3 - Ryujinx.HLE/Loaders/Elf/ElfSymbol.cs | 48 +- Ryujinx.HLE/Loaders/Elf/ElfSymbolBinding.cs | 6 +- Ryujinx.HLE/Loaders/Elf/ElfSymbolType.cs | 14 +- .../Loaders/Elf/ElfSymbolVisibility.cs | 8 +- .../Loaders/Executables/IExecutable.cs | 4 +- .../Executables/KernelInitialProcess.cs | 154 +- .../Executables/NxRelocatableObject.cs | 80 +- .../Loaders/Executables/NxStaticObject.cs | 114 +- Ryujinx.HLE/Loaders/Npdm/ACI0.cs | 50 +- Ryujinx.HLE/Loaders/Npdm/ACID.cs | 62 +- Ryujinx.HLE/Loaders/Npdm/FsAccessControl.cs | 30 +- Ryujinx.HLE/Loaders/Npdm/FsAccessHeader.cs | 24 +- .../Loaders/Npdm/KernelAccessControl.cs | 14 +- Ryujinx.HLE/Loaders/Npdm/Npdm.cs | 66 +- .../Loaders/Npdm/ServiceAccessControl.cs | 28 +- Ryujinx.HLE/PerformanceStatistics.cs | 78 +- Ryujinx.HLE/Switch.cs | 54 +- Ryujinx.HLE/Utilities/EndianSwap.cs | 14 +- Ryujinx.HLE/Utilities/FontUtils.cs | 18 +- Ryujinx.HLE/Utilities/IntUtils.cs | 16 +- Ryujinx.HLE/Utilities/LinuxError.cs | 5 +- Ryujinx.HLE/Utilities/StringUtils.cs | 52 +- Ryujinx.HLE/Utilities/StructReader.cs | 28 +- Ryujinx.HLE/Utilities/StructWriter.cs | 12 +- Ryujinx.HLE/Utilities/UInt128.cs | 26 +- Ryujinx.HLE/Utilities/WSAError.cs | 83 +- Ryujinx.sln.DotSettings | 7 - Ryujinx/Ui/GLScreen.cs | 8 +- 299 files changed, 12276 insertions(+), 12268 deletions(-) delete mode 100644 Ryujinx.sln.DotSettings diff --git a/Ryujinx.HLE/DeviceMemory.cs b/Ryujinx.HLE/DeviceMemory.cs index 540be995d..edc709119 100644 --- a/Ryujinx.HLE/DeviceMemory.cs +++ b/Ryujinx.HLE/DeviceMemory.cs @@ -7,109 +7,109 @@ namespace Ryujinx.HLE { public const long RamSize = 4L * 1024 * 1024 * 1024; - public IntPtr RamPointer { get; } + 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 *(_ramPtr + position); + return *((byte*)(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) { - *(_ramPtr + position) = value; + *((byte*)(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 c4036ea0d..58d044345 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 message) : base(message) { } + public InvalidNpdmException(string ExMsg) : base(ExMsg) { } } } diff --git a/Ryujinx.HLE/Exceptions/UndefinedInstructionException.cs b/Ryujinx.HLE/Exceptions/UndefinedInstructionException.cs index 84bb1fc59..24bf9efdd 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 0b3bfe00d..3727841dd 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 }, }; - _device = device; + this.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) + catch (NotSupportedException NEx) { 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 ade2e5a83..c7c6133b5 100644 --- a/Ryujinx.HLE/FileSystem/Content/LocationEntry.cs +++ b/Ryujinx.HLE/FileSystem/Content/LocationEntry.cs @@ -1,25 +1,28 @@ -using LibHac; +using System; +using System.Collections.Generic; +using System.Text; +using LibHac; namespace Ryujinx.HLE.FileSystem.Content { public struct LocationEntry { - public string ContentPath { get; } + public string ContentPath { get; private set; } public int Flag { get; private set; } - public long TitleId { get; } - public ContentType ContentType { get; } + 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) { - ContentPath = contentPath; - Flag = flag; - TitleId = titleId; - ContentType = contentType; + this.ContentPath = ContentPath; + this.Flag = Flag; + this.TitleId = TitleId; + this.ContentType = ContentType; } - public void SetFlag(int flag) + public void SetFlag(int Flag) { - Flag = flag; + this.Flag = Flag; } } } diff --git a/Ryujinx.HLE/FileSystem/Content/LocationHelper.cs b/Ryujinx.HLE/FileSystem/Content/LocationHelper.cs index df3f5ad65..75b594316 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 8461467d1..fdaa7fd7d 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) { - _basePath = basePath; - _rootPath = rootPath; + this.BasePath = BasePath; + this.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 8e2cae643..88a630a0d 100644 --- a/Ryujinx.HLE/FileSystem/IFileSystemProvider.cs +++ b/Ryujinx.HLE/FileSystem/IFileSystemProvider.cs @@ -1,40 +1,41 @@ 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 717576693..c901f073e 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) { - _pfs = pfs; + this.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 == "/"; + return Name == "/" ? true : false; } - 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 f6a2f82f4..d966d3d7c 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 0dfcfd2bb..20138c8cd 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 a7e7f01a9..3acd33fda 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; } - public long SaveId { get; } - public UInt128 UserId { get; } + public long TitleId { get; private set; } + public long SaveId { get; private set; } + public UInt128 UserId { get; private set; } - public SaveDataType SaveDataType { get; } - public SaveSpaceId SaveSpaceId { get; } + 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) { - TitleId = titleId; - UserId = userId; - SaveId = saveId; - SaveDataType = saveDataType; - SaveSpaceId = saveSpaceId; + this.TitleId = TitleId; + this.UserId = UserId; + this.SaveId = SaveId; + this.SaveDataType = SaveDataType; + this.SaveSpaceId = SaveSpaceId; } } } diff --git a/Ryujinx.HLE/FileSystem/VirtualFileSystem.cs b/Ryujinx.HLE/FileSystem/VirtualFileSystem.cs index eed5953f1..bde6f69f2 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 5145ff7b0..435789e0f 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) { - _leftNode = leftNode; - _subscript = subscript; + this.LeftNode = LeftNode; + this.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 4b1041ab7..167973607 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) { - _base = Base; - _dimensionExpression = dimensionExpression; + this.Base = Base; + this.DimensionExpression = DimensionExpression; } - public ArrayType(BaseNode Base, string dimensionString) : base(NodeType.ArrayType) + public ArrayType(BaseNode Base, string DimensionString) : base(NodeType.ArrayType) { - _base = Base; - _dimensionString = dimensionString; + this.Base = Base; + this.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 ca4b98f88..870758462 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) { - Type = type; + this.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 0c492df39..9cd1dd779 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) { - _leftPart = leftPart; - _name = name; - _rightPart = rightPart; + this.LeftPart = LeftPart; + this.Name = Name; + this.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 6b9782f5c..59222ea3f 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) { - _element = element; - _expression = expression; - _isArrayExpression = isArrayExpression; + this.Element = Element; + this.Expression = Expression; + this.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 802422d9a..e459f1a39 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) { - _firstNode = firstNode; - _lastNode = lastNode; - _expression = expression; + this.FirstNode = FirstNode; + this.LastNode = LastNode; + this.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 8e3fc3e69..ae43fcdb2 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) { - _callee = callee; + this.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 1149a788c..c02e9e655 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) { - _kind = kind; - _to = to; - _from = from; + this.Kind = Kind; + this.To = To; + this.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 c0dd67179..17ac7c1a2 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) { - _thenNode = thenNode; - _conditionNode = conditionNode; - _elseNode = elseNode; + this.ThenNode = ThenNode; + this.ConditionNode = ConditionNode; + this.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 dd1f7a008..7c5d35d81 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) { - _typeNode = typeNode; - _expressions = expressions; + this.TypeNode = TypeNode; + this.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 8a5cde860..55d4eecab 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 5f4581235..49ed386d0 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) { - _isDestructor = isDestructor; + this.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 3bb5b1631..7630dbe57 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) { - _firstType = firstType; - _secondType = secondType; + this.FirstType = FirstType; + this.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 14715d25e..22c34c421 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) { - _isGlobal = isGlobal; - _isArrayExpression = isArrayExpression; + this.IsGlobal = IsGlobal; + this.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 5cc4e6cfb..c65c4cfb3 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 faa91443a..dca5f0dfd 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 086cd3dc7..11f89c8d3 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) { - _elaborated = elaborated; + this.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 b45481ddc..dc991aa09 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) { - _prefix = prefix; - _expression = expression; - _postfix = postfix; + this.Prefix = Prefix; + this.Expression = Expression; + this.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 c7b6dab1a..37a9a7afe 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) { - _name = name; - _params = Params; - _cv = cv; - _ref = Ref; - _attrs = attrs; - _ret = ret; + this.Name = Name; + this.Params = Params; + this.CV = CV; + this.Ref = Ref; + this.Attrs = Attrs; + this.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 04f7053e3..e01529984 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) { - _isLeftFold = isLeftFold; - _operatorName = operatorName; - _expression = expression; - _initializer = initializer; + this.IsLeftFold = IsLeftFold; + this.OperatorName = OperatorName; + this.Expression = Expression; + this.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 1bbf6ef9a..6456e47bf 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) { - _index = index; + this.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 5654a048f..5a1ca61d5 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) { - _number = number; + this.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 4ad0c9f5f..c727eab9c 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) { - _returnType = returnType; - _params = Params; - _cvQualifier = cvQualifier; - _referenceQualifier = referenceQualifier; - _exceptionSpec = exceptionSpec; + this.ReturnType = ReturnType; + this.Params = Params; + this.CVQualifier = CVQualifier; + this.ReferenceQualifier = ReferenceQualifier; + this.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 d3b6a558f..2346c1bf7 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 7155dd601..2ed4daa46 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) { - _typeNode = typeNode; - _nodes = nodes; + this.TypeNode = TypeNode; + this.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 ef07414de..984c9aefb 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) { - _number = number; + this.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 951faa554..215cf6dce 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 _literalName; - private string _literalValue; + private string LitteralName; + private string LitteralValue; - public IntegerLiteral(string literalName, string literalValue) : base(NodeType.IntegerLiteral) + public IntegerLiteral(string LitteralName, string LitteralValue) : base(NodeType.IntegerLiteral) { - _literalValue = literalValue; - _literalName = literalName; + this.LitteralValue = LitteralValue; + this.LitteralName = LitteralName; } - public override void PrintLeft(TextWriter writer) + public override void PrintLeft(TextWriter Writer) { - if (_literalName.Length > 3) + if (LitteralName.Length > 3) { - writer.Write("("); - writer.Write(_literalName); - writer.Write(")"); + Writer.Write("("); + Writer.Write(LitteralName); + Writer.Write(")"); } - if (_literalValue[0] == 'n') + if (LitteralValue[0] == 'n') { - writer.Write("-"); - writer.Write(_literalValue.Substring(1)); + Writer.Write("-"); + Writer.Write(LitteralValue.Substring(1)); } else { - writer.Write(_literalValue); + Writer.Write(LitteralValue); } - if (_literalName.Length <= 3) + if (LitteralName.Length <= 3) { - writer.Write(_literalName); + Writer.Write(LitteralName); } } } diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/LiteralOperator.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/LiteralOperator.cs index f7e86c9e2..f9bd4a6ef 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 15d46b387..44c216289 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) { - _encoding = encoding; - _entity = entity; + this.Encoding = Encoding; + this.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 9b91f6f5d..dd3d02dbd 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) { - _leftNode = leftNode; - _kind = kind; - _rightNode = rightNode; + this.LeftNode = LeftNode; + this.Kind = Kind; + this.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 f9f4cb20e..029440cb7 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) { - _nameValue = nameValue; + this.NameValue = NameValue; } - public NameType(string nameValue) : base(NodeType.NameType) + public NameType(string NameValue) : base(NodeType.NameType) { - _nameValue = nameValue; + this.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 ee725f36b..e16bd1508 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) { - _prev = prev; - _templateArgument = templateArgument; + this.Prev = Prev; + this.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 640c200cb..0ec6d9829 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) { - _name = name; + this.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 ba4690af4..5cc14ad9f 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) { - _expressions = expressions; - _typeNode = typeNode; - _initializers = initializers; + this.Expressions = Expressions; + this.TypeNode = TypeNode; + this.Initializers = Initializers; - _isGlobal = isGlobal; - _isArrayExpression = isArrayExpression; + this.IsGlobal = IsGlobal; + this.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 1482dfc37..f7bfa194f 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) { - Nodes = nodes; + this.Nodes = Nodes; } - public NodeArray(List nodes, NodeType type) : base(type) + public NodeArray(List Nodes, NodeType Type) : base(Type) { - Nodes = nodes; + this.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 49044493e..5bee9cfac 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 4c8200958..66ad11227 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 c3645044a..ce9fa4a3b 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 d5da8729b..f1c283473 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ParentNode.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ParentNode.cs @@ -2,11 +2,11 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { public abstract class ParentNode : BaseNode { - public BaseNode Child { get; } + public BaseNode Child { get; private set; } - public ParentNode(NodeType type, BaseNode child) : base(type) + public ParentNode(NodeType Type, BaseNode Child) : base(Type) { - Child = child; + this.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 b1a3ec422..a60776a27 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) { - _child = child; + this.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 ccaea3ba7..021f2de82 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) { - _operator = Operator; + this.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 5024a8f99..465450d3f 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) { - _postfixQualifier = postfixQualifier; + this.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 9c3d4552a..619d05387 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) { - _prefix = prefix; + this.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 2e18f564e..ce356e162 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) { - _qualifier = qualifier; - _name = name; + this.Qualifier = Qualifier; + this.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 cb6dd6bf6..3721b8dee 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) { - Qualifier = qualifier; + this.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) { - Qualifier = qualifier; + this.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 a3214171f..602814afb 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) { - _reference = reference; - _child = child; + this.Reference = Reference; + this.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 1447458b3..1a299af4d 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) { - _specialValue = specialValue; + this.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 8d45e180b..f4e9a14a1 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) { - _specialSubstitutionKey = specialSubstitutionKey; + this.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 c3a97d60a..ed1b59942 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 aefd668de..d6efbd0fc 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 2972a31c2..bb1466174 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) { - _expression = expression; + this.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 76c5053ec..164d5618c 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 Base36 = "0123456789abcdefghijklmnopqrstuvwxyz"; - private List _substitutionList = new List(); - private List _templateParamList = new List(); + private static readonly string BASE_36 = "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; } + 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) { - Mangled = mangled; - _position = 0; - _length = mangled.Length; - _canParseTemplateArgs = true; + this.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 = Base36.IndexOf(reversedEncoded[i]); - if (value == -1) + int Value = BASE_36.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 564fa91dd..767664f8d 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 e13d5e84f..5c6c9b056 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, - DebugMonitor = 7, + Debug_Monitor = 7, Lr = 8, Loader = 9, - IpcCommandInterface = 10, - Ipc = 11, + IPC_Command_Interface = 10, + IPC = 11, Pm = 15, Ns = 16, Socket = 17, Htc = 18, - NcmContent = 20, + Ncm_Content = 20, Sm = 21, - RoUserland = 22, + RO_Userland = 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, - PlayReport = 129, + Play_Report = 129, Ahid = 130, Qlaunch = 132, Pcv = 133, @@ -64,23 +64,23 @@ namespace Ryujinx.HLE.HOS Ec = 144, ETicket = 145, Ngc = 146, - ErrorReport = 147, + Error_Report = 147, Apm = 148, Profiler = 150, - ErrorUpload = 151, + Error_Upload = 151, Audio = 153, Npns = 154, - NpnsHttpStream = 155, + Npns_Http_Stream = 155, Arp = 157, Swkbd = 158, Boot = 159, - NfcMifare = 161, - UserlandAssert = 162, + Nfc_Mifare = 161, + Userland_Assert = 162, Fatal = 163, - NimShop = 164, + Nim_Shop = 164, Spsm = 165, Bgtc = 167, - UserlandCrash = 168, + Userland_Crash = 168, SRepo = 180, Dauth = 181, Hid = 202, @@ -92,10 +92,10 @@ namespace Ryujinx.HLE.HOS Web = 210, Grc = 212, Migration = 216, - MigrationLdcServer = 217, - GeneralWebApplet = 800, - WifiWebAuthApplet = 809, - WhitelistedApplet = 810, + Migration_Ldc_Server = 217, + General_Web_Applet = 800, + Wifi_Web_Auth_Applet = 809, + Whitelisted_Applet = 810, ShopN = 811 } } diff --git a/Ryujinx.HLE/HOS/Font/SharedFontManager.cs b/Ryujinx.HLE/HOS/Font/SharedFontManager.cs index 31c8178ac..55adf46a5 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) { - Offset = offset; - Size = size; + this.Offset = Offset; + this.Size = Size; } } - private Dictionary _fontData; + private Dictionary FontData; - public SharedFontManager(Switch device, long physicalAddress) + public SharedFontManager(Switch Device, long PhysicalAddress) { - _physicalAddress = physicalAddress; + this.PhysicalAddress = PhysicalAddress; - _device = device; + this.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 a350dee23..d7d834533 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 b0e05554b..ffb22c7f5 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 592e3fc78..46c276495 100644 --- a/Ryujinx.HLE/HOS/Horizon.cs +++ b/Ryujinx.HLE/HOS/Horizon.cs @@ -35,34 +35,34 @@ namespace Ryujinx.HLE.HOS internal long PrivilegedProcessLowestId { get; set; } = 1; internal long PrivilegedProcessHighestId { get; set; } = 8; - internal Switch Device { get; } + internal Switch Device { get; private set; } - public SystemStateMgr State { get; } + public SystemStateMgr State { get; private set; } - internal bool KernelInitialized { get; } + internal bool KernelInitialized { get; private set; } - internal KResourceLimit ResourceLimit { get; } + internal KResourceLimit ResourceLimit { get; private set; } - internal KMemoryRegionManager[] MemoryRegions { get; } + internal KMemoryRegionManager[] MemoryRegions { get; private set; } - internal KMemoryBlockAllocator LargeMemoryBlockAllocator { get; } - internal KMemoryBlockAllocator SmallMemoryBlockAllocator { get; } + internal KMemoryBlockAllocator LargeMemoryBlockAllocator { get; private set; } + internal KMemoryBlockAllocator SmallMemoryBlockAllocator { get; private set; } - internal KSlabHeap UserSlabHeapPages { get; } + internal KSlabHeap UserSlabHeapPages { get; private set; } - internal KCriticalSection CriticalSection { get; } + internal KCriticalSection CriticalSection { get; private set; } - internal KScheduler Scheduler { get; } + internal KScheduler Scheduler { get; private set; } - internal KTimeManager TimeManager { get; } + internal KTimeManager TimeManager { get; private set; } - internal KSynchronization Synchronization { get; } + internal KSynchronization Synchronization { get; private set; } - internal KContextIdManager ContextIdManager { get; } + 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; @@ -72,20 +72,20 @@ namespace Ryujinx.HLE.HOS internal bool EnableVersionChecks { get; private set; } - internal AppletStateMgr AppletState { get; } + internal AppletStateMgr AppletState { get; private set; } - internal KSharedMemory HidSharedMem { get; } - internal KSharedMemory FontSharedMem { get; } + internal KSharedMemory HidSharedMem { get; private set; } + internal KSharedMemory FontSharedMem { get; private set; } - internal SharedFontManager Font { get; } + internal SharedFontManager Font { get; private set; } - internal ContentManager ContentManager { get; } + internal ContentManager ContentManager { get; private set; } - internal KEvent VsyncEvent { get; } + internal KEvent VsyncEvent { get; private set; } internal Keyset KeySet { get; private set; } - private bool _hasStarted; + private bool HasStarted; public Nacp ControlData { get; set; } @@ -93,11 +93,11 @@ namespace Ryujinx.HLE.HOS public IntegrityCheckLevel FsIntegrityCheckLevel { get; set; } - internal long HidBaseAddress { get; } + internal long HidBaseAddress { get; private set; } - public Horizon(Switch device) + public Horizon(Switch Device) { - Device = device; + this.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) - : new NxStaticObject(input); + IExecutable StaticObject = IsNro + ? (IExecutable)new NxRelocatableObject(Input) + : (IExecutable)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 c6356725a..03d15498f 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 0907243db..346d696e3 100644 --- a/Ryujinx.HLE/HOS/Ipc/IpcBuffDesc.cs +++ b/Ryujinx.HLE/HOS/Ipc/IpcBuffDesc.cs @@ -4,24 +4,24 @@ namespace Ryujinx.HLE.HOS.Ipc { struct IpcBuffDesc { - public long Position { get; } - public long Size { get; } - public int Flags { get; } + public long Position { get; private set; } + 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 3360dff3f..081b56952 100644 --- a/Ryujinx.HLE/HOS/Ipc/IpcHandleDesc.cs +++ b/Ryujinx.HLE/HOS/Ipc/IpcHandleDesc.cs @@ -5,87 +5,87 @@ namespace Ryujinx.HLE.HOS.Ipc { class IpcHandleDesc { - public bool HasPId { get; } + public bool HasPId { get; private set; } - public long PId { get; } + public long PId { get; private set; } - public int[] ToCopy { get; } - public int[] ToMove { get; } + 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) { - PId = pId; + this.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(PId); + Writer.Write((long)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 e5d19236b..860c8242e 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 c19566cc6..02900444a 100644 --- a/Ryujinx.HLE/HOS/Ipc/IpcMessage.cs +++ b/Ryujinx.HLE/HOS/Ipc/IpcMessage.cs @@ -9,13 +9,13 @@ namespace Ryujinx.HLE.HOS.Ipc public IpcHandleDesc HandleDesc { get; set; } - public List PtrBuff { get; } - public List SendBuff { get; } - public List ReceiveBuff { get; } - public List ExchangeBuff { get; } - public List RecvListBuff { get; } + public List PtrBuff { get; private set; } + public List SendBuff { get; private set; } + public List ReceiveBuff { get; private set; } + public List ExchangeBuff { get; private set; } + public List RecvListBuff { get; private set; } - public List ObjectIds { get; } + public List ObjectIds { get; private set; } public byte[] RawData { get; set; } @@ -30,185 +30,183 @@ 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; } - // ReSharper disable once InconsistentNaming - public (long Position, long Size) GetBufferType0x21(int index = 0) + 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); } - // ReSharper disable once InconsistentNaming - public (long Position, long Size) GetBufferType0x22(int index = 0) + 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 cecd3ab07..21f5d3bcd 100644 --- a/Ryujinx.HLE/HOS/Ipc/IpcPtrBuffDesc.cs +++ b/Ryujinx.HLE/HOS/Ipc/IpcPtrBuffDesc.cs @@ -4,23 +4,23 @@ namespace Ryujinx.HLE.HOS.Ipc { struct IpcPtrBuffDesc { - public long Position { get; } - public int Index { get; } - public long Size { get; } + public long Position { get; private set; } + 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 43152d784..1d0a8c807 100644 --- a/Ryujinx.HLE/HOS/Ipc/IpcRecvListBuffDesc.cs +++ b/Ryujinx.HLE/HOS/Ipc/IpcRecvListBuffDesc.cs @@ -4,16 +4,16 @@ namespace Ryujinx.HLE.HOS.Ipc { struct IpcRecvListBuffDesc { - public long Position { get; } - public long Size { get; } + 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 b3aaa2191..da4a7e75a 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 cfcda87ba..6a424cf23 100644 --- a/Ryujinx.HLE/HOS/Kernel/HleCoreManager.cs +++ b/Ryujinx.HLE/HOS/Kernel/HleCoreManager.cs @@ -7,7 +7,7 @@ namespace Ryujinx.HLE.HOS.Kernel { private class PausableThread { - public ManualResetEvent Event { get; } + public ManualResetEvent Event { get; private set; } public bool IsExiting { get; set; } @@ -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 9ef4ca8fd..a6053b1b1 100644 --- a/Ryujinx.HLE/HOS/Kernel/HleProcessDebugger.cs +++ b/Ryujinx.HLE/HOS/Kernel/HleProcessDebugger.cs @@ -14,138 +14,138 @@ 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 { - public long BaseAddress { get; } + public long BaseAddress { get; private set; } - public ElfSymbol[] Symbols { get; } + public ElfSymbol[] Symbols { get; private set; } - public Image(long baseAddress, ElfSymbol[] symbols) + public Image(long BaseAddress, ElfSymbol[] Symbols) { - BaseAddress = baseAddress; - Symbols = symbols; + this.BaseAddress = BaseAddress; + this.Symbols = Symbols; } } - private List _images; + private List Images; - private int _loaded; + private int Loaded; - public HleProcessDebugger(KProcess owner) + public HleProcessDebugger(KProcess Owner) { - _owner = owner; + this.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 4afc48ba4..87dbe5538 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; } + 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 < CpuCoresCount; core++) + for (int Core = 0; Core < KScheduler.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 b43524855..cc637be0e 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) { - _system = system; + this.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 f49beaac9..a91bf9a84 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) { - System = system; + this.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 575476277..e3f8128bf 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) { - _maxSessions = maxSessions; - _parent = parent; + this.MaxSessions = MaxSessions; + this.Parent = Parent; } - public new static KernelResult RemoveName(Horizon system, string name) + public new static KernelResult RemoveName(Horizon System, string Name) { - KAutoObject foundObj = FindNamedObject(system, name); + KAutoObject FoundObj = KAutoObject.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 15c96c24d..1c95f8116 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 80a1c1c71..03e7dddf7 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 4ca3c25a0..638dde9ee 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) { - _scheduler = scheduler; - _coreManager = coreManager; + this.Scheduler = Scheduler; + this.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 4bafa69dc..b02a11954 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; } + public object LockObj { get; private set; } - private int _recursionCount; + private int RecursionCount; - public KCriticalSection(Horizon system) + public KCriticalSection(Horizon System) { - _system = system; + this.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 032e2a4c2..106d1b409 100644 --- a/Ryujinx.HLE/HOS/Kernel/KEvent.cs +++ b/Ryujinx.HLE/HOS/Kernel/KEvent.cs @@ -2,12 +2,12 @@ namespace Ryujinx.HLE.HOS.Kernel { class KEvent { - public KReadableEvent ReadableEvent { get; } - public KWritableEvent WritableEvent { get; } + 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 1799e9642..9863a374b 100644 --- a/Ryujinx.HLE/HOS/Kernel/KHandleEntry.cs +++ b/Ryujinx.HLE/HOS/Kernel/KHandleEntry.cs @@ -4,14 +4,14 @@ namespace Ryujinx.HLE.HOS.Kernel { public KHandleEntry Next { get; set; } - public int Index { get; } + public int Index { get; private set; } public ushort HandleId { get; set; } public object Obj { get; set; } - public KHandleEntry(int index) + public KHandleEntry(int Index) { - Index = index; + this.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 88d0c5136..e39dfb671 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) { - _system = system; + this.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; } - _size = size; + this.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) & 0xffff8000) | entry.Index; + Handle = (int)((IdCounter << 15) & (uint)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 853c6ab16..af393b68e 100644 --- a/Ryujinx.HLE/HOS/Kernel/KMemoryArrange.cs +++ b/Ryujinx.HLE/HOS/Kernel/KMemoryArrange.cs @@ -2,21 +2,21 @@ namespace Ryujinx.HLE.HOS.Kernel { class KMemoryArrange { - public KMemoryArrangeRegion Service { get; } - public KMemoryArrangeRegion NvServices { get; } - public KMemoryArrangeRegion Applet { get; } - public KMemoryArrangeRegion Application { get; } + public KMemoryArrangeRegion Service { get; private set; } + public KMemoryArrangeRegion NvServices { get; private set; } + public KMemoryArrangeRegion Applet { get; private set; } + public KMemoryArrangeRegion Application { get; private set; } public KMemoryArrange( - KMemoryArrangeRegion service, - KMemoryArrangeRegion nvServices, - KMemoryArrangeRegion applet, - KMemoryArrangeRegion application) + KMemoryArrangeRegion Service, + KMemoryArrangeRegion NvServices, + KMemoryArrangeRegion Applet, + KMemoryArrangeRegion Application) { - Service = service; - NvServices = nvServices; - Applet = applet; - Application = application; + this.Service = Service; + this.NvServices = NvServices; + this.Applet = Applet; + this.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 c76cf42e6..7d66e2913 100644 --- a/Ryujinx.HLE/HOS/Kernel/KMemoryArrangeRegion.cs +++ b/Ryujinx.HLE/HOS/Kernel/KMemoryArrangeRegion.cs @@ -2,15 +2,15 @@ namespace Ryujinx.HLE.HOS.Kernel { struct KMemoryArrangeRegion { - public ulong Address { get; } - public ulong Size { get; } + public ulong Address { get; private set; } + public ulong Size { get; private set; } public ulong EndAddr => Address + Size; - public KMemoryArrangeRegion(ulong address, ulong size) + public KMemoryArrangeRegion(ulong Address, ulong Size) { - Address = address; - Size = size; + this.Address = Address; + this.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 44b7a6834..08190236e 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) { - BaseAddress = baseAddress; - PagesCount = pagesCount; - State = state; - Attribute = attribute; - Permission = permission; + this.BaseAddress = BaseAddress; + this.PagesCount = PagesCount; + this.State = State; + this.Attribute = Attribute; + this.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 375685e67..08512e129 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) { - _capacityElements = capacityElements; + this.CapacityElements = CapacityElements; } - public bool CanAllocate(int count) + public bool CanAllocate(int Count) { - return (ulong)(Count + count) <= _capacityElements; + return (ulong)(this.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 8ae522d41..09ba88f2c 100644 --- a/Ryujinx.HLE/HOS/Kernel/KMemoryInfo.cs +++ b/Ryujinx.HLE/HOS/Kernel/KMemoryInfo.cs @@ -2,32 +2,32 @@ namespace Ryujinx.HLE.HOS.Kernel { class KMemoryInfo { - public ulong Address { get; } - public ulong Size { get; } + public ulong Address { get; private set; } + public ulong Size { get; private set; } - public MemoryState State { get; } - public MemoryPermission Permission { get; } - public MemoryAttribute Attribute { get; } + public MemoryState State { get; private set; } + public MemoryPermission Permission { get; private set; } + public MemoryAttribute Attribute { get; private set; } - public int IpcRefCount { get; } - public int DeviceRefCount { get; } + public int IpcRefCount { get; private set; } + 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) { - Address = address; - Size = size; - State = state; - Attribute = attribute; - Permission = permission; - IpcRefCount = ipcRefCount; - DeviceRefCount = deviceRefCount; + this.Address = Address; + this.Size = Size; + this.State = State; + this.Attribute = Attribute; + this.Permission = Permission; + this.IpcRefCount = IpcRefCount; + this.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 831844c72..0aa21e3f3 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) { - _system = system; - _cpuMemory = cpuMemory; + this.System = System; + this.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; - _aslrEnabled = aslrEnabled; + this.AslrEnabled = AslrEnabled; - AddrSpaceStart = addrSpaceStart; - AddrSpaceEnd = addrSpaceEnd; + this.AddrSpaceStart = AddrSpaceStart; + this.AddrSpaceEnd = AddrSpaceEnd; - _blockAllocator = blockAllocator; + this.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; - _memRegion = memRegion; - _aslrDisabled = aslrDisabled; + this.MemRegion = MemRegion; + this.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 f7e85e9a5..1f334e655 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 4c41314d1..10db0753f 100644 --- a/Ryujinx.HLE/HOS/Kernel/KMemoryRegionManager.cs +++ b/Ryujinx.HLE/HOS/Kernel/KMemoryRegionManager.cs @@ -6,404 +6,404 @@ namespace Ryujinx.HLE.HOS.Kernel { private static readonly int[] BlockOrders = new int[] { 12, 16, 21, 22, 25, 29, 30 }; - public ulong Address { get; } - public ulong EndAddr { get; } - public ulong Size { get; } + public ulong Address { get; private set; } + 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]; - Address = address; - Size = size; - EndAddr = endAddr; + this.Address = Address; + this.Size = Size; + this.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 651626467..05162323f 100644 --- a/Ryujinx.HLE/HOS/Kernel/KPageList.cs +++ b/Ryujinx.HLE/HOS/Kernel/KPageList.cs @@ -5,31 +5,31 @@ namespace Ryujinx.HLE.HOS.Kernel { class KPageList : IEnumerable { - public LinkedList Nodes { get; } + public LinkedList Nodes { get; private set; } public KPageList() { 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 5cdb1c493..6cecab2e7 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) { - Address = address; - PagesCount = pagesCount; + this.Address = Address; + this.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 7e5ef3940..598f3a321 100644 --- a/Ryujinx.HLE/HOS/Kernel/KPort.cs +++ b/Ryujinx.HLE/HOS/Kernel/KPort.cs @@ -2,25 +2,25 @@ namespace Ryujinx.HLE.HOS.Kernel { class KPort : KAutoObject { - public KServerPort ServerPort { get; } - public KClientPort ClientPort { get; } + 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); - _isLight = isLight; - _nameAddress = nameAddress; + this.IsLight = IsLight; + this.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 53b55f7ee..094ef222f 100644 --- a/Ryujinx.HLE/HOS/Kernel/KProcess.cs +++ b/Ryujinx.HLE/HOS/Kernel/KProcess.cs @@ -21,10 +21,10 @@ namespace Ryujinx.HLE.HOS.Kernel (KernelVersionMinor << 15) | (KernelVersionRevision << 0); - public KMemoryManager MemoryManager { get; } + 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,142 +34,142 @@ 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; } + public KAddressArbiter AddressArbiter { get; private set; } - public long[] RandomEntropy { get; } + 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; } + 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; } - public Translator Translator { get; } + public Translator Translator { get; private set; } - public MemoryManager CpuMemory { get; } + public MemoryManager CpuMemory { get; private set; } - private SvcHandler _svcHandler; + private SvcHandler SvcHandler; - public HleProcessDebugger Debugger { get; } + 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) { - ResourceLimit = resourceLimit; - _memRegion = memRegion; + this.ResourceLimit = ResourceLimit; + this.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) { - ResourceLimit = resourceLimit; - _memRegion = memRegion; + this.ResourceLimit = ResourceLimit; + this.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; } - UserExceptionContextAddress = userExceptionContextAddress; + this.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 c715a41ef..dfbe1f361 100644 --- a/Ryujinx.HLE/HOS/Kernel/KProcessCapabilities.cs +++ b/Ryujinx.HLE/HOS/Kernel/KProcessCapabilities.cs @@ -4,8 +4,8 @@ namespace Ryujinx.HLE.HOS.Kernel { class KProcessCapabilities { - public byte[] SvcAccessMask { get; } - public byte[] IrqAccessMask { get; } + public byte[] SvcAccessMask { get; private set; } + public byte[] IrqAccessMask { get; private set; } public long AllowedCpuCoresMask { get; private set; } public long AllowedThreadPriosMask { get; private set; } @@ -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; } - ApplicationType = applicationType; + this.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; } - HandleTableSize = handleTableSize; + this.HandleTableSize = HandleTableSize; break; } case 0x10000: { - int debuggingFlags = cap >> 19; + int DebuggingFlags = Cap >> 19; - if ((uint)debuggingFlags > 3) + if ((uint)DebuggingFlags > 3) { return KernelResult.ReservedValue; } - DebuggingFlags &= ~3; - DebuggingFlags |= debuggingFlags; + this.DebuggingFlags &= ~3; + this.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 e1a3e63fc..bfb8e7e2d 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) { - _parent = parent; + this.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 09c53e5b0..6fd70d0ca 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(); - _system = system; + this.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) { - _limit[index] = limit; + this.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 43f1a9941..3342f4a61 100644 --- a/Ryujinx.HLE/HOS/Kernel/KScheduler.cs +++ b/Ryujinx.HLE/HOS/Kernel/KScheduler.cs @@ -12,17 +12,17 @@ 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; } + public KSchedulingData SchedulingData { get; private set; } - public KCoreContext[] CoreContexts { get; } + public KCoreContext[] CoreContexts { get; private set; } public bool ThreadReselectionRequested { get; set; } - public KScheduler(Horizon system) + public KScheduler(Horizon System) { - _system = system; + this.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 651160361..ba2730a29 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 0aa74e487..42135cd8b 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) { - _parent = parent; + this.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 a350b3231..4b21d3a63 100644 --- a/Ryujinx.HLE/HOS/Kernel/KSession.cs +++ b/Ryujinx.HLE/HOS/Kernel/KSession.cs @@ -5,14 +5,14 @@ namespace Ryujinx.HLE.HOS.Kernel { class KSession : IDisposable { - public IpcService Service { get; } + public IpcService Service { get; private set; } - public string ServiceName { get; } + public string ServiceName { get; private set; } - public KSession(IpcService service, string serviceName) + public KSession(IpcService Service, string ServiceName) { - Service = service; - ServiceName = serviceName; + this.Service = Service; + this.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 0e9f8840e..a440438b9 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) { - _pageList = pageList; - _ownerPid = ownerPid; - _ownerPermission = ownerPermission; - _userPermission = userPermission; + this.PageList = PageList; + this.OwnerPid = OwnerPid; + this.OwnerPermission = OwnerPermission; + this.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 84c4dc017..2d6b3ca0f 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 51b74a03d..19e700f4c 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) { - _system = system; + this.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 79f0673ff..5ba7784fc 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 ae1e860f9..88f144c81 100644 --- a/Ryujinx.HLE/HOS/Kernel/KThread.cs +++ b/Ryujinx.HLE/HOS/Kernel/KThread.cs @@ -22,31 +22,31 @@ 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; } - public LinkedListNode[] SiblingsPerCore { get; } + public LinkedListNode[] SiblingsPerCore { get; private set; } public LinkedList Withholder { get; set; } public LinkedListNode WithholderNode { get; set; } 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; - _entrypoint = entrypoint; + this.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) { - Owner = owner; + this.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 c662906c6..375789f05 100644 --- a/Ryujinx.HLE/HOS/Kernel/KTimeManager.cs +++ b/Ryujinx.HLE/HOS/Kernel/KTimeManager.cs @@ -10,116 +10,116 @@ namespace Ryujinx.HLE.HOS.Kernel { private class WaitingObject { - public IKFutureSchedulerObject Object { get; } + public IKFutureSchedulerObject Object { get; private set; } - public long TimePoint { get; } + public long TimePoint { get; private set; } - public WaitingObject(IKFutureSchedulerObject schedulerObj, long timePoint) + public WaitingObject(IKFutureSchedulerObject Object, long TimePoint) { - Object = schedulerObj; - TimePoint = timePoint; + this.Object = Object; + this.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 schedulerObj, long timeout) + public void ScheduleFutureInvocation(IKFutureSchedulerObject Object, long Timeout) { - long timePoint = PerformanceCounter.ElapsedMilliseconds + ConvertNanosecondsToMilliseconds(timeout); + long TimePoint = PerformanceCounter.ElapsedMilliseconds + ConvertNanosecondsToMilliseconds(Timeout); - lock (_waitingObjects) + lock (WaitingObjects) { - _waitingObjects.Add(new WaitingObject(schedulerObj, timePoint)); + WaitingObjects.Add(new WaitingObject(Object, 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 aa0614e63..18dc2decf 100644 --- a/Ryujinx.HLE/HOS/Kernel/KTlsPageInfo.cs +++ b/Ryujinx.HLE/HOS/Kernel/KTlsPageInfo.cs @@ -4,70 +4,70 @@ namespace Ryujinx.HLE.HOS.Kernel { public const int TlsEntrySize = 0x200; - public ulong PageAddr { get; } + public ulong PageAddr { get; private set; } - private bool[] _isSlotFree; + private bool[] IsSlotFree; - public KTlsPageInfo(ulong pageAddress) + public KTlsPageInfo(ulong PageAddress) { - PageAddr = pageAddress; + this.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 75f595ebc..1fb2ce6ad 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) { - _pagePosition = pagePosition; + this.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 7bdc66e34..5598f78d2 100644 --- a/Ryujinx.HLE/HOS/Kernel/KTransferMemory.cs +++ b/Ryujinx.HLE/HOS/Kernel/KTransferMemory.cs @@ -2,13 +2,13 @@ namespace Ryujinx.HLE.HOS.Kernel { class KTransferMemory { - public ulong Address { get; } - public ulong Size { get; } + public ulong Address { get; private set; } + public ulong Size { get; private set; } - public KTransferMemory(ulong address, ulong size) + public KTransferMemory(ulong Address, ulong Size) { - Address = address; - Size = size; + this.Address = Address; + this.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 4d56a92d2..1721ed001 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) { - _parent = parent; + this.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 a797951b0..efb514c12 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 c0ce72c0c..a3fabeaeb 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 5307bdc9f..b90d54d26 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 37f33f284..dae1345ae 100644 --- a/Ryujinx.HLE/HOS/Kernel/ProcessCreationInfo.cs +++ b/Ryujinx.HLE/HOS/Kernel/ProcessCreationInfo.cs @@ -2,36 +2,36 @@ namespace Ryujinx.HLE.HOS.Kernel { struct ProcessCreationInfo { - public string Name { get; } + public string Name { get; private set; } - public int Category { get; } - public long TitleId { get; } + public int Category { get; private set; } + public long TitleId { get; private set; } - public ulong CodeAddress { get; } - public int CodePagesCount { get; } + public ulong CodeAddress { get; private set; } + public int CodePagesCount { get; private set; } - public int MmuFlags { get; } - public int ResourceLimitHandle { get; } - public int PersonalMmHeapPagesCount { get; } + public int MmuFlags { get; private set; } + public int ResourceLimitHandle { get; private set; } + 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) { - Name = name; - Category = category; - TitleId = titleId; - CodeAddress = codeAddress; - CodePagesCount = codePagesCount; - MmuFlags = mmuFlags; - ResourceLimitHandle = resourceLimitHandle; - PersonalMmHeapPagesCount = 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; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/SvcHandler.cs b/Ryujinx.HLE/HOS/Kernel/SvcHandler.cs index 614087803..cbc5e31c6 100644 --- a/Ryujinx.HLE/HOS/Kernel/SvcHandler.cs +++ b/Ryujinx.HLE/HOS/Kernel/SvcHandler.cs @@ -10,38 +10,38 @@ 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 { - public KThread Thread { get; } - public KSession Session { get; } - public IpcMessage Message { get; } - public long MessagePtr { get; } + public KThread Thread { get; private set; } + public KSession Session { get; private set; } + public IpcMessage Message { get; private set; } + public long MessagePtr { get; private set; } public HleIpcMessage( - KThread thread, - KSession session, - IpcMessage message, - long messagePtr) + KThread Thread, + KSession Session, + IpcMessage Message, + long MessagePtr) { - Thread = thread; - Session = session; - Message = message; - MessagePtr = messagePtr; + this.Thread = Thread; + this.Session = Session; + this.Message = Message; + this.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 } }; - _device = device; - _process = process; - _system = device.System; - _memory = process.CpuMemory; + this.Device = Device; + this.Process = Process; + this.System = Device.System; + this.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 c99c1e985..b5845f0b6 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 e42c2b4ec..1c1d76f15 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 0121303d9..ded8f8dc9 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 11cfffe9b..3935df5d3 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 00fc6b935..ddacd3fd8 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 61fa2a9bf..76c426bca 100644 --- a/Ryujinx.HLE/HOS/ServiceCtx.cs +++ b/Ryujinx.HLE/HOS/ServiceCtx.cs @@ -7,33 +7,33 @@ namespace Ryujinx.HLE.HOS { class ServiceCtx { - public Switch Device { get; } - public KProcess Process { get; } - public MemoryManager Memory { get; } - public KSession Session { get; } - public IpcMessage Request { get; } - public IpcMessage Response { get; } - public BinaryReader RequestData { get; } - public BinaryWriter ResponseData { get; } + public Switch Device { get; private set; } + public KProcess Process { get; private set; } + public MemoryManager Memory { get; private set; } + public KSession Session { get; private set; } + public IpcMessage Request { get; private set; } + public IpcMessage Response { get; private set; } + public BinaryReader RequestData { get; private set; } + 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) { - Device = device; - Process = process; - Memory = memory; - Session = session; - Request = request; - Response = response; - RequestData = requestData; - ResponseData = 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; } } } \ 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 7ff25c4be..f920c00ba 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IAccountService() { - _commands = new Dictionary + m_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 93b4b4a18..9312b2bc8 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; - public IManagerForApplication(UInt128 uuid) + public IManagerForApplication(UInt128 Uuid) { - _commands = new Dictionary + m_Commands = new Dictionary() { { 0, CheckAvailability }, { 1, GetAccountId } }; - _uuid = uuid; + this.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 c50e95409..1d1a15cbf 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; - private UserProfile _profile; + private UserProfile Profile; - private Stream _profilePictureStream; + private Stream ProfilePictureStream; - public IProfile(UserProfile profile) + public IProfile(UserProfile Profile) { - _commands = new Dictionary + m_Commands = new Dictionary() { { 0, Get }, { 1, GetBase }, { 10, GetImageSize }, - { 11, LoadImage } + { 11, LoadImage }, }; - _profile = profile; + this.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 0d067b169..2d44526a2 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IAllSystemAppletProxiesService() { - _commands = new Dictionary + m_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 eac609ed3..c5ed09f5f 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IApplicationCreator() { - _commands = new Dictionary + m_Commands = new Dictionary() { //... }; diff --git a/Ryujinx.HLE/HOS/Services/Am/IApplicationFunctions.cs b/Ryujinx.HLE/HOS/Services/Am/IApplicationFunctions.cs index fbc5dee5c..1934798b2 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IApplicationFunctions() { - _commands = new Dictionary + m_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 fd785a70f..2aaeda782 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IApplicationProxy() { - _commands = new Dictionary + m_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 88792a165..fb518af93 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IApplicationProxyService() { - _commands = new Dictionary + m_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 a03a32663..062f2d865 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IAudioController() { - _commands = new Dictionary + m_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 8ec421529..2feaf8fc0 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; - private KEvent _displayResolutionChangeEvent; + private KEvent DisplayResolutionChangeEvent; - public ICommonStateGetter(Horizon system) + public ICommonStateGetter(Horizon System) { - _commands = new Dictionary + m_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 f7ea253de..d86743c08 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IDebugFunctions() { - _commands = new Dictionary + m_Commands = new Dictionary() { //... }; diff --git a/Ryujinx.HLE/HOS/Services/Am/IDisplayController.cs b/Ryujinx.HLE/HOS/Services/Am/IDisplayController.cs index 91fd864c5..c4d495793 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IDisplayController() { - _commands = new Dictionary + m_Commands = new Dictionary() { //... }; diff --git a/Ryujinx.HLE/HOS/Services/Am/IGlobalStateController.cs b/Ryujinx.HLE/HOS/Services/Am/IGlobalStateController.cs index b9387661f..e646327fe 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IGlobalStateController() { - _commands = new Dictionary + m_Commands = new Dictionary() { //... }; diff --git a/Ryujinx.HLE/HOS/Services/Am/IHomeMenuFunctions.cs b/Ryujinx.HLE/HOS/Services/Am/IHomeMenuFunctions.cs index db116f334..3f026e2fe 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; - private KEvent _channelEvent; + private KEvent ChannelEvent; - public IHomeMenuFunctions(Horizon system) + public IHomeMenuFunctions(Horizon System) { - _commands = new Dictionary + m_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 7c4aa16c1..9e0d0e707 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; - private KEvent _stateChangedEvent; + private KEvent StateChangedEvent; - public ILibraryAppletAccessor(Horizon system) + public ILibraryAppletAccessor(Horizon System) { - _commands = new Dictionary + m_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 3f88c5455..5535a43c7 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public ILibraryAppletCreator() { - _commands = new Dictionary + m_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 dc9220373..2abaee2e7 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; - private KEvent _launchableEvent; + private KEvent LaunchableEvent; - private int _idleTimeDetectionExtension; + private int IdleTimeDetectionExtension; - public ISelfController(Horizon system) + public ISelfController(Horizon System) { - _commands = new Dictionary + m_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; + bool Enable = Context.RequestData.ReadByte() != 0 ? true : false; Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); return 0; } - public long SetOperationModeChangedNotification(ServiceCtx context) + public long SetOperationModeChangedNotification(ServiceCtx Context) { - bool enable = context.RequestData.ReadByte() != 0; + bool Enable = Context.RequestData.ReadByte() != 0 ? true : false; Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); return 0; } - public long SetPerformanceModeChangedNotification(ServiceCtx context) + public long SetPerformanceModeChangedNotification(ServiceCtx Context) { - bool enable = context.RequestData.ReadByte() != 0; + bool Enable = Context.RequestData.ReadByte() != 0 ? true : false; Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); return 0; } - public long SetFocusHandlingMode(ServiceCtx context) + public long SetFocusHandlingMode(ServiceCtx Context) { - bool flag1 = context.RequestData.ReadByte() != 0; - bool flag2 = context.RequestData.ReadByte() != 0; - bool flag3 = context.RequestData.ReadByte() != 0; + bool Flag1 = Context.RequestData.ReadByte() != 0 ? true : false; + bool Flag2 = Context.RequestData.ReadByte() != 0 ? true : false; + bool Flag3 = Context.RequestData.ReadByte() != 0 ? true : false; Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); return 0; } - public long SetRestartMessageEnabled(ServiceCtx context) + public long SetRestartMessageEnabled(ServiceCtx Context) { - bool enable = context.RequestData.ReadByte() != 0; + bool Enable = Context.RequestData.ReadByte() != 0 ? true : false; Logger.PrintStub(LogClass.ServiceAm, "Stubbed."); return 0; } - public long SetOutOfFocusSuspendingEnabled(ServiceCtx context) + public long SetOutOfFocusSuspendingEnabled(ServiceCtx Context) { - bool enable = context.RequestData.ReadByte() != 0; + bool Enable = Context.RequestData.ReadByte() != 0 ? true : false; 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; + bool Enable = Context.RequestData.ReadByte() != 0 ? true : false; 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 c39a847ba..10778122c 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; - public byte[] Data { get; } + public byte[] Data { get; private set; } - public IStorage(byte[] data) + public IStorage(byte[] Data) { - _commands = new Dictionary + m_Commands = new Dictionary() { { 0, Open } }; - Data = data; + this.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 ac54069a5..a60cf1494 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; - private IStorage _storage; + private IStorage Storage; - public IStorageAccessor(IStorage storage) + public IStorageAccessor(IStorage Storage) { - _commands = new Dictionary + m_Commands = new Dictionary() { { 0, GetSize }, { 10, Write }, { 11, Read } }; - _storage = storage; + this.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 e8a442aec..85e11e0fd 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public ISystemAppletProxy() { - _commands = new Dictionary + m_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 aca7a666e..de5137d12 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IWindowController() { - _commands = new Dictionary + m_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 39a4c6dd9..b97ffc1ec 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 cd86e5169..50822def6 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IManager() { - _commands = new Dictionary + m_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 cef343831..d04bcfc97 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public ISession() { - _commands = new Dictionary + m_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 93bda210e..1ad049c6b 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_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) { - _commands = new Dictionary + m_Commands = new Dictionary() { { 0, GetAudioOutState }, { 1, StartAudioOut }, @@ -34,116 +34,116 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioOut { 8, GetReleasedAudioOutBufferAuto } }; - _audioOut = audioOut; - _releaseEvent = releaseEvent; - _track = track; + this.AudioOut = AudioOut; + this.ReleaseEvent = ReleaseEvent; + this.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 5d90fa5d6..50a87893b 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_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) { - _commands = new Dictionary + m_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); - _memory = memory; - _audioOut = audioOut; - _params = Params; + this.Memory = Memory; + this.AudioOut = AudioOut; + this.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 void AppendMixedBuffer(long tag) + private unsafe 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 static unsafe 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 6a37c1afc..6baf507c0 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 + enum MemoryPoolState : int { 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 9714f6d8b..baa0bc624 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 a877081d5..7d6e1c583 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 585d7e43a..f9c0d315a 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; - private KEvent _systemEvent; + private KEvent SystemEvent; - public IAudioDevice(Horizon system) + public IAudioDevice(Horizon System) { - _commands = new Dictionary + m_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 4b1440a02..b08f7640f 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IAudioOutManager() { - _commands = new Dictionary + m_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 a319537a9..48a449ccc 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IAudioRendererManager() { - _commands = new Dictionary + m_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 fc0bd8db0..a71b8602a 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_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) { - _commands = new Dictionary + m_Commands = new Dictionary() { { 0, DecodeInterleaved }, { 4, DecodeInterleavedWithPerf } }; - _sampleRate = sampleRate; - _channelsCount = channelsCount; + this.SampleRate = SampleRate; + this.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 495c8ab42..875dc74c3 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IHardwareOpusDecoderManager() { - _commands = new Dictionary + m_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 051b75d60..6263dfa81 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IBcatService() { - _commands = new Dictionary + m_Commands = new Dictionary() { //... }; diff --git a/Ryujinx.HLE/HOS/Services/Bcat/IDeliveryCacheStorageService.cs b/Ryujinx.HLE/HOS/Services/Bcat/IDeliveryCacheStorageService.cs index 043cb6074..7a55c6c89 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IDeliveryCacheStorageService() { - _commands = new Dictionary + m_Commands = new Dictionary() { //... }; diff --git a/Ryujinx.HLE/HOS/Services/Bcat/IServiceCreator.cs b/Ryujinx.HLE/HOS/Services/Bcat/IServiceCreator.cs index 6523aa632..55583c940 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IServiceCreator() { - _commands = new Dictionary + m_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 de6fa73fa..15fc7a827 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 aac85021c..37d0fcfdb 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_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) { - _commands = new Dictionary + m_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 }, }; - _isPrivileged = isPrivileged; + this.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,134 +333,135 @@ 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."); @@ -468,452 +469,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: @@ -927,34 +928,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: @@ -968,225 +969,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 ff1ccb29c..49cd4877e 100644 --- a/Ryujinx.HLE/HOS/Services/Bsd/PollEvent.cs +++ b/Ryujinx.HLE/HOS/Services/Bsd/PollEvent.cs @@ -9,20 +9,20 @@ Output = 4, Error = 8, Disconnected = 0x10, - Invalid = 0x20 + Invalid = 0x20, } - public int SocketFd { get; } - public BsdSocket Socket { get; } - public EventTypeMask InputEvents { get; } - public EventTypeMask OutputEvents { get; } + public int SocketFd { get; private set; } + public BsdSocket Socket { get; private set; } + 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) { - SocketFd = socketFd; - Socket = socket; - InputEvents = inputEvents; - OutputEvents = outputEvents; + this.SocketFd = SocketFd; + this.Socket = Socket; + this.InputEvents = InputEvents; + this.OutputEvents = OutputEvents; } } } diff --git a/Ryujinx.HLE/HOS/Services/Caps/IAlbumAccessorService.cs b/Ryujinx.HLE/HOS/Services/Caps/IAlbumAccessorService.cs index 7b334ac4e..6d96b769b 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IAlbumAccessorService() { - _commands = new Dictionary + m_Commands = new Dictionary() { //... }; diff --git a/Ryujinx.HLE/HOS/Services/Caps/IScreenshotService.cs b/Ryujinx.HLE/HOS/Services/Caps/IScreenshotService.cs index 63b155e0e..5a54d5639 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IScreenshotService() { - _commands = new Dictionary + m_Commands = new Dictionary() { //... }; diff --git a/Ryujinx.HLE/HOS/Services/Es/IETicketService.cs b/Ryujinx.HLE/HOS/Services/Es/IETicketService.cs index 049e94dbc..f11c78cca 100644 --- a/Ryujinx.HLE/HOS/Services/Es/IETicketService.cs +++ b/Ryujinx.HLE/HOS/Services/Es/IETicketService.cs @@ -1,19 +1,20 @@ 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; - private bool _isInitialized; + private bool IsInitialized; - public IeTicketService() + public IETicketService() { - _commands = new Dictionary + m_Commands = new Dictionary() { }; diff --git a/Ryujinx.HLE/HOS/Services/Friend/IFriendService.cs b/Ryujinx.HLE/HOS/Services/Friend/IFriendService.cs index 983481253..e20de267f 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IFriendService() { - _commands = new Dictionary + m_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 d7f999973..065e230dc 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IServiceCreator() { - _commands = new Dictionary + m_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 bdb0c1cd9..74ebddc21 100644 --- a/Ryujinx.HLE/HOS/Services/FspSrv/DirectoryEntry.cs +++ b/Ryujinx.HLE/HOS/Services/FspSrv/DirectoryEntry.cs @@ -1,17 +1,21 @@ -namespace Ryujinx.HLE.HOS.Services.FspSrv +using System; +using System.Collections.Generic; +using System.Text; + +namespace Ryujinx.HLE.HOS.Services.FspSrv { public struct DirectoryEntry { - public string Path { get; } - public long Size { get; } + public string Path { get; private set; } + public long Size { get; private set; } public DirectoryEntryType EntryType { get; set; } - public DirectoryEntry(string path, DirectoryEntryType directoryEntryType, long size = 0) + public DirectoryEntry(string Path, DirectoryEntryType DirectoryEntryType, long Size = 0) { - Path = path; - EntryType = directoryEntryType; - Size = size; + this.Path = Path; + EntryType = DirectoryEntryType; + this.Size = Size; } } } diff --git a/Ryujinx.HLE/HOS/Services/FspSrv/FileSystemType.cs b/Ryujinx.HLE/HOS/Services/FspSrv/FileSystemType.cs index 20fc9bdc4..2fd596734 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 + enum FileSystemType : int { Logo = 2, ContentControl = 3, diff --git a/Ryujinx.HLE/HOS/Services/FspSrv/IDirectory.cs b/Ryujinx.HLE/HOS/Services/FspSrv/IDirectory.cs index e5dcd8b1a..c964eecba 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; - private List _directoryEntries; + private List DirectoryEntries; - private int _currentItemIndex; + private int CurrentItemIndex; public event EventHandler Disposed; - public string DirectoryPath { get; } + 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) { - _commands = new Dictionary + m_Commands = new Dictionary() { { 0, Read }, { 1, GetEntryCount } }; - _provider = provider; - DirectoryPath = directoryPath; + this.Provider = Provider; + this.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 03cfad998..9bf152c4c 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; - private Stream _baseStream; + private Stream BaseStream; public event EventHandler Disposed; - public string HostPath { get; } + public string HostPath { get; private set; } - public IFile(Stream baseStream, string hostPath) + public IFile(Stream BaseStream, string HostPath) { - _commands = new Dictionary + m_Commands = new Dictionary() { { 0, Read }, { 1, Write }, @@ -28,71 +28,71 @@ namespace Ryujinx.HLE.HOS.Services.FspSrv { 4, GetSize } }; - _baseStream = baseStream; - HostPath = hostPath; + this.BaseStream = BaseStream; + this.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 9e2944601..edcdfa58c 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_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) { - _commands = new Dictionary + m_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(); - _path = path; - _provider = provider; + this.Path = Path; + this.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 8764792c3..0fc1eb80e 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IFileSystemProxy() { - _commands = new Dictionary + m_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 d000635de..6a78cdfe0 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; - private Stream _baseStream; + private Stream BaseStream; - public IStorage(Stream baseStream) + public IStorage(Stream BaseStream) { - _commands = new Dictionary + m_Commands = new Dictionary() { { 0, Read } }; - _baseStream = baseStream; + this.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 14bff3150..d27318573 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 9a22ff01a..cb2427e73 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 586b852d6..6e666919d 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IActiveApplicationDeviceList() { - _commands = new Dictionary + m_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 e82b824eb..89a17acf7 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; - private KSharedMemory _hidSharedMem; + private KSharedMemory HidSharedMem; - public IAppletResource(KSharedMemory hidSharedMem) + public IAppletResource(KSharedMemory HidSharedMem) { - _commands = new Dictionary + m_Commands = new Dictionary() { { 0, GetSharedMemoryHandle } }; - _hidSharedMem = hidSharedMem; + this.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 4e14943bc..1af734ffc 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 _commands; + private Dictionary m_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 => _commands; + public override IReadOnlyDictionary Commands => m_Commands; - public IHidServer(Horizon system) + public IHidServer(Horizon System) { - _commands = new Dictionary + m_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(); + long AppletResourceUserId = Context.RequestData.ReadInt64(); + + Logger.PrintStub(LogClass.ServiceHid, $"Stubbed. AppletResourceUserId: {AppletResourceUserId}"); - 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 ec43430e3..60a4431e9 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 d6683877f..155faea3e 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; - private bool _activated; + private bool Activated; public IIrSensorServer() { - _commands = new Dictionary + m_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 b0eebe539..f0899bd40 100644 --- a/Ryujinx.HLE/HOS/Services/Ldr/IRoInterface.cs +++ b/Ryujinx.HLE/HOS/Services/Ldr/IRoInterface.cs @@ -4,6 +4,7 @@ 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; @@ -50,54 +51,54 @@ namespace Ryujinx.HLE.HOS.Services.Ldr class NrrInfo { - public NrrHeader Header { get; } - public List Hashes { get; } - public long NrrAddress { get; } + public NrrHeader Header { get; private set; } + 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) { - NrrAddress = nrrAddress; - Header = header; - Hashes = hashes; + this.NrrAddress = NrrAddress; + this.Header = Header; + this.Hashes = Hashes; } } class NroInfo { - public NxRelocatableObject Executable { get; } + public NxRelocatableObject Executable { get; private set; } - public byte[] Hash { get; } - public ulong NroAddress { get; } - public ulong NroSize { get; } - public ulong BssAddress { get; } - public ulong BssSize { get; } - public ulong TotalSize { get; } + public byte[] Hash { get; private set; } + public ulong NroAddress { get; private set; } + public ulong NroSize { get; private set; } + public ulong BssAddress { get; private set; } + public ulong BssSize { get; private set; } + public ulong TotalSize { get; private set; } 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) { - Executable = executable; - Hash = hash; - NroAddress = nroAddress; - NroSize = nroSize; - BssAddress = bssAddress; - BssSize = bssSize; - TotalSize = totalSize; + this.Executable = Executable; + this.Hash = Hash; + this.NroAddress = NroAddress; + this.NroSize = NroSize; + this.BssAddress = BssAddress; + this.BssSize = BssSize; + this.TotalSize = TotalSize; } } class IRoInterface : IpcService { - private Dictionary _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; private const int MaxNrr = 0x40; private const int MaxNro = 0x40; @@ -105,70 +106,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() { - _commands = new Dictionary + m_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; } @@ -178,11 +179,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; } @@ -191,206 +192,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; } @@ -399,46 +400,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; } } @@ -446,125 +447,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 37621c317..d79da5157 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public ILogService() { - _commands = new Dictionary + m_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 070cf9aed..20579dfd5 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public ILogger() { - _commands = new Dictionary + m_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 6c2f19709..dc057bc1e 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; - private StorageId _storageId; + private StorageId StorageId; - public ILocationResolver(StorageId storageId) + public ILocationResolver(StorageId StorageId) { - _commands = new Dictionary + m_Commands = new Dictionary() { { 0, ResolveProgramPath }, { 1, RedirectProgramPath }, @@ -40,103 +40,103 @@ namespace Ryujinx.HLE.HOS.Services.Lr { 15, DeleteInfoHtmlNcaPath } }; - _storageId = storageId; + this.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 4b2de6b38..77710f760 100644 --- a/Ryujinx.HLE/HOS/Services/Lr/ILocationResolverManager.cs +++ b/Ryujinx.HLE/HOS/Services/Lr/ILocationResolverManager.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using Ryujinx.HLE.HOS.Ipc; using Ryujinx.HLE.FileSystem; @@ -6,24 +7,24 @@ namespace Ryujinx.HLE.HOS.Services.Lr { class ILocationResolverManager : IpcService { - private Dictionary _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public ILocationResolverManager() { - _commands = new Dictionary + m_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 a92106cf9..72067d71a 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IRequest() { - _commands = new Dictionary + m_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 bd92a4506..29792a1ba 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IContentManager() { - _commands = new Dictionary + m_Commands = new Dictionary() { }; diff --git a/Ryujinx.HLE/HOS/Services/Ncm/IContentStorage.cs b/Ryujinx.HLE/HOS/Services/Ncm/IContentStorage.cs index 7134bb4ce..a19fe079d 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IContentStorage() { - _commands = new Dictionary + m_Commands = new Dictionary() { }; diff --git a/Ryujinx.HLE/HOS/Services/Nfp/IUser.cs b/Ryujinx.HLE/HOS/Services/Nfp/IUser.cs index 9e19e77f8..f0dc825b0 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; - private const HidControllerId NpadId = HidControllerId.ControllerPlayer1; + private const HidControllerId NpadId = HidControllerId.CONTROLLER_PLAYER_1; - 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) { - _commands = new Dictionary + m_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 1bf937466..e5d5a4f1c 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IUserManager() { - _commands = new Dictionary + m_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 4b87c2c73..bc23ea910 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IGeneralService() { - _commands = new Dictionary + m_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 52adce9e7..983278604 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; - private KEvent _event0; - private KEvent _event1; + private KEvent Event0; + private KEvent Event1; - public IRequest(Horizon system) + public IRequest(Horizon System) { - _commands = new Dictionary + m_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 42d9c78e7..19e7d2470 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IStaticService() { - _commands = new Dictionary + m_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 8bbd0deac..82fce6b98 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IAddOnContentManager() { - _commands = new Dictionary + m_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 72d7787f8..ee438d993 100644 --- a/Ryujinx.HLE/HOS/Services/Ns/IApplicationManagerInterface.cs +++ b/Ryujinx.HLE/HOS/Services/Ns/IApplicationManagerInterface.cs @@ -1,19 +1,20 @@ 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; - private bool _isInitialized; + private bool IsInitialized; public IApplicationManagerInterface() { - _commands = new Dictionary + m_Commands = new Dictionary() { }; diff --git a/Ryujinx.HLE/HOS/Services/Ns/IServiceGetterInterface.cs b/Ryujinx.HLE/HOS/Services/Ns/IServiceGetterInterface.cs index 12f7b69b1..a27cfe607 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IServiceGetterInterface() { - _commands = new Dictionary + m_Commands = new Dictionary() { //... }; diff --git a/Ryujinx.HLE/HOS/Services/Ns/ISystemUpdateInterface.cs b/Ryujinx.HLE/HOS/Services/Ns/ISystemUpdateInterface.cs index 1b8985617..6ade88650 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public ISystemUpdateInterface() { - _commands = new Dictionary + m_Commands = new Dictionary() { //... }; diff --git a/Ryujinx.HLE/HOS/Services/Ns/IVulnerabilityManagerInterface.cs b/Ryujinx.HLE/HOS/Services/Ns/IVulnerabilityManagerInterface.cs index 922703ec4..cff334c0c 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IVulnerabilityManagerInterface() { - _commands = new Dictionary + m_Commands = new Dictionary() { //... }; diff --git a/Ryujinx.HLE/HOS/Services/Nv/INvDrvServices.cs b/Ryujinx.HLE/HOS/Services/Nv/INvDrvServices.cs index a8459cf4f..1b034bfa8 100644 --- a/Ryujinx.HLE/HOS/Services/Nv/INvDrvServices.cs +++ b/Ryujinx.HLE/HOS/Services/Nv/INvDrvServices.cs @@ -14,15 +14,15 @@ 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; - private static Dictionary _ioctlProcessors = - new Dictionary - { + private static Dictionary IoctlProcessors = + new Dictionary() + { { "/dev/nvhost-as-gpu", ProcessIoctlNvGpuAS }, { "/dev/nvhost-ctrl", ProcessIoctlNvHostCtrl }, { "/dev/nvhost-ctrl-gpu", ProcessIoctlNvGpuGpu }, @@ -32,13 +32,13 @@ namespace Ryujinx.HLE.HOS.Services.Nv { "/dev/nvmap", ProcessIoctlNvMap } }; - public static GlobalStateTable Fds { get; } + public static GlobalStateTable Fds { get; private set; } - private KEvent _event; + private KEvent Event; - public INvDrvServices(Horizon system) + public INvDrvServices(Horizon System) { - _commands = new Dictionary + m_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 0f7e4acd1..96f97f41e 100644 --- a/Ryujinx.HLE/HOS/Services/Nv/NvFd.cs +++ b/Ryujinx.HLE/HOS/Services/Nv/NvFd.cs @@ -2,11 +2,11 @@ namespace Ryujinx.HLE.HOS.Services.Nv { class NvFd { - public string Name { get; } + public string Name { get; private set; } - public NvFd(string name) + public NvFd(string Name) { - Name = name; + this.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 cd1ab7cdb..70275b2a9 100644 --- a/Ryujinx.HLE/HOS/Services/Nv/NvGpuAS/NvGpuASCtx.cs +++ b/Ryujinx.HLE/HOS/Services/Nv/NvGpuAS/NvGpuASCtx.cs @@ -5,73 +5,73 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvGpuAS { class NvGpuASCtx { - public NvGpuVmm Vmm { get; } + public NvGpuVmm Vmm { get; private set; } private class Range { - public ulong Start { get; } - public ulong End { get; } + 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; } } private class MappedMemory : Range { - public long PhysicalAddress { get; } - public bool VaAllocated { get; } + public long PhysicalAddress { get; private set; } + 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) { - PhysicalAddress = physicalAddress; - VaAllocated = vaAllocated; + this.PhysicalAddress = PhysicalAddress; + this.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 8e128a0d3..7fe3bbedb 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 5680fb8eb..7ee770f4c 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 140e8c968..466f3e9bf 100644 --- a/Ryujinx.HLE/HOS/Services/Nv/NvHostChannel/NvHostChannelIoctl.cs +++ b/Ryujinx.HLE/HOS/Services/Nv/NvHostChannel/NvHostChannelIoctl.cs @@ -11,57 +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 0x480b: return ZcullBind (context); - case 0x480c: return SetErrorNotifier (context); - case 0x4803: return SetTimeout (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. @@ -69,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; } } } @@ -169,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 f13f7a68d..bf92afb40 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/NvHostCtrlUserCtx.cs b/Ryujinx.HLE/HOS/Services/Nv/NvHostCtrl/NvHostCtrlUserCtx.cs index aa4577ed9..fcb808369 100644 --- a/Ryujinx.HLE/HOS/Services/Nv/NvHostCtrl/NvHostCtrlUserCtx.cs +++ b/Ryujinx.HLE/HOS/Services/Nv/NvHostCtrl/NvHostCtrlUserCtx.cs @@ -5,9 +5,9 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvHostCtrl public const int LocksCount = 16; public const int EventsCount = 64; - public NvHostSyncpt Syncpt { get; } + public NvHostSyncpt Syncpt { get; private set; } - public NvHostEvent[] Events { get; } + public NvHostEvent[] Events { get; private set; } public NvHostCtrlUserCtx() { diff --git a/Ryujinx.HLE/HOS/Services/Nv/NvHostCtrl/NvHostSyncPt.cs b/Ryujinx.HLE/HOS/Services/Nv/NvHostCtrl/NvHostSyncPt.cs index d27f7c534..9ffa93f25 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 31bf8329b..e97e4ff44 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() { - Size = size; + this.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 75a76b91d..adc523e50 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 0c539aa13..3e9d276ae 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_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) { - _commands = new Dictionary + m_Commands = new Dictionary() { { 1, Initialize } }; - _needInitialize = needInitialize; + this.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 92500187c..157d594d2 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IParentalControlServiceFactory() { - _commands = new Dictionary + m_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 c555c504e..0495a388a 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public ISharedFontManager() { - _commands = new Dictionary + m_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, type, offset)) + if (!AddFontToOrderOfPriorityList(Context, (SharedFontType)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 f8198fa95..cc96a5c92 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IPrepoService() { - _commands = new Dictionary + m_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 c7f6083c4..0b45e3c9d 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 + enum ChargerType : int { None, ChargerOrDock, UsbC } - private Dictionary _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IPsmServer() { - _commands = new Dictionary + m_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 4763f2d5c..30e5d5322 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; - private KEvent _stateChangeEvent; - private int _stateChangeEventHandle; + private KEvent StateChangeEvent; + private int StateChangeEventHandle; - public IPsmSession(Horizon system) + public IPsmSession(Horizon System) { - _commands = new Dictionary + m_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 3853d82e6..2be1db701 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 bc812d5cb..690d6de93 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public ISettingsServer() { - _commands = new Dictionary + m_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 b4464b779..416ea1fb7 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public ISystemSettingsServer() { - _commands = new Dictionary + m_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 70ab55f9d..7d1dd2ed7 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 2d3d8e9b9..65d545770 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 5de035515..a351e3dec 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IResolver() { - _commands = new Dictionary + m_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 dad02cf29..6c1b7825d 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 2bfafd955..0c26b7d9d 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; - private bool _isInitialized; + private bool IsInitialized; public IUserInterface() { - _commands = new Dictionary + m_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 cae8d8d02..6391d981c 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; - private RNGCryptoServiceProvider _rng; + private RNGCryptoServiceProvider Rng; public IRandomInterface() { - _commands = new Dictionary + m_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 cf58ed87b..8f3a0649b 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public ISslContext() { - _commands = new Dictionary + m_Commands = new Dictionary() { //... }; diff --git a/Ryujinx.HLE/HOS/Services/Ssl/ISslService.cs b/Ryujinx.HLE/HOS/Services/Ssl/ISslService.cs index b40e94733..3046aab7a 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public ISslService() { - _commands = new Dictionary + m_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 fcbaa4921..66f16501c 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; private static readonly DateTime StartupDate = DateTime.UtcNow; public IStaticService() { - _commands = new Dictionary + m_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 f535ed9cf..e4020bb14 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; - private ulong _testOffset; + private ulong TestOffset; public ISteadyClock() { - _commands = new Dictionary + m_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 1dfd7d74f..f574826a0 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_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) { - _commands = new Dictionary + m_Commands = new Dictionary() { { 0, GetCurrentTime }, { 1, SetCurrentTime }, @@ -32,74 +32,74 @@ namespace Ryujinx.HLE.HOS.Services.Time { 3, SetSystemClockContext } }; - _clockType = clockType; - _systemClockContextEpoch = System.Diagnostics.Process.GetCurrentProcess().StartTime; - _systemClockContextEnding = new byte[0x10]; - _timeOffset = 0; + this.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 563a9753c..0e321e44c 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_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() { - _commands = new Dictionary + m_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 54e007896..50fe5e1d1 100644 --- a/Ryujinx.HLE/HOS/Services/Vi/Display.cs +++ b/Ryujinx.HLE/HOS/Services/Vi/Display.cs @@ -2,11 +2,11 @@ namespace Ryujinx.HLE.HOS.Services.Vi { class Display { - public string Name { get; } + public string Name { get; private set; } - public Display(string name) + public Display(string Name) { - Name = name; + this.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 4a247d1be..4f00c3de4 100644 --- a/Ryujinx.HLE/HOS/Services/Vi/GbpBuffer.cs +++ b/Ryujinx.HLE/HOS/Services/Vi/GbpBuffer.cs @@ -4,57 +4,57 @@ namespace Ryujinx.HLE.HOS.Services.Android { struct GbpBuffer { - public int Magic { get; } - public int Width { get; } - public int Height { get; } - public int Stride { get; } - public int Format { get; } - public int Usage { get; } + public int Magic { get; private set; } + public int Width { get; private set; } + public int Height { get; private set; } + public int Stride { get; private set; } + public int Format { get; private set; } + public int Usage { get; private set; } - public int Pid { get; } - public int RefCount { get; } + public int Pid { get; private set; } + public int RefCount { get; private set; } - public int FdsCount { get; } - public int IntsCount { get; } + public int FdsCount { get; private set; } + public int IntsCount { get; private set; } - public byte[] RawData { get; } + public byte[] RawData { get; private set; } 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 63e542d24..5d1ddd84b 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; - private IdDictionary _displays; + private IdDictionary Displays; public IApplicationDisplayService() { - _commands = new Dictionary + m_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 66ab16bdd..e86734e6e 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IApplicationRootService() { - _commands = new Dictionary + m_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 7ca3053d9..09a37b0f7 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_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) { - _commands = new Dictionary + m_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 369c376f9..a78f1812f 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IManagerDisplayService() { - _commands = new Dictionary + m_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 0f0a4f264..14b8fc3c3 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public IManagerRootService() { - _commands = new Dictionary + m_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 5266a2536..4545579be 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public ISystemDisplayService() { - _commands = new Dictionary + m_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 5e255ce5a..d9b7c220b 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 _commands; + private Dictionary m_Commands; - public override IReadOnlyDictionary Commands => _commands; + public override IReadOnlyDictionary Commands => m_Commands; public ISystemRootService() { - _commands = new Dictionary + m_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 1b57b3319..facfbe60b 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 } }; - _renderer = renderer; - _binderEvent = binderEvent; + this.Renderer = Renderer; + this.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 63c5a82ff..bb8427959 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 3a4fa3c56..274892c08 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; } + 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 74513795e..aa96a4163 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 cbf6034d3..e08bc48aa 100644 --- a/Ryujinx.HLE/HOS/SystemState/UserProfile.cs +++ b/Ryujinx.HLE/HOS/SystemState/UserProfile.cs @@ -7,19 +7,19 @@ namespace Ryujinx.HLE.HOS.SystemState { private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); - public UInt128 Uuid { get; } + public UInt128 Uuid { get; private set; } - public string Name { get; } + public string Name { get; private set; } public long LastModifiedTimestamp { get; private set; } public OpenCloseState AccountState { get; set; } public OpenCloseState OnlinePlayState { get; set; } - public UserProfile(UInt128 uuid, string name) + public UserProfile(UInt128 Uuid, string Name) { - Uuid = uuid; - Name = name; + this.Uuid = Uuid; + this.Name = Name; LastModifiedTimestamp = 0; diff --git a/Ryujinx.HLE/Input/Hid.cs b/Ryujinx.HLE/Input/Hid.cs index c35fb07cd..edcfe42d2 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) { - _device = device; - HidPosition = hidPosition; + this.Device = Device; + this.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.ControllerHandheld : HidControllerId.ControllerPlayer1; + HidControllerId ControllerId = ControllerType == HidControllerType.Handheld ? + HidControllerId.CONTROLLER_HANDHELD : HidControllerId.CONTROLLER_PLAYER_1; - if (controllerType == HidControllerType.ProController) + if (ControllerType == HidControllerType.ProController) { - PrimaryController = new HidProController(_device); + PrimaryController = new HidProController(Device); } else { - PrimaryController = new HidNpadController(controllerType, - _device, - (NpadColor.BodyNeonRed, NpadColor.BodyNeonRed), - (NpadColor.ButtonsNeonBlue, NpadColor.ButtonsNeonBlue)); + PrimaryController = new HidNpadController(ControllerType, + Device, + (NpadColor.Body_Neon_Red, NpadColor.Body_Neon_Red), + (NpadColor.Buttons_Neon_Blue, NpadColor.Buttons_Neon_Blue)); } - 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 8b29d8918..9b9bb7ea9 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) { - Device = device; + this.Device = Device; - HidControllerType = controllerType; + HidControllerType = ControllerType; } - public virtual void Connect(HidControllerId controllerId) + public virtual void Connect(HidControllerId ControllerId) { - ControllerId = controllerId; + this.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 85ece5f11..b8cf2a5e9 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 { - ColorDescColorsNonexistent = (1 << 1) + ColorDesc_ColorsNonexistent = (1 << 1) } } \ No newline at end of file diff --git a/Ryujinx.HLE/Input/HidControllerConnState.cs b/Ryujinx.HLE/Input/HidControllerConnState.cs index ef41cbb80..1fc9482a0 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 { - ControllerStateConnected = (1 << 0), - ControllerStateWired = (1 << 1) + Controller_State_Connected = (1 << 0), + Controller_State_Wired = (1 << 1) } } \ No newline at end of file diff --git a/Ryujinx.HLE/Input/HidControllerId.cs b/Ryujinx.HLE/Input/HidControllerId.cs index 60faf822d..e4a0e26cb 100644 --- a/Ryujinx.HLE/Input/HidControllerId.cs +++ b/Ryujinx.HLE/Input/HidControllerId.cs @@ -2,15 +2,15 @@ namespace Ryujinx.HLE.Input { public enum HidControllerId { - ControllerPlayer1 = 0, - ControllerPlayer2 = 1, - ControllerPlayer3 = 2, - ControllerPlayer4 = 3, - ControllerPlayer5 = 4, - ControllerPlayer6 = 5, - ControllerPlayer7 = 6, - ControllerPlayer8 = 7, - ControllerHandheld = 8, - ControllerUnknown = 9 + 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 } } \ No newline at end of file diff --git a/Ryujinx.HLE/Input/HidControllerLayouts.cs b/Ryujinx.HLE/Input/HidControllerLayouts.cs index 3548175f6..39fdd3feb 100644 --- a/Ryujinx.HLE/Input/HidControllerLayouts.cs +++ b/Ryujinx.HLE/Input/HidControllerLayouts.cs @@ -2,12 +2,12 @@ namespace Ryujinx.HLE.Input { public enum HidControllerLayouts { - ProController = 0, - HandheldJoined = 1, - Joined = 2, - Left = 3, - Right = 4, - MainNoAnalog = 5, - Main = 6 + Pro_Controller = 0, + Handheld_Joined = 1, + Joined = 2, + Left = 3, + Right = 4, + Main_No_Analog = 5, + Main = 6 } } \ No newline at end of file diff --git a/Ryujinx.HLE/Input/HidJoystickPosition.cs b/Ryujinx.HLE/Input/HidJoystickPosition.cs index a1fe16087..a06ef7b2c 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 90cffbdd7..7b3fa64c4 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) { - _npadBodyColors = npadBodyColors; - _npadButtonColors = npadButtonColors; + this.NpadBodyColors = NpadBodyColors; + this.NpadButtonColors = NpadButtonColors; - _currentLayout = HidControllerLayouts.HandheldJoined; + CurrentLayout = HidControllerLayouts.Handheld_Joined; - 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.HandheldJoined ? HidControllerId.ControllerHandheld : controllerId); + base.Connect(CurrentLayout == HidControllerLayouts.Handheld_Joined ? HidControllerId.CONTROLLER_HANDHELD : ControllerId); - HidControllerColorDesc singleColorDesc = - HidControllerColorDesc.ColorDescColorsNonexistent; + HidControllerColorDesc SingleColorDesc = + HidControllerColorDesc.ColorDesc_ColorsNonexistent; - 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.ControllerStateConnected : 0) | - (_currentLayout == HidControllerLayouts.HandheldJoined ? (uint)HidControllerConnState.ControllerStateWired : 0)); + Device.Memory.WriteInt64(ControllerOffset + 0x28, + (Connected ? (uint)HidControllerConnState.Controller_State_Connected : 0) | + (CurrentLayout == HidControllerLayouts.Handheld_Joined ? (uint)HidControllerConnState.Controller_State_Wired : 0)); } } } diff --git a/Ryujinx.HLE/Input/HidProController.cs b/Ryujinx.HLE/Input/HidProController.cs index f08fb0857..40c79fede 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.ColorDescColorsNonexistent; + HidControllerColorDesc SingleColorDesc = + HidControllerColorDesc.ColorDesc_ColorsNonexistent; - 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.ProController); + long ControllerOffset = WriteInput(Buttons, LeftStick, RightStick, HidControllerLayouts.Pro_Controller); - Device.Memory.WriteInt64(controllerOffset + 0x28, - (Connected ? (uint)HidControllerConnState.ControllerStateConnected : 0) | - (_wired ? (uint)HidControllerConnState.ControllerStateWired : 0)); + Device.Memory.WriteInt64(ControllerOffset + 0x28, + (Connected ? (uint)HidControllerConnState.Controller_State_Connected : 0) | + (Wired ? (uint)HidControllerConnState.Controller_State_Wired : 0)); } } } diff --git a/Ryujinx.HLE/Input/HidValues.cs b/Ryujinx.HLE/Input/HidValues.cs index ae02bb42e..62bf07077 100644 --- a/Ryujinx.HLE/Input/HidValues.cs +++ b/Ryujinx.HLE/Input/HidValues.cs @@ -1,4 +1,8 @@ -namespace Ryujinx.HLE.Input +using System; +using System.Collections.Generic; +using System.Text; + +namespace Ryujinx.HLE.Input { public partial class Hid { diff --git a/Ryujinx.HLE/Input/IHidDevice.cs b/Ryujinx.HLE/Input/IHidDevice.cs index 0b07e767f..cc67b01a5 100644 --- a/Ryujinx.HLE/Input/IHidDevice.cs +++ b/Ryujinx.HLE/Input/IHidDevice.cs @@ -1,4 +1,8 @@ -namespace Ryujinx.HLE.Input +using System; +using System.Collections.Generic; +using System.Text; + +namespace Ryujinx.HLE.Input { interface IHidDevice { diff --git a/Ryujinx.HLE/Input/NpadColor.cs b/Ryujinx.HLE/Input/NpadColor.cs index b15c45d82..b152b789e 100644 --- a/Ryujinx.HLE/Input/NpadColor.cs +++ b/Ryujinx.HLE/Input/NpadColor.cs @@ -4,20 +4,20 @@ namespace Ryujinx.HLE.Input { Black = 0, - BodyGrey = 0x828282, - BodyNeonBlue = 0x0AB9E6, - BodyNeonRed = 0xFF3C28, - BodyNeonYellow = 0xE6FF00, - BodyNeonPink = 0xFF3278, - BodyNeonGreen = 0x1EDC00, - BodyRed = 0xE10F00, + 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, - ButtonsGrey = 0x0F0F0F, - ButtonsNeonBlue = 0x001E1E, - ButtonsNeonRed = 0x1E0A0A, - ButtonsNeonYellow = 0x142800, - ButtonsNeonPink = 0x28001E, - ButtonsNeonGreen = 0x002800, - ButtonsRed = 0x280A0A + 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 } } \ No newline at end of file diff --git a/Ryujinx.HLE/Loaders/Compression/BackwardsLz.cs b/Ryujinx.HLE/Loaders/Compression/BackwardsLz.cs index 166ae60a9..43cc601fd 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) { - _baseStream = baseStream; + this.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 e405b107b..cfb495517 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 bcf79901e..fb0ea53e0 100644 --- a/Ryujinx.HLE/Loaders/Elf/ElfDynamic.cs +++ b/Ryujinx.HLE/Loaders/Elf/ElfDynamic.cs @@ -2,14 +2,14 @@ namespace Ryujinx.HLE.Loaders.Elf { struct ElfDynamic { - public ElfDynamicTag Tag { get; } + public ElfDynamicTag Tag { get; private set; } - public long Value { get; } + public long Value { get; private set; } - public ElfDynamic(ElfDynamicTag tag, long value) + public ElfDynamic(ElfDynamicTag Tag, long Value) { - Tag = tag; - Value = value; + this.Tag = Tag; + this.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 eb37d612d..9d7ad72e0 100644 --- a/Ryujinx.HLE/Loaders/Elf/ElfDynamicTag.cs +++ b/Ryujinx.HLE/Loaders/Elf/ElfDynamicTag.cs @@ -1,8 +1,5 @@ -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 9f47e3533..3f3a2a790 100644 --- a/Ryujinx.HLE/Loaders/Elf/ElfSymbol.cs +++ b/Ryujinx.HLE/Loaders/Elf/ElfSymbol.cs @@ -2,39 +2,39 @@ namespace Ryujinx.HLE.Loaders.Elf { struct ElfSymbol { - public string Name { get; } + public string Name { get; private set; } - public ElfSymbolType Type { get; } - public ElfSymbolBinding Binding { get; } - public ElfSymbolVisibility Visibility { get; } + public ElfSymbolType Type { get; private set; } + public ElfSymbolBinding Binding { get; private set; } + public ElfSymbolVisibility Visibility { get; private set; } public bool IsFuncOrObject => - Type == ElfSymbolType.SttFunc || - Type == ElfSymbolType.SttObject; + Type == ElfSymbolType.STT_FUNC || + Type == ElfSymbolType.STT_OBJECT; public bool IsGlobalOrWeak => - Binding == ElfSymbolBinding.StbGlobal || - Binding == ElfSymbolBinding.StbWeak; + Binding == ElfSymbolBinding.STB_GLOBAL || + Binding == ElfSymbolBinding.STB_WEAK; - public int ShIdx { get; } - public long Value { get; } - public long Size { get; } + 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) { - Name = name; - Type = (ElfSymbolType)(info & 0xf); - Binding = (ElfSymbolBinding)(info >> 4); - Visibility = (ElfSymbolVisibility)other; - ShIdx = shIdx; - Value = value; - Size = 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; } } } \ No newline at end of file diff --git a/Ryujinx.HLE/Loaders/Elf/ElfSymbolBinding.cs b/Ryujinx.HLE/Loaders/Elf/ElfSymbolBinding.cs index 92274fded..3c915311e 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 { - StbLocal = 0, - StbGlobal = 1, - StbWeak = 2 + STB_LOCAL = 0, + STB_GLOBAL = 1, + STB_WEAK = 2 } } \ No newline at end of file diff --git a/Ryujinx.HLE/Loaders/Elf/ElfSymbolType.cs b/Ryujinx.HLE/Loaders/Elf/ElfSymbolType.cs index 4110d4c3e..f22e6c45f 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 { - SttNoType = 0, - SttObject = 1, - SttFunc = 2, - SttSection = 3, - SttFile = 4, - SttCommon = 5, - SttTls = 6 + STT_NOTYPE = 0, + STT_OBJECT = 1, + STT_FUNC = 2, + STT_SECTION = 3, + STT_FILE = 4, + STT_COMMON = 5, + STT_TLS = 6 } } \ No newline at end of file diff --git a/Ryujinx.HLE/Loaders/Elf/ElfSymbolVisibility.cs b/Ryujinx.HLE/Loaders/Elf/ElfSymbolVisibility.cs index f026fca89..4bec50a37 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 { - StvDefault = 0, - StvInternal = 1, - StvHidden = 2, - StvProtected = 3 + STV_DEFAULT = 0, + STV_INTERNAL = 1, + STV_HIDDEN = 2, + STV_PROTECTED = 3 } } \ No newline at end of file diff --git a/Ryujinx.HLE/Loaders/Executables/IExecutable.cs b/Ryujinx.HLE/Loaders/Executables/IExecutable.cs index 440e8f5fa..d3eefde60 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 d5ab2e8d0..1395d56f8 100644 --- a/Ryujinx.HLE/Loaders/Executables/KernelInitialProcess.cs +++ b/Ryujinx.HLE/Loaders/Executables/KernelInitialProcess.cs @@ -5,145 +5,145 @@ namespace Ryujinx.HLE.Loaders.Executables { class KernelInitialProcess : IExecutable { - public string Name { get; } + public string Name { get; private set; } - public long TitleId { get; } + public long TitleId { get; private set; } - public int ProcessCategory { get; } + public int ProcessCategory { get; private set; } - public byte MainThreadPriority { get; } - public byte DefaultProcessorId { get; } + public byte MainThreadPriority { get; private set; } + public byte DefaultProcessorId { get; private set; } - public bool Is64Bits { get; } - public bool Addr39Bits { get; } - public bool IsService { get; } + public bool Is64Bits { get; private set; } + public bool Addr39Bits { get; private set; } + public bool IsService { get; private set; } - public byte[] Text { get; } - public byte[] Ro { get; } - public byte[] Data { get; } + public byte[] Text { get; private set; } + public byte[] RO { get; private set; } + public byte[] Data { get; private set; } - public int TextOffset { get; } - public int RoOffset { get; } - public int DataOffset { get; } - public int BssOffset { get; } - public int BssSize { get; } + public int TextOffset { 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; } - public int MainThreadStackSize { get; } + public int MainThreadStackSize { get; private set; } - public int[] Capabilities { get; } + public int[] Capabilities { get; private set; } private struct SegmentHeader { - public int Offset { get; } - public int DecompressedSize { get; } - public int CompressedSize { get; } - public int Attribute { get; } + public int Offset { get; private set; } + public int DecompressedSize { get; private set; } + public int CompressedSize { get; private set; } + public int Attribute { get; private set; } public SegmentHeader( - int offset, - int decompressedSize, - int compressedSize, - int attribute) + int Offset, + int DecompressedSize, + int CompressedSize, + int Attribute) { - Offset = offset; - DecompressedSize = decompressedSize; - CompressedSize = compressedSize; - Attribute = attribute; + this.Offset = Offset; + this.DecompressedSize = DecompressedSize; + this.CompressedSize = CompressedSize; + this.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 071a6fd9d..20de5b5d9 100644 --- a/Ryujinx.HLE/Loaders/Executables/NxRelocatableObject.cs +++ b/Ryujinx.HLE/Loaders/Executables/NxRelocatableObject.cs @@ -4,61 +4,61 @@ namespace Ryujinx.HLE.Loaders.Executables { class NxRelocatableObject : IExecutable { - public byte[] Text { get; } - public byte[] Ro { get; } - public byte[] Data { get; } + public byte[] Text { get; private set; } + public byte[] RO { get; private set; } + public byte[] Data { get; private set; } - public int Mod0Offset { get; } - public int TextOffset { get; } - public int RoOffset { get; } - public int DataOffset { get; } - public int BssSize { get; } + public int Mod0Offset { get; private set; } + public int TextOffset { get; private set; } + public int ROOffset { get; private set; } + public int DataOffset { get; private set; } + public int BssSize { get; private set; } public int BssOffset => DataOffset + Data.Length; - public ulong SourceAddress { get; } - public ulong BssAddress { get; } + 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) { - SourceAddress = sourceAddress; - BssAddress = bssAddress; + this.SourceAddress = SourceAddress; + this.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(); - Mod0Offset = mod0Offset; - TextOffset = textOffset; - RoOffset = roOffset; - DataOffset = dataOffset; - BssSize = bssSize; + this.Mod0Offset = Mod0Offset; + this.TextOffset = TextOffset; + this.ROOffset = ROOffset; + this.DataOffset = DataOffset; + this.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 5509e865b..9fecb650c 100644 --- a/Ryujinx.HLE/Loaders/Executables/NxStaticObject.cs +++ b/Ryujinx.HLE/Loaders/Executables/NxStaticObject.cs @@ -6,14 +6,14 @@ namespace Ryujinx.HLE.Loaders.Executables { class NxStaticObject : IExecutable { - public byte[] Text { get; } - public byte[] Ro { get; } - public byte[] Data { get; } + public byte[] Text { get; private set; } + public byte[] RO { get; private set; } + public byte[] Data { get; private set; } - public int TextOffset { get; } - public int RoOffset { get; } - public int DataOffset { get; } - public int BssSize { get; } + public int TextOffset { get; private set; } + public int ROOffset { get; private set; } + public int DataOffset { get; private set; } + public int BssSize { get; private set; } public int BssOffset => DataOffset + Data.Length; @@ -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; - TextOffset = textMemOffset; - RoOffset = roMemOffset; - DataOffset = dataMemOffset; - BssSize = bssSize; + this.TextOffset = TextMemOffset; + this.ROOffset = ROMemOffset; + this.DataOffset = DataMemOffset; + this.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 28e11a488..4bec93e46 100644 --- a/Ryujinx.HLE/Loaders/Npdm/ACI0.cs +++ b/Ryujinx.HLE/Loaders/Npdm/ACI0.cs @@ -3,51 +3,51 @@ 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; } + public long TitleId { get; private set; } - public int FsVersion { get; } - public ulong FsPermissionsBitmask { get; } + public int FsVersion { get; private set; } + public ulong FsPermissionsBitmask { get; private set; } - public ServiceAccessControl ServiceAccessControl { get; } - public KernelAccessControl KernelAccessControl { get; } + 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 3ff873571..9206ee7bd 100644 --- a/Ryujinx.HLE/Loaders/Npdm/ACID.cs +++ b/Ryujinx.HLE/Loaders/Npdm/ACID.cs @@ -3,59 +3,59 @@ 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; } - public byte[] Rsa2048Modulus { get; } - public int Unknown1 { get; } - public int Flags { get; } + public byte[] RSA2048Signature { get; private set; } + public byte[] RSA2048Modulus { get; private set; } + public int Unknown1 { get; private set; } + public int Flags { get; private set; } - public long TitleIdRangeMin { get; } - public long TitleIdRangeMax { get; } + public long TitleIdRangeMin { get; private set; } + public long TitleIdRangeMax { get; private set; } - public FsAccessControl FsAccessControl { get; } - public ServiceAccessControl ServiceAccessControl { get; } - public KernelAccessControl KernelAccessControl { get; } + public FsAccessControl FsAccessControl { get; private set; } + 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 e246f0263..00faf3216 100644 --- a/Ryujinx.HLE/Loaders/Npdm/FsAccessControl.cs +++ b/Ryujinx.HLE/Loaders/Npdm/FsAccessControl.cs @@ -4,25 +4,25 @@ namespace Ryujinx.HLE.Loaders.Npdm { class FsAccessControl { - public int Version { get; } - public ulong PermissionsBitmask { get; } - public int Unknown1 { get; } - public int Unknown2 { get; } - public int Unknown3 { get; } - public int Unknown4 { get; } + public int Version { get; private set; } + public ulong PermissionsBitmask { get; private set; } + public int Unknown1 { get; private set; } + public int Unknown2 { get; private set; } + 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 97fb3b14f..50e823093 100644 --- a/Ryujinx.HLE/Loaders/Npdm/FsAccessHeader.cs +++ b/Ryujinx.HLE/Loaders/Npdm/FsAccessHeader.cs @@ -6,29 +6,29 @@ namespace Ryujinx.HLE.Loaders.Npdm { class FsAccessHeader { - public int Version { get; } - public ulong PermissionsBitmask { get; } + 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 a2f525f70..611eda39f 100644 --- a/Ryujinx.HLE/Loaders/Npdm/KernelAccessControl.cs +++ b/Ryujinx.HLE/Loaders/Npdm/KernelAccessControl.cs @@ -4,19 +4,19 @@ namespace Ryujinx.HLE.Loaders.Npdm { class KernelAccessControl { - public int[] Capabilities { get; } + 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 2ffef3271..6d74668a2 100644 --- a/Ryujinx.HLE/Loaders/Npdm/Npdm.cs +++ b/Ryujinx.HLE/Loaders/Npdm/Npdm.cs @@ -11,62 +11,62 @@ namespace Ryujinx.HLE.Loaders.Npdm { private const int MetaMagic = 'M' << 0 | 'E' << 8 | 'T' << 16 | 'A' << 24; - public byte MmuFlags { get; } - public bool Is64Bits { get; } - public byte MainThreadPriority { get; } - public byte DefaultCpuId { get; } - public int PersonalMmHeapSize { get; } - public int ProcessCategory { get; } - public int MainThreadStackSize { get; } - public string TitleName { get; } - public byte[] ProductCode { get; } + public byte MmuFlags { get; private set; } + public bool Is64Bits { get; private set; } + public byte MainThreadPriority { get; private set; } + public byte DefaultCpuId { get; private set; } + public int PersonalMmHeapSize { get; private set; } + public int ProcessCategory { get; private set; } + public int MainThreadStackSize { get; private set; } + public string TitleName { get; private set; } + public byte[] ProductCode { get; private set; } - public Aci0 Aci0 { get; } - public Acid Acid { get; } + 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 d349f26be..707be6038 100644 --- a/Ryujinx.HLE/Loaders/Npdm/ServiceAccessControl.cs +++ b/Ryujinx.HLE/Loaders/Npdm/ServiceAccessControl.cs @@ -7,36 +7,36 @@ namespace Ryujinx.HLE.Loaders.Npdm { class ServiceAccessControl { - public IReadOnlyDictionary Services { get; } + 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; } - Services = new ReadOnlyDictionary(services); + this.Services = new ReadOnlyDictionary(Services); } } } diff --git a/Ryujinx.HLE/PerformanceStatistics.cs b/Ryujinx.HLE/PerformanceStatistics.cs index 408e5d72a..2dabd9a08 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 7357b84cb..5b3b36d0f 100644 --- a/Ryujinx.HLE/Switch.cs +++ b/Ryujinx.HLE/Switch.cs @@ -11,43 +11,43 @@ namespace Ryujinx.HLE { public class Switch : IDisposable { - internal IAalOutput AudioOut { get; } + internal IAalOutput AudioOut { get; private set; } - internal DeviceMemory Memory { get; } + internal DeviceMemory Memory { get; private set; } - internal NvGpu Gpu { get; } + internal NvGpu Gpu { get; private set; } - internal VirtualFileSystem FileSystem { get; } + internal VirtualFileSystem FileSystem { get; private set; } - public Horizon System { get; } + public Horizon System { get; private set; } - public PerformanceStatistics Statistics { get; } + public PerformanceStatistics Statistics { get; private set; } - public Hid Hid { get; } + public Hid Hid { get; private set; } public bool EnableDeviceVsync { get; set; } = true; - public AutoResetEvent VsyncEvent { get; } + public AutoResetEvent VsyncEvent { get; private set; } 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)); } - AudioOut = audioOut; + this.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 df08191ac..5d0c8a845 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 3da0ef68b..efe7560c6 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 a7178d80c..57e9d396f 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 81a9d7be5..5c322f83c 100644 --- a/Ryujinx.HLE/Utilities/LinuxError.cs +++ b/Ryujinx.HLE/Utilities/LinuxError.cs @@ -1,8 +1,5 @@ -using System.Diagnostics.CodeAnalysis; - namespace Ryujinx.HLE.Utilities { - [SuppressMessage("ReSharper", "InconsistentNaming")] enum LinuxError { SUCCESS = 0, @@ -150,6 +147,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 e6602f48f..a10273eef 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 441dfd195..19fd26747 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) { - _memory = memory; - Position = position; + this.Memory = Memory; + this.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 86cfeedd7..a537e7a41 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) { - _memory = memory; - Position = position; + this.Memory = Memory; + this.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 9e685c181..14e04e4a6 100644 --- a/Ryujinx.HLE/Utilities/UInt128.cs +++ b/Ryujinx.HLE/Utilities/UInt128.cs @@ -6,30 +6,30 @@ namespace Ryujinx.HLE.Utilities { public struct UInt128 { - public long High { get; } - public long Low { get; } + public long High { get; private set; } + public long Low { get; private set; } - public UInt128(long low, long high) + public UInt128(long Low, long High) { - Low = low; - High = high; + this.Low = Low; + this.High = High; } - public UInt128(string hex) + public UInt128(string UInt128Hex) { - if (hex == null || hex.Length != 32 || !hex.All("0123456789abcdefABCDEF".Contains)) + if (UInt128Hex == null || UInt128Hex.Length != 32 || !UInt128Hex.All("0123456789abcdefABCDEF".Contains)) { - throw new ArgumentException("Invalid Hex value!", nameof(hex)); + throw new ArgumentException("Invalid Hex value!", nameof(UInt128Hex)); } - Low = Convert.ToInt64(hex.Substring(16), 16); - High = Convert.ToInt64(hex.Substring(0, 16), 16); + Low = Convert.ToInt64(UInt128Hex.Substring(16), 16); + High = Convert.ToInt64(UInt128Hex.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 81294b8b9..ff0896d47 100644 --- a/Ryujinx.HLE/Utilities/WSAError.cs +++ b/Ryujinx.HLE/Utilities/WSAError.cs @@ -1,9 +1,6 @@ -using System.Diagnostics.CodeAnalysis; - -namespace Ryujinx.HLE.Utilities +namespace Ryujinx.HLE.Utilities { - [SuppressMessage("ReSharper", "InconsistentNaming")] - enum WsaError + enum WSAError { /* * All Windows Sockets error constants are biased by WSABASEERR from @@ -24,43 +21,43 @@ namespace Ryujinx.HLE.Utilities /* * 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 @@ -129,6 +126,6 @@ namespace Ryujinx.HLE.Utilities * 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 deleted file mode 100644 index 737b56880..000000000 --- a/Ryujinx.sln.DotSettings +++ /dev/null @@ -1,7 +0,0 @@ - - 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 023359998..6acb199c1 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;