问题
On Windows OS for x86-32/x86-64 architecture thread stack virtual memory consist of "Reserved Part" "Commit Part", "Guard Page" and "Reserved Page".
Question:
Imagine that I have 1 page of commit memory, and 1MB of reserve memory for thread stack. I allocate on the stack some memory equal to K Pages without initialization. K is equal for example 10. It seems that in start of stack frame memory on the stack will be allocated by user space code like this:
sub esp, K*4096
Guard Page mechanism works when It is exist a read|write request to guard page.
But what will be I'll perform read/write to some memory which is beyond this guard page?
回答1:
You normally start out testing code that was compiled with runtime checking enabled. /RTC on MSVC++, enabled by default in the Debug configuration, it injects a call to _chkstk() in the function prologue. GCC/g++ has something very similar.
Which probes the pages of the allocation in the function prologue, reading every other 4096th byte. This ensures you'll always hit the guard page when you got it wrong, triggering this site's name and helping you to fix the bug.
Without that check in place, you could technically address a page that is not part of the stack at all. Although it is fairly likely to trigger the processor's #GP trap, it is not guaranteed since the page might have been mapped by another unrelated allocation. You'd have to be unlucky, it has been done. Fundamental UB, absolutely horrible to diagnose since you never suspect the stack, /RTC is quite valuable.
回答2:
Your program will crash when access address beyond guard page, but by default compiler will call the __chkstk() function each time the local allocation exceeds 4K.
Here is an article that explains how the stack guard page works in windows: kb100775
来源:https://stackoverflow.com/questions/25908736/how-windows-thread-stack-guard-page-mechanism-works-in-case-of-uninitialized-loc