16th Chapter Windows Thread stacks

Source: Internet
Author: User

16.1 line stacks and working principle

(1) Introduction to Thread stacks

When the ① system creates a thread, it will subscribe the thread to a single address space (that is, each thread's private stack space) and allocate some physical memory. by default, a 1MB address space is booked and two pages of memory are allocated .

The default size of the ② adjustment line stacks can use the compile option or the #pragma directive, depending on the compiler, the VC can use the/fnewsize compilation option to set the default stack size, where newsize is in bytes, or you can use/stack: Reserve[,commit] connection options, the style of using the #pragma directive is as follows: #pragma comment (linker, "/stack:reserve,commit"), where the reserve and commit are in bytes. This information is written to the PE file header of the. exe or. dll file.

③ can also specify a value for the dwstacksize parameter to change the size of the stack when calling the CreateThread or _beginthreadex function, and if the parameter is 0 o'clock, the size specified by the PE file header.

(2) How the line stacks works

"Initial State"

① set the page size to 4KB, the stack size is 1MB. The base address of the centerline stacks is 0x80000000, and all the allocated pages have Page_readwrite protection properties

When ② is initialized, the stack-top pointer is esp as shown (takes 0x8100 0000), which is where the thread starts to use the stack. Looking down, the 2nd page is "guard page"

③ as threads invoke more and more functions, the call tree grows deeper and the thread requires more stack space.

"Stack is about to run out of state"

① when a thread tries to access the "protect page" memory, the system is notified that the system will first allocate the physical memory to the page under the "Protection page", then remove the Page_guard protection flag from the current "Protection page" and then assign the Page_guard protection attribute to the newly allocated storage page.

② This technology uses the system to increase the size of the stack memory when the thread needs it. If the thread's call tree deepens, the address space area of the stack will soon be filled.

"Status at the time of full stack"

① if the thread's call tree is very deep, the CPU's ESP pointer points to 0x0800 3004. At this point, when a thread calls another function, it must allocate more physical memory. But when allocating physical memory to the 0x0800 1000 page. Its approach differs from allocating physical memory to other parts of the region.

② first removes the PAGE_GUARD flag from the 0X0800 2000 page and assigns the 0X0800 1000 page. The difference, however, is that 0x0800 1000 is not assigned a protection attribute at this time. This means that the address space area of the stack has already been filled with all the physical memory that it can hold.

③ when the system assigns physical memory to the 0X0800 1000 page, an additional action is thrown-throwing an Exception_stack_overflow exception to notify the application, allowing the program to gracefully recover from this exceptional situation. (here is a mechanism to let the thread stack overflow when there are remedial measures)

④ However, if the thread continues to use the stack after throwing a stack overflow exception, it runs out of 0800 1000 pages and tries to access the memory of the Address 0x800 0000 page. However, this page is designed to be "non-paged", so an access violation exception is thrown. At this point the system will retract the control and eject the error, thus ending the entire process (not just the thread!). )。 To avoid this situation, the application can call the Setthreadstackguarante function to ensure that Windows has a specified amount of memory in the address space before terminating the process, causing the application to throw Exception_stack_ Overflow exceptions to allow the user to decide how to handle and recover at their own discretion.

(3) Recovery of thread stack Overflow

① when a thread accesses the last guard page, the system throws a Exception_stack_overflow exception. If the thread catches the exception and continues execution, the system will not throw an exception again in the same thread because there are no more protection pages behind it.

② If you want to continue to receive the Exception_stack_overflow exception in the same thread, the application must reset the protection page. Simply call the runtime's _RESETSTKOFLW function (defined in malloc.h)

"StackOverflow Program"--Demo stack Overflow and how to recover

#include <windows.h>#include<tchar.h>#include<strsafe.h>#include<locale.h>#include<malloc.h>//Call the _resetstkoflow function//RecursivevoidRecursiveintrecurse) {    intiarray[ -] = {};//Allocating stack space    if(recurse) {recursive (recurse); }}//Subscript out of bounds errorvoidArrayerr () {intIarray[] = {3,4 }; iarray[Ten] =1;//Subscript is out of bounds and cannot be restored}intStack_overflow_exception_filter (intException_code) {    if(Exception_code = =Exception_stack_overflow) {        //code in {} After execution of __except, i.e. execution of exception handling code, not returned to __try        returnException_execute_handler; //exception_continue_execution, returns the exception code in the __try block continues execution, that is, the exception has been handled properly}Else{        //continue to find that this __except block cannot handle this exception        returnException_continue_search; }}int_tmain () {_tsetlocale (Lc_all, _t ("CHS")); intRecurse =1, IRet =0;  for(inti =0; I <Ten; i++) {_tprintf (_t ("%d cycles \ n"), I +1); __try{//Analog Stack Overflow//Arrayerr ();//the subscript is out of bounds and cannot be detected, so no exception is thrown. recursive (recurse); }__except (Stack_overflow_exception_filter (GetExceptionCode ())) {_tprintf (_t ("Recovery Stack Overflow .... \ n")); IRet=_resetstkoflw (); }        if(!IRet) {_tprintf (_t ("recovery failed \ n"));  Break; } Else{_tprintf (_t ("recovery successful \ n")); }} _tsystem (_t ("PAUSE")); return 0;}

16th Chapter Windows Thread stacks

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.