Repository navigation
fix(utils): prevent 32-bit shift overflow and UB in ceil_log2 on 64-bit Windows - #246
hrishikeshpathak1009 wants to merge 1 commit into
Conversation
…it Windows
On 64-bit Windows (LLP64), unsigned long is 32 bits while size_t is 64 bits. Evaluating (1UL << ret) where ret >= 32 (for x >= 2^32) invokes undefined behavior due to shifting a 32-bit type by >= 32 bits, causing wrong return values on x86/x64 hardware (e.g. ceil_log2(2^32) evaluated 1UL << 32 as 1, erroneously returning 33).
- Replace 1UL with size_t{1} to match size_t width
- Guard degenerate inputs (x <= 1 -> 0)
- Guard ret against std::numeric_limits<size_t>::digits before shifting
- Add GoogleTest unit tests in tests/unit/rabitqlib/utils/tools_test.cpp
|
Thanks for spotting the Closing this PR because it was not built and tested locally, which CONTRIBUTING requires for code PRs. Building it on Linux shows two failures:
The fix only needs |
|
Thank you for reviewing the PR and clarifying the expected behavior. I understand the conflicting test expectations and the formatting issue. I should also have built and tested the changes locally according to the contribution guidelines. I appreciate you acknowledging the underlying bug report and providing the clarification. I'll make sure to follow the project's build, test, and formatting requirements more carefully in future contributions. |
`1UL` is 32 bits on LLP64 (64-bit Windows), so ceil_log2 shifted past the operand width for inputs of 2^32 or more. No library code calls it. Reported in VectorDB-NTU#246.
Summary
Fixes undefined behavior and incorrect return values in
rabitqlib::ceil_log2()for inputs (\ge 2^{32}) on 64-bit Windows systems (LLP64 data model), and adds GoogleTest regression coverage.Problem & Root Cause
In
include/rabitqlib/utils/tools.hpp:Under the Windows x64 data model (LLP64),
sizeof(unsigned long) == 4(32 bits), whilesizeof(size_t) == 8(64 bits).For inputs (x \ge 2^{32}),
ret = floor_log2(x) >= 32. Shifting a 32-bit integer (1UL) by 32 or more positions invokes undefined behavior in C++ (ISO/IEC 14882, §7.6.7 [expr.shift]).On x86/x64 hardware, the shift count may be masked to 5 bits (
ret & 31), resulting in incorrect calculations:ceil_log2(1ULL << 32)may evaluate(1UL << 32) < (1ULL << 32)as1 < 4294967296, incorrectly returning33instead of32.ceil_log2(1ULL << 33)may evaluate the shifted value as2, incorrectly returning34instead of33.Solution
1ULwithsize_t{1}so the shift operand matches the width ofsize_t.x <= 1.std::numeric_limits<size_t>::digitsto prevent undefined shifts.tests/unit/rabitqlib/utils/tools_test.cpp, covering:size_tvalues, includingSIZE_MAX.Verification & Limitations
SIZE_MAX..clang-format.git diff --checkpassed without whitespace errors.