我正在使用 x86 指令集编写程序。为什么当我使用存储在大小为 40kb 的堆栈中的本地数组时它会崩溃。
我使用带有 i5 处理器的 windows7 操作系统并在 Visual C++ Express Edition 2008 中编译
我认为您正在以保护页面的形式抓住重点。
为了在实际使用之前不浪费实际内存,Windows 最初保留完整的堆栈空间(默认为 1MB;可以通过编辑 PE 标头进行更改)但只提交两页,并将第二页设为保护页。保护页是一个内存页 (4KB),它在任何访问它时都会触发一个特殊异常 (STATUS_GUARD_PAGE_VIOLATION)。当内核检测到保护页异常时,它会提交被触及的页面并在其后添加另一个保护页。这样,如果您的函数将小变量推送到堆栈上,它会“自行”不断增长。
但是,如果您尝试分配大小超过 4K(4096 字节)的局部变量,则会出现问题。通常,堆栈分配是通过简单地从 ESP 中减去来完成的。如果您从中减去超过 4K 的内容,然后尝试写入堆栈,则您可能会跳过保护页并在其后访问保留的内存。这不会被内核捕获,但会传递给您的程序,通常会导致崩溃。
解决方案很简单 - 以 4K(=4096=0x1000 字节)的块进行堆栈分配,并在每个块之后触摸堆栈以触发保护页面。MSVC 编译器通过__chkstk()
在使用超过 4K 局部变量的函数的开头调用函数来自动执行此操作。这是来自 CRT 源的函数列表:
;***
;_chkstk - check stack upon procedure entry
;
;Purpose:
; Provide stack checking on procedure entry. Method is to simply probe
; each page of memory required for the stack in descending order. This
; causes the necessary pages of memory to be allocated via the guard
; page scheme, if possible. In the event of failure, the OS raises the
; _XCPT_UNABLE_TO_GROW_STACK exception.
;
; NOTE: Currently, the (EAX < _PAGESIZE_) code path falls through
; to the "lastpage" label of the (EAX >= _PAGESIZE_) code path. This
; is small; a minor speed optimization would be to special case
; this up top. This would avoid the painful save/restore of
; ecx and would shorten the code path by 4-6 instructions.
;
;Entry:
; EAX = size of local frame
;
;Exit:
; ESP = new stackframe, if successful
;
;Uses:
; EAX
;
;Exceptions:
; _XCPT_GUARD_PAGE_VIOLATION - May be raised on a page probe. NEVER TRAP
; THIS!!!! It is used by the OS to grow the
; stack on demand.
; _XCPT_UNABLE_TO_GROW_STACK - The stack cannot be grown. More precisely,
; the attempt by the OS memory manager to
; allocate another guard page in response
; to a _XCPT_GUARD_PAGE_VIOLATION has
; failed.
;
;*******************************************************************************
public _alloca_probe
_chkstk proc
_alloca_probe = _chkstk
push ecx
; Calculate new TOS.
lea ecx, [esp] + 8 - 4 ; TOS before entering function + size for ret value
sub ecx, eax ; new TOS
; Handle allocation size that results in wraparound.
; Wraparound will result in StackOverflow exception.
sbb eax, eax ; 0 if CF==0, ~0 if CF==1
not eax ; ~0 if TOS did not wrapped around, 0 otherwise
and ecx, eax ; set to 0 if wraparound
mov eax, esp ; current TOS
and eax, not ( _PAGESIZE_ - 1) ; Round down to current page boundary
cs10:
cmp ecx, eax ; Is new TOS
jb short cs20 ; in probed page?
mov eax, ecx ; yes.
pop ecx
xchg esp, eax ; update esp
mov eax, dword ptr [eax] ; get return address
mov dword ptr [esp], eax ; and put it at new TOS
ret
; Find next lower page and probe
cs20:
sub eax, _PAGESIZE_ ; decrease by PAGESIZE
test dword ptr [eax],eax ; probe page.
jmp short cs10
_chkstk endp
在您的情况下,您可能不需要这种复杂的逻辑,这样的事情会做:
xor eax, eax
mov ecx, 40 ; alloc 40 pages
l1:
sub esp, 1000h ; move esp one page
mov [esp], eax ; touch the guard page
loop l1 ; keep looping
sub esp, xxxh ; alloc the remaining variables
有关堆栈和保护页的更多详细信息,请参见此处。