Skip to content

Disallow runtime shutdown when the Python error indicator is set #1780

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

Merged
merged 1 commit into from
May 4, 2022
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ and other `PyObject` derived types when called from Python.
details about the cause of the failure
- `clr.AddReference` no longer adds ".dll" implicitly
- `PyIter(PyObject)` constructor replaced with static `PyIter.GetIter(PyObject)` method
- Python runtime can no longer be shut down if the Python error indicator is set, as it would have unpredictable behavior
- BREAKING: Return values from .NET methods that return an interface are now automatically
wrapped in that interface. This is a breaking change for users that rely on being
able to access members that are part of the implementation class, but not the
Expand Down
6 changes: 6 additions & 0 deletions src/runtime/PythonEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,12 @@ public static void Shutdown()
{
return;
}
if (Exceptions.ErrorOccurred())
{
throw new InvalidOperationException(
"Python error indicator is set",
innerException: PythonException.PeekCurrentOrNull(out _));
}
// If the shutdown handlers trigger a domain unload,
// don't call shutdown again.
AppDomain.CurrentDomain.DomainUnload -= OnDomainUnload;
Expand Down
17 changes: 17 additions & 0 deletions src/runtime/PythonException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,23 @@ internal static PythonException FetchCurrentRaw()
=> FetchCurrentOrNullRaw()
?? throw new InvalidOperationException("No exception is set");

internal static Exception? PeekCurrentOrNull(out ExceptionDispatchInfo? dispatchInfo)
{
using var _ = new Py.GILState();

Runtime.PyErr_Fetch(out var type, out var value, out var traceback);
Runtime.PyErr_Restore(
new NewReference(type, canBeNull: true).StealNullable(),
new NewReference(value, canBeNull: true).StealNullable(),
new NewReference(traceback, canBeNull: true).StealNullable());

var err = FetchCurrentOrNull(out dispatchInfo);

Runtime.PyErr_Restore(type.StealNullable(), value.StealNullable(), traceback.StealNullable());

return err;
}

internal static Exception? FetchCurrentOrNull(out ExceptionDispatchInfo? dispatchInfo)
{
dispatchInfo = null;
Expand Down