Beispiel #1
0
        public static PrivilegeHolder?EnablePrivilege(string privilegeName)
        {
            var luid = LuidFromPrivilege(privilegeName, out var luidSuccess);

            if (!luidSuccess)
            {
                return(null);
            }

            PrivilegeHolder?holder  = null;
            var             success = false;

            try
            {
                // The payload is entirely in the finally block
                // This is how we ensure that the code will not be
                // interrupted by catastrophic exceptions
            }
            finally
            {
                try
                {
                    // Retrieve TLS state
                    var tlsContents = _ttlsSlotData;
                    if (tlsContents == null)
                    {
                        _ttlsSlotData = tlsContents = TlsContents.Create();
                    }
                    else
                    {
                        tlsContents.IncrementReferenceCount();
                    }

                    if (tlsContents != null)
                    {
                        holder = new PrivilegeHolder(tlsContents, luid);
                        if (holder.ObtainPrivilege())
                        {
                            success = true;
                        }
                    }
                }
                finally
                {
                    if (holder?._needToRevert == false)
                    {
                        holder.Reset();
                    }

                    if (!success)
                    {
                        holder?.Dispose();
                        holder = null;
                    }
                }
            }

            return(holder);
        }
        public LargePageMemoryChunk(ulong length)
        {
            const MemoryAllocationType flags = MemoryAllocationType.MemReserve | MemoryAllocationType.MemCommit;
            const string lockMemory          = "SeLockMemoryPrivilege";

            _bytesReserved = MemoryAlignmentHelper.LargePageMultiple(length);
            try
            {
                using var privs = PrivilegeHolder.EnablePrivilege(lockMemory);
                if (privs != null)
                {
                    const MemoryAllocationType largeFlag = flags | MemoryAllocationType.MemLargePages;
                    _ptr = NativeMethods.VirtualAlloc(IntPtr.Zero, (IntPtr)_bytesReserved, largeFlag, MemoryProtectionConstants.PageReadwrite);
                    GC.KeepAlive(privs);
                }
            }
            catch (ObjectDisposedException)
            {
                // TODO: fix the underlying cause
            }

            _ptr = NativeMethods.VirtualAlloc(IntPtr.Zero, (IntPtr)_bytesReserved, flags, MemoryProtectionConstants.PageReadwrite);
        }