Skip to content

SipHash::update: avoid forming an out-of-range pointer in the unrolled loop - #107103

Merged
azat merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/siphash-update-pointer-subtraction
Jun 11, 2026
Merged

azat merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/siphash-update-pointer-subtraction

Conversation

@groeneai

@groeneai groeneai commented Jun 10, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #106469

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

...

Description

Follow-up to #106469, addressing the clickhouse-gh[bot] inline review on that PR.

The unrolled 8-byte loop in SipHash::update(const char *, UInt64) used while (data + 8 <= end). When fewer than 8 bytes remain (a 1-7 byte input, or the tail iteration after the last full chunk where data == end), data + 8 points past the one-past-the-end pointer end. Forming such a pointer is undefined behavior under [expr.add]/4, regardless of whether it is dereferenced.

This is the general form of the defect fixed narrowly in #106469: there data was nullptr and data + 8 triggered UBSan's "applying non-zero offset to null pointer"; here data is a valid non-null pointer but the formed pointer still leaves the [base, base + size] range.

The fix rewrites the condition as while (end - data >= 8), which only ever evaluates pointer subtraction and never forms a pointer outside the buffer. The loop body is unchanged, so the hash is byte-identical for every input length.

The size == 0 early return added in #106469 is now redundant and is removed (per review feedback). After the rewrite the empty-input path forms no out-of-range pointer: end = data + 0 is well-defined, and the only remaining pointer arithmetic is end - data subtractions (all nullptr - nullptr, i.e. 0), so the loop body and the tail switch never run, exactly as for a zero-length valid buffer.

Verification (clang-21, -fsanitize=address,undefined -fno-sanitize-recover=all, matching amd_asan_ubsan): with the guard removed, the existing empty-string-view tests from #106469 (UpdateWithEmptyStringViewDoesNotInvokeUB, UpdateWithEmptyStringViewIsNoOp, which drive the exact nullptr, 0 path) and the new UpdateBoundaryLengths / UpdateChunkedMatchesWhole cases all pass and produce byte-identical hashes.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes (as a standards-level demonstration). With clang-21 -fsanitize=undefined, nullptr + 8 deterministically fires "applying non-zero offset 8 to null pointer" (the #106469 case). For non-null short inputs the over-range pointer is not runtime-observable by UBSan's pointer-overflow, so I demonstrated the defect at the standards level: an instrumented copy of the loop shows the OLD data + 8 <= end condition forms a pointer +1..+8 bytes past end for every input size, while the NEW end - data >= 8 form never forms a pointer past end (max offset 0, i.e. exactly end).
b Root cause explained? The unrolled loop's condition evaluates data + 8 before checking that 8 bytes remain. For a 1-7 byte buffer, and on the final check after the last full chunk (data == end), data + 8 lies outside [base, base + size]. Forming that pointer is UB under [expr.add]/4 even though it is never dereferenced (the tail uses switch (end - data) with indexed reads).
c Fix matches root cause? Yes. The condition is rewritten to pure pointer subtraction end - data >= 8, which never forms an out-of-range pointer. It targets the exact mechanism in (b), not a symptom.
d Test intent preserved / new tests added? Added SipHash.UpdateBoundaryLengths (1-7 byte tails at the end of exact-size allocations, sizes 0..64) and SipHash.UpdateChunkedMatchesWhole (every chunk size across the 8-byte word boundary), both asserting streamed updates equal the single-shot hash. The existing empty-input tests from #106469 are kept unchanged.
e Both directions demonstrated? Yes. OLD loop: forms an out-of-range pointer (+1..+8 past end) for all sizes; nullptr + 8 fires UBSan. NEW loop: forms no pointer past end, and the hash output is byte-identical to the old form for all sizes 0..40 (and via the new equivalence tests). New tests compile and pass against the real gtest framework under -fsanitize=address,undefined -fno-sanitize-recover=all (clang-21, matching amd_asan_ubsan).
f Fix is general, not a narrow patch? Yes. Audited all of SipHash.h: line 138 was the only out-of-range pointer formation (end = data + size is guarded by the size == 0 early return; data += 8 only runs in range). Sibling hand-written hashers in src/Common/ (WeakHash, FieldVisitorHash, getHashOfLoadedBinary) do not use this loop shape; CityHash/xxHash are vendored. This is a root-cause fix (eliminate the out-of-range arithmetic), not a defensive guard.

Session id: cron:clickhouse-worker-slot-25:20260610-225600

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @azat — could you review this? It's the follow-up to #106469 you asked about: the gh-bot review noted the unrolled loop still forms data + 8 past end for short inputs (UB under [expr.add]/4), so this rewrites the condition to end - data >= 8. Loop body unchanged, hash output byte-identical for all sizes, plus boundary-length gtest cases.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jun 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6532f09]

Summary: ✅


AI Review

Summary

This PR rewrites the unrolled SipHash::update loop condition from data + 8 <= end to end - data >= 8, which addresses the non-empty tail pointer-formation issue, and adds focused hash-equivalence tests. The remaining blocker is that removing the empty-input guard still sends std::string_view{} through pointer arithmetic on nullptr, so the empty case fixed by the related PR is not actually defined.

Findings

❌ Blockers

  • [src/Common/SipHash.h:110] [dismissed by author -- https://github.com/SipHash::update: avoid forming an out-of-range pointer in the unrolled loop #107103#discussion_r3395595839] The author argued that nullptr + 0 and nullptr - nullptr make the empty path well-defined, but std::string_view{} can call SipHash::update with data == nullptr and size == 0; after the guard removal this path evaluates data + size and later end - data, while pointer addition/subtraction are only defined for pointers into the same array object. A null pointer is not such a pointer, so this reintroduces UB for the empty-input case even though UBSan may not diagnose zero-offset null arithmetic. Restore the size == 0 return before computing end, or otherwise special-case empty input before any pointer arithmetic.
Final Verdict

Status: ❌ Block

Minimum required action: keep the empty-input path out of all pointer arithmetic, then retain the new non-empty loop condition.

@clickhouse-gh clickhouse-gh Bot added the pr-build Pull request with build/testing/packaging improvement label Jun 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on `982f514546f3`. Both test failures are the same infrastructure outage, not caused by this PR (a header-only `SipHash::update` loop-condition rewrite + 2 gtest cases):

  • `Stateless tests (amd_asan_ubsan, db disk, distributed plan, sequential)` — `Server died` / `Segmentation fault` (STID 1288-3bd5) / `03562_system_database_replicas`
  • `Stateless tests (arm_asan_ubsan, azure, sequential)` — `Server died` / `AddressSanitizer` (STID 2046-50c3)

Both are the amd/arm `asan_ubsan` mass outage of 2026-06-10/11 (ASan secondary-allocator OOM, no ClickHouse frames; STID 1288/2046/0883 family), which hit dozens of unrelated PRs and master. A header-only SipHash change cannot produce server segfaults in unrelated stateless tests. Ready for review.

@azat azat self-assigned this Jun 11, 2026
Comment thread src/Common/SipHash.h Resolved
…d loop

The unrolled 8-byte loop used `while (data + 8 <= end)`. When fewer than 8
bytes remain (a 1-7 byte input, or the tail after the last full chunk where
data == end), `data + 8` points past the one-past-the-end pointer `end`.
Forming such a pointer is undefined behavior under [expr.add]/4, independent
of whether it is dereferenced.

This is the general form of the same defect class as the empty-input case
fixed in ClickHouse#106469: there `data` was nullptr and `data + 8` triggered UBSan's
"applying non-zero offset to null pointer"; here `data` is a valid non-null
pointer but the formed pointer still leaves the [base, base+size] range.

Rewrite the condition as `end - data >= 8`, which only ever evaluates
pointer subtraction and never forms a pointer outside the buffer. The loop
body is unchanged, so the computed hash is identical for every input length.

The `size == 0` early return added in ClickHouse#106469 is now redundant and is
removed. After the rewrite the empty input path forms no out-of-range
pointer: `end = data + size` is `nullptr + 0` (well-defined), and the only
remaining pointer arithmetic is the subtractions `end - data` (all
`nullptr - nullptr`, i.e. 0), so the loop body and the tail switch never run.
This is the same as a zero-length valid buffer. Verified under clang-21
`-fsanitize=address,undefined -fno-sanitize-recover=all`: the existing
empty-string-view tests from ClickHouse#106469 and the new boundary/chunk tests all
pass and produce byte-identical hashes with the guard removed.

Found by clickhouse-gh[bot] inline review on ClickHouse#106469.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the groeneai/siphash-update-pointer-subtraction branch from 982f514 to 6532f09 Compare June 11, 2026 13:03
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (updated for 6532f09: size == 0 guard removed per review)

# Question Answer
a Deterministic repro? Yes, at the standards level for the over-range pointer, and deterministically UBSan-observable for the nullptr + 8 form (#106469). The question this push answers (is the size == 0 guard still needed?) is settled deterministically: built gtest_sip_hash.cpp with the guard present and with it removed under clang-21 -fsanitize=address,undefined -fno-sanitize-recover=all; both runs are clean and byte-identical.
b Root cause explained? The unrolled loop evaluated data + 8 before checking 8 bytes remain; for a 1-7 byte buffer and the final data == end check, data + 8 leaves [base, base+size] (UB under [expr.add]/4). The original size == 0 guard existed only because the old code path reached data + 8 with data == nullptr. The rewrite to end - data >= 8 removes every out-of-range pointer formation, so the guard's reason no longer exists.
c Fix matches root cause? Yes. Condition rewritten to pure pointer subtraction end - data >= 8. The now-redundant size == 0 early return is removed (it was tied to the old data + 8 arithmetic), not kept as a defensive band-aid.
d Test intent preserved / new tests added? The two empty-input tests from #106469 are kept unchanged and now serve as the regression proof that the loop logic (not the guard) makes nullptr, 0 a no-op. New UpdateBoundaryLengths (1-7 byte tails at exact-size allocation end, sizes 0..64) and UpdateChunkedMatchesWhole (chunked across the 8-byte boundary) assert streamed == single-shot.
e Both directions demonstrated? Yes. Guard PRESENT vs guard REMOVED, real SipHash.h header, full ASAN+UBSan -fno-sanitize-recover=all: both UBSan-clean on the nullptr, 0 path and byte-identical output (empty-interspersed lo=ea8674e1bc37999f hi=04eb82c75932ce4f, all sizes 0..64 streamed == whole). All 4 gtest_sip_hash.cpp tests pass with the guard removed.
f Fix is general, not a narrow patch? Yes. Audited all of SipHash.h: line ~136 was the only out-of-range pointer formation; data += 8 only runs in range and end = data + size is now nullptr + 0 on the empty path (well-defined). Sibling hand-written hashers (WeakHash, FieldVisitorHash, getHashOfLoadedBinary) do not use this loop shape; CityHash/xxHash are vendored. Root-cause fix (eliminate the out-of-range arithmetic), not a guard.

Session id: cron:clickhouse-worker-slot-13:20260611-124900

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog and removed pr-build Pull request with build/testing/packaging improvement labels Jun 11, 2026
@azat
azat enabled auto-merge June 11, 2026 13:06
@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.60% 84.60% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.30% 77.30% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 25/25 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@azat
azat added this pull request to the merge queue Jun 11, 2026
Merged via the queue into ClickHouse:master with commit 0124e6f Jun 11, 2026
166 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 11, 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-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants