Fix: Prevent out-of-bounds read in mi_ctz_generic32 and mi_clz_generic32 #1088
+4
−2
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.
This patch ensures that both mi_ctz_generic32 and mi_clz_generic32 perform safe indexing into the de Bruijn lookup tables by masking the computed index with
& 31.On platforms where unsigned long is 64-bit, the result of the de Bruijn multiplication and shift could exceed the valid index range (0–31), leading to an out-of-bounds read.
This change applies a bitwise AND mask to the final index:
mi_ctz_generic32: debruijn[(((x & -(int32_t)x) * 0x077CB531U) >> 27) & 31]mi_clz_generic32: debruijn[((x * 0x07C4ACDDU) >> 27) & 31]This matches the fix applied in python/cpython#134070 to its integrated mimalloc copy.
Fixes: python/cpython#134070