从_chkstk说起,谈谈用户栈的管理

上周在XP系统上测试一个驱动的时候,发现驱动加载不上,“net start”命令只是给出一个无意义的错误代码,驱动的DriverEntry()入口程序还没有得到机会运行。

初步怀疑是引入函数的问题,用WDK工具Depends.exe查看了一下驱动文件,果然是由于_chkstk函数无法解析所导致。

_chkstk是个微软C编译器的辅助库函数,MSDN上对其介绍十分简略:

_chkstk Routine is a helper routine for the C compiler. For x86 compilers, _chkstk Routine is called when the local variables exceed 4096 bytes; for x64 compilers it is 8K.

当编译器察觉到局部变量太大超过限值时(X86系统限值是4K,X64t系统上是8K), 编译器会自动插入_chkstk这个函数以保证栈空间所使用页面在内存中。

问题是发现了,但要查出来究竟在哪个函数中还是要费些心思的。从用户层移植过来不少代码,基本锁定问题出在其中,但如果一个函数一个函数寻找实在是个不讨巧的笨办法,也不符合程序人的一贯风格,便用IDA反编译驱动sys文件,于汇编代码中搜索_chkstk字串,直接锁定出了问题函数。此函数所使用的一个结构体中定义了超大数组,对栈的超常使用在内核中是相当危险的。

解决办法很简单,直接将此结构的定义放在一个从内存分配的结构中即可。问题虽已解决,但对于DDK中有关_chkstk的描述,及其相关的疑问一直让我觉得困扰,比如,为什么X86上是4K,而AMD64架构上可以是8K。

这两天终于有了时间,可以彻底地了结这个疑问了。

要想解决这个问题,还要先从用户栈的分配开始。以ReactOS代码为例,当线程创建时,CreateThread()会调用BasepCreateStack()来创建用户栈,具体可以参见ReactOS源码:
~/ReactOS/lib/kernel32/misc/utils.c。

BasepCreateStack()函数主要做三件事:

  1. 1,分配栈空间所需的虚拟内存,大小为Stack Reserve Size
  2. 2,根据Stack Commit Size锁定内存页面,如果Stack Commit Size小于Stack Reserve Size的话,需要增加一个Page,这个额外申请的Page用作Guard Page之用。
  3. 3,将栈底部的Page设定为Guard Page。

当用户栈被用尽时,会访问到栈底部的Guard Page。而对Guard Page的任何访问都会导致Page Fault的发生。Page Fault处理函数MmAccessFault()可以分析出此次Page Fault是由Guard Page导致,便会默认由用户栈处理程序MiCheckForUserStackOverflow()来处理。如果用户栈并没有溢出的话,即Stack Commit Size小于Stack Reserve Size的情况,MiCheckForUserStackOverflow()会自动向下扩展栈空间,扩展大小为GUARD_PAGE_SIZE。 GUARD_PAGE_SIZE针对不同的CPU架构有不同的定义:
X64:  #define GUARD_PAGE_SIZE   (PAGE_SIZE * 2)
X86:  #define GUARD_PAGE_SIZE   PAGE_SIZE

这里便解释了为什么X86系统上的限制是4K(即PAGE_SIZE),而X64上却为8K的原因。

说到此处,该是解答_chkstk()倒底是干什么的时候了。Visual Studio中有_chkstk的源码,以x86为例:

输入参数eax是所需堆栈大小(字节)
labelP  _chkstk,       PUBLIC

        push    ecx                          ; save ecx
        cmp     eax,_PAGESIZE_     ; more than one page requested?
        lea     ecx,[esp] + 8           ;   compute new stack pointer in ecx
                                                   ;   correct for return address and
                                                   ;   saved ecx
        jb      short lastpage           ; no

;------------

probepages:
        sub     ecx,_PAGESIZE_          ; yes, move down a page
        sub     eax,_PAGESIZE_          ; adjust request and...

        test    dword ptr [ecx],eax     ; ...probe it  (如果是guard page,刚会导致page fault,最终用户栈
                                                        ;  将向下扩展一个页面)

        cmp     eax,_PAGESIZE_          ; more than one page requested?
        jae     short probepages          ; no

lastpage:
        sub     ecx,eax                  ; move stack down by eax
        mov     eax,esp                 ; save current tos and do a...

        test    dword ptr [ecx],eax     ; ...probe in case a page was crossed
                                                        ;  调用函数将要访问的堆栈底部 ,如果此页面为guard page,同
                                                        ;  样会导致用户栈的向下延伸

        mov     esp,ecx                        ; set the new stack pointer
                                                        ; 向下更改栈指针,其上直到原ESP的栈空间为调用函数局部变量

        mov     ecx,dword ptr [eax]     ; recover ecx
        mov     eax,dword ptr [eax + 4] ; recover return address
                                                            ; 将返回地址(调用函数中)放入eax

        push    eax                     ; prepare return address
                                              ; 将返回地址(调用函数中)放入当前栈中,准备返回

                                              ; ...probe in case a page was crossed
        ret

        end

_chkstk()的主要作用是保证栈向下连续的生长。如果没有_chkstk(),当局部变量太多并超过guard page下沿时,若再有压栈操作,将会导致Access violation错误。因为此时堆栈内存页面无效,压栈直接将导致page fault的发生,而page fault处理程序因不能识别此fault的发生原因从而不能做出正确判断和有效处理。

相对用户层,内核程序的处理则相当简单,就如Win7内核中_chkstk实际上就是个空函数。其原因就是内核线程的栈空间是固定的。其取值针对X86及X64架构亦有所不同:
X64: #define KERNEL_STACK_SIZE 0x6000   /* 6个内存页面 */
X86: #define KERNEL_STACK_SIZE 12288    /* 3个内存页面 */

内核中栈资源非常紧缺,并驱动程序的编写有较高的要求,特别是有递归的情况下,一定要注意嵌套的层数,否则很容易收到M$发来的蓝屏。

Windows内核中其实还有一种大堆栈机制,以确保一些对堆栈较高消耗的特殊情况能够得到满足,但这部分完全是黑箱,对用户不可见,不是常见情况,此处不再多述。

参考资料:
1, http://support.microsoft.com/kb/100775/en
2, http://msdn.microsoft.com/en-us/library/ms648426(v=vs.85).aspx
3, http://www.reactos.org  ReactOS源码

200 条评论

  1. Get more leads for your dynox.cn website by harnessing AI on Instagram. If you’re looking to boost greater traffic, generate leads, and expand your brand’s reach, you can get more information and start a free trial here: https://ow.ly/SCza50WXAtB

    This is an AI-powered Instagram growth service that:
    -Increases followers with focused, premium audiences.
    -Improves engagement through advanced AI algorithms.
    -Focuses on users based on hashtags and accounts they follow.
    -Saves time by automating tedious Instagram tasks.

    Our service focuses on authentic, organic growth—no bots, no fake followers. It’s perfect for brands like yours that want to convert Instagram into a lead generation engine. Even better, our service is provided on a month-by-month subscription basis so you can cancel any time you like. No contracts and a 7-day free trial.

  2. At first, I wasn’t trustworthy if CBD gummies would indeed do anything, but after a match up of weeks of taking them like 10mg thc gummy for siesta, I can say they’ve helped a lot. Normally my viewpoint races at darkness and I can’t settle down, but about 45 minutes after enchanting individual, I start to caress more tranquil and drifting postponed is much easier. The precise part is I don’t fondle heavy or stupefied in the morning. They are a jot on the priceless side, but for nights when I really necessity becoming inactivity, they’ve been merit it.

  3. Tried these sleep cbd gummies in front bed a few times just now and they in fact work. I’m usually tossing and turning, but with these I result up falling asleep way quicker. No weird hangover compassionate in the morning either. Kinda excessive, but honestly value it when I straight hunger a worthy tenebriousness’s sleep.

  4. At original, I wasn’t undeviating if CBD gummies would actually do anything, but after a link of weeks of taking them like https://www.cornbreadhemp.com/collections/thc-gummies for the sake of sleep, I can say they’ve helped a lot. Normally my mind races at night and I can’t settle down, but with reference to 45 minutes after intriguing only, I start to touch more relaxed and drifting off is much easier. The unerring relinquish is I don’t fondle ungraceful or groggy in the morning. They are a jot on the extravagant side, but an eye to nights when I undeniably necessity becoming rest, they’ve been significance it.

  5. I’ve been using strongest delta 9 drinks ordinary for on the other side of a month at the moment, and I’m justifiably impressed before the absolute effects. They’ve helped me determine calmer, more balanced, and less restless from the beginning to the end of the day. My sleep is deeper, I wake up refreshed, and sober my pinpoint has improved. The trait is famous, and I cognizant the sensible ingredients. I’ll categorically keep buying and recommending them to the whole world I recall!

  6. I’ve been using https://www.nothingbuthemp.net/products/thc-indica-tincture ordinary seeing that on the other side of a month at the moment, and I’m justifiably impressed before the sure effects. They’ve helped me perceive calmer, more balanced, and less solicitous everywhere the day. My sleep is deeper, I wake up refreshed, and uniform my core has improved. The quality is famous, and I worth the accepted ingredients. I’ll categorically keep buying and recommending them to everyone I be aware!

  7. Aiming to supercharge your website’s visibility? Our AI-powered tool channels precise visitors using keywords or geographic filters from continents to towns.
    Looking to higher revenue, dynamic visitors, or stronger online impact?
    We adapt it to suit your strategy. Enjoy a 7-day free trial period with no contract. Start here:

    https://ow.ly/cmPa50WXBjl

  8. Battling low website traffic? Our intelligent AI system brings targeted visitors via keywords and location-based filters from nations to city blocks.
    Desiring increased profits, lively engagement, or greater web reach?
    We shape it to align with your vision. Enjoy a 7-day free trial period with no contract. Dive in here:

    https://cutt.ly/Er3e4rVu

  9. I’ve been using sleep gummies cbd regular for all about a month for the time being, and I’m indeed impressed at near the uncontested effects. They’ve helped me perceive calmer, more balanced, and less anxious from the beginning to the end of the day. My saw wood is deeper, I wake up refreshed, and even my nave has improved. The quality is distinguished, and I worth the common ingredients. I’ll categorically keep buying and recommending them to person I identify!

  10. I’ve been using thc candy bars constantly seeing that over a month nowadays, and I’m indeed impressed before the uncontested effects. They’ve helped me judge calmer, more balanced, and less restless from the beginning to the end of the day. My sleep is deeper, I wake up refreshed, and sober my pinpoint has improved. The attribute is outstanding, and I appreciate the natural ingredients. I’ll positively preserve buying and recommending them to person I be aware!

  11. Capture additional leads for your dynox.cn website by leveraging AI on Instagram. If you’re looking to boost enhanced traffic, generate leads, and amplify your brand’s reach, you can access more information and start a no-cost trial here: https://cutt.ly/kr9BMAzc

    This is an AI-powered Instagram growth service that:
    -Increases followers with focused, top-tier audiences.
    -Boosts engagement through intelligent AI algorithms.
    -Focuses on users based on hashtags and accounts they follow.
    -Reduces effort by automating repetitive Instagram tasks.

    Our service emphasizes on real, organic growth—zero bots, zero fake followers. It’s excellent for brands like yours that want to turn Instagram into a lead generation powerhouse. Even better, our service is provided on a monthly subscription basis so you can opt out at any point you like. No contracts and a 7 day no-cost trial.

  12. I’ve been using https://www.nothingbuthemp.net/collections/mushroom-gummies constantly on account of all about a month nowadays, and I’m indeed impressed before the absolute effects. They’ve helped me determine calmer, more balanced, and less anxious from the beginning to the end of the day. My saw wood is deeper, I wake up refreshed, and straight my pinpoint has improved. The value is famous, and I worth the common ingredients. I’ll positively heed buying and recommending them to person I identify!

  13. Needing to fuel your website’s growth? Our AI technology pulls perfect visitors via keywords with geographic precision from continents to city blocks.
    Looking for more profits, lively website traffic, or a stronger digital footprint?
    We adjust it to align with your goals. Enjoy a 7-day free trial period with no contract. Dive in here:

    https://cutt.ly/Vr3e897r

  14. Our AI-powered traffic solution delivers engaged, keyword-specific visitors from your target locations, saving you money compared to expensive paid ad platforms. Contact us today.

    https://cutt.ly/qr7yIpER

  15. Your dynox.cn website could be missing out on thousands of visitors. Use our AI powered system to drive targeted traffic to your website and increase leads and sales for free: https://cutt.ly/6r615Ail

  16. Which keywords and locations do you need traffic from for dynox.cn ? Check our traffic network to see what kind of volume we have for your keywords and locations: https://cutt.ly/5tqiYkKs
    Then start a 7 day free trial of our targeted traffic service that is powered by AI, no contracts, cancel at any time.

  17. Which keywords and locations do you need traffic from for dynox.cn ? Check our traffic network to see what kind of volume we have for your keywords and locations: https://cutt.ly/MtqiYc0S
    Then start a 7 day free trial of our targeted traffic service that is powered by AI, no contracts, cancel at any time.

  18. Which keywords and locations do you need traffic from for dynox.cn ? Check our traffic network to see what kind of volume we have for your keywords and locations: https://cutt.ly/atqiYvJ0
    Then start a 7 day free trial of our targeted traffic service that is powered by AI, no contracts, cancel at any time.

  19. Get additional leads for your dynox.cn website by harnessing AI on Instagram. If you’re looking to increase enhanced traffic, create leads, and expand your brand’s reach, you can find more information and start a no-cost trial here: https://cutt.ly/ytegGn4x

    This is an AI-powered Instagram growth service that:
    -Increases followers with focused, high-quality audiences.
    -Improves engagement through smart AI algorithms.
    -Aims at users based on hashtags and accounts they follow.
    -Saves work by automating tedious Instagram tasks.

    Our service prioritizes on real, organic growth—without bots, zero fake followers. It’s excellent for brands like yours that want to convert Instagram into a lead generation machine. Even better, our service is provided on a monthly subscription basis so you can opt out any time you like. No contracts and a 7 day no-cost trial.

  20. Your dynox.cn website could be missing out on thousands of visitors. Use our AI powered system to drive targeted traffic to your website and increase leads and sales for free: https://cutt.ly/yty5slKo

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注