Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/core/IronPython/Compiler/Ast/AstMethods.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ internal static class AstMethods {
public static readonly MethodInfo RemoveModule = GetMethod((Action<CodeContext, string, object>)PythonOps.RemoveModule);
public static readonly MethodInfo ModuleStarted = GetMethod((Action<CodeContext, ModuleOptions>)PythonOps.ModuleStarted);
public static readonly MethodInfo MakeRethrownException = GetMethod((Func<CodeContext, Exception>)PythonOps.MakeRethrownException);
public static readonly MethodInfo RethrowDeferredException = GetMethod((Action<Exception>)PythonOps.RethrowDeferredException);
public static readonly MethodInfo MakeException = GetMethod((Func<CodeContext, object, Exception>)PythonOps.MakeException);
public static readonly MethodInfo MakeExceptionWithCause = GetMethod((Func<CodeContext, object, object, Exception>)PythonOps.MakeExceptionWithCause);
public static readonly MethodInfo MakeSlice = GetMethod((Func<object, object, object, Slice>)PythonOps.MakeSlice);
Expand Down
53 changes: 43 additions & 10 deletions src/core/IronPython/Compiler/Ast/ScopeStatement.cs
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,48 @@ internal PythonContext PyContext

#region Runtime Line Number Tracing

/// <summary>
/// Runs <paramref name="onCatch"/> for any exception <paramref name="body"/> throws, then
/// rethrows that exception after the catch block has exited.
/// </summary>
/// <remarks>
/// Equivalent to <c>catch (Exception e) { onCatch; throw; }</c>, except that the rethrow
/// happens outside the catch block (see <c>PythonOps.RethrowDeferredException</c>),
/// so unwinding a deep Python call chain does not overflow the stack.
/// </remarks>
internal static MSAst.Expression/*!*/ RethrowAfterCatch(MSAst.Expression/*!*/ body, MSAst.ParameterExpression/*!*/ caught, MSAst.Expression/*!*/ onCatch) {
MSAst.ParameterExpression pending = Ast.Variable(typeof(Exception), "$pendingException");
MSAst.Expression tryCatch = Ast.TryCatch(
body,
Ast.Catch(
caught,
Ast.Block(
onCatch,
Ast.Assign(pending, caught),
Ast.Default(body.Type)
)
)
);
MSAst.Expression rethrow = Ast.IfThen(
Ast.NotEqual(pending, AstUtils.Constant(null, typeof(Exception))),
Ast.Call(AstMethods.RethrowDeferredException, pending)
);
MSAst.Expression clearPending = Ast.Assign(pending, AstUtils.Constant(null, typeof(Exception)));

if (body.Type == typeof(void)) {
return Ast.Block(new[] { pending }, clearPending, tryCatch, rethrow);
}

MSAst.ParameterExpression result = Ast.Variable(body.Type, "$result");
return Ast.Block(
new[] { pending, result },
clearPending,
Ast.Assign(result, tryCatch),
rethrow,
result
);
}

/// <summary>
/// Gets the expression for updating the dynamic stack trace at runtime when an
/// exception is thrown.
Expand Down Expand Up @@ -522,16 +564,7 @@ internal MSAst.Expression GetSaveLineNumberExpression(MSAst.ParameterExpression
if (canThrow) {
body = Ast.Block(
new[] { LineNumberExpression, LineNumberUpdated },
Ast.TryCatch(
body,
Ast.Catch(
_catchException,
Ast.Block(
GetUpdateTrackbackExpression(_catchException),
Ast.Rethrow(body.Type)
)
)
)
RethrowAfterCatch(body, _catchException, GetUpdateTrackbackExpression(_catchException))
);
}

Expand Down
14 changes: 14 additions & 0 deletions src/core/IronPython/Runtime/Operations/PythonOps.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
Expand Down Expand Up @@ -2593,6 +2594,19 @@ public static Exception MakeRethrownException(CodeContext/*!*/ context) {
return ExceptionHelpers.UpdateForRethrow(e);
}

/// <summary>
/// Rethrows an exception a frame caught and stored, once its catch block has exited.
/// </summary>
/// <remarks>
/// Rethrowing from inside the catch block would start a nested exception dispatch on
/// top of the frames still being unwound, so each Python frame an exception crosses
/// would keep several KB of stack alive and deep call chains would overflow the stack.
/// The .NET stack trace is preserved as with a plain rethrow.
/// </remarks>
public static void RethrowDeferredException(Exception e) {
ExceptionDispatchInfo.Capture(e).Throw();
}

public static Exception MakeException(CodeContext/*!*/ context, object exception)
=> MakeExceptionWorker(context, exception, null, null, withCause: false);

Expand Down
34 changes: 34 additions & 0 deletions tests/suite/test_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -1121,4 +1121,38 @@ def test_context_cycle_broken(self):
self.assertIs(e.__context__, b)
self.assertIsNone(b.__context__)

@skipUnlessIronPython()
def test_deep_exception_unwinds_compiled_frames_on_small_stack(self):
import subprocess
code = """import sys
from System.Threading import Thread, ThreadStart

DEPTH = 300

def f(n, raised):
if n == 0:
raise raised
return f(n - 1, raised)

out = []
def run():
raised = ValueError("boom")
try:
f(DEPTH, raised)
except ValueError as e:
frames = 0
tb = e.__traceback__
while tb is not None:
frames += 1
tb = tb.tb_next
out.append(e is raised and frames == DEPTH + 2)

t = Thread(ThreadStart(run), 512 * 1024)
t.Start()
t.Join()
print(out[0] if out else False)
"""
out = subprocess.check_output([sys.executable, '-X', 'NoAdaptiveCompilation', '-c', code])
self.assertEqual(out.strip(), b'True')

run_test(__name__)
Loading