Skip to content

Fixed crash in ToArray when sequence explicitly denies __len__ #1484

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
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
23 changes: 16 additions & 7 deletions src/runtime/converter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<object>();
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)
{
Expand Down