Home > Enterprise >  Calling ZwAllocateVirtualMemoryEx with DllImport
Calling ZwAllocateVirtualMemoryEx with DllImport

Time:09-03

Im trying to call the low-level function ZwAllocateVirtualMemoryEx instead the typical VirtualAllocEx.

Thats an undocumented function from ntdll.dll, thats what i found about it:

NtAllocateVirtualMemoryEx definition

(NtAllocateVirtualMemoryEx and ZwAllocateVirtualMemoryEx are pretty much the same function)

However i dont know which parameters should i put in the DllImport export method. Thats what i tried (not working)

[DllImport(NTDLL)]
public static extern uint ZwAllocateVirtualMemoryEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect, int ExtendedParameters, ulong ExtendedParameterCount);

Im pretty sure im missing the correct parameters, but since there is almost no documentation i dont know how to fix the problem.

CodePudding user response:

ZwAllocateVirtualMemoryEx is an undocumented function, and in any case is only available to kernel-mode drivers. The equivalent for user-mode would be NtAllocateVirtualMemoryEx.

You also appear to have some incorrect parameter definitions, in particular uint dwSize and int ExtendedParameters are wrong.

Be that as it may, you should just use the official documented procedures for this. You can use VirtualAlloc2, which calls directly to NtAllocateVirtualMemoryEx:

[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern IntPtr VirtualAlloc2(
  IntPtr Process,
  IntPtr BaseAddress,
  UIntPtr Size,
  int AllocationType,
  int PageProtection,
  [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 6)]
  MEM_EXTENDED_PARAMETER[] ExtendedParameters = null,
  int ParameterCount
);

struct MEM_EXTENDED_PARAMETER
{
    long Type;
    IntPtr Pointer;
    UIntPtr Size;
    IntPtr Handle;
    int ULong;
}

Or you can use the simpler VirtualAllocEx

[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern IntPtr VirtualAllocEx(
  IntPtr hProcess,
  IntPtr lpAddress,
  UIntPtr dwSize,
  uint flAllocationType,
  uint flProtect
);
  • Related