Skip to content

Commit ff45f3e

Browse files
jhonabreulclaude
andcommitted
Fix undetected integer overflow when converting to Int64 on 32-bit
On 32-bit, the TypeCode.Int64 path uses PyLong_AsLongLong, whose wrapper returns a nullable long? that is null when the Python int does not fit in a long long (with a Python OverflowError left set). The overflow check compared the nullable to -1 (`num == -1`), which is never true for null, so an overflowing value bypassed the check and was returned as a successful conversion with a null result. Check num.HasValue instead so overflow propagates as a failed conversion. This is why TestConverter.ConvertOverflow failed only on Windows x86: on x64 the Int64 case takes the else branch (PyLong_AsSignedSize_t, a 64-bit nint) whose `num == -1 && ErrorOccurred()` check works correctly. The CI matrix only builds x86 on Windows, so the 32-bit bug surfaced only there. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
1 parent 97fbe85 commit ff45f3e

1 file changed

Lines changed: 8 additions & 2 deletions

File tree

src/runtime/Converter.cs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1151,11 +1151,17 @@ internal static bool ToPrimitive(BorrowedReference value, Type obType, out objec
11511151
goto type_error;
11521152
}
11531153
long? num = Runtime.PyLong_AsLongLong(value);
1154-
if (num == -1 && Exceptions.ErrorOccurred())
1154+
// PyLong_AsLongLong already returns null when the value
1155+
// does not fit in a long long (it leaves a Python
1156+
// OverflowError set). Comparing the nullable to -1 never
1157+
// matched that null, so on 32-bit an overflowing value
1158+
// was silently accepted and returned as a null result.
1159+
// Check HasValue so the overflow propagates.
1160+
if (!num.HasValue)
11551161
{
11561162
goto convert_error;
11571163
}
1158-
result = num;
1164+
result = num.Value;
11591165
return true;
11601166
}
11611167
else

0 commit comments

Comments
 (0)