Example #1
0
        public void Set(UIntPtr start, long length, Protection prot)
        {
            if ((ulong)start < (ulong)Start)
            {
                throw new ArgumentOutOfRangeException("start");
            }

            if ((ulong)start + (ulong)length > (ulong)End)
            {
                throw new ArgumentOutOfRangeException("length");
            }

#if !MONO
            Kernel32.MemoryProtection p;
            switch (prot)
            {
            case Protection.None: p = Kernel32.MemoryProtection.NOACCESS; break;

            case Protection.R: p = Kernel32.MemoryProtection.READONLY; break;

            case Protection.RW: p = Kernel32.MemoryProtection.READWRITE; break;

            case Protection.RX: p = Kernel32.MemoryProtection.EXECUTE_READ; break;

            default: throw new ArgumentOutOfRangeException("prot");
            }
            Kernel32.MemoryProtection old;
            if (!Kernel32.VirtualProtect(start, (UIntPtr)length, p, out old))
            {
                throw new InvalidOperationException("VirtualProtect() returned FALSE!");
            }
#else
            LibC.ProtType p;
            switch (prot)
            {
            case Protection.None: p = 0; break;

            case Protection.R: p = LibC.ProtType.PROT_READ; break;

            case Protection.RW: p = LibC.ProtType.PROT_READ | LibC.ProtType.PROT_WRITE; break;

            case Protection.RX: p = LibC.ProtType.PROT_READ | LibC.ProtType.PROT_EXEC; break;

            default: throw new ArgumentOutOfRangeException("prot");
            }
            ulong end      = (ulong)start + (ulong)length;
            ulong newstart = (ulong)start & ~((ulong)Environment.SystemPageSize - 1);
            if (LibC.mprotect((UIntPtr)newstart, (UIntPtr)(end - newstart), p) != 0)
            {
                throw new InvalidOperationException("mprotect() returned -1!");
            }
#endif
        }