2

I am trying to use VirtualAlloc2 with MemExtendedParameterAddressRequirements to allocate memory to specific regions of address space. This is my first time using this new API but I haven't been able to ever get it to succeed. It always returns nullptr and GetLastError is ERROR_INVALID_PARAMETER.

Here is a minimal example, which is almost identical to the MSDN example

#include <Windows.h>

void*
AllocateAlignedBelow2GB(size_t size, size_t alignment)
{
  MEM_ADDRESS_REQUIREMENTS addressReqs = { 0 };
  MEM_EXTENDED_PARAMETER param = { 0 };

  addressReqs.Alignment = alignment;
  addressReqs.HighestEndingAddress = (PVOID)(ULONG_PTR)0x7fffffff;

  param.Type = MemExtendedParameterAddressRequirements;
  param.Pointer = &addressReqs;

  auto pVirtualAlloc2 =
    (decltype(&::VirtualAlloc2))GetProcAddress(GetModuleHandle(L"kernelbase"),
                                               "VirtualAlloc2");

  return pVirtualAlloc2(
    nullptr, nullptr,
    size,
    MEM_RESERVE | MEM_COMMIT,
    PAGE_READWRITE,
    &param, 1);
}

int main()
{
  void* p = AllocateAlignedBelow2GB(1024, 1024);
  // p is now nullptr
  // GetLastError() is ERROR_INVALID_PARAMETER
  // Same behavior on 32-bit or 64-bit
  return 0;
}

Just trying to even get this call to succeed at all, I have tried a number of things:

  • Different allocation sizes
  • Different alignments (from 1 to the system allocation granularity)
  • Using a real process handle with PROCESS_ALL_ACCESS
  • Specifying different address bounds in addressReqs

Windows SDK version 10.0.17763.0, KERNELBASE.dll is version 10.0.17134.441

tenfour
  • 36,141
  • 15
  • 83
  • 142
  • 1
    very new api, need look in kernel for parameters check. however if we want restrict the higest address this possible do with old api yet from win200 - https://stackoverflow.com/a/50553691/6401656 – RbMm Jan 16 '19 at 23:38
  • the Alignment must be `2 ^ n` where `n >= 0x10`. so >= 0x10000. or Alignment can be 0. the 1024 (0x400) is invalid value for aligment, despite it 2^0xa - the 0xa too small for aligment – RbMm Jan 17 '19 at 09:45
  • 1
    @RbMm Looks there are other restrictions too: the addresses passed in must align to page boundaries (and max address aligns to page boundary - 1). All these things together, and the API is working now. If you want to add an answer I'll mark it accepted. Otherwise I'll do it later. Thanks for your help! – tenfour Jan 17 '19 at 12:17

0 Answers0