<|start_filename|>Ryujinx.Graphics.Gpu/Shader/ShaderDumpPaths.cs<|end_filename|>
using Ryujinx.Graphics.Shader;

namespace Ryujinx.Graphics.Gpu.Shader
{
    /// <summary>
    /// Paths where shader code was dumped on disk.
    /// </summary>
    struct ShaderDumpPaths
    {
        /// <summary>
        /// Path where the full shader code with header was dumped, or null if not dumped.
        /// </summary>
        public string FullPath { get; }

        /// <summary>
        /// Path where the shader code without header was dumped, or null if not dumped.
        /// </summary>
        public string CodePath { get; }

        /// <summary>
        /// True if the shader was dumped, false otherwise.
        /// </summary>
        public bool HasPath => FullPath != null && CodePath != null;

        /// <summary>
        /// Creates a new shader dumps path structure.
        /// </summary>
        /// <param name="fullPath">Path where the full shader code with header was dumped, or null if not dumped</param>
        /// <param name="codePath">Path where the shader code without header was dumped, or null if not dumped</param>
        public ShaderDumpPaths(string fullPath, string codePath)
        {
            FullPath = fullPath;
            CodePath = codePath;
        }

        /// <summary>
        /// Prepends the shader paths on the program source, as a comment.
        /// </summary>
        /// <param name="program">Program to prepend into</param>
        public void Prepend(ShaderProgram program)
        {
            if (HasPath)
            {
                program.Prepend("// " + CodePath);
                program.Prepend("// " + FullPath);
            }
        }
    }
}

<|start_filename|>Ryujinx.HLE/HOS/Services/Hid/IHidServer.cs<|end_filename|>
using Ryujinx.Common;
using Ryujinx.Common.Logging;
using Ryujinx.HLE.HOS.Ipc;
using Ryujinx.HLE.HOS.Kernel.Common;
using Ryujinx.HLE.HOS.Kernel.Threading;
using Ryujinx.HLE.HOS.Services.Hid.HidServer;
using Ryujinx.HLE.HOS.Services.Hid.Types;
using Ryujinx.HLE.HOS.Services.Hid.Types.SharedMemory.Npad;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Runtime.InteropServices;

namespace Ryujinx.HLE.HOS.Services.Hid
{
    [Service("hid")]
    class IHidServer : IpcService
    {
        private KEvent _xpadIdEvent;
        private KEvent _palmaOperationCompleteEvent;

        private int _xpadIdEventHandle;

        private bool _sixAxisSensorFusionEnabled;
        private bool _unintendedHomeButtonInputProtectionEnabled;
        private bool _vibrationPermitted;
        private bool _usbFullKeyControllerEnabled;
        private bool _isFirmwareUpdateAvailableForSixAxisSensor;

        private HidNpadJoyAssignmentMode      _npadJoyAssignmentMode;
        private HidNpadHandheldActivationMode _npadHandheldActivationMode;
        private HidGyroscopeZeroDriftMode     _gyroscopeZeroDriftMode;

        private long  _npadCommunicationMode;
        private uint  _accelerometerPlayMode;
#pragma warning disable CS0649
        private long  _vibrationGcErmCommand;
#pragma warning restore CS0649
        private float _sevenSixAxisSensorFusionStrength;

        private HidSensorFusionParameters  _sensorFusionParams;
        private HidAccelerometerParameters _accelerometerParams;

        public IHidServer(ServiceCtx context) : base(context.Device.System.HidServer)
        {
            _xpadIdEvent                 = new KEvent(context.Device.System.KernelContext);
            _palmaOperationCompleteEvent = new KEvent(context.Device.System.KernelContext);

            _npadJoyAssignmentMode      = HidNpadJoyAssignmentMode.Dual;
            _npadHandheldActivationMode = HidNpadHandheldActivationMode.Dual;
            _gyroscopeZeroDriftMode     = HidGyroscopeZeroDriftMode.Standard;

            _isFirmwareUpdateAvailableForSixAxisSensor = false;

            _sensorFusionParams  = new HidSensorFusionParameters();
            _accelerometerParams = new HidAccelerometerParameters();

            // TODO: signal event at right place
            _xpadIdEvent.ReadableEvent.Signal();
        }

        [CommandHipc(0)]
        // CreateAppletResource(nn::applet::AppletResourceUserId) -> object<nn::hid::IAppletResource>
        public ResultCode CreateAppletResource(ServiceCtx context)
        {
            long appletResourceUserId = context.RequestData.ReadInt64();

            MakeObject(context, new IAppletResource(context.Device.System.HidSharedMem));

            return ResultCode.Success;
        }

        [CommandHipc(1)]
        // ActivateDebugPad(nn::applet::AppletResourceUserId)
        public ResultCode ActivateDebugPad(ServiceCtx context)
        {
            long appletResourceUserId = context.RequestData.ReadInt64();

            // Initialize entries to avoid issues with some games.

            for (int entry = 0; entry < Hid.SharedMemEntryCount; entry++)
            {
                context.Device.Hid.DebugPad.Update();
            }

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId });

            return ResultCode.Success;
        }

        [CommandHipc(11)]
        // ActivateTouchScreen(nn::applet::AppletResourceUserId)
        public ResultCode ActivateTouchScreen(ServiceCtx context)
        {
            long appletResourceUserId = context.RequestData.ReadInt64();

            context.Device.Hid.Touchscreen.Active = true;

            // Initialize entries to avoid issues with some games.

            for (int entry = 0; entry < Hid.SharedMemEntryCount; entry++)
            {
                context.Device.Hid.Touchscreen.Update();
            }

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId });

            return ResultCode.Success;
        }

        [CommandHipc(21)]
        // ActivateMouse(nn::applet::AppletResourceUserId)
        public ResultCode ActivateMouse(ServiceCtx context)
        {
            long appletResourceUserId = context.RequestData.ReadInt64();

            context.Device.Hid.Mouse.Active = true;

            // Initialize entries to avoid issues with some games.

            for (int entry = 0; entry < Hid.SharedMemEntryCount; entry++)
            {
                context.Device.Hid.Mouse.Update(0, 0);
            }

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId });

            return ResultCode.Success;
        }

        [CommandHipc(31)]
        // ActivateKeyboard(nn::applet::AppletResourceUserId)
        public ResultCode ActivateKeyboard(ServiceCtx context)
        {
            long appletResourceUserId = context.RequestData.ReadInt64();

            context.Device.Hid.Keyboard.Active = true;

            // Initialize entries to avoid issues with some games.

            KeyboardInput emptyInput = new KeyboardInput();
            emptyInput.Keys = new ulong[4];

            for (int entry = 0; entry < Hid.SharedMemEntryCount; entry++)
            {
                context.Device.Hid.Keyboard.Update(emptyInput);
            }

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId });

            return ResultCode.Success;
        }

        [CommandHipc(32)]
        // SendKeyboardLockKeyEvent(uint flags, pid)
        public ResultCode SendKeyboardLockKeyEvent(ServiceCtx context)
        {
            uint flags = context.RequestData.ReadUInt32();

            // NOTE: This signal the keyboard driver about lock events.

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { flags });

            return ResultCode.Success;
        }

        [CommandHipc(40)]
        // AcquireXpadIdEventHandle(ulong XpadId) -> nn::sf::NativeHandle
        public ResultCode AcquireXpadIdEventHandle(ServiceCtx context)
        {
            long xpadId = context.RequestData.ReadInt64();

            if (context.Process.HandleTable.GenerateHandle(_xpadIdEvent.ReadableEvent, out _xpadIdEventHandle) != KernelResult.Success)
            {
                throw new InvalidOperationException("Out of handles!");
            }

            context.Response.HandleDesc = IpcHandleDesc.MakeCopy(_xpadIdEventHandle);

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { xpadId });

            return ResultCode.Success;
        }

        [CommandHipc(41)]
        // ReleaseXpadIdEventHandle(ulong XpadId)
        public ResultCode ReleaseXpadIdEventHandle(ServiceCtx context)
        {
            long xpadId = context.RequestData.ReadInt64();

            context.Process.HandleTable.CloseHandle(_xpadIdEventHandle);

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { xpadId });

            return ResultCode.Success;
        }

        [CommandHipc(51)]
        // ActivateXpad(nn::hid::BasicXpadId, nn::applet::AppletResourceUserId)
        public ResultCode ActivateXpad(ServiceCtx context)
        {
            int  basicXpadId          = context.RequestData.ReadInt32();
            long appletResourceUserId = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, basicXpadId });

            return ResultCode.Success;
        }

        [CommandHipc(55)]
        // GetXpadIds() -> long IdsCount, buffer<array<nn::hid::BasicXpadId>, type: 0xa>
        public ResultCode GetXpadIds(ServiceCtx context)
        {
            // There is any Xpad, so we return 0 and write nothing inside the type-0xa buffer.
            context.ResponseData.Write(0L);

            Logger.Stub?.PrintStub(LogClass.ServiceHid);

            return ResultCode.Success;
        }

        [CommandHipc(56)]
        // ActivateJoyXpad(nn::hid::JoyXpadId)
        public ResultCode ActivateJoyXpad(ServiceCtx context)
        {
            int joyXpadId = context.RequestData.ReadInt32();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { joyXpadId });

            return ResultCode.Success;
        }

        [CommandHipc(58)]
        // GetJoyXpadLifoHandle(nn::hid::JoyXpadId) -> nn::sf::NativeHandle
        public ResultCode GetJoyXpadLifoHandle(ServiceCtx context)
        {
            int joyXpadId = context.RequestData.ReadInt32();

            int handle = 0;

            context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle);

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { joyXpadId });

            return ResultCode.Success;
        }

        [CommandHipc(59)]
        // GetJoyXpadIds() -> long IdsCount, buffer<array<nn::hid::JoyXpadId>, type: 0xa>
        public ResultCode GetJoyXpadIds(ServiceCtx context)
        {
            // There is any JoyXpad, so we return 0 and write nothing inside the type-0xa buffer.
            context.ResponseData.Write(0L);

            Logger.Stub?.PrintStub(LogClass.ServiceHid);

            return ResultCode.Success;
        }

        [CommandHipc(60)]
        // ActivateSixAxisSensor(nn::hid::BasicXpadId)
        public ResultCode ActivateSixAxisSensor(ServiceCtx context)
        {
            int basicXpadId = context.RequestData.ReadInt32();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { basicXpadId });

            return ResultCode.Success;
        }

        [CommandHipc(61)]
        // DeactivateSixAxisSensor(nn::hid::BasicXpadId)
        public ResultCode DeactivateSixAxisSensor(ServiceCtx context)
        {
            int basicXpadId = context.RequestData.ReadInt32();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { basicXpadId });

            return ResultCode.Success;
        }

        [CommandHipc(62)]
        // GetSixAxisSensorLifoHandle(nn::hid::BasicXpadId) -> nn::sf::NativeHandle
        public ResultCode GetSixAxisSensorLifoHandle(ServiceCtx context)
        {
            int basicXpadId = context.RequestData.ReadInt32();

            int handle = 0;

            context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle);

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { basicXpadId });

            return ResultCode.Success;
        }

        [CommandHipc(63)]
        // ActivateJoySixAxisSensor(nn::hid::JoyXpadId)
        public ResultCode ActivateJoySixAxisSensor(ServiceCtx context)
        {
            int joyXpadId = context.RequestData.ReadInt32();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { joyXpadId });

            return ResultCode.Success;
        }

        [CommandHipc(64)]
        // DeactivateJoySixAxisSensor(nn::hid::JoyXpadId)
        public ResultCode DeactivateJoySixAxisSensor(ServiceCtx context)
        {
            int joyXpadId = context.RequestData.ReadInt32();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { joyXpadId });

            return ResultCode.Success;
        }

        [CommandHipc(65)]
        // GetJoySixAxisSensorLifoHandle(nn::hid::JoyXpadId) -> nn::sf::NativeHandle
        public ResultCode GetJoySixAxisSensorLifoHandle(ServiceCtx context)
        {
            int joyXpadId = context.RequestData.ReadInt32();

            int handle = 0;

            context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle);

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { joyXpadId });

            return ResultCode.Success;
        }

        [CommandHipc(66)]
        // StartSixAxisSensor(nn::hid::SixAxisSensorHandle, nn::applet::AppletResourceUserId)
        public ResultCode StartSixAxisSensor(ServiceCtx context)
        {
            int  sixAxisSensorHandle  = context.RequestData.ReadInt32();
            long appletResourceUserId = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, sixAxisSensorHandle });

            return ResultCode.Success;
        }

        [CommandHipc(67)]
        // StopSixAxisSensor(nn::hid::SixAxisSensorHandle, nn::applet::AppletResourceUserId)
        public ResultCode StopSixAxisSensor(ServiceCtx context)
        {
            int  sixAxisSensorHandle  = context.RequestData.ReadInt32();
            long appletResourceUserId = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, sixAxisSensorHandle });

            return ResultCode.Success;
        }

        [CommandHipc(68)]
        // IsSixAxisSensorFusionEnabled(nn::hid::SixAxisSensorHandle, nn::applet::AppletResourceUserId) -> bool IsEnabled
        public ResultCode IsSixAxisSensorFusionEnabled(ServiceCtx context)
        {
            int  sixAxisSensorHandle  = context.RequestData.ReadInt32();
            long appletResourceUserId = context.RequestData.ReadInt64();

            context.ResponseData.Write(_sixAxisSensorFusionEnabled);

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, sixAxisSensorHandle, _sixAxisSensorFusionEnabled });

            return ResultCode.Success;
        }

        [CommandHipc(69)]
        // EnableSixAxisSensorFusion(bool Enabled, nn::hid::SixAxisSensorHandle, nn::applet::AppletResourceUserId)
        public ResultCode EnableSixAxisSensorFusion(ServiceCtx context)
        {
            _sixAxisSensorFusionEnabled = context.RequestData.ReadBoolean();
            int  sixAxisSensorHandle    = context.RequestData.ReadInt32();
            long appletResourceUserId   = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, sixAxisSensorHandle, _sixAxisSensorFusionEnabled });

            return ResultCode.Success;
        }

        [CommandHipc(70)]
        // SetSixAxisSensorFusionParameters(nn::hid::SixAxisSensorHandle, float RevisePower, float ReviseRange, nn::applet::AppletResourceUserId)
        public ResultCode SetSixAxisSensorFusionParameters(ServiceCtx context)
        {
            int   sixAxisSensorHandle = context.RequestData.ReadInt32();

            _sensorFusionParams = new HidSensorFusionParameters
            {
                RevisePower = context.RequestData.ReadInt32(),
                ReviseRange = context.RequestData.ReadInt32()
            };

            long appletResourceUserId = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, sixAxisSensorHandle, _sensorFusionParams.RevisePower, _sensorFusionParams.ReviseRange });

            return ResultCode.Success;
        }

        [CommandHipc(71)]
        // GetSixAxisSensorFusionParameters(nn::hid::SixAxisSensorHandle, nn::applet::AppletResourceUserId) -> float RevisePower, float ReviseRange)
        public ResultCode GetSixAxisSensorFusionParameters(ServiceCtx context)
        {
            int  sixAxisSensorHandle  = context.RequestData.ReadInt32();
            long appletResourceUserId = context.RequestData.ReadInt64();

            context.ResponseData.Write(_sensorFusionParams.RevisePower);
            context.ResponseData.Write(_sensorFusionParams.ReviseRange);

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, sixAxisSensorHandle, _sensorFusionParams.RevisePower, _sensorFusionParams.ReviseRange });

            return ResultCode.Success;
        }

        [CommandHipc(72)]
        // ResetSixAxisSensorFusionParameters(nn::hid::SixAxisSensorHandle, nn::applet::AppletResourceUserId)
        public ResultCode ResetSixAxisSensorFusionParameters(ServiceCtx context)
        {
            int  sixAxisSensorHandle  = context.RequestData.ReadInt32();
            long appletResourceUserId = context.RequestData.ReadInt64();

            _sensorFusionParams.RevisePower = 0;
            _sensorFusionParams.ReviseRange = 0;

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, sixAxisSensorHandle, _sensorFusionParams.RevisePower, _sensorFusionParams.ReviseRange });

            return ResultCode.Success;
        }

        [CommandHipc(73)]
        // SetAccelerometerParameters(nn::hid::SixAxisSensorHandle, float X, float Y, nn::applet::AppletResourceUserId)
        public ResultCode SetAccelerometerParameters(ServiceCtx context)
        {
            int sixAxisSensorHandle = context.RequestData.ReadInt32();

            _accelerometerParams = new HidAccelerometerParameters
            {
                X = context.RequestData.ReadInt32(),
                Y = context.RequestData.ReadInt32()
            };

            long appletResourceUserId = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, sixAxisSensorHandle, _accelerometerParams.X, _accelerometerParams.Y });

            return ResultCode.Success;
        }

        [CommandHipc(74)]
        // GetAccelerometerParameters(nn::hid::SixAxisSensorHandle, nn::applet::AppletResourceUserId) -> float X, float Y
        public ResultCode GetAccelerometerParameters(ServiceCtx context)
        {
            int  sixAxisSensorHandle  = context.RequestData.ReadInt32();
            long appletResourceUserId = context.RequestData.ReadInt64();

            context.ResponseData.Write(_accelerometerParams.X);
            context.ResponseData.Write(_accelerometerParams.Y);

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, sixAxisSensorHandle, _accelerometerParams.X, _accelerometerParams.Y });

            return ResultCode.Success;
        }

        [CommandHipc(75)]
        // ResetAccelerometerParameters(nn::hid::SixAxisSensorHandle, nn::applet::AppletResourceUserId)
        public ResultCode ResetAccelerometerParameters(ServiceCtx context)
        {
            int  sixAxisSensorHandle  = context.RequestData.ReadInt32();
            long appletResourceUserId = context.RequestData.ReadInt64();

            _accelerometerParams.X = 0;
            _accelerometerParams.Y = 0;

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, sixAxisSensorHandle, _accelerometerParams.X, _accelerometerParams.Y });

            return ResultCode.Success;
        }

        [CommandHipc(76)]
        // SetAccelerometerPlayMode(nn::hid::SixAxisSensorHandle, uint PlayMode, nn::applet::AppletResourceUserId)
        public ResultCode SetAccelerometerPlayMode(ServiceCtx context)
        {
            int  sixAxisSensorHandle    = context.RequestData.ReadInt32();
                 _accelerometerPlayMode = context.RequestData.ReadUInt32();
            long appletResourceUserId   = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, sixAxisSensorHandle, _accelerometerPlayMode });

            return ResultCode.Success;
        }

        [CommandHipc(77)]
        // GetAccelerometerPlayMode(nn::hid::SixAxisSensorHandle, nn::applet::AppletResourceUserId) -> uint PlayMode
        public ResultCode GetAccelerometerPlayMode(ServiceCtx context)
        {
            int  sixAxisSensorHandle  = context.RequestData.ReadInt32();
            long appletResourceUserId = context.RequestData.ReadInt64();

            context.ResponseData.Write(_accelerometerPlayMode);

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, sixAxisSensorHandle, _accelerometerPlayMode });

            return ResultCode.Success;
        }

        [CommandHipc(78)]
        // ResetAccelerometerPlayMode(nn::hid::SixAxisSensorHandle, nn::applet::AppletResourceUserId)
        public ResultCode ResetAccelerometerPlayMode(ServiceCtx context)
        {
            int  sixAxisSensorHandle  = context.RequestData.ReadInt32();
            long appletResourceUserId = context.RequestData.ReadInt64();

            _accelerometerPlayMode = 0;

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, sixAxisSensorHandle, _accelerometerPlayMode });

            return ResultCode.Success;
        }

        [CommandHipc(79)]
        // SetGyroscopeZeroDriftMode(nn::hid::SixAxisSensorHandle, uint GyroscopeZeroDriftMode, nn::applet::AppletResourceUserId)
        public ResultCode SetGyroscopeZeroDriftMode(ServiceCtx context)
        {
            int  sixAxisSensorHandle     = context.RequestData.ReadInt32();
                 _gyroscopeZeroDriftMode = (HidGyroscopeZeroDriftMode)context.RequestData.ReadInt32();
            long appletResourceUserId    = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, sixAxisSensorHandle, _gyroscopeZeroDriftMode });

            return ResultCode.Success;
        }

        [CommandHipc(80)]
        // GetGyroscopeZeroDriftMode(nn::applet::AppletResourceUserId, nn::hid::SixAxisSensorHandle) -> int GyroscopeZeroDriftMode
        public ResultCode GetGyroscopeZeroDriftMode(ServiceCtx context)
        {
            int  sixAxisSensorHandle  = context.RequestData.ReadInt32();
            long appletResourceUserId = context.RequestData.ReadInt64();

            context.ResponseData.Write((int)_gyroscopeZeroDriftMode);

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, sixAxisSensorHandle, _gyroscopeZeroDriftMode });

            return ResultCode.Success;
        }

        [CommandHipc(81)]
        // ResetGyroscopeZeroDriftMode(nn::hid::SixAxisSensorHandle, nn::applet::AppletResourceUserId)
        public ResultCode ResetGyroscopeZeroDriftMode(ServiceCtx context)
        {
            int  sixAxisSensorHandle  = context.RequestData.ReadInt32();
            long appletResourceUserId = context.RequestData.ReadInt64();

            _gyroscopeZeroDriftMode = HidGyroscopeZeroDriftMode.Standard;

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, sixAxisSensorHandle, _gyroscopeZeroDriftMode });

            return ResultCode.Success;
        }

        [CommandHipc(82)]
        // IsSixAxisSensorAtRest(nn::hid::SixAxisSensorHandle, nn::applet::AppletResourceUserId) -> bool IsAsRest
        public ResultCode IsSixAxisSensorAtRest(ServiceCtx context)
        {
            int  sixAxisSensorHandle  = context.RequestData.ReadInt32();
            long appletResourceUserId = context.RequestData.ReadInt64();

            bool isAtRest = true;

            context.ResponseData.Write(isAtRest);

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, sixAxisSensorHandle, isAtRest });

            return ResultCode.Success;
        }

        [CommandHipc(83)] // 6.0.0+
        // IsFirmwareUpdateAvailableForSixAxisSensor(nn::hid::AppletResourceUserId, nn::hid::SixAxisSensorHandle, pid) -> bool UpdateAvailable
        public ResultCode IsFirmwareUpdateAvailableForSixAxisSensor(ServiceCtx context)
        {
            int  sixAxisSensorHandle  = context.RequestData.ReadInt32();
            context.RequestData.BaseStream.Position += 4;
            long appletResourceUserId = context.RequestData.ReadInt64();

            context.ResponseData.Write(_isFirmwareUpdateAvailableForSixAxisSensor);

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, sixAxisSensorHandle, _isFirmwareUpdateAvailableForSixAxisSensor });

            return ResultCode.Success;
        }

        [CommandHipc(91)]
        // ActivateGesture(nn::applet::AppletResourceUserId, int Unknown0)
        public ResultCode ActivateGesture(ServiceCtx context)
        {
            long appletResourceUserId = context.RequestData.ReadInt64();
            int  unknown0             = context.RequestData.ReadInt32();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, unknown0 });

            return ResultCode.Success;
        }

        [CommandHipc(100)]
        // SetSupportedNpadStyleSet(nn::applet::AppletResourceUserId, nn::hid::NpadStyleTag)
        public ResultCode SetSupportedNpadStyleSet(ServiceCtx context)
        {
            ControllerType type = (ControllerType)context.RequestData.ReadInt32();
            long appletResourceUserId = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new {
                    appletResourceUserId,
                    type
                });

            context.Device.Hid.Npads.SupportedStyleSets = type;

            return ResultCode.Success;
        }

        [CommandHipc(101)]
        // GetSupportedNpadStyleSet(nn::applet::AppletResourceUserId) -> uint nn::hid::NpadStyleTag
        public ResultCode GetSupportedNpadStyleSet(ServiceCtx context)
        {
            long appletResourceUserId = context.RequestData.ReadInt64();

            context.ResponseData.Write((int)context.Device.Hid.Npads.SupportedStyleSets);

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new {
                    appletResourceUserId,
                    context.Device.Hid.Npads.SupportedStyleSets
                });

            return ResultCode.Success;
        }

        [CommandHipc(102)]
        // SetSupportedNpadIdType(nn::applet::AppletResourceUserId, array<NpadIdType, 9>)
        public ResultCode SetSupportedNpadIdType(ServiceCtx context)
        {
            long appletResourceUserId = context.RequestData.ReadInt64();
            ulong arrayPosition = context.Request.PtrBuff[0].Position;
            ulong arraySize = context.Request.PtrBuff[0].Size;

            ReadOnlySpan<NpadIdType> supportedPlayerIds = MemoryMarshal.Cast<byte, NpadIdType>(context.Memory.GetSpan(arrayPosition, (int)arraySize));

            context.Device.Hid.Npads.ClearSupportedPlayers();

            for (int i = 0; i < supportedPlayerIds.Length; ++i)
            {
                if (supportedPlayerIds[i] >= 0)
                {
                    context.Device.Hid.Npads.SetSupportedPlayer(HidUtils.GetIndexFromNpadIdType(supportedPlayerIds[i]));
                }
            }

            Logger.Stub?.PrintStub(LogClass.ServiceHid, $"{supportedPlayerIds.Length} " + string.Join(",", supportedPlayerIds.ToArray()));

            return ResultCode.Success;
        }

        [CommandHipc(103)]
        // ActivateNpad(nn::applet::AppletResourceUserId)
        public ResultCode ActivateNpad(ServiceCtx context)
        {
            long appletResourceUserId = context.RequestData.ReadInt64();

            context.Device.Hid.Npads.Active = true;

            // Initialize entries to avoid issues with some games.

            List<GamepadInput> emptyGamepadInputs = new List<GamepadInput>();
            List<SixAxisInput> emptySixAxisInputs = new List<SixAxisInput>();

            for (int player = 0; player < NpadDevices.MaxControllers; player++)
            {
                GamepadInput gamepadInput = new GamepadInput();
                SixAxisInput sixaxisInput = new SixAxisInput();

                gamepadInput.PlayerId = (PlayerIndex)player;
                sixaxisInput.PlayerId = (PlayerIndex)player;

                sixaxisInput.Orientation = new float[9];

                emptyGamepadInputs.Add(gamepadInput);
                emptySixAxisInputs.Add(sixaxisInput);
            }

            for (int entry = 0; entry < Hid.SharedMemEntryCount; entry++)
            {
                context.Device.Hid.Npads.Update(emptyGamepadInputs);
                context.Device.Hid.Npads.UpdateSixAxis(emptySixAxisInputs);
            }

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId });

            return ResultCode.Success;
        }

        [CommandHipc(104)]
        // DeactivateNpad(nn::applet::AppletResourceUserId)
        public ResultCode DeactivateNpad(ServiceCtx context)
        {
            long appletResourceUserId = context.RequestData.ReadInt64();

            context.Device.Hid.Npads.Active = false;
            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId });

            return ResultCode.Success;
        }

        [CommandHipc(106)]
        // AcquireNpadStyleSetUpdateEventHandle(nn::applet::AppletResourceUserId, uint, ulong) -> nn::sf::NativeHandle
        public ResultCode AcquireNpadStyleSetUpdateEventHandle(ServiceCtx context)
        {
            PlayerIndex npadId               = HidUtils.GetIndexFromNpadIdType((NpadIdType)context.RequestData.ReadInt32());
            long        appletResourceUserId = context.RequestData.ReadInt64();
            long        npadStyleSet         = context.RequestData.ReadInt64();

            KEvent evnt = context.Device.Hid.Npads.GetStyleSetUpdateEvent(npadId);
            if (context.Process.HandleTable.GenerateHandle(evnt.ReadableEvent, out int handle) != KernelResult.Success)
            {
                throw new InvalidOperationException("Out of handles!");
            }

            context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle);

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, npadId, npadStyleSet });

            return ResultCode.Success;
        }

        [CommandHipc(107)]
        // DisconnectNpad(nn::applet::AppletResourceUserId, uint NpadIdType)
        public ResultCode DisconnectNpad(ServiceCtx context)
        {
            NpadIdType npadIdType           = (NpadIdType)context.RequestData.ReadInt32();
            long       appletResourceUserId = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, npadIdType });

            return ResultCode.Success;
        }

        [CommandHipc(108)]
        // GetPlayerLedPattern(u32 npad_id) -> u64 led_pattern
        public ResultCode GetPlayerLedPattern(ServiceCtx context)
        {
            NpadIdType npadId = (NpadIdType)context.RequestData.ReadUInt32();

            ulong ledPattern = npadId switch
            {
                NpadIdType.Player1  => 0b0001,
                NpadIdType.Player2  => 0b0011,
                NpadIdType.Player3  => 0b0111,
                NpadIdType.Player4  => 0b1111,
                NpadIdType.Player5  => 0b1001,
                NpadIdType.Player6  => 0b0101,
                NpadIdType.Player7  => 0b1101,
                NpadIdType.Player8  => 0b0110,
                NpadIdType.Unknown  => 0b0000,
                NpadIdType.Handheld => 0b0000,
                _ => throw new ArgumentOutOfRangeException(nameof(npadId))
            };

            context.ResponseData.Write(ledPattern);

            return ResultCode.Success;
        }

        [CommandHipc(109)] // 5.0.0+
        // ActivateNpadWithRevision(nn::applet::AppletResourceUserId, int revision)
        public ResultCode ActivateNpadWithRevision(ServiceCtx context)
        {
            int  revision             = context.RequestData.ReadInt32();
            long appletResourceUserId = context.RequestData.ReadInt64();

            // Initialize entries to avoid issues with some games.

            List<GamepadInput> emptyGamepadInputs = new List<GamepadInput>();
            List<SixAxisInput> emptySixAxisInputs = new List<SixAxisInput>();

            for (int player = 0; player < NpadDevices.MaxControllers; player++)
            {
                GamepadInput gamepadInput = new GamepadInput();
                SixAxisInput sixaxisInput = new SixAxisInput();

                gamepadInput.PlayerId = (PlayerIndex)player;
                sixaxisInput.PlayerId = (PlayerIndex)player;

                sixaxisInput.Orientation = new float[9];

                emptyGamepadInputs.Add(gamepadInput);
                emptySixAxisInputs.Add(sixaxisInput);
            }

            for (int entry = 0; entry < Hid.SharedMemEntryCount; entry++)
            {
                context.Device.Hid.Npads.Update(emptyGamepadInputs);
                context.Device.Hid.Npads.UpdateSixAxis(emptySixAxisInputs);
            }

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, revision });

            return ResultCode.Success;
        }

        [CommandHipc(120)]
        // SetNpadJoyHoldType(nn::applet::AppletResourceUserId, ulong NpadJoyHoldType)
        public ResultCode SetNpadJoyHoldType(ServiceCtx context)
        {
            long appletResourceUserId = context.RequestData.ReadInt64();

            NpadJoyHoldType npadJoyHoldType = (NpadJoyHoldType)context.RequestData.ReadUInt64();

            if (npadJoyHoldType > NpadJoyHoldType.Horizontal)
            {
                throw new ArgumentOutOfRangeException(nameof(npadJoyHoldType));
            }

            foreach (PlayerIndex playerIndex in context.Device.Hid.Npads.GetSupportedPlayers())
            {
                if (HidUtils.GetNpadIdTypeFromIndex(playerIndex) > NpadIdType.Handheld)
                {
                    return ResultCode.InvalidNpadIdType;
                }
            }

            context.Device.Hid.Npads.JoyHold = npadJoyHoldType;

            return ResultCode.Success;
        }

        [CommandHipc(121)]
        // GetNpadJoyHoldType(nn::applet::AppletResourceUserId) -> ulong NpadJoyHoldType
        public ResultCode GetNpadJoyHoldType(ServiceCtx context)
        {
            long appletResourceUserId = context.RequestData.ReadInt64();

            foreach (PlayerIndex playerIndex in context.Device.Hid.Npads.GetSupportedPlayers())
            {
                if (HidUtils.GetNpadIdTypeFromIndex(playerIndex) > NpadIdType.Handheld)
                {
                    return ResultCode.InvalidNpadIdType;
                }
            }

            context.ResponseData.Write((ulong)context.Device.Hid.Npads.JoyHold);

            return ResultCode.Success;
        }

        [CommandHipc(122)]
        // SetNpadJoyAssignmentModeSingleByDefault(uint HidControllerId, nn::applet::AppletResourceUserId)
        public ResultCode SetNpadJoyAssignmentModeSingleByDefault(ServiceCtx context)
        {
            PlayerIndex hidControllerId      = (PlayerIndex)context.RequestData.ReadInt32();
            long        appletResourceUserId = context.RequestData.ReadInt64();

            _npadJoyAssignmentMode = HidNpadJoyAssignmentMode.Single;

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, hidControllerId, _npadJoyAssignmentMode });

            return ResultCode.Success;
        }

        [CommandHipc(123)]
        // SetNpadJoyAssignmentModeSingle(uint HidControllerId, nn::applet::AppletResourceUserId, long HidNpadJoyDeviceType)
        public ResultCode SetNpadJoyAssignmentModeSingle(ServiceCtx context)
        {
            PlayerIndex          hidControllerId      = (PlayerIndex)context.RequestData.ReadInt32();
            long                 appletResourceUserId = context.RequestData.ReadInt64();
            HidNpadJoyDeviceType hidNpadJoyDeviceType = (HidNpadJoyDeviceType)context.RequestData.ReadInt64();

            _npadJoyAssignmentMode = HidNpadJoyAssignmentMode.Single;

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, hidControllerId, hidNpadJoyDeviceType, _npadJoyAssignmentMode });

            return ResultCode.Success;
        }

        [CommandHipc(124)]
        // SetNpadJoyAssignmentModeDual(uint HidControllerId, nn::applet::AppletResourceUserId)
        public ResultCode SetNpadJoyAssignmentModeDual(ServiceCtx context)
        {
            PlayerIndex hidControllerId      = HidUtils.GetIndexFromNpadIdType((NpadIdType)context.RequestData.ReadInt32());
            long        appletResourceUserId = context.RequestData.ReadInt64();

            _npadJoyAssignmentMode = HidNpadJoyAssignmentMode.Dual;

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, hidControllerId, _npadJoyAssignmentMode });

            return ResultCode.Success;
        }

        [CommandHipc(125)]
        // MergeSingleJoyAsDualJoy(uint SingleJoyId0, uint SingleJoyId1, nn::applet::AppletResourceUserId)
        public ResultCode MergeSingleJoyAsDualJoy(ServiceCtx context)
        {
            long singleJoyId0         = context.RequestData.ReadInt32();
            long singleJoyId1         = context.RequestData.ReadInt32();
            long appletResourceUserId = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, singleJoyId0, singleJoyId1 });

            return ResultCode.Success;
        }

        [CommandHipc(126)]
        // StartLrAssignmentMode(nn::applet::AppletResourceUserId)
        public ResultCode StartLrAssignmentMode(ServiceCtx context)
        {
            long appletResourceUserId = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId });

            return ResultCode.Success;
        }

        [CommandHipc(127)]
        // StopLrAssignmentMode(nn::applet::AppletResourceUserId)
        public ResultCode StopLrAssignmentMode(ServiceCtx context)
        {
            long appletResourceUserId = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId });

            return ResultCode.Success;
        }

        [CommandHipc(128)]
        // SetNpadHandheldActivationMode(nn::applet::AppletResourceUserId, long HidNpadHandheldActivationMode)
        public ResultCode SetNpadHandheldActivationMode(ServiceCtx context)
        {
            long appletResourceUserId   = context.RequestData.ReadInt64();
            _npadHandheldActivationMode = (HidNpadHandheldActivationMode)context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, _npadHandheldActivationMode });

            return ResultCode.Success;
        }

        [CommandHipc(129)]
        // GetNpadHandheldActivationMode(nn::applet::AppletResourceUserId) -> long HidNpadHandheldActivationMode
        public ResultCode GetNpadHandheldActivationMode(ServiceCtx context)
        {
            long appletResourceUserId = context.RequestData.ReadInt64();

            context.ResponseData.Write((long)_npadHandheldActivationMode);

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, _npadHandheldActivationMode });

            return ResultCode.Success;
        }

        [CommandHipc(130)]
        // SwapNpadAssignment(uint OldNpadAssignment, uint NewNpadAssignment, nn::applet::AppletResourceUserId)
        public ResultCode SwapNpadAssignment(ServiceCtx context)
        {
            int  oldNpadAssignment    = context.RequestData.ReadInt32();
            int  newNpadAssignment    = context.RequestData.ReadInt32();
            long appletResourceUserId = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, oldNpadAssignment, newNpadAssignment });

            return ResultCode.Success;
        }

        [CommandHipc(131)]
        // IsUnintendedHomeButtonInputProtectionEnabled(uint Unknown0, nn::applet::AppletResourceUserId) ->  bool IsEnabled
        public ResultCode IsUnintendedHomeButtonInputProtectionEnabled(ServiceCtx context)
        {
            uint  unknown0            = context.RequestData.ReadUInt32();
            long appletResourceUserId = context.RequestData.ReadInt64();

            context.ResponseData.Write(_unintendedHomeButtonInputProtectionEnabled);

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, unknown0, _unintendedHomeButtonInputProtectionEnabled });

            return ResultCode.Success;
        }

        [CommandHipc(132)]
        // EnableUnintendedHomeButtonInputProtection(bool Enable, uint Unknown0, nn::applet::AppletResourceUserId)
        public ResultCode EnableUnintendedHomeButtonInputProtection(ServiceCtx context)
        {
            _unintendedHomeButtonInputProtectionEnabled = context.RequestData.ReadBoolean();
            uint  unknown0                              = context.RequestData.ReadUInt32();
            long appletResourceUserId                   = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, unknown0, _unintendedHomeButtonInputProtectionEnabled });

            return ResultCode.Success;
        }

        [CommandHipc(133)] // 5.0.0+
        // SetNpadJoyAssignmentModeSingleWithDestination(uint HidControllerId, long HidNpadJoyDeviceType, nn::applet::AppletResourceUserId) -> bool Unknown0, uint Unknown1
        public ResultCode SetNpadJoyAssignmentModeSingleWithDestination(ServiceCtx context)
        {
            PlayerIndex          hidControllerId      = (PlayerIndex)context.RequestData.ReadInt32();
            HidNpadJoyDeviceType hidNpadJoyDeviceType = (HidNpadJoyDeviceType)context.RequestData.ReadInt64();
            long                 appletResourceUserId = context.RequestData.ReadInt64();

            _npadJoyAssignmentMode = HidNpadJoyAssignmentMode.Single;

            context.ResponseData.Write(0); //Unknown0
            context.ResponseData.Write(0); //Unknown1

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new {
                appletResourceUserId,
                hidControllerId,
                hidNpadJoyDeviceType,
                _npadJoyAssignmentMode,
                Unknown0 = 0,
                Unknown1 = 0
            });

            return ResultCode.Success;
        }

        [CommandHipc(200)]
        // GetVibrationDeviceInfo(nn::hid::VibrationDeviceHandle) -> nn::hid::VibrationDeviceInfo
        public ResultCode GetVibrationDeviceInfo(ServiceCtx context)
        {
            HidVibrationDeviceHandle deviceHandle = context.RequestData.ReadStruct<HidVibrationDeviceHandle>();
            NpadStyleIndex deviceType = (NpadStyleIndex)deviceHandle.DeviceType;
            NpadIdType npadIdType = (NpadIdType)deviceHandle.PlayerId;

            if (deviceType < NpadStyleIndex.System || deviceType >= NpadStyleIndex.FullKey)
            {
                if (npadIdType >= (NpadIdType.Player8 + 1) && npadIdType != NpadIdType.Handheld && npadIdType != NpadIdType.Unknown)
                {
                    return ResultCode.InvalidNpadIdType;
                }

                if (deviceHandle.Position > 1)
                {
                    return ResultCode.InvalidDeviceIndex;
                }

                HidVibrationDeviceType vibrationDeviceType = HidVibrationDeviceType.None;

                if (Enum.IsDefined(typeof(NpadStyleIndex), deviceType))
                {
                    vibrationDeviceType = HidVibrationDeviceType.LinearResonantActuator;
                }
                else if ((uint)deviceType == 8)
                {
                    vibrationDeviceType = HidVibrationDeviceType.GcErm;
                }

                HidVibrationDevicePosition vibrationDevicePosition = HidVibrationDevicePosition.None;

                if (vibrationDeviceType == HidVibrationDeviceType.LinearResonantActuator)
                {
                    if (deviceHandle.Position == 0)
                    {
                        vibrationDevicePosition = HidVibrationDevicePosition.Left;
                    }
                    else if (deviceHandle.Position == 1)
                    {
                        vibrationDevicePosition = HidVibrationDevicePosition.Right;
                    }
                    else
                    {
                        throw new ArgumentOutOfRangeException(nameof(deviceHandle.Position));
                    }
                }

                HidVibrationDeviceValue deviceInfo = new HidVibrationDeviceValue
                {
                    DeviceType = vibrationDeviceType,
                    Position = vibrationDevicePosition
                };

                context.ResponseData.WriteStruct(deviceInfo);

                return ResultCode.Success;
            }

            return ResultCode.InvalidNpadDeviceType;
        }

        [CommandHipc(201)]
        // SendVibrationValue(nn::hid::VibrationDeviceHandle, nn::hid::VibrationValue, nn::applet::AppletResourceUserId)
        public ResultCode SendVibrationValue(ServiceCtx context)
        {
            HidVibrationDeviceHandle deviceHandle = new HidVibrationDeviceHandle
            {
                DeviceType = context.RequestData.ReadByte(),
                PlayerId = context.RequestData.ReadByte(),
                Position = context.RequestData.ReadByte(),
                Reserved = context.RequestData.ReadByte()
            };

            HidVibrationValue vibrationValue = new HidVibrationValue
            {
                AmplitudeLow  = context.RequestData.ReadSingle(),
                FrequencyLow  = context.RequestData.ReadSingle(),
                AmplitudeHigh = context.RequestData.ReadSingle(),
                FrequencyHigh = context.RequestData.ReadSingle()
            };

            long appletResourceUserId = context.RequestData.ReadInt64();

            Dictionary<byte, HidVibrationValue> dualVibrationValues = new Dictionary<byte, HidVibrationValue>();

            dualVibrationValues[deviceHandle.Position] = vibrationValue;

            context.Device.Hid.Npads.UpdateRumbleQueue((PlayerIndex)deviceHandle.PlayerId, dualVibrationValues);

            return ResultCode.Success;
        }

        [CommandHipc(202)]
        // GetActualVibrationValue(nn::hid::VibrationDeviceHandle, nn::applet::AppletResourceUserId) -> nn::hid::VibrationValue
        public ResultCode GetActualVibrationValue(ServiceCtx context)
        {
            HidVibrationDeviceHandle deviceHandle = new HidVibrationDeviceHandle
            {
                DeviceType = context.RequestData.ReadByte(),
                PlayerId = context.RequestData.ReadByte(),
                Position = context.RequestData.ReadByte(),
                Reserved = context.RequestData.ReadByte()
            };

            long appletResourceUserId = context.RequestData.ReadInt64();

            HidVibrationValue vibrationValue = context.Device.Hid.Npads.GetLastVibrationValue((PlayerIndex)deviceHandle.PlayerId, deviceHandle.Position);

            context.ResponseData.Write(vibrationValue.AmplitudeLow);
            context.ResponseData.Write(vibrationValue.FrequencyLow);
            context.ResponseData.Write(vibrationValue.AmplitudeHigh);
            context.ResponseData.Write(vibrationValue.FrequencyHigh);

            return ResultCode.Success;
        }

        [CommandHipc(203)]
        // CreateActiveVibrationDeviceList() -> object<nn::hid::IActiveVibrationDeviceList>
        public ResultCode CreateActiveVibrationDeviceList(ServiceCtx context)
        {
            MakeObject(context, new IActiveApplicationDeviceList());

            return ResultCode.Success;
        }

        [CommandHipc(204)]
        // PermitVibration(bool Enable)
        public ResultCode PermitVibration(ServiceCtx context)
        {
            _vibrationPermitted = context.RequestData.ReadBoolean();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { _vibrationPermitted });

            return ResultCode.Success;
        }

        [CommandHipc(205)]
        // IsVibrationPermitted() -> bool IsEnabled
        public ResultCode IsVibrationPermitted(ServiceCtx context)
        {
            context.ResponseData.Write(_vibrationPermitted);

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { _vibrationPermitted });

            return ResultCode.Success;
        }

        [CommandHipc(206)]
        // SendVibrationValues(nn::applet::AppletResourceUserId, buffer<array<nn::hid::VibrationDeviceHandle>, type: 9>, buffer<array<nn::hid::VibrationValue>, type: 9>)
        public ResultCode SendVibrationValues(ServiceCtx context)
        {
            long appletResourceUserId = context.RequestData.ReadInt64();

            byte[] vibrationDeviceHandleBuffer = new byte[context.Request.PtrBuff[0].Size];

            context.Memory.Read(context.Request.PtrBuff[0].Position, vibrationDeviceHandleBuffer);

            byte[] vibrationValueBuffer = new byte[context.Request.PtrBuff[1].Size];

            context.Memory.Read(context.Request.PtrBuff[1].Position, vibrationValueBuffer);

            Span<HidVibrationDeviceHandle> deviceHandles = MemoryMarshal.Cast<byte, HidVibrationDeviceHandle>(vibrationDeviceHandleBuffer);
            Span<HidVibrationValue> vibrationValues = MemoryMarshal.Cast<byte, HidVibrationValue>(vibrationValueBuffer);

            if (!deviceHandles.IsEmpty && vibrationValues.Length == deviceHandles.Length)
            {
                Dictionary<byte, HidVibrationValue> dualVibrationValues = new Dictionary<byte, HidVibrationValue>();
                PlayerIndex currentIndex = (PlayerIndex)deviceHandles[0].PlayerId;

                for (int deviceCounter = 0; deviceCounter < deviceHandles.Length; deviceCounter++)
                {
                    PlayerIndex index = (PlayerIndex)deviceHandles[deviceCounter].PlayerId;
                    byte position = deviceHandles[deviceCounter].Position;

                    if (index != currentIndex || dualVibrationValues.Count == 2)
                    {
                        context.Device.Hid.Npads.UpdateRumbleQueue(currentIndex, dualVibrationValues);
                        dualVibrationValues = new Dictionary<byte, HidVibrationValue>();
                    }

                    dualVibrationValues[position] = vibrationValues[deviceCounter];
                    currentIndex = index;
                }

                context.Device.Hid.Npads.UpdateRumbleQueue(currentIndex, dualVibrationValues);
            }

            return ResultCode.Success;
        }

        [CommandHipc(207)] // 4.0.0+
        // SendVibrationGcErmCommand(nn::hid::VibrationDeviceHandle, nn::hid::VibrationGcErmCommand, nn::applet::AppletResourceUserId)
        public ResultCode SendVibrationGcErmCommand(ServiceCtx context)
        {
            int  vibrationDeviceHandle = context.RequestData.ReadInt32();
            long vibrationGcErmCommand = context.RequestData.ReadInt64();
            long appletResourceUserId  = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, vibrationDeviceHandle, vibrationGcErmCommand });

            return ResultCode.Success;
        }

        [CommandHipc(208)] // 4.0.0+
        // GetActualVibrationGcErmCommand(nn::hid::VibrationDeviceHandle, nn::applet::AppletResourceUserId) -> nn::hid::VibrationGcErmCommand
        public ResultCode GetActualVibrationGcErmCommand(ServiceCtx context)
        {
            int  vibrationDeviceHandle = context.RequestData.ReadInt32();
            long appletResourceUserId  = context.RequestData.ReadInt64();

            context.ResponseData.Write(_vibrationGcErmCommand);

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, vibrationDeviceHandle, _vibrationGcErmCommand });

            return ResultCode.Success;
        }

        [CommandHipc(209)] // 4.0.0+
        // BeginPermitVibrationSession(nn::applet::AppletResourceUserId)
        public ResultCode BeginPermitVibrationSession(ServiceCtx context)
        {
            long appletResourceUserId = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId });

            return ResultCode.Success;
        }

        [CommandHipc(210)] // 4.0.0+
        // EndPermitVibrationSession()
        public ResultCode EndPermitVibrationSession(ServiceCtx context)
        {
            Logger.Stub?.PrintStub(LogClass.ServiceHid);

            return ResultCode.Success;
        }

        [CommandHipc(211)] // 7.0.0+
        // IsVibrationDeviceMounted(nn::hid::VibrationDeviceHandle, nn::applet::AppletResourceUserId)
        public ResultCode IsVibrationDeviceMounted(ServiceCtx context)
        {
            int  vibrationDeviceHandle = context.RequestData.ReadInt32();
            long appletResourceUserId  = context.RequestData.ReadInt64();

            // NOTE: Service use vibrationDeviceHandle to get the PlayerIndex.
            //       And return false if (npadIdType >= (NpadIdType)8 && npadIdType != NpadIdType.Handheld && npadIdType != NpadIdType.Unknown)

            context.ResponseData.Write(true);

            return ResultCode.Success;
        }

        [CommandHipc(300)]
        // ActivateConsoleSixAxisSensor(nn::applet::AppletResourceUserId)
        public ResultCode ActivateConsoleSixAxisSensor(ServiceCtx context)
        {
            long appletResourceUserId = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId });

            return ResultCode.Success;
        }

        [CommandHipc(301)]
        // StartConsoleSixAxisSensor(nn::hid::ConsoleSixAxisSensorHandle, nn::applet::AppletResourceUserId)
        public ResultCode StartConsoleSixAxisSensor(ServiceCtx context)
        {
            int  consoleSixAxisSensorHandle = context.RequestData.ReadInt32();
            long appletResourceUserId       = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, consoleSixAxisSensorHandle });

            return ResultCode.Success;
        }

        [CommandHipc(302)]
        // StopConsoleSixAxisSensor(nn::hid::ConsoleSixAxisSensorHandle, nn::applet::AppletResourceUserId)
        public ResultCode StopConsoleSixAxisSensor(ServiceCtx context)
        {
            int  consoleSixAxisSensorHandle = context.RequestData.ReadInt32();
            long appletResourceUserId       = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, consoleSixAxisSensorHandle });

            return ResultCode.Success;
        }

        [CommandHipc(303)] // 5.0.0+
        // ActivateSevenSixAxisSensor(nn::applet::AppletResourceUserId)
        public ResultCode ActivateSevenSixAxisSensor(ServiceCtx context)
        {
            long appletResourceUserId = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId });

            return ResultCode.Success;
        }

        [CommandHipc(304)] // 5.0.0+
        // StartSevenSixAxisSensor(nn::applet::AppletResourceUserId)
        public ResultCode StartSevenSixAxisSensor(ServiceCtx context)
        {
            long appletResourceUserId = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId });

            return ResultCode.Success;
        }

        [CommandHipc(305)] // 5.0.0+
        // StopSevenSixAxisSensor(nn::applet::AppletResourceUserId)
        public ResultCode StopSevenSixAxisSensor(ServiceCtx context)
        {
            long appletResourceUserId = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId });

            return ResultCode.Success;
        }

        [CommandHipc(306)] // 5.0.0+
        // InitializeSevenSixAxisSensor(array<nn::sf::NativeHandle>, ulong Counter0, array<nn::sf::NativeHandle>, ulong Counter1, nn::applet::AppletResourceUserId)
        public ResultCode InitializeSevenSixAxisSensor(ServiceCtx context)
        {
            long appletResourceUserId = context.RequestData.ReadInt64();
            long counter0             = context.RequestData.ReadInt64();
            long counter1             = context.RequestData.ReadInt64();

            // TODO: Determine if array<nn::sf::NativeHandle> is a buffer or not...

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, counter0, counter1 });

            return ResultCode.Success;
        }

        [CommandHipc(307)] // 5.0.0+
        // FinalizeSevenSixAxisSensor(nn::applet::AppletResourceUserId)
        public ResultCode FinalizeSevenSixAxisSensor(ServiceCtx context)
        {
            long appletResourceUserId = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId });

            return ResultCode.Success;
        }

        [CommandHipc(308)] // 5.0.0+
        // SetSevenSixAxisSensorFusionStrength(float Strength, nn::applet::AppletResourceUserId)
        public ResultCode SetSevenSixAxisSensorFusionStrength(ServiceCtx context)
        {
                 _sevenSixAxisSensorFusionStrength = context.RequestData.ReadSingle();
            long appletResourceUserId              = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, _sevenSixAxisSensorFusionStrength });

            return ResultCode.Success;
        }

        [CommandHipc(309)] // 5.0.0+
        // GetSevenSixAxisSensorFusionStrength(nn::applet::AppletResourceUserId) -> float Strength
        public ResultCode GetSevenSixAxisSensorFusionStrength(ServiceCtx context)
        {
            long appletResourceUserId = context.RequestData.ReadInt64();

            context.ResponseData.Write(_sevenSixAxisSensorFusionStrength);

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, _sevenSixAxisSensorFusionStrength });

            return ResultCode.Success;
        }

        [CommandHipc(310)] // 6.0.0+
        // ResetSevenSixAxisSensorTimestamp(pid, nn::applet::AppletResourceUserId)
        public ResultCode ResetSevenSixAxisSensorTimestamp(ServiceCtx context)
        {
            long appletResourceUserId = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId });

            return ResultCode.Success;
        }

        [CommandHipc(400)]
        // IsUsbFullKeyControllerEnabled() -> bool IsEnabled
        public ResultCode IsUsbFullKeyControllerEnabled(ServiceCtx context)
        {
            context.ResponseData.Write(_usbFullKeyControllerEnabled);

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { _usbFullKeyControllerEnabled });

            return ResultCode.Success;
        }

        [CommandHipc(401)]
        // EnableUsbFullKeyController(bool Enable)
        public ResultCode EnableUsbFullKeyController(ServiceCtx context)
        {
            _usbFullKeyControllerEnabled = context.RequestData.ReadBoolean();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { _usbFullKeyControllerEnabled });

            return ResultCode.Success;
        }

        [CommandHipc(402)]
        // IsUsbFullKeyControllerConnected(uint Unknown0) -> bool Connected
        public ResultCode IsUsbFullKeyControllerConnected(ServiceCtx context)
        {
            int unknown0 = context.RequestData.ReadInt32();

            context.ResponseData.Write(true); //FullKeyController is always connected ?

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { unknown0, Connected = true });

            return ResultCode.Success;
        }

        [CommandHipc(403)] // 4.0.0+
        // HasBattery(uint NpadId) -> bool HasBattery
        public ResultCode HasBattery(ServiceCtx context)
        {
            int npadId = context.RequestData.ReadInt32();

            context.ResponseData.Write(true); //Npad always got a battery ?

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { npadId, HasBattery = true });

            return ResultCode.Success;
        }

        [CommandHipc(404)] // 4.0.0+
        // HasLeftRightBattery(uint NpadId) -> bool HasLeftBattery, bool HasRightBattery
        public ResultCode HasLeftRightBattery(ServiceCtx context)
        {
            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 ?

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { npadId, HasLeftBattery = true, HasRightBattery = true });

            return ResultCode.Success;
        }

        [CommandHipc(405)] // 4.0.0+
        // GetNpadInterfaceType(uint NpadId) -> uchar InterfaceType
        public ResultCode GetNpadInterfaceType(ServiceCtx context)
        {
            int npadId = context.RequestData.ReadInt32();

            context.ResponseData.Write((byte)0);

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { npadId, NpadInterfaceType = 0 });

            return ResultCode.Success;
        }

        [CommandHipc(406)] // 4.0.0+
        // GetNpadLeftRightInterfaceType(uint NpadId) -> uchar LeftInterfaceType, uchar RightInterfaceType
        public ResultCode GetNpadLeftRightInterfaceType(ServiceCtx context)
        {
            int npadId = context.RequestData.ReadInt32();

            context.ResponseData.Write((byte)0);
            context.ResponseData.Write((byte)0);

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { npadId, LeftInterfaceType = 0, RightInterfaceType = 0 });

            return ResultCode.Success;
        }

        [CommandHipc(500)] // 5.0.0+
        // GetPalmaConnectionHandle(uint Unknown0, nn::applet::AppletResourceUserId) -> nn::hid::PalmaConnectionHandle
        public ResultCode GetPalmaConnectionHandle(ServiceCtx context)
        {
            int  unknown0             = context.RequestData.ReadInt32();
            long appletResourceUserId = context.RequestData.ReadInt64();

            int palmaConnectionHandle = 0;

            context.ResponseData.Write(palmaConnectionHandle);

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId , unknown0, palmaConnectionHandle });

            return ResultCode.Success;
        }

        [CommandHipc(501)] // 5.0.0+
        // InitializePalma(nn::hid::PalmaConnectionHandle)
        public ResultCode InitializePalma(ServiceCtx context)
        {
            int palmaConnectionHandle = context.RequestData.ReadInt32();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { palmaConnectionHandle });

            _palmaOperationCompleteEvent.ReadableEvent.Signal();

            return ResultCode.Success;
        }

        [CommandHipc(502)] // 5.0.0+
        // AcquirePalmaOperationCompleteEvent(nn::hid::PalmaConnectionHandle) -> nn::sf::NativeHandle
        public ResultCode AcquirePalmaOperationCompleteEvent(ServiceCtx context)
        {
            int palmaConnectionHandle = context.RequestData.ReadInt32();

            if (context.Process.HandleTable.GenerateHandle(_palmaOperationCompleteEvent.ReadableEvent, out int handle) != KernelResult.Success)
            {
                throw new InvalidOperationException("Out of handles!");
            }

            context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle);

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { palmaConnectionHandle });

            return ResultCode.Success;
        }

        [CommandHipc(503)] // 5.0.0+
        // GetPalmaOperationInfo(nn::hid::PalmaConnectionHandle) -> long Unknown0, buffer<Unknown>
        public ResultCode GetPalmaOperationInfo(ServiceCtx context)
        {
            int palmaConnectionHandle = context.RequestData.ReadInt32();

            long unknown0 = 0; //Counter?

            context.ResponseData.Write(unknown0);

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { palmaConnectionHandle, unknown0 });

            return ResultCode.Success;
        }

        [CommandHipc(504)] // 5.0.0+
        // PlayPalmaActivity(nn::hid::PalmaConnectionHandle, ulong Unknown0)
        public ResultCode PlayPalmaActivity(ServiceCtx context)
        {
            int  palmaConnectionHandle = context.RequestData.ReadInt32();
            long unknown0              = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { palmaConnectionHandle, unknown0 });

            _palmaOperationCompleteEvent.ReadableEvent.Signal();

            return ResultCode.Success;
        }

        [CommandHipc(505)] // 5.0.0+
        // SetPalmaFrModeType(nn::hid::PalmaConnectionHandle, ulong FrModeType)
        public ResultCode SetPalmaFrModeType(ServiceCtx context)
        {
            int  palmaConnectionHandle = context.RequestData.ReadInt32();
            long frModeType            = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { palmaConnectionHandle, frModeType });

            _palmaOperationCompleteEvent.ReadableEvent.Signal();

            return ResultCode.Success;
        }

        [CommandHipc(506)] // 5.0.0+
        // ReadPalmaStep(nn::hid::PalmaConnectionHandle)
        public ResultCode ReadPalmaStep(ServiceCtx context)
        {
            int palmaConnectionHandle = context.RequestData.ReadInt32();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { palmaConnectionHandle });

            return ResultCode.Success;
        }

        [CommandHipc(507)] // 5.0.0+
        // EnablePalmaStep(nn::hid::PalmaConnectionHandle, bool Enable)
        public ResultCode EnablePalmaStep(ServiceCtx context)
        {
            int  palmaConnectionHandle = context.RequestData.ReadInt32();
            bool enabledPalmaStep      = context.RequestData.ReadBoolean();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { palmaConnectionHandle, enabledPalmaStep });

            _palmaOperationCompleteEvent.ReadableEvent.Signal();

            return ResultCode.Success;
        }

        [CommandHipc(508)] // 5.0.0+
        // ResetPalmaStep(nn::hid::PalmaConnectionHandle)
        public ResultCode ResetPalmaStep(ServiceCtx context)
        {
            int palmaConnectionHandle = context.RequestData.ReadInt32();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { palmaConnectionHandle });

            _palmaOperationCompleteEvent.ReadableEvent.Signal();

            return ResultCode.Success;
        }

        [CommandHipc(509)] // 5.0.0+
        // ReadPalmaApplicationSection(nn::hid::PalmaConnectionHandle, ulong Unknown0, ulong Unknown1)
        public ResultCode ReadPalmaApplicationSection(ServiceCtx context)
        {
            int  palmaConnectionHandle = context.RequestData.ReadInt32();
            long unknown0              = context.RequestData.ReadInt64();
            long unknown1              = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { palmaConnectionHandle, unknown0, unknown1 });

            return ResultCode.Success;
        }

        [CommandHipc(510)] // 5.0.0+
        // WritePalmaApplicationSection(nn::hid::PalmaConnectionHandle, ulong Unknown0, ulong Unknown1, nn::hid::PalmaApplicationSectionAccessBuffer)
        public ResultCode WritePalmaApplicationSection(ServiceCtx context)
        {
            int  palmaConnectionHandle = context.RequestData.ReadInt32();
            long unknown0              = context.RequestData.ReadInt64();
            long unknown1              = context.RequestData.ReadInt64();
            // nn::hid::PalmaApplicationSectionAccessBuffer cast is unknown

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { palmaConnectionHandle, unknown0, unknown1 });

            _palmaOperationCompleteEvent.ReadableEvent.Signal();

            return ResultCode.Success;
        }

        [CommandHipc(511)] // 5.0.0+
        // ReadPalmaUniqueCode(nn::hid::PalmaConnectionHandle)
        public ResultCode ReadPalmaUniqueCode(ServiceCtx context)
        {
            int palmaConnectionHandle = context.RequestData.ReadInt32();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { palmaConnectionHandle });

            return ResultCode.Success;
        }

        [CommandHipc(512)] // 5.0.0+
        // SetPalmaUniqueCodeInvalid(nn::hid::PalmaConnectionHandle)
        public ResultCode SetPalmaUniqueCodeInvalid(ServiceCtx context)
        {
            int palmaConnectionHandle = context.RequestData.ReadInt32();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { palmaConnectionHandle });

            return ResultCode.Success;
        }

        [CommandHipc(522)] // 5.1.0+
        // SetIsPalmaAllConnectable(nn::applet::AppletResourceUserId, bool, pid)
        public ResultCode SetIsPalmaAllConnectable(ServiceCtx context)
        {
            long appletResourceUserId = context.RequestData.ReadInt64();
            long unknownBool          = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, unknownBool });

            return ResultCode.Success;
        }

        [CommandHipc(525)] // 5.1.0+
        // SetPalmaBoostMode(bool)
        public ResultCode SetPalmaBoostMode(ServiceCtx context)
        {
            // NOTE: Stubbed in system module.

            return ResultCode.Success;
        }

        [CommandHipc(1000)]
        // SetNpadCommunicationMode(long CommunicationMode, nn::applet::AppletResourceUserId)
        public ResultCode SetNpadCommunicationMode(ServiceCtx context)
        {
                 _npadCommunicationMode = context.RequestData.ReadInt64();
            long appletResourceUserId   = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, _npadCommunicationMode });

            return ResultCode.Success;
        }

        [CommandHipc(1001)]
        // GetNpadCommunicationMode() -> long CommunicationMode
        public ResultCode GetNpadCommunicationMode(ServiceCtx context)
        {
            context.ResponseData.Write(_npadCommunicationMode);

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { _npadCommunicationMode });

            return ResultCode.Success;
        }

        [CommandHipc(1002)] // 9.0.0+
        // SetTouchScreenConfiguration(nn::hid::TouchScreenConfigurationForNx, nn::applet::AppletResourceUserId)
        public ResultCode SetTouchScreenConfiguration(ServiceCtx context)
        {
            long touchScreenConfigurationForNx = context.RequestData.ReadInt64();
            long appletResourceUserId          = context.RequestData.ReadInt64();

            Logger.Stub?.PrintStub(LogClass.ServiceHid, new { appletResourceUserId, touchScreenConfigurationForNx });

            return ResultCode.Success;
        }
    }
}


<|start_filename|>Ryujinx.HLE/HOS/Tamper/CodeEmitters/EndConditionalBlock.cs<|end_filename|>
﻿using Ryujinx.HLE.Exceptions;
using Ryujinx.HLE.HOS.Tamper.Conditions;
using Ryujinx.HLE.HOS.Tamper.Operations;
using System.Collections.Generic;

namespace Ryujinx.HLE.HOS.Tamper.CodeEmitters
{
    /// <summary>
    /// Code type 2 marks the end of a conditional block (started by Code Type 1, Code Type 8 or Code Type C0).
    /// </summary>
    class EndConditionalBlock
    {
        const int TerminationTypeIndex = 1;

        private const byte End  = 0; // True end of the conditional.
        private const byte Else = 1; // End of the 'then' block and beginning of 'else' block.

        public static void Emit(byte[] instruction, CompilationContext context)
        {
            Emit(instruction, context, null);
        }

        private static void Emit(byte[] instruction, CompilationContext context, IEnumerable<IOperation> operationsElse)
        {
            // 2X000000
            // X: End type (0 = End, 1 = Else).

            byte terminationType = instruction[TerminationTypeIndex];

            switch (terminationType)
            {
                case End:
                    break;
                case Else:
                    // Start a new operation block with the 'else' instruction to signal that there is the 'then' block just above it.
                    context.BlockStack.Push(new OperationBlock(instruction));
                    return;
                default:
                    throw new TamperCompilationException($"Unknown conditional termination type {terminationType}");
            }

            // Use the conditional begin instruction stored in the stack.
            var upperInstruction = context.CurrentBlock.BaseInstruction;
            CodeType codeType = InstructionHelper.GetCodeType(upperInstruction);

            // Pop the current block of operations from the stack so control instructions
            // for the conditional can be emitted in the upper block.
            IEnumerable<IOperation> operations = context.CurrentOperations;
            context.BlockStack.Pop();

            // If the else operations are already set, then the upper block must not be another end.
            if (operationsElse != null && codeType == CodeType.EndConditionalBlock)
            {
                throw new TamperCompilationException($"Expected an upper 'if' conditional instead of 'end conditional'");
            }

            ICondition condition;

            switch (codeType)
            {
                case CodeType.BeginMemoryConditionalBlock:
                    condition = MemoryConditional.Emit(upperInstruction, context);
                    break;
                case CodeType.BeginKeypressConditionalBlock:
                    condition = KeyPressConditional.Emit(upperInstruction, context);
                    break;
                case CodeType.BeginRegisterConditionalBlock:
                    condition = RegisterConditional.Emit(upperInstruction, context);
                    break;
                case CodeType.EndConditionalBlock:
                    terminationType = upperInstruction[TerminationTypeIndex];
                    // If there is an end instruction above then it must be an else.
                    if (terminationType != Else)
                    {
                        throw new TamperCompilationException($"Expected an upper 'else' conditional instead of {terminationType}");
                    }
                    // Re-run the Emit with the else operations set.
                    Emit(instruction, context, operations);
                    return;
                default:
                    throw new TamperCompilationException($"Conditional end does not match code type {codeType} in Atmosphere cheat");
            }

            // Create a conditional block with the current operations and nest it in the upper
            // block of the stack.

            IfBlock block = new IfBlock(condition, operations, operationsElse);
            context.CurrentOperations.Add(block);
        }
    }
}


<|start_filename|>Ryujinx.HLE/HOS/Tamper/TamperedKProcess.cs<|end_filename|>
﻿using Ryujinx.Common.Logging;
using Ryujinx.HLE.Exceptions;
using Ryujinx.HLE.HOS.Kernel.Process;
using System.Runtime.CompilerServices;

namespace Ryujinx.HLE.HOS.Tamper
{
    class TamperedKProcess : ITamperedProcess
    {
        private KProcess _process;

        public ProcessState State => _process.State;

        public bool TamperedCodeMemory { get; set; } = false;

        public TamperedKProcess(KProcess process)
        {
            _process = process;
        }

        private void AssertMemoryRegion<T>(ulong va, bool isWrite) where T : unmanaged
        {
            ulong size = (ulong)Unsafe.SizeOf<T>();

            // TODO (Caian): This double check is workaround because CpuMemory.IsRangeMapped reports
            // some addresses as mapped even though they are not, i. e. 4 bytes from 0xffffffffffffff70.
            if (!_process.CpuMemory.IsMapped(va) || !_process.CpuMemory.IsRangeMapped(va, size))
            {
                throw new TamperExecutionException($"Unmapped memory access of {size} bytes at 0x{va:X16}");
            }

            if (!isWrite)
            {
                return;
            }

            // TODO (Caian): The JIT does not support invalidating a code region so writing to code memory may not work
            // as intended, so taint the operation to issue a warning later.
            if (isWrite && (va >= _process.MemoryManager.CodeRegionStart) && (va + size <= _process.MemoryManager.CodeRegionEnd))
            {
                TamperedCodeMemory = true;
            }
        }

        public T ReadMemory<T>(ulong va) where T : unmanaged
        {
            AssertMemoryRegion<T>(va, false);

            return _process.CpuMemory.Read<T>(va);
        }

        public void WriteMemory<T>(ulong va, T value) where T : unmanaged
        {
            AssertMemoryRegion<T>(va, true);
            _process.CpuMemory.Write(va, value);
        }

        public void PauseProcess()
        {
            Logger.Warning?.Print(LogClass.TamperMachine, "Process pausing is not supported!");
        }

        public void ResumeProcess()
        {
            Logger.Warning?.Print(LogClass.TamperMachine, "Process resuming is not supported!");
        }
    }
}

<|start_filename|>Ryujinx.HLE/HOS/Tamper/ITamperedProcess.cs<|end_filename|>
using Ryujinx.HLE.HOS.Kernel.Process;

namespace Ryujinx.HLE.HOS.Tamper
{
    interface ITamperedProcess
    {
        ProcessState State { get; }

        bool TamperedCodeMemory { get; set; }

        T ReadMemory<T>(ulong va) where T : unmanaged;
        void WriteMemory<T>(ulong va, T value) where T : unmanaged;
        void PauseProcess();
        void ResumeProcess();
    }
}


<|start_filename|>Ryujinx.Common/Hash128.cs<|end_filename|>
﻿using System;
using System.Runtime.InteropServices;

namespace Ryujinx.Common
{
    [StructLayout(LayoutKind.Sequential)]
    public struct Hash128 : IEquatable<Hash128>
    {
        public ulong Low;
        public ulong High;

        public Hash128(ulong low, ulong high)
        {
            Low = low;
            High = high;
        }

        public override string ToString()
        {
            return $"{High:x16}{Low:x16}";
        }

        public static bool operator ==(Hash128 x, Hash128 y)
        {
            return x.Equals(y);
        }

        public static bool operator !=(Hash128 x, Hash128 y)
        {
            return !x.Equals(y);
        }

        public override bool Equals(object obj)
        {
            return obj is Hash128 hash128 && Equals(hash128);
        }

        public bool Equals(Hash128 cmpObj)
        {
            return Low == cmpObj.Low && High == cmpObj.High;
        }

        public override int GetHashCode()
        {
            return HashCode.Combine(Low, High);
        }
    }
}


<|start_filename|>Ryujinx.Graphics.Gpu/Image/TextureScaleMode.cs<|end_filename|>
﻿namespace Ryujinx.Graphics.Gpu.Image
{
    /// <summary>
    /// The scale mode for a given texture.
    /// Blacklisted textures cannot be scaled, Eligible textures have not been scaled yet,
    /// and Scaled textures have been scaled already.
    /// Undesired textures will stay at 1x until a situation where they must match a scaled texture.
    /// </summary>
    enum TextureScaleMode
    {
        Eligible = 0,
        Scaled = 1,
        Blacklisted = 2,
        Undesired = 3
    }
}


<|start_filename|>Ryujinx.Input/IGamepad.cs<|end_filename|>
﻿using Ryujinx.Common.Configuration.Hid;
using Ryujinx.Common.Memory;
using System;
using System.Numerics;
using System.Runtime.CompilerServices;

namespace Ryujinx.Input
{
    /// <summary>
    /// Represent an emulated gamepad.
    /// </summary>
    public interface IGamepad : IDisposable
    {
        /// <summary>
        /// Features supported by the gamepad.
        /// </summary>
        GamepadFeaturesFlag Features { get; }

        /// <summary>
        /// Unique Id of the gamepad.
        /// </summary>
        string Id { get; }

        /// <summary>
        /// The name of the gamepad.
        /// </summary>
        string Name { get; }

        /// <summary>
        /// True if the gamepad is connected.
        /// </summary>
        bool IsConnected { get; }

        /// <summary>
        /// Check if a given input button is pressed on the gamepad.
        /// </summary>
        /// <param name="inputId">The button id</param>
        /// <returns>True if the given button is pressed on the gamepad</returns>
        bool IsPressed(GamepadButtonInputId inputId);

        /// <summary>
        /// Get the values of a given input joystick on the gamepad.
        /// </summary>
        /// <param name="inputId">The stick id</param>
        /// <returns>The values of the given input joystick on the gamepad</returns>
        (float, float) GetStick(StickInputId inputId);

        /// <summary>
        /// Get the values of a given motion sensors on the gamepad.
        /// </summary>
        /// <param name="inputId">The motion id</param>
        /// <returns> The values of the given motion sensors on the gamepad.</returns>
        Vector3 GetMotionData(MotionInputId inputId);

        /// <summary>
        /// Configure the threshold of the triggers on the gamepad.
        /// </summary>
        /// <param name="triggerThreshold">The threshold value for the triggers on the gamepad</param>
        void SetTriggerThreshold(float triggerThreshold);

        /// <summary>
        /// Set the configuration of the gamepad.
        /// </summary>
        /// <remarks>This expect config to be in the format expected by the driver</remarks>
        /// <param name="configuration">The configuration of the gamepad</param>
        void SetConfiguration(InputConfig configuration);

        /// <summary>
        /// Starts a rumble effect on the gamepad.
        /// </summary>
        /// <param name="lowFrequency">The intensity of the low frequency from 0.0f to 1.0f</param>
        /// <param name="highFrequency">The intensity of the high frequency from 0.0f to 1.0f</param>
        /// <param name="durationMs">The duration of the rumble effect in milliseconds.</param>
        void Rumble(float lowFrequency, float highFrequency, uint durationMs);

        /// <summary>
        /// Get a snaphost of the state of the gamepad that is remapped with the informations from the <see cref="InputConfig"/> set via <see cref="SetConfiguration(InputConfig)"/>.
        /// </summary>
        /// <returns>A remapped snaphost of the state of the gamepad.</returns>
        GamepadStateSnapshot GetMappedStateSnapshot();

        /// <summary>
        /// Get a snaphost of the state of the gamepad.
        /// </summary>
        /// <returns>A snaphost of the state of the gamepad.</returns>
        GamepadStateSnapshot GetStateSnapshot();

        /// <summary>
        /// Get a snaphost of the state of a gamepad.
        /// </summary>
        /// <param name="gamepad">The gamepad to do a snapshot of</param>
        /// <returns>A snaphost of the state of the gamepad.</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        static GamepadStateSnapshot GetStateSnapshot(IGamepad gamepad)
        {
            // NOTE: Update Array size if JoystickInputId is changed.
            Array3<Array2<float>> joysticksState = default;

            for (StickInputId inputId = StickInputId.Left; inputId < StickInputId.Count; inputId++)
            {
                (float state0, float state1) = gamepad.GetStick(inputId);

                Array2<float> state = default;

                state[0] = state0;
                state[1] = state1;

                joysticksState[(int)inputId] = state;
            }

            // NOTE: Update Array size if GamepadInputId is changed.
            Array28<bool> buttonsState = default;

            for (GamepadButtonInputId inputId = GamepadButtonInputId.A; inputId < GamepadButtonInputId.Count; inputId++)
            {
                buttonsState[(int)inputId] = gamepad.IsPressed(inputId);
            }

            return new GamepadStateSnapshot(joysticksState, buttonsState);
        }
    }
}


<|start_filename|>Ryujinx.HLE/HOS/Tamper/AtmosphereProgram.cs<|end_filename|>
using Ryujinx.HLE.HOS.Services.Hid;
using Ryujinx.HLE.HOS.Tamper.Operations;

namespace Ryujinx.HLE.HOS.Tamper
{
    class AtmosphereProgram : ITamperProgram
    {
        private Parameter<long> _pressedKeys;
        private IOperation _entryPoint;

        public string Name { get; }
        public bool TampersCodeMemory { get; set; } = false;
        public ITamperedProcess Process { get; }

        public AtmosphereProgram(string name, ITamperedProcess process, Parameter<long> pressedKeys, IOperation entryPoint)
        {
            Name = name;
            Process = process;
            _pressedKeys = pressedKeys;
            _entryPoint = entryPoint;
        }

        public void Execute(ControllerKeys pressedKeys)
        {
            _pressedKeys.Value = (long)pressedKeys;
            _entryPoint.Execute();
        }
    }
}


<|start_filename|>Ryujinx.Graphics.Gpu/Shader/ShaderCompileTask.cs<|end_filename|>
﻿using Ryujinx.Graphics.GAL;
using System.Threading;
using System.Threading.Tasks;

namespace Ryujinx.Graphics.Gpu.Shader
{
    delegate bool ShaderCompileTaskCallback(bool success, ShaderCompileTask task);

    /// <summary>
    /// A class that represents a shader compilation.
    /// </summary>
    class ShaderCompileTask
    {
        private bool _compiling;

        private Task _programsTask;
        private IProgram _program;

        private ShaderCompileTaskCallback _action;
        private AutoResetEvent _taskDoneEvent;

        public bool IsFaulted => _programsTask.IsFaulted;

        /// <summary>
        /// Create a new shader compile task, with an event to signal whenever a subtask completes.
        /// </summary>
        /// <param name="taskDoneEvent">Event to signal when a subtask completes</param>
        public ShaderCompileTask(AutoResetEvent taskDoneEvent)
        {
            _taskDoneEvent = taskDoneEvent;
        }

        /// <summary>
        /// Check the completion status of the shader compile task, and run callbacks on step completion.
        /// Calling this periodically is required to progress through steps of the compilation.
        /// </summary>
        /// <returns>True if the task is complete, false if it is in progress</returns>
        public bool IsDone()
        {
            if (_compiling)
            {
                ProgramLinkStatus status = _program.CheckProgramLink(false);

                if (status != ProgramLinkStatus.Incomplete)
                {
                    return _action(status == ProgramLinkStatus.Success, this);
                }
            }
            else
            {
                // Waiting on the task.

                if (_programsTask.IsCompleted)
                {
                    return _action(true, this);
                }
            }

            return false;
        }

        /// <summary>
        /// Run a callback when the specified task has completed.
        /// </summary>
        /// <param name="task">The task object that needs to complete</param>
        /// <param name="action">The action to perform when it is complete</param>
        public void OnTask(Task task, ShaderCompileTaskCallback action)
        {
            _compiling = false;

            _programsTask = task;
            _action = action;

            task.ContinueWith(task => _taskDoneEvent.Set());
        }

        /// <summary>
        /// Run a callback when the specified program has been linked.
        /// </summary>
        /// <param name="task">The program that needs to be linked</param>
        /// <param name="action">The action to perform when linking is complete</param>
        public void OnCompiled(IProgram program, ShaderCompileTaskCallback action)
        {
            _compiling = true;

            _program = program;
            _action = action;

            if (program == null)
            {
                action(false, this);
            }
        }
    }
}


<|start_filename|>Ryujinx.HLE/HOS/Services/Fs/IMultiCommitManager.cs<|end_filename|>
﻿using LibHac;
using Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy;

namespace Ryujinx.HLE.HOS.Services.Fs
{
    class IMultiCommitManager : DisposableIpcService // 6.0.0+
    {
        private ReferenceCountedDisposable<LibHac.FsSrv.Sf.IMultiCommitManager> _baseCommitManager;

        public IMultiCommitManager(ReferenceCountedDisposable<LibHac.FsSrv.Sf.IMultiCommitManager> baseCommitManager)
        {
            _baseCommitManager = baseCommitManager;
        }

        [CommandHipc(1)] // 6.0.0+
        // Add(object<nn::fssrv::sf::IFileSystem>)
        public ResultCode Add(ServiceCtx context)
        {
            IFileSystem fileSystem = GetObject<IFileSystem>(context, 0);

            Result result = _baseCommitManager.Target.Add(fileSystem.GetBaseFileSystem());

            return (ResultCode)result.Value;
        }

        [CommandHipc(2)] // 6.0.0+
        // Commit()
        public ResultCode Commit(ServiceCtx context)
        {
            Result result = _baseCommitManager.Target.Commit();

            return (ResultCode)result.Value;
        }

        protected override void Dispose(bool isDisposing)
        {
            if (isDisposing)
            {
                _baseCommitManager?.Dispose();
            }
        }
    }
}


<|start_filename|>Ryujinx.HLE/HOS/Services/Hid/ResultCode.cs<|end_filename|>
﻿namespace Ryujinx.HLE.HOS.Services.Hid
{
    enum ResultCode
    {
        ModuleId       = 202,
        ErrorCodeShift = 9,

        Success = 0,

        InvalidNpadDeviceType = (122 << ErrorCodeShift) | ModuleId,
        InvalidNpadIdType     = (123 << ErrorCodeShift) | ModuleId,
        InvalidDeviceIndex    = (124 << ErrorCodeShift) | ModuleId,
        InvalidBufferSize     = (131 << ErrorCodeShift) | ModuleId
    }
} 

<|start_filename|>Ryujinx.Graphics.Gpu/Engine/MME/IMacroEE.cs<|end_filename|>
﻿using Ryujinx.Graphics.Device;
using System;
using System.Collections.Generic;

namespace Ryujinx.Graphics.Gpu.Engine.MME
{
    /// <summary>
    /// FIFO word.
    /// </summary>
    struct FifoWord
    {
        /// <summary>
        /// GPU virtual address where the word is located in memory.
        /// </summary>
        public ulong GpuVa { get; }

        /// <summary>
        /// Word value.
        /// </summary>
        public int Word { get; }

        /// <summary>
        /// Creates a new FIFO word.
        /// </summary>
        /// <param name="gpuVa">GPU virtual address where the word is located in memory</param>
        /// <param name="word">Word value</param>
        public FifoWord(ulong gpuVa, int word)
        {
            GpuVa = gpuVa;
            Word = word;
        }
    }

    /// <summary>
    /// Macro Execution Engine interface.
    /// </summary>
    interface IMacroEE
    {
        /// <summary>
        /// Arguments FIFO.
        /// </summary>
        Queue<FifoWord> Fifo { get; }

        /// <summary>
        /// Should execute the GPU Macro code being passed.
        /// </summary>
        /// <param name="code">Code to be executed</param>
        /// <param name="state">GPU state at the time of the call</param>
        /// <param name="arg0">First argument to be passed to the GPU Macro</param>
        void Execute(ReadOnlySpan<int> code, IDeviceState state, int arg0);
    }
}


<|start_filename|>Ryujinx.HLE/HOS/Tamper/Operations/IfBlock.cs<|end_filename|>
using Ryujinx.HLE.HOS.Tamper.Conditions;
using System.Collections.Generic;

namespace Ryujinx.HLE.HOS.Tamper.Operations
{
    class IfBlock : IOperation
    {
        private ICondition _condition;
        private IEnumerable<IOperation> _operationsThen;
        private IEnumerable<IOperation> _operationsElse;

        public IfBlock(ICondition condition, IEnumerable<IOperation> operationsThen, IEnumerable<IOperation> operationsElse)
        {
            _condition = condition;
            _operationsThen = operationsThen;
            _operationsElse = operationsElse;
        }

        public void Execute()
        {
            IEnumerable<IOperation> operations = _condition.Evaluate() ? _operationsThen : _operationsElse;

            if (operations == null)
            {
                return;
            }

            foreach (IOperation op in operations)
            {
                op.Execute();
            }
        }
    }
}


<|start_filename|>Ryujinx.HLE/HOS/Tamper/AtmosphereCompiler.cs<|end_filename|>
using Ryujinx.Common.Logging;
using Ryujinx.HLE.Exceptions;
using Ryujinx.HLE.HOS.Tamper.CodeEmitters;
using Ryujinx.HLE.HOS.Tamper.Operations;
using System;
using System.Collections.Generic;

namespace Ryujinx.HLE.HOS.Tamper
{
    class AtmosphereCompiler
    {
        private ulong            _exeAddress;
        private ulong            _heapAddress;
        private ulong            _aliasAddress;
        private ulong            _aslrAddress;
        private ITamperedProcess _process;

        public AtmosphereCompiler(ulong exeAddress, ulong heapAddress, ulong aliasAddress, ulong aslrAddress, ITamperedProcess process)
        {
            _exeAddress   = exeAddress;
            _heapAddress  = heapAddress;
            _aliasAddress = aliasAddress;
            _aslrAddress  = aslrAddress;
            _process      = process;
        }

        public ITamperProgram Compile(string name, IEnumerable<string> rawInstructions)
        {
            string[] addresses = new string[]
            {
                $"    Executable address: 0x{_exeAddress:X16}",
                $"    Heap address      : 0x{_heapAddress:X16}",
                $"    Alias address     : 0x{_aliasAddress:X16}",
                $"    Aslr address      : 0x{_aslrAddress:X16}"
            };

            Logger.Debug?.Print(LogClass.TamperMachine, $"Compiling Atmosphere cheat {name}...\n{string.Join('\n', addresses)}");

            try
            {
                return CompileImpl(name, rawInstructions);
            }
            catch(TamperCompilationException exception)
            {
                // Just print the message without the stack trace.
                Logger.Error?.Print(LogClass.TamperMachine, exception.Message);
            }
            catch (Exception exception)
            {
                Logger.Error?.Print(LogClass.TamperMachine, exception.ToString());
            }

            Logger.Error?.Print(LogClass.TamperMachine, "There was a problem while compiling the Atmosphere cheat");

            return null;
        }

        private ITamperProgram CompileImpl(string name, IEnumerable<string> rawInstructions)
        {
            CompilationContext context = new CompilationContext(_exeAddress, _heapAddress, _aliasAddress, _aslrAddress, _process);
            context.BlockStack.Push(new OperationBlock(null));

            // Parse the instructions.

            foreach (string rawInstruction in rawInstructions)
            {
                Logger.Debug?.Print(LogClass.TamperMachine, $"Compiling instruction {rawInstruction}");

                byte[] instruction = InstructionHelper.ParseRawInstruction(rawInstruction);
                CodeType codeType = InstructionHelper.GetCodeType(instruction);

                switch (codeType)
                {
                    case CodeType.StoreConstantToAddress:
                        StoreConstantToAddress.Emit(instruction, context);
                        break;
                    case CodeType.BeginMemoryConditionalBlock:
                        BeginConditionalBlock.Emit(instruction, context);
                        break;
                    case CodeType.EndConditionalBlock:
                        EndConditionalBlock.Emit(instruction, context);
                        break;
                    case CodeType.StartEndLoop:
                        StartEndLoop.Emit(instruction, context);
                        break;
                    case CodeType.LoadRegisterWithContant:
                        LoadRegisterWithConstant.Emit(instruction, context);
                        break;
                    case CodeType.LoadRegisterWithMemory:
                        LoadRegisterWithMemory.Emit(instruction, context);
                        break;
                    case CodeType.StoreConstantToMemory:
                        StoreConstantToMemory.Emit(instruction, context);
                        break;
                    case CodeType.LegacyArithmetic:
                        LegacyArithmetic.Emit(instruction, context);
                        break;
                    case CodeType.BeginKeypressConditionalBlock:
                        BeginConditionalBlock.Emit(instruction, context);
                        break;
                    case CodeType.Arithmetic:
                        Arithmetic.Emit(instruction, context);
                        break;
                    case CodeType.StoreRegisterToMemory:
                        StoreRegisterToMemory.Emit(instruction, context);
                        break;
                    case CodeType.BeginRegisterConditionalBlock:
                        BeginConditionalBlock.Emit(instruction, context);
                        break;
                    case CodeType.SaveOrRestoreRegister:
                        SaveOrRestoreRegister.Emit(instruction, context);
                        break;
                    case CodeType.SaveOrRestoreRegisterWithMask:
                        SaveOrRestoreRegisterWithMask.Emit(instruction, context);
                        break;
                    case CodeType.ReadOrWriteStaticRegister:
                        ReadOrWriteStaticRegister.Emit(instruction, context);
                        break;
                    case CodeType.PauseProcess:
                        PauseProcess.Emit(instruction, context);
                        break;
                    case CodeType.ResumeProcess:
                        ResumeProcess.Emit(instruction, context);
                        break;
                    case CodeType.DebugLog:
                        DebugLog.Emit(instruction, context);
                        break;
                    default:
                        throw new TamperCompilationException($"Code type {codeType} not implemented in Atmosphere cheat");
                }
            }

            // Initialize only the registers used.

            Value<ulong> zero = new Value<ulong>(0UL);
            int position = 0;

            foreach (Register register in context.Registers.Values)
            {
                context.CurrentOperations.Insert(position, new OpMov<ulong>(register, zero));
                position++;
            }

            if (context.BlockStack.Count != 1)
            {
                throw new TamperCompilationException($"Reached end of compilation with unmatched conditional(s) or loop(s)");
            }

            return new AtmosphereProgram(name, _process, context.PressedKeys, new Block(context.CurrentOperations));
        }
    }
}


<|start_filename|>Ryujinx.Common/Configuration/Hid/Controller/RumbleConfigController.cs<|end_filename|>
﻿namespace Ryujinx.Common.Configuration.Hid.Controller
{
    public class RumbleConfigController
    {
        /// <summary>
        /// Controller Strong Rumble Multiplier
        /// </summary>
        public float StrongRumble { get; set; }

        /// <summary>
        /// Controller Weak Rumble Multiplier
        /// </summary>
        public float WeakRumble { get; set; }

        /// <summary>
        /// Enable Rumble
        /// </summary>
        public bool EnableRumble { get; set; }
    }
}


<|start_filename|>Ryujinx.Graphics.Shader/StructuredIr/StructuredProgramInfo.cs<|end_filename|>
using System.Collections.Generic;

namespace Ryujinx.Graphics.Shader.StructuredIr
{
    class StructuredProgramInfo
    {
        public List<StructuredFunction> Functions { get; }

        public HelperFunctionsMask HelperFunctionsMask { get; set; }

        public StructuredProgramInfo()
        {
            Functions = new List<StructuredFunction>();
        }
    }
}

<|start_filename|>Ryujinx.HLE/HOS/Services/Hid/HidServer/Types/Vibration/HidVibrationDeviceHandle.cs<|end_filename|>
﻿namespace Ryujinx.HLE.HOS.Services.Hid
{
    public struct HidVibrationDeviceHandle
    {
        public byte DeviceType;
        public byte PlayerId;
        public byte Position;
        public byte Reserved;
    }
}

<|start_filename|>Ryujinx.HLE/HOS/Services/Fs/FileSystemProxy/IFile.cs<|end_filename|>
using LibHac;
using LibHac.Fs;
using LibHac.Sf;
using Ryujinx.Common;

namespace Ryujinx.HLE.HOS.Services.Fs.FileSystemProxy
{
    class IFile : DisposableIpcService
    {
        private ReferenceCountedDisposable<LibHac.FsSrv.Sf.IFile> _baseFile;

        public IFile(ReferenceCountedDisposable<LibHac.FsSrv.Sf.IFile> baseFile)
        {
            _baseFile = baseFile;
        }

        [CommandHipc(0)]
        // Read(u32 readOption, u64 offset, u64 size) -> (u64 out_size, buffer<u8, 0x46, 0> out_buf)
        public ResultCode Read(ServiceCtx context)
        {
            ulong position = context.Request.ReceiveBuff[0].Position;

            ReadOption readOption = context.RequestData.ReadStruct<ReadOption>();
            context.RequestData.BaseStream.Position += 4;

            long offset = context.RequestData.ReadInt64();
            long size   = context.RequestData.ReadInt64();

            byte[] data = new byte[context.Request.ReceiveBuff[0].Size];

            Result result = _baseFile.Target.Read(out long bytesRead, offset, new OutBuffer(data), size, readOption);

            context.Memory.Write(position, data);

            context.ResponseData.Write(bytesRead);

            return (ResultCode)result.Value;
        }

        [CommandHipc(1)]
        // Write(u32 writeOption, u64 offset, u64 size, buffer<u8, 0x45, 0>)
        public ResultCode Write(ServiceCtx context)
        {
            ulong position = context.Request.SendBuff[0].Position;

            WriteOption writeOption = context.RequestData.ReadStruct<WriteOption>();
            context.RequestData.BaseStream.Position += 4;

            long offset = context.RequestData.ReadInt64();
            long size   = context.RequestData.ReadInt64();

            byte[] data = new byte[context.Request.SendBuff[0].Size];

            context.Memory.Read(position, data);

            return (ResultCode)_baseFile.Target.Write(offset, new InBuffer(data), size, writeOption).Value;
        }

        [CommandHipc(2)]
        // Flush()
        public ResultCode Flush(ServiceCtx context)
        {
            return (ResultCode)_baseFile.Target.Flush().Value;
        }

        [CommandHipc(3)]
        // SetSize(u64 size)
        public ResultCode SetSize(ServiceCtx context)
        {
            long size = context.RequestData.ReadInt64();

            return (ResultCode)_baseFile.Target.SetSize(size).Value;
        }

        [CommandHipc(4)]
        // GetSize() -> u64 fileSize
        public ResultCode GetSize(ServiceCtx context)
        {
            Result result = _baseFile.Target.GetSize(out long size);

            context.ResponseData.Write(size);

            return (ResultCode)result.Value;
        }

        protected override void Dispose(bool isDisposing)
        {
            if (isDisposing)
            {
                _baseFile?.Dispose();
            }
        }
    }
}

<|start_filename|>Ryujinx.HLE/HOS/Services/Hid/HidServer/Types/Vibration/HidVibrationValue.cs<|end_filename|>
﻿using Ryujinx.HLE.HOS.Tamper;
using System;

namespace Ryujinx.HLE.HOS.Services.Hid
{
    public struct HidVibrationValue
    {
        public float AmplitudeLow;
        public float FrequencyLow;
        public float AmplitudeHigh;
        public float FrequencyHigh;

        public override bool Equals(object obj)
        {
            return obj is HidVibrationValue value &&
                   AmplitudeLow == value.AmplitudeLow &&
                   AmplitudeHigh == value.AmplitudeHigh;
        }

        public override int GetHashCode()
        {
            return HashCode.Combine(AmplitudeLow, AmplitudeHigh);
        }
    }
}

<|start_filename|>Ryujinx.HLE/HOS/Services/Arp/LibHacIReader.cs<|end_filename|>
﻿using LibHac;
using LibHac.Ncm;
using LibHac.Ns;
using System;

using ApplicationId = LibHac.ApplicationId;

namespace Ryujinx.HLE.HOS.Services.Arp
{
    class LibHacIReader : LibHac.Arp.Impl.IReader
    {
        public ApplicationId ApplicationId { get; set; }

        public Result GetApplicationLaunchProperty(out LibHac.Arp.ApplicationLaunchProperty launchProperty, ulong processId)
        {
            launchProperty = new LibHac.Arp.ApplicationLaunchProperty
            {
                BaseStorageId = StorageId.BuiltInUser,
                ApplicationId = ApplicationId
            };

            return Result.Success;
        }

        public Result GetApplicationLaunchPropertyWithApplicationId(out LibHac.Arp.ApplicationLaunchProperty launchProperty, ApplicationId applicationId)
        {
            launchProperty = new LibHac.Arp.ApplicationLaunchProperty
            {
                BaseStorageId = StorageId.BuiltInUser,
                ApplicationId = applicationId
            };

            return Result.Success;
        }

        public Result GetApplicationControlProperty(out ApplicationControlProperty controlProperty, ulong processId)
        {
            throw new NotImplementedException();
        }

        public Result GetApplicationControlPropertyWithApplicationId(out ApplicationControlProperty controlProperty, ApplicationId applicationId)
        {
            throw new NotImplementedException();
        }

        public Result GetServiceObject(out object serviceObject)
        {
            throw new NotImplementedException();
        }
    }

    internal class LibHacArpServiceObject : LibHac.Sm.IServiceObject
    {
        private LibHacIReader _serviceObject;

        public LibHacArpServiceObject(LibHacIReader serviceObject)
        {
            _serviceObject = serviceObject;
        }

        public Result GetServiceObject(out object serviceObject)
        {
            serviceObject = _serviceObject;

            return Result.Success;
        }
    }
}

<|start_filename|>Ryujinx.HLE/HOS/Kernel/Process/ProcessTamperInfo.cs<|end_filename|>
using System.Collections.Generic;

namespace Ryujinx.HLE.HOS.Kernel.Process
{
    internal class ProcessTamperInfo
    {
        public KProcess Process { get; }
        public IEnumerable<string> BuildIds { get; }
        public IEnumerable<ulong> CodeAddresses { get; }
        public ulong HeapAddress { get; }
        public ulong AliasAddress { get; }
        public ulong AslrAddress { get; }

        public ProcessTamperInfo(KProcess process, IEnumerable<string> buildIds, IEnumerable<ulong> codeAddresses, ulong heapAddress, ulong aliasAddress, ulong aslrAddress)
        {
            Process       = process;
            BuildIds      = buildIds;
            CodeAddresses = codeAddresses;
            HeapAddress   = heapAddress;
            AliasAddress  = aliasAddress;
            AslrAddress   = aslrAddress;
        }
    }
}

<|start_filename|>Ryujinx.Graphics.Gpu/Shader/Cache/CacheCollection.cs<|end_filename|>
﻿using Ryujinx.Common;
using Ryujinx.Common.Logging;
using Ryujinx.Graphics.Gpu.Shader.Cache.Definition;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;

namespace Ryujinx.Graphics.Gpu.Shader.Cache
{
    /// <summary>
    /// Represent a cache collection handling one shader cache.
    /// </summary>
    class CacheCollection : IDisposable
    {
        /// <summary>
        /// Possible operation to do on the <see cref="_fileWriterWorkerQueue"/>.
        /// </summary>
        private enum CacheFileOperation
        {
            /// <summary>
            /// Save a new entry in the temp cache.
            /// </summary>
            SaveTempEntry,

            /// <summary>
            /// Save the hash manifest.
            /// </summary>
            SaveManifest,

            /// <summary>
            /// Remove entries from the hash manifest and save it.
            /// </summary>
            RemoveManifestEntries,

            /// <summary>
            /// Remove entries from the hash manifest and save it, and also deletes the temporary file.
            /// </summary>
            RemoveManifestEntryAndTempFile,

            /// <summary>
            /// Flush temporary cache to archive.
            /// </summary>
            FlushToArchive,

            /// <summary>
            /// Signal when hitting this point. This is useful to know if all previous operations were performed.
            /// </summary>
            Synchronize
        }

        /// <summary>
        /// Represent an operation to perform on the <see cref="_fileWriterWorkerQueue"/>.
        /// </summary>
        private class CacheFileOperationTask
        {
            /// <summary>
            /// The type of operation to perform.
            /// </summary>
            public CacheFileOperation Type;

            /// <summary>
            /// The data associated to this operation or null.
            /// </summary>
            public object Data;
        }

        /// <summary>
        /// Data associated to the <see cref="CacheFileOperation.SaveTempEntry"/> operation.
        /// </summary>
        private class CacheFileSaveEntryTaskData
        {
            /// <summary>
            /// The key of the entry to cache.
            /// </summary>
            public Hash128 Key;

            /// <summary>
            /// The value of the entry to cache.
            /// </summary>
            public byte[] Value;
        }

        /// <summary>
        /// The directory of the shader cache.
        /// </summary>
        private readonly string _cacheDirectory;

        /// <summary>
        /// The version of the cache.
        /// </summary>
        private readonly ulong _version;

        /// <summary>
        /// The hash type of the cache.
        /// </summary>
        private readonly CacheHashType _hashType;

        /// <summary>
        /// The graphics API of the cache.
        /// </summary>
        private readonly CacheGraphicsApi _graphicsApi;

        /// <summary>
        /// The table of all the hash registered in the cache.
        /// </summary>
        private HashSet<Hash128> _hashTable;

        /// <summary>
        /// The queue of operations to be performed by the file writer worker.
        /// </summary>
        private AsyncWorkQueue<CacheFileOperationTask> _fileWriterWorkerQueue;

        /// <summary>
        /// Main storage of the cache collection.
        /// </summary>
        private ZipArchive _cacheArchive;

        /// <summary>
        /// Indicates if the cache collection supports modification.
        /// </summary>
        public bool IsReadOnly { get; }

        /// <summary>
        /// Immutable copy of the hash table.
        /// </summary>
        public ReadOnlySpan<Hash128> HashTable => _hashTable.ToArray();

        /// <summary>
        /// Get the temp path to the cache data directory.
        /// </summary>
        /// <returns>The temp path to the cache data directory</returns>
        private string GetCacheTempDataPath() => CacheHelper.GetCacheTempDataPath(_cacheDirectory);

        /// <summary>
        /// The path to the cache archive file.
        /// </summary>
        /// <returns>The path to the cache archive file</returns>
        private string GetArchivePath() => CacheHelper.GetArchivePath(_cacheDirectory);

        /// <summary>
        /// The path to the cache manifest file.
        /// </summary>
        /// <returns>The path to the cache manifest file</returns>
        private string GetManifestPath() => CacheHelper.GetManifestPath(_cacheDirectory);

        /// <summary>
        /// Create a new temp path to the given cached file via its hash.
        /// </summary>
        /// <param name="key">The hash of the cached data</param>
        /// <returns>New path to the given cached file</returns>
        private string GenCacheTempFilePath(Hash128 key) => CacheHelper.GenCacheTempFilePath(_cacheDirectory, key);

        /// <summary>
        /// Create a new cache collection.
        /// </summary>
        /// <param name="baseCacheDirectory">The directory of the shader cache</param>
        /// <param name="hashType">The hash type of the shader cache</param>
        /// <param name="graphicsApi">The graphics api of the shader cache</param>
        /// <param name="shaderProvider">The shader provider name of the shader cache</param>
        /// <param name="cacheName">The name of the cache</param>
        /// <param name="version">The version of the cache</param>
        public CacheCollection(string baseCacheDirectory, CacheHashType hashType, CacheGraphicsApi graphicsApi, string shaderProvider, string cacheName, ulong version)
        {
            if (hashType != CacheHashType.XxHash128)
            {
                throw new NotImplementedException($"{hashType}");
            }

            _cacheDirectory = CacheHelper.GenerateCachePath(baseCacheDirectory, graphicsApi, shaderProvider, cacheName);
            _graphicsApi = graphicsApi;
            _hashType = hashType;
            _version = version;
            _hashTable = new HashSet<Hash128>();
            IsReadOnly = CacheHelper.IsArchiveReadOnly(GetArchivePath());

            Load();

            _fileWriterWorkerQueue = new AsyncWorkQueue<CacheFileOperationTask>(HandleCacheTask, $"CacheCollection.Worker.{cacheName}");
        }

        /// <summary>
        /// Load the cache manifest file and recreate it if invalid.
        /// </summary>
        private void Load()
        {
            bool isValid = false;

            if (Directory.Exists(_cacheDirectory))
            {
                string manifestPath = GetManifestPath();

                if (File.Exists(manifestPath))
                {
                    Memory<byte> rawManifest = File.ReadAllBytes(manifestPath);

                    if (MemoryMarshal.TryRead(rawManifest.Span, out CacheManifestHeader manifestHeader))
                    {
                        Memory<byte> hashTableRaw = rawManifest.Slice(Unsafe.SizeOf<CacheManifestHeader>());

                        isValid = manifestHeader.IsValid(_graphicsApi, _hashType, hashTableRaw.Span) && _version == manifestHeader.Version;

                        if (isValid)
                        {
                            ReadOnlySpan<Hash128> hashTable = MemoryMarshal.Cast<byte, Hash128>(hashTableRaw.Span);

                            foreach (Hash128 hash in hashTable)
                            {
                                _hashTable.Add(hash);
                            }
                        }
                    }
                }
            }

            if (!isValid)
            {
                Logger.Warning?.Print(LogClass.Gpu, $"Shader collection \"{_cacheDirectory}\" got invalidated, cache will need to be rebuilt.");

                if (Directory.Exists(_cacheDirectory))
                {
                    Directory.Delete(_cacheDirectory, true);
                }

                Directory.CreateDirectory(_cacheDirectory);

                SaveManifest();
            }

            FlushToArchive();
        }

        /// <summary>
        /// Queue a task to remove entries from the hash manifest.
        /// </summary>
        /// <param name="entries">Entries to remove from the manifest</param>
        public void RemoveManifestEntriesAsync(HashSet<Hash128> entries)
        {
            if (IsReadOnly)
            {
                Logger.Warning?.Print(LogClass.Gpu, "Trying to remove manifest entries on a read-only cache, ignoring.");

                return;
            }

            _fileWriterWorkerQueue.Add(new CacheFileOperationTask
            {
                Type = CacheFileOperation.RemoveManifestEntries,
                Data = entries
            });
        }

        /// <summary>
        /// Remove given entries from the manifest.
        /// </summary>
        /// <param name="entries">Entries to remove from the manifest</param>
        private void RemoveManifestEntries(HashSet<Hash128> entries)
        {
            lock (_hashTable)
            {
                foreach (Hash128 entry in entries)
                {
                    _hashTable.Remove(entry);
                }

                SaveManifest();
            }
        }

        /// <summary>
        /// Remove given entry from the manifest and delete the temporary file.
        /// </summary>
        /// <param name="entry">Entry to remove from the manifest</param>
        private void RemoveManifestEntryAndTempFile(Hash128 entry)
        {
            lock (_hashTable)
            {
                _hashTable.Remove(entry);
                SaveManifest();
            }

            File.Delete(GenCacheTempFilePath(entry));
        }

        /// <summary>
        /// Queue a task to flush temporary files to the archive on the worker.
        /// </summary>
        public void FlushToArchiveAsync()
        {
            _fileWriterWorkerQueue.Add(new CacheFileOperationTask
            {
                Type = CacheFileOperation.FlushToArchive
            });
        }

        /// <summary>
        /// Wait for all tasks before this given point to be done.
        /// </summary>
        public void Synchronize()
        {
            using (ManualResetEvent evnt = new ManualResetEvent(false))
            {
                _fileWriterWorkerQueue.Add(new CacheFileOperationTask
                {
                    Type = CacheFileOperation.Synchronize,
                    Data = evnt
                });

                evnt.WaitOne();
            }
        }

        /// <summary>
        /// Flush temporary files to the archive.
        /// </summary>
        /// <remarks>This dispose <see cref="_cacheArchive"/> if not null and reinstantiate it.</remarks>
        private void FlushToArchive()
        {
            EnsureArchiveUpToDate();

            // Open the zip in readonly to avoid anyone modifying/corrupting it during normal operations.
            _cacheArchive = ZipFile.Open(GetArchivePath(), ZipArchiveMode.Read);
        }

        /// <summary>
        /// Save temporary files not in archive.
        /// </summary>
        /// <remarks>This dispose <see cref="_cacheArchive"/> if not null.</remarks>
        public void EnsureArchiveUpToDate()
        {
            // First close previous opened instance if found.
            if (_cacheArchive != null)
            {
                _cacheArchive.Dispose();
            }

            string archivePath = GetArchivePath();

            if (IsReadOnly)
            {
                Logger.Warning?.Print(LogClass.Gpu, $"Cache collection archive in read-only, archiving task skipped.");

                return;
            }

            if (CacheHelper.IsArchiveReadOnly(archivePath))
            {
                Logger.Warning?.Print(LogClass.Gpu, $"Cache collection archive in use, archiving task skipped.");

                return;
            }

            // Open the zip in read/write.
            _cacheArchive = ZipFile.Open(archivePath, ZipArchiveMode.Update);

            Logger.Info?.Print(LogClass.Gpu, $"Updating cache collection archive {archivePath}...");

            // Update the content of the zip.
            lock (_hashTable)
            {
                CacheHelper.EnsureArchiveUpToDate(_cacheDirectory, _cacheArchive, _hashTable);

                // Close the instance to force a flush.
                _cacheArchive.Dispose();
                _cacheArchive = null;

                string cacheTempDataPath = GetCacheTempDataPath();

                // Create the cache data path if missing.
                if (!Directory.Exists(cacheTempDataPath))
                {
                    Directory.CreateDirectory(cacheTempDataPath);
                }
            }

            Logger.Info?.Print(LogClass.Gpu, $"Updated cache collection archive {archivePath}.");
        }

        /// <summary>
        /// Save the manifest file.
        /// </summary>
        private void SaveManifest()
        {
            byte[] data;

            lock (_hashTable)
            {
                data = CacheHelper.ComputeManifest(_version, _graphicsApi, _hashType, _hashTable);
            }

            File.WriteAllBytes(GetManifestPath(), data);
        }

        /// <summary>
        /// Get a cached file with the given hash.
        /// </summary>
        /// <param name="keyHash">The given hash</param>
        /// <returns>The cached file if present or null</returns>
        public byte[] GetValueRaw(ref Hash128 keyHash)
        {
            return GetValueRawFromArchive(ref keyHash) ?? GetValueRawFromFile(ref keyHash);
        }

        /// <summary>
        /// Get a cached file with the given hash that is present in the archive.
        /// </summary>
        /// <param name="keyHash">The given hash</param>
        /// <returns>The cached file if present or null</returns>
        private byte[] GetValueRawFromArchive(ref Hash128 keyHash)
        {
            bool found;

            lock (_hashTable)
            {
                found = _hashTable.Contains(keyHash);
            }

            if (found)
            {
                return CacheHelper.ReadFromArchive(_cacheArchive, keyHash);
            }

            return null;
        }

        /// <summary>
        /// Get a cached file with the given hash that is not present in the archive.
        /// </summary>
        /// <param name="keyHash">The given hash</param>
        /// <returns>The cached file if present or null</returns>
        private byte[] GetValueRawFromFile(ref Hash128 keyHash)
        {
            bool found;

            lock (_hashTable)
            {
                found = _hashTable.Contains(keyHash);
            }

            if (found)
            {
                return CacheHelper.ReadFromFile(GetCacheTempDataPath(), keyHash);
            }

            return null;
        }

        private void HandleCacheTask(CacheFileOperationTask task)
        {
            switch (task.Type)
            {
                case CacheFileOperation.SaveTempEntry:
                    SaveTempEntry((CacheFileSaveEntryTaskData)task.Data);
                    break;
                case CacheFileOperation.SaveManifest:
                    SaveManifest();
                    break;
                case CacheFileOperation.RemoveManifestEntries:
                    RemoveManifestEntries((HashSet<Hash128>)task.Data);
                    break;
                case CacheFileOperation.RemoveManifestEntryAndTempFile:
                    RemoveManifestEntryAndTempFile((Hash128)task.Data);
                    break;
                case CacheFileOperation.FlushToArchive:
                    FlushToArchive();
                    break;
                case CacheFileOperation.Synchronize:
                    ((ManualResetEvent)task.Data).Set();
                    break;
                default:
                    throw new NotImplementedException($"{task.Type}");
            }

        }

        /// <summary>
        /// Save a new entry in the temp cache.
        /// </summary>
        /// <param name="entry">The entry to save in the temp cache</param>
        private void SaveTempEntry(CacheFileSaveEntryTaskData entry)
        {
            string tempPath = GenCacheTempFilePath(entry.Key);

            File.WriteAllBytes(tempPath, entry.Value);
        }

        /// <summary>
        /// Add a new value in the cache with a given hash.
        /// </summary>
        /// <param name="keyHash">The hash to use for the value in the cache</param>
        /// <param name="value">The value to cache</param>
        public void AddValue(ref Hash128 keyHash, byte[] value)
        {
            if (IsReadOnly)
            {
                Logger.Warning?.Print(LogClass.Gpu, $"Trying to add {keyHash} on a read-only cache, ignoring.");

                return;
            }

            Debug.Assert(value != null);

            bool isAlreadyPresent;

            lock (_hashTable)
            {
                isAlreadyPresent = !_hashTable.Add(keyHash);
            }

            if (isAlreadyPresent)
            {
                // NOTE: Used for debug
                File.WriteAllBytes(GenCacheTempFilePath(new Hash128()), value);

                throw new InvalidOperationException($"Cache collision found on {GenCacheTempFilePath(keyHash)}");
            }

            // Queue file change operations
            _fileWriterWorkerQueue.Add(new CacheFileOperationTask
            {
                Type = CacheFileOperation.SaveTempEntry,
                Data = new CacheFileSaveEntryTaskData
                {
                    Key = keyHash,
                    Value = value
                }
            });

            // Save the manifest changes
            _fileWriterWorkerQueue.Add(new CacheFileOperationTask
            {
                Type = CacheFileOperation.SaveManifest,
            });
        }

        /// <summary>
        /// Replace a value at the given hash in the cache.
        /// </summary>
        /// <param name="keyHash">The hash to use for the value in the cache</param>
        /// <param name="value">The value to cache</param>
        public void ReplaceValue(ref Hash128 keyHash, byte[] value)
        {
            if (IsReadOnly)
            {
                Logger.Warning?.Print(LogClass.Gpu, $"Trying to replace {keyHash} on a read-only cache, ignoring.");

                return;
            }

            Debug.Assert(value != null);

            // Only queue file change operations
            _fileWriterWorkerQueue.Add(new CacheFileOperationTask
            {
                Type = CacheFileOperation.SaveTempEntry,
                Data = new CacheFileSaveEntryTaskData
                {
                    Key = keyHash,
                    Value = value
                }
            });
        }

        /// <summary>
        /// Removes a value at the given hash from the cache.
        /// </summary>
        /// <param name="keyHash">The hash of the value in the cache</param>
        public void RemoveValue(ref Hash128 keyHash)
        {
            if (IsReadOnly)
            {
                Logger.Warning?.Print(LogClass.Gpu, $"Trying to remove {keyHash} on a read-only cache, ignoring.");

                return;
            }

            // Only queue file change operations
            _fileWriterWorkerQueue.Add(new CacheFileOperationTask
            {
                Type = CacheFileOperation.RemoveManifestEntryAndTempFile,
                Data = keyHash
            });
        }

        public void Dispose()
        {
            Dispose(true);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                // Make sure all operations on _fileWriterWorkerQueue are done.
                Synchronize();

                _fileWriterWorkerQueue.Dispose();
                EnsureArchiveUpToDate();
            }
        }
    }
}


<|start_filename|>Ryujinx.HLE/HOS/Tamper/MemoryRegion.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ryujinx.HLE.HOS.Tamper
{
    /// <summary>
    /// The regions in the virtual address space of the process that are used as base address of memory operations.
    /// </summary>
    enum MemoryRegion
    {
        /// <summary>
        /// The position of the NSO associated with the cheat in the virtual address space.
        /// NOTE: A game can have several NSOs, but the cheat only associates itself with one.
        /// </summary>
        NSO = 0x0,

        /// <summary>
        /// The address of the heap, as determined by the kernel.
        /// </summary>
        Heap = 0x1,

        /// <summary>
        /// The address of the alias region, as determined by the kernel.
        /// </summary>
        Alias = 0x2,

        /// <summary>
        /// The address of the code region with address space layout randomization included.
        /// </summary>
        Asrl = 0x3,
    }
}


<|start_filename|>Ryujinx.HLE/HOS/Tamper/CompilationContext.cs<|end_filename|>
﻿using Ryujinx.HLE.HOS.Tamper.Operations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ryujinx.HLE.HOS.Tamper
{
    class CompilationContext
    {
        public OperationBlock CurrentBlock => BlockStack.Peek();
        public List<IOperation> CurrentOperations => CurrentBlock.Operations;

        public ITamperedProcess Process { get; }
        public Parameter<long> PressedKeys { get; }
        public Stack<OperationBlock> BlockStack { get; }
        public Dictionary<byte, Register> Registers { get; }
        public Dictionary<byte, Register> SavedRegisters { get; }
        public Dictionary<byte, Register> StaticRegisters { get; }
        public ulong ExeAddress { get; }
        public ulong HeapAddress { get; }
        public ulong AliasAddress { get; }
        public ulong AslrAddress { get; }

        public CompilationContext(ulong exeAddress, ulong heapAddress, ulong aliasAddress, ulong aslrAddress, ITamperedProcess process)
        {
            Process         = process;
            PressedKeys     = new Parameter<long>(0);
            BlockStack      = new Stack<OperationBlock>();
            Registers       = new Dictionary<byte, Register>();
            SavedRegisters  = new Dictionary<byte, Register>();
            StaticRegisters = new Dictionary<byte, Register>();
            ExeAddress      = exeAddress;
            HeapAddress     = heapAddress;
            AliasAddress    = aliasAddress;
            AslrAddress     = aslrAddress;
        }

        public Register GetRegister(byte index)
        {
            if (Registers.TryGetValue(index, out Register register))
            {
                return register;
            }

            register = new Register($"R_{index:X2}");
            Registers.Add(index, register);

            return register;
        }

        public Register GetSavedRegister(byte index)
        {
            if (SavedRegisters.TryGetValue(index, out Register register))
            {
                return register;
            }

            register = new Register($"S_{index:X2}");
            SavedRegisters.Add(index, register);

            return register;
        }

        public Register GetStaticRegister(byte index)
        {
            if (SavedRegisters.TryGetValue(index, out Register register))
            {
                return register;
            }

            register = new Register($"T_{index:X2}");
            SavedRegisters.Add(index, register);

            return register;
        }
    }
}
