Repository navigation
Fix UBSan pointer-overflow in LimitSeekableReadBuffer::seek - #103434
alexey-milovidov merged 4 commits into
Conversation
Pre-PR Validation GateSession id: a) Deterministic repro? ✅ — identical line, column, and offset to the CI failure (STID 3079-3df0). b) Root cause explained? ✅ c) Fix matches root cause? ✅ d) Test intent preserved? ✅ e) Both directions demonstrated? ✅
f) Fix is general, not a narrow patch? ✅
|
|
cc @alexey-milovidov @CheSema — could you review? This fixes a UBSan |
|
Workflow [PR], commit [12681f1] Summary: ✅ AI ReviewSummaryThis PR fixes undefined behavior in ClickHouse Rules
Final Verdict
|
| /// on pointer differences. Computing `pos + position_change` directly is undefined behavior | ||
| /// when `pos` is null (e.g. when the inner buffer hasn't been materialized yet) or when | ||
| /// `position_change` is large enough that the resulting pointer escapes the allocation. | ||
| if (pos && working_buffer.begin() <= pos + position_change |
There was a problem hiding this comment.
pos && ... avoids the null-pointer case, but this still performs pos + position_change before bounds are checked. Pointer arithmetic itself is UB once the result leaves the allocation, so a large legal seek (within [0, limit_size]) can still trigger UB here.
Please switch this condition to integer arithmetic on pointer differences (as in your PR description), e.g. compare position_change against working_buffer.begin() - pos and working_buffer.end() - pos. That keeps the fast-path check defined for both null and non-null pos.
There was a problem hiding this comment.
Thanks — good catch. Applied in commit cc7aaa4, which restores the integer-arithmetic form (working_buffer.begin() - pos <= position_change && position_change <= working_buffer.end() - pos). This is defined for both pos == nullptr (pointer subtraction of two nulls is 0, check correctly falls through) and for non-null pos with any position_change (both pointers live in the same allocation, subtraction is defined and returns the signed offset). The pos && form landed via @CheSema's in-line suggestion commit on this PR but missed the large-legal-seek case, which is exactly what BackupWriterDefault → LimitSeekableReadBuffer::seek(base_size, SEEK_SET) produces in the backup path.
Reverts the `pos && ...` style accepted from @CheSema's suggestion. `clickhouse-gh[bot]` correctly pointed out that the `pos && ...` form still performs `pos + position_change` inside the condition, which is undefined behavior per [expr.add] once the resulting pointer leaves the allocation. The null-pointer short-circuit only guards the case where `pos == nullptr` and non-zero offset — it does not guard the case where `pos` is valid but `position_change` is large enough that the sum escapes the buffer's allocation. UBSan's `-fsanitize=pointer-overflow` catches both cases. The integer-arithmetic form (`working_buffer.begin() - pos <= position_change && position_change <= working_buffer.end() - pos`) is well-defined for all inputs: - pos is null: working_buffer.begin() and working_buffer.end() are also null (same uninitialized buffer), so both subtractions evaluate to 0. For any non-zero position_change the condition is false and we correctly fall through to the slow path. - pos is non-null: both pointers belong to the same allocation (the working buffer), so pointer subtraction is defined and returns the signed offset within the buffer. Mathematically identical to the original `pos + position_change` check for all legal inputs, but defined under UBSan regardless of pos validity or position_change magnitude. Ref: ClickHouse#103434 (comment)
|
Status update: the Detailed replies posted inline:
Waiting on re-review. cc @alexey-milovidov @CheSema |
|
Pushed empty commit The Fast test failures on Not code-related — the same DNS failure affected multiple unrelated PRs and master at the same time window (13:22–13:26 UTC, 2026-04-23):
Our fix only touches |
|
@groeneai When you see a failure like Unit tests (msan, function_prop_fuzzer) or similar -- investigate and fix it in a separate PR. |
…079-3df0) `LimitSeekableReadBuffer::seek` used the expression `pos + position_change` inside its in-buffer fast-path check. When the inner buffer has not materialized its memory yet — as is the case for `EmptyReadBuffer`, `ParallelReadBuffer`, and `ReadWriteBufferFromHTTP`, all of which start with `pos == nullptr` — and a non-zero seek is requested before the first `next()`, this triggers undefined behavior per [expr.add]: "applying non-zero offset N to null pointer". On master BuzzHouse (arm_asan_ubsan) this surfaced from the BACKUP write path as STID 3079-3df0: ``` src/IO/LimitSeekableReadBuffer.cpp:97:34: runtime error: applying non-zero offset 1178 to null pointer #0 DB::LimitSeekableReadBuffer::seek(long, int) ClickHouse#1 DB::BackupWriterDefault::copyDataToFile(...) ClickHouse#2 DB::BackupImpl::writeFile(...) ClickHouse#3 DB::BackupsWorker::writeBackupEntries(...) ``` Replace the pointer-arithmetic comparison with an equivalent check expressed via pointer *differences* and integer arithmetic, which is well-defined regardless of whether `pos` is null. The condition is mathematically identical to the original for all legal inputs. Add `gtest_limit_seekable_read_buffer.cpp` covering the null-`pos` regression plus two sanity tests for the in-buffer and out-of-buffer seek paths. Without the fix the first test reproduces the exact UBSan error from CI; with the fix all three pass cleanly under `-fsanitize=address,undefined`. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=4b8132993ce0625e9c0ed0bf15ed16eb6df8262b&name_0=MasterCI&name_1=BuzzHouse+%28arm_asan_ubsan%29
Reverts the `pos && ...` style accepted from @CheSema's suggestion. `clickhouse-gh[bot]` correctly pointed out that the `pos && ...` form still performs `pos + position_change` inside the condition, which is undefined behavior per [expr.add] once the resulting pointer leaves the allocation. The null-pointer short-circuit only guards the case where `pos == nullptr` and non-zero offset — it does not guard the case where `pos` is valid but `position_change` is large enough that the sum escapes the buffer's allocation. UBSan's `-fsanitize=pointer-overflow` catches both cases. The integer-arithmetic form (`working_buffer.begin() - pos <= position_change && position_change <= working_buffer.end() - pos`) is well-defined for all inputs: - pos is null: working_buffer.begin() and working_buffer.end() are also null (same uninitialized buffer), so both subtractions evaluate to 0. For any non-zero position_change the condition is false and we correctly fall through to the slow path. - pos is non-null: both pointers belong to the same allocation (the working buffer), so pointer subtraction is defined and returns the signed offset within the buffer. Mathematically identical to the original `pos + position_change` check for all legal inputs, but defined under UBSan regardless of pos validity or position_change magnitude. Ref: ClickHouse#103434 (comment)
7260d79 to
12681f1
Compare
|
Thanks @nikitamikhaylov, agreed. The The CI run you linked (commit Just rebased this branch onto current master (new HEAD |
LLVM Coverage Report
Changed lines: 96.88% (31/32) | lost baseline coverage: 2 line(s) · Uncovered code |
|
Need this to fix 26.4 CI |
LimitSeekableReadBuffer::seekusedpos + position_changeinside itsin-buffer fast-path check. When the inner buffer has not materialized
its memory yet — as is the case for
EmptyReadBuffer,ParallelReadBuffer, andReadWriteBufferFromHTTP, all of which startwith
pos == nullptr— and a non-zero seek is requested before thefirst
next, this triggers undefined behavior per [expr.add]:"applying non-zero offset N to null pointer".
On master
BuzzHouse (arm_asan_ubsan)this surfaced from the BACKUPwrite path as STID 3079-3df0:
Root cause.
BackupEntryFromAppendOnlyFile::getReadBufferwraps theunderlying disk read buffer with
LimitSeekableReadBuffer. Some innerbuffer types start with
pos == nullptruntil the first read. WhenBackupWriterDefault::copyDataToFileimmediately callsread_buffer->seek(base_size, SEEK_SET)on such a wrapper, the fast-pathcheck computes
nullptr + position_change, which is UB.Fix. Replace the pointer-arithmetic comparison with an equivalent
check expressed via pointer differences and integer arithmetic, which
is well-defined regardless of whether
posis null. The condition ismathematically identical to the original for all legal inputs (for
non-null
poswithin the working buffer,begin - posandend - posare valid
ptrdiff_tvalues; for an empty buffer with nullposthecheck only accepts
position_change == 0, matching the original).Test. Added
gtest_limit_seekable_read_buffer.cppwith threescenarios:
SeekOnInnerBufferWithNullPos— regression test that reproduces theexact UBSan error from CI (
runtime error: applying non-zero offset 1178 to null pointer) when the fix is reverted.SeekInsideMaterializedBuffer— sanity check for the normalin-buffer fast-path.
SeekOutsideMaterializedBuffer— sanity check for the slow-pathwhere the seek target is outside the working buffer.
All three pass under
-fsanitize=address,undefinedwithUBSAN_OPTIONS=halt_on_error=1. Without the fix the first testdeterministically triggers the CI UBSan error at the exact same
location (line 97, column 34, offset 1178).
CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=4b8132993ce0625e9c0ed0bf15ed16eb6df8262b&name_0=MasterCI&name_1=BuzzHouse+%28arm_asan_ubsan%29
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix undefined behavior in
LimitSeekableReadBuffer::seekwhen the wrapped inner buffer has not been materialized yet. The fast-path in-buffer check performed pointer arithmetic on a possibly-nullpos, which UBSan reports as "applying non-zero offset to null pointer". Triggered from the BACKUP write path in debug/sanitizer builds.Documentation entry for user-facing changes