microsoft / ClearScript

A library for adding scripting to .NET applications. Supports V8 (Windows, Linux, macOS) and JScript/VBScript (Windows).
https://microsoft.github.io/ClearScript/
MIT License
1.77k stars 148 forks source link

Unable to initalize script engine due to pending script exception #560

Closed ebrandin closed 7 months ago

ebrandin commented 9 months ago

Hi

On a few occasions ClearScript has entered what seeems to be a strange erronous state after a failing script. At this point, when trying to create a new script engine, we get this exception whenever we try to execute another script:

Microsoft.ClearScript.ScriptEngineException : The V8 runtime cannot initialize the script engine because a script exception is pending
at Microsoft.ClearScript.V8.SplitProxy.V8SplitProxyNative.Invoke[T](Func`2 func)
   at Microsoft.ClearScript.V8.SplitProxy.V8ContextProxyImpl.<>c__DisplayClass3_0.<.ctor>b__0()
   at Microsoft.ClearScript.V8.SplitProxy.V8EntityHolder..ctor(String name, Func`1 acquireHandle)
   at Microsoft.ClearScript.V8.SplitProxy.V8ContextProxyImpl..ctor(V8IsolateProxy isolateProxy, String name, V8ScriptEngineFlags flags, Int32 debugPort)
   at Microsoft.ClearScript.V8.V8ScriptEngine..ctor(V8Runtime runtime, String name, V8RuntimeConstraints constraints, V8ScriptEngineFlags flags, Int32 debugPort)
   at Microsoft.ClearScript.V8.V8Runtime.CreateScriptEngine(String engineName, V8ScriptEngineFlags flags, Int32 debugPort)

So far we have only seen this issue while debugging or while running unit tests, but we would like to understand the root cause of this so it can be prevented.

Has anyone seen this exception or does anyone have any ideas to what could be going on?

ClearScriptLib commented 9 months ago

Hi @ebrandin,

Has anyone seen this exception or does anyone have any ideas to what could be going on?

Currently this happens if CreateScriptEngine is called after a no-op Interrupt call – that is, an Interrupt call that occurs when the V8 runtime is not executing script code:

var runtime = new V8Runtime();
var engine = runtime.CreateScriptEngine();
engine.Interrupt();
runtime.CreateScriptEngine(); // <-- EXCEPTION

Because it may be difficult or impossible for the host to ensure that Interrupt is always called during script execution, we consider this a bug, and we'll fix it in the next ClearScript release.

However, that exception can also be legitimate. For example:

  1. A script invokes a host method.
  2. Interrupt is called on the same V8 runtime.
  3. The host method calls CreateScriptEngine before returning to script code.

That sequence results in the same exception, and ClearScript can do nothing to prevent it. Many V8 API methods fail when a script exception (or script interruption) is pending. That behavior is by design and beyond ClearScript's control.

Thanks!

ClearScriptLib commented 7 months ago

Fixed in Version 7.4.5.