从_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. Capture increased leads for your dynox.cn website by using AI on Instagram. If you’re looking to increase enhanced traffic, generate leads, and grow your brand’s reach, you can get more information and start a complimentary trial here: https://ow.ly/aSLa50VycS2

    This is an AI-powered Instagram growth service that:
    -Increases followers with targeted, high-quality audiences.
    -Improves engagement through intelligent AI algorithms.
    -Focuses on users based on hashtags and accounts they follow.
    -Saves effort by automating time-consuming Instagram tasks.

    Our service emphasizes on real, organic growth—no bots, without fake followers. It’s excellent for brands like yours that want to turn Instagram into a lead generation machine. Best of all, our service is provided on a flexible subscription basis so you can cancel at any point you like. No contracts and a 7 day complimentary trial.

  2. Eager to maximize your website crowd? Our smart AI system delivers perfect website traffic using keywords plus location data from countries to local spots.
    Looking to increased revenue, boosted visitors, or greater digital impact?
    We customize it to match your needs. Enjoy a 7-day free trial period with no contract. Dive in here:

    https://cutt.ly/MrRRGFMv

  3. Ready to enhance your website traffic flow? Our AI-enhanced attracts ideal website traffic using keywords plus geographic filters from global zones to towns.
    Looking for more revenue, active pages, or a larger online presence?
    We shape it to your goals. Enjoy a 7-day free trial period with no contract. Begin here:

    https://cutt.ly/grT4RvEM

  4. Wanting to fuel your website growth? Our smart platform attracts tailored website traffic through keywords and location targeting from continents to city blocks.
    Desiring more revenue, engaged website traffic, or wider web presence?
    We shape it to your goals. Enjoy a 7-day free trial period with no contract. Begin here:

    https://cutt.ly/6rU1a62e

  5. Struggling to draw the right website traffic? Our AI-enhanced tool directs targeted visitors via keywords and regional focus from countries to neighborhoods.
    Looking to gain increased income, engaged website traffic, or greater online impact?
    We craft it to fit your strategy. Enjoy a 7-day free trial period with no contract. Start here:

    https://cutt.ly/zrIOAryl

  6. Facing a sluggish website traffic flow? Our AI platform channels tailored visitors via keywords and location data from continents to local spots.
    Needing higher profits, vibrant engagement, or wider online presence?
    We customize it to your needs. Enjoy a 7-day free trial period with no contract. Jump in here:

    https://ow.ly/C25S50Wrj37

  7. Our AI-driven solution delivers keyword and location-specific visitors to your site, offering a budget-friendly alternative to expensive paid advertising. Ready to boost your reach?

    https://ow.ly/RmpM50WrgMV

  8. Wanting to boost your website success? Our smart AI technology brings targeted website traffic using keywords plus geographic targeting from countries to neighborhoods.
    Looking for increased earnings, livelier website traffic, or a stronger digital presence?
    We fine-tune it to fit your objectives. Enjoy a 7-day free trial period with no contract. Join here:

    https://ow.ly/qs8k50WvEpi

  9. Capture additional leads for your dynox.cn website by leveraging AI on Instagram. If you’re looking to increase enhanced traffic, create leads, and amplify your brand’s reach, you can get more information and start a no-cost trial here: https://ow.ly/gHVO50WvEAg

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

    Our service emphasizes on real, organic growth—zero bots, without fake followers. It’s perfect for brands like yours that want to turn Instagram into a lead generation powerhouse. Better yet, our service is provided on a month-by-month subscription basis so you can stop whenever you like. No contracts and a 7 day no-cost trial.

  10. Ready to amplify your website’s growth? Our smart technology system delivers targeted visitors via keywords with geographic accuracy from continents to local streets.
    Seeking increased profits, active website traffic, or a wider digital impact?
    We shape it to align with your goals. Enjoy a 7-day free trial period with no contract. Dive in here:

    https://ow.ly/FCEL50Wvgvg

  11. Needing to boost your website reach? Our AI technology pulls targeted website traffic using keywords or place-based tags from continents to city blocks.
    Desiring more revenue, active pages, or a larger online presence?
    We tailor it to your vision. Enjoy a 7-day free trial period with no contract. Begin here:

    https://ow.ly/j3Zq50WvEoO

  12. Needing to boost your website’s reach? Our AI-enhanced pulls perfect visitors using keywords and place-based precision from continents to local streets.
    Wanting more sales, lively pages, or greater web impact?
    We shape it to fit your vision. Enjoy a 7-day free trial period with no contract. Join now:

    https://ow.ly/Ofsk50WAbbh

  13. Needing to lift your website traffic? Our AI platform channels targeted website traffic using keywords or geographic tags from nations to local spots.
    Looking for higher revenue, vibrant activity, or expanded digital reach?
    We adjust it to your needs. Enjoy a 7-day free trial period with no contract. Start now:

    https://ow.ly/XlI950WH1tP

  14. Eager to spark your website’s growth? Our smart technology platform draws focused visitors using keywords or geographic tags from countries to towns.
    Wanting increased profits, vibrant website traffic, or expanded web reach?
    We refine it to fit your objectives. Enjoy a 7-day free trial period with no contract. Begin now:

    https://ow.ly/9i2R50WJA7c

  15. Needing to propel your website traffic? Our AI-enhanced attracts ideal website traffic using keywords or geographic tags from countries to neighborhoods.
    Looking for more sales, vibrant activity, or expanded digital reach?
    We tailor it to your vision. Enjoy a 7-day free trial period with no contract. Start now:

    https://ow.ly/7nfH50WH1u0

  16. Struggling with grow your website traffic? Our AI technology attracts custom visitors through keywords and place-based precision from countries to local spots.
    Looking for higher profits, engaged users, or a broader online reach?
    We tailor it to align with your vision. Enjoy a 7-day free trial period with no contract. Join here:

    https://ow.ly/hcUo50WOcPZ

  17. Ready to supercharge your website’s visibility? Our intelligent AI tool channels targeted visitors using keywords with location accuracy from nations to local spots.
    Looking to more earnings, vibrant engagement, or wider web reach?
    We refine it to suit your strategy. Enjoy a 7-day free trial period with no contract. Start here:

    https://ow.ly/iH5Z50WSKYR

发表回复

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