Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tests of CallStack unwinding after caught exception (and quick patch) #853

Merged
merged 3 commits into from
Mar 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
60 changes: 60 additions & 0 deletions Jint.Tests/Runtime/CallStackTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;

namespace Jint.Tests.Runtime
{
public class CallStackTests
{
[Fact]
public void ShouldUnwindAfterCaughtException()
{
var engine = new Engine();
engine.Execute(@"
function thrower()
{
throw new Error('test');
}

try
{
thrower();
}
catch (error)
{
}
"
);
Assert.Equal(0, engine.CallStack.Count);
}

[Fact]
public void ShouldUnwindAfterCaughtExceptionNested()
{
var engine = new Engine();
engine.Execute(@"
function thrower2()
{
throw new Error('test');
}

function thrower1()
{
thrower2();
}

try
{
thrower1();
}
catch (error)
{
}
");
Assert.Equal(0, engine.CallStack.Count);
}
}
}
11 changes: 11 additions & 0 deletions Jint/Runtime/Interpreter/Statements/JintTryStatement.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,23 @@ public JintTryStatement(Engine engine, TryStatement statement) : base(engine, st

protected override Completion ExecuteInternal()
{
int callStackSizeBeforeExecution = _engine.CallStack.Count;

var b = _block.Execute();
if (b.Type == CompletionType.Throw)
{
// execute catch
if (_catch != null)
{
// Quick-patch for call stack not being unwinded when an exception is caught.
// Ideally, this should instead be solved by always popping the stack when returning
// from a call, regardless of whether it throws (i.e. CallStack.Pop() in finally clause
// in Engine.Call/Engine.Construct - however, that method currently breaks stack traces
// in error messages.
while (callStackSizeBeforeExecution < _engine.CallStack.Count)
{
_engine.CallStack.Pop();
}
var c = b.Value;
var oldEnv = _engine.ExecutionContext.LexicalEnvironment;
var catchEnv = LexicalEnvironment.NewDeclarativeEnvironment(_engine, oldEnv);
Expand Down