Skip to content

Fix UBSan pointer-overflow in LimitSeekableReadBuffer::seek - #103434

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-limit-seekable-read-buffer-ubsan-stid-3079
Apr 26, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-limit-seekable-read-buffer-ubsan-stid-3079

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

LimitSeekableReadBuffer::seek used 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)
  #1 DB::BackupWriterDefault::copyDataToFile(...)
  #2 DB::BackupImpl::writeFile(...)
  #3 DB::BackupsWorker::writeBackupEntries(...)

Root cause. BackupEntryFromAppendOnlyFile::getReadBuffer wraps the
underlying disk read buffer with LimitSeekableReadBuffer. Some inner
buffer types start with pos == nullptr until the first read. When
BackupWriterDefault::copyDataToFile immediately calls
read_buffer->seek(base_size, SEEK_SET) on such a wrapper, the fast-path
check 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 pos is null. The condition is
mathematically identical to the original for all legal inputs (for
non-null pos within the working buffer, begin - pos and end - pos
are valid ptrdiff_t values; for an empty buffer with null pos the
check only accepts position_change == 0, matching the original).

Test. Added gtest_limit_seekable_read_buffer.cpp with three
scenarios:

  1. SeekOnInnerBufferWithNullPos — regression test that reproduces the
    exact UBSan error from CI (runtime error: applying non-zero offset 1178 to null pointer) when the fix is reverted.
  2. SeekInsideMaterializedBuffer — sanity check for the normal
    in-buffer fast-path.
  3. SeekOutsideMaterializedBuffer — sanity check for the slow-path
    where the seek target is outside the working buffer.

All three pass under -fsanitize=address,undefined with
UBSAN_OPTIONS=halt_on_error=1. Without the fix the first test
deterministically 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):

  • CI Fix or Improvement (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fix undefined behavior in LimitSeekableReadBuffer::seek when the wrapped inner buffer has not been materialized yet. The fast-path in-buffer check performed pointer arithmetic on a possibly-null pos, 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

  • Documentation is written (mandatory for new features)

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR Validation Gate

Session id: cron:clickhouse-ci-task-worker:20260423-094500

a) Deterministic repro? ✅
build-asan/src/unit_tests_dbms --gtest_filter='LimitSeekableReadBuffer.SeekOnInnerBufferWithNullPos' with the fix reverted triggers:

src/IO/LimitSeekableReadBuffer.cpp:97:34: runtime error: applying non-zero offset 1178 to null pointer

— identical line, column, and offset to the CI failure (STID 3079-3df0).

b) Root cause explained? ✅
BackupEntryFromAppendOnlyFile::getReadBuffer wraps an inner SeekableReadBuffer that may not have materialized its memory yet (inner pos == nullptr for EmptyReadBuffer, ParallelReadBuffer, ReadWriteBufferFromHTTP). The LimitSeekableReadBuffer constructor adopts the inner buffer's pos, so it is also null. BackupWriterDefault::copyDataToFile immediately calls read_buffer->seek(base_size, SEEK_SET). In LimitSeekableReadBuffer::seek, the fast-path computes pos + position_change — pointer arithmetic with a non-zero offset on a null pointer, which is UB per [expr.add].

c) Fix matches root cause? ✅
The pointer-arithmetic expression is replaced with an equivalent check expressed via pointer differences and integer arithmetic: working_buffer.begin() - pos <= position_change && position_change <= working_buffer.end() - pos. Pointer subtraction of two pointers within the same allocation (or both null) is defined. No pointer arithmetic with offsets is performed. The new check also removes the latent second UB case (large position_change with valid pos escaping the allocation).

d) Test intent preserved? ✅
The condition is mathematically identical to the original for all legal inputs. For non-null pos inside a non-empty working buffer, begin - pos ≤ 0 ≤ end - pos, and the acceptable range for position_change is the same. For null pos with an empty buffer, both differences are 0 and the check only accepts position_change == 0 — matching original semantics in that degenerate case.

e) Both directions demonstrated? ✅

  • Without fix: UBSan reports runtime error: applying non-zero offset 1178 to null pointer at LimitSeekableReadBuffer.cpp:97:34 — exact CI failure reproduction. Test fails.
  • With fix: All three new tests pass under -fsanitize=address,undefined with UBSAN_OPTIONS=halt_on_error=1 print_stacktrace=1. Broader IO unit test suite (23 tests) also passes.

f) Fix is general, not a narrow patch? ✅

  • grep for pos + position_change and buffer().begin() <= pos across src/ returned only the fixed line — the dangerous pattern exists in no other file.
  • The fix targets the arithmetic pattern itself, not the specific null-pointer case: a defensive if (pos != nullptr) would only cover the caught case but would still UB when pos is valid and position_change is large enough to escape the allocation. The new integer-arithmetic check is safe in both scenarios.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @CheSema — could you review? This fixes a UBSan pointer-overflow bug in LimitSeekableReadBuffer::seek (STID 3079-3df0 on master BuzzHouse arm_asan_ubsan) by swapping the fast-path pointer-arithmetic check for an equivalent integer-arithmetic check on pointer differences, which is defined even when pos is null. Added a gtest that reproduces the exact CI UBSan error without the fix.

@CheSema CheSema self-assigned this Apr 23, 2026
Comment thread src/IO/LimitSeekableReadBuffer.cpp Resolved
@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Apr 23, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [12681f1]

Summary: ✅


AI Review

Summary

This PR fixes undefined behavior in LimitSeekableReadBuffer::seek for the case where the wrapped buffer has not materialized yet (pos == nullptr) and adds focused regression/sanity tests for null-position, fast-path, and slow-path seeks. I did not find correctness, safety, compatibility, or performance issues that require changes.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Apr 23, 2026
Comment thread src/IO/LimitSeekableReadBuffer.cpp Outdated
/// 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Apr 23, 2026
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)
@groeneai

Copy link
Copy Markdown
Collaborator Author

Status update: the pos && form that @CheSema applied at 11:08 UTC was reverted in commit cc7aaa4 after clickhouse-gh[bot] correctly pointed out at 12:34 UTC that even the short-circuited pos && (pos + position_change) expression is UB per [expr.add] whenever position_change is large enough to push the resulting pointer outside the allocation. The backup path (BackupWriterDefault::copyDataToFile → LimitSeekableReadBuffer::seek(base_size, SEEK_SET)) routinely seeks by GB-scale offsets into KB-sized working buffers, which is exactly the UB class that UBSan's -fsanitize=pointer-overflow catches. The integer-arithmetic form is correct in both cases.

Detailed replies posted inline:

Waiting on re-review. cc @alexey-milovidov @CheSema

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed empty commit 7260d79ab44 to re-trigger CI.

The Fast test failures on cc7aaa486d5 were all caused by a DNS infrastructure issue on the CI worker (Cannot resolve host (ip-172-31-64-98), error 0: DNS error). The CI worker couldn't resolve its own hostname; ClickHouse client failed at DNSResolver::Impl::Impl() before any query could execute.

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 src/IO/LimitSeekableReadBuffer.cpp and a gtest file — no networking/DNS code paths.

@nikitamikhaylov

Copy link
Copy Markdown
Member

@groeneai When you see a failure like Unit tests (msan, function_prop_fuzzer) or similar -- investigate and fix it in a separate PR.

groeneai and others added 4 commits April 24, 2026 15:17
…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)
@groeneai
groeneai force-pushed the fix-limit-seekable-read-buffer-ubsan-stid-3079 branch from 7260d79 to 12681f1 Compare April 24, 2026 15:17
@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks @nikitamikhaylov, agreed.

The Unit tests (msan, function_prop_fuzzer) failure you pointed to was actually a chronic trunk bug in getURLScheme (plus sibling findings in Lexer::nextToken and HasSubsequenceImpl.h that the same fuzzer surfaced). I had already investigated and opened a fix PR #103491 for those, but @yakov-olkhovskiy's PR #103489 landed on master first at 2026-04-24T11:48:40Z and superseded it — so I closed #103491.

The CI run you linked (commit 7260d79ab44, 2026-04-23) pre-dates the merge of #103489, which is why function_prop_fuzzer fails there.

Just rebased this branch onto current master (new HEAD 12681f197329) — it now picks up #103489's fixes, so the next CI run on this PR should see function_prop_fuzzer clean. The LimitSeekableReadBuffer::seek fix itself was unchanged by the rebase.

@clickhouse-gh

clickhouse-gh Bot commented Apr 24, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 83.80% 83.80% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.30% 76.20% -0.10%

Changed lines: 96.88% (31/32) | lost baseline coverage: 2 line(s) · Uncovered code

Full report · Diff report

Merged via the queue into ClickHouse:master with commit 8ecd225 Apr 26, 2026
165 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Apr 26, 2026
@PedroTadim

Copy link
Copy Markdown
Member

Need this to fix 26.4 CI

@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 9, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-ci pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.4-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants