Skip to content
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
disallow runtime shutdown when the Python error indicator is set, as …
…it may lead to unpredictable behavior
  • Loading branch information
lostmsu committed May 2, 2022
commit 6906ca94d06c31a8b4572ca20d96ca1b58364957
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