Repository navigation
Avoid overflow in integer modulus and floor division opcodes - #575
Open
raashish1601 wants to merge 1 commit into
Open
raashish1601 wants to merge 1 commit into
raashish1601 wants to merge 1 commit into
Conversation
INT_MIN % -1 and INT_MIN // -1 overflow in C and crash the process on x86. The floor-modulus fixup ((a % b) + b) % b also overflowed for divisors close to the integer limits, e.g. -1 % INT_MIN gave INT_MAX. Handle b == -1 explicitly and only add b when the remainder and the divisor have different signs, which matches NumPy.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
INT_MIN % -1andINT_MIN // -1overflow in C. On x86 this is a hardware trap, so evaluating them kills the whole Python process:The floor-modulus fixup
((a % b) + b) % balso overflows whenbis close to the integer limits, which gives wrong results instead of a crash. With int32,-1 % INT_MINreturns2147483647and-5 % INT_MINreturns2147483643; NumPy gives-1and-5.This handles
b == -1explicitly (%gives 0,//gives-acomputed in unsigned arithmetic, soINT_MIN // -1wraps toINT_MINlike NumPy), and only addsbto the C remainder when the remainder andbhave different signs, so the sum can't overflow. Same change for the int and long long opcodes, the same way the shift opcodes were guarded in #559.Added
test_mod_floordiv_extreme_values, which compares against NumPy for both dtypes. It crashes the interpreter on main and passes with this change. I built the extension in apython:3.12Docker image and rannumexpr.tests.test_numexpr(6043 passed). Also added a line to the release notes.