Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Stack Overflow Exception from crashing process

Assume I have an application, where user can provide script written in JavaScript to perform some task in it. This is done using Jint. However, badly written script can cause Stack Overflow Exception in JintEngine.Run() and therefore crashing whole application. I would rather like to inform user about the error in script.

I tried to run Jint on another application domain, that did not help, cause AFAIK default action on SOE is exiting process. Could be it changed any other way than by using CLR hosting?

I know I can run separate process and that's my fallback, nevertheless I would like not to do that.

like image 669
konrad.kruczynski Avatar asked Feb 09 '11 21:02

konrad.kruczynski


People also ask

How do I fix stack overflow exception?

Starting with the . NET Framework 2.0, you can't catch a StackOverflowException object with a try / catch block, and the corresponding process is terminated by default. Consequently, you should write your code to detect and prevent a stack overflow.

What causes stack overflow exception?

A StackOverflowException is thrown when the execution stack overflows because it contains too many nested method calls.

What causes stack overflow C#?

The most-common cause of stack overflow is excessively deep or infinite recursion, in which a function calls itself so many times that the space needed to store the variables and information associated with each call is more than can fit on the stack. An example of infinite recursion in C.

What is stack overflow exception Java?

StackOverflowError is an error which Java doesn't allow to catch, for instance, stack running out of space, as it's one of the most common runtime errors one can encounter.


1 Answers

As you suspected, it's just not possible to catch a StackOverflowException generated by the runtime unless you're hosting the CLR yourself [1]. As the Microsoft documentation suggests, your best bet is to try and detect the stack overflow before it happens.

In the case of using Jint, this means finding some way to hook into the execution engine and attach your own code to arbitrary method calls. Fortunately, a brief overview of their documentation reveals that they have a debugging mode that does just that! [2]

No doubt running in debugging mode means slowing down your script execution; it's up to you to decide if the benefit of detecting overflows is worth the penalty--and I definitely suggest measuring that penalty to ensure it's really going to be a problem. One possible mitigation would be to allow the user to choose when debugging mode is active.

-Mark

[1] http://msdn.microsoft.com/en-us/library/system.stackoverflowexception.aspx (see remarks)

[2] http://jint.codeplex.com/wikipage?title=Debugging&referringTitle=Documentation

like image 93
Mark B Avatar answered Sep 29 '22 01:09

Mark B