Skip to content

Crash on net5. Maybe try fixing with VirtualProtect #35

@daemitus

Description

@daemitus

Set memory permissions before trying to modify non-write code. Might solve the crash in net5.
https://github.com/xivdev/Penumbra/blob/master/Penumbra/Hooks/SoundShit.cs#L26

Here's some code from my branch to do the dirty deed.

        public static MemoryProtection ChangePermission(IntPtr memoryAddress, int length, MemoryProtection newPermissions)
        {
            var result = VirtualProtect(memoryAddress, (UIntPtr)length, newPermissions, out var oldPermissions);

            if (!result)
                throw new Exception($"Unable to change permissions at 0x{memoryAddress.ToInt64():X} of length {length} and permission {newPermissions} (result={result})");

            var last = Marshal.GetLastWin32Error();
            if (last > 0)
                throw new Exception($"Unable to change permissions at 0x{memoryAddress.ToInt64():X} of length {length} and permission {newPermissions} (error={last})");

            return oldPermissions;
        }

        public static void ChangePermission(IntPtr memoryAddress, int length, MemoryProtection newPermissions, out MemoryProtection oldPermissions)
            => oldPermissions = ChangePermission(memoryAddress, length, newPermissions);
        [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
        public static extern bool VirtualProtect(
            IntPtr lpAddress,
            UIntPtr dwSize,
            MemoryProtection flNewProtection,
            out MemoryProtection lpflOldProtect);
        [Flags]
        public enum MemoryProtection
        {
            Execute = 0x10,
            ExecuteRead = 0x20,
            ExecuteReadWrite = 0x40,
            ExecuteWriteCopy = 0x80,
            NoAccess = 0x01,
            ReadOnly = 0x02,
            ReadWrite = 0x04,
            WriteCopy = 0x08,
            TargetsInvalid = 0x40000000,
            TargetsNoUpdate = TargetsInvalid,
            Guard = 0x100,
            NoCache = 0x200,
            WriteCombine = 0x400,
        }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions