public static bool RemapMemoryRegion(IntPtr processHandle, IntPtr baseAddress, int regionSize, Winnt.MemoryProtectionConstraints mapProtection) { IntPtr addr = Memoryapi.VirtualAlloc(IntPtr.Zero, regionSize, Winnt.MemoryAllocationType.MEM_COMMIT | Winnt.MemoryAllocationType.MEM_RESERVE, mapProtection); if (addr == IntPtr.Zero) { return(false); } IntPtr copyBuf = Memoryapi.VirtualAlloc(IntPtr.Zero, regionSize, Winnt.MemoryAllocationType.MEM_COMMIT | Winnt.MemoryAllocationType.MEM_RESERVE, mapProtection); if (!Memoryapi.ReadProcessMemory(processHandle, baseAddress, copyBuf, regionSize, out IntPtr bytes)) { return(false); } IntPtr sectionHandle = default; long sectionMaxSize = regionSize; Ntifs.Ntstatus status = Ntifs.NtCreateSection(ref sectionHandle, Winnt.AccessMask.SECTION_ALL_ACCESS, IntPtr.Zero, ref sectionMaxSize, Winnt.MemoryProtectionConstraints.PAGE_EXECUTE_READWRITE, Winnt.SectionProtectionConstraints.SEC_COMMIT, IntPtr.Zero); if (status != Ntifs.Ntstatus.STATUS_SUCCESS) { return(false); } status = Ntapi.NtUnmapViewOfSection(processHandle, baseAddress); if (status != Ntifs.Ntstatus.STATUS_SUCCESS) { return(false); } IntPtr viewBase = baseAddress; long sectionOffset = default; uint viewSize = 0; status = Ntapi.NtMapViewOfSection ( sectionHandle, processHandle, ref viewBase, UIntPtr.Zero, regionSize, ref sectionOffset, ref viewSize, 2, 0, Winnt.MemoryProtectionConstraints.PAGE_EXECUTE_READWRITE ); if (status != Ntifs.Ntstatus.STATUS_SUCCESS) { return(false); } if (!Memoryapi.WriteProcessMemory(processHandle, viewBase, copyBuf, (int)viewSize, out bytes)) { return(false); } if (!Memoryapi.VirtualFree(copyBuf, 0, Winnt.MemFree.MEM_RELEASE)) { return(false); } return(true); }
public static extern Ntifs.Ntstatus NtMapViewOfSection(IntPtr sectionHandle, IntPtr processHandle, ref IntPtr baseAddress, UIntPtr ZeroBits, int commitSize, ref long SectionOffset, ref uint ViewSize, uint InheritDisposition, Winnt.MemoryAllocationType allocationType, Winnt.MemoryProtectionConstraints win32Protect);
public static extern Ntstatus NtCreateSection(ref IntPtr sectionHandle, Winnt.AccessMask DesiredAccess, IntPtr objectAttributes, ref long MaximumSize, Winnt.MemoryProtectionConstraints SectionPageProtection, Winnt.SectionProtectionConstraints AllocationAttributes, IntPtr fileHandle);
public static extern IntPtr VirtualAlloc(IntPtr lpAddress, int dwSize, Winnt.MemoryAllocationType flAllocationType, Winnt.MemoryProtectionConstraints flProtect);