diff --git a/src/embed_tests/TestConverter.cs b/src/embed_tests/TestConverter.cs index 746d13044..cc961ad2b 100644 --- a/src/embed_tests/TestConverter.cs +++ b/src/embed_tests/TestConverter.cs @@ -809,6 +809,142 @@ public void FailedConversionOfNonClrValueManagedTypesOnlyLeavesErrorWhenSettingE Exceptions.Clear(); } } + + [TestCase(typeof(decimal), true)] + [TestCase(typeof(decimal), false)] + [TestCase(typeof(DateTime), true)] + [TestCase(typeof(DateTime), false)] + [TestCase(typeof(TimeSpan), true)] + [TestCase(typeof(TimeSpan), false)] + public void ConversionFailsWhenStrRaises(Type type, bool setError) + { + using (Py.GIL()) + { + using var scope = Py.CreateScope(); + scope.Exec(@" +class BadStr: + def __str__(self): + raise ValueError('boom') +"); + using var value = scope.Eval("BadStr()"); + + Assert.IsFalse(Converter.ToManaged(value, type, out var result, setError)); + Assert.AreEqual(setError, Exceptions.ErrorOccurred()); + if (setError) + { + Assert.IsTrue(Exceptions.ExceptionMatches(Exceptions.TypeError)); + } + Exceptions.Clear(); + } + } + + [TestCase(typeof(decimal), true)] + [TestCase(typeof(decimal), false)] + [TestCase(typeof(DateTime), true)] + [TestCase(typeof(DateTime), false)] + [TestCase(typeof(TimeSpan), true)] + [TestCase(typeof(TimeSpan), false)] + public void ConversionFailsWhenStrCannotBeEncoded(Type type, bool setError) + { + using (Py.GIL()) + { + using var scope = Py.CreateScope(); + // a lone surrogate has no UTF-16 form + scope.Exec(@" +class Unreadable: + def __str__(self): + return chr(0xD800) +"); + using var value = scope.Eval("Unreadable()"); + + Assert.IsFalse(Converter.ToManaged(value, type, out var result, setError)); + Assert.AreEqual(setError, Exceptions.ErrorOccurred()); + if (setError) + { + Assert.IsTrue(Exceptions.ExceptionMatches(Exceptions.TypeError)); + } + Exceptions.Clear(); + } + } + + [Test] + [SetCulture("en-US")] + public void StrSubclassTextIsParsed() + { + using (Py.GIL()) + { + using var scope = Py.CreateScope(); + scope.Exec(@" +class Text(str): + pass + +class Value: + def __init__(self, text): + self.text = text + def __str__(self): + return Text(self.text) +"); + using var amount = scope.Eval("Value('1.5')"); + using var duration = scope.Eval("Value('1:30:00')"); + using var moment = scope.Eval("Value('2020-01-02 03:04:05')"); + + Assert.IsTrue(Converter.ToManaged(amount, typeof(decimal), out var result, false)); + Assert.AreEqual(1.5m, result); + Assert.IsTrue(Converter.ToManaged(duration, typeof(TimeSpan), out result, false)); + Assert.AreEqual(new TimeSpan(1, 30, 0), result); + Assert.IsTrue(Converter.ToManaged(moment, typeof(DateTime), out result, false)); + Assert.AreEqual(new DateTime(2020, 1, 2, 3, 4, 5), result); + } + } + + [Test] + public void FloatToDecimalAtTheRecursionLimitRaisesPythonError() + { + using (Py.GIL()) + { + using var scope = Py.CreateScope(); + scope.Set("target", new DecimalConsumer().ToPython()); + // str(float) itself fails at the recursion limit, so sweep the depth to land exactly on it + scope.Exec(@" +import sys +limit = sys.getrecursionlimit() +sys.setrecursionlimit(200) +errors = set() + +# a first failed call warms up the lazy state the mismatch diagnosis needs +try: + target.Take('not a number') +except TypeError: + pass + +def call(depth): + if depth == 0: + target.Take(1.5) + else: + call(depth - 1) + +try: + for depth in range(100, 260): + try: + call(depth) + except (RecursionError, TypeError) as e: + errors.add(type(e).__name__) +finally: + sys.setrecursionlimit(limit) +errors = sorted(errors) +"); + var errors = scope.Get("errors").As(); + // str(float) only fails at the limit on some Python versions, so a TypeError is optional + CollectionAssert.Contains(errors, "RecursionError"); + } + } + } + + public class DecimalConsumer + { + public void Take(decimal value) + { + } } public interface IGetList diff --git a/src/embed_tests/TestImplicitNumericOperators.cs b/src/embed_tests/TestImplicitNumericOperators.cs index cd9de7470..8c9942482 100644 --- a/src/embed_tests/TestImplicitNumericOperators.cs +++ b/src/embed_tests/TestImplicitNumericOperators.cs @@ -332,6 +332,67 @@ public void UnsupportedOperandsRaisePythonsTypeError() StringAssert.Contains("unsupported operand type(s) for -", messages[3]); } + [Test] + public void IntOperandWhoseStrRaisesIsUnsupported() + { + using var _ = Py.GIL(); + using var scope = Py.CreateScope(); + scope.Set("count", new ConvertibleCount(1).ToPython()); + // beyond long, the int is read through its str() + scope.Exec(@" +class BadInt(int): + def __str__(self): + raise ValueError('boom') + +try: + count + BadInt(10 ** 25) + error = '' +except Exception as e: + error = type(e).__name__ +"); + Assert.AreEqual("TypeError", scope.Get("error")); + } + + [Test] + public void IntOperandWhoseStrCannotBeEncodedIsUnsupported() + { + using var _ = Py.GIL(); + using var scope = Py.CreateScope(); + scope.Set("count", new ConvertibleCount(1).ToPython()); + // a lone surrogate has no UTF-16 form + scope.Exec(@" +class BadInt(int): + def __str__(self): + return chr(0xD800) + +try: + count + BadInt(10 ** 25) + error = '' +except Exception as e: + error = type(e).__name__ +"); + Assert.AreEqual("TypeError", scope.Get("error")); + } + + [Test] + public void IntOperandWhoseStrIsAStrSubclassIsRead() + { + using var _ = Py.GIL(); + using var scope = Py.CreateScope(); + scope.Set("count", new ConvertibleCount(1).ToPython()); + scope.Exec(@" +class Text(str): + pass + +class BigInt(int): + def __str__(self): + return Text(int(self)) + +matches = count + BigInt(10 ** 25) == 10 ** 25 + 1 +"); + Assert.IsTrue(scope.Get("matches")); + } + [Test] public void InheritedOperatorsKeepWinning() { diff --git a/src/embed_tests/TestPythonException.cs b/src/embed_tests/TestPythonException.cs index 9a3343460..2bb1d3272 100644 --- a/src/embed_tests/TestPythonException.cs +++ b/src/embed_tests/TestPythonException.cs @@ -349,6 +349,115 @@ def CallThrow(): } } + [Test] + public void ErrorRaisedAtTheRecursionLimitReachesPython() + { + using var _ = Py.GIL(); + using var scope = Py.CreateScope(); + scope.Set("target", new ReentrantCaller().ToPython()); + // managed code calls back into Python until the recursion limit, so the error is decoded right at it + scope.Exec(@" +import sys +limit = sys.getrecursionlimit() +sys.setrecursionlimit(200) + +def handler(): + target.Call(handler) + +try: + target.Call(handler) + error = '' +except RecursionError as e: + error = str(e) +finally: + sys.setrecursionlimit(limit) +"); + StringAssert.Contains("maximum recursion depth exceeded", scope.Get("error")); + } + + [Test] + public void DecodingKeepsARecursionLimitSetWhileItRuns() + { + using var _ = Py.GIL(); + using var scope = Py.CreateScope(); + // decoding reads attributes of the error, and this one changes the limit when it is read + scope.Exec(@" +import sys +limit = sys.getrecursionlimit() + +class LimitError(Exception): + def __getattr__(self, name): + sys.setrecursionlimit(250) + raise AttributeError(name) +"); + try + { + Assert.Throws(() => scope.Exec("raise LimitError('boom')")); + Assert.AreEqual(250, scope.Eval("sys.getrecursionlimit()")); + } + finally + { + scope.Exec("sys.setrecursionlimit(limit)"); + } + } + + [Test] + public void ErrorIsDecodedAtTheHighestRecursionLimit() + { + using var _ = Py.GIL(); + using var scope = Py.CreateScope(); + scope.Exec(@" +import sys +limit = sys.getrecursionlimit() +sys.setrecursionlimit(2147483647) +"); + try + { + var error = Assert.Throws(() => scope.Exec("raise ValueError('boom')")); + Assert.AreEqual("boom", error.Message); + Assert.AreEqual(2147483647, scope.Eval("sys.getrecursionlimit()")); + } + finally + { + scope.Exec("sys.setrecursionlimit(limit)"); + } + } + + [Test] + public void ErrorWhoseStrRaisesArrivesAsItself() + { + using var _ = Py.GIL(); + using var scope = Py.CreateScope(); + scope.Exec(@" +class Unprintable(Exception): + def __str__(self): + raise KeyError('from str') +"); + var error = Assert.Throws(() => scope.Exec("raise Unprintable('original')")); + Assert.AreEqual("Unprintable", error.Type.Name); + Assert.AreEqual("original", error.Message); + } + + [Test] + public void ErrorWhoseStrRaisesIsNamedAfterItsTypeWithoutATextArgument() + { + using var _ = Py.GIL(); + using var scope = Py.CreateScope(); + // the type name is not ASCII + scope.Exec("class D\u00e9faut(Exception):\n def __str__(self):\n raise KeyError('from str')\n"); + var error = Assert.Throws(() => scope.Exec("raise D\u00e9faut(1, 2)")); + Assert.AreEqual("D\u00e9faut", error.Message); + } + + public class ReentrantCaller + { + public void Call(PyObject callback) + { + using var _ = Py.GIL(); + callback.Invoke().Dispose(); + } + } + public class TestClass { public void ThrowException() diff --git a/src/runtime/Converter.cs b/src/runtime/Converter.cs index 47e592d16..6c7d3554f 100644 --- a/src/runtime/Converter.cs +++ b/src/runtime/Converter.cs @@ -1034,8 +1034,13 @@ internal static bool ToPrimitive(BorrowedReference value, Type obType, out objec if (obType == typeof(TimeSpan)) { op = Runtime.PyObject_Str(value); + if (op.IsNull()) + { + goto type_error; + } TimeSpan ts; - var arr = Runtime.GetManagedString(op.Borrow()).Split(','); + var arr = Runtime.GetManagedSpan(op.Borrow(), out var timeSpanText).ToString().Split(','); + timeSpanText.Dispose(); op.Dispose(); string sts = arr.Length == 1 ? arr[0] : arr[1]; if (!TimeSpan.TryParse(sts, out ts)) @@ -1370,6 +1375,10 @@ internal static bool ToPrimitive(BorrowedReference value, Type obType, out objec } case TypeCode.Decimal: op = Runtime.PyObject_Str(value); + if (op.IsNull()) + { + goto type_error; + } decimal m; var sm = Runtime.GetManagedSpan(op.Borrow(), out var newReference); if (!Decimal.TryParse(sm, NumberStyles.Number | NumberStyles.AllowExponent, nfi, out m)) @@ -1391,6 +1400,10 @@ internal static bool ToPrimitive(BorrowedReference value, Type obType, out objec // fallback to string parsing for types such as numpy op = Runtime.PyObject_Str(value); + if (op.IsNull()) + { + goto type_error; + } var sdt = Runtime.GetManagedSpan(op.Borrow(), out var reference); if (!DateTime.TryParse(sdt, out var dt)) { diff --git a/src/runtime/PythonException.cs b/src/runtime/PythonException.cs index 9f26e3a8d..2f9fe6384 100644 --- a/src/runtime/PythonException.cs +++ b/src/runtime/PythonException.cs @@ -91,40 +91,91 @@ internal static PythonException FetchCurrentRaw() return null; } + if (_decodingError) + { + // raised by the decoding below: decoding it too could fail the same way, without end + return ToUndecoded(ref type, ref value, ref traceback); + } + + _decodingError = true; try { if (TryDecodePyErr(type.Borrow(), value.BorrowNullable(), traceback.BorrowNullable()) is { } pyErr) { - type.Dispose(); - value.Dispose(); - traceback.Dispose(); return pyErr; } - } - catch - { - type.Dispose(); - value.Dispose(); - traceback.Dispose(); - throw; - } - try - { // an error set without a value, as PyErr_SetNone does, only gets one once normalized var normalizedValue = new NewReference(value.BorrowNullable(), canBeNull: true); Runtime.PyErr_NormalizeException(type: ref type, val: ref normalizedValue, tb: ref traceback); return FromPyErr(typeRef: type.Borrow(), valRef: value.IsNull() ? normalizedValue.Borrow() : value.Borrow(), nValRef: normalizedValue.Borrow(), tbRef: traceback.BorrowNullable(), out dispatchInfo); } + catch (PythonException) + { + // decoding runs Python code, which fails too at the recursion limit: keep the error as fetched + Exceptions.Clear(); + dispatchInfo = null; + return ToUndecoded(ref type, ref value, ref traceback); + } finally { + _decodingError = false; type.Dispose(); value.Dispose(); traceback.Dispose(); } } + [ThreadStatic] + private static bool _decodingError; + + /// + /// Wraps a fetched error as it is, without running any Python code. + /// + private static PythonException ToUndecoded(ref NewReference type, ref NewReference value, ref NewReference traceback) + { + var pyType = new PyType(type.Steal()); + var message = GetUndecodedMessage(pyType, value.BorrowNullable()); + return new PythonException(pyType, value.MoveToPyObjectOrNull(), + traceback.MoveToPyObjectOrNull(), message, innerException: null); + } + + /// + /// The message of an error, read without str(): the text of an error that is not normalized + /// yet, or the only argument of an exception when it is a string. Else the name of its type. + /// + private static string GetUndecodedMessage(PyType type, BorrowedReference value) + { + try + { + if (!value.IsNull) + { + if (Runtime.GetManagedString(value) is { } text) + { + return text; + } + + using var args = Runtime.PyObject_GetAttrString(value, "args"); + if (args.IsNull()) + { + Exceptions.Clear(); + } + else if (Runtime.PyTuple_Check(args.Borrow()) && Runtime.PyTuple_Size(args.Borrow()) == 1 + && Runtime.GetManagedString(Runtime.PyTuple_GetItem(args.Borrow(), 0)) is { } argument) + { + return argument; + } + } + } + catch (PythonException) + { + Exceptions.Clear(); + } + + return type.Name; + } + internal static Exception FetchCurrent() => FetchCurrentOrNull(out _) ?? throw new InvalidOperationException("No exception is set"); diff --git a/src/runtime/Runtime.cs b/src/runtime/Runtime.cs index 50cd73bb6..c8719ee40 100644 --- a/src/runtime/Runtime.cs +++ b/src/runtime/Runtime.cs @@ -1439,11 +1439,15 @@ static string GetManagedStringFromUnicodeObject(BorrowedReference op) internal static ReadOnlySpan GetManagedSpan(BorrowedReference op, out NewReference reference) { - var type = PyObject_TYPE(op); - - if (type == PyUnicodeType) + if (PyObject_TypeCheck(op, PyUnicodeType)) { reference = PyUnicode_AsUTF16String(op); + if (reference.IsNull()) + { + // no UTF-16 form (lone surrogates): reads as empty, like a non-str + Exceptions.Clear(); + return null; + } int bytesLength = checked((int)PyBytes_Size(reference.Borrow())); var codePoints = PyBytes_AsString(reference.Borrow()); return new ReadOnlySpan(IntPtr.Add(codePoints, sizeof(char)).ToPointer(), length: bytesLength / 2 - 1); diff --git a/src/runtime/Util/ImplicitNumericOps.cs b/src/runtime/Util/ImplicitNumericOps.cs index d53259f14..5285a66df 100644 --- a/src/runtime/Util/ImplicitNumericOps.cs +++ b/src/runtime/Util/ImplicitNumericOps.cs @@ -234,7 +234,11 @@ private static bool TryGetOperand(PyObject? value, out Number number) var reference = value.Reference; if (Runtime.PyInt_Check(reference)) { - number = new Number(ToBigInteger(reference)); + if (!TryToBigInteger(reference, out var big)) + { + return false; + } + number = new Number(big); return true; } if (Runtime.PyObject_TypeCheck(reference, Runtime.PyFloatType)) @@ -245,9 +249,9 @@ private static bool TryGetOperand(PyObject? value, out Number number) if (Runtime.PyObject_HasAttrString(reference, "__index__") != 0) { using var integer = Runtime.PyNumber_Long(reference); - if (!integer.IsNull()) + if (!integer.IsNull() && TryToBigInteger(integer.Borrow(), out var big)) { - number = new Number(ToBigInteger(integer.Borrow())); + number = new Number(big); return true; } } @@ -266,18 +270,29 @@ private static bool TryGetOperand(PyObject? value, out Number number) return false; } - private static BigInteger ToBigInteger(BorrowedReference integer) + private static bool TryToBigInteger(BorrowedReference integer, out BigInteger result) { var value = Runtime.PyLong_AsLongLong(integer); if (value.HasValue) { - return value.Value; + result = value.Value; + return true; } // beyond long, parse its digits Exceptions.Clear(); using var digits = Runtime.PyObject_Str(integer); - return BigInteger.Parse(Runtime.GetManagedString(digits.Borrow())!, CultureInfo.InvariantCulture); + if (digits.IsNull()) + { + // str() itself can raise, the operand is then not a number + Exceptions.Clear(); + result = default; + return false; + } + var text = Runtime.GetManagedSpan(digits.Borrow(), out var reference); + var parsed = BigInteger.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out result); + reference.Dispose(); + return parsed; } ///