diff --git a/src/core/IronPython/Compiler/Ast/AstMethods.cs b/src/core/IronPython/Compiler/Ast/AstMethods.cs index ae8d877bf..885ab74ee 100644 --- a/src/core/IronPython/Compiler/Ast/AstMethods.cs +++ b/src/core/IronPython/Compiler/Ast/AstMethods.cs @@ -37,6 +37,7 @@ internal static class AstMethods { public static readonly MethodInfo RemoveModule = GetMethod((Action)PythonOps.RemoveModule); public static readonly MethodInfo ModuleStarted = GetMethod((Action)PythonOps.ModuleStarted); public static readonly MethodInfo MakeRethrownException = GetMethod((Func)PythonOps.MakeRethrownException); + public static readonly MethodInfo RethrowDeferredException = GetMethod((Action)PythonOps.RethrowDeferredException); public static readonly MethodInfo MakeException = GetMethod((Func)PythonOps.MakeException); public static readonly MethodInfo MakeExceptionWithCause = GetMethod((Func)PythonOps.MakeExceptionWithCause); public static readonly MethodInfo MakeSlice = GetMethod((Func)PythonOps.MakeSlice); diff --git a/src/core/IronPython/Compiler/Ast/ScopeStatement.cs b/src/core/IronPython/Compiler/Ast/ScopeStatement.cs index 07151021b..5df27265b 100644 --- a/src/core/IronPython/Compiler/Ast/ScopeStatement.cs +++ b/src/core/IronPython/Compiler/Ast/ScopeStatement.cs @@ -469,6 +469,48 @@ internal PythonContext PyContext #region Runtime Line Number Tracing + /// + /// Runs for any exception throws, then + /// rethrows that exception after the catch block has exited. + /// + /// + /// Equivalent to catch (Exception e) { onCatch; throw; }, except that the rethrow + /// happens outside the catch block (see PythonOps.RethrowDeferredException), + /// so unwinding a deep Python call chain does not overflow the stack. + /// + 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 + ); + } + /// /// Gets the expression for updating the dynamic stack trace at runtime when an /// exception is thrown. @@ -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)) ); } diff --git a/src/core/IronPython/Runtime/Operations/PythonOps.cs b/src/core/IronPython/Runtime/Operations/PythonOps.cs index 40f9e8d6c..21d492275 100644 --- a/src/core/IronPython/Runtime/Operations/PythonOps.cs +++ b/src/core/IronPython/Runtime/Operations/PythonOps.cs @@ -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; @@ -2593,6 +2594,19 @@ public static Exception MakeRethrownException(CodeContext/*!*/ context) { return ExceptionHelpers.UpdateForRethrow(e); } + /// + /// Rethrows an exception a frame caught and stored, once its catch block has exited. + /// + /// + /// 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. + /// + 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); diff --git a/tests/suite/test_exceptions.py b/tests/suite/test_exceptions.py index 881e4d5db..5e0041987 100644 --- a/tests/suite/test_exceptions.py +++ b/tests/suite/test_exceptions.py @@ -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__)