Search code examples
cwindowsmemorystackallocation

Equivalent of mmap with MAP_GROWSDOWN in Windows


In Linux, I could use mmap with the MAP_GROWSDOWN flag to allocate memory for an automatically-growing stack. To quote the manpage,

   MAP_GROWSDOWN
          This flag is used for stacks.  It indicates to the kernel
          virtual memory system that the mapping should extend
          downward in memory.  The return address is one page lower
          than the memory area that is actually created in the
          process's virtual address space.  Touching an address in
          the "guard" page below the mapping will cause the mapping
          to grow by a page.  This growth can be repeated until the
          mapping grows to within a page of the high end of the next
          lower mapping, at which point touching the "guard" page
          will result in a SIGSEGV signal.

Is there some equivalent technique in Windows? Even something ugly like asking the OS notify you about page faults so you can allocate a new page underneath (and make it look contiguous by asking the OS to fiddle around with page tables)?


Solution

  • With VirtualAlloc you can reserve a block of memory, commit the top two pages, and set the lower of the two pages with PAGE_GUARD. When the stack grows down and accesses the guard page, a structured exception is thrown that you can handle to commit the next page down and set PAGE_GUARD on it.

    The above is similar to how the stack is handled in Windows processes. Below is a description of the stack using Sysinternals VMMAP.EXE. You can see it is a 256KB stack with 32K committed, 12K of guard pages, and 212K of reserved stack remaining.

    description of pages in a windows process thread stack