コード例 #1
0
        private void InitializeMessage(PortMessage existingMessage, MemoryRegion data, short dataLength)
        {
            if (dataLength > Win32.PortMessageMaxDataLength)
                throw new ArgumentOutOfRangeException("Data length is too large.");
            if (dataLength < 0)
                throw new ArgumentOutOfRangeException("Data length cannot be negative.");

            _message = new PortMessageStruct
            {
                DataLength = dataLength, 
                TotalLength = (short)(PortMessageStruct.SizeOf + dataLength), 
                DataInfoOffset = 0
            };

            if (existingMessage != null)
            {
                _message.ClientId = existingMessage.ClientId;
                _message.MessageId = existingMessage.MessageId;
            }

            _data = data;

            _referencedData = data;
            _referencedData.Reference();
        }
コード例 #2
0
ファイル: SymbolTable.cs プロジェクト: sh4nnongoh/Dynamo
 public SymbolNode(
     string name,
     int index, 
     int functionIndex,
     Type datatype,
     bool isArgument, 
     int runtimeIndex,
     MemoryRegion memregion = MemoryRegion.InvalidRegion, 
     int scope = -1,
     CompilerDefinitions.AccessModifier access = CompilerDefinitions.AccessModifier.Public,
     bool isStatic = false,
     int codeBlockId = Constants.kInvalidIndex)
 {
     this.name           = name;
     isTemp         = name.StartsWith("%");
     isSSATemp = name.StartsWith(Constants.kSSATempPrefix); 
     this.index          = index;
     this.functionIndex = functionIndex;
     this.absoluteFunctionIndex = functionIndex;
     this.datatype       = datatype;
     this.isArgument     = isArgument;
     this.memregion      = memregion;
     this.classScope     = scope;
     this.absoluteClassScope = scope;
     runtimeTableIndex = runtimeIndex;
     this.access = access;
     this.isStatic = isStatic;
     this.codeBlockId = codeBlockId;
 }
コード例 #3
0
ファイル: SMC91X.cs プロジェクト: rte-se/emul8
        public void Reset()
        {
            IRQ.Unset();
            memoryBuffer = new MemoryRegion[NumberOfPackets];
            for(var i = 0; i < memoryBuffer.Length; ++i)
            {
                memoryBuffer[i] = new MemoryRegion();
            }
           
            rxFifo.Clear();
            txFifo.Clear();
            sentFifo.Clear();

            currentBank = Bank.Bank0;
            transmitControl = 0x0000;
            receiveControl = 0x0000;
            configuration = 0xA0B1;
            generalPurposeRegister = 0x0000;
            control = 0x1210;
            packetNumber = 0x00;
            allocationResult = 0x0;
            pointer = 0x0000;
            interruptMask = 0x0;
            interruptStatus = TxEmptyInterrupt;
            earlyReceive = 0x001f;
            Update();
        }
コード例 #4
0
ファイル: PortMessage.cs プロジェクト: RoDaniel/featurehouse
        internal PortMessage(MemoryRegion headerAndData)
        {
            _message = headerAndData.ReadStruct<PortMessageStruct>();
            _data = new MemoryRegion(headerAndData, _portMessageSize, _message.DataLength);

            _referencedData = headerAndData;
            _referencedData.Reference();
        }
コード例 #5
0
ファイル: SymbolTable.cs プロジェクト: sh4nnongoh/Dynamo
 public SymbolNode()
 {
     name = string.Empty;
     memregion       = MemoryRegion.InvalidRegion;
     classScope      = Constants.kInvalidIndex;
     functionIndex   = Constants.kGlobalScope;
     absoluteClassScope = Constants.kGlobalScope;
     absoluteFunctionIndex = Constants.kGlobalScope;
     isStatic        = false;
     isTemp          = false;
 }
コード例 #6
0
        internal SsObjectAttributes(MemoryRegion data)
        {
            KphSsObjectAttributes oaInfo = data.ReadStruct<KphSsObjectAttributes>();

            if (oaInfo.ObjectNameOffset != 0)
                this.ObjectName = new SsUnicodeString(new MemoryRegion(data, oaInfo.ObjectNameOffset));

            this.Original = oaInfo.ObjectAttributes;

            if (oaInfo.RootDirectoryOffset != 0)
                this.RootDirectory = new SsHandle(new MemoryRegion(data, oaInfo.RootDirectoryOffset));
        }
コード例 #7
0
ファイル: Credentials.cs プロジェクト: andyvand/ProcessHacker
        public static void UnpackCredentials(
            MemoryRegion buffer,
            CredPackFlags flags,
            out string domainName,
            out string userName,
            out string password
            )
        {
            using (var domainNameBuffer = new MemoryAlloc(0x100))
            using (var userNameBuffer = new MemoryAlloc(0x100))
            using (var passwordBuffer = new MemoryAlloc(0x100))
            {
                int domainNameSize = domainNameBuffer.Size / 2 - 1;
                int userNameSize = userNameBuffer.Size / 2 - 1;
                int passwordSize = passwordBuffer.Size / 2 - 1;

                if (!Win32.CredUnPackAuthenticationBuffer(
                    flags,
                    buffer,
                    buffer.Size,
                    userNameBuffer,
                    ref userNameSize,
                    domainNameBuffer,
                    ref domainNameSize,
                    passwordBuffer,
                    ref passwordSize
                    ))
                {
                    domainNameBuffer.ResizeNew(domainNameSize * 2 + 2);
                    userNameBuffer.ResizeNew(userNameSize * 2 + 2);
                    passwordBuffer.ResizeNew(passwordSize * 2 + 2);

                    if (!Win32.CredUnPackAuthenticationBuffer(
                        flags,
                        buffer,
                        buffer.Size,
                        userNameBuffer,
                        ref userNameSize,
                        domainNameBuffer,
                        ref domainNameSize,
                        passwordBuffer,
                        ref passwordSize
                        ))
                        Win32.Throw();
                }

                domainName = domainNameBuffer.ReadUnicodeString(0);
                userName = userNameBuffer.ReadUnicodeString(0);
                password = passwordBuffer.ReadUnicodeString(0);
            }
        }
コード例 #8
0
        internal SsUnicodeString(MemoryRegion data)
        {
            KphSsUnicodeString unicodeStringInfo = data.ReadStruct<KphSsUnicodeString>();

            this.Original = new UnicodeString()
            {
                Length = unicodeStringInfo.Length,
                MaximumLength = unicodeStringInfo.MaximumLength,
                Buffer = unicodeStringInfo.Pointer
            };
            this.String = data.ReadUnicodeString(
                KphSsUnicodeString.BufferOffset,
                unicodeStringInfo.Length / 2
                );
        }
コード例 #9
0
ファイル: SsBytes.cs プロジェクト: andyvand/ProcessHacker
        public SsBytes(MemoryRegion data)
        {
            KphSsBytes bytes;
            byte[] buffer;

            bytes = data.ReadStruct<KphSsBytes>();
            buffer = new byte[bytes.Length];
            System.Runtime.InteropServices.Marshal.Copy(
                data.Memory.Increment(KphSsBytes.BufferOffset),
                buffer,
                0,
                buffer.Length
                );

            this.Bytes = buffer;
        }
コード例 #10
0
        internal SsHandle(MemoryRegion data)
        {
            KphSsHandle handleInfo = data.ReadStruct<KphSsHandle>(0, KphSsHandle.SizeOf, 0);

            if (handleInfo.TypeNameOffset != 0)
            {
                this.TypeName = SsLogger.ReadWString(new MemoryRegion(data, handleInfo.TypeNameOffset));
            }

            if (handleInfo.NameOffset != 0)
            {
                this.Name = SsLogger.ReadWString(new MemoryRegion(data, handleInfo.NameOffset));
            }

            this.ProcessId = handleInfo.ClientId.ProcessId;
            this.ThreadId = handleInfo.ClientId.ThreadId;
        }
コード例 #11
0
ファイル: Ace.cs プロジェクト: RoDaniel/featurehouse
        public Ace(IntPtr memory, bool copy)
            : base(copy)
        {
            if (copy)
            {
                Ace existingAce = new Ace(memory);

                _memory = new MemoryAlloc(existingAce.Size);
                _memory.WriteMemory(0, existingAce, 0, existingAce.Size);
            }
            else
            {
                _memory = new MemoryRegion(memory);
            }

            this.Read();
        }
コード例 #12
0
 public SecurityDescriptor()
 {
     NtStatus status;
     _memory = new MemoryAlloc(Win32.SecurityDescriptorMinLength);
     if ((status = Win32.RtlCreateSecurityDescriptor(
         _memory,
         Win32.SecurityDescriptorRevision
         )) >= NtStatus.Error)
     {
         _memory.Dispose();
         _memory = null;
         this.DisableOwnership(false);
         Win32.ThrowLastError(status);
     }
     _memory.Reference();
     _memory.Dispose();
 }
コード例 #13
0
ファイル: DebugBuffer.cs プロジェクト: RoDaniel/featurehouse
        public void EnumLocks(DebugEnumLocksDelegate callback)
        {
            var debugInfo = this.GetDebugInformation();

            if (debugInfo.Locks == IntPtr.Zero)
                throw new InvalidOperationException("Lock information does not exist.");

            MemoryRegion locksInfo = new MemoryRegion(debugInfo.Locks);
            var locks = locksInfo.ReadStruct<RtlProcessLocks>();

            for (int i = 0; i < locks.NumberOfLocks; i++)
            {
                var lock_ = locksInfo.ReadStruct<RtlProcessLockInformation>(sizeof(int), i);

                if (!callback(new LockInformation(lock_)))
                    break;
            }
        }
コード例 #14
0
ファイル: DebugBuffer.cs プロジェクト: RoDaniel/featurehouse
        public void EnumHeaps(DebugEnumHeapsDelegate callback)
        {
            var debugInfo = this.GetDebugInformation();

            if (debugInfo.Heaps == IntPtr.Zero)
                throw new InvalidOperationException("Heap information does not exist.");

            MemoryRegion heapInfo = new MemoryRegion(debugInfo.Heaps);
            var heaps = heapInfo.ReadStruct<RtlProcessHeaps>();

            for (int i = 0; i < heaps.NumberOfHeaps; i++)
            {
                var heap = heapInfo.ReadStruct<RtlHeapInformation>(RtlProcessHeaps.HeapsOffset, i);

                if (!callback(new HeapInformation(heap)))
                    break;
            }
        }
コード例 #15
0
ファイル: SymbolTable.cs プロジェクト: ankushraizada/Dynamo
 public SymbolNode(
     string name,
     int index, 
     int heapIndex, 
     int functionIndex,
     ProtoCore.Type datatype,
     ProtoCore.Type enforcedType,
     int size,
     int datasize, 
     bool isArgument, 
     int runtimeIndex,
     MemoryRegion memregion = MemoryRegion.kInvalidRegion, 
     bool isArray = false, 
     List<int> arraySizeList = null, 
     int scope = -1,
     ProtoCore.CompilerDefinitions.AccessModifier access = ProtoCore.CompilerDefinitions.AccessModifier.kPublic,
     bool isStatic = false,
     int codeBlockId = ProtoCore.DSASM.Constants.kInvalidIndex)
 {
     this.name           = name;
     isTemp         = name.StartsWith("%");
     this.index          = index;
     this.functionIndex = functionIndex;
     this.absoluteFunctionIndex = functionIndex;
     this.datatype       = datatype;
     this.staticType   = enforcedType;
     this.size           = size;
     this.datasize       = datasize;
     this.isArgument     = isArgument;
     this.arraySizeList  = arraySizeList;
     this.memregion      = memregion;
     this.classScope     = scope;
     this.absoluteClassScope = scope;
     runtimeTableIndex = runtimeIndex;
     this.access = access;
     this.isStatic = isStatic;
     this.codeBlockId = codeBlockId;
 }
コード例 #16
0
 public object GetProfileData(MemoryRegion buffer)
 {
     return(null);
 }
コード例 #17
0
 public static FileHandle OpenFile(MemoryRegion buf, string path)
 {
     NullTerminatedString.Set((byte *)buf.Start, path);
     return((int)MessageManager.Send(SysCallTarget.OpenFile, buf.Start));
 }
コード例 #18
0
 public AsyncIoContext BeginTransceive(MemoryRegion inBuffer, MemoryRegion outBuffer)
 {
     return this.BeginFsControl(FsCtlTransceive, inBuffer, outBuffer);
 }
コード例 #19
0
        /// <summary>
        /// Reads the debug information structure from the buffer.
        /// </summary>
        /// <returns>A RtlDebugInformation structure.</returns>
        private RtlDebugInformation GetDebugInformation()
        {
            MemoryRegion data = new MemoryRegion(_buffer);

            return(data.ReadStruct <RtlDebugInformation>());
        }
コード例 #20
0
 public void Read(MemoryRegion data)
 {
     this.Read((void *)data.Memory);
 }
コード例 #21
0
 public object GetProfileData(MemoryRegion buffer)
 {
     return null;
 }
コード例 #22
0
 public virtual void addRegion(MemoryRegion newRegion)
 {
     this._regions.Add(newRegion);
     this._regions = this._regions.OrderBy(x => x.start).ToList(); // Sort
 }
コード例 #23
0
        internal MemoryRegion[] GetMemoryRanges()
        {
            MemoryRegion[] regions = new MemoryRegion[ranges.Length];

            for (int i = 0; i < regions.Length; i++)
                regions[i] = new MemoryRegion { BaseAddress = ranges[i].MemoryStart, MemoryEnd = ranges[i].MemoryEnd };
            return regions;
        }
コード例 #24
0
        public KernelResult Initialize(
            ProcessCreationInfo creationInfo,
            int[]               caps,
            KResourceLimit resourceLimit,
            MemoryRegion memRegion)
        {
            ResourceLimit = resourceLimit;
            _memRegion    = memRegion;

            ulong personalMmHeapSize = GetPersonalMmHeapSize((ulong)creationInfo.PersonalMmHeapPagesCount, memRegion);

            ulong codePagesCount = (ulong)creationInfo.CodePagesCount;

            ulong neededSizeForProcess = personalMmHeapSize + codePagesCount * KMemoryManager.PageSize;

            if (neededSizeForProcess != 0 && resourceLimit != null)
            {
                if (!resourceLimit.Reserve(LimitableResource.Memory, neededSizeForProcess))
                {
                    return(KernelResult.ResLimitExceeded);
                }
            }

            void CleanUpForError()
            {
                if (neededSizeForProcess != 0 && resourceLimit != null)
                {
                    resourceLimit.Release(LimitableResource.Memory, neededSizeForProcess);
                }
            }

            PersonalMmHeapPagesCount = (ulong)creationInfo.PersonalMmHeapPagesCount;

            KMemoryBlockAllocator memoryBlockAllocator;

            if (PersonalMmHeapPagesCount != 0)
            {
                memoryBlockAllocator = new KMemoryBlockAllocator(PersonalMmHeapPagesCount * KMemoryManager.PageSize);
            }
            else
            {
                memoryBlockAllocator = (MmuFlags & 0x40) != 0
                    ? KernelContext.LargeMemoryBlockAllocator
                    : KernelContext.SmallMemoryBlockAllocator;
            }

            AddressSpaceType addrSpaceType = (AddressSpaceType)((creationInfo.MmuFlags >> 1) & 7);

            InitializeMemoryManager(addrSpaceType, memRegion);

            bool aslrEnabled = ((creationInfo.MmuFlags >> 5) & 1) != 0;

            ulong codeAddress = creationInfo.CodeAddress;

            ulong codeSize = codePagesCount * KMemoryManager.PageSize;

            KernelResult result = MemoryManager.InitializeForProcess(
                addrSpaceType,
                aslrEnabled,
                !aslrEnabled,
                memRegion,
                codeAddress,
                codeSize,
                memoryBlockAllocator);

            if (result != KernelResult.Success)
            {
                CleanUpForError();

                return(result);
            }

            if (!ValidateCodeAddressAndSize(codeAddress, codeSize))
            {
                CleanUpForError();

                return(KernelResult.InvalidMemRange);
            }

            result = MemoryManager.MapNewProcessCode(
                codeAddress,
                codePagesCount,
                MemoryState.CodeStatic,
                MemoryPermission.None);

            if (result != KernelResult.Success)
            {
                CleanUpForError();

                return(result);
            }

            result = Capabilities.InitializeForUser(caps, MemoryManager);

            if (result != KernelResult.Success)
            {
                CleanUpForError();

                return(result);
            }

            Pid = KernelContext.NewProcessId();

            if (Pid == -1 || (ulong)Pid < KernelConstants.InitialProcessId)
            {
                throw new InvalidOperationException($"Invalid Process Id {Pid}.");
            }

            result = ParseProcessInfo(creationInfo);

            if (result != KernelResult.Success)
            {
                CleanUpForError();
            }

            return(result);
        }
コード例 #25
0
 public MemoryRange(UInt32 start = 0, UInt32 end = 0, UInt32 length = 0, MemoryRegion region = null)
     : base(end: end, length: length)
 {
     this._region = region;
 }
コード例 #26
0
        public KernelResult InitializeKip(
            ProcessCreationInfo creationInfo,
            int[]               caps,
            KPageList pageList,
            KResourceLimit resourceLimit,
            MemoryRegion memRegion)
        {
            ResourceLimit = resourceLimit;
            _memRegion    = memRegion;

            AddressSpaceType addrSpaceType = (AddressSpaceType)((creationInfo.MmuFlags >> 1) & 7);

            InitializeMemoryManager(addrSpaceType, memRegion);

            bool aslrEnabled = ((creationInfo.MmuFlags >> 5) & 1) != 0;

            ulong codeAddress = creationInfo.CodeAddress;

            ulong codeSize = (ulong)creationInfo.CodePagesCount * KMemoryManager.PageSize;

            KMemoryBlockAllocator memoryBlockAllocator = (MmuFlags & 0x40) != 0
                ? KernelContext.LargeMemoryBlockAllocator
                : KernelContext.SmallMemoryBlockAllocator;

            KernelResult result = MemoryManager.InitializeForProcess(
                addrSpaceType,
                aslrEnabled,
                !aslrEnabled,
                memRegion,
                codeAddress,
                codeSize,
                memoryBlockAllocator);

            if (result != KernelResult.Success)
            {
                return(result);
            }

            if (!ValidateCodeAddressAndSize(codeAddress, codeSize))
            {
                return(KernelResult.InvalidMemRange);
            }

            result = MemoryManager.MapPages(
                codeAddress,
                pageList,
                MemoryState.CodeStatic,
                MemoryPermission.None);

            if (result != KernelResult.Success)
            {
                return(result);
            }

            result = Capabilities.InitializeForKernel(caps, MemoryManager);

            if (result != KernelResult.Success)
            {
                return(result);
            }

            Pid = KernelContext.NewKipId();

            if (Pid == 0 || (ulong)Pid >= KernelConstants.InitialProcessId)
            {
                throw new InvalidOperationException($"Invalid KIP Id {Pid}.");
            }

            result = ParseProcessInfo(creationInfo);

            return(result);
        }
コード例 #27
0
 public void Write(MemoryRegion data, int offset)
 {
     this.Write((void *)data.Memory.Increment(offset));
 }
コード例 #28
0
ファイル: ProgramLoader.cs プロジェクト: davirxavier/Ryujinx
        public static bool LoadStaticObjects(
            Horizon system,
            Npdm metaData,
            IExecutable[] staticObjects,
            byte[]        arguments = null)
        {
            ulong argsStart = 0;
            int   argsSize  = 0;
            ulong codeStart = metaData.Is64Bit ? 0x8000000UL : 0x200000UL;
            int   codeSize  = 0;

            ulong[] nsoBase = new ulong[staticObjects.Length];

            for (int index = 0; index < staticObjects.Length; index++)
            {
                IExecutable staticObject = staticObjects[index];

                int textEnd = staticObject.TextOffset + staticObject.Text.Length;
                int roEnd   = staticObject.RoOffset + staticObject.Ro.Length;
                int dataEnd = staticObject.DataOffset + staticObject.Data.Length + staticObject.BssSize;

                int nsoSize = textEnd;

                if ((uint)nsoSize < (uint)roEnd)
                {
                    nsoSize = roEnd;
                }

                if ((uint)nsoSize < (uint)dataEnd)
                {
                    nsoSize = dataEnd;
                }

                nsoSize = BitUtils.AlignUp(nsoSize, KMemoryManager.PageSize);

                nsoBase[index] = codeStart + (ulong)codeSize;

                codeSize += nsoSize;

                if (arguments != null && argsSize == 0)
                {
                    argsStart = (ulong)codeSize;

                    argsSize = BitUtils.AlignDown(arguments.Length * 2 + ArgsTotalSize - 1, KMemoryManager.PageSize);

                    codeSize += argsSize;
                }
            }

            int codePagesCount = codeSize / KMemoryManager.PageSize;

            int personalMmHeapPagesCount = metaData.PersonalMmHeapSize / KMemoryManager.PageSize;

            ProcessCreationInfo creationInfo = new ProcessCreationInfo(
                metaData.TitleName,
                metaData.ProcessCategory,
                metaData.Aci0.TitleId,
                codeStart,
                codePagesCount,
                metaData.MmuFlags,
                0,
                personalMmHeapPagesCount);

            KernelResult result;

            KResourceLimit resourceLimit = new KResourceLimit(system);

            long applicationRgSize = (long)system.MemoryRegions[(int)MemoryRegion.Application].Size;

            result  = resourceLimit.SetLimitValue(LimitableResource.Memory, applicationRgSize);
            result |= resourceLimit.SetLimitValue(LimitableResource.Thread, 608);
            result |= resourceLimit.SetLimitValue(LimitableResource.Event, 700);
            result |= resourceLimit.SetLimitValue(LimitableResource.TransferMemory, 128);
            result |= resourceLimit.SetLimitValue(LimitableResource.Session, 894);

            if (result != KernelResult.Success)
            {
                Logger.PrintError(LogClass.Loader, $"Process initialization failed setting resource limit values.");

                return(false);
            }

            KProcess process = new KProcess(system);

            MemoryRegion memoryRegion = (MemoryRegion)((metaData.Acid.Flags >> 2) & 0xf);

            if (memoryRegion > MemoryRegion.NvServices)
            {
                Logger.PrintError(LogClass.Loader, $"Process initialization failed due to invalid ACID flags.");

                return(false);
            }

            result = process.Initialize(
                creationInfo,
                metaData.Aci0.KernelAccessControl.Capabilities,
                resourceLimit,
                memoryRegion);

            if (result != KernelResult.Success)
            {
                Logger.PrintError(LogClass.Loader, $"Process initialization returned error \"{result}\".");

                return(false);
            }

            for (int index = 0; index < staticObjects.Length; index++)
            {
                Logger.PrintInfo(LogClass.Loader, $"Loading image {index} at 0x{nsoBase[index]:x16}...");

                result = LoadIntoMemory(process, staticObjects[index], nsoBase[index]);

                if (result != KernelResult.Success)
                {
                    Logger.PrintError(LogClass.Loader, $"Process initialization returned error \"{result}\".");

                    return(false);
                }
            }

            process.DefaultCpuCore = metaData.DefaultCpuId;

            result = process.Start(metaData.MainThreadPriority, (ulong)metaData.MainThreadStackSize);

            if (result != KernelResult.Success)
            {
                Logger.PrintError(LogClass.Loader, $"Process start returned error \"{result}\".");

                return(false);
            }

            system.Processes.Add(process.Pid, process);

            return(true);
        }
コード例 #29
0
 /// <summary>
 /// Creates a security descriptor from memory.
 /// </summary>
 /// <param name="memory">The memory region to use. This object will be referenced.</param>
 public SecurityDescriptor(MemoryRegion memory)
 {
     _memory = memory;
     _memory.Reference();
     this.Read();
 }
コード例 #30
0
 public MemoryRangeBase(UInt32 start = 0, UInt32 end = 0, UInt32 length = 0, MemoryRegion region = null)
 {
     this.start = start;
     if (length != 0)
     {
         this.end = this.start + length - 1;
     }
     else
     {
         this.end = end;
     }
     this._region = region;
 }
コード例 #31
0
 public static void WriteDebugMessage(MemoryRegion buf, string message)
 {
     NullTerminatedString.Set((byte *)buf.Start, message);
     MessageManager.Send(SysCallTarget.WriteDebugMessage, buf.Start);
 }
コード例 #32
0
ファイル: ProgramLoader.cs プロジェクト: reuniware/Ryujinx
        public static bool LoadKernelInitalProcess(Horizon system, KernelInitialProcess kip)
        {
            int endOffset = kip.DataOffset + kip.Data.Length;

            if (kip.BssSize != 0)
            {
                endOffset = kip.BssOffset + kip.BssSize;
            }

            int codeSize = BitUtils.AlignUp(kip.TextOffset + endOffset, KMemoryManager.PageSize);

            int codePagesCount = codeSize / KMemoryManager.PageSize;

            ulong codeBaseAddress = kip.Addr39Bits ? 0x8000000UL : 0x200000UL;

            ulong codeAddress = codeBaseAddress + (ulong)kip.TextOffset;

            int mmuFlags = 0;

            if (AslrEnabled)
            {
                //TODO: Randomization.

                mmuFlags |= 0x20;
            }

            if (kip.Addr39Bits)
            {
                mmuFlags |= (int)AddressSpaceType.Addr39Bits << 1;
            }

            if (kip.Is64Bits)
            {
                mmuFlags |= 1;
            }

            ProcessCreationInfo creationInfo = new ProcessCreationInfo(
                kip.Name,
                kip.ProcessCategory,
                kip.TitleId,
                codeAddress,
                codePagesCount,
                mmuFlags,
                0,
                0);

            MemoryRegion memRegion = kip.IsService
                ? MemoryRegion.Service
                : MemoryRegion.Application;

            KMemoryRegionManager region = system.MemoryRegions[(int)memRegion];

            KernelResult result = region.AllocatePages((ulong)codePagesCount, false, out KPageList pageList);

            if (result != KernelResult.Success)
            {
                Logger.PrintError(LogClass.Loader, $"Process initialization returned error \"{result}\".");

                return(false);
            }

            KProcess process = new KProcess(system);

            result = process.InitializeKip(
                creationInfo,
                kip.Capabilities,
                pageList,
                system.ResourceLimit,
                memRegion);

            if (result != KernelResult.Success)
            {
                Logger.PrintError(LogClass.Loader, $"Process initialization returned error \"{result}\".");

                return(false);
            }

            result = LoadIntoMemory(process, kip, codeBaseAddress);

            if (result != KernelResult.Success)
            {
                Logger.PrintError(LogClass.Loader, $"Process initialization returned error \"{result}\".");

                return(false);
            }

            result = process.Start(kip.MainThreadPriority, (ulong)kip.MainThreadStackSize);

            if (result != KernelResult.Success)
            {
                Logger.PrintError(LogClass.Loader, $"Process start returned error \"{result}\".");

                return(false);
            }

            system.Processes.Add(process.Pid, process);

            return(true);
        }
コード例 #33
0
        public static bool LoadKip(KernelContext context, KipExecutable kip)
        {
            uint endOffset = kip.DataOffset + (uint)kip.Data.Length;

            if (kip.BssSize != 0)
            {
                endOffset = kip.BssOffset + kip.BssSize;
            }

            uint codeSize = BitUtils.AlignUp(kip.TextOffset + endOffset, KPageTableBase.PageSize);

            int codePagesCount = (int)(codeSize / KPageTableBase.PageSize);

            ulong codeBaseAddress = kip.Is64BitAddressSpace ? 0x8000000UL : 0x200000UL;

            ulong codeAddress = codeBaseAddress + (ulong)kip.TextOffset;

            ProcessCreationFlags flags = 0;

            if (AslrEnabled)
            {
                // TODO: Randomization.

                flags |= ProcessCreationFlags.EnableAslr;
            }

            if (kip.Is64BitAddressSpace)
            {
                flags |= ProcessCreationFlags.AddressSpace64Bit;
            }

            if (kip.Is64Bit)
            {
                flags |= ProcessCreationFlags.Is64Bit;
            }

            ProcessCreationInfo creationInfo = new ProcessCreationInfo(
                kip.Name,
                kip.Version,
                kip.ProgramId,
                codeAddress,
                codePagesCount,
                flags,
                0,
                0);

            MemoryRegion memoryRegion = kip.UsesSecureMemory
                ? MemoryRegion.Service
                : MemoryRegion.Application;

            KMemoryRegionManager region = context.MemoryManager.MemoryRegions[(int)memoryRegion];

            KernelResult result = region.AllocatePages((ulong)codePagesCount, false, out KPageList pageList);

            if (result != KernelResult.Success)
            {
                Logger.Error?.Print(LogClass.Loader, $"Process initialization returned error \"{result}\".");

                return(false);
            }

            KProcess process = new KProcess(context);

            var processContextFactory = new ArmProcessContextFactory(context.Device.Gpu);

            result = process.InitializeKip(
                creationInfo,
                kip.Capabilities,
                pageList,
                context.ResourceLimit,
                memoryRegion,
                processContextFactory);

            if (result != KernelResult.Success)
            {
                Logger.Error?.Print(LogClass.Loader, $"Process initialization returned error \"{result}\".");

                return(false);
            }

            result = LoadIntoMemory(process, kip, codeBaseAddress);

            if (result != KernelResult.Success)
            {
                Logger.Error?.Print(LogClass.Loader, $"Process initialization returned error \"{result}\".");

                return(false);
            }

            process.DefaultCpuCore = kip.IdealCoreId;

            result = process.Start(kip.Priority, (ulong)kip.StackSize);

            if (result != KernelResult.Success)
            {
                Logger.Error?.Print(LogClass.Loader, $"Process start returned error \"{result}\".");

                return(false);
            }

            context.Processes.TryAdd(process.Pid, process);

            return(true);
        }
コード例 #34
0
 /// <summary>
 /// Constructs a new instance.
 /// </summary>
 /// <param name="region">accessed memory region</param>
 /// <param name="addr">accessed address</param>
 public MemParams(MemoryRegion region, ulong addr)
 {
     Region     = region;
     MinAddress = addr;
     MaxAddress = addr;
 }
コード例 #35
0
ファイル: SsClientId.cs プロジェクト: andyvand/ProcessHacker
 public SsClientId(MemoryRegion data)
 {
     this.Original = data.ReadStruct<ClientId>();
 }
コード例 #36
0
ファイル: CodeGen.cs プロジェクト: limrzx/Dynamo
        private SymbolNode Allocate(
            int classIndex,  // In which class table this variable will be allocated to ?
            int classScope,  // Variable's class scope. For example, it is a variable in base class
            int funcIndex,   // In which function this variable is defined? 
            string ident, 
            ProtoCore.Type datatype, 
            bool isStatic = false,
            ProtoCore.CompilerDefinitions.AccessModifier access = ProtoCore.CompilerDefinitions.AccessModifier.Public,
            MemoryRegion region = MemoryRegion.MemStack,
            int line = -1,
            int col = -1,
            GraphNode graphNode = null
            )
        {
            bool allocateForBaseVar = classScope < classIndex;
            bool isProperty = classIndex != Constants.kInvalidIndex && funcIndex == Constants.kInvalidIndex;
            if (!allocateForBaseVar && !isProperty && core.ClassTable.IndexOf(ident) != ProtoCore.DSASM.Constants.kInvalidIndex)
                buildStatus.LogSemanticError(String.Format(Resources.ClassNameAsVariableError, ident), null, line, col, graphNode);

            ProtoCore.DSASM.SymbolNode symbolnode = new ProtoCore.DSASM.SymbolNode();
            symbolnode.name = ident;
            symbolnode.isTemp = ident.StartsWith("%");
            symbolnode.isSSATemp = CoreUtils.IsSSATemp(ident);
            symbolnode.functionIndex = funcIndex;
            symbolnode.absoluteFunctionIndex = funcIndex;
            symbolnode.datatype = datatype;
            symbolnode.staticType = TypeSystem.BuildPrimitiveTypeObject(PrimitiveType.Var, Constants.kArbitraryRank);
            symbolnode.isArgument = false;
            symbolnode.memregion = region;
            symbolnode.classScope = classScope;
            symbolnode.absoluteClassScope = classScope;
            symbolnode.runtimeTableIndex = codeBlock.symbolTable.RuntimeIndex;
            symbolnode.isStatic = isStatic;
            symbolnode.access = access;
            symbolnode.codeBlockId = codeBlock.codeBlockId;
            if (this.isEmittingImportNode)
                symbolnode.ExternLib = core.CurrentDSFileName;

            int symbolindex = ProtoCore.DSASM.Constants.kInvalidIndex;

            if (IsInLanguageBlockDefinedInFunction())
            {
                symbolnode.classScope = Constants.kGlobalScope;
                symbolnode.functionIndex = Constants.kGlobalScope;
            }

            if (ProtoCore.DSASM.Constants.kInvalidIndex != classIndex && !IsInLanguageBlockDefinedInFunction())
            {
                // NOTE: the following comment and code is OBSOLETE - member
                // variable is not supported now
                // 
                // Yu Ke: it is possible that class table contains same-named 
                // symbols if a class inherits some member variables from base 
                // class, so we need to check name + class index + function 
                // index.
                // 
                //if (core.classTable.list[classIndex].symbols.IndexOf(ident, classIndex, funcIndex) != (int)ProtoCore.DSASM.Constants.kInvalidIndex)
                //    return null;

                symbolindex = core.ClassTable.ClassNodes[classIndex].Symbols.IndexOf(ident);
                if (symbolindex != ProtoCore.DSASM.Constants.kInvalidIndex)
                {
                    ProtoCore.DSASM.SymbolNode node = core.ClassTable.ClassNodes[classIndex].Symbols.symbolList[symbolindex];
                    if (node.functionIndex == ProtoCore.DSASM.Constants.kGlobalScope &&
                        funcIndex == ProtoCore.DSASM.Constants.kGlobalScope)
                        return null;
                }

                symbolindex = core.ClassTable.ClassNodes[classIndex].Symbols.Append(symbolnode);
                if (symbolindex == ProtoCore.DSASM.Constants.kInvalidIndex)
                {
                    return null;
                }

                if (isStatic)
                {
                    Validity.Assert(funcIndex == ProtoCore.DSASM.Constants.kGlobalScope);
                    ProtoCore.DSASM.SymbolNode staticSymbolnode = new ProtoCore.DSASM.SymbolNode();
                    staticSymbolnode.name = ident;
                    staticSymbolnode.isTemp = ident.StartsWith("%");
                    staticSymbolnode.isSSATemp = CoreUtils.IsSSATemp(ident);
                    staticSymbolnode.functionIndex = funcIndex;
                    staticSymbolnode.datatype = datatype;
                    staticSymbolnode.staticType = TypeSystem.BuildPrimitiveTypeObject(PrimitiveType.Var, Constants.kArbitraryRank);
                    staticSymbolnode.isArgument = false;
                    staticSymbolnode.memregion = region;
                    staticSymbolnode.classScope = classScope;
                    staticSymbolnode.runtimeTableIndex = codeBlock.symbolTable.RuntimeIndex;
                    staticSymbolnode.isStatic = isStatic;
                    staticSymbolnode.access = access;
                    staticSymbolnode.codeBlockId = codeBlock.codeBlockId;
                    if (this.isEmittingImportNode)
                        staticSymbolnode.ExternLib = core.CurrentDSFileName;

                    // If inherits a static property from base class, that propery
                    // symbol should have been added to code block's symbol table,
                    // so we just update symbolTableIndex 
                    int staticSymbolindex = codeBlock.symbolTable.IndexOf(ident, classScope);
                    if (staticSymbolindex == ProtoCore.DSASM.Constants.kInvalidIndex)
                    {
                        AllocateVar(staticSymbolnode);
                        staticSymbolindex = codeBlock.symbolTable.Append(staticSymbolnode);
                        if (staticSymbolindex == ProtoCore.DSASM.Constants.kInvalidIndex)
                        {
                            return null;
                        }
                        staticSymbolnode.symbolTableIndex = staticSymbolindex;
                    }
                    symbolnode.symbolTableIndex = staticSymbolindex;
                }
                else
                {
                    AllocateVar(symbolnode);
                }
            }
            else
            {               
                AllocateVar(symbolnode);

                symbolindex = codeBlock.symbolTable.Append(symbolnode);
                if (symbolindex == ProtoCore.DSASM.Constants.kInvalidIndex)
                {
                    return null;
                }
                symbolnode.symbolTableIndex = symbolindex;
                
            }

            if (ProtoCore.DSASM.Constants.kInvalidIndex == symbolindex)
            {
                return null;
            }
            return symbolnode;
        }
コード例 #37
0
        public void ReadAuthData(MemoryRegion buffer)
        {
            Msv1_0_InteractiveLogon info = buffer.ReadStruct<Msv1_0_InteractiveLogon>();

            // Fix up relative addresses.
            if (info.LogonDomainName.Buffer.CompareTo(buffer.Size) < 0)
                info.LogonDomainName.Buffer = info.LogonDomainName.Buffer.Increment(buffer);
            if (info.UserName.Buffer.CompareTo(buffer.Size) < 0)
                info.UserName.Buffer = info.UserName.Buffer.Increment(buffer);
            if (info.Password.Buffer.CompareTo(buffer.Size) < 0)
                info.Password.Buffer = info.Password.Buffer.Increment(buffer);

            _domainName = info.LogonDomainName.Text;
            _userName = info.UserName.Text;
            _password = info.Password.Text;
        }
コード例 #38
0
 public WordMemory(MemoryRegion region, ushort data, ushort address) : base(region, data, address)
 {
 }
コード例 #39
0
ファイル: KernelInit.cs プロジェクト: zh010zh/Ryujinx
 private static KMemoryRegionManager GetMemoryRegion(MemoryRegion region)
 {
     return(new KMemoryRegionManager(region.Address, region.Size, region.EndAddress));
 }
コード例 #40
0
 /// <summary>
 ///     Returns a <see cref="System.String" /> that represents this instance.
 /// </summary>
 /// <param name="detailed">
 ///     Whether or not to include additional data such as the module,
 ///     AppDomain, or GC Heap associaed with it.
 /// </param>
 /// <returns>A <see cref="System.String" /> that represents this instance.</returns>
 /// <inheritdoc />
 public string ToString(bool detailed) => MemoryRegion.ToString(detailed);
コード例 #41
0
ファイル: Ace.cs プロジェクト: RoDaniel/featurehouse
        public static AceType GetType(IntPtr ace)
        {
            MemoryRegion memory = new MemoryRegion(ace);

            return memory.ReadStruct<AceHeader>().AceType;
        }
コード例 #42
0
ファイル: SsLogger.cs プロジェクト: RoDaniel/featurehouse
        private void BufferWorkerThreadStart()
        {
            int cursor = 0;

            _bufferWorkerThreadHandle = ThreadHandle.OpenCurrent(ThreadAccess.All);

            _bufferWorkerThreadReadyEvent.Set();

            while (!_terminating)
            {
                NtStatus status;
                KphSsBlockHeader blockHeader;

                status = _readSemaphore.Wait(true);

                if (status == NtStatus.Alerted)
                    return;

                if (_buffer.Size - cursor < Marshal.SizeOf(typeof(KphSsBlockHeader)))
                    cursor = 0;

                blockHeader = _buffer.ReadStruct<KphSsBlockHeader>(cursor, 0);

                if (blockHeader.Type == KphSsBlockType.Reset)
                {
                    cursor = 0;
                    blockHeader = _buffer.ReadStruct<KphSsBlockHeader>(cursor, 0);
                }

                if (blockHeader.Type == KphSsBlockType.Event)
                {
                    var eventBlock = _buffer.ReadStruct<KphSsEventBlock>(cursor, 0);
                    int[] arguments;
                    IntPtr[] stackTrace;

                    arguments = new int[eventBlock.NumberOfArguments];
                    stackTrace = new IntPtr[eventBlock.TraceCount];

                    for (int i = 0; i < arguments.Length; i++)
                        arguments[i] = _buffer.ReadInt32(cursor + eventBlock.ArgumentsOffset, i);
                    for (int i = 0; i < stackTrace.Length; i++)
                        stackTrace[i] = _buffer.ReadIntPtr(cursor + eventBlock.TraceOffset, i);

                    SsEvent ssEvent = new SsEvent();

                    ssEvent.Time = DateTime.FromFileTime(eventBlock.Time);
                    ssEvent.ThreadId = eventBlock.ClientId.ThreadId;
                    ssEvent.ProcessId = eventBlock.ClientId.ProcessId;
                    ssEvent.Arguments = arguments;
                    ssEvent.StackTrace = stackTrace;

                    ssEvent.ArgumentsCopyFailed =
                        (eventBlock.Flags & KphSsEventFlags.CopyArgumentsFailed) == KphSsEventFlags.CopyArgumentsFailed;
                    ssEvent.ArgumentsProbeFailed =
                        (eventBlock.Flags & KphSsEventFlags.ProbeArgumentsFailed) == KphSsEventFlags.ProbeArgumentsFailed;
                    ssEvent.CallNumber = eventBlock.Number;

                    if ((eventBlock.Flags & KphSsEventFlags.UserMode) == KphSsEventFlags.UserMode)
                        ssEvent.Mode = KProcessorMode.UserMode;
                    else
                        ssEvent.Mode = KProcessorMode.KernelMode;

                    if (this.EventBlockReceived != null)
                        this.EventBlockReceived(ssEvent);
                }
                else if (blockHeader.Type == KphSsBlockType.Argument)
                {
                    var argBlock = _buffer.ReadStruct<KphSsArgumentBlock>(cursor, 0);
                    MemoryRegion dataRegion;
                    SsData ssArg = null;

                    dataRegion = new MemoryRegion(_buffer, cursor + KphSsArgumentBlock.DataOffset);

                    switch (argBlock.Type)
                    {
                        case KphSsArgumentType.Int8:
                            {
                                SsSimple simpleArg = new SsSimple();

                                simpleArg.Argument = argBlock.Data.Int8;
                                simpleArg.Type = typeof(Byte);
                                ssArg = simpleArg;
                            }
                            break;
                        case KphSsArgumentType.Int16:
                            {
                                SsSimple simpleArg = new SsSimple();

                                simpleArg.Argument = argBlock.Data.Int16;
                                simpleArg.Type = typeof(Int16);
                                ssArg = simpleArg;
                            }
                            break;
                        case KphSsArgumentType.Int32:
                            {
                                SsSimple simpleArg = new SsSimple();

                                simpleArg.Argument = argBlock.Data.Int32;
                                simpleArg.Type = typeof(Int32);
                                ssArg = simpleArg;
                            }
                            break;
                        case KphSsArgumentType.Int64:
                            {
                                SsSimple simpleArg = new SsSimple();

                                simpleArg.Argument = argBlock.Data.Int64;
                                simpleArg.Type = typeof(Int64);
                                ssArg = simpleArg;
                            }
                            break;
                        case KphSsArgumentType.Handle:
                            {
                                ssArg = new SsHandle(dataRegion);
                            }
                            break;
                        case KphSsArgumentType.UnicodeString:
                            {
                                ssArg = new SsUnicodeString(dataRegion);
                            }
                            break;
                        case KphSsArgumentType.ObjectAttributes:
                            {
                                ssArg = new SsObjectAttributes(dataRegion);
                            }
                            break;
                        case KphSsArgumentType.ClientId:
                            {
                                ssArg = new SsClientId(dataRegion);
                            }
                            break;
                    }

                    ssArg.Index = argBlock.Index;

                    if (ssArg != null)
                    {
                        if (this.ArgumentBlockReceived != null)
                            this.ArgumentBlockReceived(ssArg);
                    }
                }

                cursor += blockHeader.Size;

                _writeSemaphore.Release();
            }
        }
コード例 #43
0
ファイル: Sid.cs プロジェクト: wumn290/processhacker-3
 private Sid(MemoryRegion sid, bool owned)
     : base(owned)
 {
     _memory = sid;
 }
コード例 #44
0
ファイル: PortMessage.cs プロジェクト: RoDaniel/featurehouse
 public PortMessage(MemoryRegion data, short dataLength)
     : this(null, data, dataLength)
 {
 }
コード例 #45
0
ファイル: SsClientId.cs プロジェクト: wumn290/processhacker-3
 public SsClientId(MemoryRegion data)
 {
     this.Original = data.ReadStruct <ClientId>();
 }
コード例 #46
0
 public void Write(MemoryRegion data)
 {
     this.Write(data, 0);
 }
コード例 #47
0
 public static int GetProcessByName(MemoryRegion buf, string processName)
 {
     NullTerminatedString.Set((byte *)buf.Start, processName);
     return((int)MessageManager.Send(SysCallTarget.GetProcessByName, buf.Start));
 }
コード例 #48
0
 public static void GetFramebufferInfo(MemoryRegion buf)
 {
     MessageManager.Send(SysCallTarget.GetFramebufferInfo, buf.Start);
 }
コード例 #49
0
ファイル: Credentials.cs プロジェクト: andyvand/ProcessHacker
        public static SecPkgInfo[] GetSSPackages()
        {
            int result;
            int count;
            IntPtr packages;

            result = Win32.EnumerateSecurityPackages(out count, out packages);

            if (result != 0)
                Win32.Throw(result);

            var alloc = new MemoryRegion(packages);

            try
            {
                SecPkgInfo[] array = new SecPkgInfo[count];

                for (int i = 0; i < count; i++)
                    array[i] = alloc.ReadStruct<SecPkgInfo>(i);

                return array;
            }
            finally
            {
                Win32.FreeContextBuffer(packages);
            }
        }
コード例 #50
0
        static Console()
        {
            var writeDebugMessageProcID = SysCalls.GetProcessIDForCommand(SysCallTarget.WriteDebugMessage);

            buf = SysCalls.RequestMessageBuffer(4096, writeDebugMessageProcID);
        }
コード例 #51
0
ファイル: SsLogger.cs プロジェクト: wumn290/processhacker-3
        public static string ReadWString(MemoryRegion data)
        {
            KphSsWString wString = data.ReadStruct <KphSsWString>();

            return(data.ReadUnicodeString(KphSsWString.BufferOffset, wString.Length / 2));
        }
コード例 #52
0
ファイル: SsLogger.cs プロジェクト: wumn290/processhacker-3
        public static SsData ReadArgumentBlock(MemoryRegion data)
        {
            var argBlock = data.ReadStruct <KphSsArgumentBlock>();

            MemoryRegion dataRegion;
            SsData       ssArg = null;

            dataRegion = new MemoryRegion(data, KphSsArgumentBlock.DataOffset);

            // Process the argument block based on its type.
            switch (argBlock.Type)
            {
            case KphSsArgumentType.Int8:
            {
                SsSimple simpleArg = new SsSimple();

                simpleArg.Argument = argBlock.Data.Int8;
                simpleArg.Type     = typeof(Byte);
                ssArg = simpleArg;
            }
            break;

            case KphSsArgumentType.Int16:
            {
                SsSimple simpleArg = new SsSimple();

                simpleArg.Argument = argBlock.Data.Int16;
                simpleArg.Type     = typeof(Int16);
                ssArg = simpleArg;
            }
            break;

            case KphSsArgumentType.Int32:
            {
                SsSimple simpleArg = new SsSimple();

                simpleArg.Argument = argBlock.Data.Int32;
                simpleArg.Type     = typeof(Int32);
                ssArg = simpleArg;
            }
            break;

            case KphSsArgumentType.Int64:
            {
                SsSimple simpleArg = new SsSimple();

                simpleArg.Argument = argBlock.Data.Int64;
                simpleArg.Type     = typeof(Int64);
                ssArg = simpleArg;
            }
            break;

            case KphSsArgumentType.Handle:
            {
                ssArg = new SsHandle(dataRegion);
            }
            break;

            case KphSsArgumentType.UnicodeString:
            {
                ssArg = new SsUnicodeString(dataRegion);
            }
            break;

            case KphSsArgumentType.ObjectAttributes:
            {
                ssArg = new SsObjectAttributes(dataRegion);
            }
            break;

            case KphSsArgumentType.ClientId:
            {
                ssArg = new SsClientId(dataRegion);
            }
            break;

            case KphSsArgumentType.Bytes:
            {
                ssArg = new SsBytes(dataRegion);
            }
            break;
            }

            ssArg.Index = argBlock.Index;

            return(ssArg);
        }
コード例 #53
0
ファイル: SsLogger.cs プロジェクト: RoDaniel/featurehouse
        internal static string ReadWString(MemoryRegion data)
        {
            KphSsWString wString = data.ReadStruct<KphSsWString>();

            return data.ReadUnicodeString(KphSsWString.BufferOffset, wString.Length / 2);
        }
コード例 #54
0
        private static void EmitStore(EmitterContext context, MemoryRegion region)
        {
            OpCodeMemory op = (OpCodeMemory)context.CurrOp;

            if (op.Size > IntegerSize.B128)
            {
                context.Config.PrintLog($"Invalid store size: {op.Size}.");
            }

            bool isSmallInt = op.Size < IntegerSize.B32;

            int count = 1;

            switch (op.Size)
            {
            case IntegerSize.B64:  count = 2; break;

            case IntegerSize.B128: count = 4; break;
            }

            Operand baseOffset = context.IAdd(GetSrcA(context), Const(op.Offset));

            Operand wordOffset = context.ShiftRightU32(baseOffset, Const(2));

            Operand bitOffset = GetBitOffset(context, baseOffset);

            for (int index = 0; index < count; index++)
            {
                Register rd = new Register(op.Rd.Index + index, RegisterType.Gpr);

                Operand value = Register(rd);

                Operand offset = context.IAdd(wordOffset, Const(index));

                if (isSmallInt)
                {
                    Operand word = null;

                    switch (region)
                    {
                    case MemoryRegion.Local:  word = context.LoadLocal(offset); break;

                    case MemoryRegion.Shared: word = context.LoadShared(offset); break;
                    }

                    value = InsertSmallInt(context, op.Size, bitOffset, word, value);
                }

                switch (region)
                {
                case MemoryRegion.Local:  context.StoreLocal(offset, value); break;

                case MemoryRegion.Shared: context.StoreShared(offset, value); break;
                }

                if (rd.IsRZ)
                {
                    break;
                }
            }
        }
コード例 #55
0
ファイル: PortMessage.cs プロジェクト: RoDaniel/featurehouse
 internal void SetHeader(MemoryRegion data)
 {
     _message = data.ReadStruct<PortMessageStruct>();
 }
コード例 #56
0
 /// <summary>
 /// Creates a security descriptor from memory.
 /// </summary>
 /// <param name="memory">The memory region to use. This object will be referenced.</param>
 public SecurityDescriptor(MemoryRegion memory)
 {
     _memory = memory;
     _memory.Reference();
     this.Read();
 }
コード例 #57
0
ファイル: PortMessage.cs プロジェクト: RoDaniel/featurehouse
 public PortMessage(PortMessage existingMessage, MemoryRegion data, short dataLength)
 {
     this.InitializeMessage(existingMessage, data, dataLength);
 }
コード例 #58
0
ファイル: KProcess.cs プロジェクト: zh010zh/Ryujinx
        public KernelResult InitializeKip(
            ProcessCreationInfo creationInfo,
            ReadOnlySpan <int> capabilities,
            KPageList pageList,
            KResourceLimit resourceLimit,
            MemoryRegion memRegion,
            IProcessContextFactory contextFactory,
            ThreadStart customThreadStart = null)
        {
            ResourceLimit      = resourceLimit;
            _memRegion         = memRegion;
            _contextFactory    = contextFactory ?? new ProcessContextFactory();
            _customThreadStart = customThreadStart;

            AddressSpaceType addrSpaceType = (AddressSpaceType)((int)(creationInfo.Flags & ProcessCreationFlags.AddressSpaceMask) >> (int)ProcessCreationFlags.AddressSpaceShift);

            InitializeMemoryManager(creationInfo.Flags);

            bool aslrEnabled = creationInfo.Flags.HasFlag(ProcessCreationFlags.EnableAslr);

            ulong codeAddress = creationInfo.CodeAddress;

            ulong codeSize = (ulong)creationInfo.CodePagesCount * KMemoryManager.PageSize;

            KMemoryBlockAllocator memoryBlockAllocator = creationInfo.Flags.HasFlag(ProcessCreationFlags.IsApplication)
                ? KernelContext.LargeMemoryBlockAllocator
                : KernelContext.SmallMemoryBlockAllocator;

            KernelResult result = MemoryManager.InitializeForProcess(
                addrSpaceType,
                aslrEnabled,
                !aslrEnabled,
                memRegion,
                codeAddress,
                codeSize,
                memoryBlockAllocator);

            if (result != KernelResult.Success)
            {
                return(result);
            }

            if (!MemoryManager.CanContain(codeAddress, codeSize, MemoryState.CodeStatic))
            {
                return(KernelResult.InvalidMemRange);
            }

            result = MemoryManager.MapPages(
                codeAddress,
                pageList,
                MemoryState.CodeStatic,
                KMemoryPermission.None);

            if (result != KernelResult.Success)
            {
                return(result);
            }

            result = Capabilities.InitializeForKernel(capabilities, MemoryManager);

            if (result != KernelResult.Success)
            {
                return(result);
            }

            Pid = KernelContext.NewKipId();

            if (Pid == 0 || (ulong)Pid >= KernelConstants.InitialProcessId)
            {
                throw new InvalidOperationException($"Invalid KIP Id {Pid}.");
            }

            return(ParseProcessInfo(creationInfo));
        }
コード例 #59
0
ファイル: NativeUtils.cs プロジェクト: andyvand/ProcessHacker
        public static string GetMessage(IntPtr dllHandle, int messageTableId, int messageLanguageId, int messageId)
        {
            NtStatus status;
            IntPtr messageEntry;
            string message;

            status = Win32.RtlFindMessage(
                dllHandle,
                messageTableId,
                messageLanguageId,
                messageId,
                out messageEntry
                );

            if (status.IsError())
                return null;

            var region = new MemoryRegion(messageEntry);
            var entry = region.ReadStruct<MessageResourceEntry>();

            // Read the message, depending on format.
            if ((entry.Flags & MessageResourceFlags.Unicode) == MessageResourceFlags.Unicode)
            {
                message = region.ReadUnicodeString(MessageResourceEntry.TextOffset);
            }
            else
            {
                message = region.ReadAnsiString(MessageResourceEntry.TextOffset);
            }

            return message;
        }
コード例 #60
0
ファイル: KProcess.cs プロジェクト: zh010zh/Ryujinx
        public KernelResult Initialize(
            ProcessCreationInfo creationInfo,
            ReadOnlySpan <int> capabilities,
            KResourceLimit resourceLimit,
            MemoryRegion memRegion,
            IProcessContextFactory contextFactory,
            ThreadStart customThreadStart = null)
        {
            ResourceLimit      = resourceLimit;
            _memRegion         = memRegion;
            _contextFactory    = contextFactory ?? new ProcessContextFactory();
            _customThreadStart = customThreadStart;

            ulong personalMmHeapSize = GetPersonalMmHeapSize((ulong)creationInfo.SystemResourcePagesCount, memRegion);

            ulong codePagesCount = (ulong)creationInfo.CodePagesCount;

            ulong neededSizeForProcess = personalMmHeapSize + codePagesCount * KMemoryManager.PageSize;

            if (neededSizeForProcess != 0 && resourceLimit != null)
            {
                if (!resourceLimit.Reserve(LimitableResource.Memory, neededSizeForProcess))
                {
                    return(KernelResult.ResLimitExceeded);
                }
            }

            void CleanUpForError()
            {
                if (neededSizeForProcess != 0 && resourceLimit != null)
                {
                    resourceLimit.Release(LimitableResource.Memory, neededSizeForProcess);
                }
            }

            PersonalMmHeapPagesCount = (ulong)creationInfo.SystemResourcePagesCount;

            KMemoryBlockAllocator memoryBlockAllocator;

            if (PersonalMmHeapPagesCount != 0)
            {
                memoryBlockAllocator = new KMemoryBlockAllocator(PersonalMmHeapPagesCount * KMemoryManager.PageSize);
            }
            else
            {
                memoryBlockAllocator = creationInfo.Flags.HasFlag(ProcessCreationFlags.IsApplication)
                    ? KernelContext.LargeMemoryBlockAllocator
                    : KernelContext.SmallMemoryBlockAllocator;
            }

            AddressSpaceType addrSpaceType = (AddressSpaceType)((int)(creationInfo.Flags & ProcessCreationFlags.AddressSpaceMask) >> (int)ProcessCreationFlags.AddressSpaceShift);

            InitializeMemoryManager(creationInfo.Flags);

            bool aslrEnabled = creationInfo.Flags.HasFlag(ProcessCreationFlags.EnableAslr);

            ulong codeAddress = creationInfo.CodeAddress;

            ulong codeSize = codePagesCount * KMemoryManager.PageSize;

            KernelResult result = MemoryManager.InitializeForProcess(
                addrSpaceType,
                aslrEnabled,
                !aslrEnabled,
                memRegion,
                codeAddress,
                codeSize,
                memoryBlockAllocator);

            if (result != KernelResult.Success)
            {
                CleanUpForError();

                return(result);
            }

            if (!MemoryManager.CanContain(codeAddress, codeSize, MemoryState.CodeStatic))
            {
                CleanUpForError();

                return(KernelResult.InvalidMemRange);
            }

            result = MemoryManager.MapNewProcessCode(
                codeAddress,
                codePagesCount,
                MemoryState.CodeStatic,
                KMemoryPermission.None);

            if (result != KernelResult.Success)
            {
                CleanUpForError();

                return(result);
            }

            result = Capabilities.InitializeForUser(capabilities, MemoryManager);

            if (result != KernelResult.Success)
            {
                CleanUpForError();

                return(result);
            }

            Pid = KernelContext.NewProcessId();

            if (Pid == -1 || (ulong)Pid < KernelConstants.InitialProcessId)
            {
                throw new InvalidOperationException($"Invalid Process Id {Pid}.");
            }

            result = ParseProcessInfo(creationInfo);

            if (result != KernelResult.Success)
            {
                CleanUpForError();
            }

            return(result);
        }