From b52823b3c8cc09916a309d0b99ea792a81d9a9f0 Mon Sep 17 00:00:00 2001 From: Victor Nova Date: Tue, 6 Jul 2021 17:33:10 -0700 Subject: [PATCH] fixed crash in ToArray when sequence explicitly denies __len__ port of 8e1d4dbf7b0e647482b302bf2ce7ad36f0b9d0f5 --- src/runtime/converter.cs | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/src/runtime/converter.cs b/src/runtime/converter.cs index 7cee0890c..936f8b248 100644 --- a/src/runtime/converter.cs +++ b/src/runtime/converter.cs @@ -882,17 +882,26 @@ private static bool ToArray(IntPtr value, Type obType, out object result, bool s // See https://docs.microsoft.com/en-us/dotnet/api/system.type.makegenerictype#System_Type_MakeGenericType_System_Type var constructedListType = typeof(List<>).MakeGenericType(elementType); bool IsSeqObj = Runtime.PySequence_Check(value); + object[] constructorArgs = Array.Empty(); if (IsSeqObj) { var len = Runtime.PySequence_Size(value); - list = (IList)Activator.CreateInstance(constructedListType, new Object[] { (int)len }); - } - else - { - // CreateInstance can throw even if MakeGenericType succeeded. - // See https://docs.microsoft.com/en-us/dotnet/api/system.activator.createinstance#System_Activator_CreateInstance_System_Type_ - list = (IList)Activator.CreateInstance(constructedListType); + if (len >= 0) + { + if (len <= int.MaxValue) + { + constructorArgs = new object[] { (int)len }; + } + } + else + { + // for the sequences, that explicitly deny calling __len__() + Exceptions.Clear(); + } } + // CreateInstance can throw even if MakeGenericType succeeded. + // See https://docs.microsoft.com/en-us/dotnet/api/system.activator.createinstance#System_Activator_CreateInstance_System_Type_ + list = (IList)Activator.CreateInstance(constructedListType, args: constructorArgs); } catch (Exception e) {