Repository navigation
Enable the UBSan check for unsigned integer overflows - #120906
Conversation
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
|
Workflow [PR], commit [141978a] Summary: ✅
AI ReviewSummaryEnables fatal unsigned-overflow checks in UBSan builds, marks intentional wrapping arithmetic, and fixes several overflow paths. Reviewed PR head Findings❌ Blockers
Missing context / blind spots
Final VerdictStatus: ❌ Block Fix or explicitly track the two retained correctness issues. Complete the full CI rerun required by the review-thread gate. Existing dismissed threads remain resolved; no duplicate inline comments were posted. |
…yReduceInRanges` The rewrite of the negative-index branch turned an index pointing before the array start into a clamp to the array start, where the previous code left the range empty: `end - begin + index` wrapped around, so the `> 0` test passed and `local_begin` became a huge value that no loop entered. The comment above the branch asks for the same behaviour as `arraySlice`, and `arraySlice([1, 2, 3, 4, 5], -7, 2)` is `[]`. Select that empty range explicitly instead. Checked against the pre-change semantics for every index in `-8..8` and every length in `0..8`, and `01096_array_reduce_in_ranges` reproduces all 24 of its reference values again. Reported by Fast test on #120906. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The `offsets[i - 1]` -> `offsets[static_cast<ssize_t>(i) - 1]` rewrite also landed where the index is already signed and the cast is a no-op, which `clang-tidy` reports as `readability-redundant-casting`. The two such casts in `ColumnArray.h` failed 1658 objects on their own, almost every translation unit including that header. Remove the cast at those 26 sites; the places where the index is `size_t`, which are the point of the rewrite, stay as they are. Four sites in `arrayFold.cpp` are included that the failing build had not reported yet. Reported by Build (arm_tidy) on #120906. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`contrib/CMakeLists.txt` passes the `-fno-sanitize=` options through `add_compile_options`, which is language-agnostic, so they reach the `ASM_NASM` sources of `isa-l` on amd64 as well. `nasm` has no `-fno-` option: it reads `-fno-sanitize=unsigned-integer-overflow` as `-f no-sanitize=unsigned-integer-overflow`, an output format, which overrides the `-f elf64` in front of it, and the build stops with `nasm: fatal: unrecognised output format`. Scope both options to `C`, `CXX` and `ASM`, the way the `-gz=zlib` option in the root `CMakeLists.txt` already does for this very target. That makes the `REMOVE_ITEM` workaround in `contrib/isa-l-cmake/CMakeLists.txt` unnecessary: it stripped `-fno-sanitize=undefined` from every language of `_isal`, its C sources included, so removing it also gives `isa-l`'s C code the opt-out back. `configure` and `generate` pass locally, every contrib C/C++ translation unit still carries both options, and none of ours does. Reported by Build (amd_asan_ubsan) on #120906. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…at startup With `-fno-sanitize-recover=all` the first report ends the process, so each of these stopped its job before a single test ran: - `base/base/itoa.cpp`, `shiftedPointer`: the offset is negative when a masked AVX-512 store writes the last digits, and the address is deliberately wrapped around - which is why the arithmetic goes through `uintptr_t` instead of the pointer. Reached from `writeIntText`, so it fired on the first integer formatted, during `clickhouse local --version` in `install.sh`, on both amd jobs. It needs `ALWAYS_INLINE_NO_SANITIZE_UNSIGNED_OVERFLOW`: `no_sanitize` does not survive a separate `__attribute__((always_inline))`, which is what the function had. - `base/glibc-rseq/rseq.c`, `rseq_cpu_id`: `__rseq_offset` is negative on aarch64, where TLS variant I places `struct pthread` below the thread pointer, so `(uintptr_t)tp + __rseq_offset` wraps by design. It runs during static initialization, through gRPC's `sched_getcpu`, so every aarch64 binary aborted before `main`. Annotated in the source rather than added to the ignorelist, because ccache does not hash the ignorelist file and would keep serving the old object. - `src/Compression/tests/gtest_compressionCodec.cpp`, `SequentialGenerator`: a negative stride is the documented way of asking an unsigned type for `0xFF, 0xFE, 0xFD, ...`, so the product is meant to wrap. It fired while gtest registered the parameters, before any test body, so `unit_tests_dbms` produced no result file at all. The multiplication moves into a named helper carrying the attribute, since `no_sanitize` does not reach a lambda body. Clearing these three is what lets the jobs get past startup; the locations the tests themselves reach are still ahead. Reported by Stateless tests (amd_asan_ubsan, arm_asan_ubsan) and Unit tests (asan_ubsan) on #120906. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`DDCompatibilityTestSequence` walks the DoubleDelta corner points, which are negative, so over an unsigned `ValueType` each addition of `curr = dd + prev + prev_delta` / `prev_delta = dd + prev_delta` wraps around - the sequence that wrapping produces is what the compatibility test encodes. Only the `UInt64` instantiation reports: for the narrower types the `Int64` accumulators can represent the whole unsigned range, so the usual arithmetic conversions make the additions signed. It fired while gtest registered the parameters of `CodecTestCompatibility`, before any test body, so `unit_tests_dbms` again produced no result file. All three additions move into one annotated helper: `no_sanitize` does not reach a lambda body, and annotating each addition separately would still leave the accumulators unsigned. Annotated in the source rather than through `tests/ubsan_ignorelist.txt`, which ccache does not hash. The previous three annotations hold: the stateless jobs get past startup and pass. Reported by Unit tests (asan_ubsan) on #120906. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`-static_cast<UInt64>(x)` is the overflow-free way to get `|x|` including the minimum value of the type, so the negation wraps around by design - and UBSan reports it through `__ubsan_handle_negate_overflow`, whose message reads `negation of 18446744073709551493 cannot be represented in type 'UInt64'` and never contains the words "unsigned integer overflow". The whole family is therefore invisible to a log or corpus search for that phrase, which is how these two got through the first pass: - `src/Functions/digits.cpp:205`, hit by `04402_digits` (`SELECT digits(-123, 1)`) on the arm stateless job. The file does annotate `executeImpl`, but the arithmetic lives in the lambda passed to `castTypeToEither`, and the attribute does not reach a lambda body - the same trap as the generator in `gtest_compressionCodec`, from the other side. - `src/Functions/array/arrayReduceInRanges.cpp:270` on the amd stateless job, where no annotation was present at all. Both took the server down mid-suite (`-fno-sanitize-recover=all`), so the run stopped after 64 and 84 tests respectively. `common::negateIgnoreOverflow` already exists for exactly this and is annotated with `NO_SANITIZE_UNDEFINED`, which this PR extends to cover the new check, so routing the idiom through it needs no new helper and is immune to where the expression sits. Applied to all 12 occurrences in `src/`, not only the two that reported, since each of the others is the same latent report: `InterpreterSelectQuery`, `Planner`, `AggregateFunctionFlameGraph`, `bitSlice`, `LowCardinalityExecutionHelpers`, `GatherUtils/Algorithms`, `FunctionDateOrDateTimeAddInterval`, `arrayElement` (x2), `WindowTransform` (x2). Reported by Stateless tests (arm_asan_ubsan, targeted) and Stateless tests (amd_asan_ubsan, distributed plan, parallel, selected tests) on #120906. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… stop relying on `npos + 1`
The previous commit converted `-static_cast<UIntN>(x)`, which is only one spelling of the same
thing. Three more reports followed, each from a shape that regex could not match:
- `src/Functions/overlay.cpp:215`, hit by `03205_overlay` (`overlay('Spark SQL', '__', -12)`): the
cast is to `size_t`. There are 23 such casts in `src/`, all the same magnitude idiom, and all now
go through `common::negateIgnoreOverflow`. `getValidOffset` is restructured rather than annotated,
because the `input_size + offset` right after it wraps just as much and would have reported next.
- `src/Storages/StorageGenerateRandom.cpp:156`, hit by the `FunctionsStress` unit test: the
branchless sign mask `-(u_number >> (sizeof(T) * 8 - 1))` negates a shift, with no cast at all.
- `src/Backups/registerBackupEngineAzureBlobStorage.cpp:56`, hit by
`BackupInfo.DestinationIdentityIgnoresAzureCredentials`: this one is not an idiom to annotate.
`removeFileNameFromURL` depends on `find_last_of` returning `npos` and `npos + 1` wrapping to `0`
to mean "the whole path is the file name" - correct by accident, for a URL whose path has no `/`.
The `npos` case is now written out, on both that line and the `resize` after it.
`base/base/wide_integer_impl.h:354` has the same idiom and is left alone: it is inside the file's
`#pragma clang attribute push` region, which already covers this check.
The three annotations before this held: `digits` and `arrayReduceInRanges` no longer report, gtest
registration completes (21014 tests across 732 suites, against none before), and the runs now reach
205 unit tests and ~50 stateless tests before the next abort.
Reported by Stateless tests (arm_asan_ubsan, targeted) and Unit tests (asan_ubsan) on
#120906.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ash fold Three more sites, one of them a real bug: - `src/AggregateFunctions/AggregateFunctionQuantileInterpolatedWeighted.cpp:290`, reported by `02319_quantile_interpolated_weighted` on both stateless jobs (one site, two failures). `end = mid - 1` underflows to `SIZE_MAX` when `mid` is 0, and the loop then exits through the `if (mid > size) break` guard, which exists only to catch that wrapped value - unsigned wraparound used as the loop-exit mechanism. It gives the right answer today, which is why it went unnoticed. Rewritten half-open (`while (start < end)`, `end = mid`), so nothing underflows and the guard is gone. Not annotated: this is the `size - 1` class of bug the check is meant to find. - `src/IO/readFloatText.cpp:102`, reported by `FunctionsStress` through `parseReadableSize`: the SWAR "are these eight bytes all digits" trick credited to johnnylee-sde, whose carry between the packed bytes is the mechanism. Annotated. The same algorithm in contrib's `fast_float` is excluded by `contrib/CMakeLists.txt`, but this copy is ours. - `src/Columns/tests/gtest_compute_hash_into.cpp:1227` and `:1229`, reported by `ComputeHashInto.ReprIndependenceObjectSplit`: the object hash folds its non-typed `(path, value)` pairs with a wrapping `UInt32` sum, and the assertion right below states that commutative fold as the contract. Both additions go through one annotated helper. Every site found so far is now clear, and each cycle reaches further: the unit tests are at 483 of 21018 passing (0, then 205 in the two rounds before), the stateless suites at 100 and 163. Reported by Stateless tests (arm_asan_ubsan, targeted), Stateless tests (amd_asan_ubsan, distributed plan, parallel, selected tests) and both Unit tests (asan_ubsan) jobs on #120906. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
None of these is deliberate wraparound, so none is annotated: - `src/Functions/array/arrayShiftRotate.cpp:200`, from `arrayRotateLeft` on an empty array in `FunctionsStress`: the `nested_size > 0` guard on the line above skips the modulo, so `nested_size - shift_num` computes `0 - 2`. Harmless only because the loop that consumes the result does not run for an empty array. The whole reduction now happens under one guard. - `src/Common/Arena.h:217` and `:230`, from `Arena.TooLargeAllocationIsRejected`: `alloc` and `alignedAlloc` added `size` to `used_bytes` *before* `addMemoryChunk`, which throws for a size it cannot serve. Every rejected allocation therefore left `usedBytes()` permanently wrong, and the test's two consecutive rejections (`SIZE_MAX`, then `SIZE_MAX - 1024`) wrapped it. The counter now moves only once the memory exists, which is also the only point at which it cannot overflow. - `src/Storages/MergeTree/MergeTreePrefetchedReadPool.cpp:630`, from a plain `SELECT`: `need_marks -= marks_to_get_from_part` with `362 - 1084`. The loop above overshoots the budget on purpose, adding the tail of a range shorter than one prefetch step after the budget is met, and the subtraction then wrapped to a near-`SIZE_MAX` value - so the thread kept taking work and the prefetch distribution skewed. `need_marks` counts what is left to hand out rather than marks that exist, so it saturates; the two subtractions next to it are inventories and stand as they were. Two stateless jobs are now green through their whole selection (238 and 12 tests), and the runs reach 666 of 21020 unit tests and 3244 of 12365 stateless tests, from zero three rounds ago. Reported by Unit tests (asan_ubsan), Unit tests (asan_ubsan, function_prop_fuzzer) and Stateless tests (arm_asan_ubsan, targeted) on #120906. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Build profile diff (arm_release)Comparing Binary sizes
The official master build is compiled with Object file sizes
|
| Object file | Master | PR | Δ |
|---|---|---|---|
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantileExact… |
7.48 MiB | 7.16 MiB | -332.99 KiB (-4.35%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantileDeter… |
3.13 MiB | 2.90 MiB | -243.78 KiB (-7.59%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantileInter… |
3.92 MiB | 3.77 MiB | -154.51 KiB (-3.85%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantileTimin… |
1.89 MiB | 1.93 MiB | +44.73 KiB (+2.31%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantileBFloa… |
2.45 MiB | 2.41 MiB | -36.95 KiB (-1.48%) |
src/CMakeFiles/dbms.dir/Interpreters/Aggregator.cpp.o |
33.74 MiB | 33.76 MiB | +24.65 KiB (+0.07%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantileGK.cp… |
3.69 MiB | 3.71 MiB | +24.30 KiB (+0.64%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantileTDige… |
2.26 MiB | 2.28 MiB | +23.42 KiB (+1.01%) |
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.
Compile time of recompiled translation units
4339 translation units recompiled, 15325 s compile time in total, 4339 of them have a recent master baseline.
…eadpassphrase` The `isalpha` macro of musl subtracts `a` from the unsigned code of the character, which wraps around for every character below it and aborted the interactive TOTP prompt of the client under the unsigned overflow check. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120906&sha=2b47d6df33b08d446fcc4a7b425ea929cc30ac54&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20targeted%29 #120906 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120906&sha=0452ad4c9f30e4657e0d77f078589dbc6fa697a6&name_0=PR&name_1=Performance%20Comparison%20%28amd_release%2C%20master_head%2C%201%2F8%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. It was the only red job on 0452ad4:
So it looks sensitive to code layout rather than to a specific change, like the tests in #100759. #127697 already made it single-threaded, and that was not enough. |
|
Acknowledged. I'm investigating the |
… a large one `QuantileTiming::mergeSlow` inserted the values of a `tiny` or `medium` state into a `large` one with the unchecked `QuantileTimingLarge::insert`, but the `large` state may hold a sum of weights that is already the maximum of `UInt64`, which wrapped the count and the bin around (`30000` instead of an error). The merges and the additions to an existing `large` state now use `insertChecked`; only the conversion of a smaller kind into a new `large` state keeps the unchecked `insert`, which cannot overflow there. #120906 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ger-overflow # Conflicts: # src/Disks/DiskObjectStorage/ObjectStorages/StoredObject.cpp
…around (new master code) The broker reports the last sequence identifier -1 for a producer that has not published anything yet, which `Producer` turned into zero by wrapping the maximum of `UInt64` around. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120906&sha=f119746bfedf7858a146364111b546243339973f&name_0=PR&name_1=Unit%20tests%20(asan_ubsan) #120906 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Fixing PR: #133621. With groups of 8 rows, about 75% of each query was per-group work (group-end search, the |
…leTiming` state The checked insertion in `QuantileTiming::add` made `quantileTiming` with `GROUP BY RegionID` 22% slower. A state that rows are added to one by one is built from such rows, and its count grows by one, so only the merges of a smaller kind into a `large` state, which may hold a sum of weights, keep the checked insertion. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120906&sha=0ca8e732e562ab8179dacd0bfbc4cecfdbd0cf75&name_0=PR&name_1=Performance%20Comparison%20(arm_release%2C%20master_head%2C%207%2F8) #120906 Co-Authored-By: Claude Opus 5.5 <[email protected]>
UBSan does not check unsigned integer overflow by default, because overflow of an unsigned integer
is not undefined behaviour: it wraps around modulo 2N. An unintended wraparound is
nevertheless a bug, and usually a nasty one -
size - 1of an empty container, an offset that runsbehind a buffer, a capacity calculation that silently truncates. UBSan has a separate
unsigned-integer-overflowcheck for exactly this, which OSS-Fuzz enables as well, so this pullrequest turns it on for our UBSan builds and annotates the places that wrap around on purpose.
Third-party code is not annotated. Compiled third-party code gets
-fno-sanitize=unsigned-integer-overflowfromcontrib/CMakeLists.txt; header-only third-partycode, which is compiled as a part of our own translation units, and the third-party trees vendored
under
base/(Poco, PCG, the musl-derived compatibility code) are excluded intests/ubsan_ignorelist.txt. The 128/256-bit integer implementation says so in its own#pragma clang attributeregion, which it already had for theundefinedchecks.Our own code uses the new
NO_SANITIZE_UNSIGNED_OVERFLOWattribute.NO_SANITIZE_UNDEFINEDswitches this check off as well: a function that is already allowed to overflow signed integers is,
in practice, always a function that is allowed to wrap around unsigned integers too, and requiring a
second annotation in every such place would only make it easier to forget one of them. That covers
most of the arithmetic functions, the aggregate functions and the rounding code for free.
The rest of the diff is of three kinds.
offsets[i - 1]idiom (the bulk of it, ~370 places).PaddedPODArraykeeps zeroed paddingbefore the first element, which is why an array of offsets can be read with
offsets[i - 1]without a special case for the first element - the array's subscript takes an
ssize_t. But withan unsigned
ithe subtraction happens before the call and wraps. The index is now made signedfirst, which is what a few places in the tree already did.
generators, delta codecs, DWARF and number parsing, negative array indices, date/time arithmetic
over the unsigned domain - now say so with the attribute.
obscure, bugs:
ColumnIndex::insertIndexesRangecomputedstart + length - 1for an empty range, and thewrapped-around maximum index then widened the index type all the way.
MergeTreeIndexGranularityConstant::getRowsCountInRangeclampsendto the lastconstant-granularity mark, which can put it before
begin; the product then wrapped into anonsense row count.
ReadFromMergeTreedecremented the per-stream mark budget by the size of a part that could bebigger than the budget, so the counter wrapped instead of reaching zero and the stream went on
to swallow every remaining part.
getCompressedDataSizeof theDoubleDeltacodec was called with a wrapped-around size for aninput shorter than two items. (Its 32-bit bit count still wraps for a block above ~500 MB, as do
the
FPCandGorillabounds;CompressionCodecMultipleonmasterrelies on that wrap toreject long codec chains, so this is annotated here and left for a separate fix.)
MutateTaskdecremented the per-stream file count below zero when several commands touched thesame stream; the LogsQL civil-date helpers added a negative
intto anunsignedmonth; theSEEK_CURtargets of several read buffers wrapped for every backward seek;getTotalSizeofstored objects wrapped
UnknownSizeinto a bogus byte count.ZstdDeflatingWriteBuffermeasured the compressed output by subtracting buffer offsets takenbefore and after a loop that can flush the buffer in between and reset the offset.
ThreadPool::setMaxThreads,ProgressIndication,DecomposedFloat,arrayReduceInRanges,Volnitsky,reinterpretAs,ColumnTuple::popBack.The
i-- > 0reverse-loop idiom wraps around on the last iteration by construction; the ten placesin our own code that used it now decrement inside the body.
One build change comes with it: the extra instrumentation pushes
src/Interpreters/Aggregator.cppover the per-translation-unit memory limit of sanitizer builds (
LLVM ERROR: out of memoryin theAssignment Tracking Analysispass). Measured on aarch64 with Clang 21: it peaks at 11.0 GB ofvirtual memory with the check and 9.9 GB without, against a limit of 10 GB - that is, the file has
been sitting right at the limit for a while.
prlimit_sanitizers.shnow allows 15 GB.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Enable the
unsigned-integer-overflowcheck in UBSan builds in CI, and annotate the code that wraps around on purpose. This found several latent bugs in reading, compression and query planning.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/120906]
Version info
26.12.1.264-master(included in26.12and later)