Skip to content
16 changes: 9 additions & 7 deletions src/runtime/ClassManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -190,17 +190,19 @@ internal static ClassBase CreateClass(Type type)
impl = new InterfaceObject(type);
}

else if (type == typeof(Exception) ||
type.IsSubclassOf(typeof(Exception)))
{
impl = new ExceptionClassObject(type);
}

#pragma warning disable CS0618 // Type or member is obsolete. OK for internal use.
else if (null != PythonDerivedType.GetPyObjField(type))
#pragma warning restore CS0618 // Type or member is obsolete
{
impl = new ClassDerivedObject(type);
impl = type.IsSubclassOf(typeof(Exception))
? new ExceptionClassDerivedObject(type)
: new ClassDerivedObject(type);
}

else if (type == typeof(Exception) ||
type.IsSubclassOf(typeof(Exception)))
{
impl = new ExceptionClassObject(type);
}

else if (typeof(IDynamicMetaObjectProvider).IsAssignableFrom(type))
Expand Down
30 changes: 25 additions & 5 deletions src/runtime/Types/ClassDerived.cs
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,8 @@ internal static Type CreateDerivedType(string name,
}
}

// add the destructor so the python object created in the constructor gets destroyed
// add the destructor so the python object created in the constructor gets destroyed,
// after the base class finalizers, which may still call the Python overrides
MethodBuilder methodBuilder = typeBuilder.DefineMethod("Finalize",
MethodAttributes.Family |
MethodAttributes.Virtual |
Expand All @@ -279,11 +280,11 @@ internal static Type CreateDerivedType(string name,
Type.EmptyTypes);
ILGenerator il = methodBuilder.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, baseClass.GetMethod("Finalize", BindingFlags.NonPublic | BindingFlags.Instance));
il.Emit(OpCodes.Ldarg_0);
#pragma warning disable CS0618 // PythonDerivedType is for internal use only
il.Emit(OpCodes.Call, typeof(PythonDerivedType).GetMethod(nameof(PyFinalize)));
#pragma warning restore CS0618 // PythonDerivedType is for internal use only
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, baseClass.GetMethod("Finalize", BindingFlags.NonPublic | BindingFlags.Instance));
il.Emit(OpCodes.Ret);

Type type = typeBuilder.CreateType();
Expand Down Expand Up @@ -903,8 +904,8 @@ public static void InvokeSetProperty<T>(IPythonDerivedType obj, string propertyN

public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, object[] args)
{
var selfRef = GetPyObj(obj);
if (selfRef.Ref == null)
var createdFromDotNet = GetPyObj(obj).Ref == null;
if (createdFromDotNet)
{
// this might happen when the object is created from .NET
using var _ = Py.GIL();
Expand All @@ -921,14 +922,33 @@ public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, objec
null,
obj,
args);

// the Python object of an exception created from .NET got its args and __cause__
// before the base constructor set its Message and InnerException
if (!createdFromDotNet || obj is not Exception exception)
{
return;
}
using var gil = Py.GIL();
if (!Exceptions.SetArgsAndCause(GetPyObj(obj).CheckRun(), exception))
{
throw PythonException.ThrowLastAsClrException();
}
}

public static void PyFinalize(IPythonDerivedType obj)
{
// the C# object is being destroyed which must mean there are no more
// references to the Python object as well
var self = GetPyObj(obj);
// every generated type in a chain of Python subclasses has its own Finalize calling this on the
// same object, once the finalizers of its base classes ran: only the first one queues its Python object
if (self.Ref == null)
{
return;
}
Finalizer.Instance.AddDerivedFinalizedObject(ref self.RawObj, self.Run);
SetPyObj(obj, BorrowedReference.Null);
}

internal static void Finalize(IntPtr derived)
Expand Down
99 changes: 81 additions & 18 deletions src/runtime/Types/ExceptionClassObject.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Reflection;

namespace Python.Runtime;

Expand Down Expand Up @@ -29,17 +30,21 @@ internal ExceptionClassObject(Type tp) : base(tp)
{
return Exceptions.RaiseTypeError("invalid object");
}
string name = e.GetType().Name;
string message;
if (e.Message != String.Empty)
try
{
message = String.Format("{0}('{1}')", name, e.Message);
string name = e.GetType().Name;
string message = e.Message;
if (!string.IsNullOrEmpty(message))
{
return Runtime.PyString_FromString(String.Format("{0}('{1}')", name, message));
}
return Runtime.PyString_FromString(String.Format("{0}()", name));
}
else
catch (Exception error)
{
message = String.Format("{0}()", name);
SetError(error);
return default;
}
return Runtime.PyString_FromString(message);
}

/// <summary>
Expand All @@ -53,26 +58,84 @@ internal ExceptionClassObject(Type tp) : base(tp)
return Exceptions.RaiseTypeError("invalid object");
}

string message = e.ToString();
string fullTypeName = e.GetType().FullName;
string prefix = fullTypeName + ": ";
if (message.StartsWith(prefix))
// a None returned by a Python override of ToString reads as an empty message
try
{
message = message.Substring(prefix.Length);
string message = e.ToString() ?? string.Empty;
string fullTypeName = e.GetType().FullName;
string prefix = fullTypeName + ": ";
if (message.StartsWith(prefix))
{
message = message.Substring(prefix.Length);
}
else if (message.StartsWith(fullTypeName))
{
message = message.Substring(fullTypeName.Length);
}
return Runtime.PyString_FromString(message);
}
else if (message.StartsWith(fullTypeName))
catch (Exception error)
{
message = message.Substring(fullTypeName.Length);
SetError(error);
return default;
}
return Runtime.PyString_FromString(message);
}

public override bool Init(BorrowedReference obj, BorrowedReference args, BorrowedReference kw)
/// <summary>
/// Raises to Python the error of an exception member, as it is: a Python override of the member
/// throws its PythonException directly, whose InnerException is its cause, while a member the
/// Python subclass inherits runs through reflection, which wraps what it throws
/// </summary>
static void SetError(Exception error)
{
if (!base.Init(obj, args, kw)) return false;
var raised = error is TargetInvocationException { InnerException: { } invoked } ? invoked : error;
Exceptions.SetError(raised);
}

public override bool Init(BorrowedReference obj, BorrowedReference args, BorrowedReference kw)
=> base.Init(obj, args, kw) && SetArgsAndCause(obj);

/// <summary>
/// Sets the args and __cause__ of the constructed exception, raising to Python an error
/// its members throw, such as a Python override of Message
/// </summary>
internal static bool SetArgsAndCause(BorrowedReference obj)
{
var e = (CLRObject)GetManagedObject(obj)!;
try
{
return Exceptions.SetArgsAndCause(obj, (Exception)e.inst);
}
catch (Exception error)
{
SetError(error);
return false;
}
}
}

return Exceptions.SetArgsAndCause(obj, (Exception)e.inst);
/// <summary>
/// Implementation for the managed types generated for Python subclasses of exceptions
/// that declare __namespace__: the generated object keeps its Python object as derived
/// types do, while it still reads as an exception from Python.
/// </summary>
[Serializable]
internal class ExceptionClassDerivedObject : ClassDerivedObject
{
internal ExceptionClassDerivedObject(Type tp) : base(tp)
{
}

// Type slots are looked up on the implementing type's hierarchy, which here is ClassDerivedObject's
public new static NewReference tp_repr(BorrowedReference ob) => ExceptionClassObject.tp_repr(ob);

public new static NewReference tp_str(BorrowedReference ob) => ExceptionClassObject.tp_str(ob);

// ClassDerivedObject's tp_clear leaves the object to the .NET finalizer, but the exception's own fields
// (args, __cause__, __context__, __traceback__, __dict__) can form cycles that only clearing them breaks.
// The wrapper and its handle stay, as the .NET object may still use them.
public new static int tp_clear(BorrowedReference ob) => BaseUnmanagedClear(ob);

public override bool Init(BorrowedReference obj, BorrowedReference args, BorrowedReference kw)
=> base.Init(obj, args, kw) && ExceptionClassObject.SetArgsAndCause(obj);
}
24 changes: 24 additions & 0 deletions src/testing/constructortests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,4 +108,28 @@ public FinalizedConstructorTest(Exception toThrow)
Interlocked.Increment(ref Finalized);
}
}

public abstract class AbstractFinalizerCallbackTest
{
public static int Result;

public abstract int Callback();

~AbstractFinalizerCallbackTest()
{
Result = Callback();
}
}

public class VirtualFinalizerCallbackTest
{
public static int Result;

public virtual int Callback() => 7;

~VirtualFinalizerCallbackTest()
{
Result = Callback();
}
}
}
Loading
Loading