Question

Writing a JIT compiler in C++ on 64-bit Windows, generated code will sometimes need to call run-time functions that are written in C++. At the moment I'm allocating memory in which to place the generated code with VirtualAlloc(0, bytes, MEM_COMMIT, PAGE_EXECUTE_READWRITE); the last flag is important because allocated memory is not otherwise executable.

VirtualAlloc could presumably return memory anywhere in the 64-bit address space, which is fine for data (of which in general more than 4 gigabytes will be needed, so it does need 64-bit addressing), but the most efficient form of the x64 call instruction wants a 32-bit IP-relative offset, and since the amount of generated code will be less than 4 gigabytes, it would be preferable to locate it within a 32-bit displacement of the code compiled from C++.

Is there a way to arrange this?

Was it helpful?

Solution

You can specify a virtual address near which you want the allocation to happen as the first argument. To increase the chance of getting the allocation within the boundaries you want to could reserve the virtual memory region first and then request for committed memory as and when needed from the reserved space. Allocation by default happens bottom unless MEM_TOP_DOWN is specified or system is configured to perform memory layout top down to catch pointer truncation problems. Gist is that you can only increase the chance of having allocation within the boundary but should have code to handle when allocation is out of boundary.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top