question

Arsium-4135 avatar image
0 Votes"
Arsium-4135 asked Castorix31 answered

NtFreeVirtualMemory and VirtualFree (64bit)

Hello,

I'm implementing and testing myself native api but I got some problems with NtFreeVirtualMemory.

 NtFreeVirtualMemory(Process.GetCurrentProcess().Handle, ptr, 0, 0x00008000); //doesn't work from ntdll
    
 VirtualFree(ptr , (uint)0, 0x00008000); // from kernel32

I don't know why NtFreeVirtualMemory returns always access violation whereas VirtualFree works and frees the memory (I've inspected with ProcessHacker)

Any idea ?


dotnet-csharpwindows-api
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Castorix31 avatar image
0 Votes"
Castorix31 answered

This works for me =>

 IntPtr pBaseAddress = IntPtr.Zero;
 uint pSize = 4096;
 uint nStatus = NtAllocateVirtualMemory(Process.GetCurrentProcess().Handle, ref pBaseAddress, IntPtr.Zero, ref pSize, MEM_RESERVE, PAGE_READWRITE);
 if (nStatus == 0)
 {
     nStatus = NtFreeVirtualMemory(Process.GetCurrentProcess().Handle, ref pBaseAddress, ref pSize, MEM_RELEASE);
 }

Declarations :

 [DllImport("NtDll.dll", SetLastError = true)]
 private static extern uint NtAllocateVirtualMemory(IntPtr ProcessHandle, ref IntPtr BaseAddress, IntPtr ZeroBits, ref uint RegionSize, uint AllocationType, uint Protect);
    
 [DllImport("NtDll.dll", SetLastError = true)]
 private static extern uint NtFreeVirtualMemory(IntPtr ProcessHandle, ref IntPtr BaseAddress, ref uint RegionSize, uint FreeType);
    
 public const int MEM_COMMIT = 0x00001000;
 public const int MEM_RESERVE = 0x00002000;
 public const int MEM_DECOMMIT = 0x00004000;
 public const int MEM_RELEASE = 0x00008000;
    
 public const int PAGE_NOACCESS = 0x01;
 public const int PAGE_READONLY = 0x02;
 public const int PAGE_READWRITE = 0x04;
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.