Example #1
0
        private void SendSyncRequest(AThreadState ThreadState, long CmdPtr, long Size, int Handle)
        {
            KThread CurrThread = Process.GetThread(ThreadState.Tpidr);

            byte[] CmdData = AMemoryHelper.ReadBytes(Memory, CmdPtr, Size);

            KSession Session = Process.HandleTable.GetData <KSession>(Handle);

            if (Session != null)
            {
                Process.Scheduler.Suspend(CurrThread.ProcessorId);

                IpcMessage Cmd = new IpcMessage(CmdData, CmdPtr);

                IpcHandler.IpcCall(Ns, Process, Memory, Session, Cmd, CmdPtr);

                Thread.Yield();

                Process.Scheduler.Resume(CurrThread);

                ThreadState.X0 = 0;
            }
            else
            {
                Logging.Warn($"Tried to SendSyncRequest on invalid session handle 0x{Handle:x8}!");

                ThreadState.X0 = MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle);
            }
        }
        private void UploadUniforms(AMemory Memory)
        {
            long BasePosition = MakeInt64From2xInt32(NvGpuEngine3dReg.ShaderAddress);

            for (int Index = 0; Index < 5; Index++)
            {
                int Control = ReadRegister(NvGpuEngine3dReg.ShaderNControl + (Index + 1) * 0x10);
                int Offset  = ReadRegister(NvGpuEngine3dReg.ShaderNOffset + (Index + 1) * 0x10);

                //Note: Vertex Program (B) is always enabled.
                bool Enable = (Control & 1) != 0 || Index == 0;

                if (!Enable)
                {
                    continue;
                }

                for (int Cbuf = 0; Cbuf < ConstBuffers.Length; Cbuf++)
                {
                    ConstBuffer Cb = ConstBuffers[Cbuf];

                    if (Cb.Enabled)
                    {
                        long CbPosition = Cb.Position + Index * Cb.Size;

                        byte[] Data = AMemoryHelper.ReadBytes(Memory, CbPosition, (uint)Cb.Size);

                        Gpu.Renderer.SetConstBuffer(BasePosition + (uint)Offset, Cbuf, Data);
                    }
                }
            }
        }
Example #3
0
        public long AppendAudioOutBuffer(ServiceCtx Context)
        {
            long BufferId = Context.RequestData.ReadInt64();

            KeysQueue.Enqueue(BufferId);

            byte[] AudioOutBuffer = AMemoryHelper.ReadBytes(Context.Memory, Context.Request.SendBuff[0].Position, 0x28);
            using (MemoryStream MS = new MemoryStream(AudioOutBuffer))
            {
                BinaryReader Reader = new BinaryReader(MS);
                long         PointerToSampleDataPointer = Reader.ReadInt64();
                long         PointerToSampleData        = Reader.ReadInt64();
                long         CapacitySampleBuffer       = Reader.ReadInt64();
                long         SizeDataSampleBuffer       = Reader.ReadInt64();
                long         Unknown = Reader.ReadInt64();

                byte[] AudioSampleBuffer = AMemoryHelper.ReadBytes(Context.Memory, PointerToSampleData, (int)SizeDataSampleBuffer);

                if (OpenALInstalled)
                {
                    if (AudioCtx == null) //Needed to call the instance of AudioContext()
                    {
                        return(0);
                    }

                    Buffer = AL.GenBuffer();
                    AL.BufferData(Buffer, ALFormat.Stereo16, AudioSampleBuffer, AudioSampleBuffer.Length, 48000);

                    Source = AL.GenSource();
                    AL.SourceQueueBuffer(Source, Buffer);
                }
            }

            return(0);
        }
Example #4
0
        //(u32 socket, buffer<sockaddr, 0x21, 0>) -> (i32 ret, u32 bsd_errno)
        public long Connect(ServiceCtx Context)
        {
            int SocketId = Context.RequestData.ReadInt32();

            byte[] AddressBuffer = AMemoryHelper.ReadBytes(Context.Memory,
                                                           Context.Request.SendBuff[0].Position,
                                                           Context.Request.SendBuff[0].Size);

            try
            {
                ParseAddrBuffer(SocketId, AddressBuffer);

                Sockets[SocketId].Handle.Connect(Sockets[SocketId].RemoteEP);

                Context.ResponseData.Write(0);
                Context.ResponseData.Write(0);
            }
            catch (SocketException Ex)
            {
                Context.ResponseData.Write(-1);
                Context.ResponseData.Write(Ex.ErrorCode - 10000);
            }

            return(0);
        }
Example #5
0
        //(u32 socket, u32 level, u32 option_name, buffer<unknown, 0x21, 0>) -> (i32 ret, u32 bsd_errno)
        public long SetSockOpt(ServiceCtx Context)
        {
            int SocketId = Context.RequestData.ReadInt32();

            SocketOptionLevel SocketLevel      = (SocketOptionLevel)Context.RequestData.ReadInt32();
            SocketOptionName  SocketOptionName = (SocketOptionName)Context.RequestData.ReadInt32();

            byte[] SocketOptionValue = AMemoryHelper.ReadBytes(Context.Memory,
                                                               Context.Request.PtrBuff[0].Position,
                                                               Context.Request.PtrBuff[0].Size);

            int OptionValue = Get32(SocketOptionValue, 0);

            try
            {
                Sockets[SocketId].Handle.SetSocketOption(SocketLevel, SocketOptionName, OptionValue);

                Context.ResponseData.Write(0);
                Context.ResponseData.Write(0);
            }
            catch (SocketException Ex)
            {
                Context.ResponseData.Write(-1);
                Context.ResponseData.Write(Ex.ErrorCode - 10000);
            }

            return(0);
        }
Example #6
0
        //(u32 socket, u32 flags, buffer<i8, 0x21, 0>) -> (i32 ret, u32 bsd_errno)
        public long Send(ServiceCtx Context)
        {
            int SocketId    = Context.RequestData.ReadInt32();
            int SocketFlags = Context.RequestData.ReadInt32();

            byte[] SentBuffer = AMemoryHelper.ReadBytes(Context.Memory,
                                                        Context.Request.SendBuff[0].Position,
                                                        Context.Request.SendBuff[0].Size);

            try
            {
                //Logging.Debug("Sent Buffer:" + Environment.NewLine + Logging.HexDump(SentBuffer));

                int BytesSent = Sockets[SocketId].Handle.Send(SentBuffer);

                Context.ResponseData.Write(BytesSent);
                Context.ResponseData.Write(0);
            }
            catch (SocketException Ex)
            {
                Context.ResponseData.Write(-1);
                Context.ResponseData.Write(Ex.ErrorCode - 10000);
            }

            return(0);
        }
Example #7
0
        //(u32, u32, buffer<unknown, 0x21, 0>) -> (i32 ret, u32 bsd_errno, buffer<unknown, 0x22, 0>)
        public long Poll(ServiceCtx Context)
        {
            int PollCount = Context.RequestData.ReadInt32();
            int TimeOut   = Context.RequestData.ReadInt32();

            //https://github.com/torvalds/linux/blob/master/include/uapi/asm-generic/poll.h
            //https://msdn.microsoft.com/fr-fr/library/system.net.sockets.socket.poll(v=vs.110).aspx
            //https://github.com/switchbrew/libnx/blob/e0457c4534b3c37426d83e1a620f82cb28c3b528/nx/source/services/bsd.c#L343
            //https://github.com/TuxSH/ftpd/blob/switch_pr/source/ftp.c#L1634
            //https://linux.die.net/man/2/poll

            byte[] SentBuffer = AMemoryHelper.ReadBytes(Context.Memory,
                                                        Context.Request.SendBuff[0].Position,
                                                        Context.Request.SendBuff[0].Size);

            int SocketId        = Get32(SentBuffer, 0);
            int RequestedEvents = Get16(SentBuffer, 4);
            int ReturnedEvents  = Get16(SentBuffer, 6);

            //Todo: Stub - Need to implemented the Type-22 buffer.

            Context.ResponseData.Write(1);
            Context.ResponseData.Write(0);

            return(0);
        }
        public static long GetSettingsItemValue(ServiceCtx Context)
        {
            long ClassPos  = Context.Request.PtrBuff[0].Position;
            long ClassSize = Context.Request.PtrBuff[0].Size;

            long NamePos  = Context.Request.PtrBuff[1].Position;
            long NameSize = Context.Request.PtrBuff[1].Size;

            long ReplyPos  = Context.Request.ReceiveBuff[0].Position;
            long ReplySize = Context.Request.ReceiveBuff[0].Size;

            byte[] Class = AMemoryHelper.ReadBytes(Context.Memory, ClassPos, ClassSize);
            byte[] Name  = AMemoryHelper.ReadBytes(Context.Memory, NamePos, NameSize);

            string AskedSetting = Encoding.ASCII.GetString(Class).Trim('\0') + "!" + Encoding.ASCII.GetString(Name).Trim('\0');

            NxSettings.Settings.TryGetValue(AskedSetting, out object NxSetting);

            if (NxSetting != null)
            {
                byte[] SettingBuffer = new byte[ReplySize];

                if (NxSetting is string StringValue)
                {
                    if (StringValue.Length + 1 > ReplySize)
                    {
                        Context.Ns.Log.PrintError(Logging.LogClass.ServiceSet, $"{AskedSetting} String value size is too big!");
                    }
                    else
                    {
                        SettingBuffer = Encoding.ASCII.GetBytes(StringValue + "\0");
                    }
                }
                if (NxSetting is int IntValue)
                {
                    SettingBuffer = BitConverter.GetBytes(IntValue);
                }
                else if (NxSetting is bool BoolValue)
                {
                    SettingBuffer[0] = BoolValue ? (byte)1 : (byte)0;
                }
                else
                {
                    throw new NotImplementedException(NxSetting.GetType().Name);
                }

                AMemoryHelper.WriteBytes(Context.Memory, ReplyPos, SettingBuffer);

                Context.Ns.Log.PrintDebug(Logging.LogClass.ServiceSet, $"{AskedSetting} set value: {NxSetting} as {NxSetting.GetType()}");
            }
            else
            {
                Context.Ns.Log.PrintError(Logging.LogClass.ServiceSet, $"{AskedSetting} not found!");
            }

            return(0);
        }
        private void TextureCopy(AMemory Memory, NsGpuPBEntry PBEntry)
        {
            CopyOperation Operation = (CopyOperation)ReadRegister(NvGpuEngine2dReg.CopyOperation);

            bool SrcLinear = ReadRegister(NvGpuEngine2dReg.SrcLinear) != 0;
            int  SrcWidth  = ReadRegister(NvGpuEngine2dReg.SrcWidth);
            int  SrcHeight = ReadRegister(NvGpuEngine2dReg.SrcHeight);

            bool DstLinear = ReadRegister(NvGpuEngine2dReg.DstLinear) != 0;
            int  DstWidth  = ReadRegister(NvGpuEngine2dReg.DstWidth);
            int  DstHeight = ReadRegister(NvGpuEngine2dReg.DstHeight);
            int  DstPitch  = ReadRegister(NvGpuEngine2dReg.DstPitch);
            int  DstBlkDim = ReadRegister(NvGpuEngine2dReg.DstBlockDimensions);

            TextureSwizzle DstSwizzle = DstLinear
                ? TextureSwizzle.Pitch
                : TextureSwizzle.BlockLinear;

            int DstBlockHeight = 1 << ((DstBlkDim >> 4) & 0xf);

            long Tag = MakeInt64From2xInt32(NvGpuEngine2dReg.SrcAddress);

            TryGetCpuAddr(NvGpuEngine2dReg.SrcAddress, out long SrcAddress);
            TryGetCpuAddr(NvGpuEngine2dReg.DstAddress, out long DstAddress);

            bool IsFbTexture = Gpu.Engine3d.IsFrameBufferPosition(Tag);

            if (IsFbTexture && DstLinear)
            {
                DstSwizzle = TextureSwizzle.BlockLinear;
            }

            Texture DstTexture = new Texture(
                DstAddress,
                DstWidth,
                DstHeight,
                DstBlockHeight,
                DstBlockHeight,
                DstSwizzle,
                GalTextureFormat.A8B8G8R8);

            if (IsFbTexture)
            {
                Gpu.Renderer.GetFrameBufferData(Tag, (byte[] Buffer) =>
                {
                    CopyTexture(Memory, DstTexture, Buffer);
                });
            }
            else
            {
                long Size = SrcWidth * SrcHeight * 4;

                byte[] Buffer = AMemoryHelper.ReadBytes(Memory, SrcAddress, Size);

                CopyTexture(Memory, DstTexture, Buffer);
            }
        }
Example #10
0
        private void SendVertexBuffers(AMemory Memory)
        {
            long Position =
                (long)GetRegister(NsGpuRegister._3dVertexArray0StartHigh) << 32 |
                    (long)GetRegister(NsGpuRegister._3dVertexArray0StartLow) << 0;

            long Limit =
                (long)GetRegister(NsGpuRegister._3dVertexArray0LimitHigh) << 32 |
                    (long)GetRegister(NsGpuRegister._3dVertexArray0LimitLow) << 0;

            int VbIndex = CurrentVertexBuffers.Count;

            if (!CurrentVertexBuffers.TryAdd(Position, VbIndex))
            {
                VbIndex = CurrentVertexBuffers[Position];
            }

            if (Limit != 0)
            {
                long Size = (Limit - Position) + 1;

                Position = Gpu.MemoryMgr.GetCpuAddr(Position);

                if (Position != -1)
                {
                    byte[] Buffer = AMemoryHelper.ReadBytes(Memory, Position, (int)Size);

                    int Stride = GetRegister(NsGpuRegister._3dVertexArray0Fetch) & 0xfff;

                    List <GalVertexAttrib> Attribs = new List <GalVertexAttrib>();

                    for (int Attr = 0; Attr < 16; Attr++)
                    {
                        int Packed = GetRegister(NsGpuRegister._3dVertexAttrib0Format + Attr * 4);

                        GalVertexAttrib Attrib = new GalVertexAttrib(Attr,
                                                                     (Packed >> 0) & 0x1f,
                                                                     ((Packed >> 6) & 0x1) != 0,
                                                                     (Packed >> 7) & 0x3fff,
                                                                     (GalVertexAttribSize)((Packed >> 21) & 0x3f),
                                                                     (GalVertexAttribType)((Packed >> 27) & 0x7),
                                                                     ((Packed >> 31) & 0x1) != 0);

                        if (Attrib.Offset < Stride)
                        {
                            Attribs.Add(Attrib);
                        }
                    }

                    Gpu.Renderer.QueueAction(delegate()
                    {
                        Gpu.Renderer.SendVertexBuffer(VbIndex, Buffer, Stride, Attribs.ToArray());
                    });
                }
            }
        }
Example #11
0
        private void SendShader(
            AMemory Memory,
            uint ShaderPrg,
            uint ShaderId,
            uint CodeAddr,
            uint ShaderType,
            uint CodeEnd)
        {
            long CodePos = Gpu.MemoryMgr.GetCpuAddr(CodeAddr);

            byte[] Data = AMemoryHelper.ReadBytes(Memory, CodePos, 0x300);
        }
Example #12
0
        public long TransactParcelAuto(ServiceCtx Context)
        {
            int Id   = Context.RequestData.ReadInt32();
            int Code = Context.RequestData.ReadInt32();

            (long DataPos, long DataSize) = Context.Request.GetBufferType0x21();

            byte[] Data = AMemoryHelper.ReadBytes(Context.Memory, DataPos, DataSize);

            Data = Parcel.GetParcelData(Data);

            return Flinger.ProcessParcelRequest(Context, Data, Code);
        }
Example #13
0
        public long TransactParcel(ServiceCtx Context)
        {
            int Id   = Context.RequestData.ReadInt32();
            int Code = Context.RequestData.ReadInt32();

            long DataPos  = Context.Request.SendBuff[0].Position;
            long DataSize = Context.Request.SendBuff[0].Size;

            byte[] Data = AMemoryHelper.ReadBytes(Context.Memory, DataPos, (int)DataSize);

            Data = Parcel.GetParcelData(Data);

            return(Flinger.ProcessParcelRequest(Context, Data, Code));
        }
Example #14
0
        public long SetAudioDeviceOutputVolumeAuto(ServiceCtx Context)
        {
            float Volume = Context.RequestData.ReadSingle();

            (long Position, long Size) = Context.Request.GetBufferType0x21();

            byte[] DeviceNameBuffer = AMemoryHelper.ReadBytes(Context.Memory, Position, Size);

            string DeviceName = Encoding.UTF8.GetString(DeviceNameBuffer);

            Context.Ns.Log.PrintStub(LogClass.ServiceAudio, "Stubbed.");

            return(0);
        }
Example #15
0
        private long[] UploadShaders(AMemory Memory)
        {
            long[] Tags = new long[5];

            long BasePosition = MakeInt64From2xInt32(NvGpuEngine3dReg.ShaderAddress);

            for (int Index = 0; Index < 6; Index++)
            {
                int Control = ReadRegister(NvGpuEngine3dReg.ShaderNControl + Index * 0x10);
                int Offset  = ReadRegister(NvGpuEngine3dReg.ShaderNOffset + Index * 0x10);

                //Note: Vertex Program (B) is always enabled.
                bool Enable = (Control & 1) != 0 || Index == 1;

                if (!Enable)
                {
                    continue;
                }

                long Tag = BasePosition + (uint)Offset;

                long Position = Gpu.GetCpuAddr(Tag);

                //TODO: Find a better way to calculate the size.
                int Size = 0x20000;

                byte[] Code = AMemoryHelper.ReadBytes(Memory, Position, (uint)Size);

                GalShaderType ShaderType = GetTypeFromProgram(Index);

                Tags[(int)ShaderType] = Tag;

                Gpu.Renderer.CreateShader(Tag, ShaderType, Code);
                Gpu.Renderer.BindShader(Tag);
            }

            int RawSX = ReadRegister(NvGpuEngine3dReg.ViewportScaleX);
            int RawSY = ReadRegister(NvGpuEngine3dReg.ViewportScaleY);

            float SX = BitConverter.Int32BitsToSingle(RawSX);
            float SY = BitConverter.Int32BitsToSingle(RawSY);

            float SignX = MathF.Sign(SX);
            float SignY = MathF.Sign(SY);

            Gpu.Renderer.SetUniform2F(GalConsts.FlipUniformName, SignX, SignY);

            return(Tags);
        }
Example #16
0
        public long Write(ServiceCtx Context)
        {
            long Position = Context.Request.SendBuff[0].Position;

            long Zero   = Context.RequestData.ReadInt64();
            long Offset = Context.RequestData.ReadInt64();
            long Size   = Context.RequestData.ReadInt64();

            byte[] Data = AMemoryHelper.ReadBytes(Context.Memory, Position, (int)Size);

            BaseStream.Seek(Offset, SeekOrigin.Begin);
            BaseStream.Write(Data, 0, (int)Size);

            return(0);
        }
Example #17
0
        public long SetAudioDeviceOutputVolume(ServiceCtx Context)
        {
            float Volume = Context.RequestData.ReadSingle();

            long Position = Context.Request.SendBuff[0].Position;
            long Size     = Context.Request.SendBuff[0].Size;

            byte[] DeviceNameBuffer = AMemoryHelper.ReadBytes(Context.Memory, Position, Size);

            string DeviceName = Encoding.ASCII.GetString(DeviceNameBuffer);

            Context.Ns.Log.PrintStub(LogClass.ServiceAudio, "Stubbed.");

            return(0);
        }
Example #18
0
        public long AppendAudioOutBuffer(ServiceCtx Context)
        {
            long Tag = Context.RequestData.ReadInt64();

            AudioOutData Data = AMemoryHelper.Read <AudioOutData>(
                Context.Memory,
                Context.Request.SendBuff[0].Position);

            byte[] Buffer = AMemoryHelper.ReadBytes(
                Context.Memory,
                Data.SampleBufferPtr,
                Data.SampleBufferSize);

            AudioOut.AppendBuffer(Track, Tag, Buffer);

            return(0);
        }
Example #19
0
        private void SendSyncRequest(AThreadState ThreadState, bool UserBuffer)
        {
            long CmdPtr = ThreadState.Tpidr;
            long Size   = 0x100;
            int  Handle = 0;

            if (UserBuffer)
            {
                CmdPtr = (long)ThreadState.X0;
                Size   = (long)ThreadState.X1;
                Handle = (int)ThreadState.X2;
            }
            else
            {
                Handle = (int)ThreadState.X0;
            }

            HThread CurrThread = Process.GetThread(ThreadState.Tpidr);

            Process.Scheduler.Suspend(CurrThread.ProcessorId);

            byte[] CmdData = AMemoryHelper.ReadBytes(Memory, CmdPtr, (int)Size);

            HSession Session = Ns.Os.Handles.GetData <HSession>(Handle);

            IpcMessage Cmd = new IpcMessage(CmdData, CmdPtr, Session is HDomain);

            if (Session != null)
            {
                IpcHandler.IpcCall(Ns, Memory, Session, Cmd, CmdPtr, Handle);

                byte[] Response = AMemoryHelper.ReadBytes(Memory, CmdPtr, (int)Size);

                ThreadState.X0 = (int)SvcResult.Success;
            }
            else
            {
                ThreadState.X0 = (int)SvcResult.ErrBadIpcReq;
            }

            Thread.Yield();

            Process.Scheduler.Resume(CurrThread);
        }
Example #20
0
        private long[] UploadShaders(AMemory Memory)
        {
            long[] Tags = new long[5];

            long BasePosition = MakeInt64From2xInt32(NvGpuEngine3dReg.ShaderAddress);

            for (int Index = 0; Index < 6; Index++)
            {
                int Control = ReadRegister(NvGpuEngine3dReg.ShaderNControl + Index * 0x10);
                int Offset  = ReadRegister(NvGpuEngine3dReg.ShaderNOffset + Index * 0x10);

                //Note: Vertex Program (B) is always enabled.
                bool Enable = (Control & 1) != 0 || Index == 1;

                if (!Enable)
                {
                    continue;
                }

                long Tag = BasePosition + (uint)Offset;

                long Position = Gpu.GetCpuAddr(Tag);

                //TODO: Find a better way to calculate the size.
                int Size = 0x20000;

                byte[] Code = AMemoryHelper.ReadBytes(Memory, Position, (uint)Size);

                GalShaderType ShaderType = GetTypeFromProgram(Index);

                Tags[(int)ShaderType] = Tag;

                Gpu.Renderer.CreateShader(Tag, ShaderType, Code);
                Gpu.Renderer.BindShader(Tag);
            }

            return(Tags);
        }
Example #21
0
        public long Write(ServiceCtx Context)
        {
            //TODO: Error conditions.
            long WritePosition = Context.RequestData.ReadInt64();

            (long Position, long Size) = Context.Request.GetBufferType0x21();

            if (Size > 0)
            {
                long MaxSize = Storage.Data.Length - WritePosition;

                if (Size > MaxSize)
                {
                    Size = MaxSize;
                }

                byte[] Data = AMemoryHelper.ReadBytes(Context.Memory, Position, Size);

                Buffer.BlockCopy(Data, 0, Storage.Data, (int)WritePosition, (int)Size);
            }

            return(0);
        }
Example #22
0
        private void SendSyncRequest(ARegisters Registers, bool UserBuffer)
        {
            long CmdPtr = Registers.Tpidr;
            long Size   = 0x100;
            int  Handle = 0;

            if (UserBuffer)
            {
                CmdPtr = (long)Registers.X0;
                Size   = (long)Registers.X1;
                Handle = (int)Registers.X2;
            }
            else
            {
                Handle = (int)Registers.X0;
            }

            byte[] CmdData = AMemoryHelper.ReadBytes(Memory, CmdPtr, (int)Size);

            HSession Session = Ns.Os.Handles.GetData <HSession>(Handle);

            IpcMessage Cmd = new IpcMessage(CmdData, CmdPtr, Session is HDomain);

            if (Session != null)
            {
                IpcHandler.IpcCall(Ns, Memory, Session, Cmd, CmdPtr, Handle);

                byte[] Response = AMemoryHelper.ReadBytes(Memory, CmdPtr, (int)Size);

                Registers.X0 = (int)SvcResult.Success;
            }
            else
            {
                Registers.X0 = (int)SvcResult.ErrBadIpcReq;
            }
        }
 /// <summary>
 ///     Writes a set of bytes to memory.
 /// </summary>
 /// <param name="intPtr">The address where the bytes start in memory.</param>
 /// <param name="length">The length of the byte chunk to read from the memory address.</param>
 /// <returns>
 ///     The byte array section read from memory.
 /// </returns>
 public override byte[] Read(IntPtr intPtr, int length)
 {
     return(AMemoryHelper.ReadBytes(Handle, intPtr, length));
 }
Example #24
0
        private static byte[] GetDecodedTexture(
            AMemory Memory,
            NsGpuTextureFormat Format,
            long Position,
            int Width,
            int Height)
        {
            byte[] Data = null;

            switch (Format)
            {
            case NsGpuTextureFormat.BC1:
            {
                int Size = (Width * Height) >> 1;

                Data = AMemoryHelper.ReadBytes(Memory, Position, Size);

                Data = BCn.DecodeBC1(new NsGpuTexture()
                    {
                        Width  = Width,
                        Height = Height,
                        Data   = Data
                    }, 0);

                break;
            }

            case NsGpuTextureFormat.BC2:
            {
                int Size = Width * Height;

                Data = AMemoryHelper.ReadBytes(Memory, Position, Size);

                Data = BCn.DecodeBC2(new NsGpuTexture()
                    {
                        Width  = Width,
                        Height = Height,
                        Data   = Data
                    }, 0);

                break;
            }

            case NsGpuTextureFormat.BC3:
            {
                int Size = Width * Height;

                Data = AMemoryHelper.ReadBytes(Memory, Position, Size);

                Data = BCn.DecodeBC3(new NsGpuTexture()
                    {
                        Width  = Width,
                        Height = Height,
                        Data   = Data
                    }, 0);

                break;
            }

                //default: throw new NotImplementedException(Format.ToString());
            }

            return(Data);
        }
Example #25
0
        public long Log(ServiceCtx Context)
        {
            byte[] LogBuffer = AMemoryHelper.ReadBytes(
                Context.Memory,
                Context.Request.PtrBuff[0].Position,
                Context.Request.PtrBuff[0].Size);

            using (MemoryStream MS = new MemoryStream(LogBuffer))
            {
                BinaryReader Reader = new BinaryReader(MS);

                long  Pid           = Reader.ReadInt64();
                long  ThreadContext = Reader.ReadInt64();
                short Flags         = Reader.ReadInt16();
                byte  Level         = Reader.ReadByte();
                byte  Verbosity     = Reader.ReadByte();
                int   PayloadLength = Reader.ReadInt32();

                StringBuilder SB = new StringBuilder();

                SB.AppendLine("Guest log:");

                while (MS.Position < MS.Length)
                {
                    byte Type = Reader.ReadByte();
                    byte Size = Reader.ReadByte();

                    LmLogField Field = (LmLogField)Type;

                    string FieldStr = string.Empty;

                    if (Field == LmLogField.Skip)
                    {
                        Reader.ReadByte();

                        continue;
                    }
                    else if (Field == LmLogField.Line)
                    {
                        FieldStr = Field + ": " + Reader.ReadInt32();
                    }
                    else
                    {
                        FieldStr = Field + ": \"" + Encoding.UTF8.GetString(Reader.ReadBytes(Size)) + "\"";
                    }

                    SB.AppendLine(" " + FieldStr);
                }

                string Text = SB.ToString();

                switch ((LmLogLevel)Level)
                {
                case LmLogLevel.Trace:    Context.Ns.Log.PrintDebug(LogClass.ServiceLm, Text); break;

                case LmLogLevel.Info:     Context.Ns.Log.PrintInfo(LogClass.ServiceLm, Text); break;

                case LmLogLevel.Warning:  Context.Ns.Log.PrintWarning(LogClass.ServiceLm, Text); break;

                case LmLogLevel.Error:    Context.Ns.Log.PrintError(LogClass.ServiceLm, Text); break;

                case LmLogLevel.Critical: Context.Ns.Log.PrintError(LogClass.ServiceLm, Text); break;
                }
            }

            return(0);
        }
Example #26
0
        public long Log(ServiceCtx Context)
        {
            long BufferPosition = Context.Request.PtrBuff[0].Position;
            long BufferLen      = Context.Request.PtrBuff[0].Size;

            byte[] LogBuffer = AMemoryHelper.ReadBytes(Context.Memory, BufferPosition, BufferLen);

            MemoryStream LogMessage = new MemoryStream(LogBuffer);
            BinaryReader bReader    = new BinaryReader(LogMessage);

            //Header reading.
            long Pid        = bReader.ReadInt64();
            long ThreadCxt  = bReader.ReadInt64();
            int  Infos      = bReader.ReadInt32();
            int  PayloadLen = bReader.ReadInt32();

            int iFlags     = Infos & 0xFFFF;
            int iSeverity  = (Infos >> 17) & 0x7F;
            int iVerbosity = (Infos >> 25) & 0x7F;

            //ToDo: For now we don't care about Head or Tail Log.
            bool IsHeadLog = Convert.ToBoolean(iFlags & (int)Flags.IsHead);
            bool IsTailLog = Convert.ToBoolean(iFlags & (int)Flags.IsTail);

            string LogString = "nn::diag::detail::LogImpl()" + Environment.NewLine + Environment.NewLine +
                               "Header:" + Environment.NewLine +
                               $"   Pid: {Pid}" + Environment.NewLine +
                               $"   ThreadContext: {ThreadCxt}" + Environment.NewLine +
                               $"   Flags: {IsHeadLog}/{IsTailLog}" + Environment.NewLine +
                               $"   Severity: {Enum.GetName(typeof(Severity), iSeverity)}" + Environment.NewLine +
                               $"   Verbosity: {iVerbosity}";

            LogString += Environment.NewLine + Environment.NewLine + "Message:" + Environment.NewLine;

            string StrMessage = "", StrLine = "", StrFilename = "", StrFunction = "",
                   StrModule = "", StrThread = "";

            do
            {
                byte FieldType = bReader.ReadByte();
                byte FieldSize = bReader.ReadByte();

                if ((Field)FieldType != Field.Skip || FieldSize != 0)
                {
                    byte[] Message = bReader.ReadBytes(FieldSize);
                    switch ((Field)FieldType)
                    {
                    case Field.Message:
                        StrMessage = Encoding.UTF8.GetString(Message);
                        break;

                    case Field.Line:
                        StrLine = BitConverter.ToInt32(Message, 0).ToString();
                        break;

                    case Field.Filename:
                        StrFilename = Encoding.UTF8.GetString(Message);
                        break;

                    case Field.Function:
                        StrFunction = Encoding.UTF8.GetString(Message);
                        break;

                    case Field.Module:
                        StrModule = Encoding.UTF8.GetString(Message);
                        break;

                    case Field.Thread:
                        StrThread = Encoding.UTF8.GetString(Message);
                        break;
                    }
                }
            }while (LogMessage.Position != PayloadLen + 0x18); // 0x18 - Size of Header LogMessage.

            LogString += StrModule + " > " + StrThread + ": " + StrFilename + "@" + StrFunction + "(" + StrLine + ") '" + StrMessage + "'" + Environment.NewLine;

            switch ((Severity)iSeverity)
            {
            case Severity.Trace:    Logging.Trace(LogString); break;

            case Severity.Info:     Logging.Info(LogString);  break;

            case Severity.Warning:  Logging.Warn(LogString);  break;

            case Severity.Error:    Logging.Error(LogString); break;

            case Severity.Critical: Logging.Fatal(LogString); break;
            }

            return(0);
        }
Example #27
0
        public byte[] ReadBytes(long Position, long Size)
        {
            Position = GetPhysicalAddress(Position);

            return(AMemoryHelper.ReadBytes(Memory, Position, Size));
        }
Example #28
0
        private void UploadVertexArrays(AMemory Memory)
        {
            long IndexPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.IndexArrayAddress);

            int IndexSize  = ReadRegister(NvGpuEngine3dReg.IndexArrayFormat);
            int IndexFirst = ReadRegister(NvGpuEngine3dReg.IndexBatchFirst);
            int IndexCount = ReadRegister(NvGpuEngine3dReg.IndexBatchCount);

            GalIndexFormat IndexFormat = (GalIndexFormat)IndexSize;

            IndexSize = 1 << IndexSize;

            if (IndexSize > 4)
            {
                throw new InvalidOperationException();
            }

            if (IndexSize != 0)
            {
                IndexPosition = Gpu.GetCpuAddr(IndexPosition);

                int BufferSize = IndexCount * IndexSize;

                byte[] Data = AMemoryHelper.ReadBytes(Memory, IndexPosition, BufferSize);

                Gpu.Renderer.SetIndexArray(Data, IndexFormat);
            }

            List <GalVertexAttrib>[] Attribs = new List <GalVertexAttrib> [32];

            for (int Attr = 0; Attr < 16; Attr++)
            {
                int Packed = ReadRegister(NvGpuEngine3dReg.VertexAttribNFormat + Attr);

                int ArrayIndex = Packed & 0x1f;

                if (Attribs[ArrayIndex] == null)
                {
                    Attribs[ArrayIndex] = new List <GalVertexAttrib>();
                }

                Attribs[ArrayIndex].Add(new GalVertexAttrib(
                                            Attr,
                                            ((Packed >> 6) & 0x1) != 0,
                                            (Packed >> 7) & 0x3fff,
                                            (GalVertexAttribSize)((Packed >> 21) & 0x3f),
                                            (GalVertexAttribType)((Packed >> 27) & 0x7),
                                            ((Packed >> 31) & 0x1) != 0));
            }

            for (int Index = 0; Index < 32; Index++)
            {
                int VertexFirst = ReadRegister(NvGpuEngine3dReg.VertexArrayFirst);
                int VertexCount = ReadRegister(NvGpuEngine3dReg.VertexArrayCount);

                int Control = ReadRegister(NvGpuEngine3dReg.VertexArrayNControl + Index * 4);

                bool Enable = (Control & 0x1000) != 0;

                long VertexPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.VertexArrayNAddress + Index * 4);

                if (!Enable)
                {
                    continue;
                }

                int Stride = Control & 0xfff;

                long Size = 0;

                if (IndexCount != 0)
                {
                    Size = GetVertexCountFromIndexBuffer(
                        Memory,
                        IndexPosition,
                        IndexCount,
                        IndexSize);
                }
                else
                {
                    Size = VertexCount;
                }

                //TODO: Support cases where the Stride is 0.
                //In this case, we need to use the size of the attribute.
                Size *= Stride;

                VertexPosition = Gpu.GetCpuAddr(VertexPosition);

                byte[] Data = AMemoryHelper.ReadBytes(Memory, VertexPosition, Size);

                GalVertexAttrib[] AttribArray = Attribs[Index]?.ToArray() ?? new GalVertexAttrib[0];

                Gpu.Renderer.SetVertexArray(Index, Stride, Data, AttribArray);

                int PrimCtrl = ReadRegister(NvGpuEngine3dReg.VertexBeginGl);

                GalPrimitiveType PrimType = (GalPrimitiveType)(PrimCtrl & 0xffff);

                if (IndexCount != 0)
                {
                    Gpu.Renderer.DrawElements(Index, IndexFirst, PrimType);
                }
                else
                {
                    Gpu.Renderer.DrawArrays(Index, VertexFirst, VertexCount, PrimType);
                }
            }
        }