且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么是_chkstk()函数的目的是什么?

更新时间:2022-05-13 22:19:18

页的Windows在你的线程堆栈外,因为它被使用。在堆栈的末尾,有映射为无法访问的内存一名警卫页 - 如果该程序访问它(因为它试图使用比目前更映射栈),有一个访问冲突。操作系统捕获故障,映射在堆的另一页在同一地址的老后卫页面,创建一个新的保护页刚刚超越旧人,并从导致违规的指示继续。

Windows pages in extra stack for your thread as it is used. At the end of the stack, there is one guard page mapped as inaccessible memory -- if the program accesses it (because it is trying to use more stack than is currently mapped), there's an access violation. The OS catches the fault, maps in another page of stack at the same address as the old guard page, creates a new guard page just beyond the old one, and resumes from the instruction that caused the violation.

如果一个函数具有局部变量超过一页,则它访问第一地址可能是多个页面超出堆的当前端。因此,它会想念保护页面并引发访问冲突,该操作系统不知道的是,因为需要更多的堆栈。如果需要的总栈特别巨大的,它可以甚至达到超出保护页,超出分配给堆栈的虚拟地址空间的端部,并进入存储器这实际上是在用别的东西。

If a function has more than one page of local variables, then the first address it accesses might be more than one page beyond the current end of the stack. Hence it would miss the guard page and trigger an access violation that the OS doesn't realise is because more stack is needed. If the total stack required is particularly huge, it could perhaps even reach beyond the guard page, beyond the end of the virtual address space assigned to stack, and into memory that's actually in use for something else.

因此​​, _chkstk 确保有本地变量足够的空间。你可以想像,它通过在页面大小间隔,在触摸局部变量的内存,增加订单,以确保它不会错过保护页面做这个(所谓的堆栈探测)。我不知道是否实际上做的是,虽然,可能需要一个更直接的途径,并指示操作系统在一定量的堆栈的映射。无论哪种方式,如果需要的总大于可用堆栈虚拟地址空间大,那么OS可以抱怨代替做某事未定义关于它

So, _chkstk ensures that there is enough space for the local variables. You can imagine that it does this by touching the memory for the local variables at page-sized intervals, in increasing order, to ensure that it doesn't miss the guard page (so-called "stack probes"). I don't know whether it actually does that, though, possibly it takes a more direct route and instructs the OS to map in a certain amount of stack. Either way, if the total required is greater than the virtual address space available for stack, then the OS can complain about it instead of doing something undefined.