Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the well-known "Process is terminated due to StackOverflowException" screen appear?

A curious question:

How does the well-known "Process is terminated due to StackOverflowException" screen appear if the stack for the current process is full? Is it the runtime saving some registers for its graceful degradation or it's an internal trick that could possibly run another temp process displaying this screen?

P.S. Knowing a possible answer to this question could help someone to build his own "graceful degradation (assuming a very limited functionality of showing such a message)" mechanism from similar critical failure situations.

enter image description here

like image 609
Arman Avatar asked Jan 29 '13 18:01

Arman


People also ask

How do I fix exception of type system StackOverflowException was thrown?

StackOverflowException is thrown for execution stack overflow errors, typically in case of a very deep or unbounded recursion. So make sure your code doesn't have an infinite loop or infinite recursion.

Can I catch StackOverflowException C#?

Starting with the . NET Framework version 2.0, a StackOverflowException object cannot be caught by a try-catch block and the corresponding process is terminated by default. Consequently, users are advised to write their code to detect and prevent a stack overflow.

What is a StackOverflowException?

A StackOverflowException is thrown when the execution stack overflows because it contains too many nested method calls. For example, suppose you have an app as follows: C# Copy. using System; namespace temp { class Program { static void Main(string[] args) { Main(args); // Oops, this recursion won't stop. } } }


1 Answers

This message is displayed by the CLR. You can see the code in the SSCLI20 distribution, clr/src/vm/eepolicy.cpp source code file:

void DisplayStackOverflowException()
{
    PrintToStdErrA("\n");

    PrintToStdErrA("Process is terminated due to StackOverflowException.\n");
}

Which in turn is called by the EEPolicy::HandleFatalStackOverflow() method. The only reason you can see it at all is because you are running a console mode app so output to stderr ends up on the console window. And you'll only see it if Windows Error Reporting (WER) hasn't itself terminated the app.

There is no option to intercept this exception, the CLR cannot continue running managed code since there is too little stack space left to run any managed code safely. The line of code after the DisplayStackOverflowException() call is:

    TerminateProcess(GetCurrentProcess(), COR_E_STACKOVERFLOW);
like image 157
Hans Passant Avatar answered Sep 25 '22 20:09

Hans Passant