Skip to content

Commit aa64d2a

Browse files
authored
Fix crashes when str() fails in a conversion or an error is raised at the recursion limit (#181)
* Fix crashes when str() fails in a conversion or an error is raised at the recursion limit * Do not require a TypeError at the recursion limit, it depends on the Python version * Fail the conversion when the text of str() cannot be read, and read str subclasses * Undo the recursion headroom instead of restoring a saved limit * Read big int digits through the checked span reader, and pin the culture of a parsing test * Keep an error as fetched when decoding it fails, instead of raising the recursion limit * Test an error whose decoding fails, and read its type name as UTF-8
1 parent 865d592 commit aa64d2a

7 files changed

Lines changed: 412 additions & 23 deletions

File tree

‎src/embed_tests/TestConverter.cs‎

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -809,6 +809,142 @@ public void FailedConversionOfNonClrValueManagedTypesOnlyLeavesErrorWhenSettingE
809809
Exceptions.Clear();
810810
}
811811
}
812+
813+
[TestCase(typeof(decimal), true)]
814+
[TestCase(typeof(decimal), false)]
815+
[TestCase(typeof(DateTime), true)]
816+
[TestCase(typeof(DateTime), false)]
817+
[TestCase(typeof(TimeSpan), true)]
818+
[TestCase(typeof(TimeSpan), false)]
819+
public void ConversionFailsWhenStrRaises(Type type, bool setError)
820+
{
821+
using (Py.GIL())
822+
{
823+
using var scope = Py.CreateScope();
824+
scope.Exec(@"
825+
class BadStr:
826+
def __str__(self):
827+
raise ValueError('boom')
828+
");
829+
using var value = scope.Eval("BadStr()");
830+
831+
Assert.IsFalse(Converter.ToManaged(value, type, out var result, setError));
832+
Assert.AreEqual(setError, Exceptions.ErrorOccurred());
833+
if (setError)
834+
{
835+
Assert.IsTrue(Exceptions.ExceptionMatches(Exceptions.TypeError));
836+
}
837+
Exceptions.Clear();
838+
}
839+
}
840+
841+
[TestCase(typeof(decimal), true)]
842+
[TestCase(typeof(decimal), false)]
843+
[TestCase(typeof(DateTime), true)]
844+
[TestCase(typeof(DateTime), false)]
845+
[TestCase(typeof(TimeSpan), true)]
846+
[TestCase(typeof(TimeSpan), false)]
847+
public void ConversionFailsWhenStrCannotBeEncoded(Type type, bool setError)
848+
{
849+
using (Py.GIL())
850+
{
851+
using var scope = Py.CreateScope();
852+
// a lone surrogate has no UTF-16 form
853+
scope.Exec(@"
854+
class Unreadable:
855+
def __str__(self):
856+
return chr(0xD800)
857+
");
858+
using var value = scope.Eval("Unreadable()");
859+
860+
Assert.IsFalse(Converter.ToManaged(value, type, out var result, setError));
861+
Assert.AreEqual(setError, Exceptions.ErrorOccurred());
862+
if (setError)
863+
{
864+
Assert.IsTrue(Exceptions.ExceptionMatches(Exceptions.TypeError));
865+
}
866+
Exceptions.Clear();
867+
}
868+
}
869+
870+
[Test]
871+
[SetCulture("en-US")]
872+
public void StrSubclassTextIsParsed()
873+
{
874+
using (Py.GIL())
875+
{
876+
using var scope = Py.CreateScope();
877+
scope.Exec(@"
878+
class Text(str):
879+
pass
880+
881+
class Value:
882+
def __init__(self, text):
883+
self.text = text
884+
def __str__(self):
885+
return Text(self.text)
886+
");
887+
using var amount = scope.Eval("Value('1.5')");
888+
using var duration = scope.Eval("Value('1:30:00')");
889+
using var moment = scope.Eval("Value('2020-01-02 03:04:05')");
890+
891+
Assert.IsTrue(Converter.ToManaged(amount, typeof(decimal), out var result, false));
892+
Assert.AreEqual(1.5m, result);
893+
Assert.IsTrue(Converter.ToManaged(duration, typeof(TimeSpan), out result, false));
894+
Assert.AreEqual(new TimeSpan(1, 30, 0), result);
895+
Assert.IsTrue(Converter.ToManaged(moment, typeof(DateTime), out result, false));
896+
Assert.AreEqual(new DateTime(2020, 1, 2, 3, 4, 5), result);
897+
}
898+
}
899+
900+
[Test]
901+
public void FloatToDecimalAtTheRecursionLimitRaisesPythonError()
902+
{
903+
using (Py.GIL())
904+
{
905+
using var scope = Py.CreateScope();
906+
scope.Set("target", new DecimalConsumer().ToPython());
907+
// str(float) itself fails at the recursion limit, so sweep the depth to land exactly on it
908+
scope.Exec(@"
909+
import sys
910+
limit = sys.getrecursionlimit()
911+
sys.setrecursionlimit(200)
912+
errors = set()
913+
914+
# a first failed call warms up the lazy state the mismatch diagnosis needs
915+
try:
916+
target.Take('not a number')
917+
except TypeError:
918+
pass
919+
920+
def call(depth):
921+
if depth == 0:
922+
target.Take(1.5)
923+
else:
924+
call(depth - 1)
925+
926+
try:
927+
for depth in range(100, 260):
928+
try:
929+
call(depth)
930+
except (RecursionError, TypeError) as e:
931+
errors.add(type(e).__name__)
932+
finally:
933+
sys.setrecursionlimit(limit)
934+
errors = sorted(errors)
935+
");
936+
var errors = scope.Get("errors").As<string[]>();
937+
// str(float) only fails at the limit on some Python versions, so a TypeError is optional
938+
CollectionAssert.Contains(errors, "RecursionError");
939+
}
940+
}
941+
}
942+
943+
public class DecimalConsumer
944+
{
945+
public void Take(decimal value)
946+
{
947+
}
812948
}
813949

814950
public interface IGetList

‎src/embed_tests/TestImplicitNumericOperators.cs‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -332,6 +332,67 @@ public void UnsupportedOperandsRaisePythonsTypeError()
332332
StringAssert.Contains("unsupported operand type(s) for -", messages[3]);
333333
}
334334

335+
[Test]
336+
public void IntOperandWhoseStrRaisesIsUnsupported()
337+
{
338+
using var _ = Py.GIL();
339+
using var scope = Py.CreateScope();
340+
scope.Set("count", new ConvertibleCount(1).ToPython());
341+
// beyond long, the int is read through its str()
342+
scope.Exec(@"
343+
class BadInt(int):
344+
def __str__(self):
345+
raise ValueError('boom')
346+
347+
try:
348+
count + BadInt(10 ** 25)
349+
error = ''
350+
except Exception as e:
351+
error = type(e).__name__
352+
");
353+
Assert.AreEqual("TypeError", scope.Get<string>("error"));
354+
}
355+
356+
[Test]
357+
public void IntOperandWhoseStrCannotBeEncodedIsUnsupported()
358+
{
359+
using var _ = Py.GIL();
360+
using var scope = Py.CreateScope();
361+
scope.Set("count", new ConvertibleCount(1).ToPython());
362+
// a lone surrogate has no UTF-16 form
363+
scope.Exec(@"
364+
class BadInt(int):
365+
def __str__(self):
366+
return chr(0xD800)
367+
368+
try:
369+
count + BadInt(10 ** 25)
370+
error = ''
371+
except Exception as e:
372+
error = type(e).__name__
373+
");
374+
Assert.AreEqual("TypeError", scope.Get<string>("error"));
375+
}
376+
377+
[Test]
378+
public void IntOperandWhoseStrIsAStrSubclassIsRead()
379+
{
380+
using var _ = Py.GIL();
381+
using var scope = Py.CreateScope();
382+
scope.Set("count", new ConvertibleCount(1).ToPython());
383+
scope.Exec(@"
384+
class Text(str):
385+
pass
386+
387+
class BigInt(int):
388+
def __str__(self):
389+
return Text(int(self))
390+
391+
matches = count + BigInt(10 ** 25) == 10 ** 25 + 1
392+
");
393+
Assert.IsTrue(scope.Get<bool>("matches"));
394+
}
395+
335396
[Test]
336397
public void InheritedOperatorsKeepWinning()
337398
{

‎src/embed_tests/TestPythonException.cs‎

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,115 @@ def CallThrow():
349349
}
350350
}
351351

352+
[Test]
353+
public void ErrorRaisedAtTheRecursionLimitReachesPython()
354+
{
355+
using var _ = Py.GIL();
356+
using var scope = Py.CreateScope();
357+
scope.Set("target", new ReentrantCaller().ToPython());
358+
// managed code calls back into Python until the recursion limit, so the error is decoded right at it
359+
scope.Exec(@"
360+
import sys
361+
limit = sys.getrecursionlimit()
362+
sys.setrecursionlimit(200)
363+
364+
def handler():
365+
target.Call(handler)
366+
367+
try:
368+
target.Call(handler)
369+
error = ''
370+
except RecursionError as e:
371+
error = str(e)
372+
finally:
373+
sys.setrecursionlimit(limit)
374+
");
375+
StringAssert.Contains("maximum recursion depth exceeded", scope.Get<string>("error"));
376+
}
377+
378+
[Test]
379+
public void DecodingKeepsARecursionLimitSetWhileItRuns()
380+
{
381+
using var _ = Py.GIL();
382+
using var scope = Py.CreateScope();
383+
// decoding reads attributes of the error, and this one changes the limit when it is read
384+
scope.Exec(@"
385+
import sys
386+
limit = sys.getrecursionlimit()
387+
388+
class LimitError(Exception):
389+
def __getattr__(self, name):
390+
sys.setrecursionlimit(250)
391+
raise AttributeError(name)
392+
");
393+
try
394+
{
395+
Assert.Throws<PythonException>(() => scope.Exec("raise LimitError('boom')"));
396+
Assert.AreEqual(250, scope.Eval<int>("sys.getrecursionlimit()"));
397+
}
398+
finally
399+
{
400+
scope.Exec("sys.setrecursionlimit(limit)");
401+
}
402+
}
403+
404+
[Test]
405+
public void ErrorIsDecodedAtTheHighestRecursionLimit()
406+
{
407+
using var _ = Py.GIL();
408+
using var scope = Py.CreateScope();
409+
scope.Exec(@"
410+
import sys
411+
limit = sys.getrecursionlimit()
412+
sys.setrecursionlimit(2147483647)
413+
");
414+
try
415+
{
416+
var error = Assert.Throws<PythonException>(() => scope.Exec("raise ValueError('boom')"));
417+
Assert.AreEqual("boom", error.Message);
418+
Assert.AreEqual(2147483647, scope.Eval<int>("sys.getrecursionlimit()"));
419+
}
420+
finally
421+
{
422+
scope.Exec("sys.setrecursionlimit(limit)");
423+
}
424+
}
425+
426+
[Test]
427+
public void ErrorWhoseStrRaisesArrivesAsItself()
428+
{
429+
using var _ = Py.GIL();
430+
using var scope = Py.CreateScope();
431+
scope.Exec(@"
432+
class Unprintable(Exception):
433+
def __str__(self):
434+
raise KeyError('from str')
435+
");
436+
var error = Assert.Throws<PythonException>(() => scope.Exec("raise Unprintable('original')"));
437+
Assert.AreEqual("Unprintable", error.Type.Name);
438+
Assert.AreEqual("original", error.Message);
439+
}
440+
441+
[Test]
442+
public void ErrorWhoseStrRaisesIsNamedAfterItsTypeWithoutATextArgument()
443+
{
444+
using var _ = Py.GIL();
445+
using var scope = Py.CreateScope();
446+
// the type name is not ASCII
447+
scope.Exec("class D\u00e9faut(Exception):\n def __str__(self):\n raise KeyError('from str')\n");
448+
var error = Assert.Throws<PythonException>(() => scope.Exec("raise D\u00e9faut(1, 2)"));
449+
Assert.AreEqual("D\u00e9faut", error.Message);
450+
}
451+
452+
public class ReentrantCaller
453+
{
454+
public void Call(PyObject callback)
455+
{
456+
using var _ = Py.GIL();
457+
callback.Invoke().Dispose();
458+
}
459+
}
460+
352461
public class TestClass
353462
{
354463
public void ThrowException()

‎src/runtime/Converter.cs‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1034,8 +1034,13 @@ internal static bool ToPrimitive(BorrowedReference value, Type obType, out objec
10341034
if (obType == typeof(TimeSpan))
10351035
{
10361036
op = Runtime.PyObject_Str(value);
1037+
if (op.IsNull())
1038+
{
1039+
goto type_error;
1040+
}
10371041
TimeSpan ts;
1038-
var arr = Runtime.GetManagedString(op.Borrow()).Split(',');
1042+
var arr = Runtime.GetManagedSpan(op.Borrow(), out var timeSpanText).ToString().Split(',');
1043+
timeSpanText.Dispose();
10391044
op.Dispose();
10401045
string sts = arr.Length == 1 ? arr[0] : arr[1];
10411046
if (!TimeSpan.TryParse(sts, out ts))
@@ -1370,6 +1375,10 @@ internal static bool ToPrimitive(BorrowedReference value, Type obType, out objec
13701375
}
13711376
case TypeCode.Decimal:
13721377
op = Runtime.PyObject_Str(value);
1378+
if (op.IsNull())
1379+
{
1380+
goto type_error;
1381+
}
13731382
decimal m;
13741383
var sm = Runtime.GetManagedSpan(op.Borrow(), out var newReference);
13751384
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
13911400

13921401
// fallback to string parsing for types such as numpy
13931402
op = Runtime.PyObject_Str(value);
1403+
if (op.IsNull())
1404+
{
1405+
goto type_error;
1406+
}
13941407
var sdt = Runtime.GetManagedSpan(op.Borrow(), out var reference);
13951408
if (!DateTime.TryParse(sdt, out var dt))
13961409
{

0 commit comments

Comments
 (0)